clang API Documentation

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 (TryAnnotateCXXScopeToken())
00199       return TPResult::Error;
00200     if (Tok.is(tok::annot_cxxscope))
00201       ConsumeToken();
00202     if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id))
00203       return TPResult::Error;
00204     ConsumeToken();
00205     break;
00206 
00207   case tok::annot_cxxscope:
00208     ConsumeToken();
00209     // Fall through.
00210   default:
00211     ConsumeToken();
00212 
00213     if (getLangOpts().ObjC1 && Tok.is(tok::less))
00214       return TryParseProtocolQualifiers();
00215     break;
00216   }
00217 
00218   return TPResult::Ambiguous;
00219 }
00220 
00221 /// simple-declaration:
00222 ///   decl-specifier-seq init-declarator-list[opt] ';'
00223 ///
00224 /// (if AllowForRangeDecl specified)
00225 /// for ( for-range-declaration : for-range-initializer ) statement
00226 /// for-range-declaration: 
00227 ///    attribute-specifier-seqopt type-specifier-seq declarator
00228 ///
00229 Parser::TPResult Parser::TryParseSimpleDeclaration(bool AllowForRangeDecl) {
00230   if (TryConsumeDeclarationSpecifier() == TPResult::Error)
00231     return TPResult::Error;
00232 
00233   // Two decl-specifiers in a row conclusively disambiguate this as being a
00234   // simple-declaration. Don't bother calling isCXXDeclarationSpecifier in the
00235   // overwhelmingly common case that the next token is a '('.
00236   if (Tok.isNot(tok::l_paren)) {
00237     TPResult TPR = isCXXDeclarationSpecifier();
00238     if (TPR == TPResult::Ambiguous)
00239       return TPResult::True;
00240     if (TPR == TPResult::True || TPR == TPResult::Error)
00241       return TPR;
00242     assert(TPR == TPResult::False);
00243   }
00244 
00245   TPResult TPR = TryParseInitDeclaratorList();
00246   if (TPR != TPResult::Ambiguous)
00247     return TPR;
00248 
00249   if (Tok.isNot(tok::semi) && (!AllowForRangeDecl || Tok.isNot(tok::colon)))
00250     return TPResult::False;
00251 
00252   return TPResult::Ambiguous;
00253 }
00254 
00255 /// Tentatively parse an init-declarator-list in order to disambiguate it from
00256 /// an expression.
00257 ///
00258 ///       init-declarator-list:
00259 ///         init-declarator
00260 ///         init-declarator-list ',' init-declarator
00261 ///
00262 ///       init-declarator:
00263 ///         declarator initializer[opt]
00264 /// [GNU]   declarator simple-asm-expr[opt] attributes[opt] initializer[opt]
00265 ///
00266 ///       initializer:
00267 ///         brace-or-equal-initializer
00268 ///         '(' expression-list ')'
00269 ///
00270 ///       brace-or-equal-initializer:
00271 ///         '=' initializer-clause
00272 /// [C++11] braced-init-list
00273 ///
00274 ///       initializer-clause:
00275 ///         assignment-expression
00276 ///         braced-init-list
00277 ///
00278 ///       braced-init-list:
00279 ///         '{' initializer-list ','[opt] '}'
00280 ///         '{' '}'
00281 ///
00282 Parser::TPResult Parser::TryParseInitDeclaratorList() {
00283   while (1) {
00284     // declarator
00285     TPResult TPR = TryParseDeclarator(false/*mayBeAbstract*/);
00286     if (TPR != TPResult::Ambiguous)
00287       return TPR;
00288 
00289     // [GNU] simple-asm-expr[opt] attributes[opt]
00290     if (Tok.is(tok::kw_asm) || Tok.is(tok::kw___attribute))
00291       return TPResult::True;
00292 
00293     // initializer[opt]
00294     if (Tok.is(tok::l_paren)) {
00295       // Parse through the parens.
00296       ConsumeParen();
00297       if (!SkipUntil(tok::r_paren, StopAtSemi))
00298         return TPResult::Error;
00299     } else if (Tok.is(tok::l_brace)) {
00300       // A left-brace here is sufficient to disambiguate the parse; an
00301       // expression can never be followed directly by a braced-init-list.
00302       return TPResult::True;
00303     } else if (Tok.is(tok::equal) || isTokIdentifier_in()) {
00304       // MSVC and g++ won't examine the rest of declarators if '=' is
00305       // encountered; they just conclude that we have a declaration.
00306       // EDG parses the initializer completely, which is the proper behavior
00307       // for this case.
00308       //
00309       // At present, Clang follows MSVC and g++, since the parser does not have
00310       // the ability to parse an expression fully without recording the
00311       // results of that parse.
00312       // FIXME: Handle this case correctly.
00313       //
00314       // Also allow 'in' after an Objective-C declaration as in:
00315       // for (int (^b)(void) in array). Ideally this should be done in the
00316       // context of parsing for-init-statement of a foreach statement only. But,
00317       // in any other context 'in' is invalid after a declaration and parser
00318       // issues the error regardless of outcome of this decision.
00319       // FIXME: Change if above assumption does not hold.
00320       return TPResult::True;
00321     }
00322 
00323     if (!TryConsumeToken(tok::comma))
00324       break;
00325   }
00326 
00327   return TPResult::Ambiguous;
00328 }
00329 
00330 /// isCXXConditionDeclaration - Disambiguates between a declaration or an
00331 /// expression for a condition of a if/switch/while/for statement.
00332 /// If during the disambiguation process a parsing error is encountered,
00333 /// the function returns true to let the declaration parsing code handle it.
00334 ///
00335 ///       condition:
00336 ///         expression
00337 ///         type-specifier-seq declarator '=' assignment-expression
00338 /// [C++11] type-specifier-seq declarator '=' initializer-clause
00339 /// [C++11] type-specifier-seq declarator braced-init-list
00340 /// [GNU]   type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
00341 ///             '=' assignment-expression
00342 ///
00343 bool Parser::isCXXConditionDeclaration() {
00344   TPResult TPR = isCXXDeclarationSpecifier();
00345   if (TPR != TPResult::Ambiguous)
00346     return TPR != TPResult::False; // Returns true for TPResult::True or
00347                                    // TPResult::Error.
00348 
00349   // FIXME: Add statistics about the number of ambiguous statements encountered
00350   // and how they were resolved (number of declarations+number of expressions).
00351 
00352   // Ok, we have a simple-type-specifier/typename-specifier followed by a '('.
00353   // We need tentative parsing...
00354 
00355   TentativeParsingAction PA(*this);
00356 
00357   // type-specifier-seq
00358   TryConsumeDeclarationSpecifier();
00359   assert(Tok.is(tok::l_paren) && "Expected '('");
00360 
00361   // declarator
00362   TPR = TryParseDeclarator(false/*mayBeAbstract*/);
00363 
00364   // In case of an error, let the declaration parsing code handle it.
00365   if (TPR == TPResult::Error)
00366     TPR = TPResult::True;
00367 
00368   if (TPR == TPResult::Ambiguous) {
00369     // '='
00370     // [GNU] simple-asm-expr[opt] attributes[opt]
00371     if (Tok.is(tok::equal)  ||
00372         Tok.is(tok::kw_asm) || Tok.is(tok::kw___attribute))
00373       TPR = TPResult::True;
00374     else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace))
00375       TPR = TPResult::True;
00376     else
00377       TPR = TPResult::False;
00378   }
00379 
00380   PA.Revert();
00381 
00382   assert(TPR == TPResult::True || TPR == TPResult::False);
00383   return TPR == TPResult::True;
00384 }
00385 
00386   /// \brief Determine whether the next set of tokens contains a type-id.
00387   ///
00388   /// The context parameter states what context we're parsing right
00389   /// now, which affects how this routine copes with the token
00390   /// following the type-id. If the context is TypeIdInParens, we have
00391   /// already parsed the '(' and we will cease lookahead when we hit
00392   /// the corresponding ')'. If the context is
00393   /// TypeIdAsTemplateArgument, we've already parsed the '<' or ','
00394   /// before this template argument, and will cease lookahead when we
00395   /// hit a '>', '>>' (in C++0x), or ','. Returns true for a type-id
00396   /// and false for an expression.  If during the disambiguation
00397   /// process a parsing error is encountered, the function returns
00398   /// true to let the declaration parsing code handle it.
00399   ///
00400   /// type-id:
00401   ///   type-specifier-seq abstract-declarator[opt]
00402   ///
00403 bool Parser::isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous) {
00404 
00405   isAmbiguous = false;
00406 
00407   // C++ 8.2p2:
00408   // The ambiguity arising from the similarity between a function-style cast and
00409   // a type-id can occur in different contexts. The ambiguity appears as a
00410   // choice between a function-style cast expression and a declaration of a
00411   // type. The resolution is that any construct that could possibly be a type-id
00412   // in its syntactic context shall be considered a type-id.
00413 
00414   TPResult TPR = isCXXDeclarationSpecifier();
00415   if (TPR != TPResult::Ambiguous)
00416     return TPR != TPResult::False; // Returns true for TPResult::True or
00417                                      // TPResult::Error.
00418 
00419   // FIXME: Add statistics about the number of ambiguous statements encountered
00420   // and how they were resolved (number of declarations+number of expressions).
00421 
00422   // Ok, we have a simple-type-specifier/typename-specifier followed by a '('.
00423   // We need tentative parsing...
00424 
00425   TentativeParsingAction PA(*this);
00426 
00427   // type-specifier-seq
00428   TryConsumeDeclarationSpecifier();
00429   assert(Tok.is(tok::l_paren) && "Expected '('");
00430 
00431   // declarator
00432   TPR = TryParseDeclarator(true/*mayBeAbstract*/, false/*mayHaveIdentifier*/);
00433 
00434   // In case of an error, let the declaration parsing code handle it.
00435   if (TPR == TPResult::Error)
00436     TPR = TPResult::True;
00437 
00438   if (TPR == TPResult::Ambiguous) {
00439     // We are supposed to be inside parens, so if after the abstract declarator
00440     // we encounter a ')' this is a type-id, otherwise it's an expression.
00441     if (Context == TypeIdInParens && Tok.is(tok::r_paren)) {
00442       TPR = TPResult::True;
00443       isAmbiguous = true;
00444 
00445     // We are supposed to be inside a template argument, so if after
00446     // the abstract declarator we encounter a '>', '>>' (in C++0x), or
00447     // ',', this is a type-id. Otherwise, it's an expression.
00448     } else if (Context == TypeIdAsTemplateArgument &&
00449                (Tok.is(tok::greater) || Tok.is(tok::comma) ||
00450                 (getLangOpts().CPlusPlus11 && Tok.is(tok::greatergreater)))) {
00451       TPR = TPResult::True;
00452       isAmbiguous = true;
00453 
00454     } else
00455       TPR = TPResult::False;
00456   }
00457 
00458   PA.Revert();
00459 
00460   assert(TPR == TPResult::True || TPR == TPResult::False);
00461   return TPR == TPResult::True;
00462 }
00463 
00464 /// \brief Returns true if this is a C++11 attribute-specifier. Per
00465 /// C++11 [dcl.attr.grammar]p6, two consecutive left square bracket tokens
00466 /// always introduce an attribute. In Objective-C++11, this rule does not
00467 /// apply if either '[' begins a message-send.
00468 ///
00469 /// If Disambiguate is true, we try harder to determine whether a '[[' starts
00470 /// an attribute-specifier, and return CAK_InvalidAttributeSpecifier if not.
00471 ///
00472 /// If OuterMightBeMessageSend is true, we assume the outer '[' is either an
00473 /// Obj-C message send or the start of an attribute. Otherwise, we assume it
00474 /// is not an Obj-C message send.
00475 ///
00476 /// C++11 [dcl.attr.grammar]:
00477 ///
00478 ///     attribute-specifier:
00479 ///         '[' '[' attribute-list ']' ']'
00480 ///         alignment-specifier
00481 ///
00482 ///     attribute-list:
00483 ///         attribute[opt]
00484 ///         attribute-list ',' attribute[opt]
00485 ///         attribute '...'
00486 ///         attribute-list ',' attribute '...'
00487 ///
00488 ///     attribute:
00489 ///         attribute-token attribute-argument-clause[opt]
00490 ///
00491 ///     attribute-token:
00492 ///         identifier
00493 ///         identifier '::' identifier
00494 ///
00495 ///     attribute-argument-clause:
00496 ///         '(' balanced-token-seq ')'
00497 Parser::CXX11AttributeKind
00498 Parser::isCXX11AttributeSpecifier(bool Disambiguate,
00499                                   bool OuterMightBeMessageSend) {
00500   if (Tok.is(tok::kw_alignas))
00501     return CAK_AttributeSpecifier;
00502 
00503   if (Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square))
00504     return CAK_NotAttributeSpecifier;
00505 
00506   // No tentative parsing if we don't need to look for ']]' or a lambda.
00507   if (!Disambiguate && !getLangOpts().ObjC1)
00508     return CAK_AttributeSpecifier;
00509 
00510   TentativeParsingAction PA(*this);
00511 
00512   // Opening brackets were checked for above.
00513   ConsumeBracket();
00514 
00515   // Outside Obj-C++11, treat anything with a matching ']]' as an attribute.
00516   if (!getLangOpts().ObjC1) {
00517     ConsumeBracket();
00518 
00519     bool IsAttribute = SkipUntil(tok::r_square);
00520     IsAttribute &= Tok.is(tok::r_square);
00521 
00522     PA.Revert();
00523 
00524     return IsAttribute ? CAK_AttributeSpecifier : CAK_InvalidAttributeSpecifier;
00525   }
00526 
00527   // In Obj-C++11, we need to distinguish four situations:
00528   //  1a) int x[[attr]];                     C++11 attribute.
00529   //  1b) [[attr]];                          C++11 statement attribute.
00530   //   2) int x[[obj](){ return 1; }()];     Lambda in array size/index.
00531   //  3a) int x[[obj get]];                  Message send in array size/index.
00532   //  3b) [[Class alloc] init];              Message send in message send.
00533   //   4) [[obj]{ return self; }() doStuff]; Lambda in message send.
00534   // (1) is an attribute, (2) is ill-formed, and (3) and (4) are accepted.
00535 
00536   // If we have a lambda-introducer, then this is definitely not a message send.
00537   // FIXME: If this disambiguation is too slow, fold the tentative lambda parse
00538   // into the tentative attribute parse below.
00539   LambdaIntroducer Intro;
00540   if (!TryParseLambdaIntroducer(Intro)) {
00541     // A lambda cannot end with ']]', and an attribute must.
00542     bool IsAttribute = Tok.is(tok::r_square);
00543 
00544     PA.Revert();
00545 
00546     if (IsAttribute)
00547       // Case 1: C++11 attribute.
00548       return CAK_AttributeSpecifier;
00549 
00550     if (OuterMightBeMessageSend)
00551       // Case 4: Lambda in message send.
00552       return CAK_NotAttributeSpecifier;
00553 
00554     // Case 2: Lambda in array size / index.
00555     return CAK_InvalidAttributeSpecifier;
00556   }
00557 
00558   ConsumeBracket();
00559 
00560   // If we don't have a lambda-introducer, then we have an attribute or a
00561   // message-send.
00562   bool IsAttribute = true;
00563   while (Tok.isNot(tok::r_square)) {
00564     if (Tok.is(tok::comma)) {
00565       // Case 1: Stray commas can only occur in attributes.
00566       PA.Revert();
00567       return CAK_AttributeSpecifier;
00568     }
00569 
00570     // Parse the attribute-token, if present.
00571     // C++11 [dcl.attr.grammar]:
00572     //   If a keyword or an alternative token that satisfies the syntactic
00573     //   requirements of an identifier is contained in an attribute-token,
00574     //   it is considered an identifier.
00575     SourceLocation Loc;
00576     if (!TryParseCXX11AttributeIdentifier(Loc)) {
00577       IsAttribute = false;
00578       break;
00579     }
00580     if (Tok.is(tok::coloncolon)) {
00581       ConsumeToken();
00582       if (!TryParseCXX11AttributeIdentifier(Loc)) {
00583         IsAttribute = false;
00584         break;
00585       }
00586     }
00587 
00588     // Parse the attribute-argument-clause, if present.
00589     if (Tok.is(tok::l_paren)) {
00590       ConsumeParen();
00591       if (!SkipUntil(tok::r_paren)) {
00592         IsAttribute = false;
00593         break;
00594       }
00595     }
00596 
00597     TryConsumeToken(tok::ellipsis);
00598 
00599     if (!TryConsumeToken(tok::comma))
00600       break;
00601   }
00602 
00603   // An attribute must end ']]'.
00604   if (IsAttribute) {
00605     if (Tok.is(tok::r_square)) {
00606       ConsumeBracket();
00607       IsAttribute = Tok.is(tok::r_square);
00608     } else {
00609       IsAttribute = false;
00610     }
00611   }
00612 
00613   PA.Revert();
00614 
00615   if (IsAttribute)
00616     // Case 1: C++11 statement attribute.
00617     return CAK_AttributeSpecifier;
00618 
00619   // Case 3: Message send.
00620   return CAK_NotAttributeSpecifier;
00621 }
00622 
00623 Parser::TPResult Parser::TryParsePtrOperatorSeq() {
00624   while (true) {
00625     if (Tok.is(tok::coloncolon) || Tok.is(tok::identifier))
00626       if (TryAnnotateCXXScopeToken(true))
00627         return TPResult::Error;
00628 
00629     if (Tok.is(tok::star) || Tok.is(tok::amp) || Tok.is(tok::caret) ||
00630         Tok.is(tok::ampamp) ||
00631         (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::star))) {
00632       // ptr-operator
00633       ConsumeToken();
00634       while (Tok.is(tok::kw_const)    ||
00635              Tok.is(tok::kw_volatile) ||
00636              Tok.is(tok::kw_restrict))
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.is(tok::identifier) || Tok.is(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.is(tok::kw___attribute) ||
00835           Tok.is(tok::kw___declspec) ||
00836           Tok.is(tok::kw___cdecl) ||
00837           Tok.is(tok::kw___stdcall) ||
00838           Tok.is(tok::kw___fastcall) ||
00839           Tok.is(tok::kw___thiscall) ||
00840           Tok.is(tok::kw___unaligned))
00841         return TPResult::True; // attributes indicate declaration
00842       TPResult TPR = TryParseDeclarator(mayBeAbstract, mayHaveIdentifier);
00843       if (TPR != TPResult::Ambiguous)
00844         return TPR;
00845       if (Tok.isNot(tok::r_paren))
00846         return TPResult::False;
00847       ConsumeParen();
00848     }
00849   } else if (!mayBeAbstract) {
00850     return TPResult::False;
00851   }
00852 
00853   while (1) {
00854     TPResult TPR(TPResult::Ambiguous);
00855 
00856     // abstract-declarator: ...
00857     if (Tok.is(tok::ellipsis))
00858       ConsumeToken();
00859 
00860     if (Tok.is(tok::l_paren)) {
00861       // Check whether we have a function declarator or a possible ctor-style
00862       // initializer that follows the declarator. Note that ctor-style
00863       // initializers are not possible in contexts where abstract declarators
00864       // are allowed.
00865       if (!mayBeAbstract && !isCXXFunctionDeclarator())
00866         break;
00867 
00868       // direct-declarator '(' parameter-declaration-clause ')'
00869       //        cv-qualifier-seq[opt] exception-specification[opt]
00870       ConsumeParen();
00871       TPR = TryParseFunctionDeclarator();
00872     } else if (Tok.is(tok::l_square)) {
00873       // direct-declarator '[' constant-expression[opt] ']'
00874       // direct-abstract-declarator[opt] '[' constant-expression[opt] ']'
00875       TPR = TryParseBracketDeclarator();
00876     } else {
00877       break;
00878     }
00879 
00880     if (TPR != TPResult::Ambiguous)
00881       return TPR;
00882   }
00883 
00884   return TPResult::Ambiguous;
00885 }
00886 
00887 Parser::TPResult 
00888 Parser::isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind) {
00889   switch (Kind) {
00890   // Obviously starts an expression.
00891   case tok::numeric_constant:
00892   case tok::char_constant:
00893   case tok::wide_char_constant:
00894   case tok::utf16_char_constant:
00895   case tok::utf32_char_constant:
00896   case tok::string_literal:
00897   case tok::wide_string_literal:
00898   case tok::utf8_string_literal:
00899   case tok::utf16_string_literal:
00900   case tok::utf32_string_literal:
00901   case tok::l_square:
00902   case tok::l_paren:
00903   case tok::amp:
00904   case tok::ampamp:
00905   case tok::star:
00906   case tok::plus:
00907   case tok::plusplus:
00908   case tok::minus:
00909   case tok::minusminus:
00910   case tok::tilde:
00911   case tok::exclaim:
00912   case tok::kw_sizeof:
00913   case tok::kw___func__:
00914   case tok::kw_const_cast:
00915   case tok::kw_delete:
00916   case tok::kw_dynamic_cast:
00917   case tok::kw_false:
00918   case tok::kw_new:
00919   case tok::kw_operator:
00920   case tok::kw_reinterpret_cast:
00921   case tok::kw_static_cast:
00922   case tok::kw_this:
00923   case tok::kw_throw:
00924   case tok::kw_true:
00925   case tok::kw_typeid:
00926   case tok::kw_alignof:
00927   case tok::kw_noexcept:
00928   case tok::kw_nullptr:
00929   case tok::kw__Alignof:
00930   case tok::kw___null:
00931   case tok::kw___alignof:
00932   case tok::kw___builtin_choose_expr:
00933   case tok::kw___builtin_offsetof:
00934   case tok::kw___builtin_va_arg:
00935   case tok::kw___imag:
00936   case tok::kw___real:
00937   case tok::kw___FUNCTION__:
00938   case tok::kw___FUNCDNAME__:
00939   case tok::kw___FUNCSIG__:
00940   case tok::kw_L__FUNCTION__:
00941   case tok::kw___PRETTY_FUNCTION__:
00942   case tok::kw___uuidof:
00943 #define TYPE_TRAIT(N,Spelling,K) \
00944   case tok::kw_##Spelling:
00945 #include "clang/Basic/TokenKinds.def"
00946     return TPResult::True;
00947       
00948   // Obviously starts a type-specifier-seq:
00949   case tok::kw_char:
00950   case tok::kw_const:
00951   case tok::kw_double:
00952   case tok::kw_enum:
00953   case tok::kw_half:
00954   case tok::kw_float:
00955   case tok::kw_int:
00956   case tok::kw_long:
00957   case tok::kw___int64:
00958   case tok::kw___int128:
00959   case tok::kw_restrict:
00960   case tok::kw_short:
00961   case tok::kw_signed:
00962   case tok::kw_struct:
00963   case tok::kw_union:
00964   case tok::kw_unsigned:
00965   case tok::kw_void:
00966   case tok::kw_volatile:
00967   case tok::kw__Bool:
00968   case tok::kw__Complex:
00969   case tok::kw_class:
00970   case tok::kw_typename:
00971   case tok::kw_wchar_t:
00972   case tok::kw_char16_t:
00973   case tok::kw_char32_t:
00974   case tok::kw__Decimal32:
00975   case tok::kw__Decimal64:
00976   case tok::kw__Decimal128:
00977   case tok::kw___interface:
00978   case tok::kw___thread:
00979   case tok::kw_thread_local:
00980   case tok::kw__Thread_local:
00981   case tok::kw_typeof:
00982   case tok::kw___underlying_type:
00983   case tok::kw___cdecl:
00984   case tok::kw___stdcall:
00985   case tok::kw___fastcall:
00986   case tok::kw___thiscall:
00987   case tok::kw___unaligned:
00988   case tok::kw___vector:
00989   case tok::kw___pixel:
00990   case tok::kw__Atomic:
00991   case tok::kw___unknown_anytype:
00992     return TPResult::False;
00993 
00994   default:
00995     break;
00996   }
00997   
00998   return TPResult::Ambiguous;
00999 }
01000 
01001 bool Parser::isTentativelyDeclared(IdentifierInfo *II) {
01002   return std::find(TentativelyDeclaredIdentifiers.begin(),
01003                    TentativelyDeclaredIdentifiers.end(), II)
01004       != TentativelyDeclaredIdentifiers.end();
01005 }
01006 
01007 /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a declaration
01008 /// specifier, TPResult::False if it is not, TPResult::Ambiguous if it could
01009 /// be either a decl-specifier or a function-style cast, and TPResult::Error
01010 /// if a parsing error was found and reported.
01011 ///
01012 /// If HasMissingTypename is provided, a name with a dependent scope specifier
01013 /// will be treated as ambiguous if the 'typename' keyword is missing. If this
01014 /// happens, *HasMissingTypename will be set to 'true'. This will also be used
01015 /// as an indicator that undeclared identifiers (which will trigger a later
01016 /// parse error) should be treated as types. Returns TPResult::Ambiguous in
01017 /// such cases.
01018 ///
01019 ///         decl-specifier:
01020 ///           storage-class-specifier
01021 ///           type-specifier
01022 ///           function-specifier
01023 ///           'friend'
01024 ///           'typedef'
01025 /// [C++11]   'constexpr'
01026 /// [GNU]     attributes declaration-specifiers[opt]
01027 ///
01028 ///         storage-class-specifier:
01029 ///           'register'
01030 ///           'static'
01031 ///           'extern'
01032 ///           'mutable'
01033 ///           'auto'
01034 /// [GNU]     '__thread'
01035 /// [C++11]   'thread_local'
01036 /// [C11]     '_Thread_local'
01037 ///
01038 ///         function-specifier:
01039 ///           'inline'
01040 ///           'virtual'
01041 ///           'explicit'
01042 ///
01043 ///         typedef-name:
01044 ///           identifier
01045 ///
01046 ///         type-specifier:
01047 ///           simple-type-specifier
01048 ///           class-specifier
01049 ///           enum-specifier
01050 ///           elaborated-type-specifier
01051 ///           typename-specifier
01052 ///           cv-qualifier
01053 ///
01054 ///         simple-type-specifier:
01055 ///           '::'[opt] nested-name-specifier[opt] type-name
01056 ///           '::'[opt] nested-name-specifier 'template'
01057 ///                 simple-template-id                              [TODO]
01058 ///           'char'
01059 ///           'wchar_t'
01060 ///           'bool'
01061 ///           'short'
01062 ///           'int'
01063 ///           'long'
01064 ///           'signed'
01065 ///           'unsigned'
01066 ///           'float'
01067 ///           'double'
01068 ///           'void'
01069 /// [GNU]     typeof-specifier
01070 /// [GNU]     '_Complex'
01071 /// [C++11]   'auto'
01072 /// [C++11]   'decltype' ( expression )
01073 /// [C++1y]   'decltype' ( 'auto' )
01074 ///
01075 ///         type-name:
01076 ///           class-name
01077 ///           enum-name
01078 ///           typedef-name
01079 ///
01080 ///         elaborated-type-specifier:
01081 ///           class-key '::'[opt] nested-name-specifier[opt] identifier
01082 ///           class-key '::'[opt] nested-name-specifier[opt] 'template'[opt]
01083 ///               simple-template-id
01084 ///           'enum' '::'[opt] nested-name-specifier[opt] identifier
01085 ///
01086 ///         enum-name:
01087 ///           identifier
01088 ///
01089 ///         enum-specifier:
01090 ///           'enum' identifier[opt] '{' enumerator-list[opt] '}'
01091 ///           'enum' identifier[opt] '{' enumerator-list ',' '}'
01092 ///
01093 ///         class-specifier:
01094 ///           class-head '{' member-specification[opt] '}'
01095 ///
01096 ///         class-head:
01097 ///           class-key identifier[opt] base-clause[opt]
01098 ///           class-key nested-name-specifier identifier base-clause[opt]
01099 ///           class-key nested-name-specifier[opt] simple-template-id
01100 ///               base-clause[opt]
01101 ///
01102 ///         class-key:
01103 ///           'class'
01104 ///           'struct'
01105 ///           'union'
01106 ///
01107 ///         cv-qualifier:
01108 ///           'const'
01109 ///           'volatile'
01110 /// [GNU]     restrict
01111 ///
01112 Parser::TPResult
01113 Parser::isCXXDeclarationSpecifier(Parser::TPResult BracedCastResult,
01114                                   bool *HasMissingTypename) {
01115   switch (Tok.getKind()) {
01116   case tok::identifier: {
01117     // Check for need to substitute AltiVec __vector keyword
01118     // for "vector" identifier.
01119     if (TryAltiVecVectorToken())
01120       return TPResult::True;
01121 
01122     const Token &Next = NextToken();
01123     // In 'foo bar', 'foo' is always a type name outside of Objective-C.
01124     if (!getLangOpts().ObjC1 && Next.is(tok::identifier))
01125       return TPResult::True;
01126 
01127     if (Next.isNot(tok::coloncolon) && Next.isNot(tok::less)) {
01128       // Determine whether this is a valid expression. If not, we will hit
01129       // a parse error one way or another. In that case, tell the caller that
01130       // this is ambiguous. Typo-correct to type and expression keywords and
01131       // to types and identifiers, in order to try to recover from errors.
01132       CorrectionCandidateCallback TypoCorrection;
01133       TypoCorrection.WantRemainingKeywords = false;
01134       TypoCorrection.WantTypeSpecifiers =
01135           Next.is(tok::l_paren) || Next.is(tok::r_paren) ||
01136           Next.is(tok::greater) || Next.is(tok::l_brace) ||
01137           Next.is(tok::identifier);
01138       switch (TryAnnotateName(false /* no nested name specifier */,
01139                               &TypoCorrection)) {
01140       case ANK_Error:
01141         return TPResult::Error;
01142       case ANK_TentativeDecl:
01143         return TPResult::False;
01144       case ANK_TemplateName:
01145         // A bare type template-name which can't be a template template
01146         // argument is an error, and was probably intended to be a type.
01147         return GreaterThanIsOperator ? TPResult::True : TPResult::False;
01148       case ANK_Unresolved:
01149         return HasMissingTypename ? TPResult::Ambiguous : TPResult::False;
01150       case ANK_Success:
01151         break;
01152       }
01153       assert(Tok.isNot(tok::identifier) &&
01154              "TryAnnotateName succeeded without producing an annotation");
01155     } else {
01156       // This might possibly be a type with a dependent scope specifier and
01157       // a missing 'typename' keyword. Don't use TryAnnotateName in this case,
01158       // since it will annotate as a primary expression, and we want to use the
01159       // "missing 'typename'" logic.
01160       if (TryAnnotateTypeOrScopeToken())
01161         return TPResult::Error;
01162       // If annotation failed, assume it's a non-type.
01163       // FIXME: If this happens due to an undeclared identifier, treat it as
01164       // ambiguous.
01165       if (Tok.is(tok::identifier))
01166         return TPResult::False;
01167     }
01168 
01169     // We annotated this token as something. Recurse to handle whatever we got.
01170     return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
01171   }
01172 
01173   case tok::kw_typename:  // typename T::type
01174     // Annotate typenames and C++ scope specifiers.  If we get one, just
01175     // recurse to handle whatever we get.
01176     if (TryAnnotateTypeOrScopeToken())
01177       return TPResult::Error;
01178     return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
01179 
01180   case tok::coloncolon: {    // ::foo::bar
01181     const Token &Next = NextToken();
01182     if (Next.is(tok::kw_new) ||    // ::new
01183         Next.is(tok::kw_delete))   // ::delete
01184       return TPResult::False;
01185   }
01186     // Fall through.
01187   case tok::kw___super:
01188   case tok::kw_decltype:
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     // decl-specifier:
01196     //   storage-class-specifier
01197     //   type-specifier
01198     //   function-specifier
01199     //   'friend'
01200     //   'typedef'
01201     //   'constexpr'
01202   case tok::kw_friend:
01203   case tok::kw_typedef:
01204   case tok::kw_constexpr:
01205     // storage-class-specifier
01206   case tok::kw_register:
01207   case tok::kw_static:
01208   case tok::kw_extern:
01209   case tok::kw_mutable:
01210   case tok::kw_auto:
01211   case tok::kw___thread:
01212   case tok::kw_thread_local:
01213   case tok::kw__Thread_local:
01214     // function-specifier
01215   case tok::kw_inline:
01216   case tok::kw_virtual:
01217   case tok::kw_explicit:
01218 
01219     // Modules
01220   case tok::kw___module_private__:
01221 
01222     // Debugger support
01223   case tok::kw___unknown_anytype:
01224       
01225     // type-specifier:
01226     //   simple-type-specifier
01227     //   class-specifier
01228     //   enum-specifier
01229     //   elaborated-type-specifier
01230     //   typename-specifier
01231     //   cv-qualifier
01232 
01233     // class-specifier
01234     // elaborated-type-specifier
01235   case tok::kw_class:
01236   case tok::kw_struct:
01237   case tok::kw_union:
01238   case tok::kw___interface:
01239     // enum-specifier
01240   case tok::kw_enum:
01241     // cv-qualifier
01242   case tok::kw_const:
01243   case tok::kw_volatile:
01244 
01245     // GNU
01246   case tok::kw_restrict:
01247   case tok::kw__Complex:
01248   case tok::kw___attribute:
01249     return TPResult::True;
01250 
01251     // Microsoft
01252   case tok::kw___declspec:
01253   case tok::kw___cdecl:
01254   case tok::kw___stdcall:
01255   case tok::kw___fastcall:
01256   case tok::kw___thiscall:
01257   case tok::kw___w64:
01258   case tok::kw___sptr:
01259   case tok::kw___uptr:
01260   case tok::kw___ptr64:
01261   case tok::kw___ptr32:
01262   case tok::kw___forceinline:
01263   case tok::kw___unaligned:
01264     return TPResult::True;
01265 
01266     // Borland
01267   case tok::kw___pascal:
01268     return TPResult::True;
01269   
01270     // AltiVec
01271   case tok::kw___vector:
01272     return TPResult::True;
01273 
01274   case tok::annot_template_id: {
01275     TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
01276     if (TemplateId->Kind != TNK_Type_template)
01277       return TPResult::False;
01278     CXXScopeSpec SS;
01279     AnnotateTemplateIdTokenAsType();
01280     assert(Tok.is(tok::annot_typename));
01281     goto case_typename;
01282   }
01283 
01284   case tok::annot_cxxscope: // foo::bar or ::foo::bar, but already parsed
01285     // We've already annotated a scope; try to annotate a type.
01286     if (TryAnnotateTypeOrScopeToken())
01287       return TPResult::Error;
01288     if (!Tok.is(tok::annot_typename)) {
01289       // If the next token is an identifier or a type qualifier, then this
01290       // can't possibly be a valid expression either.
01291       if (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier)) {
01292         CXXScopeSpec SS;
01293         Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
01294                                                      Tok.getAnnotationRange(),
01295                                                      SS);
01296         if (SS.getScopeRep() && SS.getScopeRep()->isDependent()) {
01297           TentativeParsingAction PA(*this);
01298           ConsumeToken();
01299           ConsumeToken();
01300           bool isIdentifier = Tok.is(tok::identifier);
01301           TPResult TPR = TPResult::False;
01302           if (!isIdentifier)
01303             TPR = isCXXDeclarationSpecifier(BracedCastResult,
01304                                             HasMissingTypename);
01305           PA.Revert();
01306 
01307           if (isIdentifier ||
01308               TPR == TPResult::True || TPR == TPResult::Error)
01309             return TPResult::Error;
01310 
01311           if (HasMissingTypename) {
01312             // We can't tell whether this is a missing 'typename' or a valid
01313             // expression.
01314             *HasMissingTypename = true;
01315             return TPResult::Ambiguous;
01316           }
01317         } else {
01318           // Try to resolve the name. If it doesn't exist, assume it was
01319           // intended to name a type and keep disambiguating.
01320           switch (TryAnnotateName(false /* SS is not dependent */)) {
01321           case ANK_Error:
01322             return TPResult::Error;
01323           case ANK_TentativeDecl:
01324             return TPResult::False;
01325           case ANK_TemplateName:
01326             // A bare type template-name which can't be a template template
01327             // argument is an error, and was probably intended to be a type.
01328             return GreaterThanIsOperator ? TPResult::True : TPResult::False;
01329           case ANK_Unresolved:
01330             return HasMissingTypename ? TPResult::Ambiguous
01331                                       : TPResult::False;
01332           case ANK_Success:
01333             // Annotated it, check again.
01334             assert(Tok.isNot(tok::annot_cxxscope) ||
01335                    NextToken().isNot(tok::identifier));
01336             return isCXXDeclarationSpecifier(BracedCastResult,
01337                                              HasMissingTypename);
01338           }
01339         }
01340       }
01341       return TPResult::False;
01342     }
01343     // If that succeeded, fallthrough into the generic simple-type-id case.
01344 
01345     // The ambiguity resides in a simple-type-specifier/typename-specifier
01346     // followed by a '('. The '(' could either be the start of:
01347     //
01348     //   direct-declarator:
01349     //     '(' declarator ')'
01350     //
01351     //   direct-abstract-declarator:
01352     //     '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
01353     //              exception-specification[opt]
01354     //     '(' abstract-declarator ')'
01355     //
01356     // or part of a function-style cast expression:
01357     //
01358     //     simple-type-specifier '(' expression-list[opt] ')'
01359     //
01360 
01361     // simple-type-specifier:
01362 
01363   case tok::annot_typename:
01364   case_typename:
01365     // In Objective-C, we might have a protocol-qualified type.
01366     if (getLangOpts().ObjC1 && NextToken().is(tok::less)) {
01367       // Tentatively parse the 
01368       TentativeParsingAction PA(*this);
01369       ConsumeToken(); // The type token
01370       
01371       TPResult TPR = TryParseProtocolQualifiers();
01372       bool isFollowedByParen = Tok.is(tok::l_paren);
01373       bool isFollowedByBrace = Tok.is(tok::l_brace);
01374       
01375       PA.Revert();
01376       
01377       if (TPR == TPResult::Error)
01378         return TPResult::Error;
01379       
01380       if (isFollowedByParen)
01381         return TPResult::Ambiguous;
01382 
01383       if (getLangOpts().CPlusPlus11 && isFollowedByBrace)
01384         return BracedCastResult;
01385       
01386       return TPResult::True;
01387     }
01388       
01389   case tok::kw_char:
01390   case tok::kw_wchar_t:
01391   case tok::kw_char16_t:
01392   case tok::kw_char32_t:
01393   case tok::kw_bool:
01394   case tok::kw_short:
01395   case tok::kw_int:
01396   case tok::kw_long:
01397   case tok::kw___int64:
01398   case tok::kw___int128:
01399   case tok::kw_signed:
01400   case tok::kw_unsigned:
01401   case tok::kw_half:
01402   case tok::kw_float:
01403   case tok::kw_double:
01404   case tok::kw_void:
01405   case tok::annot_decltype:
01406     if (NextToken().is(tok::l_paren))
01407       return TPResult::Ambiguous;
01408 
01409     // This is a function-style cast in all cases we disambiguate other than
01410     // one:
01411     //   struct S {
01412     //     enum E : int { a = 4 }; // enum
01413     //     enum E : int { 4 };     // bit-field
01414     //   };
01415     if (getLangOpts().CPlusPlus11 && NextToken().is(tok::l_brace))
01416       return BracedCastResult;
01417 
01418     if (isStartOfObjCClassMessageMissingOpenBracket())
01419       return TPResult::False;
01420       
01421     return TPResult::True;
01422 
01423   // GNU typeof support.
01424   case tok::kw_typeof: {
01425     if (NextToken().isNot(tok::l_paren))
01426       return TPResult::True;
01427 
01428     TentativeParsingAction PA(*this);
01429 
01430     TPResult TPR = TryParseTypeofSpecifier();
01431     bool isFollowedByParen = Tok.is(tok::l_paren);
01432     bool isFollowedByBrace = Tok.is(tok::l_brace);
01433 
01434     PA.Revert();
01435 
01436     if (TPR == TPResult::Error)
01437       return TPResult::Error;
01438 
01439     if (isFollowedByParen)
01440       return TPResult::Ambiguous;
01441 
01442     if (getLangOpts().CPlusPlus11 && isFollowedByBrace)
01443       return BracedCastResult;
01444 
01445     return TPResult::True;
01446   }
01447 
01448   // C++0x type traits support
01449   case tok::kw___underlying_type:
01450     return TPResult::True;
01451 
01452   // C11 _Atomic
01453   case tok::kw__Atomic:
01454     return TPResult::True;
01455 
01456   default:
01457     return TPResult::False;
01458   }
01459 }
01460 
01461 bool Parser::isCXXDeclarationSpecifierAType() {
01462   switch (Tok.getKind()) {
01463     // typename-specifier
01464   case tok::annot_decltype:
01465   case tok::annot_template_id:
01466   case tok::annot_typename:
01467   case tok::kw_typeof:
01468   case tok::kw___underlying_type:
01469     return true;
01470 
01471     // elaborated-type-specifier
01472   case tok::kw_class:
01473   case tok::kw_struct:
01474   case tok::kw_union:
01475   case tok::kw___interface:
01476   case tok::kw_enum:
01477     return true;
01478 
01479     // simple-type-specifier
01480   case tok::kw_char:
01481   case tok::kw_wchar_t:
01482   case tok::kw_char16_t:
01483   case tok::kw_char32_t:
01484   case tok::kw_bool:
01485   case tok::kw_short:
01486   case tok::kw_int:
01487   case tok::kw_long:
01488   case tok::kw___int64:
01489   case tok::kw___int128:
01490   case tok::kw_signed:
01491   case tok::kw_unsigned:
01492   case tok::kw_half:
01493   case tok::kw_float:
01494   case tok::kw_double:
01495   case tok::kw_void:
01496   case tok::kw___unknown_anytype:
01497     return true;
01498 
01499   case tok::kw_auto:
01500     return getLangOpts().CPlusPlus11;
01501 
01502   case tok::kw__Atomic:
01503     // "_Atomic foo"
01504     return NextToken().is(tok::l_paren);
01505 
01506   default:
01507     return false;
01508   }
01509 }
01510 
01511 /// [GNU] typeof-specifier:
01512 ///         'typeof' '(' expressions ')'
01513 ///         'typeof' '(' type-name ')'
01514 ///
01515 Parser::TPResult Parser::TryParseTypeofSpecifier() {
01516   assert(Tok.is(tok::kw_typeof) && "Expected 'typeof'!");
01517   ConsumeToken();
01518 
01519   assert(Tok.is(tok::l_paren) && "Expected '('");
01520   // Parse through the parens after 'typeof'.
01521   ConsumeParen();
01522   if (!SkipUntil(tok::r_paren, StopAtSemi))
01523     return TPResult::Error;
01524 
01525   return TPResult::Ambiguous;
01526 }
01527 
01528 /// [ObjC] protocol-qualifiers:
01529 ////         '<' identifier-list '>'
01530 Parser::TPResult Parser::TryParseProtocolQualifiers() {
01531   assert(Tok.is(tok::less) && "Expected '<' for qualifier list");
01532   ConsumeToken();
01533   do {
01534     if (Tok.isNot(tok::identifier))
01535       return TPResult::Error;
01536     ConsumeToken();
01537     
01538     if (Tok.is(tok::comma)) {
01539       ConsumeToken();
01540       continue;
01541     }
01542     
01543     if (Tok.is(tok::greater)) {
01544       ConsumeToken();
01545       return TPResult::Ambiguous;
01546     }
01547   } while (false);
01548   
01549   return TPResult::Error;
01550 }
01551 
01552 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
01553 /// a constructor-style initializer, when parsing declaration statements.
01554 /// Returns true for function declarator and false for constructor-style
01555 /// initializer.
01556 /// If during the disambiguation process a parsing error is encountered,
01557 /// the function returns true to let the declaration parsing code handle it.
01558 ///
01559 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
01560 ///         exception-specification[opt]
01561 ///
01562 bool Parser::isCXXFunctionDeclarator(bool *IsAmbiguous) {
01563 
01564   // C++ 8.2p1:
01565   // The ambiguity arising from the similarity between a function-style cast and
01566   // a declaration mentioned in 6.8 can also occur in the context of a
01567   // declaration. In that context, the choice is between a function declaration
01568   // with a redundant set of parentheses around a parameter name and an object
01569   // declaration with a function-style cast as the initializer. Just as for the
01570   // ambiguities mentioned in 6.8, the resolution is to consider any construct
01571   // that could possibly be a declaration a declaration.
01572 
01573   TentativeParsingAction PA(*this);
01574 
01575   ConsumeParen();
01576   bool InvalidAsDeclaration = false;
01577   TPResult TPR = TryParseParameterDeclarationClause(&InvalidAsDeclaration);
01578   if (TPR == TPResult::Ambiguous) {
01579     if (Tok.isNot(tok::r_paren))
01580       TPR = TPResult::False;
01581     else {
01582       const Token &Next = NextToken();
01583       if (Next.is(tok::amp) || Next.is(tok::ampamp) ||
01584           Next.is(tok::kw_const) || Next.is(tok::kw_volatile) ||
01585           Next.is(tok::kw_throw) || Next.is(tok::kw_noexcept) ||
01586           Next.is(tok::l_square) || isCXX11VirtSpecifier(Next) ||
01587           Next.is(tok::l_brace) || Next.is(tok::kw_try) ||
01588           Next.is(tok::equal) || Next.is(tok::arrow))
01589         // The next token cannot appear after a constructor-style initializer,
01590         // and can appear next in a function definition. This must be a function
01591         // declarator.
01592         TPR = TPResult::True;
01593       else if (InvalidAsDeclaration)
01594         // Use the absence of 'typename' as a tie-breaker.
01595         TPR = TPResult::False;
01596     }
01597   }
01598 
01599   PA.Revert();
01600 
01601   if (IsAmbiguous && TPR == TPResult::Ambiguous)
01602     *IsAmbiguous = true;
01603 
01604   // In case of an error, let the declaration parsing code handle it.
01605   return TPR != TPResult::False;
01606 }
01607 
01608 /// parameter-declaration-clause:
01609 ///   parameter-declaration-list[opt] '...'[opt]
01610 ///   parameter-declaration-list ',' '...'
01611 ///
01612 /// parameter-declaration-list:
01613 ///   parameter-declaration
01614 ///   parameter-declaration-list ',' parameter-declaration
01615 ///
01616 /// parameter-declaration:
01617 ///   attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
01618 ///   attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
01619 ///     '=' assignment-expression
01620 ///   attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
01621 ///     attributes[opt]
01622 ///   attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
01623 ///     attributes[opt] '=' assignment-expression
01624 ///
01625 Parser::TPResult
01626 Parser::TryParseParameterDeclarationClause(bool *InvalidAsDeclaration,
01627                                            bool VersusTemplateArgument) {
01628 
01629   if (Tok.is(tok::r_paren))
01630     return TPResult::Ambiguous;
01631 
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   while (1) {
01640     // '...'[opt]
01641     if (Tok.is(tok::ellipsis)) {
01642       ConsumeToken();
01643       if (Tok.is(tok::r_paren))
01644         return TPResult::True; // '...)' is a sign of a function declarator.
01645       else
01646         return TPResult::False;
01647     }
01648 
01649     // An attribute-specifier-seq here is a sign of a function declarator.
01650     if (isCXX11AttributeSpecifier(/*Disambiguate*/false,
01651                                   /*OuterMightBeMessageSend*/true))
01652       return TPResult::True;
01653 
01654     ParsedAttributes attrs(AttrFactory);
01655     MaybeParseMicrosoftAttributes(attrs);
01656 
01657     // decl-specifier-seq
01658     // A parameter-declaration's initializer must be preceded by an '=', so
01659     // decl-specifier-seq '{' is not a parameter in C++11.
01660     TPResult TPR = isCXXDeclarationSpecifier(TPResult::False,
01661                                              InvalidAsDeclaration);
01662 
01663     if (VersusTemplateArgument && TPR == TPResult::True) {
01664       // Consume the decl-specifier-seq. We have to look past it, since a
01665       // type-id might appear here in a template argument.
01666       bool SeenType = false;
01667       do {
01668         SeenType |= isCXXDeclarationSpecifierAType();
01669         if (TryConsumeDeclarationSpecifier() == TPResult::Error)
01670           return TPResult::Error;
01671 
01672         // If we see a parameter name, this can't be a template argument.
01673         if (SeenType && Tok.is(tok::identifier))
01674           return TPResult::True;
01675 
01676         TPR = isCXXDeclarationSpecifier(TPResult::False,
01677                                         InvalidAsDeclaration);
01678         if (TPR == TPResult::Error)
01679           return TPR;
01680       } while (TPR != TPResult::False);
01681     } else if (TPR == TPResult::Ambiguous) {
01682       // Disambiguate what follows the decl-specifier.
01683       if (TryConsumeDeclarationSpecifier() == TPResult::Error)
01684         return TPResult::Error;
01685     } else
01686       return TPR;
01687 
01688     // declarator
01689     // abstract-declarator[opt]
01690     TPR = TryParseDeclarator(true/*mayBeAbstract*/);
01691     if (TPR != TPResult::Ambiguous)
01692       return TPR;
01693 
01694     // [GNU] attributes[opt]
01695     if (Tok.is(tok::kw___attribute))
01696       return TPResult::True;
01697 
01698     // If we're disambiguating a template argument in a default argument in
01699     // a class definition versus a parameter declaration, an '=' here
01700     // disambiguates the parse one way or the other.
01701     // If this is a parameter, it must have a default argument because
01702     //   (a) the previous parameter did, and
01703     //   (b) this must be the first declaration of the function, so we can't
01704     //       inherit any default arguments from elsewhere.
01705     // If we see an ')', then we've reached the end of a
01706     // parameter-declaration-clause, and the last param is missing its default
01707     // argument.
01708     if (VersusTemplateArgument)
01709       return (Tok.is(tok::equal) || Tok.is(tok::r_paren)) ? TPResult::True
01710                                                           : TPResult::False;
01711 
01712     if (Tok.is(tok::equal)) {
01713       // '=' assignment-expression
01714       // Parse through assignment-expression.
01715       // FIXME: assignment-expression may contain an unparenthesized comma.
01716       if (!SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch))
01717         return TPResult::Error;
01718     }
01719 
01720     if (Tok.is(tok::ellipsis)) {
01721       ConsumeToken();
01722       if (Tok.is(tok::r_paren))
01723         return TPResult::True; // '...)' is a sign of a function declarator.
01724       else
01725         return TPResult::False;
01726     }
01727 
01728     if (!TryConsumeToken(tok::comma))
01729       break;
01730   }
01731 
01732   return TPResult::Ambiguous;
01733 }
01734 
01735 /// TryParseFunctionDeclarator - We parsed a '(' and we want to try to continue
01736 /// parsing as a function declarator.
01737 /// If TryParseFunctionDeclarator fully parsed the function declarator, it will
01738 /// return TPResult::Ambiguous, otherwise it will return either False() or
01739 /// Error().
01740 ///
01741 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
01742 ///         exception-specification[opt]
01743 ///
01744 /// exception-specification:
01745 ///   'throw' '(' type-id-list[opt] ')'
01746 ///
01747 Parser::TPResult Parser::TryParseFunctionDeclarator() {
01748 
01749   // The '(' is already parsed.
01750 
01751   TPResult TPR = TryParseParameterDeclarationClause();
01752   if (TPR == TPResult::Ambiguous && Tok.isNot(tok::r_paren))
01753     TPR = TPResult::False;
01754 
01755   if (TPR == TPResult::False || TPR == TPResult::Error)
01756     return TPR;
01757 
01758   // Parse through the parens.
01759   if (!SkipUntil(tok::r_paren, StopAtSemi))
01760     return TPResult::Error;
01761 
01762   // cv-qualifier-seq
01763   while (Tok.is(tok::kw_const)    ||
01764          Tok.is(tok::kw_volatile) ||
01765          Tok.is(tok::kw_restrict)   )
01766     ConsumeToken();
01767 
01768   // ref-qualifier[opt]
01769   if (Tok.is(tok::amp) || Tok.is(tok::ampamp))
01770     ConsumeToken();
01771   
01772   // exception-specification
01773   if (Tok.is(tok::kw_throw)) {
01774     ConsumeToken();
01775     if (Tok.isNot(tok::l_paren))
01776       return TPResult::Error;
01777 
01778     // Parse through the parens after 'throw'.
01779     ConsumeParen();
01780     if (!SkipUntil(tok::r_paren, StopAtSemi))
01781       return TPResult::Error;
01782   }
01783   if (Tok.is(tok::kw_noexcept)) {
01784     ConsumeToken();
01785     // Possibly an expression as well.
01786     if (Tok.is(tok::l_paren)) {
01787       // Find the matching rparen.
01788       ConsumeParen();
01789       if (!SkipUntil(tok::r_paren, StopAtSemi))
01790         return TPResult::Error;
01791     }
01792   }
01793 
01794   return TPResult::Ambiguous;
01795 }
01796 
01797 /// '[' constant-expression[opt] ']'
01798 ///
01799 Parser::TPResult Parser::TryParseBracketDeclarator() {
01800   ConsumeBracket();
01801   if (!SkipUntil(tok::r_square, StopAtSemi))
01802     return TPResult::Error;
01803 
01804   return TPResult::Ambiguous;
01805 }