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 /// init-declarator-list:
189 /// init-declarator-list ',' init-declarator
192 /// declarator initializer[opt]
193 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] initializer[opt]
196 /// '=' initializer-clause
197 /// '(' expression-list ')'
199 /// initializer-clause:
200 /// assignment-expression
201 /// '{' initializer-list ','[opt] '}'
204 Parser::TPResult Parser::TryParseInitDeclaratorList() {
207 TPResult TPR = TryParseDeclarator(false/*mayBeAbstract*/);
208 if (TPR != TPResult::Ambiguous())
211 // [GNU] simple-asm-expr[opt] attributes[opt]
212 if (Tok.is(tok::kw_asm) || Tok.is(tok::kw___attribute))
213 return TPResult::True();
216 if (Tok.is(tok::l_paren)) {
217 // Parse through the parens.
219 if (!SkipUntil(tok::r_paren))
220 return TPResult::Error();
221 } else if (Tok.is(tok::equal) || isTokIdentifier_in()) {
222 // MSVC and g++ won't examine the rest of declarators if '=' is
223 // encountered; they just conclude that we have a declaration.
224 // EDG parses the initializer completely, which is the proper behavior
227 // At present, Clang follows MSVC and g++, since the parser does not have
228 // the ability to parse an expression fully without recording the
229 // results of that parse.
230 // Also allow 'in' after on objective-c declaration as in:
231 // for (int (^b)(void) in array). Ideally this should be done in the
232 // context of parsing for-init-statement of a foreach statement only. But,
233 // in any other context 'in' is invalid after a declaration and parser
234 // issues the error regardless of outcome of this decision.
235 // FIXME. Change if above assumption does not hold.
236 return TPResult::True();
239 if (Tok.isNot(tok::comma))
241 ConsumeToken(); // the comma.
244 return TPResult::Ambiguous();
247 /// isCXXConditionDeclaration - Disambiguates between a declaration or an
248 /// expression for a condition of a if/switch/while/for statement.
249 /// If during the disambiguation process a parsing error is encountered,
250 /// the function returns true to let the declaration parsing code handle it.
254 /// type-specifier-seq declarator '=' assignment-expression
255 /// [C++11] type-specifier-seq declarator '=' initializer-clause
256 /// [C++11] type-specifier-seq declarator braced-init-list
257 /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
258 /// '=' assignment-expression
260 bool Parser::isCXXConditionDeclaration() {
261 TPResult TPR = isCXXDeclarationSpecifier();
262 if (TPR != TPResult::Ambiguous())
263 return TPR != TPResult::False(); // Returns true for TPResult::True() or
264 // TPResult::Error().
266 // FIXME: Add statistics about the number of ambiguous statements encountered
267 // and how they were resolved (number of declarations+number of expressions).
269 // Ok, we have a simple-type-specifier/typename-specifier followed by a '('.
270 // We need tentative parsing...
272 TentativeParsingAction PA(*this);
274 // type-specifier-seq
275 if (Tok.is(tok::kw_typeof))
276 TryParseTypeofSpecifier();
280 if (getLangOpts().ObjC1 && Tok.is(tok::less))
281 TryParseProtocolQualifiers();
283 assert(Tok.is(tok::l_paren) && "Expected '('");
286 TPR = TryParseDeclarator(false/*mayBeAbstract*/);
288 // In case of an error, let the declaration parsing code handle it.
289 if (TPR == TPResult::Error())
290 TPR = TPResult::True();
292 if (TPR == TPResult::Ambiguous()) {
294 // [GNU] simple-asm-expr[opt] attributes[opt]
295 if (Tok.is(tok::equal) ||
296 Tok.is(tok::kw_asm) || Tok.is(tok::kw___attribute))
297 TPR = TPResult::True();
298 else if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace))
299 TPR = TPResult::True();
301 TPR = TPResult::False();
306 assert(TPR == TPResult::True() || TPR == TPResult::False());
307 return TPR == TPResult::True();
310 /// \brief Determine whether the next set of tokens contains a type-id.
312 /// The context parameter states what context we're parsing right
313 /// now, which affects how this routine copes with the token
314 /// following the type-id. If the context is TypeIdInParens, we have
315 /// already parsed the '(' and we will cease lookahead when we hit
316 /// the corresponding ')'. If the context is
317 /// TypeIdAsTemplateArgument, we've already parsed the '<' or ','
318 /// before this template argument, and will cease lookahead when we
319 /// hit a '>', '>>' (in C++0x), or ','. Returns true for a type-id
320 /// and false for an expression. If during the disambiguation
321 /// process a parsing error is encountered, the function returns
322 /// true to let the declaration parsing code handle it.
325 /// type-specifier-seq abstract-declarator[opt]
327 bool Parser::isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous) {
332 // The ambiguity arising from the similarity between a function-style cast and
333 // a type-id can occur in different contexts. The ambiguity appears as a
334 // choice between a function-style cast expression and a declaration of a
335 // type. The resolution is that any construct that could possibly be a type-id
336 // in its syntactic context shall be considered a type-id.
338 TPResult TPR = isCXXDeclarationSpecifier();
339 if (TPR != TPResult::Ambiguous())
340 return TPR != TPResult::False(); // Returns true for TPResult::True() or
341 // TPResult::Error().
343 // FIXME: Add statistics about the number of ambiguous statements encountered
344 // and how they were resolved (number of declarations+number of expressions).
346 // Ok, we have a simple-type-specifier/typename-specifier followed by a '('.
347 // We need tentative parsing...
349 TentativeParsingAction PA(*this);
351 // type-specifier-seq
352 if (Tok.is(tok::kw_typeof))
353 TryParseTypeofSpecifier();
357 if (getLangOpts().ObjC1 && Tok.is(tok::less))
358 TryParseProtocolQualifiers();
361 assert(Tok.is(tok::l_paren) && "Expected '('");
364 TPR = TryParseDeclarator(true/*mayBeAbstract*/, false/*mayHaveIdentifier*/);
366 // In case of an error, let the declaration parsing code handle it.
367 if (TPR == TPResult::Error())
368 TPR = TPResult::True();
370 if (TPR == TPResult::Ambiguous()) {
371 // We are supposed to be inside parens, so if after the abstract declarator
372 // we encounter a ')' this is a type-id, otherwise it's an expression.
373 if (Context == TypeIdInParens && Tok.is(tok::r_paren)) {
374 TPR = TPResult::True();
377 // We are supposed to be inside a template argument, so if after
378 // the abstract declarator we encounter a '>', '>>' (in C++0x), or
379 // ',', this is a type-id. Otherwise, it's an expression.
380 } else if (Context == TypeIdAsTemplateArgument &&
381 (Tok.is(tok::greater) || Tok.is(tok::comma) ||
382 (getLangOpts().CPlusPlus0x && Tok.is(tok::greatergreater)))) {
383 TPR = TPResult::True();
387 TPR = TPResult::False();
392 assert(TPR == TPResult::True() || TPR == TPResult::False());
393 return TPR == TPResult::True();
396 /// \brief Returns true if this is a C++11 attribute-specifier. Per
397 /// C++11 [dcl.attr.grammar]p6, two consecutive left square bracket tokens
398 /// always introduce an attribute. In Objective-C++11, this rule does not
399 /// apply if either '[' begins a message-send.
401 /// If Disambiguate is true, we try harder to determine whether a '[[' starts
402 /// an attribute-specifier, and return CAK_InvalidAttributeSpecifier if not.
404 /// If OuterMightBeMessageSend is true, we assume the outer '[' is either an
405 /// Obj-C message send or the start of an attribute. Otherwise, we assume it
406 /// is not an Obj-C message send.
408 /// C++11 [dcl.attr.grammar]:
410 /// attribute-specifier:
411 /// '[' '[' attribute-list ']' ']'
412 /// alignment-specifier
416 /// attribute-list ',' attribute[opt]
418 /// attribute-list ',' attribute '...'
421 /// attribute-token attribute-argument-clause[opt]
425 /// identifier '::' identifier
427 /// attribute-argument-clause:
428 /// '(' balanced-token-seq ')'
429 Parser::CXX11AttributeKind
430 Parser::isCXX11AttributeSpecifier(bool Disambiguate,
431 bool OuterMightBeMessageSend) {
432 if (Tok.is(tok::kw_alignas))
433 return CAK_AttributeSpecifier;
435 if (Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square))
436 return CAK_NotAttributeSpecifier;
438 // No tentative parsing if we don't need to look for ']]' or a lambda.
439 if (!Disambiguate && !getLangOpts().ObjC1)
440 return CAK_AttributeSpecifier;
442 TentativeParsingAction PA(*this);
444 // Opening brackets were checked for above.
447 // Outside Obj-C++11, treat anything with a matching ']]' as an attribute.
448 if (!getLangOpts().ObjC1) {
451 bool IsAttribute = SkipUntil(tok::r_square, false);
452 IsAttribute &= Tok.is(tok::r_square);
456 return IsAttribute ? CAK_AttributeSpecifier : CAK_InvalidAttributeSpecifier;
459 // In Obj-C++11, we need to distinguish four situations:
460 // 1a) int x[[attr]]; C++11 attribute.
461 // 1b) [[attr]]; C++11 statement attribute.
462 // 2) int x[[obj](){ return 1; }()]; Lambda in array size/index.
463 // 3a) int x[[obj get]]; Message send in array size/index.
464 // 3b) [[Class alloc] init]; Message send in message send.
465 // 4) [[obj]{ return self; }() doStuff]; Lambda in message send.
466 // (1) is an attribute, (2) is ill-formed, and (3) and (4) are accepted.
468 // If we have a lambda-introducer, then this is definitely not a message send.
469 // FIXME: If this disambiguation is too slow, fold the tentative lambda parse
470 // into the tentative attribute parse below.
471 LambdaIntroducer Intro;
472 if (!TryParseLambdaIntroducer(Intro)) {
473 // A lambda cannot end with ']]', and an attribute must.
474 bool IsAttribute = Tok.is(tok::r_square);
479 // Case 1: C++11 attribute.
480 return CAK_AttributeSpecifier;
482 if (OuterMightBeMessageSend)
483 // Case 4: Lambda in message send.
484 return CAK_NotAttributeSpecifier;
486 // Case 2: Lambda in array size / index.
487 return CAK_InvalidAttributeSpecifier;
492 // If we don't have a lambda-introducer, then we have an attribute or a
494 bool IsAttribute = true;
495 while (Tok.isNot(tok::r_square)) {
496 if (Tok.is(tok::comma)) {
497 // Case 1: Stray commas can only occur in attributes.
499 return CAK_AttributeSpecifier;
502 // Parse the attribute-token, if present.
503 // C++11 [dcl.attr.grammar]:
504 // If a keyword or an alternative token that satisfies the syntactic
505 // requirements of an identifier is contained in an attribute-token,
506 // it is considered an identifier.
508 if (!TryParseCXX11AttributeIdentifier(Loc)) {
512 if (Tok.is(tok::coloncolon)) {
514 if (!TryParseCXX11AttributeIdentifier(Loc)) {
520 // Parse the attribute-argument-clause, if present.
521 if (Tok.is(tok::l_paren)) {
523 if (!SkipUntil(tok::r_paren, false)) {
529 if (Tok.is(tok::ellipsis))
532 if (Tok.isNot(tok::comma))
538 // An attribute must end ']]'.
540 if (Tok.is(tok::r_square)) {
542 IsAttribute = Tok.is(tok::r_square);
551 // Case 1: C++11 statement attribute.
552 return CAK_AttributeSpecifier;
554 // Case 3: Message send.
555 return CAK_NotAttributeSpecifier;
559 /// direct-declarator
560 /// ptr-operator declarator
562 /// direct-declarator:
564 /// direct-declarator '(' parameter-declaration-clause ')'
565 /// cv-qualifier-seq[opt] exception-specification[opt]
566 /// direct-declarator '[' constant-expression[opt] ']'
567 /// '(' declarator ')'
568 /// [GNU] '(' attributes declarator ')'
570 /// abstract-declarator:
571 /// ptr-operator abstract-declarator[opt]
572 /// direct-abstract-declarator
575 /// direct-abstract-declarator:
576 /// direct-abstract-declarator[opt]
577 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
578 /// exception-specification[opt]
579 /// direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
580 /// '(' abstract-declarator ')'
583 /// '*' cv-qualifier-seq[opt]
585 /// [C++0x] '&&' [TODO]
586 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
588 /// cv-qualifier-seq:
589 /// cv-qualifier cv-qualifier-seq[opt]
596 /// '...'[opt] id-expression
600 /// qualified-id [TODO]
604 /// operator-function-id [TODO]
605 /// conversion-function-id [TODO]
606 /// '~' class-name [TODO]
607 /// template-id [TODO]
609 Parser::TPResult Parser::TryParseDeclarator(bool mayBeAbstract,
610 bool mayHaveIdentifier) {
613 // ptr-operator declarator
616 if (Tok.is(tok::coloncolon) || Tok.is(tok::identifier))
617 if (TryAnnotateCXXScopeToken(true))
618 return TPResult::Error();
620 if (Tok.is(tok::star) || Tok.is(tok::amp) || Tok.is(tok::caret) ||
621 Tok.is(tok::ampamp) ||
622 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::star))) {
625 while (Tok.is(tok::kw_const) ||
626 Tok.is(tok::kw_volatile) ||
627 Tok.is(tok::kw_restrict))
634 // direct-declarator:
635 // direct-abstract-declarator:
636 if (Tok.is(tok::ellipsis))
639 if ((Tok.is(tok::identifier) ||
640 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) &&
643 if (Tok.is(tok::annot_cxxscope))
646 TentativelyDeclaredIdentifiers.push_back(Tok.getIdentifierInfo());
648 } else if (Tok.is(tok::l_paren)) {
651 (Tok.is(tok::r_paren) || // 'int()' is a function.
652 // 'int(...)' is a function.
653 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren)) ||
654 isDeclarationSpecifier())) { // 'int(int)' is a function.
655 // '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
656 // exception-specification[opt]
657 TPResult TPR = TryParseFunctionDeclarator();
658 if (TPR != TPResult::Ambiguous())
661 // '(' declarator ')'
662 // '(' attributes declarator ')'
663 // '(' abstract-declarator ')'
664 if (Tok.is(tok::kw___attribute) ||
665 Tok.is(tok::kw___declspec) ||
666 Tok.is(tok::kw___cdecl) ||
667 Tok.is(tok::kw___stdcall) ||
668 Tok.is(tok::kw___fastcall) ||
669 Tok.is(tok::kw___thiscall) ||
670 Tok.is(tok::kw___unaligned))
671 return TPResult::True(); // attributes indicate declaration
672 TPResult TPR = TryParseDeclarator(mayBeAbstract, mayHaveIdentifier);
673 if (TPR != TPResult::Ambiguous())
675 if (Tok.isNot(tok::r_paren))
676 return TPResult::False();
679 } else if (!mayBeAbstract) {
680 return TPResult::False();
684 TPResult TPR(TPResult::Ambiguous());
686 // abstract-declarator: ...
687 if (Tok.is(tok::ellipsis))
690 if (Tok.is(tok::l_paren)) {
691 // Check whether we have a function declarator or a possible ctor-style
692 // initializer that follows the declarator. Note that ctor-style
693 // initializers are not possible in contexts where abstract declarators
695 if (!mayBeAbstract && !isCXXFunctionDeclarator())
698 // direct-declarator '(' parameter-declaration-clause ')'
699 // cv-qualifier-seq[opt] exception-specification[opt]
701 TPR = TryParseFunctionDeclarator();
702 } else if (Tok.is(tok::l_square)) {
703 // direct-declarator '[' constant-expression[opt] ']'
704 // direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
705 TPR = TryParseBracketDeclarator();
710 if (TPR != TPResult::Ambiguous())
714 return TPResult::Ambiguous();
718 Parser::isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind) {
720 // Obviously starts an expression.
721 case tok::numeric_constant:
722 case tok::char_constant:
723 case tok::wide_char_constant:
724 case tok::utf16_char_constant:
725 case tok::utf32_char_constant:
726 case tok::string_literal:
727 case tok::wide_string_literal:
728 case tok::utf8_string_literal:
729 case tok::utf16_string_literal:
730 case tok::utf32_string_literal:
739 case tok::minusminus:
743 case tok::kw___func__:
744 case tok::kw_const_cast:
746 case tok::kw_dynamic_cast:
749 case tok::kw_operator:
750 case tok::kw_reinterpret_cast:
751 case tok::kw_static_cast:
756 case tok::kw_alignof:
757 case tok::kw_noexcept:
758 case tok::kw_nullptr:
759 case tok::kw__Alignof:
761 case tok::kw___alignof:
762 case tok::kw___builtin_choose_expr:
763 case tok::kw___builtin_offsetof:
764 case tok::kw___builtin_types_compatible_p:
765 case tok::kw___builtin_va_arg:
768 case tok::kw___FUNCTION__:
769 case tok::kw_L__FUNCTION__:
770 case tok::kw___PRETTY_FUNCTION__:
771 case tok::kw___has_nothrow_assign:
772 case tok::kw___has_nothrow_copy:
773 case tok::kw___has_nothrow_constructor:
774 case tok::kw___has_trivial_assign:
775 case tok::kw___has_trivial_copy:
776 case tok::kw___has_trivial_constructor:
777 case tok::kw___has_trivial_destructor:
778 case tok::kw___has_virtual_destructor:
779 case tok::kw___is_abstract:
780 case tok::kw___is_base_of:
781 case tok::kw___is_class:
782 case tok::kw___is_convertible_to:
783 case tok::kw___is_empty:
784 case tok::kw___is_enum:
785 case tok::kw___is_interface_class:
786 case tok::kw___is_final:
787 case tok::kw___is_literal:
788 case tok::kw___is_literal_type:
789 case tok::kw___is_pod:
790 case tok::kw___is_polymorphic:
791 case tok::kw___is_trivial:
792 case tok::kw___is_trivially_assignable:
793 case tok::kw___is_trivially_constructible:
794 case tok::kw___is_trivially_copyable:
795 case tok::kw___is_union:
796 case tok::kw___uuidof:
797 return TPResult::True();
799 // Obviously starts a type-specifier-seq:
808 case tok::kw___int64:
809 case tok::kw___int128:
810 case tok::kw_restrict:
815 case tok::kw_unsigned:
817 case tok::kw_volatile:
819 case tok::kw__Complex:
821 case tok::kw_typename:
822 case tok::kw_wchar_t:
823 case tok::kw_char16_t:
824 case tok::kw_char32_t:
825 case tok::kw___underlying_type:
826 case tok::kw_thread_local:
827 case tok::kw__Decimal32:
828 case tok::kw__Decimal64:
829 case tok::kw__Decimal128:
830 case tok::kw___thread:
832 case tok::kw___cdecl:
833 case tok::kw___stdcall:
834 case tok::kw___fastcall:
835 case tok::kw___thiscall:
836 case tok::kw___unaligned:
837 case tok::kw___vector:
838 case tok::kw___pixel:
839 case tok::kw__Atomic:
840 return TPResult::False();
846 return TPResult::Ambiguous();
849 bool Parser::isTentativelyDeclared(IdentifierInfo *II) {
850 return std::find(TentativelyDeclaredIdentifiers.begin(),
851 TentativelyDeclaredIdentifiers.end(), II)
852 != TentativelyDeclaredIdentifiers.end();
855 /// isCXXDeclarationSpecifier - Returns TPResult::True() if it is a declaration
856 /// specifier, TPResult::False() if it is not, TPResult::Ambiguous() if it could
857 /// be either a decl-specifier or a function-style cast, and TPResult::Error()
858 /// if a parsing error was found and reported.
860 /// If HasMissingTypename is provided, a name with a dependent scope specifier
861 /// will be treated as ambiguous if the 'typename' keyword is missing. If this
862 /// happens, *HasMissingTypename will be set to 'true'. This will also be used
863 /// as an indicator that undeclared identifiers (which will trigger a later
864 /// parse error) should be treated as types. Returns TPResult::Ambiguous() in
868 /// storage-class-specifier
870 /// function-specifier
873 /// [C++0x] 'constexpr'
874 /// [GNU] attributes declaration-specifiers[opt]
876 /// storage-class-specifier:
884 /// function-specifier:
893 /// simple-type-specifier
896 /// elaborated-type-specifier
897 /// typename-specifier
900 /// simple-type-specifier:
901 /// '::'[opt] nested-name-specifier[opt] type-name
902 /// '::'[opt] nested-name-specifier 'template'
903 /// simple-template-id [TODO]
915 /// [GNU] typeof-specifier
917 /// [C++0x] 'auto' [TODO]
918 /// [C++0x] 'decltype' ( expression )
925 /// elaborated-type-specifier:
926 /// class-key '::'[opt] nested-name-specifier[opt] identifier
927 /// class-key '::'[opt] nested-name-specifier[opt] 'template'[opt]
928 /// simple-template-id
929 /// 'enum' '::'[opt] nested-name-specifier[opt] identifier
935 /// 'enum' identifier[opt] '{' enumerator-list[opt] '}'
936 /// 'enum' identifier[opt] '{' enumerator-list ',' '}'
939 /// class-head '{' member-specification[opt] '}'
942 /// class-key identifier[opt] base-clause[opt]
943 /// class-key nested-name-specifier identifier base-clause[opt]
944 /// class-key nested-name-specifier[opt] simple-template-id
958 Parser::isCXXDeclarationSpecifier(Parser::TPResult BracedCastResult,
959 bool *HasMissingTypename) {
960 switch (Tok.getKind()) {
961 case tok::identifier: {
962 // Check for need to substitute AltiVec __vector keyword
963 // for "vector" identifier.
964 if (TryAltiVecVectorToken())
965 return TPResult::True();
967 const Token &Next = NextToken();
968 // In 'foo bar', 'foo' is always a type name outside of Objective-C.
969 if (!getLangOpts().ObjC1 && Next.is(tok::identifier))
970 return TPResult::True();
972 if (Next.isNot(tok::coloncolon) && Next.isNot(tok::less)) {
973 // Determine whether this is a valid expression. If not, we will hit
974 // a parse error one way or another. In that case, tell the caller that
975 // this is ambiguous. Typo-correct to type and expression keywords and
976 // to types and identifiers, in order to try to recover from errors.
977 CorrectionCandidateCallback TypoCorrection;
978 TypoCorrection.WantRemainingKeywords = false;
979 switch (TryAnnotateName(false /* no nested name specifier */,
982 return TPResult::Error();
983 case ANK_TentativeDecl:
984 return TPResult::False();
985 case ANK_TemplateName:
986 // A bare type template-name which can't be a template template
987 // argument is an error, and was probably intended to be a type.
988 return GreaterThanIsOperator ? TPResult::True() : TPResult::False();
990 return HasMissingTypename ? TPResult::Ambiguous() : TPResult::False();
994 assert(Tok.isNot(tok::identifier) &&
995 "TryAnnotateName succeeded without producing an annotation");
997 // This might possibly be a type with a dependent scope specifier and
998 // a missing 'typename' keyword. Don't use TryAnnotateName in this case,
999 // since it will annotate as a primary expression, and we want to use the
1000 // "missing 'typename'" logic.
1001 if (TryAnnotateTypeOrScopeToken())
1002 return TPResult::Error();
1003 // If annotation failed, assume it's a non-type.
1004 // FIXME: If this happens due to an undeclared identifier, treat it as
1006 if (Tok.is(tok::identifier))
1007 return TPResult::False();
1010 // We annotated this token as something. Recurse to handle whatever we got.
1011 return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
1014 case tok::kw_typename: // typename T::type
1015 // Annotate typenames and C++ scope specifiers. If we get one, just
1016 // recurse to handle whatever we get.
1017 if (TryAnnotateTypeOrScopeToken())
1018 return TPResult::Error();
1019 return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
1021 case tok::coloncolon: { // ::foo::bar
1022 const Token &Next = NextToken();
1023 if (Next.is(tok::kw_new) || // ::new
1024 Next.is(tok::kw_delete)) // ::delete
1025 return TPResult::False();
1028 case tok::kw_decltype:
1029 // Annotate typenames and C++ scope specifiers. If we get one, just
1030 // recurse to handle whatever we get.
1031 if (TryAnnotateTypeOrScopeToken())
1032 return TPResult::Error();
1033 return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
1036 // storage-class-specifier
1038 // function-specifier
1042 case tok::kw_friend:
1043 case tok::kw_typedef:
1044 case tok::kw_constexpr:
1045 // storage-class-specifier
1046 case tok::kw_register:
1047 case tok::kw_static:
1048 case tok::kw_extern:
1049 case tok::kw_mutable:
1051 case tok::kw___thread:
1052 // function-specifier
1053 case tok::kw_inline:
1054 case tok::kw_virtual:
1055 case tok::kw_explicit:
1058 case tok::kw___module_private__:
1061 // simple-type-specifier
1064 // elaborated-type-specifier
1065 // typename-specifier
1069 // elaborated-type-specifier
1071 case tok::kw_struct:
1077 case tok::kw_volatile:
1080 case tok::kw_restrict:
1081 case tok::kw__Complex:
1082 case tok::kw___attribute:
1083 return TPResult::True();
1086 case tok::kw___declspec:
1087 case tok::kw___cdecl:
1088 case tok::kw___stdcall:
1089 case tok::kw___fastcall:
1090 case tok::kw___thiscall:
1092 case tok::kw___ptr64:
1093 case tok::kw___ptr32:
1094 case tok::kw___forceinline:
1095 case tok::kw___unaligned:
1096 return TPResult::True();
1099 case tok::kw___pascal:
1100 return TPResult::True();
1103 case tok::kw___vector:
1104 return TPResult::True();
1106 case tok::annot_template_id: {
1107 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1108 if (TemplateId->Kind != TNK_Type_template)
1109 return TPResult::False();
1111 AnnotateTemplateIdTokenAsType();
1112 assert(Tok.is(tok::annot_typename));
1116 case tok::annot_cxxscope: // foo::bar or ::foo::bar, but already parsed
1117 // We've already annotated a scope; try to annotate a type.
1118 if (TryAnnotateTypeOrScopeToken())
1119 return TPResult::Error();
1120 if (!Tok.is(tok::annot_typename)) {
1121 // If the next token is an identifier or a type qualifier, then this
1122 // can't possibly be a valid expression either.
1123 if (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier)) {
1125 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
1126 Tok.getAnnotationRange(),
1128 if (SS.getScopeRep() && SS.getScopeRep()->isDependent()) {
1129 TentativeParsingAction PA(*this);
1132 bool isIdentifier = Tok.is(tok::identifier);
1133 TPResult TPR = TPResult::False();
1135 TPR = isCXXDeclarationSpecifier(BracedCastResult,
1136 HasMissingTypename);
1140 TPR == TPResult::True() || TPR == TPResult::Error())
1141 return TPResult::Error();
1143 if (HasMissingTypename) {
1144 // We can't tell whether this is a missing 'typename' or a valid
1146 *HasMissingTypename = true;
1147 return TPResult::Ambiguous();
1150 // Try to resolve the name. If it doesn't exist, assume it was
1151 // intended to name a type and keep disambiguating.
1152 switch (TryAnnotateName(false /* SS is not dependent */)) {
1154 return TPResult::Error();
1155 case ANK_TentativeDecl:
1156 return TPResult::False();
1157 case ANK_TemplateName:
1158 // A bare type template-name which can't be a template template
1159 // argument is an error, and was probably intended to be a type.
1160 return GreaterThanIsOperator ? TPResult::True() : TPResult::False();
1161 case ANK_Unresolved:
1162 return HasMissingTypename ? TPResult::Ambiguous()
1163 : TPResult::False();
1165 // Annotated it, check again.
1166 assert(Tok.isNot(tok::annot_cxxscope) ||
1167 NextToken().isNot(tok::identifier));
1168 return isCXXDeclarationSpecifier(BracedCastResult,
1169 HasMissingTypename);
1173 return TPResult::False();
1175 // If that succeeded, fallthrough into the generic simple-type-id case.
1177 // The ambiguity resides in a simple-type-specifier/typename-specifier
1178 // followed by a '('. The '(' could either be the start of:
1180 // direct-declarator:
1181 // '(' declarator ')'
1183 // direct-abstract-declarator:
1184 // '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1185 // exception-specification[opt]
1186 // '(' abstract-declarator ')'
1188 // or part of a function-style cast expression:
1190 // simple-type-specifier '(' expression-list[opt] ')'
1193 // simple-type-specifier:
1195 case tok::annot_typename:
1197 // In Objective-C, we might have a protocol-qualified type.
1198 if (getLangOpts().ObjC1 && NextToken().is(tok::less)) {
1199 // Tentatively parse the
1200 TentativeParsingAction PA(*this);
1201 ConsumeToken(); // The type token
1203 TPResult TPR = TryParseProtocolQualifiers();
1204 bool isFollowedByParen = Tok.is(tok::l_paren);
1205 bool isFollowedByBrace = Tok.is(tok::l_brace);
1209 if (TPR == TPResult::Error())
1210 return TPResult::Error();
1212 if (isFollowedByParen)
1213 return TPResult::Ambiguous();
1215 if (getLangOpts().CPlusPlus0x && isFollowedByBrace)
1216 return BracedCastResult;
1218 return TPResult::True();
1222 case tok::kw_wchar_t:
1223 case tok::kw_char16_t:
1224 case tok::kw_char32_t:
1229 case tok::kw___int64:
1230 case tok::kw___int128:
1231 case tok::kw_signed:
1232 case tok::kw_unsigned:
1235 case tok::kw_double:
1237 case tok::annot_decltype:
1238 if (NextToken().is(tok::l_paren))
1239 return TPResult::Ambiguous();
1241 // This is a function-style cast in all cases we disambiguate other than
1244 // enum E : int { a = 4 }; // enum
1245 // enum E : int { 4 }; // bit-field
1247 if (getLangOpts().CPlusPlus0x && NextToken().is(tok::l_brace))
1248 return BracedCastResult;
1250 if (isStartOfObjCClassMessageMissingOpenBracket())
1251 return TPResult::False();
1253 return TPResult::True();
1255 // GNU typeof support.
1256 case tok::kw_typeof: {
1257 if (NextToken().isNot(tok::l_paren))
1258 return TPResult::True();
1260 TentativeParsingAction PA(*this);
1262 TPResult TPR = TryParseTypeofSpecifier();
1263 bool isFollowedByParen = Tok.is(tok::l_paren);
1264 bool isFollowedByBrace = Tok.is(tok::l_brace);
1268 if (TPR == TPResult::Error())
1269 return TPResult::Error();
1271 if (isFollowedByParen)
1272 return TPResult::Ambiguous();
1274 if (getLangOpts().CPlusPlus0x && isFollowedByBrace)
1275 return BracedCastResult;
1277 return TPResult::True();
1280 // C++0x type traits support
1281 case tok::kw___underlying_type:
1282 return TPResult::True();
1285 case tok::kw__Atomic:
1286 return TPResult::True();
1289 return TPResult::False();
1293 /// [GNU] typeof-specifier:
1294 /// 'typeof' '(' expressions ')'
1295 /// 'typeof' '(' type-name ')'
1297 Parser::TPResult Parser::TryParseTypeofSpecifier() {
1298 assert(Tok.is(tok::kw_typeof) && "Expected 'typeof'!");
1301 assert(Tok.is(tok::l_paren) && "Expected '('");
1302 // Parse through the parens after 'typeof'.
1304 if (!SkipUntil(tok::r_paren))
1305 return TPResult::Error();
1307 return TPResult::Ambiguous();
1310 /// [ObjC] protocol-qualifiers:
1311 //// '<' identifier-list '>'
1312 Parser::TPResult Parser::TryParseProtocolQualifiers() {
1313 assert(Tok.is(tok::less) && "Expected '<' for qualifier list");
1316 if (Tok.isNot(tok::identifier))
1317 return TPResult::Error();
1320 if (Tok.is(tok::comma)) {
1325 if (Tok.is(tok::greater)) {
1327 return TPResult::Ambiguous();
1331 return TPResult::Error();
1335 Parser::TryParseDeclarationSpecifier(bool *HasMissingTypename) {
1336 TPResult TPR = isCXXDeclarationSpecifier(TPResult::False(),
1337 HasMissingTypename);
1338 if (TPR != TPResult::Ambiguous())
1341 if (Tok.is(tok::kw_typeof))
1342 TryParseTypeofSpecifier();
1344 if (Tok.is(tok::annot_cxxscope))
1348 if (getLangOpts().ObjC1 && Tok.is(tok::less))
1349 TryParseProtocolQualifiers();
1352 return TPResult::Ambiguous();
1355 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
1356 /// a constructor-style initializer, when parsing declaration statements.
1357 /// Returns true for function declarator and false for constructor-style
1359 /// If during the disambiguation process a parsing error is encountered,
1360 /// the function returns true to let the declaration parsing code handle it.
1362 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1363 /// exception-specification[opt]
1365 bool Parser::isCXXFunctionDeclarator(bool *IsAmbiguous) {
1368 // The ambiguity arising from the similarity between a function-style cast and
1369 // a declaration mentioned in 6.8 can also occur in the context of a
1370 // declaration. In that context, the choice is between a function declaration
1371 // with a redundant set of parentheses around a parameter name and an object
1372 // declaration with a function-style cast as the initializer. Just as for the
1373 // ambiguities mentioned in 6.8, the resolution is to consider any construct
1374 // that could possibly be a declaration a declaration.
1376 TentativeParsingAction PA(*this);
1379 bool InvalidAsDeclaration = false;
1380 TPResult TPR = TryParseParameterDeclarationClause(&InvalidAsDeclaration);
1381 if (TPR == TPResult::Ambiguous()) {
1382 if (Tok.isNot(tok::r_paren))
1383 TPR = TPResult::False();
1385 const Token &Next = NextToken();
1386 if (Next.is(tok::amp) || Next.is(tok::ampamp) ||
1387 Next.is(tok::kw_const) || Next.is(tok::kw_volatile) ||
1388 Next.is(tok::kw_throw) || Next.is(tok::kw_noexcept) ||
1389 Next.is(tok::l_square) || isCXX0XVirtSpecifier(Next) ||
1390 Next.is(tok::l_brace) || Next.is(tok::kw_try) ||
1391 Next.is(tok::equal) || Next.is(tok::arrow))
1392 // The next token cannot appear after a constructor-style initializer,
1393 // and can appear next in a function definition. This must be a function
1395 TPR = TPResult::True();
1396 else if (InvalidAsDeclaration)
1397 // Use the absence of 'typename' as a tie-breaker.
1398 TPR = TPResult::False();
1404 if (IsAmbiguous && TPR == TPResult::Ambiguous())
1405 *IsAmbiguous = true;
1407 // In case of an error, let the declaration parsing code handle it.
1408 return TPR != TPResult::False();
1411 /// parameter-declaration-clause:
1412 /// parameter-declaration-list[opt] '...'[opt]
1413 /// parameter-declaration-list ',' '...'
1415 /// parameter-declaration-list:
1416 /// parameter-declaration
1417 /// parameter-declaration-list ',' parameter-declaration
1419 /// parameter-declaration:
1420 /// attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
1421 /// attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
1422 /// '=' assignment-expression
1423 /// attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
1425 /// attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
1426 /// attributes[opt] '=' assignment-expression
1429 Parser::TryParseParameterDeclarationClause(bool *InvalidAsDeclaration) {
1431 if (Tok.is(tok::r_paren))
1432 return TPResult::Ambiguous();
1434 // parameter-declaration-list[opt] '...'[opt]
1435 // parameter-declaration-list ',' '...'
1437 // parameter-declaration-list:
1438 // parameter-declaration
1439 // parameter-declaration-list ',' parameter-declaration
1443 if (Tok.is(tok::ellipsis)) {
1445 if (Tok.is(tok::r_paren))
1446 return TPResult::True(); // '...)' is a sign of a function declarator.
1448 return TPResult::False();
1451 // An attribute-specifier-seq here is a sign of a function declarator.
1452 if (isCXX11AttributeSpecifier(/*Disambiguate*/false,
1453 /*OuterMightBeMessageSend*/true))
1454 return TPResult::True();
1456 ParsedAttributes attrs(AttrFactory);
1457 MaybeParseMicrosoftAttributes(attrs);
1459 // decl-specifier-seq
1460 // A parameter-declaration's initializer must be preceded by an '=', so
1461 // decl-specifier-seq '{' is not a parameter in C++11.
1462 TPResult TPR = TryParseDeclarationSpecifier(InvalidAsDeclaration);
1463 if (TPR != TPResult::Ambiguous())
1467 // abstract-declarator[opt]
1468 TPR = TryParseDeclarator(true/*mayBeAbstract*/);
1469 if (TPR != TPResult::Ambiguous())
1472 // [GNU] attributes[opt]
1473 if (Tok.is(tok::kw___attribute))
1474 return TPResult::True();
1476 if (Tok.is(tok::equal)) {
1477 // '=' assignment-expression
1478 // Parse through assignment-expression.
1479 if (!SkipUntil(tok::comma, tok::r_paren, true/*StopAtSemi*/,
1480 true/*DontConsume*/))
1481 return TPResult::Error();
1484 if (Tok.is(tok::ellipsis)) {
1486 if (Tok.is(tok::r_paren))
1487 return TPResult::True(); // '...)' is a sign of a function declarator.
1489 return TPResult::False();
1492 if (Tok.isNot(tok::comma))
1494 ConsumeToken(); // the comma.
1497 return TPResult::Ambiguous();
1500 /// TryParseFunctionDeclarator - We parsed a '(' and we want to try to continue
1501 /// parsing as a function declarator.
1502 /// If TryParseFunctionDeclarator fully parsed the function declarator, it will
1503 /// return TPResult::Ambiguous(), otherwise it will return either False() or
1506 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
1507 /// exception-specification[opt]
1509 /// exception-specification:
1510 /// 'throw' '(' type-id-list[opt] ')'
1512 Parser::TPResult Parser::TryParseFunctionDeclarator() {
1514 // The '(' is already parsed.
1516 TPResult TPR = TryParseParameterDeclarationClause();
1517 if (TPR == TPResult::Ambiguous() && Tok.isNot(tok::r_paren))
1518 TPR = TPResult::False();
1520 if (TPR == TPResult::False() || TPR == TPResult::Error())
1523 // Parse through the parens.
1524 if (!SkipUntil(tok::r_paren))
1525 return TPResult::Error();
1528 while (Tok.is(tok::kw_const) ||
1529 Tok.is(tok::kw_volatile) ||
1530 Tok.is(tok::kw_restrict) )
1533 // ref-qualifier[opt]
1534 if (Tok.is(tok::amp) || Tok.is(tok::ampamp))
1537 // exception-specification
1538 if (Tok.is(tok::kw_throw)) {
1540 if (Tok.isNot(tok::l_paren))
1541 return TPResult::Error();
1543 // Parse through the parens after 'throw'.
1545 if (!SkipUntil(tok::r_paren))
1546 return TPResult::Error();
1548 if (Tok.is(tok::kw_noexcept)) {
1550 // Possibly an expression as well.
1551 if (Tok.is(tok::l_paren)) {
1552 // Find the matching rparen.
1554 if (!SkipUntil(tok::r_paren))
1555 return TPResult::Error();
1559 return TPResult::Ambiguous();
1562 /// '[' constant-expression[opt] ']'
1564 Parser::TPResult Parser::TryParseBracketDeclarator() {
1566 if (!SkipUntil(tok::r_square))
1567 return TPResult::Error();
1569 return TPResult::Ambiguous();