clang  mainline
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.is(tok::l_square) || Tok.is(tok::kw___attribute) ||
00183            Tok.is(tok::kw___declspec) || Tok.is(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.is(tok::identifier) || Tok.is(tok::coloncolon) ||
00199          Tok.is(tok::kw_decltype) || Tok.is(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.is(tok::kw_asm) || Tok.is(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.is(tok::equal)  ||
00374         Tok.is(tok::kw_asm) || Tok.is(tok::kw___attribute))
00375       TPR = TPResult::True;
00376     else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace))
00377       TPR = TPResult::True;
00378     else
00379       TPR = TPResult::False;
00380   }
00381 
00382   PA.Revert();
00383 
00384   assert(TPR == TPResult::True || TPR == TPResult::False);
00385   return TPR == TPResult::True;
00386 }
00387 
00388   /// \brief Determine whether the next set of tokens contains a type-id.
00389   ///
00390   /// The context parameter states what context we're parsing right
00391   /// now, which affects how this routine copes with the token
00392   /// following the type-id. If the context is TypeIdInParens, we have
00393   /// already parsed the '(' and we will cease lookahead when we hit
00394   /// the corresponding ')'. If the context is
00395   /// TypeIdAsTemplateArgument, we've already parsed the '<' or ','
00396   /// before this template argument, and will cease lookahead when we
00397   /// hit a '>', '>>' (in C++0x), or ','. Returns true for a type-id
00398   /// and false for an expression.  If during the disambiguation
00399   /// process a parsing error is encountered, the function returns
00400   /// true to let the declaration parsing code handle it.
00401   ///
00402   /// type-id:
00403   ///   type-specifier-seq abstract-declarator[opt]
00404   ///
00405 bool Parser::isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous) {
00406 
00407   isAmbiguous = false;
00408 
00409   // C++ 8.2p2:
00410   // The ambiguity arising from the similarity between a function-style cast and
00411   // a type-id can occur in different contexts. The ambiguity appears as a
00412   // choice between a function-style cast expression and a declaration of a
00413   // type. The resolution is that any construct that could possibly be a type-id
00414   // in its syntactic context shall be considered a type-id.
00415 
00416   TPResult TPR = isCXXDeclarationSpecifier();
00417   if (TPR != TPResult::Ambiguous)
00418     return TPR != TPResult::False; // Returns true for TPResult::True or
00419                                      // TPResult::Error.
00420 
00421   // FIXME: Add statistics about the number of ambiguous statements encountered
00422   // and how they were resolved (number of declarations+number of expressions).
00423 
00424   // Ok, we have a simple-type-specifier/typename-specifier followed by a '('.
00425   // We need tentative parsing...
00426 
00427   TentativeParsingAction PA(*this);
00428 
00429   // type-specifier-seq
00430   TryConsumeDeclarationSpecifier();
00431   assert(Tok.is(tok::l_paren) && "Expected '('");
00432 
00433   // declarator
00434   TPR = TryParseDeclarator(true/*mayBeAbstract*/, false/*mayHaveIdentifier*/);
00435 
00436   // In case of an error, let the declaration parsing code handle it.
00437   if (TPR == TPResult::Error)
00438     TPR = TPResult::True;
00439 
00440   if (TPR == TPResult::Ambiguous) {
00441     // We are supposed to be inside parens, so if after the abstract declarator
00442     // we encounter a ')' this is a type-id, otherwise it's an expression.
00443     if (Context == TypeIdInParens && Tok.is(tok::r_paren)) {
00444       TPR = TPResult::True;
00445       isAmbiguous = true;
00446 
00447     // We are supposed to be inside a template argument, so if after
00448     // the abstract declarator we encounter a '>', '>>' (in C++0x), or
00449     // ',', this is a type-id. Otherwise, it's an expression.
00450     } else if (Context == TypeIdAsTemplateArgument &&
00451                (Tok.is(tok::greater) || Tok.is(tok::comma) ||
00452                 (getLangOpts().CPlusPlus11 && Tok.is(tok::greatergreater)))) {
00453       TPR = TPResult::True;
00454       isAmbiguous = true;
00455 
00456     } else
00457       TPR = TPResult::False;
00458   }
00459 
00460   PA.Revert();
00461 
00462   assert(TPR == TPResult::True || TPR == TPResult::False);
00463   return TPR == TPResult::True;
00464 }
00465 
00466 /// \brief Returns true if this is a C++11 attribute-specifier. Per
00467 /// C++11 [dcl.attr.grammar]p6, two consecutive left square bracket tokens
00468 /// always introduce an attribute. In Objective-C++11, this rule does not
00469 /// apply if either '[' begins a message-send.
00470 ///
00471 /// If Disambiguate is true, we try harder to determine whether a '[[' starts
00472 /// an attribute-specifier, and return CAK_InvalidAttributeSpecifier if not.
00473 ///
00474 /// If OuterMightBeMessageSend is true, we assume the outer '[' is either an
00475 /// Obj-C message send or the start of an attribute. Otherwise, we assume it
00476 /// is not an Obj-C message send.
00477 ///
00478 /// C++11 [dcl.attr.grammar]:
00479 ///
00480 ///     attribute-specifier:
00481 ///         '[' '[' attribute-list ']' ']'
00482 ///         alignment-specifier
00483 ///
00484 ///     attribute-list:
00485 ///         attribute[opt]
00486 ///         attribute-list ',' attribute[opt]
00487 ///         attribute '...'
00488 ///         attribute-list ',' attribute '...'
00489 ///
00490 ///     attribute:
00491 ///         attribute-token attribute-argument-clause[opt]
00492 ///
00493 ///     attribute-token:
00494 ///         identifier
00495 ///         identifier '::' identifier
00496 ///
00497 ///     attribute-argument-clause:
00498 ///         '(' balanced-token-seq ')'
00499 Parser::CXX11AttributeKind
00500 Parser::isCXX11AttributeSpecifier(bool Disambiguate,
00501                                   bool OuterMightBeMessageSend) {
00502   if (Tok.is(tok::kw_alignas))
00503     return CAK_AttributeSpecifier;
00504 
00505   if (Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square))
00506     return CAK_NotAttributeSpecifier;
00507 
00508   // No tentative parsing if we don't need to look for ']]' or a lambda.
00509   if (!Disambiguate && !getLangOpts().ObjC1)
00510     return CAK_AttributeSpecifier;
00511 
00512   TentativeParsingAction PA(*this);
00513 
00514   // Opening brackets were checked for above.
00515   ConsumeBracket();
00516 
00517   // Outside Obj-C++11, treat anything with a matching ']]' as an attribute.
00518   if (!getLangOpts().ObjC1) {
00519     ConsumeBracket();
00520 
00521     bool IsAttribute = SkipUntil(tok::r_square);
00522     IsAttribute &= Tok.is(tok::r_square);
00523 
00524     PA.Revert();
00525 
00526     return IsAttribute ? CAK_AttributeSpecifier : CAK_InvalidAttributeSpecifier;
00527   }
00528 
00529   // In Obj-C++11, we need to distinguish four situations:
00530   //  1a) int x[[attr]];                     C++11 attribute.
00531   //  1b) [[attr]];                          C++11 statement attribute.
00532   //   2) int x[[obj](){ return 1; }()];     Lambda in array size/index.
00533   //  3a) int x[[obj get]];                  Message send in array size/index.
00534   //  3b) [[Class alloc] init];              Message send in message send.
00535   //   4) [[obj]{ return self; }() doStuff]; Lambda in message send.
00536   // (1) is an attribute, (2) is ill-formed, and (3) and (4) are accepted.
00537 
00538   // If we have a lambda-introducer, then this is definitely not a message send.
00539   // FIXME: If this disambiguation is too slow, fold the tentative lambda parse
00540   // into the tentative attribute parse below.
00541   LambdaIntroducer Intro;
00542   if (!TryParseLambdaIntroducer(Intro)) {
00543     // A lambda cannot end with ']]', and an attribute must.
00544     bool IsAttribute = Tok.is(tok::r_square);
00545 
00546     PA.Revert();
00547 
00548     if (IsAttribute)
00549       // Case 1: C++11 attribute.
00550       return CAK_AttributeSpecifier;
00551 
00552     if (OuterMightBeMessageSend)
00553       // Case 4: Lambda in message send.
00554       return CAK_NotAttributeSpecifier;
00555 
00556     // Case 2: Lambda in array size / index.
00557     return CAK_InvalidAttributeSpecifier;
00558   }
00559 
00560   ConsumeBracket();
00561 
00562   // If we don't have a lambda-introducer, then we have an attribute or a
00563   // message-send.
00564   bool IsAttribute = true;
00565   while (Tok.isNot(tok::r_square)) {
00566     if (Tok.is(tok::comma)) {
00567       // Case 1: Stray commas can only occur in attributes.
00568       PA.Revert();
00569       return CAK_AttributeSpecifier;
00570     }
00571 
00572     // Parse the attribute-token, if present.
00573     // C++11 [dcl.attr.grammar]:
00574     //   If a keyword or an alternative token that satisfies the syntactic
00575     //   requirements of an identifier is contained in an attribute-token,
00576     //   it is considered an identifier.
00577     SourceLocation Loc;
00578     if (!TryParseCXX11AttributeIdentifier(Loc)) {
00579       IsAttribute = false;
00580       break;
00581     }
00582     if (Tok.is(tok::coloncolon)) {
00583       ConsumeToken();
00584       if (!TryParseCXX11AttributeIdentifier(Loc)) {
00585         IsAttribute = false;
00586         break;
00587       }
00588     }
00589 
00590     // Parse the attribute-argument-clause, if present.
00591     if (Tok.is(tok::l_paren)) {
00592       ConsumeParen();
00593       if (!SkipUntil(tok::r_paren)) {
00594         IsAttribute = false;
00595         break;
00596       }
00597     }
00598 
00599     TryConsumeToken(tok::ellipsis);
00600 
00601     if (!TryConsumeToken(tok::comma))
00602       break;
00603   }
00604 
00605   // An attribute must end ']]'.
00606   if (IsAttribute) {
00607     if (Tok.is(tok::r_square)) {
00608       ConsumeBracket();
00609       IsAttribute = Tok.is(tok::r_square);
00610     } else {
00611       IsAttribute = false;
00612     }
00613   }
00614 
00615   PA.Revert();
00616 
00617   if (IsAttribute)
00618     // Case 1: C++11 statement attribute.
00619     return CAK_AttributeSpecifier;
00620 
00621   // Case 3: Message send.
00622   return CAK_NotAttributeSpecifier;
00623 }
00624 
00625 Parser::TPResult Parser::TryParsePtrOperatorSeq() {
00626   while (true) {
00627     if (Tok.is(tok::coloncolon) || Tok.is(tok::identifier))
00628       if (TryAnnotateCXXScopeToken(true))
00629         return TPResult::Error;
00630 
00631     if (Tok.is(tok::star) || Tok.is(tok::amp) || Tok.is(tok::caret) ||
00632         Tok.is(tok::ampamp) ||
00633         (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::star))) {
00634       // ptr-operator
00635       ConsumeToken();
00636       while (Tok.is(tok::kw_const)    ||
00637              Tok.is(tok::kw_volatile) ||
00638              Tok.is(tok::kw_restrict))
00639         ConsumeToken();
00640     } else {
00641       return TPResult::True;
00642     }
00643   }
00644 }
00645 
00646 ///         operator-function-id:
00647 ///           'operator' operator
00648 ///
00649 ///         operator: one of
00650 ///           new  delete  new[]  delete[]  +  -  *  /  %  ^  [...]
00651 ///
00652 ///         conversion-function-id:
00653 ///           'operator' conversion-type-id
00654 ///
00655 ///         conversion-type-id:
00656 ///           type-specifier-seq conversion-declarator[opt]
00657 ///
00658 ///         conversion-declarator:
00659 ///           ptr-operator conversion-declarator[opt]
00660 ///
00661 ///         literal-operator-id:
00662 ///           'operator' string-literal identifier
00663 ///           'operator' user-defined-string-literal
00664 Parser::TPResult Parser::TryParseOperatorId() {
00665   assert(Tok.is(tok::kw_operator));
00666   ConsumeToken();
00667 
00668   // Maybe this is an operator-function-id.
00669   switch (Tok.getKind()) {
00670   case tok::kw_new: case tok::kw_delete:
00671     ConsumeToken();
00672     if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
00673       ConsumeBracket();
00674       ConsumeBracket();
00675     }
00676     return TPResult::True;
00677 
00678 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemOnly) \
00679   case tok::Token:
00680 #define OVERLOADED_OPERATOR_MULTI(Name, Spelling, Unary, Binary, MemOnly)
00681 #include "clang/Basic/OperatorKinds.def"
00682     ConsumeToken();
00683     return TPResult::True;
00684 
00685   case tok::l_square:
00686     if (NextToken().is(tok::r_square)) {
00687       ConsumeBracket();
00688       ConsumeBracket();
00689       return TPResult::True;
00690     }
00691     break;
00692 
00693   case tok::l_paren:
00694     if (NextToken().is(tok::r_paren)) {
00695       ConsumeParen();
00696       ConsumeParen();
00697       return TPResult::True;
00698     }
00699     break;
00700 
00701   default:
00702     break;
00703   }
00704 
00705   // Maybe this is a literal-operator-id.
00706   if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
00707     bool FoundUDSuffix = false;
00708     do {
00709       FoundUDSuffix |= Tok.hasUDSuffix();
00710       ConsumeStringToken();
00711     } while (isTokenStringLiteral());
00712 
00713     if (!FoundUDSuffix) {
00714       if (Tok.is(tok::identifier))
00715         ConsumeToken();
00716       else
00717         return TPResult::Error;
00718     }
00719     return TPResult::True;
00720   }
00721 
00722   // Maybe this is a conversion-function-id.
00723   bool AnyDeclSpecifiers = false;
00724   while (true) {
00725     TPResult TPR = isCXXDeclarationSpecifier();
00726     if (TPR == TPResult::Error)
00727       return TPR;
00728     if (TPR == TPResult::False) {
00729       if (!AnyDeclSpecifiers)
00730         return TPResult::Error;
00731       break;
00732     }
00733     if (TryConsumeDeclarationSpecifier() == TPResult::Error)
00734       return TPResult::Error;
00735     AnyDeclSpecifiers = true;
00736   }
00737   return TryParsePtrOperatorSeq();
00738 }
00739 
00740 ///         declarator:
00741 ///           direct-declarator
00742 ///           ptr-operator declarator
00743 ///
00744 ///         direct-declarator:
00745 ///           declarator-id
00746 ///           direct-declarator '(' parameter-declaration-clause ')'
00747 ///                 cv-qualifier-seq[opt] exception-specification[opt]
00748 ///           direct-declarator '[' constant-expression[opt] ']'
00749 ///           '(' declarator ')'
00750 /// [GNU]     '(' attributes declarator ')'
00751 ///
00752 ///         abstract-declarator:
00753 ///           ptr-operator abstract-declarator[opt]
00754 ///           direct-abstract-declarator
00755 ///           ...
00756 ///
00757 ///         direct-abstract-declarator:
00758 ///           direct-abstract-declarator[opt]
00759 ///           '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
00760 ///                 exception-specification[opt]
00761 ///           direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
00762 ///           '(' abstract-declarator ')'
00763 ///
00764 ///         ptr-operator:
00765 ///           '*' cv-qualifier-seq[opt]
00766 ///           '&'
00767 /// [C++0x]   '&&'                                                        [TODO]
00768 ///           '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
00769 ///
00770 ///         cv-qualifier-seq:
00771 ///           cv-qualifier cv-qualifier-seq[opt]
00772 ///
00773 ///         cv-qualifier:
00774 ///           'const'
00775 ///           'volatile'
00776 ///
00777 ///         declarator-id:
00778 ///           '...'[opt] id-expression
00779 ///
00780 ///         id-expression:
00781 ///           unqualified-id
00782 ///           qualified-id                                                [TODO]
00783 ///
00784 ///         unqualified-id:
00785 ///           identifier
00786 ///           operator-function-id
00787 ///           conversion-function-id
00788 ///           literal-operator-id
00789 ///           '~' class-name                                              [TODO]
00790 ///           '~' decltype-specifier                                      [TODO]
00791 ///           template-id                                                 [TODO]
00792 ///
00793 Parser::TPResult Parser::TryParseDeclarator(bool mayBeAbstract,
00794                                             bool mayHaveIdentifier) {
00795   // declarator:
00796   //   direct-declarator
00797   //   ptr-operator declarator
00798   if (TryParsePtrOperatorSeq() == TPResult::Error)
00799     return TPResult::Error;
00800 
00801   // direct-declarator:
00802   // direct-abstract-declarator:
00803   if (Tok.is(tok::ellipsis))
00804     ConsumeToken();
00805 
00806   if ((Tok.is(tok::identifier) || Tok.is(tok::kw_operator) ||
00807        (Tok.is(tok::annot_cxxscope) && (NextToken().is(tok::identifier) ||
00808                                         NextToken().is(tok::kw_operator)))) &&
00809       mayHaveIdentifier) {
00810     // declarator-id
00811     if (Tok.is(tok::annot_cxxscope))
00812       ConsumeToken();
00813     else if (Tok.is(tok::identifier))
00814       TentativelyDeclaredIdentifiers.push_back(Tok.getIdentifierInfo());
00815     if (Tok.is(tok::kw_operator)) {
00816       if (TryParseOperatorId() == TPResult::Error)
00817         return TPResult::Error;
00818     } else
00819       ConsumeToken();
00820   } else if (Tok.is(tok::l_paren)) {
00821     ConsumeParen();
00822     if (mayBeAbstract &&
00823         (Tok.is(tok::r_paren) ||       // 'int()' is a function.
00824          // 'int(...)' is a function.
00825          (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren)) ||
00826          isDeclarationSpecifier())) {   // 'int(int)' is a function.
00827       // '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
00828       //        exception-specification[opt]
00829       TPResult TPR = TryParseFunctionDeclarator();
00830       if (TPR != TPResult::Ambiguous)
00831         return TPR;
00832     } else {
00833       // '(' declarator ')'
00834       // '(' attributes declarator ')'
00835       // '(' abstract-declarator ')'
00836       if (Tok.is(tok::kw___attribute) ||
00837           Tok.is(tok::kw___declspec) ||
00838           Tok.is(tok::kw___cdecl) ||
00839           Tok.is(tok::kw___stdcall) ||
00840           Tok.is(tok::kw___fastcall) ||
00841           Tok.is(tok::kw___thiscall) ||
00842           Tok.is(tok::kw___vectorcall) ||
00843           Tok.is(tok::kw___unaligned))
00844         return TPResult::True; // attributes indicate declaration
00845       TPResult TPR = TryParseDeclarator(mayBeAbstract, mayHaveIdentifier);
00846       if (TPR != TPResult::Ambiguous)
00847         return TPR;
00848       if (Tok.isNot(tok::r_paren))
00849         return TPResult::False;
00850       ConsumeParen();
00851     }
00852   } else if (!mayBeAbstract) {
00853     return TPResult::False;
00854   }
00855 
00856   while (1) {
00857     TPResult TPR(TPResult::Ambiguous);
00858 
00859     // abstract-declarator: ...
00860     if (Tok.is(tok::ellipsis))
00861       ConsumeToken();
00862 
00863     if (Tok.is(tok::l_paren)) {
00864       // Check whether we have a function declarator or a possible ctor-style
00865       // initializer that follows the declarator. Note that ctor-style
00866       // initializers are not possible in contexts where abstract declarators
00867       // are allowed.
00868       if (!mayBeAbstract && !isCXXFunctionDeclarator())
00869         break;
00870 
00871       // direct-declarator '(' parameter-declaration-clause ')'
00872       //        cv-qualifier-seq[opt] exception-specification[opt]
00873       ConsumeParen();
00874       TPR = TryParseFunctionDeclarator();
00875     } else if (Tok.is(tok::l_square)) {
00876       // direct-declarator '[' constant-expression[opt] ']'
00877       // direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
00878       TPR = TryParseBracketDeclarator();
00879     } else {
00880       break;
00881     }
00882 
00883     if (TPR != TPResult::Ambiguous)
00884       return TPR;
00885   }
00886 
00887   return TPResult::Ambiguous;
00888 }
00889 
00890 Parser::TPResult 
00891 Parser::isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind) {
00892   switch (Kind) {
00893   // Obviously starts an expression.
00894   case tok::numeric_constant:
00895   case tok::char_constant:
00896   case tok::wide_char_constant:
00897   case tok::utf8_char_constant:
00898   case tok::utf16_char_constant:
00899   case tok::utf32_char_constant:
00900   case tok::string_literal:
00901   case tok::wide_string_literal:
00902   case tok::utf8_string_literal:
00903   case tok::utf16_string_literal:
00904   case tok::utf32_string_literal:
00905   case tok::l_square:
00906   case tok::l_paren:
00907   case tok::amp:
00908   case tok::ampamp:
00909   case tok::star:
00910   case tok::plus:
00911   case tok::plusplus:
00912   case tok::minus:
00913   case tok::minusminus:
00914   case tok::tilde:
00915   case tok::exclaim:
00916   case tok::kw_sizeof:
00917   case tok::kw___func__:
00918   case tok::kw_const_cast:
00919   case tok::kw_delete:
00920   case tok::kw_dynamic_cast:
00921   case tok::kw_false:
00922   case tok::kw_new:
00923   case tok::kw_operator:
00924   case tok::kw_reinterpret_cast:
00925   case tok::kw_static_cast:
00926   case tok::kw_this:
00927   case tok::kw_throw:
00928   case tok::kw_true:
00929   case tok::kw_typeid:
00930   case tok::kw_alignof:
00931   case tok::kw_noexcept:
00932   case tok::kw_nullptr:
00933   case tok::kw__Alignof:
00934   case tok::kw___null:
00935   case tok::kw___alignof:
00936   case tok::kw___builtin_choose_expr:
00937   case tok::kw___builtin_offsetof:
00938   case tok::kw___builtin_va_arg:
00939   case tok::kw___imag:
00940   case tok::kw___real:
00941   case tok::kw___FUNCTION__:
00942   case tok::kw___FUNCDNAME__:
00943   case tok::kw___FUNCSIG__:
00944   case tok::kw_L__FUNCTION__:
00945   case tok::kw___PRETTY_FUNCTION__:
00946   case tok::kw___uuidof:
00947 #define TYPE_TRAIT(N,Spelling,K) \
00948   case tok::kw_##Spelling:
00949 #include "clang/Basic/TokenKinds.def"
00950     return TPResult::True;
00951       
00952   // Obviously starts a type-specifier-seq:
00953   case tok::kw_char:
00954   case tok::kw_const:
00955   case tok::kw_double:
00956   case tok::kw_enum:
00957   case tok::kw_half:
00958   case tok::kw_float:
00959   case tok::kw_int:
00960   case tok::kw_long:
00961   case tok::kw___int64:
00962   case tok::kw___int128:
00963   case tok::kw_restrict:
00964   case tok::kw_short:
00965   case tok::kw_signed:
00966   case tok::kw_struct:
00967   case tok::kw_union:
00968   case tok::kw_unsigned:
00969   case tok::kw_void:
00970   case tok::kw_volatile:
00971   case tok::kw__Bool:
00972   case tok::kw__Complex:
00973   case tok::kw_class:
00974   case tok::kw_typename:
00975   case tok::kw_wchar_t:
00976   case tok::kw_char16_t:
00977   case tok::kw_char32_t:
00978   case tok::kw__Decimal32:
00979   case tok::kw__Decimal64:
00980   case tok::kw__Decimal128:
00981   case tok::kw___interface:
00982   case tok::kw___thread:
00983   case tok::kw_thread_local:
00984   case tok::kw__Thread_local:
00985   case tok::kw_typeof:
00986   case tok::kw___underlying_type:
00987   case tok::kw___cdecl:
00988   case tok::kw___stdcall:
00989   case tok::kw___fastcall:
00990   case tok::kw___thiscall:
00991   case tok::kw___vectorcall:
00992   case tok::kw___unaligned:
00993   case tok::kw___vector:
00994   case tok::kw___pixel:
00995   case tok::kw___bool:
00996   case tok::kw__Atomic:
00997   case tok::kw___unknown_anytype:
00998     return TPResult::False;
00999 
01000   default:
01001     break;
01002   }
01003   
01004   return TPResult::Ambiguous;
01005 }
01006 
01007 bool Parser::isTentativelyDeclared(IdentifierInfo *II) {
01008   return std::find(TentativelyDeclaredIdentifiers.begin(),
01009                    TentativelyDeclaredIdentifiers.end(), II)
01010       != TentativelyDeclaredIdentifiers.end();
01011 }
01012 
01013 namespace {
01014 class TentativeParseCCC : public CorrectionCandidateCallback {
01015 public:
01016   TentativeParseCCC(const Token &Next) {
01017     WantRemainingKeywords = false;
01018     WantTypeSpecifiers = Next.is(tok::l_paren) || Next.is(tok::r_paren) ||
01019                          Next.is(tok::greater) || Next.is(tok::l_brace) ||
01020                          Next.is(tok::identifier);
01021   }
01022 
01023   bool ValidateCandidate(const TypoCorrection &Candidate) override {
01024     // Reject any candidate that only resolves to instance members since they
01025     // aren't viable as standalone identifiers instead of member references.
01026     if (Candidate.isResolved() && !Candidate.isKeyword() &&
01027         std::all_of(Candidate.begin(), Candidate.end(),
01028                     [](NamedDecl *ND) { return ND->isCXXInstanceMember(); }))
01029       return false;
01030 
01031     return CorrectionCandidateCallback::ValidateCandidate(Candidate);
01032   }
01033 };
01034 }
01035 /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a declaration
01036 /// specifier, TPResult::False if it is not, TPResult::Ambiguous if it could
01037 /// be either a decl-specifier or a function-style cast, and TPResult::Error
01038 /// if a parsing error was found and reported.
01039 ///
01040 /// If HasMissingTypename is provided, a name with a dependent scope specifier
01041 /// will be treated as ambiguous if the 'typename' keyword is missing. If this
01042 /// happens, *HasMissingTypename will be set to 'true'. This will also be used
01043 /// as an indicator that undeclared identifiers (which will trigger a later
01044 /// parse error) should be treated as types. Returns TPResult::Ambiguous in
01045 /// such cases.
01046 ///
01047 ///         decl-specifier:
01048 ///           storage-class-specifier
01049 ///           type-specifier
01050 ///           function-specifier
01051 ///           'friend'
01052 ///           'typedef'
01053 /// [C++11]   'constexpr'
01054 /// [GNU]     attributes declaration-specifiers[opt]
01055 ///
01056 ///         storage-class-specifier:
01057 ///           'register'
01058 ///           'static'
01059 ///           'extern'
01060 ///           'mutable'
01061 ///           'auto'
01062 /// [GNU]     '__thread'
01063 /// [C++11]   'thread_local'
01064 /// [C11]     '_Thread_local'
01065 ///
01066 ///         function-specifier:
01067 ///           'inline'
01068 ///           'virtual'
01069 ///           'explicit'
01070 ///
01071 ///         typedef-name:
01072 ///           identifier
01073 ///
01074 ///         type-specifier:
01075 ///           simple-type-specifier
01076 ///           class-specifier
01077 ///           enum-specifier
01078 ///           elaborated-type-specifier
01079 ///           typename-specifier
01080 ///           cv-qualifier
01081 ///
01082 ///         simple-type-specifier:
01083 ///           '::'[opt] nested-name-specifier[opt] type-name
01084 ///           '::'[opt] nested-name-specifier 'template'
01085 ///                 simple-template-id                              [TODO]
01086 ///           'char'
01087 ///           'wchar_t'
01088 ///           'bool'
01089 ///           'short'
01090 ///           'int'
01091 ///           'long'
01092 ///           'signed'
01093 ///           'unsigned'
01094 ///           'float'
01095 ///           'double'
01096 ///           'void'
01097 /// [GNU]     typeof-specifier
01098 /// [GNU]     '_Complex'
01099 /// [C++11]   'auto'
01100 /// [C++11]   'decltype' ( expression )
01101 /// [C++1y]   'decltype' ( 'auto' )
01102 ///
01103 ///         type-name:
01104 ///           class-name
01105 ///           enum-name
01106 ///           typedef-name
01107 ///
01108 ///         elaborated-type-specifier:
01109 ///           class-key '::'[opt] nested-name-specifier[opt] identifier
01110 ///           class-key '::'[opt] nested-name-specifier[opt] 'template'[opt]
01111 ///               simple-template-id
01112 ///           'enum' '::'[opt] nested-name-specifier[opt] identifier
01113 ///
01114 ///         enum-name:
01115 ///           identifier
01116 ///
01117 ///         enum-specifier:
01118 ///           'enum' identifier[opt] '{' enumerator-list[opt] '}'
01119 ///           'enum' identifier[opt] '{' enumerator-list ',' '}'
01120 ///
01121 ///         class-specifier:
01122 ///           class-head '{' member-specification[opt] '}'
01123 ///
01124 ///         class-head:
01125 ///           class-key identifier[opt] base-clause[opt]
01126 ///           class-key nested-name-specifier identifier base-clause[opt]
01127 ///           class-key nested-name-specifier[opt] simple-template-id
01128 ///               base-clause[opt]
01129 ///
01130 ///         class-key:
01131 ///           'class'
01132 ///           'struct'
01133 ///           'union'
01134 ///
01135 ///         cv-qualifier:
01136 ///           'const'
01137 ///           'volatile'
01138 /// [GNU]     restrict
01139 ///
01140 Parser::TPResult
01141 Parser::isCXXDeclarationSpecifier(Parser::TPResult BracedCastResult,
01142                                   bool *HasMissingTypename) {
01143   switch (Tok.getKind()) {
01144   case tok::identifier: {
01145     // Check for need to substitute AltiVec __vector keyword
01146     // for "vector" identifier.
01147     if (TryAltiVecVectorToken())
01148       return TPResult::True;
01149 
01150     const Token &Next = NextToken();
01151     // In 'foo bar', 'foo' is always a type name outside of Objective-C.
01152     if (!getLangOpts().ObjC1 && Next.is(tok::identifier))
01153       return TPResult::True;
01154 
01155     if (Next.isNot(tok::coloncolon) && Next.isNot(tok::less)) {
01156       // Determine whether this is a valid expression. If not, we will hit
01157       // a parse error one way or another. In that case, tell the caller that
01158       // this is ambiguous. Typo-correct to type and expression keywords and
01159       // to types and identifiers, in order to try to recover from errors.
01160       switch (TryAnnotateName(false /* no nested name specifier */,
01161                               llvm::make_unique<TentativeParseCCC>(Next))) {
01162       case ANK_Error:
01163         return TPResult::Error;
01164       case ANK_TentativeDecl:
01165         return TPResult::False;
01166       case ANK_TemplateName:
01167         // A bare type template-name which can't be a template template
01168         // argument is an error, and was probably intended to be a type.
01169         return GreaterThanIsOperator ? TPResult::True : TPResult::False;
01170       case ANK_Unresolved:
01171         return HasMissingTypename ? TPResult::Ambiguous : TPResult::False;
01172       case ANK_Success:
01173         break;
01174       }
01175       assert(Tok.isNot(tok::identifier) &&
01176              "TryAnnotateName succeeded without producing an annotation");
01177     } else {
01178       // This might possibly be a type with a dependent scope specifier and
01179       // a missing 'typename' keyword. Don't use TryAnnotateName in this case,
01180       // since it will annotate as a primary expression, and we want to use the
01181       // "missing 'typename'" logic.
01182       if (TryAnnotateTypeOrScopeToken())
01183         return TPResult::Error;
01184       // If annotation failed, assume it's a non-type.
01185       // FIXME: If this happens due to an undeclared identifier, treat it as
01186       // ambiguous.
01187       if (Tok.is(tok::identifier))
01188         return TPResult::False;
01189     }
01190 
01191     // We annotated this token as something. Recurse to handle whatever we got.
01192     return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
01193   }
01194 
01195   case tok::kw_typename:  // typename T::type
01196     // Annotate typenames and C++ scope specifiers.  If we get one, just
01197     // recurse to handle whatever we get.
01198     if (TryAnnotateTypeOrScopeToken())
01199       return TPResult::Error;
01200     return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
01201 
01202   case tok::coloncolon: {    // ::foo::bar
01203     const Token &Next = NextToken();
01204     if (Next.is(tok::kw_new) ||    // ::new
01205         Next.is(tok::kw_delete))   // ::delete
01206       return TPResult::False;
01207   }
01208     // Fall through.
01209   case tok::kw___super:
01210   case tok::kw_decltype:
01211     // Annotate typenames and C++ scope specifiers.  If we get one, just
01212     // recurse to handle whatever we get.
01213     if (TryAnnotateTypeOrScopeToken())
01214       return TPResult::Error;
01215     return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
01216 
01217     // decl-specifier:
01218     //   storage-class-specifier
01219     //   type-specifier
01220     //   function-specifier
01221     //   'friend'
01222     //   'typedef'
01223     //   'constexpr'
01224   case tok::kw_friend:
01225   case tok::kw_typedef:
01226   case tok::kw_constexpr:
01227     // storage-class-specifier
01228   case tok::kw_register:
01229   case tok::kw_static:
01230   case tok::kw_extern:
01231   case tok::kw_mutable:
01232   case tok::kw_auto:
01233   case tok::kw___thread:
01234   case tok::kw_thread_local:
01235   case tok::kw__Thread_local:
01236     // function-specifier
01237   case tok::kw_inline:
01238   case tok::kw_virtual:
01239   case tok::kw_explicit:
01240 
01241     // Modules
01242   case tok::kw___module_private__:
01243 
01244     // Debugger support
01245   case tok::kw___unknown_anytype:
01246       
01247     // type-specifier:
01248     //   simple-type-specifier
01249     //   class-specifier
01250     //   enum-specifier
01251     //   elaborated-type-specifier
01252     //   typename-specifier
01253     //   cv-qualifier
01254 
01255     // class-specifier
01256     // elaborated-type-specifier
01257   case tok::kw_class:
01258   case tok::kw_struct:
01259   case tok::kw_union:
01260   case tok::kw___interface:
01261     // enum-specifier
01262   case tok::kw_enum:
01263     // cv-qualifier
01264   case tok::kw_const:
01265   case tok::kw_volatile:
01266 
01267     // GNU
01268   case tok::kw_restrict:
01269   case tok::kw__Complex:
01270   case tok::kw___attribute:
01271     return TPResult::True;
01272 
01273     // Microsoft
01274   case tok::kw___declspec:
01275   case tok::kw___cdecl:
01276   case tok::kw___stdcall:
01277   case tok::kw___fastcall:
01278   case tok::kw___thiscall:
01279   case tok::kw___vectorcall:
01280   case tok::kw___w64:
01281   case tok::kw___sptr:
01282   case tok::kw___uptr:
01283   case tok::kw___ptr64:
01284   case tok::kw___ptr32:
01285   case tok::kw___forceinline:
01286   case tok::kw___unaligned:
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 
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     return true;
01521 
01522   case tok::kw_auto:
01523     return getLangOpts().CPlusPlus11;
01524 
01525   case tok::kw__Atomic:
01526     // "_Atomic foo"
01527     return NextToken().is(tok::l_paren);
01528 
01529   default:
01530     return false;
01531   }
01532 }
01533 
01534 /// [GNU] typeof-specifier:
01535 ///         'typeof' '(' expressions ')'
01536 ///         'typeof' '(' type-name ')'
01537 ///
01538 Parser::TPResult Parser::TryParseTypeofSpecifier() {
01539   assert(Tok.is(tok::kw_typeof) && "Expected 'typeof'!");
01540   ConsumeToken();
01541 
01542   assert(Tok.is(tok::l_paren) && "Expected '('");
01543   // Parse through the parens after 'typeof'.
01544   ConsumeParen();
01545   if (!SkipUntil(tok::r_paren, StopAtSemi))
01546     return TPResult::Error;
01547 
01548   return TPResult::Ambiguous;
01549 }
01550 
01551 /// [ObjC] protocol-qualifiers:
01552 ////         '<' identifier-list '>'
01553 Parser::TPResult Parser::TryParseProtocolQualifiers() {
01554   assert(Tok.is(tok::less) && "Expected '<' for qualifier list");
01555   ConsumeToken();
01556   do {
01557     if (Tok.isNot(tok::identifier))
01558       return TPResult::Error;
01559     ConsumeToken();
01560     
01561     if (Tok.is(tok::comma)) {
01562       ConsumeToken();
01563       continue;
01564     }
01565     
01566     if (Tok.is(tok::greater)) {
01567       ConsumeToken();
01568       return TPResult::Ambiguous;
01569     }
01570   } while (false);
01571   
01572   return TPResult::Error;
01573 }
01574 
01575 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
01576 /// a constructor-style initializer, when parsing declaration statements.
01577 /// Returns true for function declarator and false for constructor-style
01578 /// initializer.
01579 /// If during the disambiguation process a parsing error is encountered,
01580 /// the function returns true to let the declaration parsing code handle it.
01581 ///
01582 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
01583 ///         exception-specification[opt]
01584 ///
01585 bool Parser::isCXXFunctionDeclarator(bool *IsAmbiguous) {
01586 
01587   // C++ 8.2p1:
01588   // The ambiguity arising from the similarity between a function-style cast and
01589   // a declaration mentioned in 6.8 can also occur in the context of a
01590   // declaration. In that context, the choice is between a function declaration
01591   // with a redundant set of parentheses around a parameter name and an object
01592   // declaration with a function-style cast as the initializer. Just as for the
01593   // ambiguities mentioned in 6.8, the resolution is to consider any construct
01594   // that could possibly be a declaration a declaration.
01595 
01596   TentativeParsingAction PA(*this);
01597 
01598   ConsumeParen();
01599   bool InvalidAsDeclaration = false;
01600   TPResult TPR = TryParseParameterDeclarationClause(&InvalidAsDeclaration);
01601   if (TPR == TPResult::Ambiguous) {
01602     if (Tok.isNot(tok::r_paren))
01603       TPR = TPResult::False;
01604     else {
01605       const Token &Next = NextToken();
01606       if (Next.is(tok::amp) || Next.is(tok::ampamp) ||
01607           Next.is(tok::kw_const) || Next.is(tok::kw_volatile) ||
01608           Next.is(tok::kw_throw) || Next.is(tok::kw_noexcept) ||
01609           Next.is(tok::l_square) || isCXX11VirtSpecifier(Next) ||
01610           Next.is(tok::l_brace) || Next.is(tok::kw_try) ||
01611           Next.is(tok::equal) || Next.is(tok::arrow))
01612         // The next token cannot appear after a constructor-style initializer,
01613         // and can appear next in a function definition. This must be a function
01614         // declarator.
01615         TPR = TPResult::True;
01616       else if (InvalidAsDeclaration)
01617         // Use the absence of 'typename' as a tie-breaker.
01618         TPR = TPResult::False;
01619     }
01620   }
01621 
01622   PA.Revert();
01623 
01624   if (IsAmbiguous && TPR == TPResult::Ambiguous)
01625     *IsAmbiguous = true;
01626 
01627   // In case of an error, let the declaration parsing code handle it.
01628   return TPR != TPResult::False;
01629 }
01630 
01631 /// parameter-declaration-clause:
01632 ///   parameter-declaration-list[opt] '...'[opt]
01633 ///   parameter-declaration-list ',' '...'
01634 ///
01635 /// parameter-declaration-list:
01636 ///   parameter-declaration
01637 ///   parameter-declaration-list ',' parameter-declaration
01638 ///
01639 /// parameter-declaration:
01640 ///   attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
01641 ///   attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
01642 ///     '=' assignment-expression
01643 ///   attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
01644 ///     attributes[opt]
01645 ///   attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
01646 ///     attributes[opt] '=' assignment-expression
01647 ///
01648 Parser::TPResult
01649 Parser::TryParseParameterDeclarationClause(bool *InvalidAsDeclaration,
01650                                            bool VersusTemplateArgument) {
01651 
01652   if (Tok.is(tok::r_paren))
01653     return TPResult::Ambiguous;
01654 
01655   //   parameter-declaration-list[opt] '...'[opt]
01656   //   parameter-declaration-list ',' '...'
01657   //
01658   // parameter-declaration-list:
01659   //   parameter-declaration
01660   //   parameter-declaration-list ',' parameter-declaration
01661   //
01662   while (1) {
01663     // '...'[opt]
01664     if (Tok.is(tok::ellipsis)) {
01665       ConsumeToken();
01666       if (Tok.is(tok::r_paren))
01667         return TPResult::True; // '...)' is a sign of a function declarator.
01668       else
01669         return TPResult::False;
01670     }
01671 
01672     // An attribute-specifier-seq here is a sign of a function declarator.
01673     if (isCXX11AttributeSpecifier(/*Disambiguate*/false,
01674                                   /*OuterMightBeMessageSend*/true))
01675       return TPResult::True;
01676 
01677     ParsedAttributes attrs(AttrFactory);
01678     MaybeParseMicrosoftAttributes(attrs);
01679 
01680     // decl-specifier-seq
01681     // A parameter-declaration's initializer must be preceded by an '=', so
01682     // decl-specifier-seq '{' is not a parameter in C++11.
01683     TPResult TPR = isCXXDeclarationSpecifier(TPResult::False,
01684                                              InvalidAsDeclaration);
01685 
01686     if (VersusTemplateArgument && TPR == TPResult::True) {
01687       // Consume the decl-specifier-seq. We have to look past it, since a
01688       // type-id might appear here in a template argument.
01689       bool SeenType = false;
01690       do {
01691         SeenType |= isCXXDeclarationSpecifierAType();
01692         if (TryConsumeDeclarationSpecifier() == TPResult::Error)
01693           return TPResult::Error;
01694 
01695         // If we see a parameter name, this can't be a template argument.
01696         if (SeenType && Tok.is(tok::identifier))
01697           return TPResult::True;
01698 
01699         TPR = isCXXDeclarationSpecifier(TPResult::False,
01700                                         InvalidAsDeclaration);
01701         if (TPR == TPResult::Error)
01702           return TPR;
01703       } while (TPR != TPResult::False);
01704     } else if (TPR == TPResult::Ambiguous) {
01705       // Disambiguate what follows the decl-specifier.
01706       if (TryConsumeDeclarationSpecifier() == TPResult::Error)
01707         return TPResult::Error;
01708     } else
01709       return TPR;
01710 
01711     // declarator
01712     // abstract-declarator[opt]
01713     TPR = TryParseDeclarator(true/*mayBeAbstract*/);
01714     if (TPR != TPResult::Ambiguous)
01715       return TPR;
01716 
01717     // [GNU] attributes[opt]
01718     if (Tok.is(tok::kw___attribute))
01719       return TPResult::True;
01720 
01721     // If we're disambiguating a template argument in a default argument in
01722     // a class definition versus a parameter declaration, an '=' here
01723     // disambiguates the parse one way or the other.
01724     // If this is a parameter, it must have a default argument because
01725     //   (a) the previous parameter did, and
01726     //   (b) this must be the first declaration of the function, so we can't
01727     //       inherit any default arguments from elsewhere.
01728     // If we see an ')', then we've reached the end of a
01729     // parameter-declaration-clause, and the last param is missing its default
01730     // argument.
01731     if (VersusTemplateArgument)
01732       return (Tok.is(tok::equal) || Tok.is(tok::r_paren)) ? TPResult::True
01733                                                           : TPResult::False;
01734 
01735     if (Tok.is(tok::equal)) {
01736       // '=' assignment-expression
01737       // Parse through assignment-expression.
01738       // FIXME: assignment-expression may contain an unparenthesized comma.
01739       if (!SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch))
01740         return TPResult::Error;
01741     }
01742 
01743     if (Tok.is(tok::ellipsis)) {
01744       ConsumeToken();
01745       if (Tok.is(tok::r_paren))
01746         return TPResult::True; // '...)' is a sign of a function declarator.
01747       else
01748         return TPResult::False;
01749     }
01750 
01751     if (!TryConsumeToken(tok::comma))
01752       break;
01753   }
01754 
01755   return TPResult::Ambiguous;
01756 }
01757 
01758 /// TryParseFunctionDeclarator - We parsed a '(' and we want to try to continue
01759 /// parsing as a function declarator.
01760 /// If TryParseFunctionDeclarator fully parsed the function declarator, it will
01761 /// return TPResult::Ambiguous, otherwise it will return either False() or
01762 /// Error().
01763 ///
01764 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
01765 ///         exception-specification[opt]
01766 ///
01767 /// exception-specification:
01768 ///   'throw' '(' type-id-list[opt] ')'
01769 ///
01770 Parser::TPResult Parser::TryParseFunctionDeclarator() {
01771 
01772   // The '(' is already parsed.
01773 
01774   TPResult TPR = TryParseParameterDeclarationClause();
01775   if (TPR == TPResult::Ambiguous && Tok.isNot(tok::r_paren))
01776     TPR = TPResult::False;
01777 
01778   if (TPR == TPResult::False || TPR == TPResult::Error)
01779     return TPR;
01780 
01781   // Parse through the parens.
01782   if (!SkipUntil(tok::r_paren, StopAtSemi))
01783     return TPResult::Error;
01784 
01785   // cv-qualifier-seq
01786   while (Tok.is(tok::kw_const)    ||
01787          Tok.is(tok::kw_volatile) ||
01788          Tok.is(tok::kw_restrict)   )
01789     ConsumeToken();
01790 
01791   // ref-qualifier[opt]
01792   if (Tok.is(tok::amp) || Tok.is(tok::ampamp))
01793     ConsumeToken();
01794   
01795   // exception-specification
01796   if (Tok.is(tok::kw_throw)) {
01797     ConsumeToken();
01798     if (Tok.isNot(tok::l_paren))
01799       return TPResult::Error;
01800 
01801     // Parse through the parens after 'throw'.
01802     ConsumeParen();
01803     if (!SkipUntil(tok::r_paren, StopAtSemi))
01804       return TPResult::Error;
01805   }
01806   if (Tok.is(tok::kw_noexcept)) {
01807     ConsumeToken();
01808     // Possibly an expression as well.
01809     if (Tok.is(tok::l_paren)) {
01810       // Find the matching rparen.
01811       ConsumeParen();
01812       if (!SkipUntil(tok::r_paren, StopAtSemi))
01813         return TPResult::Error;
01814     }
01815   }
01816 
01817   return TPResult::Ambiguous;
01818 }
01819 
01820 /// '[' constant-expression[opt] ']'
01821 ///
01822 Parser::TPResult Parser::TryParseBracketDeclarator() {
01823   ConsumeBracket();
01824   if (!SkipUntil(tok::r_square, StopAtSemi))
01825     return TPResult::Error;
01826 
01827   return TPResult::Ambiguous;
01828 }