1 //===--- ParseTentative.cpp - Ambiguity Resolution Parsing ----------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements the tentative parsing portions of the Parser
10 // interfaces, for ambiguity resolution.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Parse/Parser.h"
15 #include "clang/Parse/ParseDiagnostic.h"
16 #include "clang/Sema/ParsedTemplate.h"
17 using namespace clang;
19 /// isCXXDeclarationStatement - C++-specialized function that disambiguates
20 /// between a declaration or an expression statement, when parsing function
21 /// bodies. Returns true for declaration, false for expression.
23 /// declaration-statement:
26 /// block-declaration:
27 /// simple-declaration
29 /// namespace-alias-definition
32 /// [C++0x] static_assert-declaration
35 /// 'asm' '(' string-literal ')' ';'
37 /// namespace-alias-definition:
38 /// 'namespace' identifier = qualified-namespace-specifier ';'
40 /// using-declaration:
41 /// 'using' typename[opt] '::'[opt] nested-name-specifier
42 /// unqualified-id ';'
43 /// 'using' '::' unqualified-id ;
46 /// 'using' 'namespace' '::'[opt] nested-name-specifier[opt]
47 /// namespace-name ';'
49 bool Parser::isCXXDeclarationStatement() {
50 switch (Tok.getKind()) {
53 // namespace-alias-definition
54 case tok::kw_namespace:
58 // static_assert-declaration
59 case tok::kw_static_assert:
60 case tok::kw__Static_assert:
64 return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
68 /// isCXXSimpleDeclaration - C++-specialized function that disambiguates
69 /// between a simple-declaration or an expression-statement.
70 /// If during the disambiguation process a parsing error is encountered,
71 /// the function returns true to let the declaration parsing code handle it.
72 /// Returns false if the statement is disambiguated as expression.
74 /// simple-declaration:
75 /// decl-specifier-seq init-declarator-list[opt] ';'
76 /// decl-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
77 /// brace-or-equal-initializer ';' [C++17]
79 /// (if AllowForRangeDecl specified)
80 /// for ( for-range-declaration : for-range-initializer ) statement
82 /// for-range-declaration:
83 /// decl-specifier-seq declarator
84 /// decl-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
86 /// In any of the above cases there can be a preceding attribute-specifier-seq,
87 /// but the caller is expected to handle that.
88 bool Parser::isCXXSimpleDeclaration(bool AllowForRangeDecl) {
90 // There is an ambiguity in the grammar involving expression-statements and
91 // declarations: An expression-statement with a function-style explicit type
92 // conversion (5.2.3) as its leftmost subexpression can be indistinguishable
93 // from a declaration where the first declarator starts with a '('. In those
94 // cases the statement is a declaration. [Note: To disambiguate, the whole
95 // statement might have to be examined to determine if it is an
96 // expression-statement or a declaration].
99 // The disambiguation is purely syntactic; that is, the meaning of the names
100 // occurring in such a statement, beyond whether they are type-names or not,
101 // is not generally used in or changed by the disambiguation. Class
102 // templates are instantiated as necessary to determine if a qualified name
103 // is a type-name. Disambiguation precedes parsing, and a statement
104 // disambiguated as a declaration may be an ill-formed declaration.
106 // We don't have to parse all of the decl-specifier-seq part. There's only
107 // an ambiguity if the first decl-specifier is
108 // simple-type-specifier/typename-specifier followed by a '(', which may
109 // indicate a function-style cast expression.
110 // isCXXDeclarationSpecifier will return TPResult::Ambiguous only in such
113 bool InvalidAsDeclaration = false;
114 TPResult TPR = isCXXDeclarationSpecifier(TPResult::False,
115 &InvalidAsDeclaration);
116 if (TPR != TPResult::Ambiguous)
117 return TPR != TPResult::False; // Returns true for TPResult::True or
120 // FIXME: TryParseSimpleDeclaration doesn't look past the first initializer,
121 // and so gets some cases wrong. We can't carry on if we've already seen
122 // something which makes this statement invalid as a declaration in this case,
123 // since it can cause us to misparse valid code. Revisit this once
124 // TryParseInitDeclaratorList is fixed.
125 if (InvalidAsDeclaration)
128 // FIXME: Add statistics about the number of ambiguous statements encountered
129 // and how they were resolved (number of declarations+number of expressions).
131 // Ok, we have a simple-type-specifier/typename-specifier followed by a '(',
132 // or an identifier which doesn't resolve as anything. We need tentative
136 RevertingTentativeParsingAction PA(*this);
137 TPR = TryParseSimpleDeclaration(AllowForRangeDecl);
140 // In case of an error, let the declaration parsing code handle it.
141 if (TPR == TPResult::Error)
144 // Declarations take precedence over expressions.
145 if (TPR == TPResult::Ambiguous)
146 TPR = TPResult::True;
148 assert(TPR == TPResult::True || TPR == TPResult::False);
149 return TPR == TPResult::True;
152 /// Try to consume a token sequence that we've already identified as
153 /// (potentially) starting a decl-specifier.
154 Parser::TPResult Parser::TryConsumeDeclarationSpecifier() {
155 switch (Tok.getKind()) {
156 case tok::kw__Atomic:
157 if (NextToken().isNot(tok::l_paren)) {
163 case tok::kw___attribute:
164 case tok::kw___underlying_type: {
166 if (Tok.isNot(tok::l_paren))
167 return TPResult::Error;
169 if (!SkipUntil(tok::r_paren))
170 return TPResult::Error;
177 case tok::kw___interface:
179 // elaborated-type-specifier:
180 // class-key attribute-specifier-seq[opt]
181 // nested-name-specifier[opt] identifier
182 // class-key nested-name-specifier[opt] template[opt] simple-template-id
183 // enum nested-name-specifier[opt] identifier
185 // FIXME: We don't support class-specifiers nor enum-specifiers here.
189 while (Tok.isOneOf(tok::l_square, tok::kw___attribute, tok::kw___declspec,
191 if (Tok.is(tok::l_square)) {
193 if (!SkipUntil(tok::r_square))
194 return TPResult::Error;
197 if (Tok.isNot(tok::l_paren))
198 return TPResult::Error;
200 if (!SkipUntil(tok::r_paren))
201 return TPResult::Error;
205 if (Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
206 tok::annot_template_id) &&
207 TryAnnotateCXXScopeToken())
208 return TPResult::Error;
209 if (Tok.is(tok::annot_cxxscope))
210 ConsumeAnnotationToken();
211 if (Tok.is(tok::identifier))
213 else if (Tok.is(tok::annot_template_id))
214 ConsumeAnnotationToken();
216 return TPResult::Error;
219 case tok::annot_cxxscope:
220 ConsumeAnnotationToken();
225 if (getLangOpts().ObjC && Tok.is(tok::less))
226 return TryParseProtocolQualifiers();
230 return TPResult::Ambiguous;
233 /// simple-declaration:
234 /// decl-specifier-seq init-declarator-list[opt] ';'
236 /// (if AllowForRangeDecl specified)
237 /// for ( for-range-declaration : for-range-initializer ) statement
238 /// for-range-declaration:
239 /// attribute-specifier-seqopt type-specifier-seq declarator
241 Parser::TPResult Parser::TryParseSimpleDeclaration(bool AllowForRangeDecl) {
242 if (TryConsumeDeclarationSpecifier() == TPResult::Error)
243 return TPResult::Error;
245 // Two decl-specifiers in a row conclusively disambiguate this as being a
246 // simple-declaration. Don't bother calling isCXXDeclarationSpecifier in the
247 // overwhelmingly common case that the next token is a '('.
248 if (Tok.isNot(tok::l_paren)) {
249 TPResult TPR = isCXXDeclarationSpecifier();
250 if (TPR == TPResult::Ambiguous)
251 return TPResult::True;
252 if (TPR == TPResult::True || TPR == TPResult::Error)
254 assert(TPR == TPResult::False);
257 TPResult TPR = TryParseInitDeclaratorList();
258 if (TPR != TPResult::Ambiguous)
261 if (Tok.isNot(tok::semi) && (!AllowForRangeDecl || Tok.isNot(tok::colon)))
262 return TPResult::False;
264 return TPResult::Ambiguous;
267 /// Tentatively parse an init-declarator-list in order to disambiguate it from
270 /// init-declarator-list:
272 /// init-declarator-list ',' init-declarator
275 /// declarator initializer[opt]
276 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] initializer[opt]
279 /// brace-or-equal-initializer
280 /// '(' expression-list ')'
282 /// brace-or-equal-initializer:
283 /// '=' initializer-clause
284 /// [C++11] braced-init-list
286 /// initializer-clause:
287 /// assignment-expression
290 /// braced-init-list:
291 /// '{' initializer-list ','[opt] '}'
294 Parser::TPResult Parser::TryParseInitDeclaratorList() {
297 TPResult TPR = TryParseDeclarator(false/*mayBeAbstract*/);
298 if (TPR != TPResult::Ambiguous)
301 // [GNU] simple-asm-expr[opt] attributes[opt]
302 if (Tok.isOneOf(tok::kw_asm, tok::kw___attribute))
303 return TPResult::True;
306 if (Tok.is(tok::l_paren)) {
307 // Parse through the parens.
309 if (!SkipUntil(tok::r_paren, StopAtSemi))
310 return TPResult::Error;
311 } else if (Tok.is(tok::l_brace)) {
312 // A left-brace here is sufficient to disambiguate the parse; an
313 // expression can never be followed directly by a braced-init-list.
314 return TPResult::True;
315 } else if (Tok.is(tok::equal) || isTokIdentifier_in()) {
316 // MSVC and g++ won't examine the rest of declarators if '=' is
317 // encountered; they just conclude that we have a declaration.
318 // EDG parses the initializer completely, which is the proper behavior
321 // At present, Clang follows MSVC and g++, since the parser does not have
322 // the ability to parse an expression fully without recording the
323 // results of that parse.
324 // FIXME: Handle this case correctly.
326 // Also allow 'in' after an Objective-C declaration as in:
327 // for (int (^b)(void) in array). Ideally this should be done in the
328 // context of parsing for-init-statement of a foreach statement only. But,
329 // in any other context 'in' is invalid after a declaration and parser
330 // issues the error regardless of outcome of this decision.
331 // FIXME: Change if above assumption does not hold.
332 return TPResult::True;
335 if (!TryConsumeToken(tok::comma))
339 return TPResult::Ambiguous;
342 struct Parser::ConditionDeclarationOrInitStatementState {
344 bool CanBeExpression = true;
345 bool CanBeCondition = true;
346 bool CanBeInitStatement;
347 bool CanBeForRangeDecl;
349 ConditionDeclarationOrInitStatementState(Parser &P, bool CanBeInitStatement,
350 bool CanBeForRangeDecl)
351 : P(P), CanBeInitStatement(CanBeInitStatement),
352 CanBeForRangeDecl(CanBeForRangeDecl) {}
355 return CanBeExpression + CanBeCondition + CanBeInitStatement +
356 CanBeForRangeDecl < 2;
359 void markNotExpression() {
360 CanBeExpression = false;
363 // FIXME: Unify the parsing codepaths for condition variables and
364 // simple-declarations so that we don't need to eagerly figure out which
365 // kind we have here. (Just parse init-declarators until we reach a
366 // semicolon or right paren.)
367 RevertingTentativeParsingAction PA(P);
368 if (CanBeForRangeDecl) {
369 // Skip until we hit a ')', ';', or a ':' with no matching '?'.
370 // The final case is a for range declaration, the rest are not.
372 unsigned QuestionColonDepth = 0;
373 P.SkipUntil({tok::r_paren, tok::semi, tok::question, tok::colon},
375 if (P.Tok.is(tok::question))
376 ++QuestionColonDepth;
377 else if (P.Tok.is(tok::colon)) {
378 if (QuestionColonDepth)
379 --QuestionColonDepth;
381 CanBeCondition = CanBeInitStatement = false;
385 CanBeForRangeDecl = false;
391 // Just skip until we hit a ')' or ';'.
392 P.SkipUntil(tok::r_paren, tok::semi, StopBeforeMatch);
394 if (P.Tok.isNot(tok::r_paren))
395 CanBeCondition = CanBeForRangeDecl = false;
396 if (P.Tok.isNot(tok::semi))
397 CanBeInitStatement = false;
401 bool markNotCondition() {
402 CanBeCondition = false;
406 bool markNotForRangeDecl() {
407 CanBeForRangeDecl = false;
411 bool update(TPResult IsDecl) {
415 assert(resolved() && "can't continue after tentative parsing bails out");
417 case TPResult::False:
418 CanBeCondition = CanBeInitStatement = CanBeForRangeDecl = false;
420 case TPResult::Ambiguous:
422 case TPResult::Error:
423 CanBeExpression = CanBeCondition = CanBeInitStatement =
424 CanBeForRangeDecl = false;
430 ConditionOrInitStatement result() const {
431 assert(CanBeExpression + CanBeCondition + CanBeInitStatement +
432 CanBeForRangeDecl < 2 &&
433 "result called but not yet resolved");
435 return ConditionOrInitStatement::Expression;
437 return ConditionOrInitStatement::ConditionDecl;
438 if (CanBeInitStatement)
439 return ConditionOrInitStatement::InitStmtDecl;
440 if (CanBeForRangeDecl)
441 return ConditionOrInitStatement::ForRangeDecl;
442 return ConditionOrInitStatement::Error;
446 /// Disambiguates between a declaration in a condition, a
447 /// simple-declaration in an init-statement, and an expression for
448 /// a condition of a if/switch statement.
452 /// type-specifier-seq declarator '=' assignment-expression
453 /// [C++11] type-specifier-seq declarator '=' initializer-clause
454 /// [C++11] type-specifier-seq declarator braced-init-list
455 /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
456 /// '=' assignment-expression
457 /// simple-declaration:
458 /// decl-specifier-seq init-declarator-list[opt] ';'
460 /// Note that, unlike isCXXSimpleDeclaration, we must disambiguate all the way
461 /// to the ';' to disambiguate cases like 'int(x))' (an expression) from
462 /// 'int(x);' (a simple-declaration in an init-statement).
463 Parser::ConditionOrInitStatement
464 Parser::isCXXConditionDeclarationOrInitStatement(bool CanBeInitStatement,
465 bool CanBeForRangeDecl) {
466 ConditionDeclarationOrInitStatementState State(*this, CanBeInitStatement,
469 if (State.update(isCXXDeclarationSpecifier()))
470 return State.result();
472 // It might be a declaration; we need tentative parsing.
473 RevertingTentativeParsingAction PA(*this);
475 // FIXME: A tag definition unambiguously tells us this is an init-statement.
476 if (State.update(TryConsumeDeclarationSpecifier()))
477 return State.result();
478 assert(Tok.is(tok::l_paren) && "Expected '('");
481 // Consume a declarator.
482 if (State.update(TryParseDeclarator(false/*mayBeAbstract*/)))
483 return State.result();
485 // Attributes, asm label, or an initializer imply this is not an expression.
486 // FIXME: Disambiguate properly after an = instead of assuming that it's a
487 // valid declaration.
488 if (Tok.isOneOf(tok::equal, tok::kw_asm, tok::kw___attribute) ||
489 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace))) {
490 State.markNotExpression();
491 return State.result();
494 // A colon here identifies a for-range declaration.
495 if (State.CanBeForRangeDecl && Tok.is(tok::colon))
496 return ConditionOrInitStatement::ForRangeDecl;
498 // At this point, it can't be a condition any more, because a condition
499 // must have a brace-or-equal-initializer.
500 if (State.markNotCondition())
501 return State.result();
503 // Likewise, it can't be a for-range declaration any more.
504 if (State.markNotForRangeDecl())
505 return State.result();
507 // A parenthesized initializer could be part of an expression or a
508 // simple-declaration.
509 if (Tok.is(tok::l_paren)) {
511 SkipUntil(tok::r_paren, StopAtSemi);
514 if (!TryConsumeToken(tok::comma))
518 // We reached the end. If it can now be some kind of decl, then it is.
519 if (State.CanBeCondition && Tok.is(tok::r_paren))
520 return ConditionOrInitStatement::ConditionDecl;
521 else if (State.CanBeInitStatement && Tok.is(tok::semi))
522 return ConditionOrInitStatement::InitStmtDecl;
524 return ConditionOrInitStatement::Expression;
527 /// Determine whether the next set of tokens contains a type-id.
529 /// The context parameter states what context we're parsing right
530 /// now, which affects how this routine copes with the token
531 /// following the type-id. If the context is TypeIdInParens, we have
532 /// already parsed the '(' and we will cease lookahead when we hit
533 /// the corresponding ')'. If the context is
534 /// TypeIdAsTemplateArgument, we've already parsed the '<' or ','
535 /// before this template argument, and will cease lookahead when we
536 /// hit a '>', '>>' (in C++0x), or ','; or, in C++0x, an ellipsis immediately
537 /// preceding such. Returns true for a type-id and false for an expression.
538 /// If during the disambiguation process a parsing error is encountered,
539 /// the function returns true to let the declaration parsing code handle it.
542 /// type-specifier-seq abstract-declarator[opt]
544 bool Parser::isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous) {
549 // The ambiguity arising from the similarity between a function-style cast and
550 // a type-id can occur in different contexts. The ambiguity appears as a
551 // choice between a function-style cast expression and a declaration of a
552 // type. The resolution is that any construct that could possibly be a type-id
553 // in its syntactic context shall be considered a type-id.
555 TPResult TPR = isCXXDeclarationSpecifier();
556 if (TPR != TPResult::Ambiguous)
557 return TPR != TPResult::False; // Returns true for TPResult::True or
560 // FIXME: Add statistics about the number of ambiguous statements encountered
561 // and how they were resolved (number of declarations+number of expressions).
563 // Ok, we have a simple-type-specifier/typename-specifier followed by a '('.
564 // We need tentative parsing...
566 RevertingTentativeParsingAction PA(*this);
568 // type-specifier-seq
569 TryConsumeDeclarationSpecifier();
570 assert(Tok.is(tok::l_paren) && "Expected '('");
573 TPR = TryParseDeclarator(true/*mayBeAbstract*/, false/*mayHaveIdentifier*/);
575 // In case of an error, let the declaration parsing code handle it.
576 if (TPR == TPResult::Error)
577 TPR = TPResult::True;
579 if (TPR == TPResult::Ambiguous) {
580 // We are supposed to be inside parens, so if after the abstract declarator
581 // we encounter a ')' this is a type-id, otherwise it's an expression.
582 if (Context == TypeIdInParens && Tok.is(tok::r_paren)) {
583 TPR = TPResult::True;
586 // We are supposed to be inside a template argument, so if after
587 // the abstract declarator we encounter a '>', '>>' (in C++0x), or
588 // ','; or, in C++0x, an ellipsis immediately preceding such, this
589 // is a type-id. Otherwise, it's an expression.
590 } else if (Context == TypeIdAsTemplateArgument &&
591 (Tok.isOneOf(tok::greater, tok::comma) ||
592 (getLangOpts().CPlusPlus11 &&
593 (Tok.isOneOf(tok::greatergreater,
594 tok::greatergreatergreater) ||
595 (Tok.is(tok::ellipsis) &&
596 NextToken().isOneOf(tok::greater, tok::greatergreater,
597 tok::greatergreatergreater,
599 TPR = TPResult::True;
603 TPR = TPResult::False;
606 assert(TPR == TPResult::True || TPR == TPResult::False);
607 return TPR == TPResult::True;
610 /// Returns true if this is a C++11 attribute-specifier. Per
611 /// C++11 [dcl.attr.grammar]p6, two consecutive left square bracket tokens
612 /// always introduce an attribute. In Objective-C++11, this rule does not
613 /// apply if either '[' begins a message-send.
615 /// If Disambiguate is true, we try harder to determine whether a '[[' starts
616 /// an attribute-specifier, and return CAK_InvalidAttributeSpecifier if not.
618 /// If OuterMightBeMessageSend is true, we assume the outer '[' is either an
619 /// Obj-C message send or the start of an attribute. Otherwise, we assume it
620 /// is not an Obj-C message send.
622 /// C++11 [dcl.attr.grammar]:
624 /// attribute-specifier:
625 /// '[' '[' attribute-list ']' ']'
626 /// alignment-specifier
630 /// attribute-list ',' attribute[opt]
632 /// attribute-list ',' attribute '...'
635 /// attribute-token attribute-argument-clause[opt]
639 /// identifier '::' identifier
641 /// attribute-argument-clause:
642 /// '(' balanced-token-seq ')'
643 Parser::CXX11AttributeKind
644 Parser::isCXX11AttributeSpecifier(bool Disambiguate,
645 bool OuterMightBeMessageSend) {
646 if (Tok.is(tok::kw_alignas))
647 return CAK_AttributeSpecifier;
649 if (Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square))
650 return CAK_NotAttributeSpecifier;
652 // No tentative parsing if we don't need to look for ']]' or a lambda.
653 if (!Disambiguate && !getLangOpts().ObjC)
654 return CAK_AttributeSpecifier;
656 // '[[using ns: ...]]' is an attribute.
657 if (GetLookAheadToken(2).is(tok::kw_using))
658 return CAK_AttributeSpecifier;
660 RevertingTentativeParsingAction PA(*this);
662 // Opening brackets were checked for above.
665 if (!getLangOpts().ObjC) {
668 bool IsAttribute = SkipUntil(tok::r_square);
669 IsAttribute &= Tok.is(tok::r_square);
671 return IsAttribute ? CAK_AttributeSpecifier : CAK_InvalidAttributeSpecifier;
674 // In Obj-C++11, we need to distinguish four situations:
675 // 1a) int x[[attr]]; C++11 attribute.
676 // 1b) [[attr]]; C++11 statement attribute.
677 // 2) int x[[obj](){ return 1; }()]; Lambda in array size/index.
678 // 3a) int x[[obj get]]; Message send in array size/index.
679 // 3b) [[Class alloc] init]; Message send in message send.
680 // 4) [[obj]{ return self; }() doStuff]; Lambda in message send.
681 // (1) is an attribute, (2) is ill-formed, and (3) and (4) are accepted.
683 // Check to see if this is a lambda-expression.
684 // FIXME: If this disambiguation is too slow, fold the tentative lambda parse
685 // into the tentative attribute parse below.
687 RevertingTentativeParsingAction LambdaTPA(*this);
688 LambdaIntroducer Intro;
689 LambdaIntroducerTentativeParse Tentative;
690 if (ParseLambdaIntroducer(Intro, &Tentative)) {
691 // We hit a hard error after deciding this was not an attribute.
692 // FIXME: Don't parse and annotate expressions when disambiguating
693 // against an attribute.
694 return CAK_NotAttributeSpecifier;
698 case LambdaIntroducerTentativeParse::MessageSend:
699 // Case 3: The inner construct is definitely a message send, so the
700 // outer construct is definitely not an attribute.
701 return CAK_NotAttributeSpecifier;
703 case LambdaIntroducerTentativeParse::Success:
704 case LambdaIntroducerTentativeParse::Incomplete:
705 // This is a lambda-introducer or attribute-specifier.
706 if (Tok.is(tok::r_square))
707 // Case 1: C++11 attribute.
708 return CAK_AttributeSpecifier;
710 if (OuterMightBeMessageSend)
711 // Case 4: Lambda in message send.
712 return CAK_NotAttributeSpecifier;
714 // Case 2: Lambda in array size / index.
715 return CAK_InvalidAttributeSpecifier;
717 case LambdaIntroducerTentativeParse::Invalid:
718 // No idea what this is; we couldn't parse it as a lambda-introducer.
719 // Might still be an attribute-specifier or a message send.
726 // If we don't have a lambda-introducer, then we have an attribute or a
728 bool IsAttribute = true;
729 while (Tok.isNot(tok::r_square)) {
730 if (Tok.is(tok::comma)) {
731 // Case 1: Stray commas can only occur in attributes.
732 return CAK_AttributeSpecifier;
735 // Parse the attribute-token, if present.
736 // C++11 [dcl.attr.grammar]:
737 // If a keyword or an alternative token that satisfies the syntactic
738 // requirements of an identifier is contained in an attribute-token,
739 // it is considered an identifier.
741 if (!TryParseCXX11AttributeIdentifier(Loc)) {
745 if (Tok.is(tok::coloncolon)) {
747 if (!TryParseCXX11AttributeIdentifier(Loc)) {
753 // Parse the attribute-argument-clause, if present.
754 if (Tok.is(tok::l_paren)) {
756 if (!SkipUntil(tok::r_paren)) {
762 TryConsumeToken(tok::ellipsis);
764 if (!TryConsumeToken(tok::comma))
768 // An attribute must end ']]'.
770 if (Tok.is(tok::r_square)) {
772 IsAttribute = Tok.is(tok::r_square);
779 // Case 1: C++11 statement attribute.
780 return CAK_AttributeSpecifier;
782 // Case 3: Message send.
783 return CAK_NotAttributeSpecifier;
786 Parser::TPResult Parser::TryParsePtrOperatorSeq() {
788 if (Tok.isOneOf(tok::coloncolon, tok::identifier))
789 if (TryAnnotateCXXScopeToken(true))
790 return TPResult::Error;
792 if (Tok.isOneOf(tok::star, tok::amp, tok::caret, tok::ampamp) ||
793 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::star))) {
796 while (Tok.isOneOf(tok::kw_const, tok::kw_volatile, tok::kw_restrict,
797 tok::kw__Nonnull, tok::kw__Nullable,
798 tok::kw__Null_unspecified))
801 return TPResult::True;
806 /// operator-function-id:
807 /// 'operator' operator
810 /// new delete new[] delete[] + - * / % ^ [...]
812 /// conversion-function-id:
813 /// 'operator' conversion-type-id
815 /// conversion-type-id:
816 /// type-specifier-seq conversion-declarator[opt]
818 /// conversion-declarator:
819 /// ptr-operator conversion-declarator[opt]
821 /// literal-operator-id:
822 /// 'operator' string-literal identifier
823 /// 'operator' user-defined-string-literal
824 Parser::TPResult Parser::TryParseOperatorId() {
825 assert(Tok.is(tok::kw_operator));
828 // Maybe this is an operator-function-id.
829 switch (Tok.getKind()) {
830 case tok::kw_new: case tok::kw_delete:
832 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
836 return TPResult::True;
838 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemOnly) \
840 #define OVERLOADED_OPERATOR_MULTI(Name, Spelling, Unary, Binary, MemOnly)
841 #include "clang/Basic/OperatorKinds.def"
843 return TPResult::True;
846 if (NextToken().is(tok::r_square)) {
849 return TPResult::True;
854 if (NextToken().is(tok::r_paren)) {
857 return TPResult::True;
865 // Maybe this is a literal-operator-id.
866 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
867 bool FoundUDSuffix = false;
869 FoundUDSuffix |= Tok.hasUDSuffix();
870 ConsumeStringToken();
871 } while (isTokenStringLiteral());
873 if (!FoundUDSuffix) {
874 if (Tok.is(tok::identifier))
877 return TPResult::Error;
879 return TPResult::True;
882 // Maybe this is a conversion-function-id.
883 bool AnyDeclSpecifiers = false;
885 TPResult TPR = isCXXDeclarationSpecifier();
886 if (TPR == TPResult::Error)
888 if (TPR == TPResult::False) {
889 if (!AnyDeclSpecifiers)
890 return TPResult::Error;
893 if (TryConsumeDeclarationSpecifier() == TPResult::Error)
894 return TPResult::Error;
895 AnyDeclSpecifiers = true;
897 return TryParsePtrOperatorSeq();
901 /// direct-declarator
902 /// ptr-operator declarator
904 /// direct-declarator:
906 /// direct-declarator '(' parameter-declaration-clause ')'
907 /// cv-qualifier-seq[opt] exception-specification[opt]
908 /// direct-declarator '[' constant-expression[opt] ']'
909 /// '(' declarator ')'
910 /// [GNU] '(' attributes declarator ')'
912 /// abstract-declarator:
913 /// ptr-operator abstract-declarator[opt]
914 /// direct-abstract-declarator
916 /// direct-abstract-declarator:
917 /// direct-abstract-declarator[opt]
918 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
919 /// exception-specification[opt]
920 /// direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
921 /// '(' abstract-declarator ')'
925 /// '*' cv-qualifier-seq[opt]
927 /// [C++0x] '&&' [TODO]
928 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
930 /// cv-qualifier-seq:
931 /// cv-qualifier cv-qualifier-seq[opt]
938 /// '...'[opt] id-expression
942 /// qualified-id [TODO]
946 /// operator-function-id
947 /// conversion-function-id
948 /// literal-operator-id
949 /// '~' class-name [TODO]
950 /// '~' decltype-specifier [TODO]
951 /// template-id [TODO]
953 Parser::TPResult Parser::TryParseDeclarator(bool mayBeAbstract,
954 bool mayHaveIdentifier,
955 bool mayHaveDirectInit) {
958 // ptr-operator declarator
959 if (TryParsePtrOperatorSeq() == TPResult::Error)
960 return TPResult::Error;
962 // direct-declarator:
963 // direct-abstract-declarator:
964 if (Tok.is(tok::ellipsis))
967 if ((Tok.isOneOf(tok::identifier, tok::kw_operator) ||
968 (Tok.is(tok::annot_cxxscope) && (NextToken().is(tok::identifier) ||
969 NextToken().is(tok::kw_operator)))) &&
972 if (Tok.is(tok::annot_cxxscope))
973 ConsumeAnnotationToken();
974 else if (Tok.is(tok::identifier))
975 TentativelyDeclaredIdentifiers.push_back(Tok.getIdentifierInfo());
976 if (Tok.is(tok::kw_operator)) {
977 if (TryParseOperatorId() == TPResult::Error)
978 return TPResult::Error;
981 } else if (Tok.is(tok::l_paren)) {
984 (Tok.is(tok::r_paren) || // 'int()' is a function.
985 // 'int(...)' is a function.
986 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren)) ||
987 isDeclarationSpecifier())) { // 'int(int)' is a function.
988 // '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
989 // exception-specification[opt]
990 TPResult TPR = TryParseFunctionDeclarator();
991 if (TPR != TPResult::Ambiguous)
994 // '(' declarator ')'
995 // '(' attributes declarator ')'
996 // '(' abstract-declarator ')'
997 if (Tok.isOneOf(tok::kw___attribute, tok::kw___declspec, tok::kw___cdecl,
998 tok::kw___stdcall, tok::kw___fastcall, tok::kw___thiscall,
999 tok::kw___regcall, tok::kw___vectorcall))
1000 return TPResult::True; // attributes indicate declaration
1001 TPResult TPR = TryParseDeclarator(mayBeAbstract, mayHaveIdentifier);
1002 if (TPR != TPResult::Ambiguous)
1004 if (Tok.isNot(tok::r_paren))
1005 return TPResult::False;
1008 } else if (!mayBeAbstract) {
1009 return TPResult::False;
1012 if (mayHaveDirectInit)
1013 return TPResult::Ambiguous;
1016 TPResult TPR(TPResult::Ambiguous);
1018 if (Tok.is(tok::l_paren)) {
1019 // Check whether we have a function declarator or a possible ctor-style
1020 // initializer that follows the declarator. Note that ctor-style
1021 // initializers are not possible in contexts where abstract declarators
1023 if (!mayBeAbstract && !isCXXFunctionDeclarator())
1026 // direct-declarator '(' parameter-declaration-clause ')'
1027 // cv-qualifier-seq[opt] exception-specification[opt]
1029 TPR = TryParseFunctionDeclarator();
1030 } else if (Tok.is(tok::l_square)) {
1031 // direct-declarator '[' constant-expression[opt] ']'
1032 // direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
1033 TPR = TryParseBracketDeclarator();
1038 if (TPR != TPResult::Ambiguous)
1042 return TPResult::Ambiguous;
1046 Parser::isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind) {
1048 // Obviously starts an expression.
1049 case tok::numeric_constant:
1050 case tok::char_constant:
1051 case tok::wide_char_constant:
1052 case tok::utf8_char_constant:
1053 case tok::utf16_char_constant:
1054 case tok::utf32_char_constant:
1055 case tok::string_literal:
1056 case tok::wide_string_literal:
1057 case tok::utf8_string_literal:
1058 case tok::utf16_string_literal:
1059 case tok::utf32_string_literal:
1068 case tok::minusminus:
1071 case tok::kw_sizeof:
1072 case tok::kw___func__:
1073 case tok::kw_const_cast:
1074 case tok::kw_delete:
1075 case tok::kw_dynamic_cast:
1078 case tok::kw_operator:
1079 case tok::kw_reinterpret_cast:
1080 case tok::kw_static_cast:
1084 case tok::kw_typeid:
1085 case tok::kw_alignof:
1086 case tok::kw_noexcept:
1087 case tok::kw_nullptr:
1088 case tok::kw__Alignof:
1089 case tok::kw___null:
1090 case tok::kw___alignof:
1091 case tok::kw___builtin_choose_expr:
1092 case tok::kw___builtin_offsetof:
1093 case tok::kw___builtin_va_arg:
1094 case tok::kw___imag:
1095 case tok::kw___real:
1096 case tok::kw___FUNCTION__:
1097 case tok::kw___FUNCDNAME__:
1098 case tok::kw___FUNCSIG__:
1099 case tok::kw_L__FUNCTION__:
1100 case tok::kw_L__FUNCSIG__:
1101 case tok::kw___PRETTY_FUNCTION__:
1102 case tok::kw___uuidof:
1103 #define TYPE_TRAIT(N,Spelling,K) \
1104 case tok::kw_##Spelling:
1105 #include "clang/Basic/TokenKinds.def"
1106 return TPResult::True;
1108 // Obviously starts a type-specifier-seq:
1111 case tok::kw_double:
1112 case tok::kw__Float16:
1113 case tok::kw___float128:
1119 case tok::kw___int64:
1120 case tok::kw___int128:
1121 case tok::kw_restrict:
1123 case tok::kw_signed:
1124 case tok::kw_struct:
1126 case tok::kw_unsigned:
1128 case tok::kw_volatile:
1130 case tok::kw__Complex:
1132 case tok::kw_typename:
1133 case tok::kw_wchar_t:
1134 case tok::kw_char8_t:
1135 case tok::kw_char16_t:
1136 case tok::kw_char32_t:
1137 case tok::kw__Decimal32:
1138 case tok::kw__Decimal64:
1139 case tok::kw__Decimal128:
1140 case tok::kw___interface:
1141 case tok::kw___thread:
1142 case tok::kw_thread_local:
1143 case tok::kw__Thread_local:
1144 case tok::kw_typeof:
1145 case tok::kw___underlying_type:
1146 case tok::kw___cdecl:
1147 case tok::kw___stdcall:
1148 case tok::kw___fastcall:
1149 case tok::kw___thiscall:
1150 case tok::kw___regcall:
1151 case tok::kw___vectorcall:
1152 case tok::kw___unaligned:
1153 case tok::kw___vector:
1154 case tok::kw___pixel:
1155 case tok::kw___bool:
1156 case tok::kw__Atomic:
1157 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
1158 #include "clang/Basic/OpenCLImageTypes.def"
1159 case tok::kw___unknown_anytype:
1160 return TPResult::False;
1166 return TPResult::Ambiguous;
1169 bool Parser::isTentativelyDeclared(IdentifierInfo *II) {
1170 return std::find(TentativelyDeclaredIdentifiers.begin(),
1171 TentativelyDeclaredIdentifiers.end(), II)
1172 != TentativelyDeclaredIdentifiers.end();
1176 class TentativeParseCCC final : public CorrectionCandidateCallback {
1178 TentativeParseCCC(const Token &Next) {
1179 WantRemainingKeywords = false;
1180 WantTypeSpecifiers = Next.isOneOf(tok::l_paren, tok::r_paren, tok::greater,
1181 tok::l_brace, tok::identifier);
1184 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1185 // Reject any candidate that only resolves to instance members since they
1186 // aren't viable as standalone identifiers instead of member references.
1187 if (Candidate.isResolved() && !Candidate.isKeyword() &&
1188 llvm::all_of(Candidate,
1189 [](NamedDecl *ND) { return ND->isCXXInstanceMember(); }))
1192 return CorrectionCandidateCallback::ValidateCandidate(Candidate);
1195 std::unique_ptr<CorrectionCandidateCallback> clone() override {
1196 return std::make_unique<TentativeParseCCC>(*this);
1200 /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a declaration
1201 /// specifier, TPResult::False if it is not, TPResult::Ambiguous if it could
1202 /// be either a decl-specifier or a function-style cast, and TPResult::Error
1203 /// if a parsing error was found and reported.
1205 /// If InvalidAsDeclSpec is not null, some cases that would be ill-formed as
1206 /// declaration specifiers but possibly valid as some other kind of construct
1207 /// return TPResult::Ambiguous instead of TPResult::False. When this happens,
1208 /// the intent is to keep trying to disambiguate, on the basis that we might
1209 /// find a better reason to treat this construct as a declaration later on.
1210 /// When this happens and the name could possibly be valid in some other
1211 /// syntactic context, *InvalidAsDeclSpec is set to 'true'. The current cases
1212 /// that trigger this are:
1214 /// * When parsing X::Y (with no 'typename') where X is dependent
1215 /// * When parsing X<Y> where X is undeclared
1218 /// storage-class-specifier
1220 /// function-specifier
1223 /// [C++11] 'constexpr'
1224 /// [C++20] 'consteval'
1225 /// [GNU] attributes declaration-specifiers[opt]
1227 /// storage-class-specifier:
1233 /// [GNU] '__thread'
1234 /// [C++11] 'thread_local'
1235 /// [C11] '_Thread_local'
1237 /// function-specifier:
1246 /// simple-type-specifier
1249 /// elaborated-type-specifier
1250 /// typename-specifier
1253 /// simple-type-specifier:
1254 /// '::'[opt] nested-name-specifier[opt] type-name
1255 /// '::'[opt] nested-name-specifier 'template'
1256 /// simple-template-id [TODO]
1268 /// [GNU] typeof-specifier
1269 /// [GNU] '_Complex'
1271 /// [GNU] '__auto_type'
1272 /// [C++11] 'decltype' ( expression )
1273 /// [C++1y] 'decltype' ( 'auto' )
1280 /// elaborated-type-specifier:
1281 /// class-key '::'[opt] nested-name-specifier[opt] identifier
1282 /// class-key '::'[opt] nested-name-specifier[opt] 'template'[opt]
1283 /// simple-template-id
1284 /// 'enum' '::'[opt] nested-name-specifier[opt] identifier
1290 /// 'enum' identifier[opt] '{' enumerator-list[opt] '}'
1291 /// 'enum' identifier[opt] '{' enumerator-list ',' '}'
1293 /// class-specifier:
1294 /// class-head '{' member-specification[opt] '}'
1297 /// class-key identifier[opt] base-clause[opt]
1298 /// class-key nested-name-specifier identifier base-clause[opt]
1299 /// class-key nested-name-specifier[opt] simple-template-id
1300 /// base-clause[opt]
1313 Parser::isCXXDeclarationSpecifier(Parser::TPResult BracedCastResult,
1314 bool *InvalidAsDeclSpec) {
1315 switch (Tok.getKind()) {
1316 case tok::identifier: {
1317 // Check for need to substitute AltiVec __vector keyword
1318 // for "vector" identifier.
1319 if (TryAltiVecVectorToken())
1320 return TPResult::True;
1322 const Token &Next = NextToken();
1323 // In 'foo bar', 'foo' is always a type name outside of Objective-C.
1324 if (!getLangOpts().ObjC && Next.is(tok::identifier))
1325 return TPResult::True;
1327 if (Next.isNot(tok::coloncolon) && Next.isNot(tok::less)) {
1328 // Determine whether this is a valid expression. If not, we will hit
1329 // a parse error one way or another. In that case, tell the caller that
1330 // this is ambiguous. Typo-correct to type and expression keywords and
1331 // to types and identifiers, in order to try to recover from errors.
1332 TentativeParseCCC CCC(Next);
1333 switch (TryAnnotateName(&CCC)) {
1335 return TPResult::Error;
1336 case ANK_TentativeDecl:
1337 return TPResult::False;
1338 case ANK_TemplateName:
1339 // In C++17, this could be a type template for class template argument
1340 // deduction. Try to form a type annotation for it. If we're in a
1341 // template template argument, we'll undo this when checking the
1342 // validity of the argument.
1343 if (getLangOpts().CPlusPlus17) {
1344 if (TryAnnotateTypeOrScopeToken())
1345 return TPResult::Error;
1346 if (Tok.isNot(tok::identifier))
1350 // A bare type template-name which can't be a template template
1351 // argument is an error, and was probably intended to be a type.
1352 return GreaterThanIsOperator ? TPResult::True : TPResult::False;
1353 case ANK_Unresolved:
1354 return InvalidAsDeclSpec ? TPResult::Ambiguous : TPResult::False;
1358 assert(Tok.isNot(tok::identifier) &&
1359 "TryAnnotateName succeeded without producing an annotation");
1361 // This might possibly be a type with a dependent scope specifier and
1362 // a missing 'typename' keyword. Don't use TryAnnotateName in this case,
1363 // since it will annotate as a primary expression, and we want to use the
1364 // "missing 'typename'" logic.
1365 if (TryAnnotateTypeOrScopeToken())
1366 return TPResult::Error;
1367 // If annotation failed, assume it's a non-type.
1368 // FIXME: If this happens due to an undeclared identifier, treat it as
1370 if (Tok.is(tok::identifier))
1371 return TPResult::False;
1374 // We annotated this token as something. Recurse to handle whatever we got.
1375 return isCXXDeclarationSpecifier(BracedCastResult, InvalidAsDeclSpec);
1378 case tok::kw_typename: // typename T::type
1379 // Annotate typenames and C++ scope specifiers. If we get one, just
1380 // recurse to handle whatever we get.
1381 if (TryAnnotateTypeOrScopeToken())
1382 return TPResult::Error;
1383 return isCXXDeclarationSpecifier(BracedCastResult, InvalidAsDeclSpec);
1385 case tok::coloncolon: { // ::foo::bar
1386 const Token &Next = NextToken();
1387 if (Next.isOneOf(tok::kw_new, // ::new
1388 tok::kw_delete)) // ::delete
1389 return TPResult::False;
1392 case tok::kw___super:
1393 case tok::kw_decltype:
1394 // Annotate typenames and C++ scope specifiers. If we get one, just
1395 // recurse to handle whatever we get.
1396 if (TryAnnotateTypeOrScopeToken())
1397 return TPResult::Error;
1398 return isCXXDeclarationSpecifier(BracedCastResult, InvalidAsDeclSpec);
1401 // storage-class-specifier
1403 // function-specifier
1407 case tok::kw_friend:
1408 case tok::kw_typedef:
1409 case tok::kw_constexpr:
1410 case tok::kw_consteval:
1411 case tok::kw_constinit:
1412 // storage-class-specifier
1413 case tok::kw_register:
1414 case tok::kw_static:
1415 case tok::kw_extern:
1416 case tok::kw_mutable:
1418 case tok::kw___thread:
1419 case tok::kw_thread_local:
1420 case tok::kw__Thread_local:
1421 // function-specifier
1422 case tok::kw_inline:
1423 case tok::kw_virtual:
1424 case tok::kw_explicit:
1427 case tok::kw___module_private__:
1430 case tok::kw___unknown_anytype:
1433 // simple-type-specifier
1436 // elaborated-type-specifier
1437 // typename-specifier
1441 // elaborated-type-specifier
1443 case tok::kw_struct:
1445 case tok::kw___interface:
1450 case tok::kw_volatile:
1451 return TPResult::True;
1453 // OpenCL address space qualifiers
1454 case tok::kw_private:
1455 if (!getLangOpts().OpenCL)
1456 return TPResult::False;
1458 case tok::kw___private:
1459 case tok::kw___local:
1460 case tok::kw___global:
1461 case tok::kw___constant:
1462 case tok::kw___generic:
1463 // OpenCL access qualifiers
1464 case tok::kw___read_only:
1465 case tok::kw___write_only:
1466 case tok::kw___read_write:
1471 case tok::kw_restrict:
1472 case tok::kw__Complex:
1473 case tok::kw___attribute:
1474 case tok::kw___auto_type:
1475 return TPResult::True;
1478 case tok::kw___declspec:
1479 case tok::kw___cdecl:
1480 case tok::kw___stdcall:
1481 case tok::kw___fastcall:
1482 case tok::kw___thiscall:
1483 case tok::kw___regcall:
1484 case tok::kw___vectorcall:
1486 case tok::kw___sptr:
1487 case tok::kw___uptr:
1488 case tok::kw___ptr64:
1489 case tok::kw___ptr32:
1490 case tok::kw___forceinline:
1491 case tok::kw___unaligned:
1492 case tok::kw__Nonnull:
1493 case tok::kw__Nullable:
1494 case tok::kw__Null_unspecified:
1495 case tok::kw___kindof:
1496 return TPResult::True;
1499 case tok::kw___pascal:
1500 return TPResult::True;
1503 case tok::kw___vector:
1504 return TPResult::True;
1506 case tok::annot_template_id: {
1507 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1508 // If lookup for the template-name found nothing, don't assume we have a
1509 // definitive disambiguation result yet.
1510 if (TemplateId->Kind == TNK_Undeclared_template && InvalidAsDeclSpec) {
1511 // 'template-id(' can be a valid expression but not a valid decl spec if
1512 // the template-name is not declared, but we don't consider this to be a
1513 // definitive disambiguation. In any other context, it's an error either
1515 *InvalidAsDeclSpec = NextToken().is(tok::l_paren);
1516 return TPResult::Ambiguous;
1518 if (TemplateId->Kind != TNK_Type_template)
1519 return TPResult::False;
1521 AnnotateTemplateIdTokenAsType();
1522 assert(Tok.is(tok::annot_typename));
1526 case tok::annot_cxxscope: // foo::bar or ::foo::bar, but already parsed
1527 // We've already annotated a scope; try to annotate a type.
1528 if (TryAnnotateTypeOrScopeToken())
1529 return TPResult::Error;
1530 if (!Tok.is(tok::annot_typename)) {
1531 // If the next token is an identifier or a type qualifier, then this
1532 // can't possibly be a valid expression either.
1533 if (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier)) {
1535 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
1536 Tok.getAnnotationRange(),
1538 if (SS.getScopeRep() && SS.getScopeRep()->isDependent()) {
1539 RevertingTentativeParsingAction PA(*this);
1540 ConsumeAnnotationToken();
1542 bool isIdentifier = Tok.is(tok::identifier);
1543 TPResult TPR = TPResult::False;
1545 TPR = isCXXDeclarationSpecifier(BracedCastResult,
1549 TPR == TPResult::True || TPR == TPResult::Error)
1550 return TPResult::Error;
1552 if (InvalidAsDeclSpec) {
1553 // We can't tell whether this is a missing 'typename' or a valid
1555 *InvalidAsDeclSpec = true;
1556 return TPResult::Ambiguous;
1558 // In MS mode, if InvalidAsDeclSpec is not provided, and the tokens
1559 // are or the form *) or &) *> or &> &&>, this can't be an expression.
1560 // The typename must be missing.
1561 if (getLangOpts().MSVCCompat) {
1562 if (((Tok.is(tok::amp) || Tok.is(tok::star)) &&
1563 (NextToken().is(tok::r_paren) ||
1564 NextToken().is(tok::greater))) ||
1565 (Tok.is(tok::ampamp) && NextToken().is(tok::greater)))
1566 return TPResult::True;
1570 // Try to resolve the name. If it doesn't exist, assume it was
1571 // intended to name a type and keep disambiguating.
1572 switch (TryAnnotateName()) {
1574 return TPResult::Error;
1575 case ANK_TentativeDecl:
1576 return TPResult::False;
1577 case ANK_TemplateName:
1578 // In C++17, this could be a type template for class template
1579 // argument deduction.
1580 if (getLangOpts().CPlusPlus17) {
1581 if (TryAnnotateTypeOrScopeToken())
1582 return TPResult::Error;
1583 if (Tok.isNot(tok::identifier))
1587 // A bare type template-name which can't be a template template
1588 // argument is an error, and was probably intended to be a type.
1589 // In C++17, this could be class template argument deduction.
1590 return (getLangOpts().CPlusPlus17 || GreaterThanIsOperator)
1593 case ANK_Unresolved:
1594 return InvalidAsDeclSpec ? TPResult::Ambiguous : TPResult::False;
1599 // Annotated it, check again.
1600 assert(Tok.isNot(tok::annot_cxxscope) ||
1601 NextToken().isNot(tok::identifier));
1602 return isCXXDeclarationSpecifier(BracedCastResult, InvalidAsDeclSpec);
1605 return TPResult::False;
1607 // If that succeeded, fallthrough into the generic simple-type-id case.
1610 // The ambiguity resides in a simple-type-specifier/typename-specifier
1611 // followed by a '('. The '(' could either be the start of:
1613 // direct-declarator:
1614 // '(' declarator ')'
1616 // direct-abstract-declarator:
1617 // '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1618 // exception-specification[opt]
1619 // '(' abstract-declarator ')'
1621 // or part of a function-style cast expression:
1623 // simple-type-specifier '(' expression-list[opt] ')'
1626 // simple-type-specifier:
1628 case tok::annot_typename:
1630 // In Objective-C, we might have a protocol-qualified type.
1631 if (getLangOpts().ObjC && NextToken().is(tok::less)) {
1632 // Tentatively parse the protocol qualifiers.
1633 RevertingTentativeParsingAction PA(*this);
1634 ConsumeAnyToken(); // The type token
1636 TPResult TPR = TryParseProtocolQualifiers();
1637 bool isFollowedByParen = Tok.is(tok::l_paren);
1638 bool isFollowedByBrace = Tok.is(tok::l_brace);
1640 if (TPR == TPResult::Error)
1641 return TPResult::Error;
1643 if (isFollowedByParen)
1644 return TPResult::Ambiguous;
1646 if (getLangOpts().CPlusPlus11 && isFollowedByBrace)
1647 return BracedCastResult;
1649 return TPResult::True;
1654 case tok::kw_wchar_t:
1655 case tok::kw_char8_t:
1656 case tok::kw_char16_t:
1657 case tok::kw_char32_t:
1662 case tok::kw___int64:
1663 case tok::kw___int128:
1664 case tok::kw_signed:
1665 case tok::kw_unsigned:
1668 case tok::kw_double:
1669 case tok::kw__Float16:
1670 case tok::kw___float128:
1672 case tok::annot_decltype:
1673 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
1674 #include "clang/Basic/OpenCLImageTypes.def"
1675 if (NextToken().is(tok::l_paren))
1676 return TPResult::Ambiguous;
1678 // This is a function-style cast in all cases we disambiguate other than
1681 // enum E : int { a = 4 }; // enum
1682 // enum E : int { 4 }; // bit-field
1684 if (getLangOpts().CPlusPlus11 && NextToken().is(tok::l_brace))
1685 return BracedCastResult;
1687 if (isStartOfObjCClassMessageMissingOpenBracket())
1688 return TPResult::False;
1690 return TPResult::True;
1692 // GNU typeof support.
1693 case tok::kw_typeof: {
1694 if (NextToken().isNot(tok::l_paren))
1695 return TPResult::True;
1697 RevertingTentativeParsingAction PA(*this);
1699 TPResult TPR = TryParseTypeofSpecifier();
1700 bool isFollowedByParen = Tok.is(tok::l_paren);
1701 bool isFollowedByBrace = Tok.is(tok::l_brace);
1703 if (TPR == TPResult::Error)
1704 return TPResult::Error;
1706 if (isFollowedByParen)
1707 return TPResult::Ambiguous;
1709 if (getLangOpts().CPlusPlus11 && isFollowedByBrace)
1710 return BracedCastResult;
1712 return TPResult::True;
1715 // C++0x type traits support
1716 case tok::kw___underlying_type:
1717 return TPResult::True;
1720 case tok::kw__Atomic:
1721 return TPResult::True;
1724 return TPResult::False;
1728 bool Parser::isCXXDeclarationSpecifierAType() {
1729 switch (Tok.getKind()) {
1730 // typename-specifier
1731 case tok::annot_decltype:
1732 case tok::annot_template_id:
1733 case tok::annot_typename:
1734 case tok::kw_typeof:
1735 case tok::kw___underlying_type:
1738 // elaborated-type-specifier
1740 case tok::kw_struct:
1742 case tok::kw___interface:
1746 // simple-type-specifier
1748 case tok::kw_wchar_t:
1749 case tok::kw_char8_t:
1750 case tok::kw_char16_t:
1751 case tok::kw_char32_t:
1756 case tok::kw___int64:
1757 case tok::kw___int128:
1758 case tok::kw_signed:
1759 case tok::kw_unsigned:
1762 case tok::kw_double:
1763 case tok::kw__Float16:
1764 case tok::kw___float128:
1766 case tok::kw___unknown_anytype:
1767 case tok::kw___auto_type:
1768 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
1769 #include "clang/Basic/OpenCLImageTypes.def"
1773 return getLangOpts().CPlusPlus11;
1775 case tok::kw__Atomic:
1777 return NextToken().is(tok::l_paren);
1784 /// [GNU] typeof-specifier:
1785 /// 'typeof' '(' expressions ')'
1786 /// 'typeof' '(' type-name ')'
1788 Parser::TPResult Parser::TryParseTypeofSpecifier() {
1789 assert(Tok.is(tok::kw_typeof) && "Expected 'typeof'!");
1792 assert(Tok.is(tok::l_paren) && "Expected '('");
1793 // Parse through the parens after 'typeof'.
1795 if (!SkipUntil(tok::r_paren, StopAtSemi))
1796 return TPResult::Error;
1798 return TPResult::Ambiguous;
1801 /// [ObjC] protocol-qualifiers:
1802 //// '<' identifier-list '>'
1803 Parser::TPResult Parser::TryParseProtocolQualifiers() {
1804 assert(Tok.is(tok::less) && "Expected '<' for qualifier list");
1807 if (Tok.isNot(tok::identifier))
1808 return TPResult::Error;
1811 if (Tok.is(tok::comma)) {
1816 if (Tok.is(tok::greater)) {
1818 return TPResult::Ambiguous;
1822 return TPResult::Error;
1825 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
1826 /// a constructor-style initializer, when parsing declaration statements.
1827 /// Returns true for function declarator and false for constructor-style
1829 /// If during the disambiguation process a parsing error is encountered,
1830 /// the function returns true to let the declaration parsing code handle it.
1832 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1833 /// exception-specification[opt]
1835 bool Parser::isCXXFunctionDeclarator(bool *IsAmbiguous) {
1838 // The ambiguity arising from the similarity between a function-style cast and
1839 // a declaration mentioned in 6.8 can also occur in the context of a
1840 // declaration. In that context, the choice is between a function declaration
1841 // with a redundant set of parentheses around a parameter name and an object
1842 // declaration with a function-style cast as the initializer. Just as for the
1843 // ambiguities mentioned in 6.8, the resolution is to consider any construct
1844 // that could possibly be a declaration a declaration.
1846 RevertingTentativeParsingAction PA(*this);
1849 bool InvalidAsDeclaration = false;
1850 TPResult TPR = TryParseParameterDeclarationClause(&InvalidAsDeclaration);
1851 if (TPR == TPResult::Ambiguous) {
1852 if (Tok.isNot(tok::r_paren))
1853 TPR = TPResult::False;
1855 const Token &Next = NextToken();
1856 if (Next.isOneOf(tok::amp, tok::ampamp, tok::kw_const, tok::kw_volatile,
1857 tok::kw_throw, tok::kw_noexcept, tok::l_square,
1858 tok::l_brace, tok::kw_try, tok::equal, tok::arrow) ||
1859 isCXX11VirtSpecifier(Next))
1860 // The next token cannot appear after a constructor-style initializer,
1861 // and can appear next in a function definition. This must be a function
1863 TPR = TPResult::True;
1864 else if (InvalidAsDeclaration)
1865 // Use the absence of 'typename' as a tie-breaker.
1866 TPR = TPResult::False;
1870 if (IsAmbiguous && TPR == TPResult::Ambiguous)
1871 *IsAmbiguous = true;
1873 // In case of an error, let the declaration parsing code handle it.
1874 return TPR != TPResult::False;
1877 /// parameter-declaration-clause:
1878 /// parameter-declaration-list[opt] '...'[opt]
1879 /// parameter-declaration-list ',' '...'
1881 /// parameter-declaration-list:
1882 /// parameter-declaration
1883 /// parameter-declaration-list ',' parameter-declaration
1885 /// parameter-declaration:
1886 /// attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
1887 /// attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
1888 /// '=' assignment-expression
1889 /// attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
1891 /// attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
1892 /// attributes[opt] '=' assignment-expression
1895 Parser::TryParseParameterDeclarationClause(bool *InvalidAsDeclaration,
1896 bool VersusTemplateArgument) {
1898 if (Tok.is(tok::r_paren))
1899 return TPResult::Ambiguous;
1901 // parameter-declaration-list[opt] '...'[opt]
1902 // parameter-declaration-list ',' '...'
1904 // parameter-declaration-list:
1905 // parameter-declaration
1906 // parameter-declaration-list ',' parameter-declaration
1910 if (Tok.is(tok::ellipsis)) {
1912 if (Tok.is(tok::r_paren))
1913 return TPResult::True; // '...)' is a sign of a function declarator.
1915 return TPResult::False;
1918 // An attribute-specifier-seq here is a sign of a function declarator.
1919 if (isCXX11AttributeSpecifier(/*Disambiguate*/false,
1920 /*OuterMightBeMessageSend*/true))
1921 return TPResult::True;
1923 ParsedAttributes attrs(AttrFactory);
1924 MaybeParseMicrosoftAttributes(attrs);
1926 // decl-specifier-seq
1927 // A parameter-declaration's initializer must be preceded by an '=', so
1928 // decl-specifier-seq '{' is not a parameter in C++11.
1929 TPResult TPR = isCXXDeclarationSpecifier(TPResult::False,
1930 InvalidAsDeclaration);
1931 // A declaration-specifier (not followed by '(' or '{') means this can't be
1932 // an expression, but it could still be a template argument.
1933 if (TPR != TPResult::Ambiguous &&
1934 !(VersusTemplateArgument && TPR == TPResult::True))
1937 bool SeenType = false;
1939 SeenType |= isCXXDeclarationSpecifierAType();
1940 if (TryConsumeDeclarationSpecifier() == TPResult::Error)
1941 return TPResult::Error;
1943 // If we see a parameter name, this can't be a template argument.
1944 if (SeenType && Tok.is(tok::identifier))
1945 return TPResult::True;
1947 TPR = isCXXDeclarationSpecifier(TPResult::False,
1948 InvalidAsDeclaration);
1949 if (TPR == TPResult::Error)
1952 // Two declaration-specifiers means this can't be an expression.
1953 if (TPR == TPResult::True && !VersusTemplateArgument)
1955 } while (TPR != TPResult::False);
1958 // abstract-declarator[opt]
1959 TPR = TryParseDeclarator(true/*mayBeAbstract*/);
1960 if (TPR != TPResult::Ambiguous)
1963 // [GNU] attributes[opt]
1964 if (Tok.is(tok::kw___attribute))
1965 return TPResult::True;
1967 // If we're disambiguating a template argument in a default argument in
1968 // a class definition versus a parameter declaration, an '=' here
1969 // disambiguates the parse one way or the other.
1970 // If this is a parameter, it must have a default argument because
1971 // (a) the previous parameter did, and
1972 // (b) this must be the first declaration of the function, so we can't
1973 // inherit any default arguments from elsewhere.
1974 // If we see an ')', then we've reached the end of a
1975 // parameter-declaration-clause, and the last param is missing its default
1977 if (VersusTemplateArgument)
1978 return Tok.isOneOf(tok::equal, tok::r_paren) ? TPResult::True
1981 if (Tok.is(tok::equal)) {
1982 // '=' assignment-expression
1983 // Parse through assignment-expression.
1984 // FIXME: assignment-expression may contain an unparenthesized comma.
1985 if (!SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch))
1986 return TPResult::Error;
1989 if (Tok.is(tok::ellipsis)) {
1991 if (Tok.is(tok::r_paren))
1992 return TPResult::True; // '...)' is a sign of a function declarator.
1994 return TPResult::False;
1997 if (!TryConsumeToken(tok::comma))
2001 return TPResult::Ambiguous;
2004 /// TryParseFunctionDeclarator - We parsed a '(' and we want to try to continue
2005 /// parsing as a function declarator.
2006 /// If TryParseFunctionDeclarator fully parsed the function declarator, it will
2007 /// return TPResult::Ambiguous, otherwise it will return either False() or
2010 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
2011 /// exception-specification[opt]
2013 /// exception-specification:
2014 /// 'throw' '(' type-id-list[opt] ')'
2016 Parser::TPResult Parser::TryParseFunctionDeclarator() {
2018 // The '(' is already parsed.
2020 TPResult TPR = TryParseParameterDeclarationClause();
2021 if (TPR == TPResult::Ambiguous && Tok.isNot(tok::r_paren))
2022 TPR = TPResult::False;
2024 if (TPR == TPResult::False || TPR == TPResult::Error)
2027 // Parse through the parens.
2028 if (!SkipUntil(tok::r_paren, StopAtSemi))
2029 return TPResult::Error;
2032 while (Tok.isOneOf(tok::kw_const, tok::kw_volatile, tok::kw___unaligned,
2036 // ref-qualifier[opt]
2037 if (Tok.isOneOf(tok::amp, tok::ampamp))
2040 // exception-specification
2041 if (Tok.is(tok::kw_throw)) {
2043 if (Tok.isNot(tok::l_paren))
2044 return TPResult::Error;
2046 // Parse through the parens after 'throw'.
2048 if (!SkipUntil(tok::r_paren, StopAtSemi))
2049 return TPResult::Error;
2051 if (Tok.is(tok::kw_noexcept)) {
2053 // Possibly an expression as well.
2054 if (Tok.is(tok::l_paren)) {
2055 // Find the matching rparen.
2057 if (!SkipUntil(tok::r_paren, StopAtSemi))
2058 return TPResult::Error;
2062 return TPResult::Ambiguous;
2065 /// '[' constant-expression[opt] ']'
2067 Parser::TPResult Parser::TryParseBracketDeclarator() {
2069 if (!SkipUntil(tok::r_square, StopAtSemi))
2070 return TPResult::Error;
2072 return TPResult::Ambiguous;
2075 /// Determine whether we might be looking at the '<' template-argument-list '>'
2076 /// of a template-id or simple-template-id, rather than a less-than comparison.
2077 /// This will often fail and produce an ambiguity, but should never be wrong
2078 /// if it returns True or False.
2079 Parser::TPResult Parser::isTemplateArgumentList(unsigned TokensToSkip) {
2080 if (!TokensToSkip) {
2081 if (Tok.isNot(tok::less))
2082 return TPResult::False;
2083 if (NextToken().is(tok::greater))
2084 return TPResult::True;
2087 RevertingTentativeParsingAction PA(*this);
2089 while (TokensToSkip) {
2094 if (!TryConsumeToken(tok::less))
2095 return TPResult::False;
2097 // We can't do much to tell an expression apart from a template-argument,
2098 // but one good distinguishing factor is that a "decl-specifier" not
2099 // followed by '(' or '{' can't appear in an expression.
2100 bool InvalidAsTemplateArgumentList = false;
2101 if (isCXXDeclarationSpecifier(TPResult::False,
2102 &InvalidAsTemplateArgumentList) ==
2104 return TPResult::True;
2105 if (InvalidAsTemplateArgumentList)
2106 return TPResult::False;
2108 // FIXME: In many contexts, X<thing1, Type> can only be a
2109 // template-argument-list. But that's not true in general:
2113 // int a = A<B, b, c = C>D; // OK, declares b, not a template-id.
2115 // X<Y<0, int> // ', int>' might be end of X's template argument list
2117 // We might be able to disambiguate a few more cases if we're careful.
2119 // A template-argument-list must be terminated by a '>'.
2120 if (SkipUntil({tok::greater, tok::greatergreater, tok::greatergreatergreater},
2121 StopAtSemi | StopBeforeMatch))
2122 return TPResult::Ambiguous;
2123 return TPResult::False;