forked from IronLanguages/ironpython3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParser.cs
More file actions
3286 lines (2825 loc) · 123 KB
/
Parser.cs
File metadata and controls
3286 lines (2825 loc) · 123 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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Numerics;
using System.Text;
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Compiler.Ast;
using IronPython.Hosting;
using IronPython.Runtime;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
namespace IronPython.Compiler {
// this file is your friend (check the python version that is being developed against)
// https://raw.githubusercontent.com/python/cpython/v3.4.10/Grammar/Grammar
// the parser itself should match the grammar rules in this file. the closer it is, the easier it is to add new
// features and fix bugs since the code flow can be read alongside the rules in the file.
//
// it's not entirely clear whether there is a name for the syntax used in this file, however i found this helpful
// http://matt.might.net/articles/grammars-bnf-ebnf/
// '|' is or rather than '/'
// * means repetition of 0 or more
// # starts a comment
// that's probably about all you need to know to get stuck in.
public class Parser : IDisposable { // TODO: remove IDisposable
// immutable properties:
private readonly Tokenizer _tokenizer;
// mutable properties:
private ErrorSink _errors;
private ParserSink _sink;
// resettable properties:
private SourceUnit _sourceUnit;
/// <summary>
/// Language features initialized on parser construction and possibly updated during parsing.
/// The code can set the language features (e.g. "from __future__ import division").
/// </summary>
private ModuleOptions _languageFeatures;
// state:
private TokenWithSpan _token;
private TokenWithSpan _lookahead;
private Stack<FunctionDefinition> _functions;
private Stack<ClassDefinition> _classes;
private bool _fromFutureAllowed;
private string _privatePrefix;
private bool _parsingStarted, _allowIncomplete;
private bool _inLoop, _inFinally, _inFinallyLoop;
private SourceCodeReader _sourceReader;
private int _errorCode;
private readonly CompilerContext _context;
private PythonAst _globalParent;
private static readonly char[] newLineChar = new char[] { '\n' };
private static readonly char[] whiteSpace = { ' ', '\t' };
#region Construction
private Parser(CompilerContext context, Tokenizer tokenizer, ErrorSink errorSink, ParserSink parserSink, ModuleOptions languageFeatures) {
ContractUtils.RequiresNotNull(tokenizer, nameof(tokenizer));
ContractUtils.RequiresNotNull(errorSink, nameof(errorSink));
ContractUtils.RequiresNotNull(parserSink, nameof(parserSink));
tokenizer.ErrorSink = new TokenizerErrorSink(this);
_tokenizer = tokenizer;
_errors = errorSink;
if (parserSink != ParserSink.Null) {
_sink = parserSink;
}
_context = context;
Reset(tokenizer.SourceUnit, languageFeatures);
}
public static Parser CreateParser(CompilerContext context, PythonOptions options) {
return CreateParserWorker(context, options, false);
}
[Obsolete("pass verbatim via PythonCompilerOptions in PythonOptions")]
public static Parser CreateParser(CompilerContext context, PythonOptions options, bool verbatim) {
return CreateParserWorker(context, options, verbatim);
}
private static Parser CreateParserWorker(CompilerContext context, PythonOptions options, bool verbatim) {
ContractUtils.RequiresNotNull(context, nameof(context));
ContractUtils.RequiresNotNull(options, nameof(options));
PythonCompilerOptions compilerOptions = context.Options as PythonCompilerOptions;
if (options == null) {
throw new ValueErrorException(Resources.PythonContextRequired);
}
SourceCodeReader reader;
try {
reader = context.SourceUnit.GetReader();
if (compilerOptions.SkipFirstLine) {
reader.ReadLine();
}
} catch (IOException e) {
context.Errors.Add(context.SourceUnit, e.Message, SourceSpan.Invalid, 0, Severity.Error);
throw;
}
Tokenizer tokenizer = new Tokenizer(context.Errors, compilerOptions, verbatim);
tokenizer.Initialize(null, reader, context.SourceUnit, SourceLocation.MinValue);
tokenizer.IndentationInconsistencySeverity = options.IndentationInconsistencySeverity;
Parser result = new Parser(context, tokenizer, context.Errors, context.ParserSink, compilerOptions.Module);
result._sourceReader = reader;
return result;
}
#endregion
#region Public parser interface
public PythonAst ParseFile(bool makeModule) {
return ParseFile(makeModule, false);
}
//single_input: Newline | simple_stmt | compound_stmt Newline
//eval_input: testlist Newline* ENDMARKER
//file_input: (Newline | stmt)* ENDMARKER
public PythonAst ParseFile(bool makeModule, bool returnValue) {
try {
return ParseFileWorker(makeModule, returnValue);
} catch (DecoderFallbackException dfe) {
throw BadSourceError(dfe);
}
}
//[stmt_list] Newline | compound_stmt Newline
//stmt_list ::= simple_stmt (";" simple_stmt)* [";"]
//compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
//Returns a simple or coumpound_stmt or null if input is incomplete
/// <summary>
/// Parse one or more lines of interactive input
/// </summary>
/// <returns>null if input is not yet valid but could be with more lines</returns>
public PythonAst ParseInteractiveCode(out ScriptCodeParseResult properties) {
bool parsingMultiLineCmpdStmt;
bool isEmptyStmt = false;
properties = ScriptCodeParseResult.Complete;
_globalParent = new PythonAst(false, _languageFeatures, true, _context);
StartParsing();
Statement ret = InternalParseInteractiveInput(out parsingMultiLineCmpdStmt, out isEmptyStmt);
if (_errorCode == 0) {
if (isEmptyStmt) {
properties = ScriptCodeParseResult.Empty;
} else if (parsingMultiLineCmpdStmt) {
properties = ScriptCodeParseResult.IncompleteStatement;
}
if (isEmptyStmt) {
return null;
}
return FinishParsing(ret);
} else {
if ((_errorCode & ErrorCodes.IncompleteMask) != 0) {
if ((_errorCode & ErrorCodes.IncompleteToken) != 0) {
properties = ScriptCodeParseResult.IncompleteToken;
return null;
}
if ((_errorCode & ErrorCodes.IncompleteStatement) != 0) {
if (parsingMultiLineCmpdStmt) {
properties = ScriptCodeParseResult.IncompleteStatement;
} else {
properties = ScriptCodeParseResult.IncompleteToken;
}
return null;
}
}
properties = ScriptCodeParseResult.Invalid;
return null;
}
}
private PythonAst FinishParsing(Statement ret) {
var res = _globalParent;
_globalParent = null;
var lineLocs = _tokenizer.GetLineLocations();
// update line mapping
if (_sourceUnit.HasLineMapping) {
List<int> newLineMapping = new List<int>();
int last = 0;
for (int i = 0; i < lineLocs.Length; i++) {
while (newLineMapping.Count < i) {
newLineMapping.Add(last);
}
last = lineLocs[i] + 1;
newLineMapping.Add(lineLocs[i]);
}
lineLocs = newLineMapping.ToArray();
}
res.ParsingFinished(lineLocs, ret, _languageFeatures);
return res;
}
public PythonAst ParseSingleStatement() {
try {
_globalParent = new PythonAst(false, _languageFeatures, true, _context);
StartParsing();
MaybeEatNewLine();
Statement statement = ParseStmt();
EatEndOfInput();
return FinishParsing(statement);
} catch (DecoderFallbackException dfe) {
throw BadSourceError(dfe);
}
}
public PythonAst ParseTopExpression() {
try {
// TODO: move from source unit .TrimStart(' ', '\t')
_globalParent = new PythonAst(false, _languageFeatures, false, _context);
ReturnStatement ret = new ReturnStatement(ParseTestListAsExpression());
ret.SetLoc(_globalParent, 0, 0);
return FinishParsing(ret);
} catch (DecoderFallbackException dfe) {
throw BadSourceError(dfe);
}
}
/// <summary>
/// Given the interactive text input for a compound statement, calculate what the
/// indentation level of the next line should be
/// </summary>
public static int GetNextAutoIndentSize(string text, int autoIndentTabWidth) {
ContractUtils.RequiresNotNull(text, nameof(text));
Debug.Assert(text[text.Length - 1] == '\n');
string[] lines = text.Split(newLineChar);
if (lines.Length <= 1) return 0;
string lastLine = lines[lines.Length - 2];
// Figure out the number of white-spaces at the start of the last line
int startingSpaces = 0;
while (startingSpaces < lastLine.Length && lastLine[startingSpaces] == ' ')
startingSpaces++;
// Assume the same indent as the previous line
int autoIndentSize = startingSpaces;
// Increase the indent if this looks like the start of a compounds statement.
// Ideally, we would ask the parser to tell us the exact indentation level
if (lastLine.TrimEnd(whiteSpace).EndsWith(":"))
autoIndentSize += autoIndentTabWidth;
return autoIndentSize;
}
public ErrorSink ErrorSink {
get {
return _errors;
}
set {
ContractUtils.RequiresNotNull(value, nameof(value));
_errors = value;
}
}
public ParserSink ParserSink {
get {
return _sink;
}
set {
if (_sink == ParserSink.Null) {
_sink = null;
} else {
_sink = value;
}
}
}
public int ErrorCode {
get { return _errorCode; }
}
public void Reset(SourceUnit sourceUnit, ModuleOptions languageFeatures) {
ContractUtils.RequiresNotNull(sourceUnit, nameof(sourceUnit));
_sourceUnit = sourceUnit;
_languageFeatures = languageFeatures;
_token = new TokenWithSpan();
_lookahead = new TokenWithSpan();
_fromFutureAllowed = true;
_functions = null;
_privatePrefix = null;
_parsingStarted = false;
_errorCode = 0;
}
public void Reset() {
Reset(_sourceUnit, _languageFeatures);
}
#endregion
#region Error Reporting
private void ReportSyntaxError(TokenWithSpan t, int errorCode = ErrorCodes.SyntaxError) {
ReportSyntaxError(t.Token, t.Span, errorCode, true);
}
private void ReportSyntaxError(Token t, IndexSpan span, int errorCode, bool allowIncomplete) {
var start = span.Start;
var end = span.End;
if (allowIncomplete && (t.Kind == TokenKind.EndOfFile || (_tokenizer.IsEndOfFile && (t.Kind == TokenKind.Dedent || t.Kind == TokenKind.NLToken)))) {
errorCode |= ErrorCodes.IncompleteStatement;
}
string msg = string.Format(System.Globalization.CultureInfo.InvariantCulture, GetErrorMessage(t, errorCode), t.Image);
ReportSyntaxError(start, end, msg, errorCode);
}
private static string GetErrorMessage(Token t, int errorCode) {
string msg;
if ((errorCode & ~ErrorCodes.IncompleteMask) == ErrorCodes.IndentationError) {
msg = Resources.ExpectedIndentation;
} else if (t.Kind != TokenKind.EndOfFile) {
msg = "invalid syntax";
} else {
msg = "unexpected EOF while parsing";
}
return msg;
}
private void ReportSyntaxError(string message) {
ReportSyntaxError(_lookahead.Span.Start, _lookahead.Span.End, message);
}
internal void ReportSyntaxError(int start, int end, string message, int errorCode = ErrorCodes.SyntaxError) {
// save the first one, the next error codes may be induced errors:
if (_errorCode == 0) {
_errorCode = errorCode;
}
_errors.Add(_sourceUnit,
message,
new SourceSpan(_tokenizer.IndexToLocation(start), _tokenizer.IndexToLocation(end)),
errorCode,
Severity.FatalError);
}
#endregion
#region LL(1) Parsing
private static bool IsPrivateName(string name) {
return name.StartsWith("__") && !name.EndsWith("__");
}
private string FixName(string name) {
if (_privatePrefix != null && IsPrivateName(name)) {
name = "_" + _privatePrefix + name;
}
return name;
}
private string ReadName() {
if (PeekToken() is NameToken n) {
NextToken();
return FixName(n.Name);
}
ReportSyntaxError(_lookahead);
return null;
}
//stmt: simple_stmt | compound_stmt
//compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated | async_stmt
private Statement ParseStmt() {
switch (PeekToken().Kind) {
case TokenKind.KeywordIf:
return ParseIfStmt();
case TokenKind.KeywordWhile:
return ParseWhileStmt();
case TokenKind.KeywordFor:
return ParseForStmt();
case TokenKind.KeywordTry:
return ParseTryStatement();
case TokenKind.At:
return ParseDecorated();
case TokenKind.KeywordDef:
return ParseFuncDef();
case TokenKind.KeywordClass:
return ParseClassDef();
case TokenKind.KeywordWith:
return ParseWithStmt();
case TokenKind.KeywordAsync:
return ParseAsyncStmt();
default:
return ParseSimpleStmt();
}
}
//simple_stmt: small_stmt (';' small_stmt)* [';'] Newline
private Statement ParseSimpleStmt() {
Statement s = ParseSmallStmt();
if (MaybeEat(TokenKind.Semicolon)) {
var start = s.StartIndex;
List<Statement> l = new List<Statement>();
l.Add(s);
while (true) {
if (MaybeEatNewLine() || MaybeEat(TokenKind.EndOfFile)) {
break;
}
l.Add(ParseSmallStmt());
if (MaybeEat(TokenKind.EndOfFile)) {
// implies a new line
break;
} else if (!MaybeEat(TokenKind.Semicolon)) {
EatNewLine();
break;
}
}
Statement[] stmts = l.ToArray();
SuiteStatement ret = new SuiteStatement(stmts);
ret.SetLoc(_globalParent, start, stmts[stmts.Length - 1].EndIndex);
return ret;
} else if (!MaybeEat(TokenKind.EndOfFile) && !EatNewLine()) {
// error handling, make sure we're making forward progress
NextToken();
}
return s;
}
/*
small_stmt: expr_stmt | del_stmt | pass_stmt | flow_stmt | import_stmt | global_stmt | nonlocal_stmt | assert_stmt
del_stmt: 'del' exprlist
pass_stmt: 'pass'
flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt
break_stmt: 'break'
continue_stmt: 'continue'
return_stmt: 'return' [testlist]
yield_stmt: yield_expr
*/
private Statement ParseSmallStmt() {
switch (PeekToken().Kind) {
case TokenKind.KeywordPass:
return FinishSmallStmt(new EmptyStatement());
case TokenKind.KeywordBreak:
if (!_inLoop) {
ReportSyntaxError("'break' outside loop");
}
return FinishSmallStmt(new BreakStatement());
case TokenKind.KeywordContinue:
if (!_inLoop) {
ReportSyntaxError("'continue' not properly in loop");
} else if (_inFinally && !_inFinallyLoop) {
ReportSyntaxError("'continue' not supported inside 'finally' clause");
}
return FinishSmallStmt(new ContinueStatement());
case TokenKind.KeywordReturn:
return ParseReturnStmt();
case TokenKind.KeywordFrom:
return ParseFromImportStmt();
case TokenKind.KeywordImport:
return ParseImportStmt();
case TokenKind.KeywordGlobal:
return ParseGlobalStmt();
case TokenKind.KeywordNonlocal:
return ParseNonLocalStmt();
case TokenKind.KeywordRaise:
return ParseRaiseStmt();
case TokenKind.KeywordAssert:
return ParseAssertStmt();
case TokenKind.KeywordDel:
return ParseDelStmt();
case TokenKind.KeywordYield:
return ParseYieldStmt();
default:
return ParseExprStmt();
}
}
// del_stmt: "del" exprlist
// for error reporting reasons we allow any expression and then report the bad
// delete node when it fails
private Statement ParseDelStmt() {
NextToken();
var start = GetStart();
List<Expression> l = ParseExprList(out _);
foreach (Expression e in l) {
string delError = e.CheckDelete();
if (delError != null) {
ReportSyntaxError(e.StartIndex, e.EndIndex, delError, ErrorCodes.SyntaxError);
}
}
DelStatement ret = new DelStatement(l.ToArray());
ret.SetLoc(_globalParent, start, GetEnd());
return ret;
}
// return_stmt: 'return' [testlist]
private Statement ParseReturnStmt() {
if (CurrentFunction == null) {
ReportSyntaxError(IronPython.Resources.MisplacedReturn);
}
NextToken();
Expression expr = null;
var start = GetStart();
if (!NeverTestToken(PeekToken())) {
expr = ParseTestList();
}
ReturnStatement ret = new ReturnStatement(expr);
ret.SetLoc(_globalParent, start, GetEnd());
return ret;
}
private Statement FinishSmallStmt(Statement stmt) {
NextToken();
stmt.SetLoc(_globalParent, GetStart(), GetEnd());
return stmt;
}
// yield_stmt: yield_expr
private Statement ParseYieldStmt() {
// For yield statements, continue to enforce that it's currently in a function.
// This gives us better syntax error reporting for yield-statements than for yield-expressions.
FunctionDefinition current = CurrentFunction;
if (current == null) {
ReportSyntaxError(IronPython.Resources.MisplacedYield);
}
Eat(TokenKind.KeywordYield);
// See Pep 342: a yield statement is now just an expression statement around a yield expression.
Expression e = ParseYieldExpression();
Debug.Assert(e != null); // caller already verified we have a yield.
Statement s = new ExpressionStatement(e);
s.SetLoc(_globalParent, e.IndexSpan);
return s;
}
/// <summary>
/// Peek if the next token is a 'yield' and parse a yield expression. Else return null.
///
/// Called w/ yield already eaten.
/// </summary>
/// <returns>A yield expression if present, else null. </returns>
// yield_expr: 'yield' [yield_arg]
// yield_arg: 'from' test | testlist
private Expression ParseYieldExpression() {
// Mark that this function is actually a generator.
// If we're in a generator expression, then we don't have a function yet.
// g=((yield i) for i in range(5))
// In that acse, the genexp will mark IsGenerator.
FunctionDefinition current = CurrentFunction;
if (current != null) {
current.IsGenerator = true;
}
var start = GetStart();
// Parse expression list after yield. This can be:
// 1) empty, in which case it becomes 'yield None'
// 2) a single expression
// 3) multiple expression, in which case it's wrapped in a tuple.
Expression yieldResult;
bool isYieldFrom = false;
if (MaybeEat(TokenKind.KeywordFrom)) {
yieldResult = ParseTest();
yieldResult.SetLoc(_globalParent, start, GetEnd());
isYieldFrom = true;
} else {
bool trailingComma;
List<Expression> l = ParseTestList(out trailingComma);
if (l.Count == 0) {
// Check empty expression and convert to 'none'
yieldResult = new ConstantExpression(null);
// location set to match yield location (consistent with cpython)
yieldResult.SetLoc(_globalParent, start, GetEnd());
} else if (l.Count != 1) {
// make a tuple
yieldResult = MakeTupleOrExpr(l, trailingComma);
} else {
// just take the single expression
yieldResult = l[0];
}
}
Expression yieldExpression = new YieldExpression(yieldResult, isYieldFrom);
yieldExpression.SetLoc(_globalParent, start, GetEnd());
return yieldExpression;
}
private Statement FinishAssignments(Expression right) {
List<Expression> left = null;
Expression singleLeft = null;
while (MaybeEat(TokenKind.Assign)) {
if (right.CheckAssign() is { } assignError) {
ReportSyntaxError(right.StartIndex, right.EndIndex, assignError, ErrorCodes.SyntaxError | ErrorCodes.NoCaret);
}
if (right is StarredExpression) {
ReportSyntaxError(right.StartIndex, right.EndIndex, "starred assignment target must be in a list or tuple");
}
if (singleLeft == null) {
singleLeft = right;
} else {
if (left == null) {
left = new List<Expression> { singleLeft };
}
left.Add(right);
}
right = MaybeEat(TokenKind.KeywordYield) ? ParseYieldExpression() : ParseTestListStarExpr();
}
CheckNotAssignmentTargetOnly(right);
var target = left?.ToArray() ?? new [] { singleLeft };
Debug.Assert(target.Length > 0);
Debug.Assert(target[0] != null);
var assign = new AssignmentStatement(target, right);
assign.SetLoc(_globalParent, target[0].StartIndex, right.EndIndex);
return assign;
}
// expr_stmt: testlist_star_expr (augassign (yield_expr|testlist) | ('=' (yield_expr|testlist_star_expr))*)
// augassign: ('+=' | '-=' | '*=' | '@=' | '/=' | '%=' | '&=' | '|=' | '^=' | '<<=' | '>>=' | '**=' | '//=')
private Statement ParseExprStmt() {
Expression ret = ParseTestListStarExpr();
if (ret is ErrorExpression) {
NextToken();
}
if (PeekToken(TokenKind.Assign)) {
return FinishAssignments(ret);
}
PythonOperator op = GetAssignOperator(PeekToken());
if (op != PythonOperator.None) {
NextToken();
Expression rhs;
if (MaybeEat(TokenKind.KeywordYield)) {
rhs = ParseYieldExpression();
} else {
rhs = ParseTestList();
}
string assignError = ret.CheckAugmentedAssign();
if (assignError != null) {
ReportSyntaxError(assignError);
}
AugmentedAssignStatement aug = new AugmentedAssignStatement(op, ret, rhs);
aug.SetLoc(_globalParent, ret.StartIndex, GetEnd());
return aug;
}
CheckNotAssignmentTargetOnly(ret);
Statement stmt = new ExpressionStatement(ret);
stmt.SetLoc(_globalParent, ret.IndexSpan);
return stmt;
}
private void CheckNotAssignmentTargetOnly(Expression expr) {
switch (expr)
{
case SequenceExpression sequence: {
foreach (var expression in sequence.Items)
{
if (expression is StarredExpression starred)
{
ReportSyntaxError(
starred.StartIndex,
starred.EndIndex,
"can use starred expression only as assignment target");
}
}
break;
}
case StarredExpression starred:
ReportSyntaxError(
starred.StartIndex,
starred.EndIndex,
"can use starred expression only as assignment target");
break;
}
}
private PythonOperator GetAssignOperator(Token t) {
switch (t.Kind) {
case TokenKind.AddEqual: return PythonOperator.Add;
case TokenKind.SubtractEqual: return PythonOperator.Subtract;
case TokenKind.MultiplyEqual: return PythonOperator.Multiply;
case TokenKind.TrueDivideEqual: return PythonOperator.TrueDivide;
case TokenKind.ModEqual: return PythonOperator.Mod;
case TokenKind.BitwiseAndEqual: return PythonOperator.BitwiseAnd;
case TokenKind.BitwiseOrEqual: return PythonOperator.BitwiseOr;
case TokenKind.ExclusiveOrEqual: return PythonOperator.Xor;
case TokenKind.LeftShiftEqual: return PythonOperator.LeftShift;
case TokenKind.RightShiftEqual: return PythonOperator.RightShift;
case TokenKind.PowerEqual: return PythonOperator.Power;
case TokenKind.FloorDivideEqual: return PythonOperator.FloorDivide;
default: return PythonOperator.None;
}
}
private PythonOperator GetBinaryOperator(OperatorToken token) {
switch (token.Kind) {
case TokenKind.Add: return PythonOperator.Add;
case TokenKind.Subtract: return PythonOperator.Subtract;
case TokenKind.Multiply: return PythonOperator.Multiply;
case TokenKind.TrueDivide: return PythonOperator.TrueDivide;
case TokenKind.Mod: return PythonOperator.Mod;
case TokenKind.BitwiseAnd: return PythonOperator.BitwiseAnd;
case TokenKind.BitwiseOr: return PythonOperator.BitwiseOr;
case TokenKind.ExclusiveOr: return PythonOperator.Xor;
case TokenKind.LeftShift: return PythonOperator.LeftShift;
case TokenKind.RightShift: return PythonOperator.RightShift;
case TokenKind.Power: return PythonOperator.Power;
case TokenKind.FloorDivide: return PythonOperator.FloorDivide;
default:
string message = string.Format(
System.Globalization.CultureInfo.InvariantCulture,
Resources.UnexpectedToken,
token.Kind);
Debug.Assert(false, message);
throw new ValueErrorException(message);
}
}
// import_stmt: 'import' module ['as' name"] (',' module ['as' name])*
// name: identifier
private ImportStatement ParseImportStmt() {
Eat(TokenKind.KeywordImport);
var start = GetStart();
List<ModuleName> l = new List<ModuleName>();
List<string> las = new List<string>();
l.Add(ParseModuleName());
las.Add(MaybeParseAsName());
while (MaybeEat(TokenKind.Comma)) {
l.Add(ParseModuleName());
las.Add(MaybeParseAsName());
}
ModuleName[] names = l.ToArray();
var asNames = las.ToArray();
ImportStatement ret = new ImportStatement(names, asNames);
ret.SetLoc(_globalParent, start, GetEnd());
return ret;
}
// module: (identifier '.')* identifier
private ModuleName ParseModuleName() {
var start = GetStart();
ModuleName ret = new ModuleName(ReadNames());
ret.SetLoc(_globalParent, start, GetEnd());
return ret;
}
// relative_module: "."* module | "."+
private ModuleName ParseRelativeModuleName() {
var start = GetStart();
int dotCount = 0;
while (MaybeEat(TokenKind.Dot)) {
dotCount++;
}
string[] names = ArrayUtils.EmptyStrings;
if (PeekToken() is NameToken) {
names = ReadNames();
}
ModuleName ret;
if (dotCount > 0) {
ret = new RelativeModuleName(names, dotCount);
} else {
if (names.Length == 0) {
ReportSyntaxError("invalid syntax");
}
ret = new ModuleName(names);
}
ret.SetLoc(_globalParent, start, GetEnd());
return ret;
}
private string[] ReadNames() {
List<string> l = new List<string>();
l.Add(ReadName());
while (MaybeEat(TokenKind.Dot)) {
l.Add(ReadName());
}
return l.ToArray();
}
// 'from' relative_module 'import' identifier ['as' name] (',' identifier ['as' name]) *
// 'from' relative_module 'import' '(' identifier ['as' name] (',' identifier ['as' name])* [','] ')'
// 'from' module 'import' "*"
private FromImportStatement ParseFromImportStmt() {
Eat(TokenKind.KeywordFrom);
var start = GetStart();
ModuleName dname = ParseRelativeModuleName();
Eat(TokenKind.KeywordImport);
bool ateParen = MaybeEat(TokenKind.LeftParenthesis);
string[] names;
string[] asNames;
bool fromFuture = false;
if (MaybeEat(TokenKind.Multiply)) {
names = (string[])FromImportStatement.Star;
asNames = null;
} else {
List<string> l = new List<string>();
List<string> las = new List<string>();
if (MaybeEat(TokenKind.LeftParenthesis)) {
ParseAsNameList(l, las);
Eat(TokenKind.RightParenthesis);
} else {
ParseAsNameList(l, las);
}
names = l.ToArray();
asNames = las.ToArray();
}
// Process from __future__ statement
if (dname.Names.Count == 1 && dname.Names[0] == "__future__") {
if (!_fromFutureAllowed) {
ReportSyntaxError(Resources.MisplacedFuture);
}
if (names == FromImportStatement.Star) {
ReportSyntaxError(Resources.NoFutureStar);
}
fromFuture = true;
foreach (string name in names) {
if (name == "division") {
// Ignored in Python 3
} else if (name == "with_statement") {
// Ignored in Python 2.7
} else if (name == "absolute_import") {
// Ignored in Python 3
} else if (name == "print_function") {
// Ignored in Python 3
} else if (name == "unicode_literals") {
// Ignored in Python 3
} else if (name == "nested_scopes") {
} else if (name == "generators") {
} else {
string strName = name;
fromFuture = false;
if (strName != "braces") {
ReportSyntaxError(Resources.UnknownFutureFeature + strName);
} else {
// match CPython error message
ReportSyntaxError(Resources.NotAChance);
}
}
}
}
if (ateParen) {
Eat(TokenKind.RightParenthesis);
}
FromImportStatement ret = new FromImportStatement(dname, (string[])names, asNames, fromFuture);
ret.SetLoc(_globalParent, start, GetEnd());
return ret;
}
// import_as_name (',' import_as_name)*
private void ParseAsNameList(List<string> l, List<string> las) {
l.Add(ReadName());
las.Add(MaybeParseAsName());
while (MaybeEat(TokenKind.Comma)) {
if (PeekToken(TokenKind.RightParenthesis)) return; // the list is allowed to end with a ,
l.Add(ReadName());
las.Add(MaybeParseAsName());
}
}
//import_as_name: NAME [NAME NAME]
//dotted_as_name: dotted_name [NAME NAME]
private string MaybeParseAsName() {
if (MaybeEat(TokenKind.KeywordAs)) {
return ReadName();
}
return null;
}
//nonlocal_stmt: 'nonlocal' NAME (',' NAME)*
private NonlocalStatement ParseNonLocalStmt() {
Eat(TokenKind.KeywordNonlocal);
var start = GetStart();
var l = new List<string>();
l.Add(ReadName());
while(MaybeEat(TokenKind.Comma)) {
l.Add(ReadName());
}
string[] names = l.ToArray();
NonlocalStatement ret = new NonlocalStatement(names);
ret.SetLoc(_globalParent, start, GetEnd());
return ret;
}
//global_stmt: 'global' NAME (',' NAME)*
private GlobalStatement ParseGlobalStmt() {
Eat(TokenKind.KeywordGlobal);
var start = GetStart();
List<string> l = new List<string>();
l.Add(ReadName());
while (MaybeEat(TokenKind.Comma)) {
l.Add(ReadName());
}
string[] names = l.ToArray();
GlobalStatement ret = new GlobalStatement(names);
ret.SetLoc(_globalParent, start, GetEnd());
return ret;
}
//raise_stmt: 'raise' [test ['from' test]]
private RaiseStatement ParseRaiseStmt() {
Eat(TokenKind.KeywordRaise);
var start = GetStart();
Expression exception = null, cause = null;
if (!NeverTestToken(PeekToken())) {
exception = ParseTest();
if (MaybeEat(TokenKind.KeywordFrom)) {
cause = ParseTest();
}
}
RaiseStatement ret = new RaiseStatement(exception, cause);
ret.SetLoc(_globalParent, start, GetEnd());
return ret;
}
//assert_stmt: 'assert' expression [',' expression]
private AssertStatement ParseAssertStmt() {
Eat(TokenKind.KeywordAssert);
var start = GetStart();
Expression expr = ParseTest();
Expression message = null;
if (MaybeEat(TokenKind.Comma)) {
message = ParseTest();
}
AssertStatement ret = new AssertStatement(expr, message);
ret.SetLoc(_globalParent, start, GetEnd());
return ret;
}