forked from microsoft/python-language-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParser.cs
More file actions
5532 lines (4871 loc) · 228 KB
/
Parser.cs
File metadata and controls
5532 lines (4871 loc) · 228 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
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.Python.Core;
using Microsoft.Python.Core.Collections;
using Microsoft.Python.Core.Text;
using Microsoft.Python.Parsing.Ast;
namespace Microsoft.Python.Parsing {
public class Parser {
// immutable properties:
private readonly Tokenizer _tokenizer;
// mutable properties:
private ErrorSink _errors;
/// <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 FutureOptions _languageFeatures;
private readonly PythonLanguageVersion _langVersion;
// state:
private TokenWithSpan _token;
private TokenWithSpan _lookahead, _lookahead2;
private Stack<FunctionDefinition> _functions;
private int _classDepth;
private bool _fromFutureAllowed;
private string _privatePrefix;
private bool _parsingStarted, _allowIncomplete;
private bool _inLoop, _inFinally, _isGenerator, _inGeneratorExpression;
private List<IndexSpan> _returnsWithValue;
private readonly bool _verbatim; // true if we're in verbatim mode and the ASTs can be turned back into source code, preserving white space / comments
private readonly bool _bindReferences; // true if we should bind the references in the ASTs
private string _tokenWhiteSpace, _lookaheadWhiteSpace; // the whitespace for the current and lookahead tokens as provided from the parser
private string _lookahead2WhiteSpace;
private Dictionary<Node, Dictionary<object, object>> _attributes = new Dictionary<Node, Dictionary<object, object>>(); // attributes for each node, currently just round tripping information
private bool _alwaysAllowContextDependentSyntax;
private bool _stubFile;
private static Regex _codingRegex;
#region Construction
private Parser(Tokenizer tokenizer, ErrorSink errorSink, PythonLanguageVersion langVersion, bool verbatim, bool bindRefs, string privatePrefix) {
Contract.Assert(tokenizer != null);
Contract.Assert(errorSink != null);
tokenizer.ErrorSink = new TokenizerErrorSink(this);
_tokenizer = tokenizer;
_errors = errorSink;
_langVersion = langVersion;
_verbatim = verbatim;
_bindReferences = bindRefs;
Reset(FutureOptions.None);
if (langVersion.Is3x()) {
// 3.x always does true division and absolute import
_languageFeatures |= FutureOptions.TrueDivision | FutureOptions.AbsoluteImports;
}
_privatePrefix = privatePrefix;
}
public static Parser CreateParser(TextReader reader, PythonLanguageVersion version) => CreateParser(reader, version, null);
public static Parser CreateParser(TextReader reader, PythonLanguageVersion version, ParserOptions parserOptions) {
if (reader == null) {
throw new ArgumentNullException(nameof(reader));
}
var options = parserOptions ?? ParserOptions.Default;
Parser parser = null;
var tokenizer = new Tokenizer(
version, options.ErrorSink,
(options.Verbatim ? TokenizerOptions.Verbatim : TokenizerOptions.None) |
TokenizerOptions.GroupingRecovery |
(options.StubFile ? TokenizerOptions.StubFile : 0) |
(options.ParseFStringExpression ? TokenizerOptions.FStringExpression : 0));
tokenizer.Initialize(null, reader, options.InitialSourceLocation ?? SourceLocation.MinValue);
tokenizer.IndentationInconsistencySeverity = options.IndentationInconsistencySeverity;
parser = new Parser(
tokenizer,
options.ErrorSink ?? ErrorSink.Null,
version,
options.Verbatim,
options.BindReferences,
options.PrivatePrefix
) { _stubFile = options.StubFile };
return parser;
}
public static Parser CreateParser(Stream stream, PythonLanguageVersion version) {
if (stream == null) {
throw new ArgumentNullException(nameof(stream));
}
return CreateParser(stream, version, null);
}
/// <summary>
/// Creates a new parser from a seekable stream including scanning the BOM or looking for a # coding: comment to detect the appropriate coding.
/// </summary>
public static Parser CreateParser(Stream stream, PythonLanguageVersion version, ParserOptions parserOptions = null) {
var options = parserOptions ?? ParserOptions.Default;
var defaultEncoding = version.Is2x() ? Encoding.ASCII : Encoding.UTF8;
var reader = GetStreamReaderWithEncoding(stream, defaultEncoding, options.ErrorSink);
return CreateParser(reader, version, options);
}
#endregion
#region Public parser interface
//single_input: Newline | simple_stmt | compound_stmt Newline
//eval_input: testlist Newline* ENDMARKER
//file_input: (Newline | stmt)* ENDMARKER
public PythonAst ParseFile(Uri module = null) => ParseFileWorker(module);
//[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(Uri module, out ParseResult properties) {
bool parsingMultiLineCmpdStmt;
properties = ParseResult.Complete;
StartParsing();
Statement ret = InternalParseInteractiveInput(out parsingMultiLineCmpdStmt, out bool isEmptyStmt);
if (ErrorCode == 0) {
if (isEmptyStmt) {
properties = ParseResult.Empty;
} else if (parsingMultiLineCmpdStmt) {
properties = ParseResult.IncompleteStatement;
}
if (isEmptyStmt) {
return null;
}
return CreateAst(module, ret);
} else {
if ((ErrorCode & ErrorCodes.IncompleteMask) != 0) {
if ((ErrorCode & ErrorCodes.IncompleteToken) != 0) {
properties = ParseResult.IncompleteToken;
return null;
}
if ((ErrorCode & ErrorCodes.IncompleteStatement) != 0) {
if (parsingMultiLineCmpdStmt) {
properties = ParseResult.IncompleteStatement;
} else {
properties = ParseResult.IncompleteToken;
}
return null;
}
}
properties = ParseResult.Invalid;
return null;
}
}
public Expression ParseFStrSubExpr() {
_alwaysAllowContextDependentSyntax = true;
StartParsing();
// Read empty spaces
while (MaybeEatNewLine() || MaybeEat(TokenKind.Dedent) || MaybeEat(TokenKind.Indent)) {
;
}
if (PeekToken(TokenKind.EndOfFile)) {
ReportSyntaxError(Resources.EmptyExpressionFStringErrorMsg);
}
// Yield expressions are allowed
Expression node = null;
if (PeekToken(TokenKind.KeywordYield)) {
Eat(TokenKind.KeywordYield);
node = ParseYieldExpression();
} else {
node = ParseTestListAsExpr();
}
if (node is LambdaExpression lambda) {
_errors.Add(
Resources.LambdaParenthesesFstringErrorMsg,
new SourceSpan(_tokenizer.IndexToLocation(node.StartIndex), _tokenizer.IndexToLocation(node.EndIndex)),
ErrorCodes.SyntaxError,
Severity.Error
);
}
if (ErrorCode == 0) {
// Detect if there are unexpected tokens
EatEndOfInput();
}
_alwaysAllowContextDependentSyntax = false;
return node;
}
private PythonAst CreateAst(Uri module, Statement ret) {
var ast = new PythonAst(module, ret, _tokenizer.GetLineLocations(), _tokenizer.LanguageVersion, _tokenizer.GetCommentLocations()) { HasVerbatim = _verbatim, PrivatePrefix = _privatePrefix };
if (_token.Token != null) {
ast.SetLoc(0, GetEndForStatement());
}
if (_verbatim) {
AddExtraVerbatimText(ast, _lookaheadWhiteSpace + _lookahead.Token.VerbatimImage);
}
ast.SetAttributes(_attributes);
PythonNameBinder.BindAst(_langVersion, ast, _errors, _bindReferences);
return ast;
}
public PythonAst ParseTopExpression(Uri module) {
// TODO: move from source unit .TrimStart(' ', '\t')
_alwaysAllowContextDependentSyntax = true;
var ret = new ReturnStatement(ParseTestListAsExpression());
_alwaysAllowContextDependentSyntax = false;
ret.SetLoc(0, 0);
return CreateAst(module, ret);
}
internal ErrorSink ErrorSink {
get => _errors;
set {
Contract.Assert(value != null);
_errors = value;
}
}
public int ErrorCode { get; private set; }
public void Reset(FutureOptions languageFeatures) {
_languageFeatures = languageFeatures;
_token = new TokenWithSpan();
_lookahead = new TokenWithSpan();
_fromFutureAllowed = true;
_classDepth = 0;
_functions = null;
_privatePrefix = null;
_parsingStarted = false;
ErrorCode = 0;
}
public void Reset() => Reset(_languageFeatures);
#endregion
#region Error Reporting
private void ReportSyntaxError(TokenWithSpan t) => ReportSyntaxError(t, ErrorCodes.SyntaxError);
private void ReportSyntaxError(TokenWithSpan t, int errorCode) => 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;
}
var msg = GetErrorMessage(t, errorCode);
ReportSyntaxError(start, end, msg, errorCode);
}
private static string GetErrorMessage(Token t, int errorCode) {
string msg;
if ((errorCode & ~ErrorCodes.IncompleteMask) == ErrorCodes.IndentationError) {
msg = Resources.ExpectedIndentedBlockErrorMsg;//"expected an indented block";
} else if (t.Kind != TokenKind.EndOfFile) {
msg = Resources.UnexpectedTokenErrorMsg.FormatUI(t.Image); //"unexpected token '{0}'".FormatUI(t.Image);
} else {
msg = Resources.UnexpectedEndOfFileWhileParsingErrorMsg;//"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) => ReportSyntaxError(start, end, message, ErrorCodes.SyntaxError);
internal void ReportSyntaxError(int start, int end, string message, int errorCode) {
// save the first one, the next error codes may be induced errors:
if (ErrorCode == 0) {
ErrorCode = errorCode;
}
_errors.Add(
message,
new SourceSpan(_tokenizer.IndexToLocation(start), _tokenizer.IndexToLocation(end)),
errorCode,
Severity.Error
);
}
#endregion
#region LL(1) Parsing
private static bool IsPrivateName(string name) => name.StartsWithOrdinal("__") && !name.EndsWithOrdinal("__");
private string FixName(string name) {
if (_privatePrefix != null && IsPrivateName(name)) {
name = "_" + _privatePrefix + name;
}
return name;
}
private Name ReadNameMaybeNone(int prevTokenStart, int prevTokenLength) {
// peek for better error recovery
var t = PeekToken();
if (t == Tokens.NoneToken) {
NextToken();
return Name.None;
}
var n = TokenToName(t);
if (n.HasName) {
NextToken();
return n;
}
var prevTokenEnd = prevTokenStart + prevTokenLength;
var message = Resources.SyntaxErrorMsg;//"syntax error";
if (_lookahead.Token.Kind == TokenKind.NewLine) {
// Incomplete member expression, report next character unless there is none.
// If there is none, then point to the newline. If we are at EOF, report the dot.
if (_lookahead.Span.Start == prevTokenEnd) {
// Dot then immediately the newline. Report the newline.
ReportSyntaxError(_lookahead.Span.Start, _lookahead.Span.End, message);
} else {
// There is something between the dot and the newline.
// Report character after the dot.
ReportSyntaxError(prevTokenEnd, prevTokenEnd + 1, message);
}
} else {
ReportSyntaxError(message);
}
return Name.Empty;
}
struct Name {
public readonly string RealName;
public readonly string VerbatimName;
public static readonly Name Empty = new Name();
public static readonly Name Async = new Name("async", "async");
public static readonly Name Await = new Name("await", "await");
public static readonly Name None = new Name("None", "None");
public Name(string name, string verbatimName) {
RealName = name;
VerbatimName = verbatimName;
}
public bool HasName => RealName != null;
}
private Name ReadName() {
var n = TokenToName(PeekToken());
if (n.HasName) {
NextToken();
} else {
ReportSyntaxError(_lookahead);
}
return n;
}
private Name TokenToName(Token t) {
if (!AllowAsyncAwaitSyntax) {
if (t.Kind == TokenKind.KeywordAwait) {
return Name.Await;
} else if (t.Kind == TokenKind.KeywordAsync) {
return Name.Async;
}
}
if (t is NameToken n) {
return new Name(FixName(n.Name), n.Name);
}
return Name.Empty;
}
private bool AllowReturnSyntax => _alwaysAllowContextDependentSyntax ||
CurrentFunction != null;
private bool AllowYieldSyntax {
get {
FunctionDefinition cf;
if (_alwaysAllowContextDependentSyntax) {
return true;
}
if ((cf = CurrentFunction) == null) {
return false;
}
if (_langVersion >= PythonLanguageVersion.V36) {
return true;
}
if (!cf.IsCoroutine) {
return true;
}
return false;
}
}
private bool AllowAsyncAwaitSyntax {
get {
FunctionDefinition cf;
return _alwaysAllowContextDependentSyntax ||
((cf = CurrentFunction) != null && cf.IsCoroutine);
}
}
//stmt: simple_stmt | compound_stmt
//compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
private Statement ParseStmt() {
switch (PeekToken().Kind) {
case TokenKind.KeywordIf:
return ParseIfStmt();
case TokenKind.KeywordWhile:
return ParseWhileStmt();
case TokenKind.KeywordFor:
return ParseForStmt(isAsync: false);
case TokenKind.KeywordTry:
return ParseTryStatement();
case TokenKind.At:
return ParseDecorated();
case TokenKind.KeywordDef:
return ParseFuncDef(isCoroutine: false);
case TokenKind.KeywordClass:
return ParseClassDef();
case TokenKind.KeywordWith:
return ParseWithStmt(isAsync: false);
case TokenKind.KeywordAsync:
return ParseAsyncStmt();
default:
return ParseSimpleStmt();
}
}
private Statement ParseAsyncStmt() {
var token2 = PeekToken2();
if (token2.Kind == TokenKind.KeywordDef) {
Eat(TokenKind.KeywordAsync);
return ParseFuncDef(isCoroutine: true);
}
if (!AllowAsyncAwaitSyntax) {
// 'async', outside coroutine, and not followed by def, is a
// regular name
return ParseSimpleStmt();
}
NextToken();
switch (PeekToken().Kind) {
case TokenKind.KeywordFor:
return ParseForStmt(isAsync: true);
case TokenKind.KeywordWith:
return ParseWithStmt(isAsync: true);
}
ReportSyntaxError(Resources.SyntaxErrorMsg);//"syntax error"
return ParseStmt();
}
//simple_stmt: small_stmt (';' small_stmt)* [';'] Newline
private Statement ParseSimpleStmt() {
var s = ParseSmallStmt();
string newline = null;
if (MaybeEat(TokenKind.Semicolon)) {
var itemWhiteSpace = MakeWhiteSpaceList();
if (itemWhiteSpace != null) {
itemWhiteSpace.Add(_tokenWhiteSpace);
}
var start = s.StartIndex;
var l = new List<Statement> { s };
while (true) {
if (MaybeEatNewLine(out newline) || MaybeEatEof()) {
break;
}
l.Add(ParseSmallStmt());
if (MaybeEatEof()) {
// implies a new line
break;
} else if (!MaybeEat(TokenKind.Semicolon)) {
EatNewLine(out newline);
break;
}
if (itemWhiteSpace != null) {
itemWhiteSpace.Add(_tokenWhiteSpace);
}
}
var stmts = l.ToArray();
var ret = new SuiteStatement(stmts);
ret.SetLoc(start, stmts[stmts.Length - 1].EndIndex);
if (itemWhiteSpace != null) {
AddListWhiteSpace(ret, itemWhiteSpace.ToArray());
}
if (newline != null) {
_lookaheadWhiteSpace = newline + _lookaheadWhiteSpace;
}
return ret;
} else if (MaybeEatEof()) {
} else if (EatNewLine(out newline)) {
if (_verbatim) {
_lookaheadWhiteSpace = newline + _lookaheadWhiteSpace;
}
} else {
// error handling, make sure we're making forward progress
NextToken();
if (_verbatim) {
_lookaheadWhiteSpace = _tokenWhiteSpace + _token.Token.VerbatimImage + _lookaheadWhiteSpace;
}
}
return s;
}
private bool MaybeEatEof() {
if (PeekToken().Kind == TokenKind.EndOfFile) {
return true;
}
return false;
}
/*
small_stmt: expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt | import_stmt | global_stmt | exec_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' testlist
*/
private Statement ParseSmallStmt() {
switch (PeekToken().Kind) {
case TokenKind.KeywordPrint:
return ParsePrintStmt();
case TokenKind.KeywordPass:
return FinishSmallStmt(new EmptyStatement());
case TokenKind.KeywordBreak:
if (!_inLoop) {
ReportSyntaxError(Resources.BreakOustideLoopErrorMsg);//"'break' outside loop"
}
return FinishSmallStmt(new BreakStatement());
case TokenKind.KeywordContinue:
if (!_inLoop) {
ReportSyntaxError(Resources.ContinueNotInLoopErrorMsg);//'continue' not properly in loop
} else if (_inFinally) {
ReportSyntaxError(Resources.ContinueNotSupportedInsideFinallyErrorMsg);//'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.KeywordExec:
return ParseExecStmt();
case TokenKind.KeywordDel:
return ParseDelStmt();
case TokenKind.KeywordYield:
return ParseYieldStmt();
default:
return ParseExprStmt();
}
}
// del_stmt: "del" target_list
// for error reporting reasons we allow any expression and then report the bad
// delete node when it fails. This is the reason we don't call ParseTargetList.
private Statement ParseDelStmt() {
var curLookahead = _lookahead;
NextToken();
var delWhiteSpace = _tokenWhiteSpace;
var start = GetStart();
DelStatement ret;
if (PeekToken(TokenKind.NewLine) || PeekToken(TokenKind.EndOfFile)) {
ReportSyntaxError(curLookahead.Span.Start, curLookahead.Span.End, Resources.ExpectedExpressionAfterDelErrorMsg);//expected expression after del
ret = new DelStatement(ImmutableArray<Expression>.Empty);
} else {
var l = ParseExprList(out var itemWhiteSpace);
foreach (var e in l) {
if (e is ErrorExpression) {
continue;
}
var delError = e.CheckDelete();
if (delError != null) {
ReportSyntaxError(e.StartIndex, e.EndIndex, delError, ErrorCodes.SyntaxError);
}
}
ret = new DelStatement(ImmutableArray<Expression>.Create(l));
if (itemWhiteSpace != null) {
AddListWhiteSpace(ret, itemWhiteSpace.ToArray());
}
}
ret.SetLoc(start, GetEndForStatement());
if (_verbatim) {
AddPreceedingWhiteSpace(ret, delWhiteSpace);
}
return ret;
}
private Statement ParseReturnStmt() {
if (!AllowReturnSyntax) {
ReportSyntaxError(Resources.ReturnOutsideFunctionErrorMsg);//'return' outside function
}
var returnToken = _lookahead;
NextToken();
var returnWhitespace = _tokenWhiteSpace;
Expression expr = null;
var start = GetStart();
if (!NeverTestToken(PeekToken())) {
expr = ParseTestListAsExpr();
}
if (expr != null && _langVersion < PythonLanguageVersion.V33) {
if (_isGenerator) {
ReportSyntaxError(returnToken.Span.Start, expr.EndIndex, Resources.ReturnWithArgumentInGeneratorErrorMsg);//'return' with argument inside generator
} else {
if (_returnsWithValue == null) {
_returnsWithValue = new List<IndexSpan>();
}
_returnsWithValue.Add(new IndexSpan(returnToken.Span.Start, expr.EndIndex - returnToken.Span.Start));
}
}
var ret = new ReturnStatement(expr);
if (_verbatim) {
AddPreceedingWhiteSpace(ret, returnWhitespace);
}
ret.SetLoc(start, GetEndForStatement());
return ret;
}
private Statement FinishSmallStmt(Statement stmt) {
NextToken();
stmt.SetLoc(GetStart(), GetEndForStatement());
if (_verbatim) {
AddPreceedingWhiteSpace(stmt, _tokenWhiteSpace);
}
return stmt;
}
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.
if (!AllowYieldSyntax) {
if (AllowAsyncAwaitSyntax) {
ReportSyntaxError(Resources.YieldInsideAsyncErrorMsg);//'yield' inside async function
} else {
ReportSyntaxError(Resources.MisplacedYieldErrorMsg);//misplaced yield
}
}
_isGenerator = true;
if (_returnsWithValue != null && _langVersion < PythonLanguageVersion.V33) {
foreach (var span in _returnsWithValue) {
ReportSyntaxError(span.Start, span.End, Resources.ReturnWithArgumentInGeneratorErrorMsg);//'return' with argument inside generator
}
}
Eat(TokenKind.KeywordYield);
// See Pep 342: a yield statement is now just an expression statement around a yield expression.
var e = ParseYieldExpression();
Debug.Assert(e != null); // caller already verified we have a yield.
Statement s = new ExpressionStatement(e);
s.SetLoc(e.StartIndex, GetEndForStatement());
return s;
}
/// <summary>
/// Peek if the next token is a 'yield' and parse a yield or yield from expression. Else return null.
///
/// Called w/ yield already eaten.
/// </summary>
/// <returns>A yield or yield from expression if present, else null.</returns>
// yield_expression: "yield" [expression_list]
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 case, the genexp will mark IsGenerator.
var current = CurrentFunction;
if (current != null && !current.IsCoroutine) {
current.IsGenerator = true;
}
var whitespace = _tokenWhiteSpace;
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.
// 4) 'from', in which case we expect a single expression and return YieldFromExpression
Expression yieldResult;
var isYieldFrom = PeekToken(TokenKind.KeywordFrom);
var suppressSyntaxError = false;
var fromWhitespace = string.Empty;
if (isYieldFrom) {
if (_langVersion < PythonLanguageVersion.V33) {
// yield from added to 3.3
ReportSyntaxError(Resources.InvalidSyntaxErrorMsg);
suppressSyntaxError = true;
}
NextToken();
fromWhitespace = _tokenWhiteSpace;
}
var l = ParseTestListAsExpr(null, out var itemWhiteSpace, out var trailingComma);
if (l.Count == 0) {
if (_langVersion < PythonLanguageVersion.V25 && !suppressSyntaxError) {
// 2.4 doesn't allow plain yield
ReportSyntaxError(Resources.InvalidSyntaxErrorMsg);
} else if (isYieldFrom && !suppressSyntaxError) {
// yield from requires one expression
ReportSyntaxError(Resources.InvalidSyntaxErrorMsg);
}
// Check empty expression and convert to 'none'
yieldResult = new ConstantExpression(null);
} else if (l.Count != 1) {
if (isYieldFrom && !suppressSyntaxError) {
// yield from requires one expression
ReportSyntaxError(l[0].StartIndex, l[l.Count - 1].EndIndex, Resources.InvalidSyntaxErrorMsg);
}
// make a tuple
yieldResult = MakeTupleOrExpr(l, itemWhiteSpace, trailingComma, true);
} else {
// just take the single expression
yieldResult = l[0];
}
Expression yieldExpression;
if (isYieldFrom) {
yieldExpression = new YieldFromExpression(yieldResult);
} else {
yieldExpression = new YieldExpression(yieldResult);
}
if (_verbatim) {
AddPreceedingWhiteSpace(yieldExpression, whitespace);
if (!string.IsNullOrEmpty(fromWhitespace)) {
AddSecondPreceedingWhiteSpace(yieldExpression, fromWhitespace);
}
if (l.Count == 0) {
AddIsAltForm(yieldExpression);
} else if (l.Count == 1 && trailingComma) {
AddListWhiteSpace(yieldExpression, itemWhiteSpace.ToArray());
}
}
yieldExpression.SetLoc(start, GetEnd());
return yieldExpression;
}
private Statement FinishAssignments(Expression right, bool thereCanBeOnlyOne = false) {
List<Expression> left = null;
var assignWhiteSpace = MakeWhiteSpaceList();
Expression singleLeft = null;
while (MaybeEat(TokenKind.Assign)) {
if (assignWhiteSpace != null) {
assignWhiteSpace.Add(_tokenWhiteSpace);
}
var assignError = right.CheckAssign();
if (assignError != null) {
ReportSyntaxError(right.StartIndex, right.EndIndex, assignError, ErrorCodes.SyntaxError | ErrorCodes.NoCaret);
}
if (singleLeft == null) {
singleLeft = right;
} else {
if (thereCanBeOnlyOne) {
ReportSyntaxError(GetStart(), GetEnd(), Resources.InvalidSyntaxErrorMsg);
}
if (left == null) {
left = new List<Expression> { singleLeft };
}
left.Add(right);
}
if (_langVersion >= PythonLanguageVersion.V25 && PeekToken(TokenKind.KeywordYield)) {
if (!AllowYieldSyntax && AllowAsyncAwaitSyntax) {
ReportSyntaxError(Resources.YieldInsideAsyncErrorMsg);//'yield' inside async function
}
Eat(TokenKind.KeywordYield);
right = ParseYieldExpression();
} else {
right = ParseTestListAsExpr(allowNamedExpression: false);
}
}
AssignmentStatement assign;
if (left != null) {
Debug.Assert(left.Count > 0);
assign = new AssignmentStatement(left.ToArray(), right);
assign.SetLoc(left[0].StartIndex, right.EndIndex);
} else {
Debug.Assert(singleLeft != null);
assign = new AssignmentStatement(new[] { singleLeft }, right);
assign.SetLoc(singleLeft.StartIndex, right.EndIndex);
}
if (assignWhiteSpace != null) {
AddListWhiteSpace(assign, assignWhiteSpace.ToArray());
}
return assign;
}
private static bool IsEndOfLineToken(Token t) {
switch (t.Kind) {
case TokenKind.Comment:
case TokenKind.NewLine:
case TokenKind.NLToken:
case TokenKind.EndOfFile:
return true;
}
return false;
}
private ErrorExpression ReadLineAsError(Expression preceeding, string message) {
var t = NextToken();
Debug.Assert(t.Kind == TokenKind.Colon);
var image = new StringBuilder();
if (_verbatim) {
image.Append(_tokenWhiteSpace);
}
image.Append(':');
while (!IsEndOfLineToken(PeekToken())) {
t = NextToken();
if (_verbatim) {
image.Append(_tokenWhiteSpace);
image.Append(t.VerbatimImage);
} else {
image.Append(t.Image);
}
}
var err = new ErrorExpression(image.ToString(), preceeding);
err.SetLoc(preceeding.StartIndex, GetEnd());
ReportSyntaxError(err.StartIndex, err.EndIndex, message);
return err;
}
private Expression ParseNameAnnotation(Expression expr) {
var inex = (expr as ParenthesisExpression)?.Expression;
if (expr is NameExpression || expr is MemberExpression || expr is IndexExpression ||
inex is NameExpression || inex is MemberExpression || inex is IndexExpression) {
// pass
} else if (expr is TupleExpression) {
return ReadLineAsError(expr, Resources.SingleTargetCanBeAnnotatedErrorMsg);//only single target (not tuple) can be annotated
} else {
return ReadLineAsError(expr, Resources.IllegalTargetAnnotationErrorMsg);//illegal target for annotation
}
Eat(TokenKind.Colon);
var ws2 = _tokenWhiteSpace;
var startColon = GetStart();
var ann = ParseExpression();
if (ann is ErrorExpression err) {
var image = ws2 + ":";
Dictionary<object, object> attr = null;
if (_verbatim && _attributes.TryGetValue(err, out attr)) {
if (attr.TryGetValue(NodeAttributes.PreceedingWhiteSpace, out var o)) {
image += o.ToString();
}
}
var err2 = err.AddPrefix(image, expr);
err2.SetLoc(startColon, err.EndIndex);
if (attr != null) {
_attributes[err2] = attr;
_attributes.Remove(err);
}
return err2;
}
var ret = new ExpressionWithAnnotation(expr, ann);
ret.SetLoc(expr.StartIndex, ann.EndIndex);
if (_verbatim) {
AddSecondPreceedingWhiteSpace(ret, ws2);
}
return ret;
}
// expr_stmt: expression_list
// expression_list: expression ( "," expression )* [","]
// assignment_stmt: (target_list "=")+ (expression_list | yield_expression)
// augmented_assignment_stmt ::= target augop (expression_list | yield_expression)
// augop: '+=' | '-=' | '*=' | '/=' | '%=' | '**=' | '>>=' | '<<=' | '&=' | '^=' | '|=' | '//='
private Statement ParseExprStmt() {
var ret = ParseTestListAsExpr(allowNamedExpression: false);
var hasAnnotation = false;
if (PeekToken(TokenKind.Colon) && (_stubFile || _langVersion >= PythonLanguageVersion.V36)) {
ret = ParseNameAnnotation(ret);
hasAnnotation = true;
if (!PeekToken(TokenKind.Assign)) {
Statement stmt = new ExpressionStatement(ret);
stmt.SetLoc(ret.StartIndex, GetEndForStatement());
return stmt;
}
}
if (PeekToken(TokenKind.Assign)) {
if (_stubFile || _langVersion.Is3x()) {
var hasStar = false;
if (ret is SequenceExpression seq) {
for (var i = 0; i < seq.Items.Count; i++) {
if (seq.Items[i] is StarredExpression) {
if (hasStar) {
ReportSyntaxError(seq.Items[i].StartIndex, seq.Items[i].EndIndex, Resources.TwoStarredExpressionErrorMsg);//two starred expressions in assignment
}
hasStar = true;
}
}
}
}
return FinishAssignments(ret, hasAnnotation);
} else {
var op = GetAssignOperator(PeekToken());
if (op != PythonOperator.None) {
NextToken();
var whiteSpace = _tokenWhiteSpace;
Expression rhs;
if (_langVersion >= PythonLanguageVersion.V25 && PeekToken(TokenKind.KeywordYield)) {
if (!AllowYieldSyntax && AllowAsyncAwaitSyntax) {
ReportSyntaxError(Resources.YieldInsideAsyncErrorMsg);//'yield' inside async function
}