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 = Next.isNot(tok::arrow);
01135       switch (TryAnnotateName(false /* no nested name specifier */,
01136                               &TypoCorrection)) {
01137       case ANK_Error:
01138         return TPResult::Error;
01139       case ANK_TentativeDecl:
01140         return TPResult::False;
01141       case ANK_TemplateName:
01142         // A bare type template-name which can't be a template template
01143         // argument is an error, and was probably intended to be a type.
01144         return GreaterThanIsOperator ? TPResult::True : TPResult::False;
01145       case ANK_Unresolved:
01146         return HasMissingTypename ? TPResult::Ambiguous : TPResult::False;
01147       case ANK_Success:
01148         break;
01149       }
01150       assert(Tok.isNot(tok::identifier) &&
01151              "TryAnnotateName succeeded without producing an annotation");
01152     } else {
01153       // This might possibly be a type with a dependent scope specifier and
01154       // a missing 'typename' keyword. Don't use TryAnnotateName in this case,
01155       // since it will annotate as a primary expression, and we want to use the
01156       // "missing 'typename'" logic.
01157       if (TryAnnotateTypeOrScopeToken())
01158         return TPResult::Error;
01159       // If annotation failed, assume it's a non-type.
01160       // FIXME: If this happens due to an undeclared identifier, treat it as
01161       // ambiguous.
01162       if (Tok.is(tok::identifier))
01163         return TPResult::False;
01164     }
01165 
01166     // We annotated this token as something. Recurse to handle whatever we got.
01167     return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
01168   }
01169 
01170   case tok::kw_typename:  // typename T::type
01171     // Annotate typenames and C++ scope specifiers.  If we get one, just
01172     // recurse to handle whatever we get.
01173     if (TryAnnotateTypeOrScopeToken())
01174       return TPResult::Error;
01175     return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
01176 
01177   case tok::coloncolon: {    // ::foo::bar
01178     const Token &Next = NextToken();
01179     if (Next.is(tok::kw_new) ||    // ::new
01180         Next.is(tok::kw_delete))   // ::delete
01181       return TPResult::False;
01182   }
01183     // Fall through.
01184   case tok::kw_decltype:
01185     // Annotate typenames and C++ scope specifiers.  If we get one, just
01186     // recurse to handle whatever we get.
01187     if (TryAnnotateTypeOrScopeToken())
01188       return TPResult::Error;
01189     return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename);
01190 
01191     // decl-specifier:
01192     //   storage-class-specifier
01193     //   type-specifier
01194     //   function-specifier
01195     //   'friend'
01196     //   'typedef'
01197     //   'constexpr'
01198   case tok::kw_friend:
01199   case tok::kw_typedef:
01200   case tok::kw_constexpr:
01201     // storage-class-specifier
01202   case tok::kw_register:
01203   case tok::kw_static:
01204   case tok::kw_extern:
01205   case tok::kw_mutable:
01206   case tok::kw_auto:
01207   case tok::kw___thread:
01208   case tok::kw_thread_local:
01209   case tok::kw__Thread_local:
01210     // function-specifier
01211   case tok::kw_inline:
01212   case tok::kw_virtual:
01213   case tok::kw_explicit:
01214 
01215     // Modules
01216   case tok::kw___module_private__:
01217 
01218     // Debugger support
01219   case tok::kw___unknown_anytype:
01220       
01221     // type-specifier:
01222     //   simple-type-specifier
01223     //   class-specifier
01224     //   enum-specifier
01225     //   elaborated-type-specifier
01226     //   typename-specifier
01227     //   cv-qualifier
01228 
01229     // class-specifier
01230     // elaborated-type-specifier
01231   case tok::kw_class:
01232   case tok::kw_struct:
01233   case tok::kw_union:
01234   case tok::kw___interface:
01235     // enum-specifier
01236   case tok::kw_enum:
01237     // cv-qualifier
01238   case tok::kw_const:
01239   case tok::kw_volatile:
01240 
01241     // GNU
01242   case tok::kw_restrict:
01243   case tok::kw__Complex:
01244   case tok::kw___attribute:
01245     return TPResult::True;
01246 
01247     // Microsoft
01248   case tok::kw___declspec:
01249   case tok::kw___cdecl:
01250   case tok::kw___stdcall:
01251   case tok::kw___fastcall:
01252   case tok::kw___thiscall:
01253   case tok::kw___w64:
01254   case tok::kw___sptr:
01255   case tok::kw___uptr:
01256   case tok::kw___ptr64:
01257   case tok::kw___ptr32:
01258   case tok::kw___forceinline:
01259   case tok::kw___unaligned:
01260     return TPResult::True;
01261 
01262     // Borland
01263   case tok::kw___pascal:
01264     return TPResult::True;
01265   
01266     // AltiVec
01267   case tok::kw___vector:
01268     return TPResult::True;
01269 
01270   case tok::annot_template_id: {
01271     TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
01272     if (TemplateId->Kind != TNK_Type_template)
01273       return TPResult::False;
01274     CXXScopeSpec SS;
01275     AnnotateTemplateIdTokenAsType();
01276     assert(Tok.is(tok::annot_typename));
01277     goto case_typename;
01278   }
01279 
01280   case tok::annot_cxxscope: // foo::bar or ::foo::bar, but already parsed
01281     // We've already annotated a scope; try to annotate a type.
01282     if (TryAnnotateTypeOrScopeToken())
01283       return TPResult::Error;
01284     if (!Tok.is(tok::annot_typename)) {
01285       // If the next token is an identifier or a type qualifier, then this
01286       // can't possibly be a valid expression either.
01287       if (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier)) {
01288         CXXScopeSpec SS;
01289         Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
01290                                                      Tok.getAnnotationRange(),
01291                                                      SS);
01292         if (SS.getScopeRep() && SS.getScopeRep()->isDependent()) {
01293           TentativeParsingAction PA(*this);
01294           ConsumeToken();
01295           ConsumeToken();
01296           bool isIdentifier = Tok.is(tok::identifier);
01297           TPResult TPR = TPResult::False;
01298           if (!isIdentifier)
01299             TPR = isCXXDeclarationSpecifier(BracedCastResult,
01300                                             HasMissingTypename);
01301           PA.Revert();
01302 
01303           if (isIdentifier ||
01304               TPR == TPResult::True || TPR == TPResult::Error)
01305             return TPResult::Error;
01306 
01307           if (HasMissingTypename) {
01308             // We can't tell whether this is a missing 'typename' or a valid
01309             // expression.
01310             *HasMissingTypename = true;
01311             return TPResult::Ambiguous;
01312           }
01313         } else {
01314           // Try to resolve the name. If it doesn't exist, assume it was
01315           // intended to name a type and keep disambiguating.
01316           switch (TryAnnotateName(false /* SS is not dependent */)) {
01317           case ANK_Error:
01318             return TPResult::Error;
01319           case ANK_TentativeDecl:
01320             return TPResult::False;
01321           case ANK_TemplateName:
01322             // A bare type template-name which can't be a template template
01323             // argument is an error, and was probably intended to be a type.
01324             return GreaterThanIsOperator ? TPResult::True : TPResult::False;
01325           case ANK_Unresolved:
01326             return HasMissingTypename ? TPResult::Ambiguous
01327                                       : TPResult::False;
01328           case ANK_Success:
01329             // Annotated it, check again.
01330             assert(Tok.isNot(tok::annot_cxxscope) ||
01331                    NextToken().isNot(tok::identifier));
01332             return isCXXDeclarationSpecifier(BracedCastResult,
01333                                              HasMissingTypename);
01334           }
01335         }
01336       }
01337       return TPResult::False;
01338     }
01339     // If that succeeded, fallthrough into the generic simple-type-id case.
01340 
01341     // The ambiguity resides in a simple-type-specifier/typename-specifier
01342     // followed by a '('. The '(' could either be the start of:
01343     //
01344     //   direct-declarator:
01345     //     '(' declarator ')'
01346     //
01347     //   direct-abstract-declarator:
01348     //     '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
01349     //              exception-specification[opt]
01350     //     '(' abstract-declarator ')'
01351     //
01352     // or part of a function-style cast expression:
01353     //
01354     //     simple-type-specifier '(' expression-list[opt] ')'
01355     //
01356 
01357     // simple-type-specifier:
01358 
01359   case tok::annot_typename:
01360   case_typename:
01361     // In Objective-C, we might have a protocol-qualified type.
01362     if (getLangOpts().ObjC1 && NextToken().is(tok::less)) {
01363       // Tentatively parse the 
01364       TentativeParsingAction PA(*this);
01365       ConsumeToken(); // The type token
01366       
01367       TPResult TPR = TryParseProtocolQualifiers();
01368       bool isFollowedByParen = Tok.is(tok::l_paren);
01369       bool isFollowedByBrace = Tok.is(tok::l_brace);
01370       
01371       PA.Revert();
01372       
01373       if (TPR == TPResult::Error)
01374         return TPResult::Error;
01375       
01376       if (isFollowedByParen)
01377         return TPResult::Ambiguous;
01378 
01379       if (getLangOpts().CPlusPlus11 && isFollowedByBrace)
01380         return BracedCastResult;
01381       
01382       return TPResult::True;
01383     }
01384       
01385   case tok::kw_char:
01386   case tok::kw_wchar_t:
01387   case tok::kw_char16_t:
01388   case tok::kw_char32_t:
01389   case tok::kw_bool:
01390   case tok::kw_short:
01391   case tok::kw_int:
01392   case tok::kw_long:
01393   case tok::kw___int64:
01394   case tok::kw___int128:
01395   case tok::kw_signed:
01396   case tok::kw_unsigned:
01397   case tok::kw_half:
01398   case tok::kw_float:
01399   case tok::kw_double:
01400   case tok::kw_void:
01401   case tok::annot_decltype:
01402     if (NextToken().is(tok::l_paren))
01403       return TPResult::Ambiguous;
01404 
01405     // This is a function-style cast in all cases we disambiguate other than
01406     // one:
01407     //   struct S {
01408     //     enum E : int { a = 4 }; // enum
01409     //     enum E : int { 4 };     // bit-field
01410     //   };
01411     if (getLangOpts().CPlusPlus11 && NextToken().is(tok::l_brace))
01412       return BracedCastResult;
01413 
01414     if (isStartOfObjCClassMessageMissingOpenBracket())
01415       return TPResult::False;
01416       
01417     return TPResult::True;
01418 
01419   // GNU typeof support.
01420   case tok::kw_typeof: {
01421     if (NextToken().isNot(tok::l_paren))
01422       return TPResult::True;
01423 
01424     TentativeParsingAction PA(*this);
01425 
01426     TPResult TPR = TryParseTypeofSpecifier();
01427     bool isFollowedByParen = Tok.is(tok::l_paren);
01428     bool isFollowedByBrace = Tok.is(tok::l_brace);
01429 
01430     PA.Revert();
01431 
01432     if (TPR == TPResult::Error)
01433       return TPResult::Error;
01434 
01435     if (isFollowedByParen)
01436       return TPResult::Ambiguous;
01437 
01438     if (getLangOpts().CPlusPlus11 && isFollowedByBrace)
01439       return BracedCastResult;
01440 
01441     return TPResult::True;
01442   }
01443 
01444   // C++0x type traits support
01445   case tok::kw___underlying_type:
01446     return TPResult::True;
01447 
01448   // C11 _Atomic
01449   case tok::kw__Atomic:
01450     return TPResult::True;
01451 
01452   default:
01453     return TPResult::False;
01454   }
01455 }
01456 
01457 bool Parser::isCXXDeclarationSpecifierAType() {
01458   switch (Tok.getKind()) {
01459     // typename-specifier
01460   case tok::annot_decltype:
01461   case tok::annot_template_id:
01462   case tok::annot_typename:
01463   case tok::kw_typeof:
01464   case tok::kw___underlying_type:
01465     return true;
01466 
01467     // elaborated-type-specifier
01468   case tok::kw_class:
01469   case tok::kw_struct:
01470   case tok::kw_union:
01471   case tok::kw___interface:
01472   case tok::kw_enum:
01473     return true;
01474 
01475     // simple-type-specifier
01476   case tok::kw_char:
01477   case tok::kw_wchar_t:
01478   case tok::kw_char16_t:
01479   case tok::kw_char32_t:
01480   case tok::kw_bool:
01481   case tok::kw_short:
01482   case tok::kw_int:
01483   case tok::kw_long:
01484   case tok::kw___int64:
01485   case tok::kw___int128:
01486   case tok::kw_signed:
01487   case tok::kw_unsigned:
01488   case tok::kw_half:
01489   case tok::kw_float:
01490   case tok::kw_double:
01491   case tok::kw_void:
01492   case tok::kw___unknown_anytype:
01493     return true;
01494 
01495   case tok::kw_auto:
01496     return getLangOpts().CPlusPlus11;
01497 
01498   case tok::kw__Atomic:
01499     // "_Atomic foo"
01500     return NextToken().is(tok::l_paren);
01501 
01502   default:
01503     return false;
01504   }
01505 }
01506 
01507 /// [GNU] typeof-specifier:
01508 ///         'typeof' '(' expressions ')'
01509 ///         'typeof' '(' type-name ')'
01510 ///
01511 Parser::TPResult Parser::TryParseTypeofSpecifier() {
01512   assert(Tok.is(tok::kw_typeof) && "Expected 'typeof'!");
01513   ConsumeToken();
01514 
01515   assert(Tok.is(tok::l_paren) && "Expected '('");
01516   // Parse through the parens after 'typeof'.
01517   ConsumeParen();
01518   if (!SkipUntil(tok::r_paren, StopAtSemi))
01519     return TPResult::Error;
01520 
01521   return TPResult::Ambiguous;
01522 }
01523 
01524 /// [ObjC] protocol-qualifiers:
01525 ////         '<' identifier-list '>'
01526 Parser::TPResult Parser::TryParseProtocolQualifiers() {
01527   assert(Tok.is(tok::less) && "Expected '<' for qualifier list");
01528   ConsumeToken();
01529   do {
01530     if (Tok.isNot(tok::identifier))
01531       return TPResult::Error;
01532     ConsumeToken();
01533     
01534     if (Tok.is(tok::comma)) {
01535       ConsumeToken();
01536       continue;
01537     }
01538     
01539     if (Tok.is(tok::greater)) {
01540       ConsumeToken();
01541       return TPResult::Ambiguous;
01542     }
01543   } while (false);
01544   
01545   return TPResult::Error;
01546 }
01547 
01548 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
01549 /// a constructor-style initializer, when parsing declaration statements.
01550 /// Returns true for function declarator and false for constructor-style
01551 /// initializer.
01552 /// If during the disambiguation process a parsing error is encountered,
01553 /// the function returns true to let the declaration parsing code handle it.
01554 ///
01555 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
01556 ///         exception-specification[opt]
01557 ///
01558 bool Parser::isCXXFunctionDeclarator(bool *IsAmbiguous) {
01559 
01560   // C++ 8.2p1:
01561   // The ambiguity arising from the similarity between a function-style cast and
01562   // a declaration mentioned in 6.8 can also occur in the context of a
01563   // declaration. In that context, the choice is between a function declaration
01564   // with a redundant set of parentheses around a parameter name and an object
01565   // declaration with a function-style cast as the initializer. Just as for the
01566   // ambiguities mentioned in 6.8, the resolution is to consider any construct
01567   // that could possibly be a declaration a declaration.
01568 
01569   TentativeParsingAction PA(*this);
01570 
01571   ConsumeParen();
01572   bool InvalidAsDeclaration = false;
01573   TPResult TPR = TryParseParameterDeclarationClause(&InvalidAsDeclaration);
01574   if (TPR == TPResult::Ambiguous) {
01575     if (Tok.isNot(tok::r_paren))
01576       TPR = TPResult::False;
01577     else {
01578       const Token &Next = NextToken();
01579       if (Next.is(tok::amp) || Next.is(tok::ampamp) ||
01580           Next.is(tok::kw_const) || Next.is(tok::kw_volatile) ||
01581           Next.is(tok::kw_throw) || Next.is(tok::kw_noexcept) ||
01582           Next.is(tok::l_square) || isCXX11VirtSpecifier(Next) ||
01583           Next.is(tok::l_brace) || Next.is(tok::kw_try) ||
01584           Next.is(tok::equal) || Next.is(tok::arrow))
01585         // The next token cannot appear after a constructor-style initializer,
01586         // and can appear next in a function definition. This must be a function
01587         // declarator.
01588         TPR = TPResult::True;
01589       else if (InvalidAsDeclaration)
01590         // Use the absence of 'typename' as a tie-breaker.
01591         TPR = TPResult::False;
01592     }
01593   }
01594 
01595   PA.Revert();
01596 
01597   if (IsAmbiguous && TPR == TPResult::Ambiguous)
01598     *IsAmbiguous = true;
01599 
01600   // In case of an error, let the declaration parsing code handle it.
01601   return TPR != TPResult::False;
01602 }
01603 
01604 /// parameter-declaration-clause:
01605 ///   parameter-declaration-list[opt] '...'[opt]
01606 ///   parameter-declaration-list ',' '...'
01607 ///
01608 /// parameter-declaration-list:
01609 ///   parameter-declaration
01610 ///   parameter-declaration-list ',' parameter-declaration
01611 ///
01612 /// parameter-declaration:
01613 ///   attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
01614 ///   attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt]
01615 ///     '=' assignment-expression
01616 ///   attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
01617 ///     attributes[opt]
01618 ///   attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt]
01619 ///     attributes[opt] '=' assignment-expression
01620 ///
01621 Parser::TPResult
01622 Parser::TryParseParameterDeclarationClause(bool *InvalidAsDeclaration,
01623                                            bool VersusTemplateArgument) {
01624 
01625   if (Tok.is(tok::r_paren))
01626     return TPResult::Ambiguous;
01627 
01628   //   parameter-declaration-list[opt] '...'[opt]
01629   //   parameter-declaration-list ',' '...'
01630   //
01631   // parameter-declaration-list:
01632   //   parameter-declaration
01633   //   parameter-declaration-list ',' parameter-declaration
01634   //
01635   while (1) {
01636     // '...'[opt]
01637     if (Tok.is(tok::ellipsis)) {
01638       ConsumeToken();
01639       if (Tok.is(tok::r_paren))
01640         return TPResult::True; // '...)' is a sign of a function declarator.
01641       else
01642         return TPResult::False;
01643     }
01644 
01645     // An attribute-specifier-seq here is a sign of a function declarator.
01646     if (isCXX11AttributeSpecifier(/*Disambiguate*/false,
01647                                   /*OuterMightBeMessageSend*/true))
01648       return TPResult::True;
01649 
01650     ParsedAttributes attrs(AttrFactory);
01651     MaybeParseMicrosoftAttributes(attrs);
01652 
01653     // decl-specifier-seq
01654     // A parameter-declaration's initializer must be preceded by an '=', so
01655     // decl-specifier-seq '{' is not a parameter in C++11.
01656     TPResult TPR = isCXXDeclarationSpecifier(TPResult::False,
01657                                              InvalidAsDeclaration);
01658 
01659     if (VersusTemplateArgument && TPR == TPResult::True) {
01660       // Consume the decl-specifier-seq. We have to look past it, since a
01661       // type-id might appear here in a template argument.
01662       bool SeenType = false;
01663       do {
01664         SeenType |= isCXXDeclarationSpecifierAType();
01665         if (TryConsumeDeclarationSpecifier() == TPResult::Error)
01666           return TPResult::Error;
01667 
01668         // If we see a parameter name, this can't be a template argument.
01669         if (SeenType && Tok.is(tok::identifier))
01670           return TPResult::True;
01671 
01672         TPR = isCXXDeclarationSpecifier(TPResult::False,
01673                                         InvalidAsDeclaration);
01674         if (TPR == TPResult::Error)
01675           return TPR;
01676       } while (TPR != TPResult::False);
01677     } else if (TPR == TPResult::Ambiguous) {
01678       // Disambiguate what follows the decl-specifier.
01679       if (TryConsumeDeclarationSpecifier() == TPResult::Error)
01680         return TPResult::Error;
01681     } else
01682       return TPR;
01683 
01684     // declarator
01685     // abstract-declarator[opt]
01686     TPR = TryParseDeclarator(true/*mayBeAbstract*/);
01687     if (TPR != TPResult::Ambiguous)
01688       return TPR;
01689 
01690     // [GNU] attributes[opt]
01691     if (Tok.is(tok::kw___attribute))
01692       return TPResult::True;
01693 
01694     // If we're disambiguating a template argument in a default argument in
01695     // a class definition versus a parameter declaration, an '=' here
01696     // disambiguates the parse one way or the other.
01697     // If this is a parameter, it must have a default argument because
01698     //   (a) the previous parameter did, and
01699     //   (b) this must be the first declaration of the function, so we can't
01700     //       inherit any default arguments from elsewhere.
01701     // If we see an ')', then we've reached the end of a
01702     // parameter-declaration-clause, and the last param is missing its default
01703     // argument.
01704     if (VersusTemplateArgument)
01705       return (Tok.is(tok::equal) || Tok.is(tok::r_paren)) ? TPResult::True
01706                                                           : TPResult::False;
01707 
01708     if (Tok.is(tok::equal)) {
01709       // '=' assignment-expression
01710       // Parse through assignment-expression.
01711       // FIXME: assignment-expression may contain an unparenthesized comma.
01712       if (!SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch))
01713         return TPResult::Error;
01714     }
01715 
01716     if (Tok.is(tok::ellipsis)) {
01717       ConsumeToken();
01718       if (Tok.is(tok::r_paren))
01719         return TPResult::True; // '...)' is a sign of a function declarator.
01720       else
01721         return TPResult::False;
01722     }
01723 
01724     if (!TryConsumeToken(tok::comma))
01725       break;
01726   }
01727 
01728   return TPResult::Ambiguous;
01729 }
01730 
01731 /// TryParseFunctionDeclarator - We parsed a '(' and we want to try to continue
01732 /// parsing as a function declarator.
01733 /// If TryParseFunctionDeclarator fully parsed the function declarator, it will
01734 /// return TPResult::Ambiguous, otherwise it will return either False() or
01735 /// Error().
01736 ///
01737 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
01738 ///         exception-specification[opt]
01739 ///
01740 /// exception-specification:
01741 ///   'throw' '(' type-id-list[opt] ')'
01742 ///
01743 Parser::TPResult Parser::TryParseFunctionDeclarator() {
01744 
01745   // The '(' is already parsed.
01746 
01747   TPResult TPR = TryParseParameterDeclarationClause();
01748   if (TPR == TPResult::Ambiguous && Tok.isNot(tok::r_paren))
01749     TPR = TPResult::False;
01750 
01751   if (TPR == TPResult::False || TPR == TPResult::Error)
01752     return TPR;
01753 
01754   // Parse through the parens.
01755   if (!SkipUntil(tok::r_paren, StopAtSemi))
01756     return TPResult::Error;
01757 
01758   // cv-qualifier-seq
01759   while (Tok.is(tok::kw_const)    ||
01760          Tok.is(tok::kw_volatile) ||
01761          Tok.is(tok::kw_restrict)   )
01762     ConsumeToken();
01763 
01764   // ref-qualifier[opt]
01765   if (Tok.is(tok::amp) || Tok.is(tok::ampamp))
01766     ConsumeToken();
01767   
01768   // exception-specification
01769   if (Tok.is(tok::kw_throw)) {
01770     ConsumeToken();
01771     if (Tok.isNot(tok::l_paren))
01772       return TPResult::Error;
01773 
01774     // Parse through the parens after 'throw'.
01775     ConsumeParen();
01776     if (!SkipUntil(tok::r_paren, StopAtSemi))
01777       return TPResult::Error;
01778   }
01779   if (Tok.is(tok::kw_noexcept)) {
01780     ConsumeToken();
01781     // Possibly an expression as well.
01782     if (Tok.is(tok::l_paren)) {
01783       // Find the matching rparen.
01784       ConsumeParen();
01785       if (!SkipUntil(tok::r_paren, StopAtSemi))
01786         return TPResult::Error;
01787     }
01788   }
01789 
01790   return TPResult::Ambiguous;
01791 }
01792 
01793 /// '[' constant-expression[opt] ']'
01794 ///
01795 Parser::TPResult Parser::TryParseBracketDeclarator() {
01796   ConsumeBracket();
01797   if (!SkipUntil(tok::r_square, StopAtSemi))
01798     return TPResult::Error;
01799 
01800   return TPResult::Ambiguous;
01801 }