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
112 // TPResult::Error().
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
129 TentativeParsingAction PA(*this);
130 TPR = TryParseSimpleDeclaration(AllowForRangeDecl);
133 // In case of an error, let the declaration parsing code handle it.
134 if (TPR == TPResult::Error())
137 // Declarations take precedence over expressions.
138 if (TPR == TPResult::Ambiguous())
139 TPR = TPResult::True();
141 assert(TPR == TPResult::True() || TPR == TPResult::False());
142 return TPR == TPResult::True();
145 /// simple-declaration:
146 /// decl-specifier-seq init-declarator-list[opt] ';'
148 /// (if AllowForRangeDecl specified)
149 /// for ( for-range-declaration : for-range-initializer ) statement
150 /// for-range-declaration:
151 /// attribute-specifier-seqopt type-specifier-seq declarator
153 Parser::TPResult Parser::TryParseSimpleDeclaration(bool AllowForRangeDecl) {
154 if (Tok.is(tok::kw_typeof))
155 TryParseTypeofSpecifier();
157 if (Tok.is(tok::annot_cxxscope))
161 if (getLangOpts().ObjC1 && Tok.is(tok::less))
162 TryParseProtocolQualifiers();
165 // Two decl-specifiers in a row conclusively disambiguate this as being a
166 // simple-declaration. Don't bother calling isCXXDeclarationSpecifier in the
167 // overwhelmingly common case that the next token is a '('.
168 if (Tok.isNot(tok::l_paren)) {
169 TPResult TPR = isCXXDeclarationSpecifier();
170 if (TPR == TPResult::Ambiguous())
171 return TPResult::True();
172 if (TPR == TPResult::True() || TPR == TPResult::Error())
174 assert(TPR == TPResult::False());
177 TPResult TPR = TryParseInitDeclaratorList();
178 if (TPR != TPResult::Ambiguous())
181 if (Tok.isNot(tok::semi) && (!AllowForRangeDecl || Tok.isNot(tok::colon)))
182 return TPResult::False();
184 return TPResult::Ambiguous();
187 /// Tentatively parse an init-declarator-list in order to disambiguate it from
190 /// init-declarator-list:
192 /// init-declarator-list ',' init-declarator
195 /// declarator initializer[opt]
196 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] initializer[opt]
199 /// brace-or-equal-initializer
200 /// '(' expression-list ')'
202 /// brace-or-equal-initializer:
203 /// '=' initializer-clause
204 /// [C++11] braced-init-list
206 /// initializer-clause:
207 /// assignment-expression
210 /// braced-init-list:
211 /// '{' initializer-list ','[opt] '}'
214 Parser::TPResult Parser::TryParseInitDeclaratorList() {
217 TPResult TPR = TryParseDeclarator(false/*mayBeAbstract*/);
218 if (TPR != TPResult::Ambiguous())
221 // [GNU] simple-asm-expr[opt] attributes[opt]
222 if (Tok.is(tok::kw_asm) || Tok.is(tok::kw___attribute))
223 return TPResult::True();
226 if (Tok.is(tok::l_paren)) {
227 // Parse through the parens.
229 if (!SkipUntil(tok::r_paren))
230 return TPResult::Error();
231 } else if (Tok.is(tok::l_brace)) {
232 // A left-brace here is sufficient to disambiguate the parse; an
233 // expression can never be followed directly by a braced-init-list.
234 return TPResult::True();
235 } else if (Tok.is(tok::equal) || isTokIdentifier_in()) {
236 // MSVC and g++ won't examine the rest of declarators if '=' is
237 // encountered; they just conclude that we have a declaration.
238 // EDG parses the initializer completely, which is the proper behavior
241 // At present, Clang follows MSVC and g++, since the parser does not have
242 // the ability to parse an expression fully without recording the
243 // results of that parse.
244 // Also allow 'in' after on objective-c declaration as in:
245 // for (int (^b)(void) in array). Ideally this should be done in the
246 // context of parsing for-init-statement of a foreach statement only. But,
247 // in any other context 'in' is invalid after a declaration and parser
248 // issues the error regardless of outcome of this decision.
249 // FIXME. Change if above assumption does not hold.
250 return TPResult::True();
253 if (Tok.isNot(tok::comma))
255 ConsumeToken(); // the comma.
258 return TPResult::Ambiguous();
261 /// isCXXConditionDeclaration - Disambiguates between a declaration or an
262 /// expression for a condition of a if/switch/while/for statement.
263 /// If during the disambiguation process a parsing error is encountered,
264 /// the function returns true to let the declaration parsing code handle it.
268 /// type-specifier-seq declarator '=' assignment-expression
269 /// [C++11] type-specifier-seq declarator '=' initializer-clause
270 /// [C++11] type-specifier-seq declarator braced-init-list
271 /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
272 /// '=' assignment-expression
274 bool Parser::isCXXConditionDeclaration() {
275 TPResult TPR = isCXXDeclarationSpecifier();
276 if (TPR != TPResult::Ambiguous())
277 return TPR != TPResult::False(); // Returns true for TPResult::True() or
278 // TPResult::Error().
280 // FIXME: Add statistics about the number of ambiguous statements encountered
281 // and how they were resolved (number of declarations+number of expressions).
283 // Ok, we have a simple-type-specifier/typename-specifier followed by a '('.
284 // We need tentative parsing...
286 TentativeParsingAction PA(*this);
288 // type-specifier-seq
289 if (Tok.is(tok::kw_typeof))
290 TryParseTypeofSpecifier();
294 if (getLangOpts().ObjC1 && Tok.is(tok::less))
295 TryParseProtocolQualifiers();
297 assert(Tok.is(tok::l_paren) && "Expected '('");
300 TPR = TryParseDeclarator(false/*mayBeAbstract*/);
302 // In case of an error, let the declaration parsing code handle it.
303 if (TPR == TPResult::Error())
304 TPR = TPResult::True();
306 if (TPR == TPResult::Ambiguous()) {
308 // [GNU] simple-asm-expr[opt] attributes[opt]
309 if (Tok.is(tok::equal) ||
310 Tok.is(tok::kw_asm) || Tok.is(tok::kw___attribute))
311 TPR = TPResult::True();
312 else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace))
313 TPR = TPResult::True();
315 TPR = TPResult::False();
320 assert(TPR == TPResult::True() || TPR == TPResult::False());
321 return TPR == TPResult::True();
324 /// \brief Determine whether the next set of tokens contains a type-id.
326 /// The context parameter states what context we're parsing right
327 /// now, which affects how this routine copes with the token
328 /// following the type-id. If the context is TypeIdInParens, we have
329 /// already parsed the '(' and we will cease lookahead when we hit
330 /// the corresponding ')'. If the context is
331 /// TypeIdAsTemplateArgument, we've already parsed the '<' or ','
332 /// before this template argument, and will cease lookahead when we
333 /// hit a '>', '>>' (in C++0x), or ','. Returns true for a type-id
334 /// and false for an expression. If during the disambiguation
335 /// process a parsing error is encountered, the function returns
336 /// true to let the declaration parsing code handle it.
339 /// type-specifier-seq abstract-declarator[opt]
341 bool Parser::isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous) {
346 // The ambiguity arising from the similarity between a function-style cast and
347 // a type-id can occur in different contexts. The ambiguity appears as a
348 // choice between a function-style cast expression and a declaration of a
349 // type. The resolution is that any construct that could possibly be a type-id
350 // in its syntactic context shall be considered a type-id.
352 TPResult TPR = isCXXDeclarationSpecifier();
353 if (TPR != TPResult::Ambiguous())
354 return TPR != TPResult::False(); // Returns true for TPResult::True() or
355 // TPResult::Error().
357 // FIXME: Add statistics about the number of ambiguous statements encountered
358 // and how they were resolved (number of declarations+number of expressions).
360 // Ok, we have a simple-type-specifier/typename-specifier followed by a '('.
361 // We need tentative parsing...
363 TentativeParsingAction PA(*this);
365 // type-specifier-seq
366 if (Tok.is(tok::kw_typeof))
367 TryParseTypeofSpecifier();
371 if (getLangOpts().ObjC1 && Tok.is(tok::less))
372 TryParseProtocolQualifiers();
375 assert(Tok.is(tok::l_paren) && "Expected '('");
378 TPR = TryParseDeclarator(true/*mayBeAbstract*/, false/*mayHaveIdentifier*/);
380 // In case of an error, let the declaration parsing code handle it.
381 if (TPR == TPResult::Error())
382 TPR = TPResult::True();
384 if (TPR == TPResult::Ambiguous()) {
385 // We are supposed to be inside parens, so if after the abstract declarator
386 // we encounter a ')' this is a type-id, otherwise it's an expression.
387 if (Context == TypeIdInParens && Tok.is(tok::r_paren)) {
388 TPR = TPResult::True();
391 // We are supposed to be inside a template argument, so if after
392 // the abstract declarator we encounter a '>', '>>' (in C++0x), or
393 // ',', this is a type-id. Otherwise, it's an expression.
394 } else if (Context == TypeIdAsTemplateArgument &&
395 (Tok.is(tok::greater) || Tok.is(tok::comma) ||
396 (getLangOpts().CPlusPlus11 && Tok.is(tok::greatergreater)))) {
397 TPR = TPResult::True();
401 TPR = TPResult::False();
406 assert(TPR == TPResult::True() || TPR == TPResult::False());
407 return TPR == TPResult::True();
410 /// \brief Returns true if this is a C++11 attribute-specifier. Per
411 /// C++11 [dcl.attr.grammar]p6, two consecutive left square bracket tokens
412 /// always introduce an attribute. In Objective-C++11, this rule does not
413 /// apply if either '[' begins a message-send.
415 /// If Disambiguate is true, we try harder to determine whether a '[[' starts
416 /// an attribute-specifier, and return CAK_InvalidAttributeSpecifier if not.
418 /// If OuterMightBeMessageSend is true, we assume the outer '[' is either an
419 /// Obj-C message send or the start of an attribute. Otherwise, we assume it
420 /// is not an Obj-C message send.
422 /// C++11 [dcl.attr.grammar]:
424 /// attribute-specifier:
425 /// '[' '[' attribute-list ']' ']'
426 /// alignment-specifier
430 /// attribute-list ',' attribute[opt]
432 /// attribute-list ',' attribute '...'
435 /// attribute-token attribute-argument-clause[opt]
439 /// identifier '::' identifier
441 /// attribute-argument-clause:
442 /// '(' balanced-token-seq ')'
443 Parser::CXX11AttributeKind
444 Parser::isCXX11AttributeSpecifier(bool Disambiguate,
445 bool OuterMightBeMessageSend) {
446 if (Tok.is(tok::kw_alignas))
447 return CAK_AttributeSpecifier;
449 if (Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square))
450 return CAK_NotAttributeSpecifier;
452 // No tentative parsing if we don't need to look for ']]' or a lambda.
453 if (!Disambiguate && !getLangOpts().ObjC1)
454 return CAK_AttributeSpecifier;
456 TentativeParsingAction PA(*this);
458 // Opening brackets were checked for above.
461 // Outside Obj-C++11, treat anything with a matching ']]' as an attribute.
462 if (!getLangOpts().ObjC1) {
465 bool IsAttribute = SkipUntil(tok::r_square, false);
466 IsAttribute &= Tok.is(tok::r_square);
470 return IsAttribute ? CAK_AttributeSpecifier : CAK_InvalidAttributeSpecifier;
473 // In Obj-C++11, we need to distinguish four situations:
474 // 1a) int x[[attr]]; C++11 attribute.
475 // 1b) [[attr]]; C++11 statement attribute.
476 // 2) int x[[obj](){ return 1; }()]; Lambda in array size/index.
477 // 3a) int x[[obj get]]; Message send in array size/index.
478 // 3b) [[Class alloc] init]; Message send in message send.
479 // 4) [[obj]{ return self; }() doStuff]; Lambda in message send.
480 // (1) is an attribute, (2) is ill-formed, and (3) and (4) are accepted.
482 // If we have a lambda-introducer, then this is definitely not a message send.
483 // FIXME: If this disambiguation is too slow, fold the tentative lambda parse
484 // into the tentative attribute parse below.
485 LambdaIntroducer Intro;
486 if (!TryParseLambdaIntroducer(Intro)) {
487 // A lambda cannot end with ']]', and an attribute must.
488 bool IsAttribute = Tok.is(tok::r_square);
493 // Case 1: C++11 attribute.
494 return CAK_AttributeSpecifier;
496 if (OuterMightBeMessageSend)
497 // Case 4: Lambda in message send.
498 return CAK_NotAttributeSpecifier;
500 // Case 2: Lambda in array size / index.
501 return CAK_InvalidAttributeSpecifier;
506 // If we don't have a lambda-introducer, then we have an attribute or a
508 bool IsAttribute = true;
509 while (Tok.isNot(tok::r_square)) {
510 if (Tok.is(tok::comma)) {
511 // Case 1: Stray commas can only occur in attributes.
513 return CAK_AttributeSpecifier;
516 // Parse the attribute-token, if present.
517 // C++11 [dcl.attr.grammar]:
518 // If a keyword or an alternative token that satisfies the syntactic
519 // requirements of an identifier is contained in an attribute-token,
520 // it is considered an identifier.
522 if (!TryParseCXX11AttributeIdentifier(Loc)) {
526 if (Tok.is(tok::coloncolon)) {
528 if (!TryParseCXX11AttributeIdentifier(Loc)) {
534 // Parse the attribute-argument-clause, if present.
535 if (Tok.is(tok::l_paren)) {
537 if (!SkipUntil(tok::r_paren, false)) {
543 if (Tok.is(tok::ellipsis))
546 if (Tok.isNot(tok::comma))
552 // An attribute must end ']]'.
554 if (Tok.is(tok::r_square)) {
556 IsAttribute = Tok.is(tok::r_square);
565 // Case 1: C++11 statement attribute.
566 return CAK_AttributeSpecifier;
568 // Case 3: Message send.
569 return CAK_NotAttributeSpecifier;
573 /// direct-declarator
574 /// ptr-operator declarator
576 /// direct-declarator:
578 /// direct-declarator '(' parameter-declaration-clause ')'
579 /// cv-qualifier-seq[opt] exception-specification[opt]
580 /// direct-declarator '[' constant-expression[opt] ']'
581 /// '(' declarator ')'
582 /// [GNU] '(' attributes declarator ')'
584 /// abstract-declarator:
585 /// ptr-operator abstract-declarator[opt]
586 /// direct-abstract-declarator
589 /// direct-abstract-declarator:
590 /// direct-abstract-declarator[opt]
591 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
592 /// exception-specification[opt]
593 /// direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
594 /// '(' abstract-declarator ')'
597 /// '*' cv-qualifier-seq[opt]
599 /// [C++0x] '&&' [TODO]
600 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
602 /// cv-qualifier-seq:
603 /// cv-qualifier cv-qualifier-seq[opt]
610 /// '...'[opt] id-expression
614 /// qualified-id [TODO]
618 /// operator-function-id [TODO]
619 /// conversion-function-id [TODO]
620 /// '~' class-name [TODO]
621 /// template-id [TODO]
623 Parser::TPResult Parser::TryParseDeclarator(bool mayBeAbstract,
624 bool mayHaveIdentifier) {
627 // ptr-operator declarator
630 if (Tok.is(tok::coloncolon) || Tok.is(tok::identifier))
631 if (TryAnnotateCXXScopeToken(true))
632 return TPResult::Error();
634 if (Tok.is(tok::star) || Tok.is(tok::amp) || Tok.is(tok::caret) ||
635 Tok.is(tok::ampamp) ||
636 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::star))) {
639 while (Tok.is(tok::kw_const) ||
640 Tok.is(tok::kw_volatile) ||
641 Tok.is(tok::kw_restrict))
648 // direct-declarator:
649 // direct-abstract-declarator:
650 if (Tok.is(tok::ellipsis))
653 if ((Tok.is(tok::identifier) ||
654 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) &&
657 if (Tok.is(tok::annot_cxxscope))
660 TentativelyDeclaredIdentifiers.push_back(Tok.getIdentifierInfo());
662 } else if (Tok.is(tok::l_paren)) {
665 (Tok.is(tok::r_paren) || // 'int()' is a function.
666 // 'int(...)' is a function.
667 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren)) ||
668 isDeclarationSpecifier())) { // 'int(int)' is a function.
669 // '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
670 // exception-specification[opt]
671 TPResult TPR = TryParseFunctionDeclarator();
672 if (TPR != TPResult::Ambiguous())
675 // '(' declarator ')'
676 // '(' attributes declarator ')'
677 // '(' abstract-declarator ')'
678 if (Tok.is(tok::kw___attribute) ||
679 Tok.is(tok::kw___declspec) ||
680 Tok.is(tok::kw___cdecl) ||
681 Tok.is(tok::kw___stdcall) ||
682 Tok.is(tok::kw___fastcall) ||
683 Tok.is(tok::kw___thiscall) ||
684 Tok.is(tok::kw___unaligned))
685 return TPResult::True(); // attributes indicate declaration
686 TPResult TPR = TryParseDeclarator(mayBeAbstract, mayHaveIdentifier);
687 if (TPR != TPResult::Ambiguous())
689 if (Tok.isNot(tok::r_paren))
690 return TPResult::False();
693 } else if (!mayBeAbstract) {
694 return TPResult::False();
698 TPResult TPR(TPResult::Ambiguous());
700 // abstract-declarator: ...
701 if (Tok.is(tok::ellipsis))
704 if (Tok.is(tok::l_paren)) {
705 // Check whether we have a function declarator or a possible ctor-style
706 // initializer that follows the declarator. Note that ctor-style
707 // initializers are not possible in contexts where abstract declarators
709 if (!mayBeAbstract && !isCXXFunctionDeclarator())
712 // direct-declarator '(' parameter-declaration-clause ')'
713 // cv-qualifier-seq[opt] exception-specification[opt]
715 TPR = TryParseFunctionDeclarator();
716 } else if (Tok.is(tok::l_square)) {
717 // direct-declarator '[' constant-expression[opt] ']'
718 // direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
719 TPR = TryParseBracketDeclarator();
724 if (TPR != TPResult::Ambiguous())
728 return TPResult::Ambiguous();
732 Parser::isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind) {
734 // Obviously starts an expression.
735 case tok::numeric_constant:
736 case tok::char_constant:
737 case tok::wide_char_constant:
738 case tok::utf16_char_constant:
739 case tok::utf32_char_constant:
740 case tok::string_literal:
741 case tok::wide_string_literal:
742 case tok::utf8_string_literal:
743 case tok::utf16_string_literal:
744 case tok::utf32_string_literal:
753 case tok::minusminus:
757 case tok::kw___func__:
758 case tok::kw_const_cast:
760 case tok::kw_dynamic_cast:
763 case tok::kw_operator:
764 case tok::kw_reinterpret_cast:
765 case tok::kw_static_cast:
770 case tok::kw_alignof:
771 case tok::kw_noexcept:
772 case tok::kw_nullptr:
773 case tok::kw__Alignof:
775 case tok::kw___alignof:
776 case tok::kw___builtin_choose_expr:
777 case tok::kw___builtin_offsetof:
778 case tok::kw___builtin_types_compatible_p:
779 case tok::kw___builtin_va_arg:
782 case tok::kw___FUNCTION__:
783 case tok::kw_L__FUNCTION__:
784 case tok::kw___PRETTY_FUNCTION__:
785 case tok::kw___has_nothrow_assign:
786 case tok::kw___has_nothrow_copy:
787 case tok::kw___has_nothrow_constructor:
788 case tok::kw___has_trivial_assign:
789 case tok::kw___has_trivial_copy:
790 case tok::kw___has_trivial_constructor:
791 case tok::kw___has_trivial_destructor:
792 case tok::kw___has_virtual_destructor:
793 case tok::kw___is_abstract:
794 case tok::kw___is_base_of:
795 case tok::kw___is_class:
796 case tok::kw___is_convertible_to:
797 case tok::kw___is_empty:
798 case tok::kw___is_enum:
799 case tok::kw___is_interface_class:
800 case tok::kw___is_final:
801 case tok::kw___is_literal:
802 case tok::kw___is_literal_type:
803 case tok::kw___is_pod:
804 case tok::kw___is_polymorphic:
805 case tok::kw___is_trivial:
806 case tok::kw___is_trivially_assignable:
807 case tok::kw___is_trivially_constructible:
808 case tok::kw___is_trivially_copyable:
809 case tok::kw___is_union:
810 case tok::kw___uuidof:
811 return TPResult::True();
813 // Obviously starts a type-specifier-seq:
822 case tok::kw___int64:
823 case tok::kw___int128:
824 case tok::kw_restrict:
829 case tok::kw_unsigned:
831 case tok::kw_volatile:
833 case tok::kw__Complex:
835 case tok::kw_typename:
836 case tok::kw_wchar_t:
837 case tok::kw_char16_t:
838 case tok::kw_char32_t:
839 case tok::kw___underlying_type:
840 case tok::kw__Decimal32:
841 case tok::kw__Decimal64:
842 case tok::kw__Decimal128:
843 case tok::kw___thread:
844 case tok::kw_thread_local:
845 case tok::kw__Thread_local:
847 case tok::kw___cdecl:
848 case tok::kw___stdcall:
849 case tok::kw___fastcall:
850 case tok::kw___thiscall:
851 case tok::kw___unaligned:
852 case tok::kw___vector:
853 case tok::kw___pixel:
854 case tok::kw__Atomic:
855 case tok::kw_image1d_t:
856 case tok::kw_image1d_array_t:
857 case tok::kw_image1d_buffer_t:
858 case tok::kw_image2d_t:
859 case tok::kw_image2d_array_t:
860 case tok::kw_image3d_t:
861 case tok::kw_sampler_t:
862 case tok::kw_event_t:
863 case tok::kw___unknown_anytype:
864 return TPResult::False();
870 return TPResult::Ambiguous();
873 bool Parser::isTentativelyDeclared(IdentifierInfo *II) {
874 return std::find(TentativelyDeclaredIdentifiers.begin(),
875 TentativelyDeclaredIdentifiers.end(), II)
876 != TentativelyDeclaredIdentifiers.end();
879 /// isCXXDeclarationSpecifier - Returns TPResult::True() if it is a declaration
880 /// specifier, TPResult::False() if it is not, TPResult::Ambiguous() if it could
881 /// be either a decl-specifier or a function-style cast, and TPResult::Error()
882 /// if a parsing error was found and reported.
884 /// If HasMissingTypename is provided, a name with a dependent scope specifier
885 /// will be treated as ambiguous if the 'typename' keyword is missing. If this
886 /// happens, *HasMissingTypename will be set to 'true'. This will also be used
887 /// as an indicator that undeclared identifiers (which will trigger a later
888 /// parse error) should be treated as types. Returns TPResult::Ambiguous() in
892 /// storage-class-specifier
894 /// function-specifier
897 /// [C++11] 'constexpr'
898 /// [GNU] attributes declaration-specifiers[opt]
900 /// storage-class-specifier:
907 /// [C++11] 'thread_local'
908 /// [C11] '_Thread_local'
910 /// function-specifier:
919 /// simple-type-specifier
922 /// elaborated-type-specifier
923 /// typename-specifier
926 /// simple-type-specifier:
927 /// '::'[opt] nested-name-specifier[opt] type-name
928 /// '::'[opt] nested-name-specifier 'template'
929 /// simple-template-id [TODO]
941 /// [GNU] typeof-specifier
944 /// [C++11] 'decltype' ( expression )
945 /// [C++1y] 'decltype' ( 'auto' )
952 /// elaborated-type-specifier:
953 /// class-key '::'[opt] nested-name-specifier[opt] identifier
954 /// class-key '::'[opt] nested-name-specifier[opt] 'template'[opt]
955 /// simple-template-id
956 /// 'enum' '::'[opt] nested-name-specifier[opt] identifier
962 /// 'enum' identifier[opt] '{' enumerator-list[opt] '}'
963 /// 'enum' identifier[opt] '{' enumerator-list ',' '}'
966 /// class-head '{' member-specification[opt] '}'
969 /// class-key identifier[opt] base-clause[opt]
970 /// class-key nested-name-specifier identifier base-clause[opt]
971 /// class-key nested-name-specifier[opt] simple-template-id
985 Parser::isCXXDeclarationSpecifier(Parser::TPResult BracedCastResult,
986 bool *HasMissingTypename) {
987 switch (Tok.getKind()) {
988 case tok::identifier: {
989 // Check for need to substitute AltiVec __vector keyword
990 // for "vector" identifier.
991 if (TryAltiVecVectorToken())
992 return TPResult::True();
994 const Token &Next = NextToken();
995 // In 'foo bar', 'foo' is always a type name outside of Objective-C.
996 if (!getLangOpts().ObjC1 && Next.is(tok::identifier))
997 return TPResult::True();
999 if (Next.isNot(tok::coloncolon) && Next.isNot(tok::less)) {
1000 // Determine whether this is a valid expression. If not, we will hit
1001 // a parse error one way or another. In that case, tell the caller that
1002 // this is ambiguous. Typo-correct to type and expression keywords and
1003 // to types and identifiers, in order to try to recover from errors.
1004 CorrectionCandidateCallback TypoCorrection;
1005 TypoCorrection.WantRemainingKeywords = false;
1006 TypoCorrection.WantTypeSpecifiers = Next.isNot(tok::arrow);
1007 switch (TryAnnotateName(false /* no nested name specifier */,
1010 return TPResult::Error();
1011 case ANK_TentativeDecl:
1012 return TPResult::False();
1013 case ANK_TemplateName:
1014 // A bare type template-name which can't be a template template
1015 // argument is an error, and was probably intended to be a type.
1016 return GreaterThanIsOperator ? TPResult::True() : TPResult::False();
1017 case ANK_Unresolved:
1018 return HasMissingTypename ? TPResult::Ambiguous() : TPResult::False();
1022 assert(Tok.isNot(tok::identifier) &&
1023 "TryAnnotateName succeeded without producing an annotation");
1025 // This might possibly be a type with a dependent scope specifier and
1026 // a missing 'typename' keyword. Don't use TryAnnotateName in this case,
1027 // since it will annotate as a primary expression, and we want to use the
1028 // "missing 'typename'" logic.
1029 if (TryAnnotateTypeOrScopeToken())
1030 return TPResult::Error();
1031 // If annotation failed, assume it's a non-type.
1032 // FIXME: If this happens due to an undeclared identifier, treat it as
1034 if (Tok.is(tok::identifier))
1035 return TPResult::False();
1038 // We annotated this token as something. Recurse to handle whatever we got.
1039 return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
1042 case tok::kw_typename: // typename T::type
1043 // Annotate typenames and C++ scope specifiers. If we get one, just
1044 // recurse to handle whatever we get.
1045 if (TryAnnotateTypeOrScopeToken())
1046 return TPResult::Error();
1047 return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
1049 case tok::coloncolon: { // ::foo::bar
1050 const Token &Next = NextToken();
1051 if (Next.is(tok::kw_new) || // ::new
1052 Next.is(tok::kw_delete)) // ::delete
1053 return TPResult::False();
1056 case tok::kw_decltype:
1057 // Annotate typenames and C++ scope specifiers. If we get one, just
1058 // recurse to handle whatever we get.
1059 if (TryAnnotateTypeOrScopeToken())
1060 return TPResult::Error();
1061 return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
1064 // storage-class-specifier
1066 // function-specifier
1070 case tok::kw_friend:
1071 case tok::kw_typedef:
1072 case tok::kw_constexpr:
1073 // storage-class-specifier
1074 case tok::kw_register:
1075 case tok::kw_static:
1076 case tok::kw_extern:
1077 case tok::kw_mutable:
1079 case tok::kw___thread:
1080 case tok::kw_thread_local:
1081 case tok::kw__Thread_local:
1082 // function-specifier
1083 case tok::kw_inline:
1084 case tok::kw_virtual:
1085 case tok::kw_explicit:
1088 case tok::kw___module_private__:
1091 case tok::kw___unknown_anytype:
1094 // simple-type-specifier
1097 // elaborated-type-specifier
1098 // typename-specifier
1102 // elaborated-type-specifier
1104 case tok::kw_struct:
1110 case tok::kw_volatile:
1113 case tok::kw_restrict:
1114 case tok::kw__Complex:
1115 case tok::kw___attribute:
1116 return TPResult::True();
1119 case tok::kw___declspec:
1120 case tok::kw___cdecl:
1121 case tok::kw___stdcall:
1122 case tok::kw___fastcall:
1123 case tok::kw___thiscall:
1125 case tok::kw___ptr64:
1126 case tok::kw___ptr32:
1127 case tok::kw___forceinline:
1128 case tok::kw___unaligned:
1129 return TPResult::True();
1132 case tok::kw___pascal:
1133 return TPResult::True();
1136 case tok::kw___vector:
1137 return TPResult::True();
1139 case tok::annot_template_id: {
1140 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1141 if (TemplateId->Kind != TNK_Type_template)
1142 return TPResult::False();
1144 AnnotateTemplateIdTokenAsType();
1145 assert(Tok.is(tok::annot_typename));
1149 case tok::annot_cxxscope: // foo::bar or ::foo::bar, but already parsed
1150 // We've already annotated a scope; try to annotate a type.
1151 if (TryAnnotateTypeOrScopeToken())
1152 return TPResult::Error();
1153 if (!Tok.is(tok::annot_typename)) {
1154 // If the next token is an identifier or a type qualifier, then this
1155 // can't possibly be a valid expression either.
1156 if (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier)) {
1158 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
1159 Tok.getAnnotationRange(),
1161 if (SS.getScopeRep() && SS.getScopeRep()->isDependent()) {
1162 TentativeParsingAction PA(*this);
1165 bool isIdentifier = Tok.is(tok::identifier);
1166 TPResult TPR = TPResult::False();
1168 TPR = isCXXDeclarationSpecifier(BracedCastResult,
1169 HasMissingTypename);
1173 TPR == TPResult::True() || TPR == TPResult::Error())
1174 return TPResult::Error();
1176 if (HasMissingTypename) {
1177 // We can't tell whether this is a missing 'typename' or a valid
1179 *HasMissingTypename = true;
1180 return TPResult::Ambiguous();
1183 // Try to resolve the name. If it doesn't exist, assume it was
1184 // intended to name a type and keep disambiguating.
1185 switch (TryAnnotateName(false /* SS is not dependent */)) {
1187 return TPResult::Error();
1188 case ANK_TentativeDecl:
1189 return TPResult::False();
1190 case ANK_TemplateName:
1191 // A bare type template-name which can't be a template template
1192 // argument is an error, and was probably intended to be a type.
1193 return GreaterThanIsOperator ? TPResult::True() : TPResult::False();
1194 case ANK_Unresolved:
1195 return HasMissingTypename ? TPResult::Ambiguous()
1196 : TPResult::False();
1198 // Annotated it, check again.
1199 assert(Tok.isNot(tok::annot_cxxscope) ||
1200 NextToken().isNot(tok::identifier));
1201 return isCXXDeclarationSpecifier(BracedCastResult,
1202 HasMissingTypename);
1206 return TPResult::False();
1208 // If that succeeded, fallthrough into the generic simple-type-id case.
1210 // The ambiguity resides in a simple-type-specifier/typename-specifier
1211 // followed by a '('. The '(' could either be the start of:
1213 // direct-declarator:
1214 // '(' declarator ')'
1216 // direct-abstract-declarator:
1217 // '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1218 // exception-specification[opt]
1219 // '(' abstract-declarator ')'
1221 // or part of a function-style cast expression:
1223 // simple-type-specifier '(' expression-list[opt] ')'
1226 // simple-type-specifier:
1228 case tok::annot_typename:
1230 // In Objective-C, we might have a protocol-qualified type.
1231 if (getLangOpts().ObjC1 && NextToken().is(tok::less)) {
1232 // Tentatively parse the
1233 TentativeParsingAction PA(*this);
1234 ConsumeToken(); // The type token
1236 TPResult TPR = TryParseProtocolQualifiers();
1237 bool isFollowedByParen = Tok.is(tok::l_paren);
1238 bool isFollowedByBrace = Tok.is(tok::l_brace);
1242 if (TPR == TPResult::Error())
1243 return TPResult::Error();
1245 if (isFollowedByParen)
1246 return TPResult::Ambiguous();
1248 if (getLangOpts().CPlusPlus11 && isFollowedByBrace)
1249 return BracedCastResult;
1251 return TPResult::True();
1255 case tok::kw_wchar_t:
1256 case tok::kw_char16_t:
1257 case tok::kw_char32_t:
1262 case tok::kw___int64:
1263 case tok::kw___int128:
1264 case tok::kw_signed:
1265 case tok::kw_unsigned:
1268 case tok::kw_double:
1270 case tok::annot_decltype:
1271 if (NextToken().is(tok::l_paren))
1272 return TPResult::Ambiguous();
1274 // This is a function-style cast in all cases we disambiguate other than
1277 // enum E : int { a = 4 }; // enum
1278 // enum E : int { 4 }; // bit-field
1280 if (getLangOpts().CPlusPlus11 && NextToken().is(tok::l_brace))
1281 return BracedCastResult;
1283 if (isStartOfObjCClassMessageMissingOpenBracket())
1284 return TPResult::False();
1286 return TPResult::True();
1288 // GNU typeof support.
1289 case tok::kw_typeof: {
1290 if (NextToken().isNot(tok::l_paren))
1291 return TPResult::True();
1293 TentativeParsingAction PA(*this);
1295 TPResult TPR = TryParseTypeofSpecifier();
1296 bool isFollowedByParen = Tok.is(tok::l_paren);
1297 bool isFollowedByBrace = Tok.is(tok::l_brace);
1301 if (TPR == TPResult::Error())
1302 return TPResult::Error();
1304 if (isFollowedByParen)
1305 return TPResult::Ambiguous();
1307 if (getLangOpts().CPlusPlus11 && isFollowedByBrace)
1308 return BracedCastResult;
1310 return TPResult::True();
1313 // C++0x type traits support
1314 case tok::kw___underlying_type:
1315 return TPResult::True();
1318 case tok::kw__Atomic:
1319 return TPResult::True();
1322 return TPResult::False();
1326 /// [GNU] typeof-specifier:
1327 /// 'typeof' '(' expressions ')'
1328 /// 'typeof' '(' type-name ')'
1330 Parser::TPResult Parser::TryParseTypeofSpecifier() {
1331 assert(Tok.is(tok::kw_typeof) && "Expected 'typeof'!");
1334 assert(Tok.is(tok::l_paren) && "Expected '('");
1335 // Parse through the parens after 'typeof'.
1337 if (!SkipUntil(tok::r_paren))
1338 return TPResult::Error();
1340 return TPResult::Ambiguous();
1343 /// [ObjC] protocol-qualifiers:
1344 //// '<' identifier-list '>'
1345 Parser::TPResult Parser::TryParseProtocolQualifiers() {
1346 assert(Tok.is(tok::less) && "Expected '<' for qualifier list");
1349 if (Tok.isNot(tok::identifier))
1350 return TPResult::Error();
1353 if (Tok.is(tok::comma)) {
1358 if (Tok.is(tok::greater)) {
1360 return TPResult::Ambiguous();
1364 return TPResult::Error();
1368 Parser::TryParseDeclarationSpecifier(bool *HasMissingTypename) {
1369 TPResult TPR = isCXXDeclarationSpecifier(TPResult::False(),
1370 HasMissingTypename);
1371 if (TPR != TPResult::Ambiguous())
1374 if (Tok.is(tok::kw_typeof))
1375 TryParseTypeofSpecifier();
1377 if (Tok.is(tok::annot_cxxscope))
1381 if (getLangOpts().ObjC1 && Tok.is(tok::less))
1382 TryParseProtocolQualifiers();
1385 return TPResult::Ambiguous();
1388 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
1389 /// a constructor-style initializer, when parsing declaration statements.
1390 /// Returns true for function declarator and false for constructor-style
1392 /// If during the disambiguation process a parsing error is encountered,
1393 /// the function returns true to let the declaration parsing code handle it.
1395 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1396 /// exception-specification[opt]
1398 bool Parser::isCXXFunctionDeclarator(bool *IsAmbiguous) {
1401 // The ambiguity arising from the similarity between a function-style cast and
1402 // a declaration mentioned in 6.8 can also occur in the context of a
1403 // declaration. In that context, the choice is between a function declaration
1404 // with a redundant set of parentheses around a parameter name and an object
1405 // declaration with a function-style cast as the initializer. Just as for the
1406 // ambiguities mentioned in 6.8, the resolution is to consider any construct
1407 // that could possibly be a declaration a declaration.
1409 TentativeParsingAction PA(*this);
1412 bool InvalidAsDeclaration = false;
1413 TPResult TPR = TryParseParameterDeclarationClause(&InvalidAsDeclaration);
1414 if (TPR == TPResult::Ambiguous()) {
1415 if (Tok.isNot(tok::r_paren))
1416 TPR = TPResult::False();
1418 const Token &Next = NextToken();
1419 if (Next.is(tok::amp) || Next.is(tok::ampamp) ||
1420 Next.is(tok::kw_const) || Next.is(tok::kw_volatile) ||
1421 Next.is(tok::kw_throw) || Next.is(tok::kw_noexcept) ||
1422 Next.is(tok::l_square) || isCXX11VirtSpecifier(Next) ||
1423 Next.is(tok::l_brace) || Next.is(tok::kw_try) ||
1424 Next.is(tok::equal) || Next.is(tok::arrow))
1425 // The next token cannot appear after a constructor-style initializer,
1426 // and can appear next in a function definition. This must be a function
1428 TPR = TPResult::True();
1429 else if (InvalidAsDeclaration)
1430 // Use the absence of 'typename' as a tie-breaker.
1431 TPR = TPResult::False();
1437 if (IsAmbiguous && TPR == TPResult::Ambiguous())
1438 *IsAmbiguous = true;
1440 // In case of an error, let the declaration parsing code handle it.
1441 return TPR != TPResult::False();
1444 /// parameter-declaration-clause:
1445 /// parameter-declaration-list[opt] '...'[opt]
1446 /// parameter-declaration-list ',' '...'
1448 /// parameter-declaration-list:
1449 /// parameter-declaration
1450 /// parameter-declaration-list ',' parameter-declaration
1452 /// parameter-declaration:
1453 /// attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
1454 /// attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
1455 /// '=' assignment-expression
1456 /// attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
1458 /// attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
1459 /// attributes[opt] '=' assignment-expression
1462 Parser::TryParseParameterDeclarationClause(bool *InvalidAsDeclaration) {
1464 if (Tok.is(tok::r_paren))
1465 return TPResult::Ambiguous();
1467 // parameter-declaration-list[opt] '...'[opt]
1468 // parameter-declaration-list ',' '...'
1470 // parameter-declaration-list:
1471 // parameter-declaration
1472 // parameter-declaration-list ',' parameter-declaration
1476 if (Tok.is(tok::ellipsis)) {
1478 if (Tok.is(tok::r_paren))
1479 return TPResult::True(); // '...)' is a sign of a function declarator.
1481 return TPResult::False();
1484 // An attribute-specifier-seq here is a sign of a function declarator.
1485 if (isCXX11AttributeSpecifier(/*Disambiguate*/false,
1486 /*OuterMightBeMessageSend*/true))
1487 return TPResult::True();
1489 ParsedAttributes attrs(AttrFactory);
1490 MaybeParseMicrosoftAttributes(attrs);
1492 // decl-specifier-seq
1493 // A parameter-declaration's initializer must be preceded by an '=', so
1494 // decl-specifier-seq '{' is not a parameter in C++11.
1495 TPResult TPR = TryParseDeclarationSpecifier(InvalidAsDeclaration);
1496 if (TPR != TPResult::Ambiguous())
1500 // abstract-declarator[opt]
1501 TPR = TryParseDeclarator(true/*mayBeAbstract*/);
1502 if (TPR != TPResult::Ambiguous())
1505 // [GNU] attributes[opt]
1506 if (Tok.is(tok::kw___attribute))
1507 return TPResult::True();
1509 if (Tok.is(tok::equal)) {
1510 // '=' assignment-expression
1511 // Parse through assignment-expression.
1512 if (!SkipUntil(tok::comma, tok::r_paren, true/*StopAtSemi*/,
1513 true/*DontConsume*/))
1514 return TPResult::Error();
1517 if (Tok.is(tok::ellipsis)) {
1519 if (Tok.is(tok::r_paren))
1520 return TPResult::True(); // '...)' is a sign of a function declarator.
1522 return TPResult::False();
1525 if (Tok.isNot(tok::comma))
1527 ConsumeToken(); // the comma.
1530 return TPResult::Ambiguous();
1533 /// TryParseFunctionDeclarator - We parsed a '(' and we want to try to continue
1534 /// parsing as a function declarator.
1535 /// If TryParseFunctionDeclarator fully parsed the function declarator, it will
1536 /// return TPResult::Ambiguous(), otherwise it will return either False() or
1539 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1540 /// exception-specification[opt]
1542 /// exception-specification:
1543 /// 'throw' '(' type-id-list[opt] ')'
1545 Parser::TPResult Parser::TryParseFunctionDeclarator() {
1547 // The '(' is already parsed.
1549 TPResult TPR = TryParseParameterDeclarationClause();
1550 if (TPR == TPResult::Ambiguous() && Tok.isNot(tok::r_paren))
1551 TPR = TPResult::False();
1553 if (TPR == TPResult::False() || TPR == TPResult::Error())
1556 // Parse through the parens.
1557 if (!SkipUntil(tok::r_paren))
1558 return TPResult::Error();
1561 while (Tok.is(tok::kw_const) ||
1562 Tok.is(tok::kw_volatile) ||
1563 Tok.is(tok::kw_restrict) )
1566 // ref-qualifier[opt]
1567 if (Tok.is(tok::amp) || Tok.is(tok::ampamp))
1570 // exception-specification
1571 if (Tok.is(tok::kw_throw)) {
1573 if (Tok.isNot(tok::l_paren))
1574 return TPResult::Error();
1576 // Parse through the parens after 'throw'.
1578 if (!SkipUntil(tok::r_paren))
1579 return TPResult::Error();
1581 if (Tok.is(tok::kw_noexcept)) {
1583 // Possibly an expression as well.
1584 if (Tok.is(tok::l_paren)) {
1585 // Find the matching rparen.
1587 if (!SkipUntil(tok::r_paren))
1588 return TPResult::Error();
1592 return TPResult::Ambiguous();
1595 /// '[' constant-expression[opt] ']'
1597 Parser::TPResult Parser::TryParseBracketDeclarator() {
1599 if (!SkipUntil(tok::r_square))
1600 return TPResult::Error();
1602 return TPResult::Ambiguous();