forked from apple/swift-clang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ParseTentative.cpp
2000 lines (1795 loc) · 64.6 KB
/
ParseTentative.cpp
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
//===--- ParseTentative.cpp - Ambiguity Resolution Parsing ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the tentative parsing portions of the Parser
// interfaces, for ambiguity resolution.
//
//===----------------------------------------------------------------------===//
#include "clang/Parse/Parser.h"
#include "clang/Parse/ParseDiagnostic.h"
#include "clang/Sema/ParsedTemplate.h"
using namespace clang;
/// isCXXDeclarationStatement - C++-specialized function that disambiguates
/// between a declaration or an expression statement, when parsing function
/// bodies. Returns true for declaration, false for expression.
///
/// declaration-statement:
/// block-declaration
///
/// block-declaration:
/// simple-declaration
/// asm-definition
/// namespace-alias-definition
/// using-declaration
/// using-directive
/// [C++0x] static_assert-declaration
///
/// asm-definition:
/// 'asm' '(' string-literal ')' ';'
///
/// namespace-alias-definition:
/// 'namespace' identifier = qualified-namespace-specifier ';'
///
/// using-declaration:
/// 'using' typename[opt] '::'[opt] nested-name-specifier
/// unqualified-id ';'
/// 'using' '::' unqualified-id ;
///
/// using-directive:
/// 'using' 'namespace' '::'[opt] nested-name-specifier[opt]
/// namespace-name ';'
///
bool Parser::isCXXDeclarationStatement() {
switch (Tok.getKind()) {
// asm-definition
case tok::kw_asm:
// namespace-alias-definition
case tok::kw_namespace:
// using-declaration
// using-directive
case tok::kw_using:
// static_assert-declaration
case tok::kw_static_assert:
case tok::kw__Static_assert:
return true;
// simple-declaration
default:
return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
}
}
/// isCXXSimpleDeclaration - C++-specialized function that disambiguates
/// between a simple-declaration or an expression-statement.
/// If during the disambiguation process a parsing error is encountered,
/// the function returns true to let the declaration parsing code handle it.
/// Returns false if the statement is disambiguated as expression.
///
/// simple-declaration:
/// decl-specifier-seq init-declarator-list[opt] ';'
/// decl-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
/// brace-or-equal-initializer ';' [C++17]
///
/// (if AllowForRangeDecl specified)
/// for ( for-range-declaration : for-range-initializer ) statement
///
/// for-range-declaration:
/// decl-specifier-seq declarator
/// decl-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
///
/// In any of the above cases there can be a preceding attribute-specifier-seq,
/// but the caller is expected to handle that.
bool Parser::isCXXSimpleDeclaration(bool AllowForRangeDecl) {
// C++ 6.8p1:
// There is an ambiguity in the grammar involving expression-statements and
// declarations: An expression-statement with a function-style explicit type
// conversion (5.2.3) as its leftmost subexpression can be indistinguishable
// from a declaration where the first declarator starts with a '('. In those
// cases the statement is a declaration. [Note: To disambiguate, the whole
// statement might have to be examined to determine if it is an
// expression-statement or a declaration].
// C++ 6.8p3:
// The disambiguation is purely syntactic; that is, the meaning of the names
// occurring in such a statement, beyond whether they are type-names or not,
// is not generally used in or changed by the disambiguation. Class
// templates are instantiated as necessary to determine if a qualified name
// is a type-name. Disambiguation precedes parsing, and a statement
// disambiguated as a declaration may be an ill-formed declaration.
// We don't have to parse all of the decl-specifier-seq part. There's only
// an ambiguity if the first decl-specifier is
// simple-type-specifier/typename-specifier followed by a '(', which may
// indicate a function-style cast expression.
// isCXXDeclarationSpecifier will return TPResult::Ambiguous only in such
// a case.
bool InvalidAsDeclaration = false;
TPResult TPR = isCXXDeclarationSpecifier(TPResult::False,
&InvalidAsDeclaration);
if (TPR != TPResult::Ambiguous)
return TPR != TPResult::False; // Returns true for TPResult::True or
// TPResult::Error.
// FIXME: TryParseSimpleDeclaration doesn't look past the first initializer,
// and so gets some cases wrong. We can't carry on if we've already seen
// something which makes this statement invalid as a declaration in this case,
// since it can cause us to misparse valid code. Revisit this once
// TryParseInitDeclaratorList is fixed.
if (InvalidAsDeclaration)
return false;
// FIXME: Add statistics about the number of ambiguous statements encountered
// and how they were resolved (number of declarations+number of expressions).
// Ok, we have a simple-type-specifier/typename-specifier followed by a '(',
// or an identifier which doesn't resolve as anything. We need tentative
// parsing...
{
RevertingTentativeParsingAction PA(*this);
TPR = TryParseSimpleDeclaration(AllowForRangeDecl);
}
// In case of an error, let the declaration parsing code handle it.
if (TPR == TPResult::Error)
return true;
// Declarations take precedence over expressions.
if (TPR == TPResult::Ambiguous)
TPR = TPResult::True;
assert(TPR == TPResult::True || TPR == TPResult::False);
return TPR == TPResult::True;
}
/// Try to consume a token sequence that we've already identified as
/// (potentially) starting a decl-specifier.
Parser::TPResult Parser::TryConsumeDeclarationSpecifier() {
switch (Tok.getKind()) {
case tok::kw__Atomic:
if (NextToken().isNot(tok::l_paren)) {
ConsumeToken();
break;
}
LLVM_FALLTHROUGH;
case tok::kw_typeof:
case tok::kw___attribute:
case tok::kw___underlying_type: {
ConsumeToken();
if (Tok.isNot(tok::l_paren))
return TPResult::Error;
ConsumeParen();
if (!SkipUntil(tok::r_paren))
return TPResult::Error;
break;
}
case tok::kw_class:
case tok::kw_struct:
case tok::kw_union:
case tok::kw___interface:
case tok::kw_enum:
// elaborated-type-specifier:
// class-key attribute-specifier-seq[opt]
// nested-name-specifier[opt] identifier
// class-key nested-name-specifier[opt] template[opt] simple-template-id
// enum nested-name-specifier[opt] identifier
//
// FIXME: We don't support class-specifiers nor enum-specifiers here.
ConsumeToken();
// Skip attributes.
while (Tok.isOneOf(tok::l_square, tok::kw___attribute, tok::kw___declspec,
tok::kw_alignas)) {
if (Tok.is(tok::l_square)) {
ConsumeBracket();
if (!SkipUntil(tok::r_square))
return TPResult::Error;
} else {
ConsumeToken();
if (Tok.isNot(tok::l_paren))
return TPResult::Error;
ConsumeParen();
if (!SkipUntil(tok::r_paren))
return TPResult::Error;
}
}
if (Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
tok::annot_template_id) &&
TryAnnotateCXXScopeToken())
return TPResult::Error;
if (Tok.is(tok::annot_cxxscope))
ConsumeAnnotationToken();
if (Tok.is(tok::identifier))
ConsumeToken();
else if (Tok.is(tok::annot_template_id))
ConsumeAnnotationToken();
else
return TPResult::Error;
break;
case tok::annot_cxxscope:
ConsumeAnnotationToken();
LLVM_FALLTHROUGH;
default:
ConsumeAnyToken();
if (getLangOpts().ObjC && Tok.is(tok::less))
return TryParseProtocolQualifiers();
break;
}
return TPResult::Ambiguous;
}
/// simple-declaration:
/// decl-specifier-seq init-declarator-list[opt] ';'
///
/// (if AllowForRangeDecl specified)
/// for ( for-range-declaration : for-range-initializer ) statement
/// for-range-declaration:
/// attribute-specifier-seqopt type-specifier-seq declarator
///
Parser::TPResult Parser::TryParseSimpleDeclaration(bool AllowForRangeDecl) {
if (TryConsumeDeclarationSpecifier() == TPResult::Error)
return TPResult::Error;
// Two decl-specifiers in a row conclusively disambiguate this as being a
// simple-declaration. Don't bother calling isCXXDeclarationSpecifier in the
// overwhelmingly common case that the next token is a '('.
if (Tok.isNot(tok::l_paren)) {
TPResult TPR = isCXXDeclarationSpecifier();
if (TPR == TPResult::Ambiguous)
return TPResult::True;
if (TPR == TPResult::True || TPR == TPResult::Error)
return TPR;
assert(TPR == TPResult::False);
}
TPResult TPR = TryParseInitDeclaratorList();
if (TPR != TPResult::Ambiguous)
return TPR;
if (Tok.isNot(tok::semi) && (!AllowForRangeDecl || Tok.isNot(tok::colon)))
return TPResult::False;
return TPResult::Ambiguous;
}
/// Tentatively parse an init-declarator-list in order to disambiguate it from
/// an expression.
///
/// init-declarator-list:
/// init-declarator
/// init-declarator-list ',' init-declarator
///
/// init-declarator:
/// declarator initializer[opt]
/// [GNU] declarator simple-asm-expr[opt] attributes[opt] initializer[opt]
///
/// initializer:
/// brace-or-equal-initializer
/// '(' expression-list ')'
///
/// brace-or-equal-initializer:
/// '=' initializer-clause
/// [C++11] braced-init-list
///
/// initializer-clause:
/// assignment-expression
/// braced-init-list
///
/// braced-init-list:
/// '{' initializer-list ','[opt] '}'
/// '{' '}'
///
Parser::TPResult Parser::TryParseInitDeclaratorList() {
while (1) {
// declarator
TPResult TPR = TryParseDeclarator(false/*mayBeAbstract*/);
if (TPR != TPResult::Ambiguous)
return TPR;
// [GNU] simple-asm-expr[opt] attributes[opt]
if (Tok.isOneOf(tok::kw_asm, tok::kw___attribute))
return TPResult::True;
// initializer[opt]
if (Tok.is(tok::l_paren)) {
// Parse through the parens.
ConsumeParen();
if (!SkipUntil(tok::r_paren, StopAtSemi))
return TPResult::Error;
} else if (Tok.is(tok::l_brace)) {
// A left-brace here is sufficient to disambiguate the parse; an
// expression can never be followed directly by a braced-init-list.
return TPResult::True;
} else if (Tok.is(tok::equal) || isTokIdentifier_in()) {
// MSVC and g++ won't examine the rest of declarators if '=' is
// encountered; they just conclude that we have a declaration.
// EDG parses the initializer completely, which is the proper behavior
// for this case.
//
// At present, Clang follows MSVC and g++, since the parser does not have
// the ability to parse an expression fully without recording the
// results of that parse.
// FIXME: Handle this case correctly.
//
// Also allow 'in' after an Objective-C declaration as in:
// for (int (^b)(void) in array). Ideally this should be done in the
// context of parsing for-init-statement of a foreach statement only. But,
// in any other context 'in' is invalid after a declaration and parser
// issues the error regardless of outcome of this decision.
// FIXME: Change if above assumption does not hold.
return TPResult::True;
}
if (!TryConsumeToken(tok::comma))
break;
}
return TPResult::Ambiguous;
}
struct Parser::ConditionDeclarationOrInitStatementState {
Parser &P;
bool CanBeExpression = true;
bool CanBeCondition = true;
bool CanBeInitStatement;
bool CanBeForRangeDecl;
ConditionDeclarationOrInitStatementState(Parser &P, bool CanBeInitStatement,
bool CanBeForRangeDecl)
: P(P), CanBeInitStatement(CanBeInitStatement),
CanBeForRangeDecl(CanBeForRangeDecl) {}
bool resolved() {
return CanBeExpression + CanBeCondition + CanBeInitStatement +
CanBeForRangeDecl < 2;
}
void markNotExpression() {
CanBeExpression = false;
if (!resolved()) {
// FIXME: Unify the parsing codepaths for condition variables and
// simple-declarations so that we don't need to eagerly figure out which
// kind we have here. (Just parse init-declarators until we reach a
// semicolon or right paren.)
RevertingTentativeParsingAction PA(P);
if (CanBeForRangeDecl) {
// Skip until we hit a ')', ';', or a ':' with no matching '?'.
// The final case is a for range declaration, the rest are not.
while (true) {
unsigned QuestionColonDepth = 0;
P.SkipUntil({tok::r_paren, tok::semi, tok::question, tok::colon},
StopBeforeMatch);
if (P.Tok.is(tok::question))
++QuestionColonDepth;
else if (P.Tok.is(tok::colon)) {
if (QuestionColonDepth)
--QuestionColonDepth;
else {
CanBeCondition = CanBeInitStatement = false;
return;
}
} else {
CanBeForRangeDecl = false;
break;
}
P.ConsumeToken();
}
} else {
// Just skip until we hit a ')' or ';'.
P.SkipUntil(tok::r_paren, tok::semi, StopBeforeMatch);
}
if (P.Tok.isNot(tok::r_paren))
CanBeCondition = CanBeForRangeDecl = false;
if (P.Tok.isNot(tok::semi))
CanBeInitStatement = false;
}
}
bool markNotCondition() {
CanBeCondition = false;
return resolved();
}
bool markNotForRangeDecl() {
CanBeForRangeDecl = false;
return resolved();
}
bool update(TPResult IsDecl) {
switch (IsDecl) {
case TPResult::True:
markNotExpression();
assert(resolved() && "can't continue after tentative parsing bails out");
break;
case TPResult::False:
CanBeCondition = CanBeInitStatement = CanBeForRangeDecl = false;
break;
case TPResult::Ambiguous:
break;
case TPResult::Error:
CanBeExpression = CanBeCondition = CanBeInitStatement =
CanBeForRangeDecl = false;
break;
}
return resolved();
}
ConditionOrInitStatement result() const {
assert(CanBeExpression + CanBeCondition + CanBeInitStatement +
CanBeForRangeDecl < 2 &&
"result called but not yet resolved");
if (CanBeExpression)
return ConditionOrInitStatement::Expression;
if (CanBeCondition)
return ConditionOrInitStatement::ConditionDecl;
if (CanBeInitStatement)
return ConditionOrInitStatement::InitStmtDecl;
if (CanBeForRangeDecl)
return ConditionOrInitStatement::ForRangeDecl;
return ConditionOrInitStatement::Error;
}
};
/// Disambiguates between a declaration in a condition, a
/// simple-declaration in an init-statement, and an expression for
/// a condition of a if/switch statement.
///
/// condition:
/// expression
/// type-specifier-seq declarator '=' assignment-expression
/// [C++11] type-specifier-seq declarator '=' initializer-clause
/// [C++11] type-specifier-seq declarator braced-init-list
/// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
/// '=' assignment-expression
/// simple-declaration:
/// decl-specifier-seq init-declarator-list[opt] ';'
///
/// Note that, unlike isCXXSimpleDeclaration, we must disambiguate all the way
/// to the ';' to disambiguate cases like 'int(x))' (an expression) from
/// 'int(x);' (a simple-declaration in an init-statement).
Parser::ConditionOrInitStatement
Parser::isCXXConditionDeclarationOrInitStatement(bool CanBeInitStatement,
bool CanBeForRangeDecl) {
ConditionDeclarationOrInitStatementState State(*this, CanBeInitStatement,
CanBeForRangeDecl);
if (State.update(isCXXDeclarationSpecifier()))
return State.result();
// It might be a declaration; we need tentative parsing.
RevertingTentativeParsingAction PA(*this);
// FIXME: A tag definition unambiguously tells us this is an init-statement.
if (State.update(TryConsumeDeclarationSpecifier()))
return State.result();
assert(Tok.is(tok::l_paren) && "Expected '('");
while (true) {
// Consume a declarator.
if (State.update(TryParseDeclarator(false/*mayBeAbstract*/)))
return State.result();
// Attributes, asm label, or an initializer imply this is not an expression.
// FIXME: Disambiguate properly after an = instead of assuming that it's a
// valid declaration.
if (Tok.isOneOf(tok::equal, tok::kw_asm, tok::kw___attribute) ||
(getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace))) {
State.markNotExpression();
return State.result();
}
// A colon here identifies a for-range declaration.
if (State.CanBeForRangeDecl && Tok.is(tok::colon))
return ConditionOrInitStatement::ForRangeDecl;
// At this point, it can't be a condition any more, because a condition
// must have a brace-or-equal-initializer.
if (State.markNotCondition())
return State.result();
// Likewise, it can't be a for-range declaration any more.
if (State.markNotForRangeDecl())
return State.result();
// A parenthesized initializer could be part of an expression or a
// simple-declaration.
if (Tok.is(tok::l_paren)) {
ConsumeParen();
SkipUntil(tok::r_paren, StopAtSemi);
}
if (!TryConsumeToken(tok::comma))
break;
}
// We reached the end. If it can now be some kind of decl, then it is.
if (State.CanBeCondition && Tok.is(tok::r_paren))
return ConditionOrInitStatement::ConditionDecl;
else if (State.CanBeInitStatement && Tok.is(tok::semi))
return ConditionOrInitStatement::InitStmtDecl;
else
return ConditionOrInitStatement::Expression;
}
/// Determine whether the next set of tokens contains a type-id.
///
/// The context parameter states what context we're parsing right
/// now, which affects how this routine copes with the token
/// following the type-id. If the context is TypeIdInParens, we have
/// already parsed the '(' and we will cease lookahead when we hit
/// the corresponding ')'. If the context is
/// TypeIdAsTemplateArgument, we've already parsed the '<' or ','
/// before this template argument, and will cease lookahead when we
/// hit a '>', '>>' (in C++0x), or ','; or, in C++0x, an ellipsis immediately
/// preceding such. Returns true for a type-id and false for an expression.
/// If during the disambiguation process a parsing error is encountered,
/// the function returns true to let the declaration parsing code handle it.
///
/// type-id:
/// type-specifier-seq abstract-declarator[opt]
///
bool Parser::isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous) {
isAmbiguous = false;
// C++ 8.2p2:
// The ambiguity arising from the similarity between a function-style cast and
// a type-id can occur in different contexts. The ambiguity appears as a
// choice between a function-style cast expression and a declaration of a
// type. The resolution is that any construct that could possibly be a type-id
// in its syntactic context shall be considered a type-id.
TPResult TPR = isCXXDeclarationSpecifier();
if (TPR != TPResult::Ambiguous)
return TPR != TPResult::False; // Returns true for TPResult::True or
// TPResult::Error.
// FIXME: Add statistics about the number of ambiguous statements encountered
// and how they were resolved (number of declarations+number of expressions).
// Ok, we have a simple-type-specifier/typename-specifier followed by a '('.
// We need tentative parsing...
RevertingTentativeParsingAction PA(*this);
// type-specifier-seq
TryConsumeDeclarationSpecifier();
assert(Tok.is(tok::l_paren) && "Expected '('");
// declarator
TPR = TryParseDeclarator(true/*mayBeAbstract*/, false/*mayHaveIdentifier*/);
// In case of an error, let the declaration parsing code handle it.
if (TPR == TPResult::Error)
TPR = TPResult::True;
if (TPR == TPResult::Ambiguous) {
// We are supposed to be inside parens, so if after the abstract declarator
// we encounter a ')' this is a type-id, otherwise it's an expression.
if (Context == TypeIdInParens && Tok.is(tok::r_paren)) {
TPR = TPResult::True;
isAmbiguous = true;
// We are supposed to be inside a template argument, so if after
// the abstract declarator we encounter a '>', '>>' (in C++0x), or
// ','; or, in C++0x, an ellipsis immediately preceding such, this
// is a type-id. Otherwise, it's an expression.
} else if (Context == TypeIdAsTemplateArgument &&
(Tok.isOneOf(tok::greater, tok::comma) ||
(getLangOpts().CPlusPlus11 &&
(Tok.is(tok::greatergreater) ||
(Tok.is(tok::ellipsis) &&
NextToken().isOneOf(tok::greater, tok::greatergreater,
tok::comma)))))) {
TPR = TPResult::True;
isAmbiguous = true;
} else
TPR = TPResult::False;
}
assert(TPR == TPResult::True || TPR == TPResult::False);
return TPR == TPResult::True;
}
/// Returns true if this is a C++11 attribute-specifier. Per
/// C++11 [dcl.attr.grammar]p6, two consecutive left square bracket tokens
/// always introduce an attribute. In Objective-C++11, this rule does not
/// apply if either '[' begins a message-send.
///
/// If Disambiguate is true, we try harder to determine whether a '[[' starts
/// an attribute-specifier, and return CAK_InvalidAttributeSpecifier if not.
///
/// If OuterMightBeMessageSend is true, we assume the outer '[' is either an
/// Obj-C message send or the start of an attribute. Otherwise, we assume it
/// is not an Obj-C message send.
///
/// C++11 [dcl.attr.grammar]:
///
/// attribute-specifier:
/// '[' '[' attribute-list ']' ']'
/// alignment-specifier
///
/// attribute-list:
/// attribute[opt]
/// attribute-list ',' attribute[opt]
/// attribute '...'
/// attribute-list ',' attribute '...'
///
/// attribute:
/// attribute-token attribute-argument-clause[opt]
///
/// attribute-token:
/// identifier
/// identifier '::' identifier
///
/// attribute-argument-clause:
/// '(' balanced-token-seq ')'
Parser::CXX11AttributeKind
Parser::isCXX11AttributeSpecifier(bool Disambiguate,
bool OuterMightBeMessageSend) {
if (Tok.is(tok::kw_alignas))
return CAK_AttributeSpecifier;
if (Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square))
return CAK_NotAttributeSpecifier;
// No tentative parsing if we don't need to look for ']]' or a lambda.
if (!Disambiguate && !getLangOpts().ObjC)
return CAK_AttributeSpecifier;
RevertingTentativeParsingAction PA(*this);
// Opening brackets were checked for above.
ConsumeBracket();
// Outside Obj-C++11, treat anything with a matching ']]' as an attribute.
if (!getLangOpts().ObjC) {
ConsumeBracket();
bool IsAttribute = SkipUntil(tok::r_square);
IsAttribute &= Tok.is(tok::r_square);
return IsAttribute ? CAK_AttributeSpecifier : CAK_InvalidAttributeSpecifier;
}
// In Obj-C++11, we need to distinguish four situations:
// 1a) int x[[attr]]; C++11 attribute.
// 1b) [[attr]]; C++11 statement attribute.
// 2) int x[[obj](){ return 1; }()]; Lambda in array size/index.
// 3a) int x[[obj get]]; Message send in array size/index.
// 3b) [[Class alloc] init]; Message send in message send.
// 4) [[obj]{ return self; }() doStuff]; Lambda in message send.
// (1) is an attribute, (2) is ill-formed, and (3) and (4) are accepted.
// If we have a lambda-introducer, then this is definitely not a message send.
// FIXME: If this disambiguation is too slow, fold the tentative lambda parse
// into the tentative attribute parse below.
LambdaIntroducer Intro;
if (!TryParseLambdaIntroducer(Intro)) {
// A lambda cannot end with ']]', and an attribute must.
bool IsAttribute = Tok.is(tok::r_square);
if (IsAttribute)
// Case 1: C++11 attribute.
return CAK_AttributeSpecifier;
if (OuterMightBeMessageSend)
// Case 4: Lambda in message send.
return CAK_NotAttributeSpecifier;
// Case 2: Lambda in array size / index.
return CAK_InvalidAttributeSpecifier;
}
ConsumeBracket();
// If we don't have a lambda-introducer, then we have an attribute or a
// message-send.
bool IsAttribute = true;
while (Tok.isNot(tok::r_square)) {
if (Tok.is(tok::comma)) {
// Case 1: Stray commas can only occur in attributes.
return CAK_AttributeSpecifier;
}
// Parse the attribute-token, if present.
// C++11 [dcl.attr.grammar]:
// If a keyword or an alternative token that satisfies the syntactic
// requirements of an identifier is contained in an attribute-token,
// it is considered an identifier.
SourceLocation Loc;
if (!TryParseCXX11AttributeIdentifier(Loc)) {
IsAttribute = false;
break;
}
if (Tok.is(tok::coloncolon)) {
ConsumeToken();
if (!TryParseCXX11AttributeIdentifier(Loc)) {
IsAttribute = false;
break;
}
}
// Parse the attribute-argument-clause, if present.
if (Tok.is(tok::l_paren)) {
ConsumeParen();
if (!SkipUntil(tok::r_paren)) {
IsAttribute = false;
break;
}
}
TryConsumeToken(tok::ellipsis);
if (!TryConsumeToken(tok::comma))
break;
}
// An attribute must end ']]'.
if (IsAttribute) {
if (Tok.is(tok::r_square)) {
ConsumeBracket();
IsAttribute = Tok.is(tok::r_square);
} else {
IsAttribute = false;
}
}
if (IsAttribute)
// Case 1: C++11 statement attribute.
return CAK_AttributeSpecifier;
// Case 3: Message send.
return CAK_NotAttributeSpecifier;
}
Parser::TPResult Parser::TryParsePtrOperatorSeq() {
while (true) {
if (Tok.isOneOf(tok::coloncolon, tok::identifier))
if (TryAnnotateCXXScopeToken(true))
return TPResult::Error;
if (Tok.isOneOf(tok::star, tok::amp, tok::caret, tok::ampamp) ||
(Tok.is(tok::annot_cxxscope) && NextToken().is(tok::star))) {
// ptr-operator
ConsumeAnyToken();
while (Tok.isOneOf(tok::kw_const, tok::kw_volatile, tok::kw_restrict,
tok::kw__Nonnull, tok::kw__Nullable,
tok::kw__Null_unspecified))
ConsumeToken();
} else {
return TPResult::True;
}
}
}
/// operator-function-id:
/// 'operator' operator
///
/// operator: one of
/// new delete new[] delete[] + - * / % ^ [...]
///
/// conversion-function-id:
/// 'operator' conversion-type-id
///
/// conversion-type-id:
/// type-specifier-seq conversion-declarator[opt]
///
/// conversion-declarator:
/// ptr-operator conversion-declarator[opt]
///
/// literal-operator-id:
/// 'operator' string-literal identifier
/// 'operator' user-defined-string-literal
Parser::TPResult Parser::TryParseOperatorId() {
assert(Tok.is(tok::kw_operator));
ConsumeToken();
// Maybe this is an operator-function-id.
switch (Tok.getKind()) {
case tok::kw_new: case tok::kw_delete:
ConsumeToken();
if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
ConsumeBracket();
ConsumeBracket();
}
return TPResult::True;
#define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemOnly) \
case tok::Token:
#define OVERLOADED_OPERATOR_MULTI(Name, Spelling, Unary, Binary, MemOnly)
#include "clang/Basic/OperatorKinds.def"
ConsumeToken();
return TPResult::True;
case tok::l_square:
if (NextToken().is(tok::r_square)) {
ConsumeBracket();
ConsumeBracket();
return TPResult::True;
}
break;
case tok::l_paren:
if (NextToken().is(tok::r_paren)) {
ConsumeParen();
ConsumeParen();
return TPResult::True;
}
break;
default:
break;
}
// Maybe this is a literal-operator-id.
if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
bool FoundUDSuffix = false;
do {
FoundUDSuffix |= Tok.hasUDSuffix();
ConsumeStringToken();
} while (isTokenStringLiteral());
if (!FoundUDSuffix) {
if (Tok.is(tok::identifier))
ConsumeToken();
else
return TPResult::Error;
}
return TPResult::True;
}
// Maybe this is a conversion-function-id.
bool AnyDeclSpecifiers = false;
while (true) {
TPResult TPR = isCXXDeclarationSpecifier();
if (TPR == TPResult::Error)
return TPR;
if (TPR == TPResult::False) {
if (!AnyDeclSpecifiers)
return TPResult::Error;
break;
}
if (TryConsumeDeclarationSpecifier() == TPResult::Error)
return TPResult::Error;
AnyDeclSpecifiers = true;
}
return TryParsePtrOperatorSeq();
}
/// declarator:
/// direct-declarator
/// ptr-operator declarator
///
/// direct-declarator:
/// declarator-id
/// direct-declarator '(' parameter-declaration-clause ')'
/// cv-qualifier-seq[opt] exception-specification[opt]
/// direct-declarator '[' constant-expression[opt] ']'
/// '(' declarator ')'
/// [GNU] '(' attributes declarator ')'
///
/// abstract-declarator:
/// ptr-operator abstract-declarator[opt]
/// direct-abstract-declarator
///
/// direct-abstract-declarator:
/// direct-abstract-declarator[opt]
/// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
/// exception-specification[opt]
/// direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
/// '(' abstract-declarator ')'
/// [C++0x] ...
///
/// ptr-operator:
/// '*' cv-qualifier-seq[opt]
/// '&'
/// [C++0x] '&&' [TODO]
/// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
///
/// cv-qualifier-seq:
/// cv-qualifier cv-qualifier-seq[opt]
///
/// cv-qualifier:
/// 'const'
/// 'volatile'
///
/// declarator-id:
/// '...'[opt] id-expression
///
/// id-expression:
/// unqualified-id
/// qualified-id [TODO]
///
/// unqualified-id:
/// identifier
/// operator-function-id
/// conversion-function-id
/// literal-operator-id
/// '~' class-name [TODO]
/// '~' decltype-specifier [TODO]
/// template-id [TODO]
///
Parser::TPResult Parser::TryParseDeclarator(bool mayBeAbstract,
bool mayHaveIdentifier,
bool mayHaveDirectInit) {
// declarator:
// direct-declarator
// ptr-operator declarator
if (TryParsePtrOperatorSeq() == TPResult::Error)
return TPResult::Error;
// direct-declarator:
// direct-abstract-declarator:
if (Tok.is(tok::ellipsis))
ConsumeToken();
if ((Tok.isOneOf(tok::identifier, tok::kw_operator) ||
(Tok.is(tok::annot_cxxscope) && (NextToken().is(tok::identifier) ||
NextToken().is(tok::kw_operator)))) &&
mayHaveIdentifier) {
// declarator-id
if (Tok.is(tok::annot_cxxscope))
ConsumeAnnotationToken();
else if (Tok.is(tok::identifier))
TentativelyDeclaredIdentifiers.push_back(Tok.getIdentifierInfo());
if (Tok.is(tok::kw_operator)) {
if (TryParseOperatorId() == TPResult::Error)
return TPResult::Error;
} else
ConsumeToken();
} else if (Tok.is(tok::l_paren)) {
ConsumeParen();
if (mayBeAbstract &&
(Tok.is(tok::r_paren) || // 'int()' is a function.
// 'int(...)' is a function.
(Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren)) ||
isDeclarationSpecifier())) { // 'int(int)' is a function.
// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
// exception-specification[opt]
TPResult TPR = TryParseFunctionDeclarator();
if (TPR != TPResult::Ambiguous)
return TPR;
} else {
// '(' declarator ')'
// '(' attributes declarator ')'
// '(' abstract-declarator ')'
if (Tok.isOneOf(tok::kw___attribute, tok::kw___declspec, tok::kw___cdecl,
tok::kw___stdcall, tok::kw___fastcall, tok::kw___thiscall,
tok::kw___regcall, tok::kw___vectorcall))
return TPResult::True; // attributes indicate declaration
TPResult TPR = TryParseDeclarator(mayBeAbstract, mayHaveIdentifier);
if (TPR != TPResult::Ambiguous)
return TPR;
if (Tok.isNot(tok::r_paren))
return TPResult::False;
ConsumeParen();
}
} else if (!mayBeAbstract) {
return TPResult::False;
}
if (mayHaveDirectInit)
return TPResult::Ambiguous;
while (1) {
TPResult TPR(TPResult::Ambiguous);
if (Tok.is(tok::l_paren)) {
// Check whether we have a function declarator or a possible ctor-style
// initializer that follows the declarator. Note that ctor-style
// initializers are not possible in contexts where abstract declarators
// are allowed.
if (!mayBeAbstract && !isCXXFunctionDeclarator())
break;