-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
Copy pathLanguageParser.cs
13813 lines (12149 loc) · 595 KB
/
LanguageParser.cs
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 MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax
{
using Microsoft.CodeAnalysis.Syntax.InternalSyntax;
internal partial class LanguageParser : SyntaxParser
{
// list pools - allocators for lists that are used to build sequences of nodes. The lists
// can be reused (hence pooled) since the syntax factory methods don't keep references to
// them
private readonly SyntaxListPool _pool = new SyntaxListPool(); // Don't need to reset this.
private readonly SyntaxFactoryContext _syntaxFactoryContext; // Fields are resettable.
private readonly ContextAwareSyntax _syntaxFactory; // Has context, the fields of which are resettable.
private int _recursionDepth;
private TerminatorState _termState; // Resettable
private bool _isInTry; // Resettable
private bool _checkedTopLevelStatementsFeatureAvailability; // Resettable
// NOTE: If you add new state, you should probably add it to ResetPoint as well.
internal LanguageParser(
Lexer lexer,
CSharp.CSharpSyntaxNode oldTree,
IEnumerable<TextChangeRange> changes,
LexerMode lexerMode = LexerMode.Syntax,
CancellationToken cancellationToken = default(CancellationToken))
: base(lexer, lexerMode, oldTree, changes, allowModeReset: false,
preLexIfNotIncremental: true, cancellationToken: cancellationToken)
{
_syntaxFactoryContext = new SyntaxFactoryContext();
_syntaxFactory = new ContextAwareSyntax(_syntaxFactoryContext);
}
private static bool IsSomeWord(SyntaxKind kind)
{
return kind == SyntaxKind.IdentifierToken || SyntaxFacts.IsKeywordKind(kind);
}
// Parsing rule terminating conditions. This is how we know if it is
// okay to abort the current parsing rule when unexpected tokens occur.
[Flags]
internal enum TerminatorState
{
EndOfFile = 0,
IsNamespaceMemberStartOrStop = 1 << 0,
IsAttributeDeclarationTerminator = 1 << 1,
IsPossibleAggregateClauseStartOrStop = 1 << 2,
IsPossibleMemberStartOrStop = 1 << 3,
IsEndOfReturnType = 1 << 4,
IsEndOfParameterList = 1 << 5,
IsEndOfFieldDeclaration = 1 << 6,
IsPossibleEndOfVariableDeclaration = 1 << 7,
IsEndOfTypeArgumentList = 1 << 8,
IsPossibleStatementStartOrStop = 1 << 9,
IsEndOfFixedStatement = 1 << 10,
IsEndOfTryBlock = 1 << 11,
IsEndOfCatchClause = 1 << 12,
IsEndOfFilterClause = 1 << 13,
IsEndOfCatchBlock = 1 << 14,
IsEndOfDoWhileExpression = 1 << 15,
IsEndOfForStatementArgument = 1 << 16,
IsEndOfDeclarationClause = 1 << 17,
IsEndOfArgumentList = 1 << 18,
IsSwitchSectionStart = 1 << 19,
IsEndOfTypeParameterList = 1 << 20,
IsEndOfMethodSignature = 1 << 21,
IsEndOfNameInExplicitInterface = 1 << 22,
IsEndOfFunctionPointerParameterList = 1 << 23,
IsEndOfFunctionPointerParameterListErrored = 1 << 24,
IsEndOfFunctionPointerCallingConvention = 1 << 25,
IsEndOfRecordSignature = 1 << 26,
}
private const int LastTerminatorState = (int)TerminatorState.IsEndOfRecordSignature;
private bool IsTerminator()
{
if (this.CurrentToken.Kind == SyntaxKind.EndOfFileToken)
{
return true;
}
for (int i = 1; i <= LastTerminatorState; i <<= 1)
{
switch (_termState & (TerminatorState)i)
{
case TerminatorState.IsNamespaceMemberStartOrStop when this.IsNamespaceMemberStartOrStop():
case TerminatorState.IsAttributeDeclarationTerminator when this.IsAttributeDeclarationTerminator():
case TerminatorState.IsPossibleAggregateClauseStartOrStop when this.IsPossibleAggregateClauseStartOrStop():
case TerminatorState.IsPossibleMemberStartOrStop when this.IsPossibleMemberStartOrStop():
case TerminatorState.IsEndOfReturnType when this.IsEndOfReturnType():
case TerminatorState.IsEndOfParameterList when this.IsEndOfParameterList():
case TerminatorState.IsEndOfFieldDeclaration when this.IsEndOfFieldDeclaration():
case TerminatorState.IsPossibleEndOfVariableDeclaration when this.IsPossibleEndOfVariableDeclaration():
case TerminatorState.IsEndOfTypeArgumentList when this.IsEndOfTypeArgumentList():
case TerminatorState.IsPossibleStatementStartOrStop when this.IsPossibleStatementStartOrStop():
case TerminatorState.IsEndOfFixedStatement when this.IsEndOfFixedStatement():
case TerminatorState.IsEndOfTryBlock when this.IsEndOfTryBlock():
case TerminatorState.IsEndOfCatchClause when this.IsEndOfCatchClause():
case TerminatorState.IsEndOfFilterClause when this.IsEndOfFilterClause():
case TerminatorState.IsEndOfCatchBlock when this.IsEndOfCatchBlock():
case TerminatorState.IsEndOfDoWhileExpression when this.IsEndOfDoWhileExpression():
case TerminatorState.IsEndOfForStatementArgument when this.IsEndOfForStatementArgument():
case TerminatorState.IsEndOfDeclarationClause when this.IsEndOfDeclarationClause():
case TerminatorState.IsEndOfArgumentList when this.IsEndOfArgumentList():
case TerminatorState.IsSwitchSectionStart when this.IsPossibleSwitchSection():
case TerminatorState.IsEndOfTypeParameterList when this.IsEndOfTypeParameterList():
case TerminatorState.IsEndOfMethodSignature when this.IsEndOfMethodSignature():
case TerminatorState.IsEndOfNameInExplicitInterface when this.IsEndOfNameInExplicitInterface():
case TerminatorState.IsEndOfFunctionPointerParameterList when this.IsEndOfFunctionPointerParameterList(errored: false):
case TerminatorState.IsEndOfFunctionPointerParameterListErrored when this.IsEndOfFunctionPointerParameterList(errored: true):
case TerminatorState.IsEndOfFunctionPointerCallingConvention when this.IsEndOfFunctionPointerCallingConvention():
case TerminatorState.IsEndOfRecordSignature when this.IsEndOfRecordSignature():
return true;
}
}
return false;
}
private static CSharp.CSharpSyntaxNode GetOldParent(CSharp.CSharpSyntaxNode node)
{
return node != null ? node.Parent : null;
}
private struct NamespaceBodyBuilder
{
public SyntaxListBuilder<ExternAliasDirectiveSyntax> Externs;
public SyntaxListBuilder<UsingDirectiveSyntax> Usings;
public SyntaxListBuilder<AttributeListSyntax> Attributes;
public SyntaxListBuilder<MemberDeclarationSyntax> Members;
public NamespaceBodyBuilder(SyntaxListPool pool)
{
Externs = pool.Allocate<ExternAliasDirectiveSyntax>();
Usings = pool.Allocate<UsingDirectiveSyntax>();
Attributes = pool.Allocate<AttributeListSyntax>();
Members = pool.Allocate<MemberDeclarationSyntax>();
}
internal void Free(SyntaxListPool pool)
{
pool.Free(Members);
pool.Free(Attributes);
pool.Free(Usings);
pool.Free(Externs);
}
}
internal CompilationUnitSyntax ParseCompilationUnit()
{
return ParseWithStackGuard(
ParseCompilationUnitCore,
() => SyntaxFactory.CompilationUnit(
new SyntaxList<ExternAliasDirectiveSyntax>(),
new SyntaxList<UsingDirectiveSyntax>(),
new SyntaxList<AttributeListSyntax>(),
new SyntaxList<MemberDeclarationSyntax>(),
SyntaxFactory.Token(SyntaxKind.EndOfFileToken)));
}
internal CompilationUnitSyntax ParseCompilationUnitCore()
{
SyntaxToken tmp = null;
SyntaxListBuilder initialBadNodes = null;
var body = new NamespaceBodyBuilder(_pool);
try
{
this.ParseNamespaceBody(ref tmp, ref body, ref initialBadNodes, SyntaxKind.CompilationUnit);
var eof = this.EatToken(SyntaxKind.EndOfFileToken);
var result = _syntaxFactory.CompilationUnit(body.Externs, body.Usings, body.Attributes, body.Members, eof);
if (initialBadNodes != null)
{
// attach initial bad nodes as leading trivia on first token
result = AddLeadingSkippedSyntax(result, initialBadNodes.ToListNode());
_pool.Free(initialBadNodes);
}
return result;
}
finally
{
body.Free(_pool);
}
}
internal TNode ParseWithStackGuard<TNode>(Func<TNode> parseFunc, Func<TNode> createEmptyNodeFunc) where TNode : CSharpSyntaxNode
{
// If this value is non-zero then we are nesting calls to ParseWithStackGuard which should not be
// happening. It's not a bug but it's inefficient and should be changed.
Debug.Assert(_recursionDepth == 0);
try
{
return parseFunc();
}
catch (InsufficientExecutionStackException)
{
return CreateForGlobalFailure(lexer.TextWindow.Position, createEmptyNodeFunc());
}
}
private TNode CreateForGlobalFailure<TNode>(int position, TNode node) where TNode : CSharpSyntaxNode
{
// Turn the complete input into a single skipped token. This avoids running the lexer, and therefore
// the preprocessor directive parser, which may itself run into the same problem that caused the
// original failure.
var builder = new SyntaxListBuilder(1);
builder.Add(SyntaxFactory.BadToken(null, lexer.TextWindow.Text.ToString(), null));
var fileAsTrivia = _syntaxFactory.SkippedTokensTrivia(builder.ToList<SyntaxToken>());
node = AddLeadingSkippedSyntax(node, fileAsTrivia);
ForceEndOfFile(); // force the scanner to report that it is at the end of the input.
return AddError(node, position, 0, ErrorCode.ERR_InsufficientStack);
}
private BaseNamespaceDeclarationSyntax ParseNamespaceDeclaration(
SyntaxList<AttributeListSyntax> attributeLists,
SyntaxListBuilder modifiers)
{
_recursionDepth++;
StackGuard.EnsureSufficientExecutionStack(_recursionDepth);
var result = ParseNamespaceDeclarationCore(attributeLists, modifiers);
_recursionDepth--;
return result;
}
private BaseNamespaceDeclarationSyntax ParseNamespaceDeclarationCore(
SyntaxList<AttributeListSyntax> attributeLists,
SyntaxListBuilder modifiers)
{
Debug.Assert(this.CurrentToken.Kind == SyntaxKind.NamespaceKeyword);
var namespaceToken = this.EatToken(SyntaxKind.NamespaceKeyword);
if (IsScript)
{
namespaceToken = this.AddError(namespaceToken, ErrorCode.ERR_NamespaceNotAllowedInScript);
}
var name = this.ParseQualifiedName();
SyntaxToken openBrace = null;
SyntaxToken semicolon = null;
if (this.CurrentToken.Kind == SyntaxKind.SemicolonToken)
{
semicolon = this.EatToken(SyntaxKind.SemicolonToken);
}
else if (this.CurrentToken.Kind == SyntaxKind.OpenBraceToken || IsPossibleNamespaceMemberDeclaration())
{
//either we see the brace we expect here or we see something that could come after a brace
//so we insert a missing one
openBrace = this.EatToken(SyntaxKind.OpenBraceToken);
}
else
{
//the next character is neither the brace we expect, nor a token that could follow the expected
//brace so we assume it's a mistake and replace it with a missing brace
openBrace = this.EatTokenWithPrejudice(SyntaxKind.OpenBraceToken);
openBrace = this.ConvertToMissingWithTrailingTrivia(openBrace, SyntaxKind.OpenBraceToken);
}
Debug.Assert(semicolon != null || openBrace != null);
var body = new NamespaceBodyBuilder(_pool);
try
{
if (openBrace == null)
{
Debug.Assert(semicolon != null);
SyntaxListBuilder initialBadNodes = null;
this.ParseNamespaceBody(ref semicolon, ref body, ref initialBadNodes, SyntaxKind.FileScopedNamespaceDeclaration);
Debug.Assert(initialBadNodes == null); // init bad nodes should have been attached to semicolon...
namespaceToken = CheckFeatureAvailability(namespaceToken, MessageID.IDS_FeatureFileScopedNamespace);
return _syntaxFactory.FileScopedNamespaceDeclaration(
attributeLists,
modifiers.ToList(),
namespaceToken,
name,
semicolon,
body.Externs,
body.Usings,
body.Members);
}
else
{
SyntaxListBuilder initialBadNodes = null;
this.ParseNamespaceBody(ref openBrace, ref body, ref initialBadNodes, SyntaxKind.NamespaceDeclaration);
Debug.Assert(initialBadNodes == null); // init bad nodes should have been attached to open brace...
return _syntaxFactory.NamespaceDeclaration(
attributeLists,
modifiers.ToList(),
namespaceToken,
name,
openBrace,
body.Externs,
body.Usings,
body.Members,
this.EatToken(SyntaxKind.CloseBraceToken),
this.TryEatToken(SyntaxKind.SemicolonToken));
}
}
finally
{
body.Free(_pool);
}
}
private static bool IsPossibleStartOfTypeDeclaration(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.EnumKeyword:
case SyntaxKind.DelegateKeyword:
case SyntaxKind.ClassKeyword:
case SyntaxKind.InterfaceKeyword:
case SyntaxKind.StructKeyword:
case SyntaxKind.AbstractKeyword:
case SyntaxKind.InternalKeyword:
case SyntaxKind.NewKeyword:
case SyntaxKind.PrivateKeyword:
case SyntaxKind.ProtectedKeyword:
case SyntaxKind.PublicKeyword:
case SyntaxKind.SealedKeyword:
case SyntaxKind.StaticKeyword:
case SyntaxKind.UnsafeKeyword:
case SyntaxKind.OpenBracketToken:
return true;
default:
return false;
}
}
private void AddSkippedNamespaceText(
ref SyntaxToken openBraceOrSemicolon,
ref NamespaceBodyBuilder body,
ref SyntaxListBuilder initialBadNodes,
CSharpSyntaxNode skippedSyntax)
{
if (body.Members.Count > 0)
{
AddTrailingSkippedSyntax(body.Members, skippedSyntax);
}
else if (body.Attributes.Count > 0)
{
AddTrailingSkippedSyntax(body.Attributes, skippedSyntax);
}
else if (body.Usings.Count > 0)
{
AddTrailingSkippedSyntax(body.Usings, skippedSyntax);
}
else if (body.Externs.Count > 0)
{
AddTrailingSkippedSyntax(body.Externs, skippedSyntax);
}
else if (openBraceOrSemicolon != null)
{
openBraceOrSemicolon = AddTrailingSkippedSyntax(openBraceOrSemicolon, skippedSyntax);
}
else
{
if (initialBadNodes == null)
{
initialBadNodes = _pool.Allocate();
}
initialBadNodes.AddRange(skippedSyntax);
}
}
// Parts of a namespace declaration in the order they can be defined.
private enum NamespaceParts
{
None = 0,
ExternAliases = 1,
Usings = 2,
GlobalAttributes = 3,
MembersAndStatements = 4,
TypesAndNamespaces = 5,
TopLevelStatementsAfterTypesAndNamespaces = 6,
}
private void ParseNamespaceBody(ref SyntaxToken openBraceOrSemicolon, ref NamespaceBodyBuilder body, ref SyntaxListBuilder initialBadNodes, SyntaxKind parentKind)
{
// "top-level" expressions and statements should never occur inside an asynchronous context
Debug.Assert(!IsInAsync);
bool isGlobal = openBraceOrSemicolon == null;
var saveTerm = _termState;
_termState |= TerminatorState.IsNamespaceMemberStartOrStop;
NamespaceParts seen = NamespaceParts.None;
var pendingIncompleteMembers = _pool.Allocate<MemberDeclarationSyntax>();
bool reportUnexpectedToken = true;
try
{
while (true)
{
switch (this.CurrentToken.Kind)
{
case SyntaxKind.NamespaceKeyword:
// incomplete members must be processed before we add any nodes to the body:
AddIncompleteMembers(ref pendingIncompleteMembers, ref body);
var attributeLists = _pool.Allocate<AttributeListSyntax>();
var modifiers = _pool.Allocate();
body.Members.Add(adjustStateAndReportStatementOutOfOrder(ref seen, this.ParseNamespaceDeclaration(attributeLists, modifiers)));
_pool.Free(attributeLists);
_pool.Free(modifiers);
reportUnexpectedToken = true;
break;
case SyntaxKind.CloseBraceToken:
// A very common user error is to type an additional }
// somewhere in the file. This will cause us to stop parsing
// the root (global) namespace too early and will make the
// rest of the file unparseable and unusable by intellisense.
// We detect that case here and we skip the close curly and
// continue parsing as if we did not see the }
if (isGlobal)
{
// incomplete members must be processed before we add any nodes to the body:
ReduceIncompleteMembers(ref pendingIncompleteMembers, ref openBraceOrSemicolon, ref body, ref initialBadNodes);
var token = this.EatToken();
token = this.AddError(token,
IsScript ? ErrorCode.ERR_GlobalDefinitionOrStatementExpected : ErrorCode.ERR_EOFExpected);
this.AddSkippedNamespaceText(ref openBraceOrSemicolon, ref body, ref initialBadNodes, token);
reportUnexpectedToken = true;
break;
}
else
{
// This token marks the end of a namespace body
return;
}
case SyntaxKind.EndOfFileToken:
// This token marks the end of a namespace body
return;
case SyntaxKind.ExternKeyword:
if (isGlobal && !ScanExternAliasDirective())
{
// extern member or a local function
goto default;
}
else
{
// incomplete members must be processed before we add any nodes to the body:
ReduceIncompleteMembers(ref pendingIncompleteMembers, ref openBraceOrSemicolon, ref body, ref initialBadNodes);
var @extern = ParseExternAliasDirective();
if (seen > NamespaceParts.ExternAliases)
{
@extern = this.AddErrorToFirstToken(@extern, ErrorCode.ERR_ExternAfterElements);
this.AddSkippedNamespaceText(ref openBraceOrSemicolon, ref body, ref initialBadNodes, @extern);
}
else
{
body.Externs.Add(@extern);
seen = NamespaceParts.ExternAliases;
}
reportUnexpectedToken = true;
break;
}
case SyntaxKind.UsingKeyword:
if (isGlobal && (this.PeekToken(1).Kind == SyntaxKind.OpenParenToken || (!IsScript && IsPossibleTopLevelUsingLocalDeclarationStatement())))
{
// Top-level using statement or using local declaration
goto default;
}
else
{
parseUsingDirective(ref openBraceOrSemicolon, ref body, ref initialBadNodes, ref seen, ref pendingIncompleteMembers);
}
reportUnexpectedToken = true;
break;
case SyntaxKind.IdentifierToken:
if (this.CurrentToken.ContextualKind != SyntaxKind.GlobalKeyword || this.PeekToken(1).Kind != SyntaxKind.UsingKeyword)
{
goto default;
}
else
{
parseUsingDirective(ref openBraceOrSemicolon, ref body, ref initialBadNodes, ref seen, ref pendingIncompleteMembers);
}
reportUnexpectedToken = true;
break;
case SyntaxKind.OpenBracketToken:
if (this.IsPossibleGlobalAttributeDeclaration())
{
// incomplete members must be processed before we add any nodes to the body:
ReduceIncompleteMembers(ref pendingIncompleteMembers, ref openBraceOrSemicolon, ref body, ref initialBadNodes);
var attribute = this.ParseAttributeDeclaration();
if (!isGlobal || seen > NamespaceParts.GlobalAttributes)
{
attribute = this.AddError(attribute, attribute.Target.Identifier, ErrorCode.ERR_GlobalAttributesNotFirst);
this.AddSkippedNamespaceText(ref openBraceOrSemicolon, ref body, ref initialBadNodes, attribute);
}
else
{
body.Attributes.Add(attribute);
seen = NamespaceParts.GlobalAttributes;
}
reportUnexpectedToken = true;
break;
}
goto default;
default:
var memberOrStatement = isGlobal ? this.ParseMemberDeclarationOrStatement(parentKind) : this.ParseMemberDeclaration(parentKind);
if (memberOrStatement == null)
{
// incomplete members must be processed before we add any nodes to the body:
ReduceIncompleteMembers(ref pendingIncompleteMembers, ref openBraceOrSemicolon, ref body, ref initialBadNodes);
// eat one token and try to parse declaration or statement again:
var skippedToken = EatToken();
if (reportUnexpectedToken && !skippedToken.ContainsDiagnostics)
{
skippedToken = this.AddError(skippedToken,
IsScript ? ErrorCode.ERR_GlobalDefinitionOrStatementExpected : ErrorCode.ERR_EOFExpected);
// do not report the error multiple times for subsequent tokens:
reportUnexpectedToken = false;
}
this.AddSkippedNamespaceText(ref openBraceOrSemicolon, ref body, ref initialBadNodes, skippedToken);
}
else if (memberOrStatement.Kind == SyntaxKind.IncompleteMember && seen < NamespaceParts.MembersAndStatements)
{
pendingIncompleteMembers.Add(memberOrStatement);
reportUnexpectedToken = true;
}
else
{
// incomplete members must be processed before we add any nodes to the body:
AddIncompleteMembers(ref pendingIncompleteMembers, ref body);
body.Members.Add(adjustStateAndReportStatementOutOfOrder(ref seen, memberOrStatement));
reportUnexpectedToken = true;
}
break;
}
}
}
finally
{
_termState = saveTerm;
// adds pending incomplete nodes:
AddIncompleteMembers(ref pendingIncompleteMembers, ref body);
_pool.Free(pendingIncompleteMembers);
}
MemberDeclarationSyntax adjustStateAndReportStatementOutOfOrder(ref NamespaceParts seen, MemberDeclarationSyntax memberOrStatement)
{
switch (memberOrStatement.Kind)
{
case SyntaxKind.GlobalStatement:
if (seen < NamespaceParts.MembersAndStatements)
{
seen = NamespaceParts.MembersAndStatements;
}
else if (seen == NamespaceParts.TypesAndNamespaces)
{
seen = NamespaceParts.TopLevelStatementsAfterTypesAndNamespaces;
if (!IsScript)
{
memberOrStatement = this.AddError(memberOrStatement, ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType);
}
}
break;
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.FileScopedNamespaceDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.DelegateDeclaration:
case SyntaxKind.RecordDeclaration:
case SyntaxKind.RecordStructDeclaration:
if (seen < NamespaceParts.TypesAndNamespaces)
{
seen = NamespaceParts.TypesAndNamespaces;
}
break;
default:
if (seen < NamespaceParts.MembersAndStatements)
{
seen = NamespaceParts.MembersAndStatements;
}
break;
}
return memberOrStatement;
}
void parseUsingDirective(ref SyntaxToken openBrace, ref NamespaceBodyBuilder body, ref SyntaxListBuilder initialBadNodes, ref NamespaceParts seen, ref SyntaxListBuilder<MemberDeclarationSyntax> pendingIncompleteMembers)
{
// incomplete members must be processed before we add any nodes to the body:
ReduceIncompleteMembers(ref pendingIncompleteMembers, ref openBrace, ref body, ref initialBadNodes);
var @using = this.ParseUsingDirective();
if (seen > NamespaceParts.Usings)
{
@using = this.AddError(@using, ErrorCode.ERR_UsingAfterElements);
this.AddSkippedNamespaceText(ref openBrace, ref body, ref initialBadNodes, @using);
}
else
{
body.Usings.Add(@using);
seen = NamespaceParts.Usings;
}
}
}
private GlobalStatementSyntax CheckTopLevelStatementsFeatureAvailability(GlobalStatementSyntax globalStatementSyntax)
{
if (IsScript || _checkedTopLevelStatementsFeatureAvailability)
{
return globalStatementSyntax;
}
_checkedTopLevelStatementsFeatureAvailability = true;
return CheckFeatureAvailability(globalStatementSyntax, MessageID.IDS_TopLevelStatements);
}
private static void AddIncompleteMembers(ref SyntaxListBuilder<MemberDeclarationSyntax> incompleteMembers, ref NamespaceBodyBuilder body)
{
if (incompleteMembers.Count > 0)
{
body.Members.AddRange(incompleteMembers);
incompleteMembers.Clear();
}
}
private void ReduceIncompleteMembers(
ref SyntaxListBuilder<MemberDeclarationSyntax> incompleteMembers,
ref SyntaxToken openBraceOrSemicolon,
ref NamespaceBodyBuilder body,
ref SyntaxListBuilder initialBadNodes)
{
for (int i = 0; i < incompleteMembers.Count; i++)
{
this.AddSkippedNamespaceText(ref openBraceOrSemicolon, ref body, ref initialBadNodes, incompleteMembers[i]);
}
incompleteMembers.Clear();
}
private bool IsPossibleNamespaceMemberDeclaration()
{
switch (this.CurrentToken.Kind)
{
case SyntaxKind.ExternKeyword:
case SyntaxKind.UsingKeyword:
case SyntaxKind.NamespaceKeyword:
return true;
case SyntaxKind.IdentifierToken:
return IsPartialInNamespaceMemberDeclaration();
default:
return IsPossibleStartOfTypeDeclaration(this.CurrentToken.Kind);
}
}
private bool IsPartialInNamespaceMemberDeclaration()
{
if (this.CurrentToken.ContextualKind == SyntaxKind.PartialKeyword)
{
if (this.IsPartialType())
{
return true;
}
else if (this.PeekToken(1).Kind == SyntaxKind.NamespaceKeyword)
{
return true;
}
}
return false;
}
public bool IsEndOfNamespace()
{
return this.CurrentToken.Kind == SyntaxKind.CloseBraceToken;
}
public bool IsGobalAttributesTerminator()
{
return this.IsEndOfNamespace()
|| this.IsPossibleNamespaceMemberDeclaration();
}
private bool IsNamespaceMemberStartOrStop()
{
return this.IsEndOfNamespace()
|| this.IsPossibleNamespaceMemberDeclaration();
}
/// <summary>
/// Returns true if the lookahead tokens compose extern alias directive.
/// </summary>
private bool ScanExternAliasDirective()
{
// The check also includes the ending semicolon so that we can disambiguate among:
// extern alias goo;
// extern alias goo();
// extern alias goo { get; }
return this.CurrentToken.Kind == SyntaxKind.ExternKeyword
&& this.PeekToken(1).Kind == SyntaxKind.IdentifierToken && this.PeekToken(1).ContextualKind == SyntaxKind.AliasKeyword
&& this.PeekToken(2).Kind == SyntaxKind.IdentifierToken
&& this.PeekToken(3).Kind == SyntaxKind.SemicolonToken;
}
private ExternAliasDirectiveSyntax ParseExternAliasDirective()
{
if (this.IsIncrementalAndFactoryContextMatches && this.CurrentNodeKind == SyntaxKind.ExternAliasDirective)
{
return (ExternAliasDirectiveSyntax)this.EatNode();
}
Debug.Assert(this.CurrentToken.Kind == SyntaxKind.ExternKeyword);
var externToken = this.EatToken(SyntaxKind.ExternKeyword);
var aliasToken = this.EatContextualToken(SyntaxKind.AliasKeyword);
externToken = CheckFeatureAvailability(externToken, MessageID.IDS_FeatureExternAlias);
var name = this.ParseIdentifierToken();
var semicolon = this.EatToken(SyntaxKind.SemicolonToken);
return _syntaxFactory.ExternAliasDirective(externToken, aliasToken, name, semicolon);
}
private NameEqualsSyntax ParseNameEquals()
{
Debug.Assert(this.IsNamedAssignment());
return _syntaxFactory.NameEquals(
_syntaxFactory.IdentifierName(this.ParseIdentifierToken()),
this.EatToken(SyntaxKind.EqualsToken));
}
private UsingDirectiveSyntax ParseUsingDirective()
{
if (this.IsIncrementalAndFactoryContextMatches && this.CurrentNodeKind == SyntaxKind.UsingDirective)
{
return (UsingDirectiveSyntax)this.EatNode();
}
SyntaxToken globalToken = null;
if (this.CurrentToken.ContextualKind == SyntaxKind.GlobalKeyword)
{
globalToken = ConvertToKeyword(this.EatToken());
}
Debug.Assert(this.CurrentToken.Kind == SyntaxKind.UsingKeyword);
var usingToken = this.EatToken(SyntaxKind.UsingKeyword);
var staticToken = this.TryEatToken(SyntaxKind.StaticKeyword);
var alias = this.IsNamedAssignment() ? ParseNameEquals() : null;
NameSyntax name;
SyntaxToken semicolon;
if (IsPossibleNamespaceMemberDeclaration())
{
//We're worried about the case where someone already has a correct program
//and they've gone back to add a using directive, but have not finished the
//new directive. e.g.
//
// using
// namespace Goo {
// //...
// }
//
//If the token we see after "using" could be its own top-level construct, then
//we just want to insert a missing identifier and semicolon and then return to
//parsing at the top-level.
//
//NB: there's no way this could be true for a set of tokens that form a valid
//using directive, so there's no danger in checking the error case first.
name = WithAdditionalDiagnostics(CreateMissingIdentifierName(), GetExpectedTokenError(SyntaxKind.IdentifierToken, this.CurrentToken.Kind));
semicolon = SyntaxFactory.MissingToken(SyntaxKind.SemicolonToken);
}
else
{
name = this.ParseQualifiedName();
if (name.IsMissing && this.PeekToken(1).Kind == SyntaxKind.SemicolonToken)
{
//if we can see a semicolon ahead, then the current token was
//probably supposed to be an identifier
name = AddTrailingSkippedSyntax(name, this.EatToken());
}
semicolon = this.EatToken(SyntaxKind.SemicolonToken);
}
var usingDirective = _syntaxFactory.UsingDirective(globalToken, usingToken, staticToken, alias, name, semicolon);
if (staticToken != null)
{
usingDirective = CheckFeatureAvailability(usingDirective, MessageID.IDS_FeatureUsingStatic);
}
if (globalToken != null)
{
usingDirective = CheckFeatureAvailability(usingDirective, MessageID.IDS_FeatureGlobalUsing);
}
return usingDirective;
}
private bool IsPossibleGlobalAttributeDeclaration()
{
return this.CurrentToken.Kind == SyntaxKind.OpenBracketToken
&& IsGlobalAttributeTarget(this.PeekToken(1))
&& this.PeekToken(2).Kind == SyntaxKind.ColonToken;
}
private static bool IsGlobalAttributeTarget(SyntaxToken token)
{
switch (token.ToAttributeLocation())
{
case AttributeLocation.Assembly:
case AttributeLocation.Module:
return true;
default:
return false;
}
}
private bool IsPossibleAttributeDeclaration()
{
return this.CurrentToken.Kind == SyntaxKind.OpenBracketToken;
}
private SyntaxList<AttributeListSyntax> ParseAttributeDeclarations()
{
var attributes = _pool.Allocate<AttributeListSyntax>();
try
{
var saveTerm = _termState;
_termState |= TerminatorState.IsAttributeDeclarationTerminator;
while (this.IsPossibleAttributeDeclaration())
{
var attribute = this.ParseAttributeDeclaration();
attributes.Add(attribute);
}
_termState = saveTerm;
return attributes.ToList();
}
finally
{
_pool.Free(attributes);
}
}
private bool IsAttributeDeclarationTerminator()
{
return this.CurrentToken.Kind == SyntaxKind.CloseBracketToken
|| this.IsPossibleAttributeDeclaration(); // start of a new one...
}
private AttributeListSyntax ParseAttributeDeclaration()
{
if (this.IsIncrementalAndFactoryContextMatches && this.CurrentNodeKind == SyntaxKind.AttributeList)
{
return (AttributeListSyntax)this.EatNode();
}
var openBracket = this.EatToken(SyntaxKind.OpenBracketToken);
// Check for optional location :
AttributeTargetSpecifierSyntax attrLocation = null;
if (IsSomeWord(this.CurrentToken.Kind) && this.PeekToken(1).Kind == SyntaxKind.ColonToken)
{
var id = ConvertToKeyword(this.EatToken());
var colon = this.EatToken(SyntaxKind.ColonToken);
attrLocation = _syntaxFactory.AttributeTargetSpecifier(id, colon);
}
var attributes = _pool.AllocateSeparated<AttributeSyntax>();
try
{
if (attrLocation != null && attrLocation.Identifier.ToAttributeLocation() == AttributeLocation.Module)
{
attrLocation = CheckFeatureAvailability(attrLocation, MessageID.IDS_FeatureModuleAttrLoc);
}
this.ParseAttributes(attributes);
var closeBracket = this.EatToken(SyntaxKind.CloseBracketToken);
var declaration = _syntaxFactory.AttributeList(openBracket, attrLocation, attributes, closeBracket);
return declaration;
}
finally
{
_pool.Free(attributes);
}
}
private void ParseAttributes(SeparatedSyntaxListBuilder<AttributeSyntax> nodes)
{
// always expect at least one attribute
nodes.Add(this.ParseAttribute());
// remaining attributes
while (this.CurrentToken.Kind != SyntaxKind.CloseBracketToken)
{
if (this.CurrentToken.Kind == SyntaxKind.CommaToken)
{
// comma is optional, but if it is present it may be followed by another attribute
nodes.AddSeparator(this.EatToken());
// check for legal trailing comma
if (this.CurrentToken.Kind == SyntaxKind.CloseBracketToken)
{
break;
}
nodes.Add(this.ParseAttribute());
}
else if (this.IsPossibleAttribute())
{
// report missing comma
nodes.AddSeparator(this.EatToken(SyntaxKind.CommaToken));
nodes.Add(this.ParseAttribute());
}
else if (this.SkipBadAttributeListTokens(nodes, SyntaxKind.IdentifierToken) == PostSkipAction.Abort)
{
break;
}
}
}
private PostSkipAction SkipBadAttributeListTokens(SeparatedSyntaxListBuilder<AttributeSyntax> list, SyntaxKind expected)
{
Debug.Assert(list.Count > 0);
SyntaxToken tmp = null;
return this.SkipBadSeparatedListTokensWithExpectedKind(ref tmp, list,
p => p.CurrentToken.Kind != SyntaxKind.CommaToken && !p.IsPossibleAttribute(),
p => p.CurrentToken.Kind == SyntaxKind.CloseBracketToken || p.IsTerminator(),
expected);
}
private bool IsPossibleAttribute()
{
return this.IsTrueIdentifier();
}
private AttributeSyntax ParseAttribute()
{
if (this.IsIncrementalAndFactoryContextMatches && this.CurrentNodeKind == SyntaxKind.Attribute)