1 //===--- ParseTentative.cpp - Ambiguity Resolution Parsing ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the tentative parsing portions of the Parser
11 // interfaces, for ambiguity resolution.
13 //===----------------------------------------------------------------------===//
15 #include "clang/Parse/Parser.h"
16 #include "clang/Parse/ParseDiagnostic.h"
17 #include "clang/Sema/ParsedTemplate.h"
18 using namespace clang;
20 /// isCXXDeclarationStatement - C++-specialized function that disambiguates
21 /// between a declaration or an expression statement, when parsing function
22 /// bodies. Returns true for declaration, false for expression.
24 /// declaration-statement:
27 /// block-declaration:
28 /// simple-declaration
30 /// namespace-alias-definition
33 /// [C++0x] static_assert-declaration
36 /// 'asm' '(' string-literal ')' ';'
38 /// namespace-alias-definition:
39 /// 'namespace' identifier = qualified-namespace-specifier ';'
41 /// using-declaration:
42 /// 'using' typename[opt] '::'[opt] nested-name-specifier
43 /// unqualified-id ';'
44 /// 'using' '::' unqualified-id ;
47 /// 'using' 'namespace' '::'[opt] nested-name-specifier[opt]
48 /// namespace-name ';'
50 bool Parser::isCXXDeclarationStatement() {
51 switch (Tok.getKind()) {
54 // namespace-alias-definition
55 case tok::kw_namespace:
59 // static_assert-declaration
60 case tok::kw_static_assert:
61 case tok::kw__Static_assert:
65 return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
69 /// isCXXSimpleDeclaration - C++-specialized function that disambiguates
70 /// between a simple-declaration or an expression-statement.
71 /// If during the disambiguation process a parsing error is encountered,
72 /// the function returns true to let the declaration parsing code handle it.
73 /// Returns false if the statement is disambiguated as expression.
75 /// simple-declaration:
76 /// decl-specifier-seq init-declarator-list[opt] ';'
77 /// decl-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
78 /// brace-or-equal-initializer ';' [C++17]
80 /// (if AllowForRangeDecl specified)
81 /// for ( for-range-declaration : for-range-initializer ) statement
83 /// for-range-declaration:
84 /// decl-specifier-seq declarator
85 /// decl-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
87 /// In any of the above cases there can be a preceding attribute-specifier-seq,
88 /// but the caller is expected to handle that.
89 bool Parser::isCXXSimpleDeclaration(bool AllowForRangeDecl) {
91 // There is an ambiguity in the grammar involving expression-statements and
92 // declarations: An expression-statement with a function-style explicit type
93 // conversion (5.2.3) as its leftmost subexpression can be indistinguishable
94 // from a declaration where the first declarator starts with a '('. In those
95 // cases the statement is a declaration. [Note: To disambiguate, the whole
96 // statement might have to be examined to determine if it is an
97 // expression-statement or a declaration].
100 // The disambiguation is purely syntactic; that is, the meaning of the names
101 // occurring in such a statement, beyond whether they are type-names or not,
102 // is not generally used in or changed by the disambiguation. Class
103 // templates are instantiated as necessary to determine if a qualified name
104 // is a type-name. Disambiguation precedes parsing, and a statement
105 // disambiguated as a declaration may be an ill-formed declaration.
107 // We don't have to parse all of the decl-specifier-seq part. There's only
108 // an ambiguity if the first decl-specifier is
109 // simple-type-specifier/typename-specifier followed by a '(', which may
110 // indicate a function-style cast expression.
111 // isCXXDeclarationSpecifier will return TPResult::Ambiguous only in such
114 bool InvalidAsDeclaration = false;
115 TPResult TPR = isCXXDeclarationSpecifier(TPResult::False,
116 &InvalidAsDeclaration);
117 if (TPR != TPResult::Ambiguous)
118 return TPR != TPResult::False; // Returns true for TPResult::True or
121 // FIXME: TryParseSimpleDeclaration doesn't look past the first initializer,
122 // and so gets some cases wrong. We can't carry on if we've already seen
123 // something which makes this statement invalid as a declaration in this case,
124 // since it can cause us to misparse valid code. Revisit this once
125 // TryParseInitDeclaratorList is fixed.
126 if (InvalidAsDeclaration)
129 // FIXME: Add statistics about the number of ambiguous statements encountered
130 // and how they were resolved (number of declarations+number of expressions).
132 // Ok, we have a simple-type-specifier/typename-specifier followed by a '(',
133 // or an identifier which doesn't resolve as anything. We need tentative
137 RevertingTentativeParsingAction PA(*this);
138 TPR = TryParseSimpleDeclaration(AllowForRangeDecl);
141 // In case of an error, let the declaration parsing code handle it.
142 if (TPR == TPResult::Error)
145 // Declarations take precedence over expressions.
146 if (TPR == TPResult::Ambiguous)
147 TPR = TPResult::True;
149 assert(TPR == TPResult::True || TPR == TPResult::False);
150 return TPR == TPResult::True;
153 /// Try to consume a token sequence that we've already identified as
154 /// (potentially) starting a decl-specifier.
155 Parser::TPResult Parser::TryConsumeDeclarationSpecifier() {
156 switch (Tok.getKind()) {
157 case tok::kw__Atomic:
158 if (NextToken().isNot(tok::l_paren)) {
164 case tok::kw___attribute:
165 case tok::kw___underlying_type: {
167 if (Tok.isNot(tok::l_paren))
168 return TPResult::Error;
170 if (!SkipUntil(tok::r_paren))
171 return TPResult::Error;
178 case tok::kw___interface:
180 // elaborated-type-specifier:
181 // class-key attribute-specifier-seq[opt]
182 // nested-name-specifier[opt] identifier
183 // class-key nested-name-specifier[opt] template[opt] simple-template-id
184 // enum nested-name-specifier[opt] identifier
186 // FIXME: We don't support class-specifiers nor enum-specifiers here.
190 while (Tok.isOneOf(tok::l_square, tok::kw___attribute, tok::kw___declspec,
192 if (Tok.is(tok::l_square)) {
194 if (!SkipUntil(tok::r_square))
195 return TPResult::Error;
198 if (Tok.isNot(tok::l_paren))
199 return TPResult::Error;
201 if (!SkipUntil(tok::r_paren))
202 return TPResult::Error;
206 if (Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
207 tok::annot_template_id) &&
208 TryAnnotateCXXScopeToken())
209 return TPResult::Error;
210 if (Tok.is(tok::annot_cxxscope))
211 ConsumeAnnotationToken();
212 if (Tok.is(tok::identifier))
214 else if (Tok.is(tok::annot_template_id))
215 ConsumeAnnotationToken();
217 return TPResult::Error;
220 case tok::annot_cxxscope:
221 ConsumeAnnotationToken();
226 if (getLangOpts().ObjC1 && Tok.is(tok::less))
227 return TryParseProtocolQualifiers();
231 return TPResult::Ambiguous;
234 /// simple-declaration:
235 /// decl-specifier-seq init-declarator-list[opt] ';'
237 /// (if AllowForRangeDecl specified)
238 /// for ( for-range-declaration : for-range-initializer ) statement
239 /// for-range-declaration:
240 /// attribute-specifier-seqopt type-specifier-seq declarator
242 Parser::TPResult Parser::TryParseSimpleDeclaration(bool AllowForRangeDecl) {
243 if (TryConsumeDeclarationSpecifier() == TPResult::Error)
244 return TPResult::Error;
246 // Two decl-specifiers in a row conclusively disambiguate this as being a
247 // simple-declaration. Don't bother calling isCXXDeclarationSpecifier in the
248 // overwhelmingly common case that the next token is a '('.
249 if (Tok.isNot(tok::l_paren)) {
250 TPResult TPR = isCXXDeclarationSpecifier();
251 if (TPR == TPResult::Ambiguous)
252 return TPResult::True;
253 if (TPR == TPResult::True || TPR == TPResult::Error)
255 assert(TPR == TPResult::False);
258 TPResult TPR = TryParseInitDeclaratorList();
259 if (TPR != TPResult::Ambiguous)
262 if (Tok.isNot(tok::semi) && (!AllowForRangeDecl || Tok.isNot(tok::colon)))
263 return TPResult::False;
265 return TPResult::Ambiguous;
268 /// Tentatively parse an init-declarator-list in order to disambiguate it from
271 /// init-declarator-list:
273 /// init-declarator-list ',' init-declarator
276 /// declarator initializer[opt]
277 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] initializer[opt]
280 /// brace-or-equal-initializer
281 /// '(' expression-list ')'
283 /// brace-or-equal-initializer:
284 /// '=' initializer-clause
285 /// [C++11] braced-init-list
287 /// initializer-clause:
288 /// assignment-expression
291 /// braced-init-list:
292 /// '{' initializer-list ','[opt] '}'
295 Parser::TPResult Parser::TryParseInitDeclaratorList() {
298 TPResult TPR = TryParseDeclarator(false/*mayBeAbstract*/);
299 if (TPR != TPResult::Ambiguous)
302 // [GNU] simple-asm-expr[opt] attributes[opt]
303 if (Tok.isOneOf(tok::kw_asm, tok::kw___attribute))
304 return TPResult::True;
307 if (Tok.is(tok::l_paren)) {
308 // Parse through the parens.
310 if (!SkipUntil(tok::r_paren, StopAtSemi))
311 return TPResult::Error;
312 } else if (Tok.is(tok::l_brace)) {
313 // A left-brace here is sufficient to disambiguate the parse; an
314 // expression can never be followed directly by a braced-init-list.
315 return TPResult::True;
316 } else if (Tok.is(tok::equal) || isTokIdentifier_in()) {
317 // MSVC and g++ won't examine the rest of declarators if '=' is
318 // encountered; they just conclude that we have a declaration.
319 // EDG parses the initializer completely, which is the proper behavior
322 // At present, Clang follows MSVC and g++, since the parser does not have
323 // the ability to parse an expression fully without recording the
324 // results of that parse.
325 // FIXME: Handle this case correctly.
327 // Also allow 'in' after an Objective-C declaration as in:
328 // for (int (^b)(void) in array). Ideally this should be done in the
329 // context of parsing for-init-statement of a foreach statement only. But,
330 // in any other context 'in' is invalid after a declaration and parser
331 // issues the error regardless of outcome of this decision.
332 // FIXME: Change if above assumption does not hold.
333 return TPResult::True;
336 if (!TryConsumeToken(tok::comma))
340 return TPResult::Ambiguous;
343 struct Parser::ConditionDeclarationOrInitStatementState {
345 bool CanBeExpression = true;
346 bool CanBeCondition = true;
347 bool CanBeInitStatement;
349 ConditionDeclarationOrInitStatementState(Parser &P, bool CanBeInitStatement)
350 : P(P), CanBeInitStatement(CanBeInitStatement) {}
352 void markNotExpression() {
353 CanBeExpression = false;
355 if (CanBeCondition && CanBeInitStatement) {
356 // FIXME: Unify the parsing codepaths for condition variables and
357 // simple-declarations so that we don't need to eagerly figure out which
358 // kind we have here. (Just parse init-declarators until we reach a
359 // semicolon or right paren.)
360 RevertingTentativeParsingAction PA(P);
361 P.SkipUntil(tok::r_paren, tok::semi, StopBeforeMatch);
362 if (P.Tok.isNot(tok::r_paren))
363 CanBeCondition = false;
364 if (P.Tok.isNot(tok::semi))
365 CanBeInitStatement = false;
369 bool markNotCondition() {
370 CanBeCondition = false;
371 return !CanBeInitStatement || !CanBeExpression;
374 bool update(TPResult IsDecl) {
379 case TPResult::False:
380 CanBeCondition = CanBeInitStatement = false;
382 case TPResult::Ambiguous:
384 case TPResult::Error:
385 CanBeExpression = CanBeCondition = CanBeInitStatement = false;
388 llvm_unreachable("unknown tentative parse result");
391 ConditionOrInitStatement result() const {
392 assert(CanBeExpression + CanBeCondition + CanBeInitStatement < 2 &&
393 "result called but not yet resolved");
395 return ConditionOrInitStatement::Expression;
397 return ConditionOrInitStatement::ConditionDecl;
398 if (CanBeInitStatement)
399 return ConditionOrInitStatement::InitStmtDecl;
400 return ConditionOrInitStatement::Error;
404 /// Disambiguates between a declaration in a condition, a
405 /// simple-declaration in an init-statement, and an expression for
406 /// a condition of a if/switch statement.
410 /// type-specifier-seq declarator '=' assignment-expression
411 /// [C++11] type-specifier-seq declarator '=' initializer-clause
412 /// [C++11] type-specifier-seq declarator braced-init-list
413 /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
414 /// '=' assignment-expression
415 /// simple-declaration:
416 /// decl-specifier-seq init-declarator-list[opt] ';'
418 /// Note that, unlike isCXXSimpleDeclaration, we must disambiguate all the way
419 /// to the ';' to disambiguate cases like 'int(x))' (an expression) from
420 /// 'int(x);' (a simple-declaration in an init-statement).
421 Parser::ConditionOrInitStatement
422 Parser::isCXXConditionDeclarationOrInitStatement(bool CanBeInitStatement) {
423 ConditionDeclarationOrInitStatementState State(*this, CanBeInitStatement);
425 if (State.update(isCXXDeclarationSpecifier()))
426 return State.result();
428 // It might be a declaration; we need tentative parsing.
429 RevertingTentativeParsingAction PA(*this);
431 // FIXME: A tag definition unambiguously tells us this is an init-statement.
432 if (State.update(TryConsumeDeclarationSpecifier()))
433 return State.result();
434 assert(Tok.is(tok::l_paren) && "Expected '('");
437 // Consume a declarator.
438 if (State.update(TryParseDeclarator(false/*mayBeAbstract*/)))
439 return State.result();
441 // Attributes, asm label, or an initializer imply this is not an expression.
442 // FIXME: Disambiguate properly after an = instead of assuming that it's a
443 // valid declaration.
444 if (Tok.isOneOf(tok::equal, tok::kw_asm, tok::kw___attribute) ||
445 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace))) {
446 State.markNotExpression();
447 return State.result();
450 // At this point, it can't be a condition any more, because a condition
451 // must have a brace-or-equal-initializer.
452 if (State.markNotCondition())
453 return State.result();
455 // A parenthesized initializer could be part of an expression or a
456 // simple-declaration.
457 if (Tok.is(tok::l_paren)) {
459 SkipUntil(tok::r_paren, StopAtSemi);
462 if (!TryConsumeToken(tok::comma))
466 // We reached the end. If it can now be some kind of decl, then it is.
467 if (State.CanBeCondition && Tok.is(tok::r_paren))
468 return ConditionOrInitStatement::ConditionDecl;
469 else if (State.CanBeInitStatement && Tok.is(tok::semi))
470 return ConditionOrInitStatement::InitStmtDecl;
472 return ConditionOrInitStatement::Expression;
475 /// Determine whether the next set of tokens contains a type-id.
477 /// The context parameter states what context we're parsing right
478 /// now, which affects how this routine copes with the token
479 /// following the type-id. If the context is TypeIdInParens, we have
480 /// already parsed the '(' and we will cease lookahead when we hit
481 /// the corresponding ')'. If the context is
482 /// TypeIdAsTemplateArgument, we've already parsed the '<' or ','
483 /// before this template argument, and will cease lookahead when we
484 /// hit a '>', '>>' (in C++0x), or ','; or, in C++0x, an ellipsis immediately
485 /// preceding such. Returns true for a type-id and false for an expression.
486 /// If during the disambiguation process a parsing error is encountered,
487 /// the function returns true to let the declaration parsing code handle it.
490 /// type-specifier-seq abstract-declarator[opt]
492 bool Parser::isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous) {
497 // The ambiguity arising from the similarity between a function-style cast and
498 // a type-id can occur in different contexts. The ambiguity appears as a
499 // choice between a function-style cast expression and a declaration of a
500 // type. The resolution is that any construct that could possibly be a type-id
501 // in its syntactic context shall be considered a type-id.
503 TPResult TPR = isCXXDeclarationSpecifier();
504 if (TPR != TPResult::Ambiguous)
505 return TPR != TPResult::False; // Returns true for TPResult::True or
508 // FIXME: Add statistics about the number of ambiguous statements encountered
509 // and how they were resolved (number of declarations+number of expressions).
511 // Ok, we have a simple-type-specifier/typename-specifier followed by a '('.
512 // We need tentative parsing...
514 RevertingTentativeParsingAction PA(*this);
516 // type-specifier-seq
517 TryConsumeDeclarationSpecifier();
518 assert(Tok.is(tok::l_paren) && "Expected '('");
521 TPR = TryParseDeclarator(true/*mayBeAbstract*/, false/*mayHaveIdentifier*/);
523 // In case of an error, let the declaration parsing code handle it.
524 if (TPR == TPResult::Error)
525 TPR = TPResult::True;
527 if (TPR == TPResult::Ambiguous) {
528 // We are supposed to be inside parens, so if after the abstract declarator
529 // we encounter a ')' this is a type-id, otherwise it's an expression.
530 if (Context == TypeIdInParens && Tok.is(tok::r_paren)) {
531 TPR = TPResult::True;
534 // We are supposed to be inside a template argument, so if after
535 // the abstract declarator we encounter a '>', '>>' (in C++0x), or
536 // ','; or, in C++0x, an ellipsis immediately preceding such, this
537 // is a type-id. Otherwise, it's an expression.
538 } else if (Context == TypeIdAsTemplateArgument &&
539 (Tok.isOneOf(tok::greater, tok::comma) ||
540 (getLangOpts().CPlusPlus11 &&
541 (Tok.is(tok::greatergreater) ||
542 (Tok.is(tok::ellipsis) &&
543 NextToken().isOneOf(tok::greater, tok::greatergreater,
545 TPR = TPResult::True;
549 TPR = TPResult::False;
552 assert(TPR == TPResult::True || TPR == TPResult::False);
553 return TPR == TPResult::True;
556 /// Returns true if this is a C++11 attribute-specifier. Per
557 /// C++11 [dcl.attr.grammar]p6, two consecutive left square bracket tokens
558 /// always introduce an attribute. In Objective-C++11, this rule does not
559 /// apply if either '[' begins a message-send.
561 /// If Disambiguate is true, we try harder to determine whether a '[[' starts
562 /// an attribute-specifier, and return CAK_InvalidAttributeSpecifier if not.
564 /// If OuterMightBeMessageSend is true, we assume the outer '[' is either an
565 /// Obj-C message send or the start of an attribute. Otherwise, we assume it
566 /// is not an Obj-C message send.
568 /// C++11 [dcl.attr.grammar]:
570 /// attribute-specifier:
571 /// '[' '[' attribute-list ']' ']'
572 /// alignment-specifier
576 /// attribute-list ',' attribute[opt]
578 /// attribute-list ',' attribute '...'
581 /// attribute-token attribute-argument-clause[opt]
585 /// identifier '::' identifier
587 /// attribute-argument-clause:
588 /// '(' balanced-token-seq ')'
589 Parser::CXX11AttributeKind
590 Parser::isCXX11AttributeSpecifier(bool Disambiguate,
591 bool OuterMightBeMessageSend) {
592 if (Tok.is(tok::kw_alignas))
593 return CAK_AttributeSpecifier;
595 if (Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square))
596 return CAK_NotAttributeSpecifier;
598 // No tentative parsing if we don't need to look for ']]' or a lambda.
599 if (!Disambiguate && !getLangOpts().ObjC1)
600 return CAK_AttributeSpecifier;
602 RevertingTentativeParsingAction PA(*this);
604 // Opening brackets were checked for above.
607 // Outside Obj-C++11, treat anything with a matching ']]' as an attribute.
608 if (!getLangOpts().ObjC1) {
611 bool IsAttribute = SkipUntil(tok::r_square);
612 IsAttribute &= Tok.is(tok::r_square);
614 return IsAttribute ? CAK_AttributeSpecifier : CAK_InvalidAttributeSpecifier;
617 // In Obj-C++11, we need to distinguish four situations:
618 // 1a) int x[[attr]]; C++11 attribute.
619 // 1b) [[attr]]; C++11 statement attribute.
620 // 2) int x[[obj](){ return 1; }()]; Lambda in array size/index.
621 // 3a) int x[[obj get]]; Message send in array size/index.
622 // 3b) [[Class alloc] init]; Message send in message send.
623 // 4) [[obj]{ return self; }() doStuff]; Lambda in message send.
624 // (1) is an attribute, (2) is ill-formed, and (3) and (4) are accepted.
626 // If we have a lambda-introducer, then this is definitely not a message send.
627 // FIXME: If this disambiguation is too slow, fold the tentative lambda parse
628 // into the tentative attribute parse below.
629 LambdaIntroducer Intro;
630 if (!TryParseLambdaIntroducer(Intro)) {
631 // A lambda cannot end with ']]', and an attribute must.
632 bool IsAttribute = Tok.is(tok::r_square);
635 // Case 1: C++11 attribute.
636 return CAK_AttributeSpecifier;
638 if (OuterMightBeMessageSend)
639 // Case 4: Lambda in message send.
640 return CAK_NotAttributeSpecifier;
642 // Case 2: Lambda in array size / index.
643 return CAK_InvalidAttributeSpecifier;
648 // If we don't have a lambda-introducer, then we have an attribute or a
650 bool IsAttribute = true;
651 while (Tok.isNot(tok::r_square)) {
652 if (Tok.is(tok::comma)) {
653 // Case 1: Stray commas can only occur in attributes.
654 return CAK_AttributeSpecifier;
657 // Parse the attribute-token, if present.
658 // C++11 [dcl.attr.grammar]:
659 // If a keyword or an alternative token that satisfies the syntactic
660 // requirements of an identifier is contained in an attribute-token,
661 // it is considered an identifier.
663 if (!TryParseCXX11AttributeIdentifier(Loc)) {
667 if (Tok.is(tok::coloncolon)) {
669 if (!TryParseCXX11AttributeIdentifier(Loc)) {
675 // Parse the attribute-argument-clause, if present.
676 if (Tok.is(tok::l_paren)) {
678 if (!SkipUntil(tok::r_paren)) {
684 TryConsumeToken(tok::ellipsis);
686 if (!TryConsumeToken(tok::comma))
690 // An attribute must end ']]'.
692 if (Tok.is(tok::r_square)) {
694 IsAttribute = Tok.is(tok::r_square);
701 // Case 1: C++11 statement attribute.
702 return CAK_AttributeSpecifier;
704 // Case 3: Message send.
705 return CAK_NotAttributeSpecifier;
708 Parser::TPResult Parser::TryParsePtrOperatorSeq() {
710 if (Tok.isOneOf(tok::coloncolon, tok::identifier))
711 if (TryAnnotateCXXScopeToken(true))
712 return TPResult::Error;
714 if (Tok.isOneOf(tok::star, tok::amp, tok::caret, tok::ampamp) ||
715 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::star))) {
718 while (Tok.isOneOf(tok::kw_const, tok::kw_volatile, tok::kw_restrict,
719 tok::kw__Nonnull, tok::kw__Nullable,
720 tok::kw__Null_unspecified))
723 return TPResult::True;
728 /// operator-function-id:
729 /// 'operator' operator
732 /// new delete new[] delete[] + - * / % ^ [...]
734 /// conversion-function-id:
735 /// 'operator' conversion-type-id
737 /// conversion-type-id:
738 /// type-specifier-seq conversion-declarator[opt]
740 /// conversion-declarator:
741 /// ptr-operator conversion-declarator[opt]
743 /// literal-operator-id:
744 /// 'operator' string-literal identifier
745 /// 'operator' user-defined-string-literal
746 Parser::TPResult Parser::TryParseOperatorId() {
747 assert(Tok.is(tok::kw_operator));
750 // Maybe this is an operator-function-id.
751 switch (Tok.getKind()) {
752 case tok::kw_new: case tok::kw_delete:
754 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
758 return TPResult::True;
760 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemOnly) \
762 #define OVERLOADED_OPERATOR_MULTI(Name, Spelling, Unary, Binary, MemOnly)
763 #include "clang/Basic/OperatorKinds.def"
765 return TPResult::True;
768 if (NextToken().is(tok::r_square)) {
771 return TPResult::True;
776 if (NextToken().is(tok::r_paren)) {
779 return TPResult::True;
787 // Maybe this is a literal-operator-id.
788 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
789 bool FoundUDSuffix = false;
791 FoundUDSuffix |= Tok.hasUDSuffix();
792 ConsumeStringToken();
793 } while (isTokenStringLiteral());
795 if (!FoundUDSuffix) {
796 if (Tok.is(tok::identifier))
799 return TPResult::Error;
801 return TPResult::True;
804 // Maybe this is a conversion-function-id.
805 bool AnyDeclSpecifiers = false;
807 TPResult TPR = isCXXDeclarationSpecifier();
808 if (TPR == TPResult::Error)
810 if (TPR == TPResult::False) {
811 if (!AnyDeclSpecifiers)
812 return TPResult::Error;
815 if (TryConsumeDeclarationSpecifier() == TPResult::Error)
816 return TPResult::Error;
817 AnyDeclSpecifiers = true;
819 return TryParsePtrOperatorSeq();
823 /// direct-declarator
824 /// ptr-operator declarator
826 /// direct-declarator:
828 /// direct-declarator '(' parameter-declaration-clause ')'
829 /// cv-qualifier-seq[opt] exception-specification[opt]
830 /// direct-declarator '[' constant-expression[opt] ']'
831 /// '(' declarator ')'
832 /// [GNU] '(' attributes declarator ')'
834 /// abstract-declarator:
835 /// ptr-operator abstract-declarator[opt]
836 /// direct-abstract-declarator
838 /// direct-abstract-declarator:
839 /// direct-abstract-declarator[opt]
840 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
841 /// exception-specification[opt]
842 /// direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
843 /// '(' abstract-declarator ')'
847 /// '*' cv-qualifier-seq[opt]
849 /// [C++0x] '&&' [TODO]
850 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
852 /// cv-qualifier-seq:
853 /// cv-qualifier cv-qualifier-seq[opt]
860 /// '...'[opt] id-expression
864 /// qualified-id [TODO]
868 /// operator-function-id
869 /// conversion-function-id
870 /// literal-operator-id
871 /// '~' class-name [TODO]
872 /// '~' decltype-specifier [TODO]
873 /// template-id [TODO]
875 Parser::TPResult Parser::TryParseDeclarator(bool mayBeAbstract,
876 bool mayHaveIdentifier,
877 bool mayHaveDirectInit) {
880 // ptr-operator declarator
881 if (TryParsePtrOperatorSeq() == TPResult::Error)
882 return TPResult::Error;
884 // direct-declarator:
885 // direct-abstract-declarator:
886 if (Tok.is(tok::ellipsis))
889 if ((Tok.isOneOf(tok::identifier, tok::kw_operator) ||
890 (Tok.is(tok::annot_cxxscope) && (NextToken().is(tok::identifier) ||
891 NextToken().is(tok::kw_operator)))) &&
894 if (Tok.is(tok::annot_cxxscope))
895 ConsumeAnnotationToken();
896 else if (Tok.is(tok::identifier))
897 TentativelyDeclaredIdentifiers.push_back(Tok.getIdentifierInfo());
898 if (Tok.is(tok::kw_operator)) {
899 if (TryParseOperatorId() == TPResult::Error)
900 return TPResult::Error;
903 } else if (Tok.is(tok::l_paren)) {
906 (Tok.is(tok::r_paren) || // 'int()' is a function.
907 // 'int(...)' is a function.
908 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren)) ||
909 isDeclarationSpecifier())) { // 'int(int)' is a function.
910 // '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
911 // exception-specification[opt]
912 TPResult TPR = TryParseFunctionDeclarator();
913 if (TPR != TPResult::Ambiguous)
916 // '(' declarator ')'
917 // '(' attributes declarator ')'
918 // '(' abstract-declarator ')'
919 if (Tok.isOneOf(tok::kw___attribute, tok::kw___declspec, tok::kw___cdecl,
920 tok::kw___stdcall, tok::kw___fastcall, tok::kw___thiscall,
921 tok::kw___regcall, tok::kw___vectorcall))
922 return TPResult::True; // attributes indicate declaration
923 TPResult TPR = TryParseDeclarator(mayBeAbstract, mayHaveIdentifier);
924 if (TPR != TPResult::Ambiguous)
926 if (Tok.isNot(tok::r_paren))
927 return TPResult::False;
930 } else if (!mayBeAbstract) {
931 return TPResult::False;
934 if (mayHaveDirectInit)
935 return TPResult::Ambiguous;
938 TPResult TPR(TPResult::Ambiguous);
940 if (Tok.is(tok::l_paren)) {
941 // Check whether we have a function declarator or a possible ctor-style
942 // initializer that follows the declarator. Note that ctor-style
943 // initializers are not possible in contexts where abstract declarators
945 if (!mayBeAbstract && !isCXXFunctionDeclarator())
948 // direct-declarator '(' parameter-declaration-clause ')'
949 // cv-qualifier-seq[opt] exception-specification[opt]
951 TPR = TryParseFunctionDeclarator();
952 } else if (Tok.is(tok::l_square)) {
953 // direct-declarator '[' constant-expression[opt] ']'
954 // direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
955 TPR = TryParseBracketDeclarator();
960 if (TPR != TPResult::Ambiguous)
964 return TPResult::Ambiguous;
968 Parser::isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind) {
970 // Obviously starts an expression.
971 case tok::numeric_constant:
972 case tok::char_constant:
973 case tok::wide_char_constant:
974 case tok::utf8_char_constant:
975 case tok::utf16_char_constant:
976 case tok::utf32_char_constant:
977 case tok::string_literal:
978 case tok::wide_string_literal:
979 case tok::utf8_string_literal:
980 case tok::utf16_string_literal:
981 case tok::utf32_string_literal:
990 case tok::minusminus:
994 case tok::kw___func__:
995 case tok::kw_const_cast:
997 case tok::kw_dynamic_cast:
1000 case tok::kw_operator:
1001 case tok::kw_reinterpret_cast:
1002 case tok::kw_static_cast:
1006 case tok::kw_typeid:
1007 case tok::kw_alignof:
1008 case tok::kw_noexcept:
1009 case tok::kw_nullptr:
1010 case tok::kw__Alignof:
1011 case tok::kw___null:
1012 case tok::kw___alignof:
1013 case tok::kw___builtin_choose_expr:
1014 case tok::kw___builtin_offsetof:
1015 case tok::kw___builtin_va_arg:
1016 case tok::kw___imag:
1017 case tok::kw___real:
1018 case tok::kw___FUNCTION__:
1019 case tok::kw___FUNCDNAME__:
1020 case tok::kw___FUNCSIG__:
1021 case tok::kw_L__FUNCTION__:
1022 case tok::kw_L__FUNCSIG__:
1023 case tok::kw___PRETTY_FUNCTION__:
1024 case tok::kw___uuidof:
1025 #define TYPE_TRAIT(N,Spelling,K) \
1026 case tok::kw_##Spelling:
1027 #include "clang/Basic/TokenKinds.def"
1028 return TPResult::True;
1030 // Obviously starts a type-specifier-seq:
1033 case tok::kw_double:
1034 case tok::kw__Float16:
1035 case tok::kw___float128:
1041 case tok::kw___int64:
1042 case tok::kw___int128:
1043 case tok::kw_restrict:
1045 case tok::kw_signed:
1046 case tok::kw_struct:
1048 case tok::kw_unsigned:
1050 case tok::kw_volatile:
1052 case tok::kw__Complex:
1054 case tok::kw_typename:
1055 case tok::kw_wchar_t:
1056 case tok::kw_char8_t:
1057 case tok::kw_char16_t:
1058 case tok::kw_char32_t:
1059 case tok::kw__Decimal32:
1060 case tok::kw__Decimal64:
1061 case tok::kw__Decimal128:
1062 case tok::kw___interface:
1063 case tok::kw___thread:
1064 case tok::kw_thread_local:
1065 case tok::kw__Thread_local:
1066 case tok::kw_typeof:
1067 case tok::kw___underlying_type:
1068 case tok::kw___cdecl:
1069 case tok::kw___stdcall:
1070 case tok::kw___fastcall:
1071 case tok::kw___thiscall:
1072 case tok::kw___regcall:
1073 case tok::kw___vectorcall:
1074 case tok::kw___unaligned:
1075 case tok::kw___vector:
1076 case tok::kw___pixel:
1077 case tok::kw___bool:
1078 case tok::kw__Atomic:
1079 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
1080 #include "clang/Basic/OpenCLImageTypes.def"
1081 case tok::kw___unknown_anytype:
1082 return TPResult::False;
1088 return TPResult::Ambiguous;
1091 bool Parser::isTentativelyDeclared(IdentifierInfo *II) {
1092 return std::find(TentativelyDeclaredIdentifiers.begin(),
1093 TentativelyDeclaredIdentifiers.end(), II)
1094 != TentativelyDeclaredIdentifiers.end();
1098 class TentativeParseCCC : public CorrectionCandidateCallback {
1100 TentativeParseCCC(const Token &Next) {
1101 WantRemainingKeywords = false;
1102 WantTypeSpecifiers = Next.isOneOf(tok::l_paren, tok::r_paren, tok::greater,
1103 tok::l_brace, tok::identifier);
1106 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1107 // Reject any candidate that only resolves to instance members since they
1108 // aren't viable as standalone identifiers instead of member references.
1109 if (Candidate.isResolved() && !Candidate.isKeyword() &&
1110 std::all_of(Candidate.begin(), Candidate.end(),
1111 [](NamedDecl *ND) { return ND->isCXXInstanceMember(); }))
1114 return CorrectionCandidateCallback::ValidateCandidate(Candidate);
1118 /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a declaration
1119 /// specifier, TPResult::False if it is not, TPResult::Ambiguous if it could
1120 /// be either a decl-specifier or a function-style cast, and TPResult::Error
1121 /// if a parsing error was found and reported.
1123 /// If HasMissingTypename is provided, a name with a dependent scope specifier
1124 /// will be treated as ambiguous if the 'typename' keyword is missing. If this
1125 /// happens, *HasMissingTypename will be set to 'true'. This will also be used
1126 /// as an indicator that undeclared identifiers (which will trigger a later
1127 /// parse error) should be treated as types. Returns TPResult::Ambiguous in
1131 /// storage-class-specifier
1133 /// function-specifier
1136 /// [C++11] 'constexpr'
1137 /// [GNU] attributes declaration-specifiers[opt]
1139 /// storage-class-specifier:
1145 /// [GNU] '__thread'
1146 /// [C++11] 'thread_local'
1147 /// [C11] '_Thread_local'
1149 /// function-specifier:
1158 /// simple-type-specifier
1161 /// elaborated-type-specifier
1162 /// typename-specifier
1165 /// simple-type-specifier:
1166 /// '::'[opt] nested-name-specifier[opt] type-name
1167 /// '::'[opt] nested-name-specifier 'template'
1168 /// simple-template-id [TODO]
1180 /// [GNU] typeof-specifier
1181 /// [GNU] '_Complex'
1183 /// [GNU] '__auto_type'
1184 /// [C++11] 'decltype' ( expression )
1185 /// [C++1y] 'decltype' ( 'auto' )
1192 /// elaborated-type-specifier:
1193 /// class-key '::'[opt] nested-name-specifier[opt] identifier
1194 /// class-key '::'[opt] nested-name-specifier[opt] 'template'[opt]
1195 /// simple-template-id
1196 /// 'enum' '::'[opt] nested-name-specifier[opt] identifier
1202 /// 'enum' identifier[opt] '{' enumerator-list[opt] '}'
1203 /// 'enum' identifier[opt] '{' enumerator-list ',' '}'
1205 /// class-specifier:
1206 /// class-head '{' member-specification[opt] '}'
1209 /// class-key identifier[opt] base-clause[opt]
1210 /// class-key nested-name-specifier identifier base-clause[opt]
1211 /// class-key nested-name-specifier[opt] simple-template-id
1212 /// base-clause[opt]
1225 Parser::isCXXDeclarationSpecifier(Parser::TPResult BracedCastResult,
1226 bool *HasMissingTypename) {
1227 switch (Tok.getKind()) {
1228 case tok::identifier: {
1229 // Check for need to substitute AltiVec __vector keyword
1230 // for "vector" identifier.
1231 if (TryAltiVecVectorToken())
1232 return TPResult::True;
1234 const Token &Next = NextToken();
1235 // In 'foo bar', 'foo' is always a type name outside of Objective-C.
1236 if (!getLangOpts().ObjC1 && Next.is(tok::identifier))
1237 return TPResult::True;
1239 if (Next.isNot(tok::coloncolon) && Next.isNot(tok::less)) {
1240 // Determine whether this is a valid expression. If not, we will hit
1241 // a parse error one way or another. In that case, tell the caller that
1242 // this is ambiguous. Typo-correct to type and expression keywords and
1243 // to types and identifiers, in order to try to recover from errors.
1244 switch (TryAnnotateName(false /* no nested name specifier */,
1245 llvm::make_unique<TentativeParseCCC>(Next))) {
1247 return TPResult::Error;
1248 case ANK_TentativeDecl:
1249 return TPResult::False;
1250 case ANK_TemplateName:
1251 // In C++17, this could be a type template for class template argument
1252 // deduction. Try to form a type annotation for it. If we're in a
1253 // template template argument, we'll undo this when checking the
1254 // validity of the argument.
1255 if (getLangOpts().CPlusPlus17) {
1256 if (TryAnnotateTypeOrScopeToken())
1257 return TPResult::Error;
1258 if (Tok.isNot(tok::identifier))
1262 // A bare type template-name which can't be a template template
1263 // argument is an error, and was probably intended to be a type.
1264 return GreaterThanIsOperator ? TPResult::True : TPResult::False;
1265 case ANK_Unresolved:
1266 return HasMissingTypename ? TPResult::Ambiguous : TPResult::False;
1270 assert(Tok.isNot(tok::identifier) &&
1271 "TryAnnotateName succeeded without producing an annotation");
1273 // This might possibly be a type with a dependent scope specifier and
1274 // a missing 'typename' keyword. Don't use TryAnnotateName in this case,
1275 // since it will annotate as a primary expression, and we want to use the
1276 // "missing 'typename'" logic.
1277 if (TryAnnotateTypeOrScopeToken())
1278 return TPResult::Error;
1279 // If annotation failed, assume it's a non-type.
1280 // FIXME: If this happens due to an undeclared identifier, treat it as
1282 if (Tok.is(tok::identifier))
1283 return TPResult::False;
1286 // We annotated this token as something. Recurse to handle whatever we got.
1287 return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
1290 case tok::kw_typename: // typename T::type
1291 // Annotate typenames and C++ scope specifiers. If we get one, just
1292 // recurse to handle whatever we get.
1293 if (TryAnnotateTypeOrScopeToken())
1294 return TPResult::Error;
1295 return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
1297 case tok::coloncolon: { // ::foo::bar
1298 const Token &Next = NextToken();
1299 if (Next.isOneOf(tok::kw_new, // ::new
1300 tok::kw_delete)) // ::delete
1301 return TPResult::False;
1304 case tok::kw___super:
1305 case tok::kw_decltype:
1306 // Annotate typenames and C++ scope specifiers. If we get one, just
1307 // recurse to handle whatever we get.
1308 if (TryAnnotateTypeOrScopeToken())
1309 return TPResult::Error;
1310 return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
1313 // storage-class-specifier
1315 // function-specifier
1319 case tok::kw_friend:
1320 case tok::kw_typedef:
1321 case tok::kw_constexpr:
1322 // storage-class-specifier
1323 case tok::kw_register:
1324 case tok::kw_static:
1325 case tok::kw_extern:
1326 case tok::kw_mutable:
1328 case tok::kw___thread:
1329 case tok::kw_thread_local:
1330 case tok::kw__Thread_local:
1331 // function-specifier
1332 case tok::kw_inline:
1333 case tok::kw_virtual:
1334 case tok::kw_explicit:
1337 case tok::kw___module_private__:
1340 case tok::kw___unknown_anytype:
1343 // simple-type-specifier
1346 // elaborated-type-specifier
1347 // typename-specifier
1351 // elaborated-type-specifier
1353 case tok::kw_struct:
1355 case tok::kw___interface:
1360 case tok::kw_volatile:
1361 case tok::kw___private:
1362 case tok::kw___local:
1363 case tok::kw___global:
1364 case tok::kw___constant:
1365 case tok::kw___generic:
1368 case tok::kw_restrict:
1369 case tok::kw__Complex:
1370 case tok::kw___attribute:
1371 case tok::kw___auto_type:
1372 return TPResult::True;
1375 case tok::kw___declspec:
1376 case tok::kw___cdecl:
1377 case tok::kw___stdcall:
1378 case tok::kw___fastcall:
1379 case tok::kw___thiscall:
1380 case tok::kw___regcall:
1381 case tok::kw___vectorcall:
1383 case tok::kw___sptr:
1384 case tok::kw___uptr:
1385 case tok::kw___ptr64:
1386 case tok::kw___ptr32:
1387 case tok::kw___forceinline:
1388 case tok::kw___unaligned:
1389 case tok::kw__Nonnull:
1390 case tok::kw__Nullable:
1391 case tok::kw__Null_unspecified:
1392 case tok::kw___kindof:
1393 return TPResult::True;
1396 case tok::kw___pascal:
1397 return TPResult::True;
1400 case tok::kw___vector:
1401 return TPResult::True;
1403 case tok::annot_template_id: {
1404 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1405 if (TemplateId->Kind != TNK_Type_template)
1406 return TPResult::False;
1408 AnnotateTemplateIdTokenAsType();
1409 assert(Tok.is(tok::annot_typename));
1413 case tok::annot_cxxscope: // foo::bar or ::foo::bar, but already parsed
1414 // We've already annotated a scope; try to annotate a type.
1415 if (TryAnnotateTypeOrScopeToken())
1416 return TPResult::Error;
1417 if (!Tok.is(tok::annot_typename)) {
1418 // If the next token is an identifier or a type qualifier, then this
1419 // can't possibly be a valid expression either.
1420 if (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier)) {
1422 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
1423 Tok.getAnnotationRange(),
1425 if (SS.getScopeRep() && SS.getScopeRep()->isDependent()) {
1426 RevertingTentativeParsingAction PA(*this);
1427 ConsumeAnnotationToken();
1429 bool isIdentifier = Tok.is(tok::identifier);
1430 TPResult TPR = TPResult::False;
1432 TPR = isCXXDeclarationSpecifier(BracedCastResult,
1433 HasMissingTypename);
1436 TPR == TPResult::True || TPR == TPResult::Error)
1437 return TPResult::Error;
1439 if (HasMissingTypename) {
1440 // We can't tell whether this is a missing 'typename' or a valid
1442 *HasMissingTypename = true;
1443 return TPResult::Ambiguous;
1446 // Try to resolve the name. If it doesn't exist, assume it was
1447 // intended to name a type and keep disambiguating.
1448 switch (TryAnnotateName(false /* SS is not dependent */)) {
1450 return TPResult::Error;
1451 case ANK_TentativeDecl:
1452 return TPResult::False;
1453 case ANK_TemplateName:
1454 // In C++17, this could be a type template for class template
1455 // argument deduction.
1456 if (getLangOpts().CPlusPlus17) {
1457 if (TryAnnotateTypeOrScopeToken())
1458 return TPResult::Error;
1459 if (Tok.isNot(tok::identifier))
1463 // A bare type template-name which can't be a template template
1464 // argument is an error, and was probably intended to be a type.
1465 // In C++17, this could be class template argument deduction.
1466 return (getLangOpts().CPlusPlus17 || GreaterThanIsOperator)
1469 case ANK_Unresolved:
1470 return HasMissingTypename ? TPResult::Ambiguous
1476 // Annotated it, check again.
1477 assert(Tok.isNot(tok::annot_cxxscope) ||
1478 NextToken().isNot(tok::identifier));
1479 return isCXXDeclarationSpecifier(BracedCastResult,
1480 HasMissingTypename);
1483 return TPResult::False;
1485 // If that succeeded, fallthrough into the generic simple-type-id case.
1488 // The ambiguity resides in a simple-type-specifier/typename-specifier
1489 // followed by a '('. The '(' could either be the start of:
1491 // direct-declarator:
1492 // '(' declarator ')'
1494 // direct-abstract-declarator:
1495 // '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1496 // exception-specification[opt]
1497 // '(' abstract-declarator ')'
1499 // or part of a function-style cast expression:
1501 // simple-type-specifier '(' expression-list[opt] ')'
1504 // simple-type-specifier:
1506 case tok::annot_typename:
1508 // In Objective-C, we might have a protocol-qualified type.
1509 if (getLangOpts().ObjC1 && NextToken().is(tok::less)) {
1510 // Tentatively parse the protocol qualifiers.
1511 RevertingTentativeParsingAction PA(*this);
1512 ConsumeAnyToken(); // The type token
1514 TPResult TPR = TryParseProtocolQualifiers();
1515 bool isFollowedByParen = Tok.is(tok::l_paren);
1516 bool isFollowedByBrace = Tok.is(tok::l_brace);
1518 if (TPR == TPResult::Error)
1519 return TPResult::Error;
1521 if (isFollowedByParen)
1522 return TPResult::Ambiguous;
1524 if (getLangOpts().CPlusPlus11 && isFollowedByBrace)
1525 return BracedCastResult;
1527 return TPResult::True;
1532 case tok::kw_wchar_t:
1533 case tok::kw_char8_t:
1534 case tok::kw_char16_t:
1535 case tok::kw_char32_t:
1540 case tok::kw___int64:
1541 case tok::kw___int128:
1542 case tok::kw_signed:
1543 case tok::kw_unsigned:
1546 case tok::kw_double:
1547 case tok::kw__Float16:
1548 case tok::kw___float128:
1550 case tok::annot_decltype:
1551 if (NextToken().is(tok::l_paren))
1552 return TPResult::Ambiguous;
1554 // This is a function-style cast in all cases we disambiguate other than
1557 // enum E : int { a = 4 }; // enum
1558 // enum E : int { 4 }; // bit-field
1560 if (getLangOpts().CPlusPlus11 && NextToken().is(tok::l_brace))
1561 return BracedCastResult;
1563 if (isStartOfObjCClassMessageMissingOpenBracket())
1564 return TPResult::False;
1566 return TPResult::True;
1568 // GNU typeof support.
1569 case tok::kw_typeof: {
1570 if (NextToken().isNot(tok::l_paren))
1571 return TPResult::True;
1573 RevertingTentativeParsingAction PA(*this);
1575 TPResult TPR = TryParseTypeofSpecifier();
1576 bool isFollowedByParen = Tok.is(tok::l_paren);
1577 bool isFollowedByBrace = Tok.is(tok::l_brace);
1579 if (TPR == TPResult::Error)
1580 return TPResult::Error;
1582 if (isFollowedByParen)
1583 return TPResult::Ambiguous;
1585 if (getLangOpts().CPlusPlus11 && isFollowedByBrace)
1586 return BracedCastResult;
1588 return TPResult::True;
1591 // C++0x type traits support
1592 case tok::kw___underlying_type:
1593 return TPResult::True;
1596 case tok::kw__Atomic:
1597 return TPResult::True;
1600 return TPResult::False;
1604 bool Parser::isCXXDeclarationSpecifierAType() {
1605 switch (Tok.getKind()) {
1606 // typename-specifier
1607 case tok::annot_decltype:
1608 case tok::annot_template_id:
1609 case tok::annot_typename:
1610 case tok::kw_typeof:
1611 case tok::kw___underlying_type:
1614 // elaborated-type-specifier
1616 case tok::kw_struct:
1618 case tok::kw___interface:
1622 // simple-type-specifier
1624 case tok::kw_wchar_t:
1625 case tok::kw_char8_t:
1626 case tok::kw_char16_t:
1627 case tok::kw_char32_t:
1632 case tok::kw___int64:
1633 case tok::kw___int128:
1634 case tok::kw_signed:
1635 case tok::kw_unsigned:
1638 case tok::kw_double:
1639 case tok::kw__Float16:
1640 case tok::kw___float128:
1642 case tok::kw___unknown_anytype:
1643 case tok::kw___auto_type:
1647 return getLangOpts().CPlusPlus11;
1649 case tok::kw__Atomic:
1651 return NextToken().is(tok::l_paren);
1658 /// [GNU] typeof-specifier:
1659 /// 'typeof' '(' expressions ')'
1660 /// 'typeof' '(' type-name ')'
1662 Parser::TPResult Parser::TryParseTypeofSpecifier() {
1663 assert(Tok.is(tok::kw_typeof) && "Expected 'typeof'!");
1666 assert(Tok.is(tok::l_paren) && "Expected '('");
1667 // Parse through the parens after 'typeof'.
1669 if (!SkipUntil(tok::r_paren, StopAtSemi))
1670 return TPResult::Error;
1672 return TPResult::Ambiguous;
1675 /// [ObjC] protocol-qualifiers:
1676 //// '<' identifier-list '>'
1677 Parser::TPResult Parser::TryParseProtocolQualifiers() {
1678 assert(Tok.is(tok::less) && "Expected '<' for qualifier list");
1681 if (Tok.isNot(tok::identifier))
1682 return TPResult::Error;
1685 if (Tok.is(tok::comma)) {
1690 if (Tok.is(tok::greater)) {
1692 return TPResult::Ambiguous;
1696 return TPResult::Error;
1699 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
1700 /// a constructor-style initializer, when parsing declaration statements.
1701 /// Returns true for function declarator and false for constructor-style
1703 /// If during the disambiguation process a parsing error is encountered,
1704 /// the function returns true to let the declaration parsing code handle it.
1706 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1707 /// exception-specification[opt]
1709 bool Parser::isCXXFunctionDeclarator(bool *IsAmbiguous) {
1712 // The ambiguity arising from the similarity between a function-style cast and
1713 // a declaration mentioned in 6.8 can also occur in the context of a
1714 // declaration. In that context, the choice is between a function declaration
1715 // with a redundant set of parentheses around a parameter name and an object
1716 // declaration with a function-style cast as the initializer. Just as for the
1717 // ambiguities mentioned in 6.8, the resolution is to consider any construct
1718 // that could possibly be a declaration a declaration.
1720 RevertingTentativeParsingAction PA(*this);
1723 bool InvalidAsDeclaration = false;
1724 TPResult TPR = TryParseParameterDeclarationClause(&InvalidAsDeclaration);
1725 if (TPR == TPResult::Ambiguous) {
1726 if (Tok.isNot(tok::r_paren))
1727 TPR = TPResult::False;
1729 const Token &Next = NextToken();
1730 if (Next.isOneOf(tok::amp, tok::ampamp, tok::kw_const, tok::kw_volatile,
1731 tok::kw_throw, tok::kw_noexcept, tok::l_square,
1732 tok::l_brace, tok::kw_try, tok::equal, tok::arrow) ||
1733 isCXX11VirtSpecifier(Next))
1734 // The next token cannot appear after a constructor-style initializer,
1735 // and can appear next in a function definition. This must be a function
1737 TPR = TPResult::True;
1738 else if (InvalidAsDeclaration)
1739 // Use the absence of 'typename' as a tie-breaker.
1740 TPR = TPResult::False;
1744 if (IsAmbiguous && TPR == TPResult::Ambiguous)
1745 *IsAmbiguous = true;
1747 // In case of an error, let the declaration parsing code handle it.
1748 return TPR != TPResult::False;
1751 /// parameter-declaration-clause:
1752 /// parameter-declaration-list[opt] '...'[opt]
1753 /// parameter-declaration-list ',' '...'
1755 /// parameter-declaration-list:
1756 /// parameter-declaration
1757 /// parameter-declaration-list ',' parameter-declaration
1759 /// parameter-declaration:
1760 /// attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
1761 /// attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
1762 /// '=' assignment-expression
1763 /// attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
1765 /// attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
1766 /// attributes[opt] '=' assignment-expression
1769 Parser::TryParseParameterDeclarationClause(bool *InvalidAsDeclaration,
1770 bool VersusTemplateArgument) {
1772 if (Tok.is(tok::r_paren))
1773 return TPResult::Ambiguous;
1775 // parameter-declaration-list[opt] '...'[opt]
1776 // parameter-declaration-list ',' '...'
1778 // parameter-declaration-list:
1779 // parameter-declaration
1780 // parameter-declaration-list ',' parameter-declaration
1784 if (Tok.is(tok::ellipsis)) {
1786 if (Tok.is(tok::r_paren))
1787 return TPResult::True; // '...)' is a sign of a function declarator.
1789 return TPResult::False;
1792 // An attribute-specifier-seq here is a sign of a function declarator.
1793 if (isCXX11AttributeSpecifier(/*Disambiguate*/false,
1794 /*OuterMightBeMessageSend*/true))
1795 return TPResult::True;
1797 ParsedAttributes attrs(AttrFactory);
1798 MaybeParseMicrosoftAttributes(attrs);
1800 // decl-specifier-seq
1801 // A parameter-declaration's initializer must be preceded by an '=', so
1802 // decl-specifier-seq '{' is not a parameter in C++11.
1803 TPResult TPR = isCXXDeclarationSpecifier(TPResult::False,
1804 InvalidAsDeclaration);
1806 if (VersusTemplateArgument && TPR == TPResult::True) {
1807 // Consume the decl-specifier-seq. We have to look past it, since a
1808 // type-id might appear here in a template argument.
1809 bool SeenType = false;
1811 SeenType |= isCXXDeclarationSpecifierAType();
1812 if (TryConsumeDeclarationSpecifier() == TPResult::Error)
1813 return TPResult::Error;
1815 // If we see a parameter name, this can't be a template argument.
1816 if (SeenType && Tok.is(tok::identifier))
1817 return TPResult::True;
1819 TPR = isCXXDeclarationSpecifier(TPResult::False,
1820 InvalidAsDeclaration);
1821 if (TPR == TPResult::Error)
1823 } while (TPR != TPResult::False);
1824 } else if (TPR == TPResult::Ambiguous) {
1825 // Disambiguate what follows the decl-specifier.
1826 if (TryConsumeDeclarationSpecifier() == TPResult::Error)
1827 return TPResult::Error;
1832 // abstract-declarator[opt]
1833 TPR = TryParseDeclarator(true/*mayBeAbstract*/);
1834 if (TPR != TPResult::Ambiguous)
1837 // [GNU] attributes[opt]
1838 if (Tok.is(tok::kw___attribute))
1839 return TPResult::True;
1841 // If we're disambiguating a template argument in a default argument in
1842 // a class definition versus a parameter declaration, an '=' here
1843 // disambiguates the parse one way or the other.
1844 // If this is a parameter, it must have a default argument because
1845 // (a) the previous parameter did, and
1846 // (b) this must be the first declaration of the function, so we can't
1847 // inherit any default arguments from elsewhere.
1848 // If we see an ')', then we've reached the end of a
1849 // parameter-declaration-clause, and the last param is missing its default
1851 if (VersusTemplateArgument)
1852 return Tok.isOneOf(tok::equal, tok::r_paren) ? TPResult::True
1855 if (Tok.is(tok::equal)) {
1856 // '=' assignment-expression
1857 // Parse through assignment-expression.
1858 // FIXME: assignment-expression may contain an unparenthesized comma.
1859 if (!SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch))
1860 return TPResult::Error;
1863 if (Tok.is(tok::ellipsis)) {
1865 if (Tok.is(tok::r_paren))
1866 return TPResult::True; // '...)' is a sign of a function declarator.
1868 return TPResult::False;
1871 if (!TryConsumeToken(tok::comma))
1875 return TPResult::Ambiguous;
1878 /// TryParseFunctionDeclarator - We parsed a '(' and we want to try to continue
1879 /// parsing as a function declarator.
1880 /// If TryParseFunctionDeclarator fully parsed the function declarator, it will
1881 /// return TPResult::Ambiguous, otherwise it will return either False() or
1884 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1885 /// exception-specification[opt]
1887 /// exception-specification:
1888 /// 'throw' '(' type-id-list[opt] ')'
1890 Parser::TPResult Parser::TryParseFunctionDeclarator() {
1892 // The '(' is already parsed.
1894 TPResult TPR = TryParseParameterDeclarationClause();
1895 if (TPR == TPResult::Ambiguous && Tok.isNot(tok::r_paren))
1896 TPR = TPResult::False;
1898 if (TPR == TPResult::False || TPR == TPResult::Error)
1901 // Parse through the parens.
1902 if (!SkipUntil(tok::r_paren, StopAtSemi))
1903 return TPResult::Error;
1906 while (Tok.isOneOf(tok::kw_const, tok::kw_volatile, tok::kw___unaligned,
1910 // ref-qualifier[opt]
1911 if (Tok.isOneOf(tok::amp, tok::ampamp))
1914 // exception-specification
1915 if (Tok.is(tok::kw_throw)) {
1917 if (Tok.isNot(tok::l_paren))
1918 return TPResult::Error;
1920 // Parse through the parens after 'throw'.
1922 if (!SkipUntil(tok::r_paren, StopAtSemi))
1923 return TPResult::Error;
1925 if (Tok.is(tok::kw_noexcept)) {
1927 // Possibly an expression as well.
1928 if (Tok.is(tok::l_paren)) {
1929 // Find the matching rparen.
1931 if (!SkipUntil(tok::r_paren, StopAtSemi))
1932 return TPResult::Error;
1936 return TPResult::Ambiguous;
1939 /// '[' constant-expression[opt] ']'
1941 Parser::TPResult Parser::TryParseBracketDeclarator() {
1943 if (!SkipUntil(tok::r_square, StopAtSemi))
1944 return TPResult::Error;
1946 return TPResult::Ambiguous;