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] ';'
78 /// (if AllowForRangeDecl specified)
79 /// for ( for-range-declaration : for-range-initializer ) statement
80 /// for-range-declaration:
81 /// attribute-specifier-seqopt type-specifier-seq declarator
82 bool Parser::isCXXSimpleDeclaration(bool AllowForRangeDecl) {
84 // There is an ambiguity in the grammar involving expression-statements and
85 // declarations: An expression-statement with a function-style explicit type
86 // conversion (5.2.3) as its leftmost subexpression can be indistinguishable
87 // from a declaration where the first declarator starts with a '('. In those
88 // cases the statement is a declaration. [Note: To disambiguate, the whole
89 // statement might have to be examined to determine if it is an
90 // expression-statement or a declaration].
93 // The disambiguation is purely syntactic; that is, the meaning of the names
94 // occurring in such a statement, beyond whether they are type-names or not,
95 // is not generally used in or changed by the disambiguation. Class
96 // templates are instantiated as necessary to determine if a qualified name
97 // is a type-name. Disambiguation precedes parsing, and a statement
98 // disambiguated as a declaration may be an ill-formed declaration.
100 // We don't have to parse all of the decl-specifier-seq part. There's only
101 // an ambiguity if the first decl-specifier is
102 // simple-type-specifier/typename-specifier followed by a '(', which may
103 // indicate a function-style cast expression.
104 // isCXXDeclarationSpecifier will return TPResult::Ambiguous only in such
107 bool InvalidAsDeclaration = false;
108 TPResult TPR = isCXXDeclarationSpecifier(TPResult::False,
109 &InvalidAsDeclaration);
110 if (TPR != TPResult::Ambiguous)
111 return TPR != TPResult::False; // Returns true for TPResult::True or
114 // FIXME: TryParseSimpleDeclaration doesn't look past the first initializer,
115 // and so gets some cases wrong. We can't carry on if we've already seen
116 // something which makes this statement invalid as a declaration in this case,
117 // since it can cause us to misparse valid code. Revisit this once
118 // TryParseInitDeclaratorList is fixed.
119 if (InvalidAsDeclaration)
122 // FIXME: Add statistics about the number of ambiguous statements encountered
123 // and how they were resolved (number of declarations+number of expressions).
125 // Ok, we have a simple-type-specifier/typename-specifier followed by a '(',
126 // or an identifier which doesn't resolve as anything. We need tentative
130 RevertingTentativeParsingAction PA(*this);
131 TPR = TryParseSimpleDeclaration(AllowForRangeDecl);
134 // In case of an error, let the declaration parsing code handle it.
135 if (TPR == TPResult::Error)
138 // Declarations take precedence over expressions.
139 if (TPR == TPResult::Ambiguous)
140 TPR = TPResult::True;
142 assert(TPR == TPResult::True || TPR == TPResult::False);
143 return TPR == TPResult::True;
146 /// Try to consume a token sequence that we've already identified as
147 /// (potentially) starting a decl-specifier.
148 Parser::TPResult Parser::TryConsumeDeclarationSpecifier() {
149 switch (Tok.getKind()) {
150 case tok::kw__Atomic:
151 if (NextToken().isNot(tok::l_paren)) {
157 case tok::kw___attribute:
158 case tok::kw___underlying_type: {
160 if (Tok.isNot(tok::l_paren))
161 return TPResult::Error;
163 if (!SkipUntil(tok::r_paren))
164 return TPResult::Error;
171 case tok::kw___interface:
173 // elaborated-type-specifier:
174 // class-key attribute-specifier-seq[opt]
175 // nested-name-specifier[opt] identifier
176 // class-key nested-name-specifier[opt] template[opt] simple-template-id
177 // enum nested-name-specifier[opt] identifier
179 // FIXME: We don't support class-specifiers nor enum-specifiers here.
183 while (Tok.isOneOf(tok::l_square, tok::kw___attribute, tok::kw___declspec,
185 if (Tok.is(tok::l_square)) {
187 if (!SkipUntil(tok::r_square))
188 return TPResult::Error;
191 if (Tok.isNot(tok::l_paren))
192 return TPResult::Error;
194 if (!SkipUntil(tok::r_paren))
195 return TPResult::Error;
199 if (Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
200 tok::annot_template_id) &&
201 TryAnnotateCXXScopeToken())
202 return TPResult::Error;
203 if (Tok.is(tok::annot_cxxscope))
205 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id))
206 return TPResult::Error;
210 case tok::annot_cxxscope:
216 if (getLangOpts().ObjC1 && Tok.is(tok::less))
217 return TryParseProtocolQualifiers();
221 return TPResult::Ambiguous;
224 /// simple-declaration:
225 /// decl-specifier-seq init-declarator-list[opt] ';'
227 /// (if AllowForRangeDecl specified)
228 /// for ( for-range-declaration : for-range-initializer ) statement
229 /// for-range-declaration:
230 /// attribute-specifier-seqopt type-specifier-seq declarator
232 Parser::TPResult Parser::TryParseSimpleDeclaration(bool AllowForRangeDecl) {
233 if (TryConsumeDeclarationSpecifier() == TPResult::Error)
234 return TPResult::Error;
236 // Two decl-specifiers in a row conclusively disambiguate this as being a
237 // simple-declaration. Don't bother calling isCXXDeclarationSpecifier in the
238 // overwhelmingly common case that the next token is a '('.
239 if (Tok.isNot(tok::l_paren)) {
240 TPResult TPR = isCXXDeclarationSpecifier();
241 if (TPR == TPResult::Ambiguous)
242 return TPResult::True;
243 if (TPR == TPResult::True || TPR == TPResult::Error)
245 assert(TPR == TPResult::False);
248 TPResult TPR = TryParseInitDeclaratorList();
249 if (TPR != TPResult::Ambiguous)
252 if (Tok.isNot(tok::semi) && (!AllowForRangeDecl || Tok.isNot(tok::colon)))
253 return TPResult::False;
255 return TPResult::Ambiguous;
258 /// Tentatively parse an init-declarator-list in order to disambiguate it from
261 /// init-declarator-list:
263 /// init-declarator-list ',' init-declarator
266 /// declarator initializer[opt]
267 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] initializer[opt]
270 /// brace-or-equal-initializer
271 /// '(' expression-list ')'
273 /// brace-or-equal-initializer:
274 /// '=' initializer-clause
275 /// [C++11] braced-init-list
277 /// initializer-clause:
278 /// assignment-expression
281 /// braced-init-list:
282 /// '{' initializer-list ','[opt] '}'
285 Parser::TPResult Parser::TryParseInitDeclaratorList() {
288 TPResult TPR = TryParseDeclarator(false/*mayBeAbstract*/);
289 if (TPR != TPResult::Ambiguous)
292 // [GNU] simple-asm-expr[opt] attributes[opt]
293 if (Tok.isOneOf(tok::kw_asm, tok::kw___attribute))
294 return TPResult::True;
297 if (Tok.is(tok::l_paren)) {
298 // Parse through the parens.
300 if (!SkipUntil(tok::r_paren, StopAtSemi))
301 return TPResult::Error;
302 } else if (Tok.is(tok::l_brace)) {
303 // A left-brace here is sufficient to disambiguate the parse; an
304 // expression can never be followed directly by a braced-init-list.
305 return TPResult::True;
306 } else if (Tok.is(tok::equal) || isTokIdentifier_in()) {
307 // MSVC and g++ won't examine the rest of declarators if '=' is
308 // encountered; they just conclude that we have a declaration.
309 // EDG parses the initializer completely, which is the proper behavior
312 // At present, Clang follows MSVC and g++, since the parser does not have
313 // the ability to parse an expression fully without recording the
314 // results of that parse.
315 // FIXME: Handle this case correctly.
317 // Also allow 'in' after an Objective-C declaration as in:
318 // for (int (^b)(void) in array). Ideally this should be done in the
319 // context of parsing for-init-statement of a foreach statement only. But,
320 // in any other context 'in' is invalid after a declaration and parser
321 // issues the error regardless of outcome of this decision.
322 // FIXME: Change if above assumption does not hold.
323 return TPResult::True;
326 if (!TryConsumeToken(tok::comma))
330 return TPResult::Ambiguous;
333 struct Parser::ConditionDeclarationOrInitStatementState {
335 bool CanBeExpression = true;
336 bool CanBeCondition = true;
337 bool CanBeInitStatement;
339 ConditionDeclarationOrInitStatementState(Parser &P, bool CanBeInitStatement)
340 : P(P), CanBeInitStatement(CanBeInitStatement) {}
342 void markNotExpression() {
343 CanBeExpression = false;
345 if (CanBeCondition && CanBeInitStatement) {
346 // FIXME: Unify the parsing codepaths for condition variables and
347 // simple-declarations so that we don't need to eagerly figure out which
348 // kind we have here. (Just parse init-declarators until we reach a
349 // semicolon or right paren.)
350 RevertingTentativeParsingAction PA(P);
351 P.SkipUntil(tok::r_paren, tok::semi, StopBeforeMatch);
352 if (P.Tok.isNot(tok::r_paren))
353 CanBeCondition = false;
354 if (P.Tok.isNot(tok::semi))
355 CanBeInitStatement = false;
359 bool markNotCondition() {
360 CanBeCondition = false;
361 return !CanBeInitStatement || !CanBeExpression;
364 bool update(TPResult IsDecl) {
369 case TPResult::False:
370 CanBeCondition = CanBeInitStatement = false;
372 case TPResult::Ambiguous:
374 case TPResult::Error:
375 CanBeExpression = CanBeCondition = CanBeInitStatement = false;
378 llvm_unreachable("unknown tentative parse result");
381 ConditionOrInitStatement result() const {
382 assert(CanBeExpression + CanBeCondition + CanBeInitStatement < 2 &&
383 "result called but not yet resolved");
385 return ConditionOrInitStatement::Expression;
387 return ConditionOrInitStatement::ConditionDecl;
388 if (CanBeInitStatement)
389 return ConditionOrInitStatement::InitStmtDecl;
390 return ConditionOrInitStatement::Error;
394 /// \brief Disambiguates between a declaration in a condition, a
395 /// simple-declaration in an init-statement, and an expression for
396 /// a condition of a if/switch statement.
400 /// type-specifier-seq declarator '=' assignment-expression
401 /// [C++11] type-specifier-seq declarator '=' initializer-clause
402 /// [C++11] type-specifier-seq declarator braced-init-list
403 /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
404 /// '=' assignment-expression
405 /// simple-declaration:
406 /// decl-specifier-seq init-declarator-list[opt] ';'
408 /// Note that, unlike isCXXSimpleDeclaration, we must disambiguate all the way
409 /// to the ';' to disambiguate cases like 'int(x))' (an expression) from
410 /// 'int(x);' (a simple-declaration in an init-statement).
411 Parser::ConditionOrInitStatement
412 Parser::isCXXConditionDeclarationOrInitStatement(bool CanBeInitStatement) {
413 ConditionDeclarationOrInitStatementState State(*this, CanBeInitStatement);
415 if (State.update(isCXXDeclarationSpecifier()))
416 return State.result();
418 // It might be a declaration; we need tentative parsing.
419 RevertingTentativeParsingAction PA(*this);
421 // FIXME: A tag definition unambiguously tells us this is an init-statement.
422 if (State.update(TryConsumeDeclarationSpecifier()))
423 return State.result();
424 assert(Tok.is(tok::l_paren) && "Expected '('");
427 // Consume a declarator.
428 if (State.update(TryParseDeclarator(false/*mayBeAbstract*/)))
429 return State.result();
431 // Attributes, asm label, or an initializer imply this is not an expression.
432 // FIXME: Disambiguate properly after an = instead of assuming that it's a
433 // valid declaration.
434 if (Tok.isOneOf(tok::equal, tok::kw_asm, tok::kw___attribute) ||
435 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace))) {
436 State.markNotExpression();
437 return State.result();
440 // At this point, it can't be a condition any more, because a condition
441 // must have a brace-or-equal-initializer.
442 if (State.markNotCondition())
443 return State.result();
445 // A parenthesized initializer could be part of an expression or a
446 // simple-declaration.
447 if (Tok.is(tok::l_paren)) {
449 SkipUntil(tok::r_paren, StopAtSemi);
452 if (!TryConsumeToken(tok::comma))
456 // We reached the end. If it can now be some kind of decl, then it is.
457 if (State.CanBeCondition && Tok.is(tok::r_paren))
458 return ConditionOrInitStatement::ConditionDecl;
459 else if (State.CanBeInitStatement && Tok.is(tok::semi))
460 return ConditionOrInitStatement::InitStmtDecl;
462 return ConditionOrInitStatement::Expression;
465 /// \brief Determine whether the next set of tokens contains a type-id.
467 /// The context parameter states what context we're parsing right
468 /// now, which affects how this routine copes with the token
469 /// following the type-id. If the context is TypeIdInParens, we have
470 /// already parsed the '(' and we will cease lookahead when we hit
471 /// the corresponding ')'. If the context is
472 /// TypeIdAsTemplateArgument, we've already parsed the '<' or ','
473 /// before this template argument, and will cease lookahead when we
474 /// hit a '>', '>>' (in C++0x), or ','. Returns true for a type-id
475 /// and false for an expression. If during the disambiguation
476 /// process a parsing error is encountered, the function returns
477 /// true to let the declaration parsing code handle it.
480 /// type-specifier-seq abstract-declarator[opt]
482 bool Parser::isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous) {
487 // The ambiguity arising from the similarity between a function-style cast and
488 // a type-id can occur in different contexts. The ambiguity appears as a
489 // choice between a function-style cast expression and a declaration of a
490 // type. The resolution is that any construct that could possibly be a type-id
491 // in its syntactic context shall be considered a type-id.
493 TPResult TPR = isCXXDeclarationSpecifier();
494 if (TPR != TPResult::Ambiguous)
495 return TPR != TPResult::False; // Returns true for TPResult::True or
498 // FIXME: Add statistics about the number of ambiguous statements encountered
499 // and how they were resolved (number of declarations+number of expressions).
501 // Ok, we have a simple-type-specifier/typename-specifier followed by a '('.
502 // We need tentative parsing...
504 RevertingTentativeParsingAction PA(*this);
506 // type-specifier-seq
507 TryConsumeDeclarationSpecifier();
508 assert(Tok.is(tok::l_paren) && "Expected '('");
511 TPR = TryParseDeclarator(true/*mayBeAbstract*/, false/*mayHaveIdentifier*/);
513 // In case of an error, let the declaration parsing code handle it.
514 if (TPR == TPResult::Error)
515 TPR = TPResult::True;
517 if (TPR == TPResult::Ambiguous) {
518 // We are supposed to be inside parens, so if after the abstract declarator
519 // we encounter a ')' this is a type-id, otherwise it's an expression.
520 if (Context == TypeIdInParens && Tok.is(tok::r_paren)) {
521 TPR = TPResult::True;
524 // We are supposed to be inside a template argument, so if after
525 // the abstract declarator we encounter a '>', '>>' (in C++0x), or
526 // ',', this is a type-id. Otherwise, it's an expression.
527 } else if (Context == TypeIdAsTemplateArgument &&
528 (Tok.isOneOf(tok::greater, tok::comma) ||
529 (getLangOpts().CPlusPlus11 && Tok.is(tok::greatergreater)))) {
530 TPR = TPResult::True;
534 TPR = TPResult::False;
537 assert(TPR == TPResult::True || TPR == TPResult::False);
538 return TPR == TPResult::True;
541 /// \brief Returns true if this is a C++11 attribute-specifier. Per
542 /// C++11 [dcl.attr.grammar]p6, two consecutive left square bracket tokens
543 /// always introduce an attribute. In Objective-C++11, this rule does not
544 /// apply if either '[' begins a message-send.
546 /// If Disambiguate is true, we try harder to determine whether a '[[' starts
547 /// an attribute-specifier, and return CAK_InvalidAttributeSpecifier if not.
549 /// If OuterMightBeMessageSend is true, we assume the outer '[' is either an
550 /// Obj-C message send or the start of an attribute. Otherwise, we assume it
551 /// is not an Obj-C message send.
553 /// C++11 [dcl.attr.grammar]:
555 /// attribute-specifier:
556 /// '[' '[' attribute-list ']' ']'
557 /// alignment-specifier
561 /// attribute-list ',' attribute[opt]
563 /// attribute-list ',' attribute '...'
566 /// attribute-token attribute-argument-clause[opt]
570 /// identifier '::' identifier
572 /// attribute-argument-clause:
573 /// '(' balanced-token-seq ')'
574 Parser::CXX11AttributeKind
575 Parser::isCXX11AttributeSpecifier(bool Disambiguate,
576 bool OuterMightBeMessageSend) {
577 if (Tok.is(tok::kw_alignas))
578 return CAK_AttributeSpecifier;
580 if (Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square))
581 return CAK_NotAttributeSpecifier;
583 // No tentative parsing if we don't need to look for ']]' or a lambda.
584 if (!Disambiguate && !getLangOpts().ObjC1)
585 return CAK_AttributeSpecifier;
587 RevertingTentativeParsingAction PA(*this);
589 // Opening brackets were checked for above.
592 // Outside Obj-C++11, treat anything with a matching ']]' as an attribute.
593 if (!getLangOpts().ObjC1) {
596 bool IsAttribute = SkipUntil(tok::r_square);
597 IsAttribute &= Tok.is(tok::r_square);
599 return IsAttribute ? CAK_AttributeSpecifier : CAK_InvalidAttributeSpecifier;
602 // In Obj-C++11, we need to distinguish four situations:
603 // 1a) int x[[attr]]; C++11 attribute.
604 // 1b) [[attr]]; C++11 statement attribute.
605 // 2) int x[[obj](){ return 1; }()]; Lambda in array size/index.
606 // 3a) int x[[obj get]]; Message send in array size/index.
607 // 3b) [[Class alloc] init]; Message send in message send.
608 // 4) [[obj]{ return self; }() doStuff]; Lambda in message send.
609 // (1) is an attribute, (2) is ill-formed, and (3) and (4) are accepted.
611 // If we have a lambda-introducer, then this is definitely not a message send.
612 // FIXME: If this disambiguation is too slow, fold the tentative lambda parse
613 // into the tentative attribute parse below.
614 LambdaIntroducer Intro;
615 if (!TryParseLambdaIntroducer(Intro)) {
616 // A lambda cannot end with ']]', and an attribute must.
617 bool IsAttribute = Tok.is(tok::r_square);
620 // Case 1: C++11 attribute.
621 return CAK_AttributeSpecifier;
623 if (OuterMightBeMessageSend)
624 // Case 4: Lambda in message send.
625 return CAK_NotAttributeSpecifier;
627 // Case 2: Lambda in array size / index.
628 return CAK_InvalidAttributeSpecifier;
633 // If we don't have a lambda-introducer, then we have an attribute or a
635 bool IsAttribute = true;
636 while (Tok.isNot(tok::r_square)) {
637 if (Tok.is(tok::comma)) {
638 // Case 1: Stray commas can only occur in attributes.
639 return CAK_AttributeSpecifier;
642 // Parse the attribute-token, if present.
643 // C++11 [dcl.attr.grammar]:
644 // If a keyword or an alternative token that satisfies the syntactic
645 // requirements of an identifier is contained in an attribute-token,
646 // it is considered an identifier.
648 if (!TryParseCXX11AttributeIdentifier(Loc)) {
652 if (Tok.is(tok::coloncolon)) {
654 if (!TryParseCXX11AttributeIdentifier(Loc)) {
660 // Parse the attribute-argument-clause, if present.
661 if (Tok.is(tok::l_paren)) {
663 if (!SkipUntil(tok::r_paren)) {
669 TryConsumeToken(tok::ellipsis);
671 if (!TryConsumeToken(tok::comma))
675 // An attribute must end ']]'.
677 if (Tok.is(tok::r_square)) {
679 IsAttribute = Tok.is(tok::r_square);
686 // Case 1: C++11 statement attribute.
687 return CAK_AttributeSpecifier;
689 // Case 3: Message send.
690 return CAK_NotAttributeSpecifier;
693 Parser::TPResult Parser::TryParsePtrOperatorSeq() {
695 if (Tok.isOneOf(tok::coloncolon, tok::identifier))
696 if (TryAnnotateCXXScopeToken(true))
697 return TPResult::Error;
699 if (Tok.isOneOf(tok::star, tok::amp, tok::caret, tok::ampamp) ||
700 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::star))) {
703 while (Tok.isOneOf(tok::kw_const, tok::kw_volatile, tok::kw_restrict,
704 tok::kw__Nonnull, tok::kw__Nullable,
705 tok::kw__Null_unspecified))
708 return TPResult::True;
713 /// operator-function-id:
714 /// 'operator' operator
717 /// new delete new[] delete[] + - * / % ^ [...]
719 /// conversion-function-id:
720 /// 'operator' conversion-type-id
722 /// conversion-type-id:
723 /// type-specifier-seq conversion-declarator[opt]
725 /// conversion-declarator:
726 /// ptr-operator conversion-declarator[opt]
728 /// literal-operator-id:
729 /// 'operator' string-literal identifier
730 /// 'operator' user-defined-string-literal
731 Parser::TPResult Parser::TryParseOperatorId() {
732 assert(Tok.is(tok::kw_operator));
735 // Maybe this is an operator-function-id.
736 switch (Tok.getKind()) {
737 case tok::kw_new: case tok::kw_delete:
739 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
743 return TPResult::True;
745 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemOnly) \
747 #define OVERLOADED_OPERATOR_MULTI(Name, Spelling, Unary, Binary, MemOnly)
748 #include "clang/Basic/OperatorKinds.def"
750 return TPResult::True;
753 if (NextToken().is(tok::r_square)) {
756 return TPResult::True;
761 if (NextToken().is(tok::r_paren)) {
764 return TPResult::True;
772 // Maybe this is a literal-operator-id.
773 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
774 bool FoundUDSuffix = false;
776 FoundUDSuffix |= Tok.hasUDSuffix();
777 ConsumeStringToken();
778 } while (isTokenStringLiteral());
780 if (!FoundUDSuffix) {
781 if (Tok.is(tok::identifier))
784 return TPResult::Error;
786 return TPResult::True;
789 // Maybe this is a conversion-function-id.
790 bool AnyDeclSpecifiers = false;
792 TPResult TPR = isCXXDeclarationSpecifier();
793 if (TPR == TPResult::Error)
795 if (TPR == TPResult::False) {
796 if (!AnyDeclSpecifiers)
797 return TPResult::Error;
800 if (TryConsumeDeclarationSpecifier() == TPResult::Error)
801 return TPResult::Error;
802 AnyDeclSpecifiers = true;
804 return TryParsePtrOperatorSeq();
808 /// direct-declarator
809 /// ptr-operator declarator
811 /// direct-declarator:
813 /// direct-declarator '(' parameter-declaration-clause ')'
814 /// cv-qualifier-seq[opt] exception-specification[opt]
815 /// direct-declarator '[' constant-expression[opt] ']'
816 /// '(' declarator ')'
817 /// [GNU] '(' attributes declarator ')'
819 /// abstract-declarator:
820 /// ptr-operator abstract-declarator[opt]
821 /// direct-abstract-declarator
824 /// direct-abstract-declarator:
825 /// direct-abstract-declarator[opt]
826 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
827 /// exception-specification[opt]
828 /// direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
829 /// '(' abstract-declarator ')'
832 /// '*' cv-qualifier-seq[opt]
834 /// [C++0x] '&&' [TODO]
835 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
837 /// cv-qualifier-seq:
838 /// cv-qualifier cv-qualifier-seq[opt]
845 /// '...'[opt] id-expression
849 /// qualified-id [TODO]
853 /// operator-function-id
854 /// conversion-function-id
855 /// literal-operator-id
856 /// '~' class-name [TODO]
857 /// '~' decltype-specifier [TODO]
858 /// template-id [TODO]
860 Parser::TPResult Parser::TryParseDeclarator(bool mayBeAbstract,
861 bool mayHaveIdentifier) {
864 // ptr-operator declarator
865 if (TryParsePtrOperatorSeq() == TPResult::Error)
866 return TPResult::Error;
868 // direct-declarator:
869 // direct-abstract-declarator:
870 if (Tok.is(tok::ellipsis))
873 if ((Tok.isOneOf(tok::identifier, tok::kw_operator) ||
874 (Tok.is(tok::annot_cxxscope) && (NextToken().is(tok::identifier) ||
875 NextToken().is(tok::kw_operator)))) &&
878 if (Tok.is(tok::annot_cxxscope))
880 else if (Tok.is(tok::identifier))
881 TentativelyDeclaredIdentifiers.push_back(Tok.getIdentifierInfo());
882 if (Tok.is(tok::kw_operator)) {
883 if (TryParseOperatorId() == TPResult::Error)
884 return TPResult::Error;
887 } else if (Tok.is(tok::l_paren)) {
890 (Tok.is(tok::r_paren) || // 'int()' is a function.
891 // 'int(...)' is a function.
892 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren)) ||
893 isDeclarationSpecifier())) { // 'int(int)' is a function.
894 // '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
895 // exception-specification[opt]
896 TPResult TPR = TryParseFunctionDeclarator();
897 if (TPR != TPResult::Ambiguous)
900 // '(' declarator ')'
901 // '(' attributes declarator ')'
902 // '(' abstract-declarator ')'
903 if (Tok.isOneOf(tok::kw___attribute, tok::kw___declspec, tok::kw___cdecl,
904 tok::kw___stdcall, tok::kw___fastcall, tok::kw___thiscall,
905 tok::kw___vectorcall))
906 return TPResult::True; // attributes indicate declaration
907 TPResult TPR = TryParseDeclarator(mayBeAbstract, mayHaveIdentifier);
908 if (TPR != TPResult::Ambiguous)
910 if (Tok.isNot(tok::r_paren))
911 return TPResult::False;
914 } else if (!mayBeAbstract) {
915 return TPResult::False;
919 TPResult TPR(TPResult::Ambiguous);
921 // abstract-declarator: ...
922 if (Tok.is(tok::ellipsis))
925 if (Tok.is(tok::l_paren)) {
926 // Check whether we have a function declarator or a possible ctor-style
927 // initializer that follows the declarator. Note that ctor-style
928 // initializers are not possible in contexts where abstract declarators
930 if (!mayBeAbstract && !isCXXFunctionDeclarator())
933 // direct-declarator '(' parameter-declaration-clause ')'
934 // cv-qualifier-seq[opt] exception-specification[opt]
936 TPR = TryParseFunctionDeclarator();
937 } else if (Tok.is(tok::l_square)) {
938 // direct-declarator '[' constant-expression[opt] ']'
939 // direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
940 TPR = TryParseBracketDeclarator();
945 if (TPR != TPResult::Ambiguous)
949 return TPResult::Ambiguous;
953 Parser::isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind) {
955 // Obviously starts an expression.
956 case tok::numeric_constant:
957 case tok::char_constant:
958 case tok::wide_char_constant:
959 case tok::utf8_char_constant:
960 case tok::utf16_char_constant:
961 case tok::utf32_char_constant:
962 case tok::string_literal:
963 case tok::wide_string_literal:
964 case tok::utf8_string_literal:
965 case tok::utf16_string_literal:
966 case tok::utf32_string_literal:
975 case tok::minusminus:
979 case tok::kw___func__:
980 case tok::kw_const_cast:
982 case tok::kw_dynamic_cast:
985 case tok::kw_operator:
986 case tok::kw_reinterpret_cast:
987 case tok::kw_static_cast:
992 case tok::kw_alignof:
993 case tok::kw_noexcept:
994 case tok::kw_nullptr:
995 case tok::kw__Alignof:
997 case tok::kw___alignof:
998 case tok::kw___builtin_choose_expr:
999 case tok::kw___builtin_offsetof:
1000 case tok::kw___builtin_va_arg:
1001 case tok::kw___imag:
1002 case tok::kw___real:
1003 case tok::kw___FUNCTION__:
1004 case tok::kw___FUNCDNAME__:
1005 case tok::kw___FUNCSIG__:
1006 case tok::kw_L__FUNCTION__:
1007 case tok::kw___PRETTY_FUNCTION__:
1008 case tok::kw___uuidof:
1009 #define TYPE_TRAIT(N,Spelling,K) \
1010 case tok::kw_##Spelling:
1011 #include "clang/Basic/TokenKinds.def"
1012 return TPResult::True;
1014 // Obviously starts a type-specifier-seq:
1017 case tok::kw_double:
1018 case tok::kw___float128:
1024 case tok::kw___int64:
1025 case tok::kw___int128:
1026 case tok::kw_restrict:
1028 case tok::kw_signed:
1029 case tok::kw_struct:
1031 case tok::kw_unsigned:
1033 case tok::kw_volatile:
1035 case tok::kw__Complex:
1037 case tok::kw_typename:
1038 case tok::kw_wchar_t:
1039 case tok::kw_char16_t:
1040 case tok::kw_char32_t:
1041 case tok::kw__Decimal32:
1042 case tok::kw__Decimal64:
1043 case tok::kw__Decimal128:
1044 case tok::kw___interface:
1045 case tok::kw___thread:
1046 case tok::kw_thread_local:
1047 case tok::kw__Thread_local:
1048 case tok::kw_typeof:
1049 case tok::kw___underlying_type:
1050 case tok::kw___cdecl:
1051 case tok::kw___stdcall:
1052 case tok::kw___fastcall:
1053 case tok::kw___thiscall:
1054 case tok::kw___vectorcall:
1055 case tok::kw___unaligned:
1056 case tok::kw___vector:
1057 case tok::kw___pixel:
1058 case tok::kw___bool:
1059 case tok::kw__Atomic:
1060 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
1061 #include "clang/Basic/OpenCLImageTypes.def"
1062 case tok::kw___unknown_anytype:
1063 return TPResult::False;
1069 return TPResult::Ambiguous;
1072 bool Parser::isTentativelyDeclared(IdentifierInfo *II) {
1073 return std::find(TentativelyDeclaredIdentifiers.begin(),
1074 TentativelyDeclaredIdentifiers.end(), II)
1075 != TentativelyDeclaredIdentifiers.end();
1079 class TentativeParseCCC : public CorrectionCandidateCallback {
1081 TentativeParseCCC(const Token &Next) {
1082 WantRemainingKeywords = false;
1083 WantTypeSpecifiers = Next.isOneOf(tok::l_paren, tok::r_paren, tok::greater,
1084 tok::l_brace, tok::identifier);
1087 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1088 // Reject any candidate that only resolves to instance members since they
1089 // aren't viable as standalone identifiers instead of member references.
1090 if (Candidate.isResolved() && !Candidate.isKeyword() &&
1091 std::all_of(Candidate.begin(), Candidate.end(),
1092 [](NamedDecl *ND) { return ND->isCXXInstanceMember(); }))
1095 return CorrectionCandidateCallback::ValidateCandidate(Candidate);
1099 /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a declaration
1100 /// specifier, TPResult::False if it is not, TPResult::Ambiguous if it could
1101 /// be either a decl-specifier or a function-style cast, and TPResult::Error
1102 /// if a parsing error was found and reported.
1104 /// If HasMissingTypename is provided, a name with a dependent scope specifier
1105 /// will be treated as ambiguous if the 'typename' keyword is missing. If this
1106 /// happens, *HasMissingTypename will be set to 'true'. This will also be used
1107 /// as an indicator that undeclared identifiers (which will trigger a later
1108 /// parse error) should be treated as types. Returns TPResult::Ambiguous in
1112 /// storage-class-specifier
1114 /// function-specifier
1117 /// [C++11] 'constexpr'
1118 /// [GNU] attributes declaration-specifiers[opt]
1120 /// storage-class-specifier:
1126 /// [GNU] '__thread'
1127 /// [C++11] 'thread_local'
1128 /// [C11] '_Thread_local'
1130 /// function-specifier:
1139 /// simple-type-specifier
1142 /// elaborated-type-specifier
1143 /// typename-specifier
1146 /// simple-type-specifier:
1147 /// '::'[opt] nested-name-specifier[opt] type-name
1148 /// '::'[opt] nested-name-specifier 'template'
1149 /// simple-template-id [TODO]
1161 /// [GNU] typeof-specifier
1162 /// [GNU] '_Complex'
1164 /// [GNU] '__auto_type'
1165 /// [C++11] 'decltype' ( expression )
1166 /// [C++1y] 'decltype' ( 'auto' )
1173 /// elaborated-type-specifier:
1174 /// class-key '::'[opt] nested-name-specifier[opt] identifier
1175 /// class-key '::'[opt] nested-name-specifier[opt] 'template'[opt]
1176 /// simple-template-id
1177 /// 'enum' '::'[opt] nested-name-specifier[opt] identifier
1183 /// 'enum' identifier[opt] '{' enumerator-list[opt] '}'
1184 /// 'enum' identifier[opt] '{' enumerator-list ',' '}'
1186 /// class-specifier:
1187 /// class-head '{' member-specification[opt] '}'
1190 /// class-key identifier[opt] base-clause[opt]
1191 /// class-key nested-name-specifier identifier base-clause[opt]
1192 /// class-key nested-name-specifier[opt] simple-template-id
1193 /// base-clause[opt]
1206 Parser::isCXXDeclarationSpecifier(Parser::TPResult BracedCastResult,
1207 bool *HasMissingTypename) {
1208 switch (Tok.getKind()) {
1209 case tok::identifier: {
1210 // Check for need to substitute AltiVec __vector keyword
1211 // for "vector" identifier.
1212 if (TryAltiVecVectorToken())
1213 return TPResult::True;
1215 const Token &Next = NextToken();
1216 // In 'foo bar', 'foo' is always a type name outside of Objective-C.
1217 if (!getLangOpts().ObjC1 && Next.is(tok::identifier))
1218 return TPResult::True;
1220 if (Next.isNot(tok::coloncolon) && Next.isNot(tok::less)) {
1221 // Determine whether this is a valid expression. If not, we will hit
1222 // a parse error one way or another. In that case, tell the caller that
1223 // this is ambiguous. Typo-correct to type and expression keywords and
1224 // to types and identifiers, in order to try to recover from errors.
1225 switch (TryAnnotateName(false /* no nested name specifier */,
1226 llvm::make_unique<TentativeParseCCC>(Next))) {
1228 return TPResult::Error;
1229 case ANK_TentativeDecl:
1230 return TPResult::False;
1231 case ANK_TemplateName:
1232 // A bare type template-name which can't be a template template
1233 // argument is an error, and was probably intended to be a type.
1234 return GreaterThanIsOperator ? TPResult::True : TPResult::False;
1235 case ANK_Unresolved:
1236 return HasMissingTypename ? TPResult::Ambiguous : TPResult::False;
1240 assert(Tok.isNot(tok::identifier) &&
1241 "TryAnnotateName succeeded without producing an annotation");
1243 // This might possibly be a type with a dependent scope specifier and
1244 // a missing 'typename' keyword. Don't use TryAnnotateName in this case,
1245 // since it will annotate as a primary expression, and we want to use the
1246 // "missing 'typename'" logic.
1247 if (TryAnnotateTypeOrScopeToken())
1248 return TPResult::Error;
1249 // If annotation failed, assume it's a non-type.
1250 // FIXME: If this happens due to an undeclared identifier, treat it as
1252 if (Tok.is(tok::identifier))
1253 return TPResult::False;
1256 // We annotated this token as something. Recurse to handle whatever we got.
1257 return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
1260 case tok::kw_typename: // typename T::type
1261 // Annotate typenames and C++ scope specifiers. If we get one, just
1262 // recurse to handle whatever we get.
1263 if (TryAnnotateTypeOrScopeToken())
1264 return TPResult::Error;
1265 return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
1267 case tok::coloncolon: { // ::foo::bar
1268 const Token &Next = NextToken();
1269 if (Next.isOneOf(tok::kw_new, // ::new
1270 tok::kw_delete)) // ::delete
1271 return TPResult::False;
1274 case tok::kw___super:
1275 case tok::kw_decltype:
1276 // Annotate typenames and C++ scope specifiers. If we get one, just
1277 // recurse to handle whatever we get.
1278 if (TryAnnotateTypeOrScopeToken())
1279 return TPResult::Error;
1280 return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
1283 // storage-class-specifier
1285 // function-specifier
1290 case tok::kw_friend:
1291 case tok::kw_typedef:
1292 case tok::kw_constexpr:
1293 case tok::kw_concept:
1294 // storage-class-specifier
1295 case tok::kw_register:
1296 case tok::kw_static:
1297 case tok::kw_extern:
1298 case tok::kw_mutable:
1300 case tok::kw___thread:
1301 case tok::kw_thread_local:
1302 case tok::kw__Thread_local:
1303 // function-specifier
1304 case tok::kw_inline:
1305 case tok::kw_virtual:
1306 case tok::kw_explicit:
1309 case tok::kw___module_private__:
1312 case tok::kw___unknown_anytype:
1315 // simple-type-specifier
1318 // elaborated-type-specifier
1319 // typename-specifier
1323 // elaborated-type-specifier
1325 case tok::kw_struct:
1327 case tok::kw___interface:
1332 case tok::kw_volatile:
1335 case tok::kw_restrict:
1336 case tok::kw__Complex:
1337 case tok::kw___attribute:
1338 case tok::kw___auto_type:
1339 return TPResult::True;
1342 case tok::kw___declspec:
1343 case tok::kw___cdecl:
1344 case tok::kw___stdcall:
1345 case tok::kw___fastcall:
1346 case tok::kw___thiscall:
1347 case tok::kw___vectorcall:
1349 case tok::kw___sptr:
1350 case tok::kw___uptr:
1351 case tok::kw___ptr64:
1352 case tok::kw___ptr32:
1353 case tok::kw___forceinline:
1354 case tok::kw___unaligned:
1355 case tok::kw__Nonnull:
1356 case tok::kw__Nullable:
1357 case tok::kw__Null_unspecified:
1358 case tok::kw___kindof:
1359 return TPResult::True;
1362 case tok::kw___pascal:
1363 return TPResult::True;
1366 case tok::kw___vector:
1367 return TPResult::True;
1369 case tok::annot_template_id: {
1370 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1371 if (TemplateId->Kind != TNK_Type_template)
1372 return TPResult::False;
1374 AnnotateTemplateIdTokenAsType();
1375 assert(Tok.is(tok::annot_typename));
1379 case tok::annot_cxxscope: // foo::bar or ::foo::bar, but already parsed
1380 // We've already annotated a scope; try to annotate a type.
1381 if (TryAnnotateTypeOrScopeToken())
1382 return TPResult::Error;
1383 if (!Tok.is(tok::annot_typename)) {
1384 // If the next token is an identifier or a type qualifier, then this
1385 // can't possibly be a valid expression either.
1386 if (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier)) {
1388 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
1389 Tok.getAnnotationRange(),
1391 if (SS.getScopeRep() && SS.getScopeRep()->isDependent()) {
1392 RevertingTentativeParsingAction PA(*this);
1395 bool isIdentifier = Tok.is(tok::identifier);
1396 TPResult TPR = TPResult::False;
1398 TPR = isCXXDeclarationSpecifier(BracedCastResult,
1399 HasMissingTypename);
1402 TPR == TPResult::True || TPR == TPResult::Error)
1403 return TPResult::Error;
1405 if (HasMissingTypename) {
1406 // We can't tell whether this is a missing 'typename' or a valid
1408 *HasMissingTypename = true;
1409 return TPResult::Ambiguous;
1412 // FIXME: Fails to either revert or commit the tentative parse!
1414 // Try to resolve the name. If it doesn't exist, assume it was
1415 // intended to name a type and keep disambiguating.
1416 switch (TryAnnotateName(false /* SS is not dependent */)) {
1418 return TPResult::Error;
1419 case ANK_TentativeDecl:
1420 return TPResult::False;
1421 case ANK_TemplateName:
1422 // A bare type template-name which can't be a template template
1423 // argument is an error, and was probably intended to be a type.
1424 return GreaterThanIsOperator ? TPResult::True : TPResult::False;
1425 case ANK_Unresolved:
1426 return HasMissingTypename ? TPResult::Ambiguous
1429 // Annotated it, check again.
1430 assert(Tok.isNot(tok::annot_cxxscope) ||
1431 NextToken().isNot(tok::identifier));
1432 return isCXXDeclarationSpecifier(BracedCastResult,
1433 HasMissingTypename);
1437 return TPResult::False;
1439 // If that succeeded, fallthrough into the generic simple-type-id case.
1441 // The ambiguity resides in a simple-type-specifier/typename-specifier
1442 // followed by a '('. The '(' could either be the start of:
1444 // direct-declarator:
1445 // '(' declarator ')'
1447 // direct-abstract-declarator:
1448 // '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1449 // exception-specification[opt]
1450 // '(' abstract-declarator ')'
1452 // or part of a function-style cast expression:
1454 // simple-type-specifier '(' expression-list[opt] ')'
1457 // simple-type-specifier:
1459 case tok::annot_typename:
1461 // In Objective-C, we might have a protocol-qualified type.
1462 if (getLangOpts().ObjC1 && NextToken().is(tok::less)) {
1463 // Tentatively parse the protocol qualifiers.
1464 RevertingTentativeParsingAction PA(*this);
1465 ConsumeToken(); // The type token
1467 TPResult TPR = TryParseProtocolQualifiers();
1468 bool isFollowedByParen = Tok.is(tok::l_paren);
1469 bool isFollowedByBrace = Tok.is(tok::l_brace);
1471 if (TPR == TPResult::Error)
1472 return TPResult::Error;
1474 if (isFollowedByParen)
1475 return TPResult::Ambiguous;
1477 if (getLangOpts().CPlusPlus11 && isFollowedByBrace)
1478 return BracedCastResult;
1480 return TPResult::True;
1484 case tok::kw_wchar_t:
1485 case tok::kw_char16_t:
1486 case tok::kw_char32_t:
1491 case tok::kw___int64:
1492 case tok::kw___int128:
1493 case tok::kw_signed:
1494 case tok::kw_unsigned:
1497 case tok::kw_double:
1498 case tok::kw___float128:
1500 case tok::annot_decltype:
1501 if (NextToken().is(tok::l_paren))
1502 return TPResult::Ambiguous;
1504 // This is a function-style cast in all cases we disambiguate other than
1507 // enum E : int { a = 4 }; // enum
1508 // enum E : int { 4 }; // bit-field
1510 if (getLangOpts().CPlusPlus11 && NextToken().is(tok::l_brace))
1511 return BracedCastResult;
1513 if (isStartOfObjCClassMessageMissingOpenBracket())
1514 return TPResult::False;
1516 return TPResult::True;
1518 // GNU typeof support.
1519 case tok::kw_typeof: {
1520 if (NextToken().isNot(tok::l_paren))
1521 return TPResult::True;
1523 RevertingTentativeParsingAction PA(*this);
1525 TPResult TPR = TryParseTypeofSpecifier();
1526 bool isFollowedByParen = Tok.is(tok::l_paren);
1527 bool isFollowedByBrace = Tok.is(tok::l_brace);
1529 if (TPR == TPResult::Error)
1530 return TPResult::Error;
1532 if (isFollowedByParen)
1533 return TPResult::Ambiguous;
1535 if (getLangOpts().CPlusPlus11 && isFollowedByBrace)
1536 return BracedCastResult;
1538 return TPResult::True;
1541 // C++0x type traits support
1542 case tok::kw___underlying_type:
1543 return TPResult::True;
1546 case tok::kw__Atomic:
1547 return TPResult::True;
1550 return TPResult::False;
1554 bool Parser::isCXXDeclarationSpecifierAType() {
1555 switch (Tok.getKind()) {
1556 // typename-specifier
1557 case tok::annot_decltype:
1558 case tok::annot_template_id:
1559 case tok::annot_typename:
1560 case tok::kw_typeof:
1561 case tok::kw___underlying_type:
1564 // elaborated-type-specifier
1566 case tok::kw_struct:
1568 case tok::kw___interface:
1572 // simple-type-specifier
1574 case tok::kw_wchar_t:
1575 case tok::kw_char16_t:
1576 case tok::kw_char32_t:
1581 case tok::kw___int64:
1582 case tok::kw___int128:
1583 case tok::kw_signed:
1584 case tok::kw_unsigned:
1587 case tok::kw_double:
1588 case tok::kw___float128:
1590 case tok::kw___unknown_anytype:
1591 case tok::kw___auto_type:
1595 return getLangOpts().CPlusPlus11;
1597 case tok::kw__Atomic:
1599 return NextToken().is(tok::l_paren);
1606 /// [GNU] typeof-specifier:
1607 /// 'typeof' '(' expressions ')'
1608 /// 'typeof' '(' type-name ')'
1610 Parser::TPResult Parser::TryParseTypeofSpecifier() {
1611 assert(Tok.is(tok::kw_typeof) && "Expected 'typeof'!");
1614 assert(Tok.is(tok::l_paren) && "Expected '('");
1615 // Parse through the parens after 'typeof'.
1617 if (!SkipUntil(tok::r_paren, StopAtSemi))
1618 return TPResult::Error;
1620 return TPResult::Ambiguous;
1623 /// [ObjC] protocol-qualifiers:
1624 //// '<' identifier-list '>'
1625 Parser::TPResult Parser::TryParseProtocolQualifiers() {
1626 assert(Tok.is(tok::less) && "Expected '<' for qualifier list");
1629 if (Tok.isNot(tok::identifier))
1630 return TPResult::Error;
1633 if (Tok.is(tok::comma)) {
1638 if (Tok.is(tok::greater)) {
1640 return TPResult::Ambiguous;
1644 return TPResult::Error;
1647 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
1648 /// a constructor-style initializer, when parsing declaration statements.
1649 /// Returns true for function declarator and false for constructor-style
1651 /// If during the disambiguation process a parsing error is encountered,
1652 /// the function returns true to let the declaration parsing code handle it.
1654 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1655 /// exception-specification[opt]
1657 bool Parser::isCXXFunctionDeclarator(bool *IsAmbiguous) {
1660 // The ambiguity arising from the similarity between a function-style cast and
1661 // a declaration mentioned in 6.8 can also occur in the context of a
1662 // declaration. In that context, the choice is between a function declaration
1663 // with a redundant set of parentheses around a parameter name and an object
1664 // declaration with a function-style cast as the initializer. Just as for the
1665 // ambiguities mentioned in 6.8, the resolution is to consider any construct
1666 // that could possibly be a declaration a declaration.
1668 RevertingTentativeParsingAction PA(*this);
1671 bool InvalidAsDeclaration = false;
1672 TPResult TPR = TryParseParameterDeclarationClause(&InvalidAsDeclaration);
1673 if (TPR == TPResult::Ambiguous) {
1674 if (Tok.isNot(tok::r_paren))
1675 TPR = TPResult::False;
1677 const Token &Next = NextToken();
1678 if (Next.isOneOf(tok::amp, tok::ampamp, tok::kw_const, tok::kw_volatile,
1679 tok::kw_throw, tok::kw_noexcept, tok::l_square,
1680 tok::l_brace, tok::kw_try, tok::equal, tok::arrow) ||
1681 isCXX11VirtSpecifier(Next))
1682 // The next token cannot appear after a constructor-style initializer,
1683 // and can appear next in a function definition. This must be a function
1685 TPR = TPResult::True;
1686 else if (InvalidAsDeclaration)
1687 // Use the absence of 'typename' as a tie-breaker.
1688 TPR = TPResult::False;
1692 if (IsAmbiguous && TPR == TPResult::Ambiguous)
1693 *IsAmbiguous = true;
1695 // In case of an error, let the declaration parsing code handle it.
1696 return TPR != TPResult::False;
1699 /// parameter-declaration-clause:
1700 /// parameter-declaration-list[opt] '...'[opt]
1701 /// parameter-declaration-list ',' '...'
1703 /// parameter-declaration-list:
1704 /// parameter-declaration
1705 /// parameter-declaration-list ',' parameter-declaration
1707 /// parameter-declaration:
1708 /// attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
1709 /// attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
1710 /// '=' assignment-expression
1711 /// attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
1713 /// attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
1714 /// attributes[opt] '=' assignment-expression
1717 Parser::TryParseParameterDeclarationClause(bool *InvalidAsDeclaration,
1718 bool VersusTemplateArgument) {
1720 if (Tok.is(tok::r_paren))
1721 return TPResult::Ambiguous;
1723 // parameter-declaration-list[opt] '...'[opt]
1724 // parameter-declaration-list ',' '...'
1726 // parameter-declaration-list:
1727 // parameter-declaration
1728 // parameter-declaration-list ',' parameter-declaration
1732 if (Tok.is(tok::ellipsis)) {
1734 if (Tok.is(tok::r_paren))
1735 return TPResult::True; // '...)' is a sign of a function declarator.
1737 return TPResult::False;
1740 // An attribute-specifier-seq here is a sign of a function declarator.
1741 if (isCXX11AttributeSpecifier(/*Disambiguate*/false,
1742 /*OuterMightBeMessageSend*/true))
1743 return TPResult::True;
1745 ParsedAttributes attrs(AttrFactory);
1746 MaybeParseMicrosoftAttributes(attrs);
1748 // decl-specifier-seq
1749 // A parameter-declaration's initializer must be preceded by an '=', so
1750 // decl-specifier-seq '{' is not a parameter in C++11.
1751 TPResult TPR = isCXXDeclarationSpecifier(TPResult::False,
1752 InvalidAsDeclaration);
1754 if (VersusTemplateArgument && TPR == TPResult::True) {
1755 // Consume the decl-specifier-seq. We have to look past it, since a
1756 // type-id might appear here in a template argument.
1757 bool SeenType = false;
1759 SeenType |= isCXXDeclarationSpecifierAType();
1760 if (TryConsumeDeclarationSpecifier() == TPResult::Error)
1761 return TPResult::Error;
1763 // If we see a parameter name, this can't be a template argument.
1764 if (SeenType && Tok.is(tok::identifier))
1765 return TPResult::True;
1767 TPR = isCXXDeclarationSpecifier(TPResult::False,
1768 InvalidAsDeclaration);
1769 if (TPR == TPResult::Error)
1771 } while (TPR != TPResult::False);
1772 } else if (TPR == TPResult::Ambiguous) {
1773 // Disambiguate what follows the decl-specifier.
1774 if (TryConsumeDeclarationSpecifier() == TPResult::Error)
1775 return TPResult::Error;
1780 // abstract-declarator[opt]
1781 TPR = TryParseDeclarator(true/*mayBeAbstract*/);
1782 if (TPR != TPResult::Ambiguous)
1785 // [GNU] attributes[opt]
1786 if (Tok.is(tok::kw___attribute))
1787 return TPResult::True;
1789 // If we're disambiguating a template argument in a default argument in
1790 // a class definition versus a parameter declaration, an '=' here
1791 // disambiguates the parse one way or the other.
1792 // If this is a parameter, it must have a default argument because
1793 // (a) the previous parameter did, and
1794 // (b) this must be the first declaration of the function, so we can't
1795 // inherit any default arguments from elsewhere.
1796 // If we see an ')', then we've reached the end of a
1797 // parameter-declaration-clause, and the last param is missing its default
1799 if (VersusTemplateArgument)
1800 return Tok.isOneOf(tok::equal, tok::r_paren) ? TPResult::True
1803 if (Tok.is(tok::equal)) {
1804 // '=' assignment-expression
1805 // Parse through assignment-expression.
1806 // FIXME: assignment-expression may contain an unparenthesized comma.
1807 if (!SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch))
1808 return TPResult::Error;
1811 if (Tok.is(tok::ellipsis)) {
1813 if (Tok.is(tok::r_paren))
1814 return TPResult::True; // '...)' is a sign of a function declarator.
1816 return TPResult::False;
1819 if (!TryConsumeToken(tok::comma))
1823 return TPResult::Ambiguous;
1826 /// TryParseFunctionDeclarator - We parsed a '(' and we want to try to continue
1827 /// parsing as a function declarator.
1828 /// If TryParseFunctionDeclarator fully parsed the function declarator, it will
1829 /// return TPResult::Ambiguous, otherwise it will return either False() or
1832 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1833 /// exception-specification[opt]
1835 /// exception-specification:
1836 /// 'throw' '(' type-id-list[opt] ')'
1838 Parser::TPResult Parser::TryParseFunctionDeclarator() {
1840 // The '(' is already parsed.
1842 TPResult TPR = TryParseParameterDeclarationClause();
1843 if (TPR == TPResult::Ambiguous && Tok.isNot(tok::r_paren))
1844 TPR = TPResult::False;
1846 if (TPR == TPResult::False || TPR == TPResult::Error)
1849 // Parse through the parens.
1850 if (!SkipUntil(tok::r_paren, StopAtSemi))
1851 return TPResult::Error;
1854 while (Tok.isOneOf(tok::kw_const, tok::kw_volatile, tok::kw_restrict))
1857 // ref-qualifier[opt]
1858 if (Tok.isOneOf(tok::amp, tok::ampamp))
1861 // exception-specification
1862 if (Tok.is(tok::kw_throw)) {
1864 if (Tok.isNot(tok::l_paren))
1865 return TPResult::Error;
1867 // Parse through the parens after 'throw'.
1869 if (!SkipUntil(tok::r_paren, StopAtSemi))
1870 return TPResult::Error;
1872 if (Tok.is(tok::kw_noexcept)) {
1874 // Possibly an expression as well.
1875 if (Tok.is(tok::l_paren)) {
1876 // Find the matching rparen.
1878 if (!SkipUntil(tok::r_paren, StopAtSemi))
1879 return TPResult::Error;
1883 return TPResult::Ambiguous;
1886 /// '[' constant-expression[opt] ']'
1888 Parser::TPResult Parser::TryParseBracketDeclarator() {
1890 if (!SkipUntil(tok::r_square, StopAtSemi))
1891 return TPResult::Error;
1893 return TPResult::Ambiguous;