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_thread_local:
841 case tok::kw__Decimal32:
842 case tok::kw__Decimal64:
843 case tok::kw__Decimal128:
844 case tok::kw___thread:
846 case tok::kw___cdecl:
847 case tok::kw___stdcall:
848 case tok::kw___fastcall:
849 case tok::kw___thiscall:
850 case tok::kw___unaligned:
851 case tok::kw___vector:
852 case tok::kw___pixel:
853 case tok::kw__Atomic:
854 case tok::kw_image1d_t:
855 case tok::kw_image1d_array_t:
856 case tok::kw_image1d_buffer_t:
857 case tok::kw_image2d_t:
858 case tok::kw_image2d_array_t:
859 case tok::kw_image3d_t:
860 case tok::kw_sampler_t:
861 case tok::kw_event_t:
862 case tok::kw___unknown_anytype:
863 return TPResult::False();
869 return TPResult::Ambiguous();
872 bool Parser::isTentativelyDeclared(IdentifierInfo *II) {
873 return std::find(TentativelyDeclaredIdentifiers.begin(),
874 TentativelyDeclaredIdentifiers.end(), II)
875 != TentativelyDeclaredIdentifiers.end();
878 /// isCXXDeclarationSpecifier - Returns TPResult::True() if it is a declaration
879 /// specifier, TPResult::False() if it is not, TPResult::Ambiguous() if it could
880 /// be either a decl-specifier or a function-style cast, and TPResult::Error()
881 /// if a parsing error was found and reported.
883 /// If HasMissingTypename is provided, a name with a dependent scope specifier
884 /// will be treated as ambiguous if the 'typename' keyword is missing. If this
885 /// happens, *HasMissingTypename will be set to 'true'. This will also be used
886 /// as an indicator that undeclared identifiers (which will trigger a later
887 /// parse error) should be treated as types. Returns TPResult::Ambiguous() in
891 /// storage-class-specifier
893 /// function-specifier
896 /// [C++0x] 'constexpr'
897 /// [GNU] attributes declaration-specifiers[opt]
899 /// storage-class-specifier:
907 /// function-specifier:
916 /// simple-type-specifier
919 /// elaborated-type-specifier
920 /// typename-specifier
923 /// simple-type-specifier:
924 /// '::'[opt] nested-name-specifier[opt] type-name
925 /// '::'[opt] nested-name-specifier 'template'
926 /// simple-template-id [TODO]
938 /// [GNU] typeof-specifier
940 /// [C++0x] 'auto' [TODO]
941 /// [C++0x] 'decltype' ( expression )
948 /// elaborated-type-specifier:
949 /// class-key '::'[opt] nested-name-specifier[opt] identifier
950 /// class-key '::'[opt] nested-name-specifier[opt] 'template'[opt]
951 /// simple-template-id
952 /// 'enum' '::'[opt] nested-name-specifier[opt] identifier
958 /// 'enum' identifier[opt] '{' enumerator-list[opt] '}'
959 /// 'enum' identifier[opt] '{' enumerator-list ',' '}'
962 /// class-head '{' member-specification[opt] '}'
965 /// class-key identifier[opt] base-clause[opt]
966 /// class-key nested-name-specifier identifier base-clause[opt]
967 /// class-key nested-name-specifier[opt] simple-template-id
981 Parser::isCXXDeclarationSpecifier(Parser::TPResult BracedCastResult,
982 bool *HasMissingTypename) {
983 switch (Tok.getKind()) {
984 case tok::identifier: {
985 // Check for need to substitute AltiVec __vector keyword
986 // for "vector" identifier.
987 if (TryAltiVecVectorToken())
988 return TPResult::True();
990 const Token &Next = NextToken();
991 // In 'foo bar', 'foo' is always a type name outside of Objective-C.
992 if (!getLangOpts().ObjC1 && Next.is(tok::identifier))
993 return TPResult::True();
995 if (Next.isNot(tok::coloncolon) && Next.isNot(tok::less)) {
996 // Determine whether this is a valid expression. If not, we will hit
997 // a parse error one way or another. In that case, tell the caller that
998 // this is ambiguous. Typo-correct to type and expression keywords and
999 // to types and identifiers, in order to try to recover from errors.
1000 CorrectionCandidateCallback TypoCorrection;
1001 TypoCorrection.WantRemainingKeywords = false;
1002 TypoCorrection.WantTypeSpecifiers = Next.isNot(tok::arrow);
1003 switch (TryAnnotateName(false /* no nested name specifier */,
1006 return TPResult::Error();
1007 case ANK_TentativeDecl:
1008 return TPResult::False();
1009 case ANK_TemplateName:
1010 // A bare type template-name which can't be a template template
1011 // argument is an error, and was probably intended to be a type.
1012 return GreaterThanIsOperator ? TPResult::True() : TPResult::False();
1013 case ANK_Unresolved:
1014 return HasMissingTypename ? TPResult::Ambiguous() : TPResult::False();
1018 assert(Tok.isNot(tok::identifier) &&
1019 "TryAnnotateName succeeded without producing an annotation");
1021 // This might possibly be a type with a dependent scope specifier and
1022 // a missing 'typename' keyword. Don't use TryAnnotateName in this case,
1023 // since it will annotate as a primary expression, and we want to use the
1024 // "missing 'typename'" logic.
1025 if (TryAnnotateTypeOrScopeToken())
1026 return TPResult::Error();
1027 // If annotation failed, assume it's a non-type.
1028 // FIXME: If this happens due to an undeclared identifier, treat it as
1030 if (Tok.is(tok::identifier))
1031 return TPResult::False();
1034 // We annotated this token as something. Recurse to handle whatever we got.
1035 return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
1038 case tok::kw_typename: // typename T::type
1039 // Annotate typenames and C++ scope specifiers. If we get one, just
1040 // recurse to handle whatever we get.
1041 if (TryAnnotateTypeOrScopeToken())
1042 return TPResult::Error();
1043 return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
1045 case tok::coloncolon: { // ::foo::bar
1046 const Token &Next = NextToken();
1047 if (Next.is(tok::kw_new) || // ::new
1048 Next.is(tok::kw_delete)) // ::delete
1049 return TPResult::False();
1052 case tok::kw_decltype:
1053 // Annotate typenames and C++ scope specifiers. If we get one, just
1054 // recurse to handle whatever we get.
1055 if (TryAnnotateTypeOrScopeToken())
1056 return TPResult::Error();
1057 return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
1060 // storage-class-specifier
1062 // function-specifier
1066 case tok::kw_friend:
1067 case tok::kw_typedef:
1068 case tok::kw_constexpr:
1069 // storage-class-specifier
1070 case tok::kw_register:
1071 case tok::kw_static:
1072 case tok::kw_extern:
1073 case tok::kw_mutable:
1075 case tok::kw___thread:
1076 // function-specifier
1077 case tok::kw_inline:
1078 case tok::kw_virtual:
1079 case tok::kw_explicit:
1082 case tok::kw___module_private__:
1085 case tok::kw___unknown_anytype:
1088 // simple-type-specifier
1091 // elaborated-type-specifier
1092 // typename-specifier
1096 // elaborated-type-specifier
1098 case tok::kw_struct:
1104 case tok::kw_volatile:
1107 case tok::kw_restrict:
1108 case tok::kw__Complex:
1109 case tok::kw___attribute:
1110 return TPResult::True();
1113 case tok::kw___declspec:
1114 case tok::kw___cdecl:
1115 case tok::kw___stdcall:
1116 case tok::kw___fastcall:
1117 case tok::kw___thiscall:
1119 case tok::kw___ptr64:
1120 case tok::kw___ptr32:
1121 case tok::kw___forceinline:
1122 case tok::kw___unaligned:
1123 return TPResult::True();
1126 case tok::kw___pascal:
1127 return TPResult::True();
1130 case tok::kw___vector:
1131 return TPResult::True();
1133 case tok::annot_template_id: {
1134 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1135 if (TemplateId->Kind != TNK_Type_template)
1136 return TPResult::False();
1138 AnnotateTemplateIdTokenAsType();
1139 assert(Tok.is(tok::annot_typename));
1143 case tok::annot_cxxscope: // foo::bar or ::foo::bar, but already parsed
1144 // We've already annotated a scope; try to annotate a type.
1145 if (TryAnnotateTypeOrScopeToken())
1146 return TPResult::Error();
1147 if (!Tok.is(tok::annot_typename)) {
1148 // If the next token is an identifier or a type qualifier, then this
1149 // can't possibly be a valid expression either.
1150 if (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier)) {
1152 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
1153 Tok.getAnnotationRange(),
1155 if (SS.getScopeRep() && SS.getScopeRep()->isDependent()) {
1156 TentativeParsingAction PA(*this);
1159 bool isIdentifier = Tok.is(tok::identifier);
1160 TPResult TPR = TPResult::False();
1162 TPR = isCXXDeclarationSpecifier(BracedCastResult,
1163 HasMissingTypename);
1167 TPR == TPResult::True() || TPR == TPResult::Error())
1168 return TPResult::Error();
1170 if (HasMissingTypename) {
1171 // We can't tell whether this is a missing 'typename' or a valid
1173 *HasMissingTypename = true;
1174 return TPResult::Ambiguous();
1177 // Try to resolve the name. If it doesn't exist, assume it was
1178 // intended to name a type and keep disambiguating.
1179 switch (TryAnnotateName(false /* SS is not dependent */)) {
1181 return TPResult::Error();
1182 case ANK_TentativeDecl:
1183 return TPResult::False();
1184 case ANK_TemplateName:
1185 // A bare type template-name which can't be a template template
1186 // argument is an error, and was probably intended to be a type.
1187 return GreaterThanIsOperator ? TPResult::True() : TPResult::False();
1188 case ANK_Unresolved:
1189 return HasMissingTypename ? TPResult::Ambiguous()
1190 : TPResult::False();
1192 // Annotated it, check again.
1193 assert(Tok.isNot(tok::annot_cxxscope) ||
1194 NextToken().isNot(tok::identifier));
1195 return isCXXDeclarationSpecifier(BracedCastResult,
1196 HasMissingTypename);
1200 return TPResult::False();
1202 // If that succeeded, fallthrough into the generic simple-type-id case.
1204 // The ambiguity resides in a simple-type-specifier/typename-specifier
1205 // followed by a '('. The '(' could either be the start of:
1207 // direct-declarator:
1208 // '(' declarator ')'
1210 // direct-abstract-declarator:
1211 // '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1212 // exception-specification[opt]
1213 // '(' abstract-declarator ')'
1215 // or part of a function-style cast expression:
1217 // simple-type-specifier '(' expression-list[opt] ')'
1220 // simple-type-specifier:
1222 case tok::annot_typename:
1224 // In Objective-C, we might have a protocol-qualified type.
1225 if (getLangOpts().ObjC1 && NextToken().is(tok::less)) {
1226 // Tentatively parse the
1227 TentativeParsingAction PA(*this);
1228 ConsumeToken(); // The type token
1230 TPResult TPR = TryParseProtocolQualifiers();
1231 bool isFollowedByParen = Tok.is(tok::l_paren);
1232 bool isFollowedByBrace = Tok.is(tok::l_brace);
1236 if (TPR == TPResult::Error())
1237 return TPResult::Error();
1239 if (isFollowedByParen)
1240 return TPResult::Ambiguous();
1242 if (getLangOpts().CPlusPlus11 && isFollowedByBrace)
1243 return BracedCastResult;
1245 return TPResult::True();
1249 case tok::kw_wchar_t:
1250 case tok::kw_char16_t:
1251 case tok::kw_char32_t:
1256 case tok::kw___int64:
1257 case tok::kw___int128:
1258 case tok::kw_signed:
1259 case tok::kw_unsigned:
1262 case tok::kw_double:
1264 case tok::annot_decltype:
1265 if (NextToken().is(tok::l_paren))
1266 return TPResult::Ambiguous();
1268 // This is a function-style cast in all cases we disambiguate other than
1271 // enum E : int { a = 4 }; // enum
1272 // enum E : int { 4 }; // bit-field
1274 if (getLangOpts().CPlusPlus11 && NextToken().is(tok::l_brace))
1275 return BracedCastResult;
1277 if (isStartOfObjCClassMessageMissingOpenBracket())
1278 return TPResult::False();
1280 return TPResult::True();
1282 // GNU typeof support.
1283 case tok::kw_typeof: {
1284 if (NextToken().isNot(tok::l_paren))
1285 return TPResult::True();
1287 TentativeParsingAction PA(*this);
1289 TPResult TPR = TryParseTypeofSpecifier();
1290 bool isFollowedByParen = Tok.is(tok::l_paren);
1291 bool isFollowedByBrace = Tok.is(tok::l_brace);
1295 if (TPR == TPResult::Error())
1296 return TPResult::Error();
1298 if (isFollowedByParen)
1299 return TPResult::Ambiguous();
1301 if (getLangOpts().CPlusPlus11 && isFollowedByBrace)
1302 return BracedCastResult;
1304 return TPResult::True();
1307 // C++0x type traits support
1308 case tok::kw___underlying_type:
1309 return TPResult::True();
1312 case tok::kw__Atomic:
1313 return TPResult::True();
1316 return TPResult::False();
1320 /// [GNU] typeof-specifier:
1321 /// 'typeof' '(' expressions ')'
1322 /// 'typeof' '(' type-name ')'
1324 Parser::TPResult Parser::TryParseTypeofSpecifier() {
1325 assert(Tok.is(tok::kw_typeof) && "Expected 'typeof'!");
1328 assert(Tok.is(tok::l_paren) && "Expected '('");
1329 // Parse through the parens after 'typeof'.
1331 if (!SkipUntil(tok::r_paren))
1332 return TPResult::Error();
1334 return TPResult::Ambiguous();
1337 /// [ObjC] protocol-qualifiers:
1338 //// '<' identifier-list '>'
1339 Parser::TPResult Parser::TryParseProtocolQualifiers() {
1340 assert(Tok.is(tok::less) && "Expected '<' for qualifier list");
1343 if (Tok.isNot(tok::identifier))
1344 return TPResult::Error();
1347 if (Tok.is(tok::comma)) {
1352 if (Tok.is(tok::greater)) {
1354 return TPResult::Ambiguous();
1358 return TPResult::Error();
1362 Parser::TryParseDeclarationSpecifier(bool *HasMissingTypename) {
1363 TPResult TPR = isCXXDeclarationSpecifier(TPResult::False(),
1364 HasMissingTypename);
1365 if (TPR != TPResult::Ambiguous())
1368 if (Tok.is(tok::kw_typeof))
1369 TryParseTypeofSpecifier();
1371 if (Tok.is(tok::annot_cxxscope))
1375 if (getLangOpts().ObjC1 && Tok.is(tok::less))
1376 TryParseProtocolQualifiers();
1379 return TPResult::Ambiguous();
1382 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
1383 /// a constructor-style initializer, when parsing declaration statements.
1384 /// Returns true for function declarator and false for constructor-style
1386 /// If during the disambiguation process a parsing error is encountered,
1387 /// the function returns true to let the declaration parsing code handle it.
1389 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1390 /// exception-specification[opt]
1392 bool Parser::isCXXFunctionDeclarator(bool *IsAmbiguous) {
1395 // The ambiguity arising from the similarity between a function-style cast and
1396 // a declaration mentioned in 6.8 can also occur in the context of a
1397 // declaration. In that context, the choice is between a function declaration
1398 // with a redundant set of parentheses around a parameter name and an object
1399 // declaration with a function-style cast as the initializer. Just as for the
1400 // ambiguities mentioned in 6.8, the resolution is to consider any construct
1401 // that could possibly be a declaration a declaration.
1403 TentativeParsingAction PA(*this);
1406 bool InvalidAsDeclaration = false;
1407 TPResult TPR = TryParseParameterDeclarationClause(&InvalidAsDeclaration);
1408 if (TPR == TPResult::Ambiguous()) {
1409 if (Tok.isNot(tok::r_paren))
1410 TPR = TPResult::False();
1412 const Token &Next = NextToken();
1413 if (Next.is(tok::amp) || Next.is(tok::ampamp) ||
1414 Next.is(tok::kw_const) || Next.is(tok::kw_volatile) ||
1415 Next.is(tok::kw_throw) || Next.is(tok::kw_noexcept) ||
1416 Next.is(tok::l_square) || isCXX11VirtSpecifier(Next) ||
1417 Next.is(tok::l_brace) || Next.is(tok::kw_try) ||
1418 Next.is(tok::equal) || Next.is(tok::arrow))
1419 // The next token cannot appear after a constructor-style initializer,
1420 // and can appear next in a function definition. This must be a function
1422 TPR = TPResult::True();
1423 else if (InvalidAsDeclaration)
1424 // Use the absence of 'typename' as a tie-breaker.
1425 TPR = TPResult::False();
1431 if (IsAmbiguous && TPR == TPResult::Ambiguous())
1432 *IsAmbiguous = true;
1434 // In case of an error, let the declaration parsing code handle it.
1435 return TPR != TPResult::False();
1438 /// parameter-declaration-clause:
1439 /// parameter-declaration-list[opt] '...'[opt]
1440 /// parameter-declaration-list ',' '...'
1442 /// parameter-declaration-list:
1443 /// parameter-declaration
1444 /// parameter-declaration-list ',' parameter-declaration
1446 /// parameter-declaration:
1447 /// attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
1448 /// attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
1449 /// '=' assignment-expression
1450 /// attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
1452 /// attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
1453 /// attributes[opt] '=' assignment-expression
1456 Parser::TryParseParameterDeclarationClause(bool *InvalidAsDeclaration) {
1458 if (Tok.is(tok::r_paren))
1459 return TPResult::Ambiguous();
1461 // parameter-declaration-list[opt] '...'[opt]
1462 // parameter-declaration-list ',' '...'
1464 // parameter-declaration-list:
1465 // parameter-declaration
1466 // parameter-declaration-list ',' parameter-declaration
1470 if (Tok.is(tok::ellipsis)) {
1472 if (Tok.is(tok::r_paren))
1473 return TPResult::True(); // '...)' is a sign of a function declarator.
1475 return TPResult::False();
1478 // An attribute-specifier-seq here is a sign of a function declarator.
1479 if (isCXX11AttributeSpecifier(/*Disambiguate*/false,
1480 /*OuterMightBeMessageSend*/true))
1481 return TPResult::True();
1483 ParsedAttributes attrs(AttrFactory);
1484 MaybeParseMicrosoftAttributes(attrs);
1486 // decl-specifier-seq
1487 // A parameter-declaration's initializer must be preceded by an '=', so
1488 // decl-specifier-seq '{' is not a parameter in C++11.
1489 TPResult TPR = TryParseDeclarationSpecifier(InvalidAsDeclaration);
1490 if (TPR != TPResult::Ambiguous())
1494 // abstract-declarator[opt]
1495 TPR = TryParseDeclarator(true/*mayBeAbstract*/);
1496 if (TPR != TPResult::Ambiguous())
1499 // [GNU] attributes[opt]
1500 if (Tok.is(tok::kw___attribute))
1501 return TPResult::True();
1503 if (Tok.is(tok::equal)) {
1504 // '=' assignment-expression
1505 // Parse through assignment-expression.
1506 if (!SkipUntil(tok::comma, tok::r_paren, true/*StopAtSemi*/,
1507 true/*DontConsume*/))
1508 return TPResult::Error();
1511 if (Tok.is(tok::ellipsis)) {
1513 if (Tok.is(tok::r_paren))
1514 return TPResult::True(); // '...)' is a sign of a function declarator.
1516 return TPResult::False();
1519 if (Tok.isNot(tok::comma))
1521 ConsumeToken(); // the comma.
1524 return TPResult::Ambiguous();
1527 /// TryParseFunctionDeclarator - We parsed a '(' and we want to try to continue
1528 /// parsing as a function declarator.
1529 /// If TryParseFunctionDeclarator fully parsed the function declarator, it will
1530 /// return TPResult::Ambiguous(), otherwise it will return either False() or
1533 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1534 /// exception-specification[opt]
1536 /// exception-specification:
1537 /// 'throw' '(' type-id-list[opt] ')'
1539 Parser::TPResult Parser::TryParseFunctionDeclarator() {
1541 // The '(' is already parsed.
1543 TPResult TPR = TryParseParameterDeclarationClause();
1544 if (TPR == TPResult::Ambiguous() && Tok.isNot(tok::r_paren))
1545 TPR = TPResult::False();
1547 if (TPR == TPResult::False() || TPR == TPResult::Error())
1550 // Parse through the parens.
1551 if (!SkipUntil(tok::r_paren))
1552 return TPResult::Error();
1555 while (Tok.is(tok::kw_const) ||
1556 Tok.is(tok::kw_volatile) ||
1557 Tok.is(tok::kw_restrict) )
1560 // ref-qualifier[opt]
1561 if (Tok.is(tok::amp) || Tok.is(tok::ampamp))
1564 // exception-specification
1565 if (Tok.is(tok::kw_throw)) {
1567 if (Tok.isNot(tok::l_paren))
1568 return TPResult::Error();
1570 // Parse through the parens after 'throw'.
1572 if (!SkipUntil(tok::r_paren))
1573 return TPResult::Error();
1575 if (Tok.is(tok::kw_noexcept)) {
1577 // Possibly an expression as well.
1578 if (Tok.is(tok::l_paren)) {
1579 // Find the matching rparen.
1581 if (!SkipUntil(tok::r_paren))
1582 return TPResult::Error();
1586 return TPResult::Ambiguous();
1589 /// '[' constant-expression[opt] ']'
1591 Parser::TPResult Parser::TryParseBracketDeclarator() {
1593 if (!SkipUntil(tok::r_square))
1594 return TPResult::Error();
1596 return TPResult::Ambiguous();