-
Notifications
You must be signed in to change notification settings - Fork 418
Expand file tree
/
Copy pathParseOperation.cs
More file actions
454 lines (382 loc) · 15.6 KB
/
ParseOperation.cs
File metadata and controls
454 lines (382 loc) · 15.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.CommandLine.Invocation;
using System.Linq;
namespace System.CommandLine.Parsing
{
internal sealed class ParseOperation
{
private readonly List<Token> _tokens;
private readonly ParserConfiguration _configuration;
private readonly string? _rawInput;
private readonly SymbolResultTree _symbolResultTree;
private readonly CommandResult _rootCommandResult;
private int _index;
private CommandResult _innermostCommandResult;
private bool _isTerminatingDirectiveSpecified;
private CommandLineAction? _primaryAction;
private List<CommandLineAction>? _preActions;
private readonly Command _rootCommand;
public ParseOperation(
List<Token> tokens,
Command rootCommand,
ParserConfiguration configuration,
List<string>? tokenizeErrors,
string? rawInput)
{
_tokens = tokens;
_configuration = configuration;
_rootCommand = rootCommand;
_rawInput = rawInput;
_symbolResultTree = new(_rootCommand, tokenizeErrors);
_innermostCommandResult = _rootCommandResult = new CommandResult(
_rootCommand,
CurrentToken,
_symbolResultTree);
_symbolResultTree.Add(_rootCommand, _rootCommandResult);
Advance();
}
private Token CurrentToken => _tokens[_index];
private void Advance() => _index++;
private bool More(out TokenType currentTokenType)
{
bool result = _index < _tokens.Count;
currentTokenType = result ? _tokens[_index].Type : (TokenType)(-1);
return result;
}
internal ParseResult Parse()
{
ParseDirectives();
ParseCommandChildren();
ValidateAndAddDefaultResults();
return new(
_configuration,
_rootCommandResult,
_innermostCommandResult,
_tokens,
_symbolResultTree.UnmatchedTokens,
_symbolResultTree.Errors,
_rawInput,
_primaryAction,
_preActions);
}
private void ParseSubcommand()
{
Command command = (Command)CurrentToken.Symbol!;
_innermostCommandResult = new CommandResult(
command,
CurrentToken,
_symbolResultTree,
_innermostCommandResult);
_symbolResultTree.Add(command, _innermostCommandResult);
Advance();
ParseCommandChildren();
}
private void ParseCommandChildren()
{
int currentArgumentCount = 0;
int currentArgumentIndex = 0;
while (More(out TokenType currentTokenType))
{
if (currentTokenType == TokenType.Command)
{
ParseSubcommand();
}
else if (currentTokenType == TokenType.Option)
{
ParseOption();
}
else if (currentTokenType == TokenType.Argument)
{
ParseCommandArguments(ref currentArgumentCount, ref currentArgumentIndex);
}
else
{
AddCurrentTokenToUnmatched();
Advance();
}
}
}
private void ParseCommandArguments(ref int currentArgumentCount, ref int currentArgumentIndex)
{
while (More(out TokenType currentTokenType) && currentTokenType == TokenType.Argument)
{
while (_innermostCommandResult.Command.HasArguments && currentArgumentIndex < _innermostCommandResult.Command.Arguments.Count)
{
Argument argument = _innermostCommandResult.Command.Arguments[currentArgumentIndex];
if (currentArgumentCount < argument.Arity.MaximumNumberOfValues)
{
if (CurrentToken.Symbol is null)
{
// update the token with missing information now, so later stages don't need to modify it
CurrentToken.Symbol = argument;
}
if (!(_symbolResultTree.TryGetValue(argument, out var symbolResult)
&& symbolResult is ArgumentResult argumentResult))
{
argumentResult =
new ArgumentResult(
argument,
_symbolResultTree,
_innermostCommandResult);
_symbolResultTree.Add(argument, argumentResult);
}
argumentResult.AddToken(CurrentToken);
_innermostCommandResult.AddToken(CurrentToken);
currentArgumentCount++;
Advance();
break;
}
else
{
currentArgumentCount = 0;
currentArgumentIndex++;
}
}
if (currentArgumentCount == 0) // no matching arguments found
{
AddCurrentTokenToUnmatched();
Advance();
}
}
}
private void ParseOption()
{
Option option = (Option)CurrentToken.Symbol!;
OptionResult optionResult;
if (!_symbolResultTree.TryGetValue(option, out SymbolResult? symbolResult))
{
if (option.Action is not null)
{
// directives have a precedence over --help and --version
if (!_isTerminatingDirectiveSpecified)
{
if (option.Action.Terminating)
{
_primaryAction = option.Action;
}
else
{
AddPreAction(option.Action);
}
}
}
optionResult = new OptionResult(
option,
_symbolResultTree,
CurrentToken,
_innermostCommandResult);
_symbolResultTree.Add(option, optionResult);
}
else
{
optionResult = (OptionResult)symbolResult;
}
optionResult.IdentifierTokenCount++;
Advance();
ParseOptionArguments(optionResult);
}
private void ParseOptionArguments(OptionResult optionResult)
{
var argument = optionResult.Option.Argument;
var contiguousTokens = 0;
int argumentCount = 0;
while (More(out TokenType currentTokenType) && currentTokenType == TokenType.Argument)
{
if (argumentCount >= argument.Arity.MaximumNumberOfValues)
{
if (contiguousTokens > 0)
{
break;
}
if (argument.Arity.MaximumNumberOfValues == 0)
{
break;
}
}
else if (argument.IsBoolean() && !bool.TryParse(CurrentToken.Value, out _))
{
// Don't greedily consume the following token for bool. The presence of the option token (i.e. a flag) is sufficient.
break;
}
if (!(_symbolResultTree.TryGetValue(argument, out SymbolResult? symbolResult)
&& symbolResult is ArgumentResult argumentResult))
{
argumentResult = new ArgumentResult(
argument,
_symbolResultTree,
optionResult);
_symbolResultTree.Add(argument, argumentResult);
}
argumentResult.AddToken(CurrentToken);
optionResult.AddToken(CurrentToken);
argumentCount++;
contiguousTokens++;
Advance();
if (!optionResult.Option.AllowMultipleArgumentsPerToken)
{
return;
}
}
if (argumentCount == 0)
{
if (!_symbolResultTree.ContainsKey(argument))
{
var argumentResult = new ArgumentResult(argument, _symbolResultTree, optionResult);
_symbolResultTree.Add(argument, argumentResult);
}
}
}
private void ParseDirectives()
{
while (More(out TokenType currentTokenType) && currentTokenType == TokenType.Directive)
{
if (_rootCommand is RootCommand { Directives.Count: > 0 })
{
ParseDirective(); // kept in separate method to avoid JIT
}
Advance();
}
void ParseDirective()
{
var token = CurrentToken;
if (token.Symbol is not Directive directive)
{
AddCurrentTokenToUnmatched();
return;
}
DirectiveResult result;
if (_symbolResultTree.TryGetValue(directive, out var directiveResult))
{
result = (DirectiveResult)directiveResult;
result.AddToken(token);
}
else
{
result = new (directive, token, _symbolResultTree);
_symbolResultTree.Add(directive, result);
}
ReadOnlySpan<char> withoutBrackets = token.Value.AsSpan(1, token.Value.Length - 2);
int indexOfColon = withoutBrackets.IndexOf(':');
if (indexOfColon > 0)
{
result.AddValue(withoutBrackets.Slice(indexOfColon + 1).ToString());
}
if (directive.Action is not null)
{
if (directive.Action.Terminating)
{
_primaryAction = directive.Action;
_isTerminatingDirectiveSpecified = true;
}
else
{
AddPreAction(directive.Action);
}
}
}
}
private void AddPreAction(CommandLineAction action)
{
if (_preActions is null)
{
_preActions = new();
}
_preActions.Add(action);
}
private void AddPreActionsForImplicitOptions()
{
foreach (var kvp in _symbolResultTree)
{
if (kvp is { Key: Option { Action: { Terminating: false } action }, Value: OptionResult { Implicit: true } } &&
_primaryAction != action)
{
AddPreAction(action);
}
}
}
private void AddCurrentTokenToUnmatched()
{
if (CurrentToken.Type == TokenType.DoubleDash)
{
return;
}
_symbolResultTree.AddUnmatchedToken(CurrentToken, _innermostCommandResult, _rootCommandResult);
}
private void ValidateAndAddDefaultResults()
{
// Only the innermost command goes through complete validation,
// for other commands only a subset of options is checked.
_innermostCommandResult.Validate(isInnermostCommand: true);
CommandResult? currentResult = _innermostCommandResult.Parent as CommandResult;
while (currentResult is not null)
{
currentResult.Validate(isInnermostCommand: false);
currentResult = currentResult.Parent as CommandResult;
}
if (_primaryAction is null)
{
if (_innermostCommandResult is { Command: { Action: null, HasSubcommands: true } })
{
_symbolResultTree.InsertFirstError(
new ParseError(LocalizationResources.RequiredCommandWasNotProvided(), _innermostCommandResult));
}
if (_innermostCommandResult is { Command.Action.ClearsParseErrors: true } &&
_symbolResultTree.Errors is not null)
{
var errorsNotUnderInnermostCommand = _symbolResultTree
.Errors
.Where(e => e.SymbolResult != _innermostCommandResult)
.ToList();
_symbolResultTree.Errors = errorsNotUnderInnermostCommand;
}
else if (_symbolResultTree.ErrorCount > 0)
{
_primaryAction = new ParseErrorAction();
}
}
else
{
if (_symbolResultTree.ErrorCount > 0 &&
_primaryAction.ClearsParseErrors &&
_symbolResultTree.Errors is not null)
{
foreach (var kvp in _symbolResultTree)
{
var symbol = kvp.Key;
if (symbol is Option { Action: { } optionAction } option)
{
if (_primaryAction == optionAction)
{
var errorsForPrimarySymbol = _symbolResultTree
.Errors
.Where(e => e.SymbolResult is OptionResult r && r.Option == option)
.ToList();
_symbolResultTree.Errors = errorsForPrimarySymbol;
return;
}
}
if (symbol is Command { Action: { } commandAction } command)
{
if (_primaryAction == commandAction)
{
var errorsForPrimarySymbol = _symbolResultTree
.Errors
.Where(e => e.SymbolResult is CommandResult r && r.Command == command)
.ToList();
_symbolResultTree.Errors = errorsForPrimarySymbol;
return;
}
}
}
if (_symbolResultTree.ErrorCount > 0)
{
_symbolResultTree.Errors?.Clear();
}
}
}
AddPreActionsForImplicitOptions();
}
}
}