clang  3.9.0svn
ParseTentative.cpp
Go to the documentation of this file.
00001 //===--- ParseTentative.cpp - Ambiguity Resolution Parsing ----------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file implements the tentative parsing portions of the Parser
00011 //  interfaces, for ambiguity resolution.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "clang/Parse/Parser.h"
00016 #include "clang/Parse/ParseDiagnostic.h"
00017 #include "clang/Sema/ParsedTemplate.h"
00018 using namespace clang;
00019 
00020 /// isCXXDeclarationStatement - C++-specialized function that disambiguates
00021 /// between a declaration or an expression statement, when parsing function
00022 /// bodies. Returns true for declaration, false for expression.
00023 ///
00024 ///         declaration-statement:
00025 ///           block-declaration
00026 ///
00027 ///         block-declaration:
00028 ///           simple-declaration
00029 ///           asm-definition
00030 ///           namespace-alias-definition
00031 ///           using-declaration
00032 ///           using-directive
00033 /// [C++0x]   static_assert-declaration
00034 ///
00035 ///         asm-definition:
00036 ///           'asm' '(' string-literal ')' ';'
00037 ///
00038 ///         namespace-alias-definition:
00039 ///           'namespace' identifier = qualified-namespace-specifier ';'
00040 ///
00041 ///         using-declaration:
00042 ///           'using' typename[opt] '::'[opt] nested-name-specifier
00043 ///                 unqualified-id ';'
00044 ///           'using' '::' unqualified-id ;
00045 ///
00046 ///         using-directive:
00047 ///           'using' 'namespace' '::'[opt] nested-name-specifier[opt]
00048 ///                 namespace-name ';'
00049 ///
00050 bool Parser::isCXXDeclarationStatement() {
00051   switch (Tok.getKind()) {
00052     // asm-definition
00053   case tok::kw_asm:
00054     // namespace-alias-definition
00055   case tok::kw_namespace:
00056     // using-declaration
00057     // using-directive
00058   case tok::kw_using:
00059     // static_assert-declaration
00060   case tok::kw_static_assert:
00061   case tok::kw__Static_assert:
00062     return true;
00063     // simple-declaration
00064   default:
00065     return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
00066   }
00067 }
00068 
00069 /// isCXXSimpleDeclaration - C++-specialized function that disambiguates
00070 /// between a simple-declaration or an expression-statement.
00071 /// If during the disambiguation process a parsing error is encountered,
00072 /// the function returns true to let the declaration parsing code handle it.
00073 /// Returns false if the statement is disambiguated as expression.
00074 ///
00075 /// simple-declaration:
00076 ///   decl-specifier-seq init-declarator-list[opt] ';'
00077 ///
00078 /// (if AllowForRangeDecl specified)
00079 /// for ( for-range-declaration : for-range-initializer ) statement
00080 /// for-range-declaration: 
00081 ///    attribute-specifier-seqopt type-specifier-seq declarator
00082 bool Parser::isCXXSimpleDeclaration(bool AllowForRangeDecl) {
00083   // C++ 6.8p1:
00084   // There is an ambiguity in the grammar involving expression-statements and
00085   // declarations: An expression-statement with a function-style explicit type
00086   // conversion (5.2.3) as its leftmost subexpression can be indistinguishable
00087   // from a declaration where the first declarator starts with a '('. In those
00088   // cases the statement is a declaration. [Note: To disambiguate, the whole
00089   // statement might have to be examined to determine if it is an
00090   // expression-statement or a declaration].
00091 
00092   // C++ 6.8p3:
00093   // The disambiguation is purely syntactic; that is, the meaning of the names
00094   // occurring in such a statement, beyond whether they are type-names or not,
00095   // is not generally used in or changed by the disambiguation. Class
00096   // templates are instantiated as necessary to determine if a qualified name
00097   // is a type-name. Disambiguation precedes parsing, and a statement
00098   // disambiguated as a declaration may be an ill-formed declaration.
00099 
00100   // We don't have to parse all of the decl-specifier-seq part. There's only
00101   // an ambiguity if the first decl-specifier is
00102   // simple-type-specifier/typename-specifier followed by a '(', which may
00103   // indicate a function-style cast expression.
00104   // isCXXDeclarationSpecifier will return TPResult::Ambiguous only in such
00105   // a case.
00106 
00107   bool InvalidAsDeclaration = false;
00108   TPResult TPR = isCXXDeclarationSpecifier(TPResult::False,
00109                                            &InvalidAsDeclaration);
00110   if (TPR != TPResult::Ambiguous)
00111     return TPR != TPResult::False; // Returns true for TPResult::True or
00112                                    // TPResult::Error.
00113 
00114   // FIXME: TryParseSimpleDeclaration doesn't look past the first initializer,
00115   // and so gets some cases wrong. We can't carry on if we've already seen
00116   // something which makes this statement invalid as a declaration in this case,
00117   // since it can cause us to misparse valid code. Revisit this once
00118   // TryParseInitDeclaratorList is fixed.
00119   if (InvalidAsDeclaration)
00120     return false;
00121 
00122   // FIXME: Add statistics about the number of ambiguous statements encountered
00123   // and how they were resolved (number of declarations+number of expressions).
00124 
00125   // Ok, we have a simple-type-specifier/typename-specifier followed by a '(',
00126   // or an identifier which doesn't resolve as anything. We need tentative
00127   // parsing...
00128 
00129   TentativeParsingAction PA(*this);
00130   TPR = TryParseSimpleDeclaration(AllowForRangeDecl);
00131   PA.Revert();
00132 
00133   // In case of an error, let the declaration parsing code handle it.
00134   if (TPR == TPResult::Error)
00135     return true;
00136 
00137   // Declarations take precedence over expressions.
00138   if (TPR == TPResult::Ambiguous)
00139     TPR = TPResult::True;
00140 
00141   assert(TPR == TPResult::True || TPR == TPResult::False);
00142   return TPR == TPResult::True;
00143 }
00144 
00145 /// Try to consume a token sequence that we've already identified as
00146 /// (potentially) starting a decl-specifier.
00147 Parser::TPResult Parser::TryConsumeDeclarationSpecifier() {
00148   switch (Tok.getKind()) {
00149   case tok::kw__Atomic:
00150     if (NextToken().isNot(tok::l_paren)) {
00151       ConsumeToken();
00152       break;
00153     }
00154     // Fall through.
00155   case tok::kw_typeof:
00156   case tok::kw___attribute:
00157   case tok::kw___underlying_type: {
00158     ConsumeToken();
00159     if (Tok.isNot(tok::l_paren))
00160       return TPResult::Error;
00161     ConsumeParen();
00162     if (!SkipUntil(tok::r_paren))
00163       return TPResult::Error;
00164     break;
00165   }
00166 
00167   case tok::kw_class:
00168   case tok::kw_struct:
00169   case tok::kw_union:
00170   case tok::kw___interface:
00171   case tok::kw_enum:
00172     // elaborated-type-specifier:
00173     //     class-key attribute-specifier-seq[opt]
00174     //         nested-name-specifier[opt] identifier
00175     //     class-key nested-name-specifier[opt] template[opt] simple-template-id
00176     //     enum nested-name-specifier[opt] identifier
00177     //
00178     // FIXME: We don't support class-specifiers nor enum-specifiers here.
00179     ConsumeToken();
00180 
00181     // Skip attributes.
00182     while (Tok.isOneOf(tok::l_square, tok::kw___attribute, tok::kw___declspec,
00183                        tok::kw_alignas)) {
00184       if (Tok.is(tok::l_square)) {
00185         ConsumeBracket();
00186         if (!SkipUntil(tok::r_square))
00187           return TPResult::Error;
00188       } else {
00189         ConsumeToken();
00190         if (Tok.isNot(tok::l_paren))
00191           return TPResult::Error;
00192         ConsumeParen();
00193         if (!SkipUntil(tok::r_paren))
00194           return TPResult::Error;
00195       }
00196     }
00197 
00198     if (Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
00199                     tok::annot_template_id) &&
00200         TryAnnotateCXXScopeToken())
00201       return TPResult::Error;
00202     if (Tok.is(tok::annot_cxxscope))
00203       ConsumeToken();
00204     if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id))
00205       return TPResult::Error;
00206     ConsumeToken();
00207     break;
00208 
00209   case tok::annot_cxxscope:
00210     ConsumeToken();
00211     // Fall through.
00212   default:
00213     ConsumeToken();
00214 
00215     if (getLangOpts().ObjC1 && Tok.is(tok::less))
00216       return TryParseProtocolQualifiers();
00217     break;
00218   }
00219 
00220   return TPResult::Ambiguous;
00221 }
00222 
00223 /// simple-declaration:
00224 ///   decl-specifier-seq init-declarator-list[opt] ';'
00225 ///
00226 /// (if AllowForRangeDecl specified)
00227 /// for ( for-range-declaration : for-range-initializer ) statement
00228 /// for-range-declaration: 
00229 ///    attribute-specifier-seqopt type-specifier-seq declarator
00230 ///
00231 Parser::TPResult Parser::TryParseSimpleDeclaration(bool AllowForRangeDecl) {
00232   if (TryConsumeDeclarationSpecifier() == TPResult::Error)
00233     return TPResult::Error;
00234 
00235   // Two decl-specifiers in a row conclusively disambiguate this as being a
00236   // simple-declaration. Don't bother calling isCXXDeclarationSpecifier in the
00237   // overwhelmingly common case that the next token is a '('.
00238   if (Tok.isNot(tok::l_paren)) {
00239     TPResult TPR = isCXXDeclarationSpecifier();
00240     if (TPR == TPResult::Ambiguous)
00241       return TPResult::True;
00242     if (TPR == TPResult::True || TPR == TPResult::Error)
00243       return TPR;
00244     assert(TPR == TPResult::False);
00245   }
00246 
00247   TPResult TPR = TryParseInitDeclaratorList();
00248   if (TPR != TPResult::Ambiguous)
00249     return TPR;
00250 
00251   if (Tok.isNot(tok::semi) && (!AllowForRangeDecl || Tok.isNot(tok::colon)))
00252     return TPResult::False;
00253 
00254   return TPResult::Ambiguous;
00255 }
00256 
00257 /// Tentatively parse an init-declarator-list in order to disambiguate it from
00258 /// an expression.
00259 ///
00260 ///       init-declarator-list:
00261 ///         init-declarator
00262 ///         init-declarator-list ',' init-declarator
00263 ///
00264 ///       init-declarator:
00265 ///         declarator initializer[opt]
00266 /// [GNU]   declarator simple-asm-expr[opt] attributes[opt] initializer[opt]
00267 ///
00268 ///       initializer:
00269 ///         brace-or-equal-initializer
00270 ///         '(' expression-list ')'
00271 ///
00272 ///       brace-or-equal-initializer:
00273 ///         '=' initializer-clause
00274 /// [C++11] braced-init-list
00275 ///
00276 ///       initializer-clause:
00277 ///         assignment-expression
00278 ///         braced-init-list
00279 ///
00280 ///       braced-init-list:
00281 ///         '{' initializer-list ','[opt] '}'
00282 ///         '{' '}'
00283 ///
00284 Parser::TPResult Parser::TryParseInitDeclaratorList() {
00285   while (1) {
00286     // declarator
00287     TPResult TPR = TryParseDeclarator(false/*mayBeAbstract*/);
00288     if (TPR != TPResult::Ambiguous)
00289       return TPR;
00290 
00291     // [GNU] simple-asm-expr[opt] attributes[opt]
00292     if (Tok.isOneOf(tok::kw_asm, tok::kw___attribute))
00293       return TPResult::True;
00294 
00295     // initializer[opt]
00296     if (Tok.is(tok::l_paren)) {
00297       // Parse through the parens.
00298       ConsumeParen();
00299       if (!SkipUntil(tok::r_paren, StopAtSemi))
00300         return TPResult::Error;
00301     } else if (Tok.is(tok::l_brace)) {
00302       // A left-brace here is sufficient to disambiguate the parse; an
00303       // expression can never be followed directly by a braced-init-list.
00304       return TPResult::True;
00305     } else if (Tok.is(tok::equal) || isTokIdentifier_in()) {
00306       // MSVC and g++ won't examine the rest of declarators if '=' is
00307       // encountered; they just conclude that we have a declaration.
00308       // EDG parses the initializer completely, which is the proper behavior
00309       // for this case.
00310       //
00311       // At present, Clang follows MSVC and g++, since the parser does not have
00312       // the ability to parse an expression fully without recording the
00313       // results of that parse.
00314       // FIXME: Handle this case correctly.
00315       //
00316       // Also allow 'in' after an Objective-C declaration as in:
00317       // for (int (^b)(void) in array). Ideally this should be done in the
00318       // context of parsing for-init-statement of a foreach statement only. But,
00319       // in any other context 'in' is invalid after a declaration and parser
00320       // issues the error regardless of outcome of this decision.
00321       // FIXME: Change if above assumption does not hold.
00322       return TPResult::True;
00323     }
00324 
00325     if (!TryConsumeToken(tok::comma))
00326       break;
00327   }
00328 
00329   return TPResult::Ambiguous;
00330 }
00331 
00332 /// isCXXConditionDeclaration - Disambiguates between a declaration or an
00333 /// expression for a condition of a if/switch/while/for statement.
00334 /// If during the disambiguation process a parsing error is encountered,
00335 /// the function returns true to let the declaration parsing code handle it.
00336 ///
00337 ///       condition:
00338 ///         expression
00339 ///         type-specifier-seq declarator '=' assignment-expression
00340 /// [C++11] type-specifier-seq declarator '=' initializer-clause
00341 /// [C++11] type-specifier-seq declarator braced-init-list
00342 /// [GNU]   type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
00343 ///             '=' assignment-expression
00344 ///
00345 bool Parser::isCXXConditionDeclaration() {
00346   TPResult TPR = isCXXDeclarationSpecifier();
00347   if (TPR != TPResult::Ambiguous)
00348     return TPR != TPResult::False; // Returns true for TPResult::True or
00349                                    // TPResult::Error.
00350 
00351   // FIXME: Add statistics about the number of ambiguous statements encountered
00352   // and how they were resolved (number of declarations+number of expressions).
00353 
00354   // Ok, we have a simple-type-specifier/typename-specifier followed by a '('.
00355   // We need tentative parsing...
00356 
00357   TentativeParsingAction PA(*this);
00358 
00359   // type-specifier-seq
00360   TryConsumeDeclarationSpecifier();
00361   assert(Tok.is(tok::l_paren) && "Expected '('");
00362 
00363   // declarator
00364   TPR = TryParseDeclarator(false/*mayBeAbstract*/);
00365 
00366   // In case of an error, let the declaration parsing code handle it.
00367   if (TPR == TPResult::Error)
00368     TPR = TPResult::True;
00369 
00370   if (TPR == TPResult::Ambiguous) {
00371     // '='
00372     // [GNU] simple-asm-expr[opt] attributes[opt]
00373     if (Tok.isOneOf(tok::equal, tok::kw_asm, tok::kw___attribute))
00374       TPR = TPResult::True;
00375     else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace))
00376       TPR = TPResult::True;
00377     else
00378       TPR = TPResult::False;
00379   }
00380 
00381   PA.Revert();
00382 
00383   assert(TPR == TPResult::True || TPR == TPResult::False);
00384   return TPR == TPResult::True;
00385 }
00386 
00387   /// \brief Determine whether the next set of tokens contains a type-id.
00388   ///
00389   /// The context parameter states what context we're parsing right
00390   /// now, which affects how this routine copes with the token
00391   /// following the type-id. If the context is TypeIdInParens, we have
00392   /// already parsed the '(' and we will cease lookahead when we hit
00393   /// the corresponding ')'. If the context is
00394   /// TypeIdAsTemplateArgument, we've already parsed the '<' or ','
00395   /// before this template argument, and will cease lookahead when we
00396   /// hit a '>', '>>' (in C++0x), or ','. Returns true for a type-id
00397   /// and false for an expression.  If during the disambiguation
00398   /// process a parsing error is encountered, the function returns
00399   /// true to let the declaration parsing code handle it.
00400   ///
00401   /// type-id:
00402   ///   type-specifier-seq abstract-declarator[opt]
00403   ///
00404 bool Parser::isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous) {
00405 
00406   isAmbiguous = false;
00407 
00408   // C++ 8.2p2:
00409   // The ambiguity arising from the similarity between a function-style cast and
00410   // a type-id can occur in different contexts. The ambiguity appears as a
00411   // choice between a function-style cast expression and a declaration of a
00412   // type. The resolution is that any construct that could possibly be a type-id
00413   // in its syntactic context shall be considered a type-id.
00414 
00415   TPResult TPR = isCXXDeclarationSpecifier();
00416   if (TPR != TPResult::Ambiguous)
00417     return TPR != TPResult::False; // Returns true for TPResult::True or
00418                                      // TPResult::Error.
00419 
00420   // FIXME: Add statistics about the number of ambiguous statements encountered
00421   // and how they were resolved (number of declarations+number of expressions).
00422 
00423   // Ok, we have a simple-type-specifier/typename-specifier followed by a '('.
00424   // We need tentative parsing...
00425 
00426   TentativeParsingAction PA(*this);
00427 
00428   // type-specifier-seq
00429   TryConsumeDeclarationSpecifier();
00430   assert(Tok.is(tok::l_paren) && "Expected '('");
00431 
00432   // declarator
00433   TPR = TryParseDeclarator(true/*mayBeAbstract*/, false/*mayHaveIdentifier*/);
00434 
00435   // In case of an error, let the declaration parsing code handle it.
00436   if (TPR == TPResult::Error)
00437     TPR = TPResult::True;
00438 
00439   if (TPR == TPResult::Ambiguous) {
00440     // We are supposed to be inside parens, so if after the abstract declarator
00441     // we encounter a ')' this is a type-id, otherwise it's an expression.
00442     if (Context == TypeIdInParens && Tok.is(tok::r_paren)) {
00443       TPR = TPResult::True;
00444       isAmbiguous = true;
00445 
00446     // We are supposed to be inside a template argument, so if after
00447     // the abstract declarator we encounter a '>', '>>' (in C++0x), or
00448     // ',', this is a type-id. Otherwise, it's an expression.
00449     } else if (Context == TypeIdAsTemplateArgument &&
00450                (Tok.isOneOf(tok::greater, tok::comma) ||
00451                 (getLangOpts().CPlusPlus11 && Tok.is(tok::greatergreater)))) {
00452       TPR = TPResult::True;
00453       isAmbiguous = true;
00454 
00455     } else
00456       TPR = TPResult::False;
00457   }
00458 
00459   PA.Revert();
00460 
00461   assert(TPR == TPResult::True || TPR == TPResult::False);
00462   return TPR == TPResult::True;
00463 }
00464 
00465 /// \brief Returns true if this is a C++11 attribute-specifier. Per
00466 /// C++11 [dcl.attr.grammar]p6, two consecutive left square bracket tokens
00467 /// always introduce an attribute. In Objective-C++11, this rule does not
00468 /// apply if either '[' begins a message-send.
00469 ///
00470 /// If Disambiguate is true, we try harder to determine whether a '[[' starts
00471 /// an attribute-specifier, and return CAK_InvalidAttributeSpecifier if not.
00472 ///
00473 /// If OuterMightBeMessageSend is true, we assume the outer '[' is either an
00474 /// Obj-C message send or the start of an attribute. Otherwise, we assume it
00475 /// is not an Obj-C message send.
00476 ///
00477 /// C++11 [dcl.attr.grammar]:
00478 ///
00479 ///     attribute-specifier:
00480 ///         '[' '[' attribute-list ']' ']'
00481 ///         alignment-specifier
00482 ///
00483 ///     attribute-list:
00484 ///         attribute[opt]
00485 ///         attribute-list ',' attribute[opt]
00486 ///         attribute '...'
00487 ///         attribute-list ',' attribute '...'
00488 ///
00489 ///     attribute:
00490 ///         attribute-token attribute-argument-clause[opt]
00491 ///
00492 ///     attribute-token:
00493 ///         identifier
00494 ///         identifier '::' identifier
00495 ///
00496 ///     attribute-argument-clause:
00497 ///         '(' balanced-token-seq ')'
00498 Parser::CXX11AttributeKind
00499 Parser::isCXX11AttributeSpecifier(bool Disambiguate,
00500                                   bool OuterMightBeMessageSend) {
00501   if (Tok.is(tok::kw_alignas))
00502     return CAK_AttributeSpecifier;
00503 
00504   if (Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square))
00505     return CAK_NotAttributeSpecifier;
00506 
00507   // No tentative parsing if we don't need to look for ']]' or a lambda.
00508   if (!Disambiguate && !getLangOpts().ObjC1)
00509     return CAK_AttributeSpecifier;
00510 
00511   TentativeParsingAction PA(*this);
00512 
00513   // Opening brackets were checked for above.
00514   ConsumeBracket();
00515 
00516   // Outside Obj-C++11, treat anything with a matching ']]' as an attribute.
00517   if (!getLangOpts().ObjC1) {
00518     ConsumeBracket();
00519 
00520     bool IsAttribute = SkipUntil(tok::r_square);
00521     IsAttribute &= Tok.is(tok::r_square);
00522 
00523     PA.Revert();
00524 
00525     return IsAttribute ? CAK_AttributeSpecifier : CAK_InvalidAttributeSpecifier;
00526   }
00527 
00528   // In Obj-C++11, we need to distinguish four situations:
00529   //  1a) int x[[attr]];                     C++11 attribute.
00530   //  1b) [[attr]];                          C++11 statement attribute.
00531   //   2) int x[[obj](){ return 1; }()];     Lambda in array size/index.
00532   //  3a) int x[[obj get]];                  Message send in array size/index.
00533   //  3b) [[Class alloc] init];              Message send in message send.
00534   //   4) [[obj]{ return self; }() doStuff]; Lambda in message send.
00535   // (1) is an attribute, (2) is ill-formed, and (3) and (4) are accepted.
00536 
00537   // If we have a lambda-introducer, then this is definitely not a message send.
00538   // FIXME: If this disambiguation is too slow, fold the tentative lambda parse
00539   // into the tentative attribute parse below.
00540   LambdaIntroducer Intro;
00541   if (!TryParseLambdaIntroducer(Intro)) {
00542     // A lambda cannot end with ']]', and an attribute must.
00543     bool IsAttribute = Tok.is(tok::r_square);
00544 
00545     PA.Revert();
00546 
00547     if (IsAttribute)
00548       // Case 1: C++11 attribute.
00549       return CAK_AttributeSpecifier;
00550 
00551     if (OuterMightBeMessageSend)
00552       // Case 4: Lambda in message send.
00553       return CAK_NotAttributeSpecifier;
00554 
00555     // Case 2: Lambda in array size / index.
00556     return CAK_InvalidAttributeSpecifier;
00557   }
00558 
00559   ConsumeBracket();
00560 
00561   // If we don't have a lambda-introducer, then we have an attribute or a
00562   // message-send.
00563   bool IsAttribute = true;
00564   while (Tok.isNot(tok::r_square)) {
00565     if (Tok.is(tok::comma)) {
00566       // Case 1: Stray commas can only occur in attributes.
00567       PA.Revert();
00568       return CAK_AttributeSpecifier;
00569     }
00570 
00571     // Parse the attribute-token, if present.
00572     // C++11 [dcl.attr.grammar]:
00573     //   If a keyword or an alternative token that satisfies the syntactic
00574     //   requirements of an identifier is contained in an attribute-token,
00575     //   it is considered an identifier.
00576     SourceLocation Loc;
00577     if (!TryParseCXX11AttributeIdentifier(Loc)) {
00578       IsAttribute = false;
00579       break;
00580     }
00581     if (Tok.is(tok::coloncolon)) {
00582       ConsumeToken();
00583       if (!TryParseCXX11AttributeIdentifier(Loc)) {
00584         IsAttribute = false;
00585         break;
00586       }
00587     }
00588 
00589     // Parse the attribute-argument-clause, if present.
00590     if (Tok.is(tok::l_paren)) {
00591       ConsumeParen();
00592       if (!SkipUntil(tok::r_paren)) {
00593         IsAttribute = false;
00594         break;
00595       }
00596     }
00597 
00598     TryConsumeToken(tok::ellipsis);
00599 
00600     if (!TryConsumeToken(tok::comma))
00601       break;
00602   }
00603 
00604   // An attribute must end ']]'.
00605   if (IsAttribute) {
00606     if (Tok.is(tok::r_square)) {
00607       ConsumeBracket();
00608       IsAttribute = Tok.is(tok::r_square);
00609     } else {
00610       IsAttribute = false;
00611     }
00612   }
00613 
00614   PA.Revert();
00615 
00616   if (IsAttribute)
00617     // Case 1: C++11 statement attribute.
00618     return CAK_AttributeSpecifier;
00619 
00620   // Case 3: Message send.
00621   return CAK_NotAttributeSpecifier;
00622 }
00623 
00624 Parser::TPResult Parser::TryParsePtrOperatorSeq() {
00625   while (true) {
00626     if (Tok.isOneOf(tok::coloncolon, tok::identifier))
00627       if (TryAnnotateCXXScopeToken(true))
00628         return TPResult::Error;
00629 
00630     if (Tok.isOneOf(tok::star, tok::amp, tok::caret, tok::ampamp) ||
00631         (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::star))) {
00632       // ptr-operator
00633       ConsumeToken();
00634       while (Tok.isOneOf(tok::kw_const, tok::kw_volatile, tok::kw_restrict,
00635                          tok::kw__Nonnull, tok::kw__Nullable,
00636                          tok::kw__Null_unspecified))
00637         ConsumeToken();
00638     } else {
00639       return TPResult::True;
00640     }
00641   }
00642 }
00643 
00644 ///         operator-function-id:
00645 ///           'operator' operator
00646 ///
00647 ///         operator: one of
00648 ///           new  delete  new[]  delete[]  +  -  *  /  %  ^  [...]
00649 ///
00650 ///         conversion-function-id:
00651 ///           'operator' conversion-type-id
00652 ///
00653 ///         conversion-type-id:
00654 ///           type-specifier-seq conversion-declarator[opt]
00655 ///
00656 ///         conversion-declarator:
00657 ///           ptr-operator conversion-declarator[opt]
00658 ///
00659 ///         literal-operator-id:
00660 ///           'operator' string-literal identifier
00661 ///           'operator' user-defined-string-literal
00662 Parser::TPResult Parser::TryParseOperatorId() {
00663   assert(Tok.is(tok::kw_operator));
00664   ConsumeToken();
00665 
00666   // Maybe this is an operator-function-id.
00667   switch (Tok.getKind()) {
00668   case tok::kw_new: case tok::kw_delete:
00669     ConsumeToken();
00670     if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
00671       ConsumeBracket();
00672       ConsumeBracket();
00673     }
00674     return TPResult::True;
00675 
00676 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemOnly) \
00677   case tok::Token:
00678 #define OVERLOADED_OPERATOR_MULTI(Name, Spelling, Unary, Binary, MemOnly)
00679 #include "clang/Basic/OperatorKinds.def"
00680     ConsumeToken();
00681     return TPResult::True;
00682 
00683   case tok::l_square:
00684     if (NextToken().is(tok::r_square)) {
00685       ConsumeBracket();
00686       ConsumeBracket();
00687       return TPResult::True;
00688     }
00689     break;
00690 
00691   case tok::l_paren:
00692     if (NextToken().is(tok::r_paren)) {
00693       ConsumeParen();
00694       ConsumeParen();
00695       return TPResult::True;
00696     }
00697     break;
00698 
00699   default:
00700     break;
00701   }
00702 
00703   // Maybe this is a literal-operator-id.
00704   if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
00705     bool FoundUDSuffix = false;
00706     do {
00707       FoundUDSuffix |= Tok.hasUDSuffix();
00708       ConsumeStringToken();
00709     } while (isTokenStringLiteral());
00710 
00711     if (!FoundUDSuffix) {
00712       if (Tok.is(tok::identifier))
00713         ConsumeToken();
00714       else
00715         return TPResult::Error;
00716     }
00717     return TPResult::True;
00718   }
00719 
00720   // Maybe this is a conversion-function-id.
00721   bool AnyDeclSpecifiers = false;
00722   while (true) {
00723     TPResult TPR = isCXXDeclarationSpecifier();
00724     if (TPR == TPResult::Error)
00725       return TPR;
00726     if (TPR == TPResult::False) {
00727       if (!AnyDeclSpecifiers)
00728         return TPResult::Error;
00729       break;
00730     }
00731     if (TryConsumeDeclarationSpecifier() == TPResult::Error)
00732       return TPResult::Error;
00733     AnyDeclSpecifiers = true;
00734   }
00735   return TryParsePtrOperatorSeq();
00736 }
00737 
00738 ///         declarator:
00739 ///           direct-declarator
00740 ///           ptr-operator declarator
00741 ///
00742 ///         direct-declarator:
00743 ///           declarator-id
00744 ///           direct-declarator '(' parameter-declaration-clause ')'
00745 ///                 cv-qualifier-seq[opt] exception-specification[opt]
00746 ///           direct-declarator '[' constant-expression[opt] ']'
00747 ///           '(' declarator ')'
00748 /// [GNU]     '(' attributes declarator ')'
00749 ///
00750 ///         abstract-declarator:
00751 ///           ptr-operator abstract-declarator[opt]
00752 ///           direct-abstract-declarator
00753 ///           ...
00754 ///
00755 ///         direct-abstract-declarator:
00756 ///           direct-abstract-declarator[opt]
00757 ///           '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
00758 ///                 exception-specification[opt]
00759 ///           direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
00760 ///           '(' abstract-declarator ')'
00761 ///
00762 ///         ptr-operator:
00763 ///           '*' cv-qualifier-seq[opt]
00764 ///           '&'
00765 /// [C++0x]   '&&'                                                        [TODO]
00766 ///           '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
00767 ///
00768 ///         cv-qualifier-seq:
00769 ///           cv-qualifier cv-qualifier-seq[opt]
00770 ///
00771 ///         cv-qualifier:
00772 ///           'const'
00773 ///           'volatile'
00774 ///
00775 ///         declarator-id:
00776 ///           '...'[opt] id-expression
00777 ///
00778 ///         id-expression:
00779 ///           unqualified-id
00780 ///           qualified-id                                                [TODO]
00781 ///
00782 ///         unqualified-id:
00783 ///           identifier
00784 ///           operator-function-id
00785 ///           conversion-function-id
00786 ///           literal-operator-id
00787 ///           '~' class-name                                              [TODO]
00788 ///           '~' decltype-specifier                                      [TODO]
00789 ///           template-id                                                 [TODO]
00790 ///
00791 Parser::TPResult Parser::TryParseDeclarator(bool mayBeAbstract,
00792                                             bool mayHaveIdentifier) {
00793   // declarator:
00794   //   direct-declarator
00795   //   ptr-operator declarator
00796   if (TryParsePtrOperatorSeq() == TPResult::Error)
00797     return TPResult::Error;
00798 
00799   // direct-declarator:
00800   // direct-abstract-declarator:
00801   if (Tok.is(tok::ellipsis))
00802     ConsumeToken();
00803 
00804   if ((Tok.isOneOf(tok::identifier, tok::kw_operator) ||
00805        (Tok.is(tok::annot_cxxscope) && (NextToken().is(tok::identifier) ||
00806                                         NextToken().is(tok::kw_operator)))) &&
00807       mayHaveIdentifier) {
00808     // declarator-id
00809     if (Tok.is(tok::annot_cxxscope))
00810       ConsumeToken();
00811     else if (Tok.is(tok::identifier))
00812       TentativelyDeclaredIdentifiers.push_back(Tok.getIdentifierInfo());
00813     if (Tok.is(tok::kw_operator)) {
00814       if (TryParseOperatorId() == TPResult::Error)
00815         return TPResult::Error;
00816     } else
00817       ConsumeToken();
00818   } else if (Tok.is(tok::l_paren)) {
00819     ConsumeParen();
00820     if (mayBeAbstract &&
00821         (Tok.is(tok::r_paren) ||       // 'int()' is a function.
00822          // 'int(...)' is a function.
00823          (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren)) ||
00824          isDeclarationSpecifier())) {   // 'int(int)' is a function.
00825       // '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
00826       //        exception-specification[opt]
00827       TPResult TPR = TryParseFunctionDeclarator();
00828       if (TPR != TPResult::Ambiguous)
00829         return TPR;
00830     } else {
00831       // '(' declarator ')'
00832       // '(' attributes declarator ')'
00833       // '(' abstract-declarator ')'
00834       if (Tok.isOneOf(tok::kw___attribute, tok::kw___declspec, tok::kw___cdecl,
00835                       tok::kw___stdcall, tok::kw___fastcall, tok::kw___thiscall,
00836                       tok::kw___vectorcall, tok::kw___unaligned))
00837         return TPResult::True; // attributes indicate declaration
00838       TPResult TPR = TryParseDeclarator(mayBeAbstract, mayHaveIdentifier);
00839       if (TPR != TPResult::Ambiguous)
00840         return TPR;
00841       if (Tok.isNot(tok::r_paren))
00842         return TPResult::False;
00843       ConsumeParen();
00844     }
00845   } else if (!mayBeAbstract) {
00846     return TPResult::False;
00847   }
00848 
00849   while (1) {
00850     TPResult TPR(TPResult::Ambiguous);
00851 
00852     // abstract-declarator: ...
00853     if (Tok.is(tok::ellipsis))
00854       ConsumeToken();
00855 
00856     if (Tok.is(tok::l_paren)) {
00857       // Check whether we have a function declarator or a possible ctor-style
00858       // initializer that follows the declarator. Note that ctor-style
00859       // initializers are not possible in contexts where abstract declarators
00860       // are allowed.
00861       if (!mayBeAbstract && !isCXXFunctionDeclarator())
00862         break;
00863 
00864       // direct-declarator '(' parameter-declaration-clause ')'
00865       //        cv-qualifier-seq[opt] exception-specification[opt]
00866       ConsumeParen();
00867       TPR = TryParseFunctionDeclarator();
00868     } else if (Tok.is(tok::l_square)) {
00869       // direct-declarator '[' constant-expression[opt] ']'
00870       // direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
00871       TPR = TryParseBracketDeclarator();
00872     } else {
00873       break;
00874     }
00875 
00876     if (TPR != TPResult::Ambiguous)
00877       return TPR;
00878   }
00879 
00880   return TPResult::Ambiguous;
00881 }
00882 
00883 Parser::TPResult 
00884 Parser::isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind) {
00885   switch (Kind) {
00886   // Obviously starts an expression.
00887   case tok::numeric_constant:
00888   case tok::char_constant:
00889   case tok::wide_char_constant:
00890   case tok::utf8_char_constant:
00891   case tok::utf16_char_constant:
00892   case tok::utf32_char_constant:
00893   case tok::string_literal:
00894   case tok::wide_string_literal:
00895   case tok::utf8_string_literal:
00896   case tok::utf16_string_literal:
00897   case tok::utf32_string_literal:
00898   case tok::l_square:
00899   case tok::l_paren:
00900   case tok::amp:
00901   case tok::ampamp:
00902   case tok::star:
00903   case tok::plus:
00904   case tok::plusplus:
00905   case tok::minus:
00906   case tok::minusminus:
00907   case tok::tilde:
00908   case tok::exclaim:
00909   case tok::kw_sizeof:
00910   case tok::kw___func__:
00911   case tok::kw_const_cast:
00912   case tok::kw_delete:
00913   case tok::kw_dynamic_cast:
00914   case tok::kw_false:
00915   case tok::kw_new:
00916   case tok::kw_operator:
00917   case tok::kw_reinterpret_cast:
00918   case tok::kw_static_cast:
00919   case tok::kw_this:
00920   case tok::kw_throw:
00921   case tok::kw_true:
00922   case tok::kw_typeid:
00923   case tok::kw_alignof:
00924   case tok::kw_noexcept:
00925   case tok::kw_nullptr:
00926   case tok::kw__Alignof:
00927   case tok::kw___null:
00928   case tok::kw___alignof:
00929   case tok::kw___builtin_choose_expr:
00930   case tok::kw___builtin_offsetof:
00931   case tok::kw___builtin_va_arg:
00932   case tok::kw___imag:
00933   case tok::kw___real:
00934   case tok::kw___FUNCTION__:
00935   case tok::kw___FUNCDNAME__:
00936   case tok::kw___FUNCSIG__:
00937   case tok::kw_L__FUNCTION__:
00938   case tok::kw___PRETTY_FUNCTION__:
00939   case tok::kw___uuidof:
00940 #define TYPE_TRAIT(N,Spelling,K) \
00941   case tok::kw_##Spelling:
00942 #include "clang/Basic/TokenKinds.def"
00943     return TPResult::True;
00944       
00945   // Obviously starts a type-specifier-seq:
00946   case tok::kw_char:
00947   case tok::kw_const:
00948   case tok::kw_double:
00949   case tok::kw_enum:
00950   case tok::kw_half:
00951   case tok::kw_float:
00952   case tok::kw_int:
00953   case tok::kw_long:
00954   case tok::kw___int64:
00955   case tok::kw___int128:
00956   case tok::kw_restrict:
00957   case tok::kw_short:
00958   case tok::kw_signed:
00959   case tok::kw_struct:
00960   case tok::kw_union:
00961   case tok::kw_unsigned:
00962   case tok::kw_void:
00963   case tok::kw_volatile:
00964   case tok::kw__Bool:
00965   case tok::kw__Complex:
00966   case tok::kw_class:
00967   case tok::kw_typename:
00968   case tok::kw_wchar_t:
00969   case tok::kw_char16_t:
00970   case tok::kw_char32_t:
00971   case tok::kw__Decimal32:
00972   case tok::kw__Decimal64:
00973   case tok::kw__Decimal128:
00974   case tok::kw___interface:
00975   case tok::kw___thread:
00976   case tok::kw_thread_local:
00977   case tok::kw__Thread_local:
00978   case tok::kw_typeof:
00979   case tok::kw___underlying_type:
00980   case tok::kw___cdecl:
00981   case tok::kw___stdcall:
00982   case tok::kw___fastcall:
00983   case tok::kw___thiscall:
00984   case tok::kw___vectorcall:
00985   case tok::kw___unaligned:
00986   case tok::kw___vector:
00987   case tok::kw___pixel:
00988   case tok::kw___bool:
00989   case tok::kw__Atomic:
00990   case tok::kw___unknown_anytype:
00991     return TPResult::False;
00992 
00993   default:
00994     break;
00995   }
00996   
00997   return TPResult::Ambiguous;
00998 }
00999 
01000 bool Parser::isTentativelyDeclared(IdentifierInfo *II) {
01001   return std::find(TentativelyDeclaredIdentifiers.begin(),
01002                    TentativelyDeclaredIdentifiers.end(), II)
01003       != TentativelyDeclaredIdentifiers.end();
01004 }
01005 
01006 namespace {
01007 class TentativeParseCCC : public CorrectionCandidateCallback {
01008 public:
01009   TentativeParseCCC(const Token &Next) {
01010     WantRemainingKeywords = false;
01011     WantTypeSpecifiers = Next.isOneOf(tok::l_paren, tok::r_paren, tok::greater,
01012                                       tok::l_brace, tok::identifier);
01013   }
01014 
01015   bool ValidateCandidate(const TypoCorrection &Candidate) override {
01016     // Reject any candidate that only resolves to instance members since they
01017     // aren't viable as standalone identifiers instead of member references.
01018     if (Candidate.isResolved() && !Candidate.isKeyword() &&
01019         std::all_of(Candidate.begin(), Candidate.end(),
01020                     [](NamedDecl *ND) { return ND->isCXXInstanceMember(); }))
01021       return false;
01022 
01023     return CorrectionCandidateCallback::ValidateCandidate(Candidate);
01024   }
01025 };
01026 }
01027 /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a declaration
01028 /// specifier, TPResult::False if it is not, TPResult::Ambiguous if it could
01029 /// be either a decl-specifier or a function-style cast, and TPResult::Error
01030 /// if a parsing error was found and reported.
01031 ///
01032 /// If HasMissingTypename is provided, a name with a dependent scope specifier
01033 /// will be treated as ambiguous if the 'typename' keyword is missing. If this
01034 /// happens, *HasMissingTypename will be set to 'true'. This will also be used
01035 /// as an indicator that undeclared identifiers (which will trigger a later
01036 /// parse error) should be treated as types. Returns TPResult::Ambiguous in
01037 /// such cases.
01038 ///
01039 ///         decl-specifier:
01040 ///           storage-class-specifier
01041 ///           type-specifier
01042 ///           function-specifier
01043 ///           'friend'
01044 ///           'typedef'
01045 /// [C++11]   'constexpr'
01046 /// [GNU]     attributes declaration-specifiers[opt]
01047 ///
01048 ///         storage-class-specifier:
01049 ///           'register'
01050 ///           'static'
01051 ///           'extern'
01052 ///           'mutable'
01053 ///           'auto'
01054 /// [GNU]     '__thread'
01055 /// [C++11]   'thread_local'
01056 /// [C11]     '_Thread_local'
01057 ///
01058 ///         function-specifier:
01059 ///           'inline'
01060 ///           'virtual'
01061 ///           'explicit'
01062 ///
01063 ///         typedef-name:
01064 ///           identifier
01065 ///
01066 ///         type-specifier:
01067 ///           simple-type-specifier
01068 ///           class-specifier
01069 ///           enum-specifier
01070 ///           elaborated-type-specifier
01071 ///           typename-specifier
01072 ///           cv-qualifier
01073 ///
01074 ///         simple-type-specifier:
01075 ///           '::'[opt] nested-name-specifier[opt] type-name
01076 ///           '::'[opt] nested-name-specifier 'template'
01077 ///                 simple-template-id                              [TODO]
01078 ///           'char'
01079 ///           'wchar_t'
01080 ///           'bool'
01081 ///           'short'
01082 ///           'int'
01083 ///           'long'
01084 ///           'signed'
01085 ///           'unsigned'
01086 ///           'float'
01087 ///           'double'
01088 ///           'void'
01089 /// [GNU]     typeof-specifier
01090 /// [GNU]     '_Complex'
01091 /// [C++11]   'auto'
01092 /// [GNU]     '__auto_type'
01093 /// [C++11]   'decltype' ( expression )
01094 /// [C++1y]   'decltype' ( 'auto' )
01095 ///
01096 ///         type-name:
01097 ///           class-name
01098 ///           enum-name
01099 ///           typedef-name
01100 ///
01101 ///         elaborated-type-specifier:
01102 ///           class-key '::'[opt] nested-name-specifier[opt] identifier
01103 ///           class-key '::'[opt] nested-name-specifier[opt] 'template'[opt]
01104 ///               simple-template-id
01105 ///           'enum' '::'[opt] nested-name-specifier[opt] identifier
01106 ///
01107 ///         enum-name:
01108 ///           identifier
01109 ///
01110 ///         enum-specifier:
01111 ///           'enum' identifier[opt] '{' enumerator-list[opt] '}'
01112 ///           'enum' identifier[opt] '{' enumerator-list ',' '}'
01113 ///
01114 ///         class-specifier:
01115 ///           class-head '{' member-specification[opt] '}'
01116 ///
01117 ///         class-head:
01118 ///           class-key identifier[opt] base-clause[opt]
01119 ///           class-key nested-name-specifier identifier base-clause[opt]
01120 ///           class-key nested-name-specifier[opt] simple-template-id
01121 ///               base-clause[opt]
01122 ///
01123 ///         class-key:
01124 ///           'class'
01125 ///           'struct'
01126 ///           'union'
01127 ///
01128 ///         cv-qualifier:
01129 ///           'const'
01130 ///           'volatile'
01131 /// [GNU]     restrict
01132 ///
01133 Parser::TPResult
01134 Parser::isCXXDeclarationSpecifier(Parser::TPResult BracedCastResult,
01135                                   bool *HasMissingTypename) {
01136   switch (Tok.getKind()) {
01137   case tok::identifier: {
01138     // Check for need to substitute AltiVec __vector keyword
01139     // for "vector" identifier.
01140     if (TryAltiVecVectorToken())
01141       return TPResult::True;
01142 
01143     const Token &Next = NextToken();
01144     // In 'foo bar', 'foo' is always a type name outside of Objective-C.
01145     if (!getLangOpts().ObjC1 && Next.is(tok::identifier))
01146       return TPResult::True;
01147 
01148     if (Next.isNot(tok::coloncolon) && Next.isNot(tok::less)) {
01149       // Determine whether this is a valid expression. If not, we will hit
01150       // a parse error one way or another. In that case, tell the caller that
01151       // this is ambiguous. Typo-correct to type and expression keywords and
01152       // to types and identifiers, in order to try to recover from errors.
01153       switch (TryAnnotateName(false /* no nested name specifier */,
01154                               llvm::make_unique<TentativeParseCCC>(Next))) {
01155       case ANK_Error:
01156         return TPResult::Error;
01157       case ANK_TentativeDecl:
01158         return TPResult::False;
01159       case ANK_TemplateName:
01160         // A bare type template-name which can't be a template template
01161         // argument is an error, and was probably intended to be a type.
01162         return GreaterThanIsOperator ? TPResult::True : TPResult::False;
01163       case ANK_Unresolved:
01164         return HasMissingTypename ? TPResult::Ambiguous : TPResult::False;
01165       case ANK_Success:
01166         break;
01167       }
01168       assert(Tok.isNot(tok::identifier) &&
01169              "TryAnnotateName succeeded without producing an annotation");
01170     } else {
01171       // This might possibly be a type with a dependent scope specifier and
01172       // a missing 'typename' keyword. Don't use TryAnnotateName in this case,
01173       // since it will annotate as a primary expression, and we want to use the
01174       // "missing 'typename'" logic.
01175       if (TryAnnotateTypeOrScopeToken())
01176         return TPResult::Error;
01177       // If annotation failed, assume it's a non-type.
01178       // FIXME: If this happens due to an undeclared identifier, treat it as
01179       // ambiguous.
01180       if (Tok.is(tok::identifier))
01181         return TPResult::False;
01182     }
01183 
01184     // We annotated this token as something. Recurse to handle whatever we got.
01185     return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
01186   }
01187 
01188   case tok::kw_typename:  // typename T::type
01189     // Annotate typenames and C++ scope specifiers.  If we get one, just
01190     // recurse to handle whatever we get.
01191     if (TryAnnotateTypeOrScopeToken())
01192       return TPResult::Error;
01193     return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
01194 
01195   case tok::coloncolon: {    // ::foo::bar
01196     const Token &Next = NextToken();
01197     if (Next.isOneOf(tok::kw_new,       // ::new
01198                      tok::kw_delete))   // ::delete
01199       return TPResult::False;
01200   }
01201     // Fall through.
01202   case tok::kw___super:
01203   case tok::kw_decltype:
01204     // Annotate typenames and C++ scope specifiers.  If we get one, just
01205     // recurse to handle whatever we get.
01206     if (TryAnnotateTypeOrScopeToken())
01207       return TPResult::Error;
01208     return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
01209 
01210     // decl-specifier:
01211     //   storage-class-specifier
01212     //   type-specifier
01213     //   function-specifier
01214     //   'friend'
01215     //   'typedef'
01216     //   'constexpr'
01217     //   'concept'
01218   case tok::kw_friend:
01219   case tok::kw_typedef:
01220   case tok::kw_constexpr:
01221   case tok::kw_concept:
01222     // storage-class-specifier
01223   case tok::kw_register:
01224   case tok::kw_static:
01225   case tok::kw_extern:
01226   case tok::kw_mutable:
01227   case tok::kw_auto:
01228   case tok::kw___thread:
01229   case tok::kw_thread_local:
01230   case tok::kw__Thread_local:
01231     // function-specifier
01232   case tok::kw_inline:
01233   case tok::kw_virtual:
01234   case tok::kw_explicit:
01235 
01236     // Modules
01237   case tok::kw___module_private__:
01238 
01239     // Debugger support
01240   case tok::kw___unknown_anytype:
01241       
01242     // type-specifier:
01243     //   simple-type-specifier
01244     //   class-specifier
01245     //   enum-specifier
01246     //   elaborated-type-specifier
01247     //   typename-specifier
01248     //   cv-qualifier
01249 
01250     // class-specifier
01251     // elaborated-type-specifier
01252   case tok::kw_class:
01253   case tok::kw_struct:
01254   case tok::kw_union:
01255   case tok::kw___interface:
01256     // enum-specifier
01257   case tok::kw_enum:
01258     // cv-qualifier
01259   case tok::kw_const:
01260   case tok::kw_volatile:
01261 
01262     // GNU
01263   case tok::kw_restrict:
01264   case tok::kw__Complex:
01265   case tok::kw___attribute:
01266   case tok::kw___auto_type:
01267     return TPResult::True;
01268 
01269     // Microsoft
01270   case tok::kw___declspec:
01271   case tok::kw___cdecl:
01272   case tok::kw___stdcall:
01273   case tok::kw___fastcall:
01274   case tok::kw___thiscall:
01275   case tok::kw___vectorcall:
01276   case tok::kw___w64:
01277   case tok::kw___sptr:
01278   case tok::kw___uptr:
01279   case tok::kw___ptr64:
01280   case tok::kw___ptr32:
01281   case tok::kw___forceinline:
01282   case tok::kw___unaligned:
01283   case tok::kw__Nonnull:
01284   case tok::kw__Nullable:
01285   case tok::kw__Null_unspecified:
01286   case tok::kw___kindof:
01287     return TPResult::True;
01288 
01289     // Borland
01290   case tok::kw___pascal:
01291     return TPResult::True;
01292   
01293     // AltiVec
01294   case tok::kw___vector:
01295     return TPResult::True;
01296 
01297   case tok::annot_template_id: {
01298     TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
01299     if (TemplateId->Kind != TNK_Type_template)
01300       return TPResult::False;
01301     CXXScopeSpec SS;
01302     AnnotateTemplateIdTokenAsType();
01303     assert(Tok.is(tok::annot_typename));
01304     goto case_typename;
01305   }
01306 
01307   case tok::annot_cxxscope: // foo::bar or ::foo::bar, but already parsed
01308     // We've already annotated a scope; try to annotate a type.
01309     if (TryAnnotateTypeOrScopeToken())
01310       return TPResult::Error;
01311     if (!Tok.is(tok::annot_typename)) {
01312       // If the next token is an identifier or a type qualifier, then this
01313       // can't possibly be a valid expression either.
01314       if (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier)) {
01315         CXXScopeSpec SS;
01316         Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
01317                                                      Tok.getAnnotationRange(),
01318                                                      SS);
01319         if (SS.getScopeRep() && SS.getScopeRep()->isDependent()) {
01320           TentativeParsingAction PA(*this);
01321           ConsumeToken();
01322           ConsumeToken();
01323           bool isIdentifier = Tok.is(tok::identifier);
01324           TPResult TPR = TPResult::False;
01325           if (!isIdentifier)
01326             TPR = isCXXDeclarationSpecifier(BracedCastResult,
01327                                             HasMissingTypename);
01328           PA.Revert();
01329 
01330           if (isIdentifier ||
01331               TPR == TPResult::True || TPR == TPResult::Error)
01332             return TPResult::Error;
01333 
01334           if (HasMissingTypename) {
01335             // We can't tell whether this is a missing 'typename' or a valid
01336             // expression.
01337             *HasMissingTypename = true;
01338             return TPResult::Ambiguous;
01339           }
01340         } else {
01341           // Try to resolve the name. If it doesn't exist, assume it was
01342           // intended to name a type and keep disambiguating.
01343           switch (TryAnnotateName(false /* SS is not dependent */)) {
01344           case ANK_Error:
01345             return TPResult::Error;
01346           case ANK_TentativeDecl:
01347             return TPResult::False;
01348           case ANK_TemplateName:
01349             // A bare type template-name which can't be a template template
01350             // argument is an error, and was probably intended to be a type.
01351             return GreaterThanIsOperator ? TPResult::True : TPResult::False;
01352           case ANK_Unresolved:
01353             return HasMissingTypename ? TPResult::Ambiguous
01354                                       : TPResult::False;
01355           case ANK_Success:
01356             // Annotated it, check again.
01357             assert(Tok.isNot(tok::annot_cxxscope) ||
01358                    NextToken().isNot(tok::identifier));
01359             return isCXXDeclarationSpecifier(BracedCastResult,
01360                                              HasMissingTypename);
01361           }
01362         }
01363       }
01364       return TPResult::False;
01365     }
01366     // If that succeeded, fallthrough into the generic simple-type-id case.
01367 
01368     // The ambiguity resides in a simple-type-specifier/typename-specifier
01369     // followed by a '('. The '(' could either be the start of:
01370     //
01371     //   direct-declarator:
01372     //     '(' declarator ')'
01373     //
01374     //   direct-abstract-declarator:
01375     //     '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
01376     //              exception-specification[opt]
01377     //     '(' abstract-declarator ')'
01378     //
01379     // or part of a function-style cast expression:
01380     //
01381     //     simple-type-specifier '(' expression-list[opt] ')'
01382     //
01383 
01384     // simple-type-specifier:
01385 
01386   case tok::annot_typename:
01387   case_typename:
01388     // In Objective-C, we might have a protocol-qualified type.
01389     if (getLangOpts().ObjC1 && NextToken().is(tok::less)) {
01390       // Tentatively parse the protocol qualifiers.
01391       TentativeParsingAction PA(*this);
01392       ConsumeToken(); // The type token
01393       
01394       TPResult TPR = TryParseProtocolQualifiers();
01395       bool isFollowedByParen = Tok.is(tok::l_paren);
01396       bool isFollowedByBrace = Tok.is(tok::l_brace);
01397       
01398       PA.Revert();
01399       
01400       if (TPR == TPResult::Error)
01401         return TPResult::Error;
01402       
01403       if (isFollowedByParen)
01404         return TPResult::Ambiguous;
01405 
01406       if (getLangOpts().CPlusPlus11 && isFollowedByBrace)
01407         return BracedCastResult;
01408       
01409       return TPResult::True;
01410     }
01411       
01412   case tok::kw_char:
01413   case tok::kw_wchar_t:
01414   case tok::kw_char16_t:
01415   case tok::kw_char32_t:
01416   case tok::kw_bool:
01417   case tok::kw_short:
01418   case tok::kw_int:
01419   case tok::kw_long:
01420   case tok::kw___int64:
01421   case tok::kw___int128:
01422   case tok::kw_signed:
01423   case tok::kw_unsigned:
01424   case tok::kw_half:
01425   case tok::kw_float:
01426   case tok::kw_double:
01427   case tok::kw_void:
01428   case tok::annot_decltype:
01429     if (NextToken().is(tok::l_paren))
01430       return TPResult::Ambiguous;
01431 
01432     // This is a function-style cast in all cases we disambiguate other than
01433     // one:
01434     //   struct S {
01435     //     enum E : int { a = 4 }; // enum
01436     //     enum E : int { 4 };     // bit-field
01437     //   };
01438     if (getLangOpts().CPlusPlus11 && NextToken().is(tok::l_brace))
01439       return BracedCastResult;
01440 
01441     if (isStartOfObjCClassMessageMissingOpenBracket())
01442       return TPResult::False;
01443       
01444     return TPResult::True;
01445 
01446   // GNU typeof support.
01447   case tok::kw_typeof: {
01448     if (NextToken().isNot(tok::l_paren))
01449       return TPResult::True;
01450 
01451     TentativeParsingAction PA(*this);
01452 
01453     TPResult TPR = TryParseTypeofSpecifier();
01454     bool isFollowedByParen = Tok.is(tok::l_paren);
01455     bool isFollowedByBrace = Tok.is(tok::l_brace);
01456 
01457     PA.Revert();
01458 
01459     if (TPR == TPResult::Error)
01460       return TPResult::Error;
01461 
01462     if (isFollowedByParen)
01463       return TPResult::Ambiguous;
01464 
01465     if (getLangOpts().CPlusPlus11 && isFollowedByBrace)
01466       return BracedCastResult;
01467 
01468     return TPResult::True;
01469   }
01470 
01471   // C++0x type traits support
01472   case tok::kw___underlying_type:
01473     return TPResult::True;
01474 
01475   // C11 _Atomic
01476   case tok::kw__Atomic:
01477     return TPResult::True;
01478 
01479   default:
01480     return TPResult::False;
01481   }
01482 }
01483 
01484 bool Parser::isCXXDeclarationSpecifierAType() {
01485   switch (Tok.getKind()) {
01486     // typename-specifier
01487   case tok::annot_decltype:
01488   case tok::annot_template_id:
01489   case tok::annot_typename:
01490   case tok::kw_typeof:
01491   case tok::kw___underlying_type:
01492     return true;
01493 
01494     // elaborated-type-specifier
01495   case tok::kw_class:
01496   case tok::kw_struct:
01497   case tok::kw_union:
01498   case tok::kw___interface:
01499   case tok::kw_enum:
01500     return true;
01501 
01502     // simple-type-specifier
01503   case tok::kw_char:
01504   case tok::kw_wchar_t:
01505   case tok::kw_char16_t:
01506   case tok::kw_char32_t:
01507   case tok::kw_bool:
01508   case tok::kw_short:
01509   case tok::kw_int:
01510   case tok::kw_long:
01511   case tok::kw___int64:
01512   case tok::kw___int128:
01513   case tok::kw_signed:
01514   case tok::kw_unsigned:
01515   case tok::kw_half:
01516   case tok::kw_float:
01517   case tok::kw_double:
01518   case tok::kw_void:
01519   case tok::kw___unknown_anytype:
01520   case tok::kw___auto_type:
01521     return true;
01522 
01523   case tok::kw_auto:
01524     return getLangOpts().CPlusPlus11;
01525 
01526   case tok::kw__Atomic:
01527     // "_Atomic foo"
01528     return NextToken().is(tok::l_paren);
01529 
01530   default:
01531     return false;
01532   }
01533 }
01534 
01535 /// [GNU] typeof-specifier:
01536 ///         'typeof' '(' expressions ')'
01537 ///         'typeof' '(' type-name ')'
01538 ///
01539 Parser::TPResult Parser::TryParseTypeofSpecifier() {
01540   assert(Tok.is(tok::kw_typeof) && "Expected 'typeof'!");
01541   ConsumeToken();
01542 
01543   assert(Tok.is(tok::l_paren) && "Expected '('");
01544   // Parse through the parens after 'typeof'.
01545   ConsumeParen();
01546   if (!SkipUntil(tok::r_paren, StopAtSemi))
01547     return TPResult::Error;
01548 
01549   return TPResult::Ambiguous;
01550 }
01551 
01552 /// [ObjC] protocol-qualifiers:
01553 ////         '<' identifier-list '>'
01554 Parser::TPResult Parser::TryParseProtocolQualifiers() {
01555   assert(Tok.is(tok::less) && "Expected '<' for qualifier list");
01556   ConsumeToken();
01557   do {
01558     if (Tok.isNot(tok::identifier))
01559       return TPResult::Error;
01560     ConsumeToken();
01561     
01562     if (Tok.is(tok::comma)) {
01563       ConsumeToken();
01564       continue;
01565     }
01566     
01567     if (Tok.is(tok::greater)) {
01568       ConsumeToken();
01569       return TPResult::Ambiguous;
01570     }
01571   } while (false);
01572   
01573   return TPResult::Error;
01574 }
01575 
01576 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
01577 /// a constructor-style initializer, when parsing declaration statements.
01578 /// Returns true for function declarator and false for constructor-style
01579 /// initializer.
01580 /// If during the disambiguation process a parsing error is encountered,
01581 /// the function returns true to let the declaration parsing code handle it.
01582 ///
01583 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
01584 ///         exception-specification[opt]
01585 ///
01586 bool Parser::isCXXFunctionDeclarator(bool *IsAmbiguous) {
01587 
01588   // C++ 8.2p1:
01589   // The ambiguity arising from the similarity between a function-style cast and
01590   // a declaration mentioned in 6.8 can also occur in the context of a
01591   // declaration. In that context, the choice is between a function declaration
01592   // with a redundant set of parentheses around a parameter name and an object
01593   // declaration with a function-style cast as the initializer. Just as for the
01594   // ambiguities mentioned in 6.8, the resolution is to consider any construct
01595   // that could possibly be a declaration a declaration.
01596 
01597   TentativeParsingAction PA(*this);
01598 
01599   ConsumeParen();
01600   bool InvalidAsDeclaration = false;
01601   TPResult TPR = TryParseParameterDeclarationClause(&InvalidAsDeclaration);
01602   if (TPR == TPResult::Ambiguous) {
01603     if (Tok.isNot(tok::r_paren))
01604       TPR = TPResult::False;
01605     else {
01606       const Token &Next = NextToken();
01607       if (Next.isOneOf(tok::amp, tok::ampamp, tok::kw_const, tok::kw_volatile,
01608                        tok::kw_throw, tok::kw_noexcept, tok::l_square,
01609                        tok::l_brace, tok::kw_try, tok::equal, tok::arrow) ||
01610           isCXX11VirtSpecifier(Next))
01611         // The next token cannot appear after a constructor-style initializer,
01612         // and can appear next in a function definition. This must be a function
01613         // declarator.
01614         TPR = TPResult::True;
01615       else if (InvalidAsDeclaration)
01616         // Use the absence of 'typename' as a tie-breaker.
01617         TPR = TPResult::False;
01618     }
01619   }
01620 
01621   PA.Revert();
01622 
01623   if (IsAmbiguous && TPR == TPResult::Ambiguous)
01624     *IsAmbiguous = true;
01625 
01626   // In case of an error, let the declaration parsing code handle it.
01627   return TPR != TPResult::False;
01628 }
01629 
01630 /// parameter-declaration-clause:
01631 ///   parameter-declaration-list[opt] '...'[opt]
01632 ///   parameter-declaration-list ',' '...'
01633 ///
01634 /// parameter-declaration-list:
01635 ///   parameter-declaration
01636 ///   parameter-declaration-list ',' parameter-declaration
01637 ///
01638 /// parameter-declaration:
01639 ///   attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
01640 ///   attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
01641 ///     '=' assignment-expression
01642 ///   attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
01643 ///     attributes[opt]
01644 ///   attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
01645 ///     attributes[opt] '=' assignment-expression
01646 ///
01647 Parser::TPResult
01648 Parser::TryParseParameterDeclarationClause(bool *InvalidAsDeclaration,
01649                                            bool VersusTemplateArgument) {
01650 
01651   if (Tok.is(tok::r_paren))
01652     return TPResult::Ambiguous;
01653 
01654   //   parameter-declaration-list[opt] '...'[opt]
01655   //   parameter-declaration-list ',' '...'
01656   //
01657   // parameter-declaration-list:
01658   //   parameter-declaration
01659   //   parameter-declaration-list ',' parameter-declaration
01660   //
01661   while (1) {
01662     // '...'[opt]
01663     if (Tok.is(tok::ellipsis)) {
01664       ConsumeToken();
01665       if (Tok.is(tok::r_paren))
01666         return TPResult::True; // '...)' is a sign of a function declarator.
01667       else
01668         return TPResult::False;
01669     }
01670 
01671     // An attribute-specifier-seq here is a sign of a function declarator.
01672     if (isCXX11AttributeSpecifier(/*Disambiguate*/false,
01673                                   /*OuterMightBeMessageSend*/true))
01674       return TPResult::True;
01675 
01676     ParsedAttributes attrs(AttrFactory);
01677     MaybeParseMicrosoftAttributes(attrs);
01678 
01679     // decl-specifier-seq
01680     // A parameter-declaration's initializer must be preceded by an '=', so
01681     // decl-specifier-seq '{' is not a parameter in C++11.
01682     TPResult TPR = isCXXDeclarationSpecifier(TPResult::False,
01683                                              InvalidAsDeclaration);
01684 
01685     if (VersusTemplateArgument && TPR == TPResult::True) {
01686       // Consume the decl-specifier-seq. We have to look past it, since a
01687       // type-id might appear here in a template argument.
01688       bool SeenType = false;
01689       do {
01690         SeenType |= isCXXDeclarationSpecifierAType();
01691         if (TryConsumeDeclarationSpecifier() == TPResult::Error)
01692           return TPResult::Error;
01693 
01694         // If we see a parameter name, this can't be a template argument.
01695         if (SeenType && Tok.is(tok::identifier))
01696           return TPResult::True;
01697 
01698         TPR = isCXXDeclarationSpecifier(TPResult::False,
01699                                         InvalidAsDeclaration);
01700         if (TPR == TPResult::Error)
01701           return TPR;
01702       } while (TPR != TPResult::False);
01703     } else if (TPR == TPResult::Ambiguous) {
01704       // Disambiguate what follows the decl-specifier.
01705       if (TryConsumeDeclarationSpecifier() == TPResult::Error)
01706         return TPResult::Error;
01707     } else
01708       return TPR;
01709 
01710     // declarator
01711     // abstract-declarator[opt]
01712     TPR = TryParseDeclarator(true/*mayBeAbstract*/);
01713     if (TPR != TPResult::Ambiguous)
01714       return TPR;
01715 
01716     // [GNU] attributes[opt]
01717     if (Tok.is(tok::kw___attribute))
01718       return TPResult::True;
01719 
01720     // If we're disambiguating a template argument in a default argument in
01721     // a class definition versus a parameter declaration, an '=' here
01722     // disambiguates the parse one way or the other.
01723     // If this is a parameter, it must have a default argument because
01724     //   (a) the previous parameter did, and
01725     //   (b) this must be the first declaration of the function, so we can't
01726     //       inherit any default arguments from elsewhere.
01727     // If we see an ')', then we've reached the end of a
01728     // parameter-declaration-clause, and the last param is missing its default
01729     // argument.
01730     if (VersusTemplateArgument)
01731       return Tok.isOneOf(tok::equal, tok::r_paren) ? TPResult::True
01732                                                    : TPResult::False;
01733 
01734     if (Tok.is(tok::equal)) {
01735       // '=' assignment-expression
01736       // Parse through assignment-expression.
01737       // FIXME: assignment-expression may contain an unparenthesized comma.
01738       if (!SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch))
01739         return TPResult::Error;
01740     }
01741 
01742     if (Tok.is(tok::ellipsis)) {
01743       ConsumeToken();
01744       if (Tok.is(tok::r_paren))
01745         return TPResult::True; // '...)' is a sign of a function declarator.
01746       else
01747         return TPResult::False;
01748     }
01749 
01750     if (!TryConsumeToken(tok::comma))
01751       break;
01752   }
01753 
01754   return TPResult::Ambiguous;
01755 }
01756 
01757 /// TryParseFunctionDeclarator - We parsed a '(' and we want to try to continue
01758 /// parsing as a function declarator.
01759 /// If TryParseFunctionDeclarator fully parsed the function declarator, it will
01760 /// return TPResult::Ambiguous, otherwise it will return either False() or
01761 /// Error().
01762 ///
01763 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
01764 ///         exception-specification[opt]
01765 ///
01766 /// exception-specification:
01767 ///   'throw' '(' type-id-list[opt] ')'
01768 ///
01769 Parser::TPResult Parser::TryParseFunctionDeclarator() {
01770 
01771   // The '(' is already parsed.
01772 
01773   TPResult TPR = TryParseParameterDeclarationClause();
01774   if (TPR == TPResult::Ambiguous && Tok.isNot(tok::r_paren))
01775     TPR = TPResult::False;
01776 
01777   if (TPR == TPResult::False || TPR == TPResult::Error)
01778     return TPR;
01779 
01780   // Parse through the parens.
01781   if (!SkipUntil(tok::r_paren, StopAtSemi))
01782     return TPResult::Error;
01783 
01784   // cv-qualifier-seq
01785   while (Tok.isOneOf(tok::kw_const, tok::kw_volatile, tok::kw_restrict))
01786     ConsumeToken();
01787 
01788   // ref-qualifier[opt]
01789   if (Tok.isOneOf(tok::amp, tok::ampamp))
01790     ConsumeToken();
01791   
01792   // exception-specification
01793   if (Tok.is(tok::kw_throw)) {
01794     ConsumeToken();
01795     if (Tok.isNot(tok::l_paren))
01796       return TPResult::Error;
01797 
01798     // Parse through the parens after 'throw'.
01799     ConsumeParen();
01800     if (!SkipUntil(tok::r_paren, StopAtSemi))
01801       return TPResult::Error;
01802   }
01803   if (Tok.is(tok::kw_noexcept)) {
01804     ConsumeToken();
01805     // Possibly an expression as well.
01806     if (Tok.is(tok::l_paren)) {
01807       // Find the matching rparen.
01808       ConsumeParen();
01809       if (!SkipUntil(tok::r_paren, StopAtSemi))
01810         return TPResult::Error;
01811     }
01812   }
01813 
01814   return TPResult::Ambiguous;
01815 }
01816 
01817 /// '[' constant-expression[opt] ']'
01818 ///
01819 Parser::TPResult Parser::TryParseBracketDeclarator() {
01820   ConsumeBracket();
01821   if (!SkipUntil(tok::r_square, StopAtSemi))
01822     return TPResult::Error;
01823 
01824   return TPResult::Ambiguous;
01825 }