clang API Documentation

Parse/Parser.cpp
Go to the documentation of this file.
00001 //===--- Parser.cpp - C Language Family Parser ----------------------------===//
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 Parser interfaces.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "clang/Parse/Parser.h"
00015 #include "RAIIObjectsForParser.h"
00016 #include "clang/AST/ASTConsumer.h"
00017 #include "clang/AST/ASTContext.h"
00018 #include "clang/AST/DeclTemplate.h"
00019 #include "clang/Parse/ParseDiagnostic.h"
00020 #include "clang/Sema/DeclSpec.h"
00021 #include "clang/Sema/ParsedTemplate.h"
00022 #include "clang/Sema/Scope.h"
00023 #include "llvm/Support/raw_ostream.h"
00024 using namespace clang;
00025 
00026 
00027 namespace {
00028 /// \brief A comment handler that passes comments found by the preprocessor
00029 /// to the parser action.
00030 class ActionCommentHandler : public CommentHandler {
00031   Sema &S;
00032 
00033 public:
00034   explicit ActionCommentHandler(Sema &S) : S(S) { }
00035 
00036   bool HandleComment(Preprocessor &PP, SourceRange Comment) override {
00037     S.ActOnComment(Comment);
00038     return false;
00039   }
00040 };
00041 } // end anonymous namespace
00042 
00043 IdentifierInfo *Parser::getSEHExceptKeyword() {
00044   // __except is accepted as a (contextual) keyword 
00045   if (!Ident__except && (getLangOpts().MicrosoftExt || getLangOpts().Borland))
00046     Ident__except = PP.getIdentifierInfo("__except");
00047 
00048   return Ident__except;
00049 }
00050 
00051 Parser::Parser(Preprocessor &pp, Sema &actions, bool skipFunctionBodies)
00052   : PP(pp), Actions(actions), Diags(PP.getDiagnostics()),
00053     GreaterThanIsOperator(true), ColonIsSacred(false), 
00054     InMessageExpression(false), TemplateParameterDepth(0),
00055     ParsingInObjCContainer(false) {
00056   SkipFunctionBodies = pp.isCodeCompletionEnabled() || skipFunctionBodies;
00057   Tok.startToken();
00058   Tok.setKind(tok::eof);
00059   Actions.CurScope = nullptr;
00060   NumCachedScopes = 0;
00061   ParenCount = BracketCount = BraceCount = 0;
00062   CurParsedObjCImpl = nullptr;
00063 
00064   // Add #pragma handlers. These are removed and destroyed in the
00065   // destructor.
00066   initializePragmaHandlers();
00067 
00068   CommentSemaHandler.reset(new ActionCommentHandler(actions));
00069   PP.addCommentHandler(CommentSemaHandler.get());
00070 
00071   PP.setCodeCompletionHandler(*this);
00072 }
00073 
00074 DiagnosticBuilder Parser::Diag(SourceLocation Loc, unsigned DiagID) {
00075   return Diags.Report(Loc, DiagID);
00076 }
00077 
00078 DiagnosticBuilder Parser::Diag(const Token &Tok, unsigned DiagID) {
00079   return Diag(Tok.getLocation(), DiagID);
00080 }
00081 
00082 /// \brief Emits a diagnostic suggesting parentheses surrounding a
00083 /// given range.
00084 ///
00085 /// \param Loc The location where we'll emit the diagnostic.
00086 /// \param DK The kind of diagnostic to emit.
00087 /// \param ParenRange Source range enclosing code that should be parenthesized.
00088 void Parser::SuggestParentheses(SourceLocation Loc, unsigned DK,
00089                                 SourceRange ParenRange) {
00090   SourceLocation EndLoc = PP.getLocForEndOfToken(ParenRange.getEnd());
00091   if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
00092     // We can't display the parentheses, so just dig the
00093     // warning/error and return.
00094     Diag(Loc, DK);
00095     return;
00096   }
00097 
00098   Diag(Loc, DK)
00099     << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
00100     << FixItHint::CreateInsertion(EndLoc, ")");
00101 }
00102 
00103 static bool IsCommonTypo(tok::TokenKind ExpectedTok, const Token &Tok) {
00104   switch (ExpectedTok) {
00105   case tok::semi:
00106     return Tok.is(tok::colon) || Tok.is(tok::comma); // : or , for ;
00107   default: return false;
00108   }
00109 }
00110 
00111 bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID,
00112                               StringRef Msg) {
00113   if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) {
00114     ConsumeAnyToken();
00115     return false;
00116   }
00117 
00118   // Detect common single-character typos and resume.
00119   if (IsCommonTypo(ExpectedTok, Tok)) {
00120     SourceLocation Loc = Tok.getLocation();
00121     {
00122       DiagnosticBuilder DB = Diag(Loc, DiagID);
00123       DB << FixItHint::CreateReplacement(
00124                 SourceRange(Loc), tok::getPunctuatorSpelling(ExpectedTok));
00125       if (DiagID == diag::err_expected)
00126         DB << ExpectedTok;
00127       else if (DiagID == diag::err_expected_after)
00128         DB << Msg << ExpectedTok;
00129       else
00130         DB << Msg;
00131     }
00132 
00133     // Pretend there wasn't a problem.
00134     ConsumeAnyToken();
00135     return false;
00136   }
00137 
00138   SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
00139   const char *Spelling = nullptr;
00140   if (EndLoc.isValid())
00141     Spelling = tok::getPunctuatorSpelling(ExpectedTok);
00142 
00143   DiagnosticBuilder DB =
00144       Spelling
00145           ? Diag(EndLoc, DiagID) << FixItHint::CreateInsertion(EndLoc, Spelling)
00146           : Diag(Tok, DiagID);
00147   if (DiagID == diag::err_expected)
00148     DB << ExpectedTok;
00149   else if (DiagID == diag::err_expected_after)
00150     DB << Msg << ExpectedTok;
00151   else
00152     DB << Msg;
00153 
00154   return true;
00155 }
00156 
00157 bool Parser::ExpectAndConsumeSemi(unsigned DiagID) {
00158   if (TryConsumeToken(tok::semi))
00159     return false;
00160 
00161   if (Tok.is(tok::code_completion)) {
00162     handleUnexpectedCodeCompletionToken();
00163     return false;
00164   }
00165   
00166   if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) && 
00167       NextToken().is(tok::semi)) {
00168     Diag(Tok, diag::err_extraneous_token_before_semi)
00169       << PP.getSpelling(Tok)
00170       << FixItHint::CreateRemoval(Tok.getLocation());
00171     ConsumeAnyToken(); // The ')' or ']'.
00172     ConsumeToken(); // The ';'.
00173     return false;
00174   }
00175   
00176   return ExpectAndConsume(tok::semi, DiagID);
00177 }
00178 
00179 void Parser::ConsumeExtraSemi(ExtraSemiKind Kind, unsigned TST) {
00180   if (!Tok.is(tok::semi)) return;
00181 
00182   bool HadMultipleSemis = false;
00183   SourceLocation StartLoc = Tok.getLocation();
00184   SourceLocation EndLoc = Tok.getLocation();
00185   ConsumeToken();
00186 
00187   while ((Tok.is(tok::semi) && !Tok.isAtStartOfLine())) {
00188     HadMultipleSemis = true;
00189     EndLoc = Tok.getLocation();
00190     ConsumeToken();
00191   }
00192 
00193   // C++11 allows extra semicolons at namespace scope, but not in any of the
00194   // other contexts.
00195   if (Kind == OutsideFunction && getLangOpts().CPlusPlus) {
00196     if (getLangOpts().CPlusPlus11)
00197       Diag(StartLoc, diag::warn_cxx98_compat_top_level_semi)
00198           << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
00199     else
00200       Diag(StartLoc, diag::ext_extra_semi_cxx11)
00201           << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
00202     return;
00203   }
00204 
00205   if (Kind != AfterMemberFunctionDefinition || HadMultipleSemis)
00206     Diag(StartLoc, diag::ext_extra_semi)
00207         << Kind << DeclSpec::getSpecifierName((DeclSpec::TST)TST,
00208                                     Actions.getASTContext().getPrintingPolicy())
00209         << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
00210   else
00211     // A single semicolon is valid after a member function definition.
00212     Diag(StartLoc, diag::warn_extra_semi_after_mem_fn_def)
00213       << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
00214 }
00215 
00216 //===----------------------------------------------------------------------===//
00217 // Error recovery.
00218 //===----------------------------------------------------------------------===//
00219 
00220 static bool HasFlagsSet(Parser::SkipUntilFlags L, Parser::SkipUntilFlags R) {
00221   return (static_cast<unsigned>(L) & static_cast<unsigned>(R)) != 0;
00222 }
00223 
00224 /// SkipUntil - Read tokens until we get to the specified token, then consume
00225 /// it (unless no flag StopBeforeMatch).  Because we cannot guarantee that the
00226 /// token will ever occur, this skips to the next token, or to some likely
00227 /// good stopping point.  If StopAtSemi is true, skipping will stop at a ';'
00228 /// character.
00229 ///
00230 /// If SkipUntil finds the specified token, it returns true, otherwise it
00231 /// returns false.
00232 bool Parser::SkipUntil(ArrayRef<tok::TokenKind> Toks, SkipUntilFlags Flags) {
00233   // We always want this function to skip at least one token if the first token
00234   // isn't T and if not at EOF.
00235   bool isFirstTokenSkipped = true;
00236   while (1) {
00237     // If we found one of the tokens, stop and return true.
00238     for (unsigned i = 0, NumToks = Toks.size(); i != NumToks; ++i) {
00239       if (Tok.is(Toks[i])) {
00240         if (HasFlagsSet(Flags, StopBeforeMatch)) {
00241           // Noop, don't consume the token.
00242         } else {
00243           ConsumeAnyToken();
00244         }
00245         return true;
00246       }
00247     }
00248 
00249     // Important special case: The caller has given up and just wants us to
00250     // skip the rest of the file. Do this without recursing, since we can
00251     // get here precisely because the caller detected too much recursion.
00252     if (Toks.size() == 1 && Toks[0] == tok::eof &&
00253         !HasFlagsSet(Flags, StopAtSemi) &&
00254         !HasFlagsSet(Flags, StopAtCodeCompletion)) {
00255       while (Tok.isNot(tok::eof))
00256         ConsumeAnyToken();
00257       return true;
00258     }
00259 
00260     switch (Tok.getKind()) {
00261     case tok::eof:
00262       // Ran out of tokens.
00263       return false;
00264 
00265     case tok::annot_pragma_openmp_end:
00266       // Stop before an OpenMP pragma boundary.
00267     case tok::annot_module_begin:
00268     case tok::annot_module_end:
00269     case tok::annot_module_include:
00270       // Stop before we change submodules. They generally indicate a "good"
00271       // place to pick up parsing again (except in the special case where
00272       // we're trying to skip to EOF).
00273       return false;
00274 
00275     case tok::code_completion:
00276       if (!HasFlagsSet(Flags, StopAtCodeCompletion))
00277         handleUnexpectedCodeCompletionToken();
00278       return false;
00279         
00280     case tok::l_paren:
00281       // Recursively skip properly-nested parens.
00282       ConsumeParen();
00283       if (HasFlagsSet(Flags, StopAtCodeCompletion))
00284         SkipUntil(tok::r_paren, StopAtCodeCompletion);
00285       else
00286         SkipUntil(tok::r_paren);
00287       break;
00288     case tok::l_square:
00289       // Recursively skip properly-nested square brackets.
00290       ConsumeBracket();
00291       if (HasFlagsSet(Flags, StopAtCodeCompletion))
00292         SkipUntil(tok::r_square, StopAtCodeCompletion);
00293       else
00294         SkipUntil(tok::r_square);
00295       break;
00296     case tok::l_brace:
00297       // Recursively skip properly-nested braces.
00298       ConsumeBrace();
00299       if (HasFlagsSet(Flags, StopAtCodeCompletion))
00300         SkipUntil(tok::r_brace, StopAtCodeCompletion);
00301       else
00302         SkipUntil(tok::r_brace);
00303       break;
00304 
00305     // Okay, we found a ']' or '}' or ')', which we think should be balanced.
00306     // Since the user wasn't looking for this token (if they were, it would
00307     // already be handled), this isn't balanced.  If there is a LHS token at a
00308     // higher level, we will assume that this matches the unbalanced token
00309     // and return it.  Otherwise, this is a spurious RHS token, which we skip.
00310     case tok::r_paren:
00311       if (ParenCount && !isFirstTokenSkipped)
00312         return false;  // Matches something.
00313       ConsumeParen();
00314       break;
00315     case tok::r_square:
00316       if (BracketCount && !isFirstTokenSkipped)
00317         return false;  // Matches something.
00318       ConsumeBracket();
00319       break;
00320     case tok::r_brace:
00321       if (BraceCount && !isFirstTokenSkipped)
00322         return false;  // Matches something.
00323       ConsumeBrace();
00324       break;
00325 
00326     case tok::string_literal:
00327     case tok::wide_string_literal:
00328     case tok::utf8_string_literal:
00329     case tok::utf16_string_literal:
00330     case tok::utf32_string_literal:
00331       ConsumeStringToken();
00332       break;
00333         
00334     case tok::semi:
00335       if (HasFlagsSet(Flags, StopAtSemi))
00336         return false;
00337       // FALL THROUGH.
00338     default:
00339       // Skip this token.
00340       ConsumeToken();
00341       break;
00342     }
00343     isFirstTokenSkipped = false;
00344   }
00345 }
00346 
00347 //===----------------------------------------------------------------------===//
00348 // Scope manipulation
00349 //===----------------------------------------------------------------------===//
00350 
00351 /// EnterScope - Start a new scope.
00352 void Parser::EnterScope(unsigned ScopeFlags) {
00353   if (NumCachedScopes) {
00354     Scope *N = ScopeCache[--NumCachedScopes];
00355     N->Init(getCurScope(), ScopeFlags);
00356     Actions.CurScope = N;
00357   } else {
00358     Actions.CurScope = new Scope(getCurScope(), ScopeFlags, Diags);
00359   }
00360 }
00361 
00362 /// ExitScope - Pop a scope off the scope stack.
00363 void Parser::ExitScope() {
00364   assert(getCurScope() && "Scope imbalance!");
00365 
00366   // Inform the actions module that this scope is going away if there are any
00367   // decls in it.
00368   Actions.ActOnPopScope(Tok.getLocation(), getCurScope());
00369 
00370   Scope *OldScope = getCurScope();
00371   Actions.CurScope = OldScope->getParent();
00372 
00373   if (NumCachedScopes == ScopeCacheSize)
00374     delete OldScope;
00375   else
00376     ScopeCache[NumCachedScopes++] = OldScope;
00377 }
00378 
00379 /// Set the flags for the current scope to ScopeFlags. If ManageFlags is false,
00380 /// this object does nothing.
00381 Parser::ParseScopeFlags::ParseScopeFlags(Parser *Self, unsigned ScopeFlags,
00382                                  bool ManageFlags)
00383   : CurScope(ManageFlags ? Self->getCurScope() : nullptr) {
00384   if (CurScope) {
00385     OldFlags = CurScope->getFlags();
00386     CurScope->setFlags(ScopeFlags);
00387   }
00388 }
00389 
00390 /// Restore the flags for the current scope to what they were before this
00391 /// object overrode them.
00392 Parser::ParseScopeFlags::~ParseScopeFlags() {
00393   if (CurScope)
00394     CurScope->setFlags(OldFlags);
00395 }
00396 
00397 
00398 //===----------------------------------------------------------------------===//
00399 // C99 6.9: External Definitions.
00400 //===----------------------------------------------------------------------===//
00401 
00402 Parser::~Parser() {
00403   // If we still have scopes active, delete the scope tree.
00404   delete getCurScope();
00405   Actions.CurScope = nullptr;
00406 
00407   // Free the scope cache.
00408   for (unsigned i = 0, e = NumCachedScopes; i != e; ++i)
00409     delete ScopeCache[i];
00410 
00411   resetPragmaHandlers();
00412 
00413   PP.removeCommentHandler(CommentSemaHandler.get());
00414 
00415   PP.clearCodeCompletionHandler();
00416 
00417   assert(TemplateIds.empty() && "Still alive TemplateIdAnnotations around?");
00418 }
00419 
00420 /// Initialize - Warm up the parser.
00421 ///
00422 void Parser::Initialize() {
00423   // Create the translation unit scope.  Install it as the current scope.
00424   assert(getCurScope() == nullptr && "A scope is already active?");
00425   EnterScope(Scope::DeclScope);
00426   Actions.ActOnTranslationUnitScope(getCurScope());
00427 
00428   // Initialization for Objective-C context sensitive keywords recognition.
00429   // Referenced in Parser::ParseObjCTypeQualifierList.
00430   if (getLangOpts().ObjC1) {
00431     ObjCTypeQuals[objc_in] = &PP.getIdentifierTable().get("in");
00432     ObjCTypeQuals[objc_out] = &PP.getIdentifierTable().get("out");
00433     ObjCTypeQuals[objc_inout] = &PP.getIdentifierTable().get("inout");
00434     ObjCTypeQuals[objc_oneway] = &PP.getIdentifierTable().get("oneway");
00435     ObjCTypeQuals[objc_bycopy] = &PP.getIdentifierTable().get("bycopy");
00436     ObjCTypeQuals[objc_byref] = &PP.getIdentifierTable().get("byref");
00437   }
00438 
00439   Ident_instancetype = nullptr;
00440   Ident_final = nullptr;
00441   Ident_sealed = nullptr;
00442   Ident_override = nullptr;
00443 
00444   Ident_super = &PP.getIdentifierTable().get("super");
00445 
00446   if (getLangOpts().AltiVec) {
00447     Ident_vector = &PP.getIdentifierTable().get("vector");
00448     Ident_pixel = &PP.getIdentifierTable().get("pixel");
00449     Ident_bool = &PP.getIdentifierTable().get("bool");
00450   }
00451 
00452   Ident_introduced = nullptr;
00453   Ident_deprecated = nullptr;
00454   Ident_obsoleted = nullptr;
00455   Ident_unavailable = nullptr;
00456 
00457   Ident__except = nullptr;
00458 
00459   Ident__exception_code = Ident__exception_info = nullptr;
00460   Ident__abnormal_termination = Ident___exception_code = nullptr;
00461   Ident___exception_info = Ident___abnormal_termination = nullptr;
00462   Ident_GetExceptionCode = Ident_GetExceptionInfo = nullptr;
00463   Ident_AbnormalTermination = nullptr;
00464 
00465   if(getLangOpts().Borland) {
00466     Ident__exception_info        = PP.getIdentifierInfo("_exception_info");
00467     Ident___exception_info       = PP.getIdentifierInfo("__exception_info");
00468     Ident_GetExceptionInfo       = PP.getIdentifierInfo("GetExceptionInformation");
00469     Ident__exception_code        = PP.getIdentifierInfo("_exception_code");
00470     Ident___exception_code       = PP.getIdentifierInfo("__exception_code");
00471     Ident_GetExceptionCode       = PP.getIdentifierInfo("GetExceptionCode");
00472     Ident__abnormal_termination  = PP.getIdentifierInfo("_abnormal_termination");
00473     Ident___abnormal_termination = PP.getIdentifierInfo("__abnormal_termination");
00474     Ident_AbnormalTermination    = PP.getIdentifierInfo("AbnormalTermination");
00475 
00476     PP.SetPoisonReason(Ident__exception_code,diag::err_seh___except_block);
00477     PP.SetPoisonReason(Ident___exception_code,diag::err_seh___except_block);
00478     PP.SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block);
00479     PP.SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter);
00480     PP.SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter);
00481     PP.SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter);
00482     PP.SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block);
00483     PP.SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block);
00484     PP.SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block);
00485   }
00486 
00487   Actions.Initialize();
00488 
00489   // Prime the lexer look-ahead.
00490   ConsumeToken();
00491 }
00492 
00493 namespace {
00494   /// \brief RAIIObject to destroy the contents of a SmallVector of
00495   /// TemplateIdAnnotation pointers and clear the vector.
00496   class DestroyTemplateIdAnnotationsRAIIObj {
00497     SmallVectorImpl<TemplateIdAnnotation *> &Container;
00498   public:
00499     DestroyTemplateIdAnnotationsRAIIObj(SmallVectorImpl<TemplateIdAnnotation *>
00500                                        &Container)
00501       : Container(Container) {}
00502 
00503     ~DestroyTemplateIdAnnotationsRAIIObj() {
00504       for (SmallVectorImpl<TemplateIdAnnotation *>::iterator I =
00505            Container.begin(), E = Container.end();
00506            I != E; ++I)
00507         (*I)->Destroy();
00508       Container.clear();
00509     }
00510   };
00511 }
00512 
00513 void Parser::LateTemplateParserCleanupCallback(void *P) {
00514   // While this RAII helper doesn't bracket any actual work, the destructor will
00515   // clean up annotations that were created during ActOnEndOfTranslationUnit
00516   // when incremental processing is enabled.
00517   DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(((Parser *)P)->TemplateIds);
00518 }
00519 
00520 /// ParseTopLevelDecl - Parse one top-level declaration, return whatever the
00521 /// action tells us to.  This returns true if the EOF was encountered.
00522 bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result) {
00523   DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
00524 
00525   // Skip over the EOF token, flagging end of previous input for incremental
00526   // processing
00527   if (PP.isIncrementalProcessingEnabled() && Tok.is(tok::eof))
00528     ConsumeToken();
00529 
00530   Result = DeclGroupPtrTy();
00531   switch (Tok.getKind()) {
00532   case tok::annot_pragma_unused:
00533     HandlePragmaUnused();
00534     return false;
00535 
00536   case tok::annot_module_include:
00537     Actions.ActOnModuleInclude(Tok.getLocation(),
00538                                reinterpret_cast<Module *>(
00539                                    Tok.getAnnotationValue()));
00540     ConsumeToken();
00541     return false;
00542 
00543   case tok::annot_module_begin:
00544   case tok::annot_module_end:
00545     // FIXME: Update visibility based on the submodule we're in.
00546     ConsumeToken();
00547     return false;
00548 
00549   case tok::eof:
00550     // Late template parsing can begin.
00551     if (getLangOpts().DelayedTemplateParsing)
00552       Actions.SetLateTemplateParser(LateTemplateParserCallback,
00553                                     PP.isIncrementalProcessingEnabled() ?
00554                                     LateTemplateParserCleanupCallback : nullptr,
00555                                     this);
00556     if (!PP.isIncrementalProcessingEnabled())
00557       Actions.ActOnEndOfTranslationUnit();
00558     //else don't tell Sema that we ended parsing: more input might come.
00559     return true;
00560 
00561   default:
00562     break;
00563   }
00564 
00565   ParsedAttributesWithRange attrs(AttrFactory);
00566   MaybeParseCXX11Attributes(attrs);
00567   MaybeParseMicrosoftAttributes(attrs);
00568 
00569   Result = ParseExternalDeclaration(attrs);
00570   return false;
00571 }
00572 
00573 /// ParseExternalDeclaration:
00574 ///
00575 ///       external-declaration: [C99 6.9], declaration: [C++ dcl.dcl]
00576 ///         function-definition
00577 ///         declaration
00578 /// [GNU]   asm-definition
00579 /// [GNU]   __extension__ external-declaration
00580 /// [OBJC]  objc-class-definition
00581 /// [OBJC]  objc-class-declaration
00582 /// [OBJC]  objc-alias-declaration
00583 /// [OBJC]  objc-protocol-definition
00584 /// [OBJC]  objc-method-definition
00585 /// [OBJC]  @end
00586 /// [C++]   linkage-specification
00587 /// [GNU] asm-definition:
00588 ///         simple-asm-expr ';'
00589 /// [C++11] empty-declaration
00590 /// [C++11] attribute-declaration
00591 ///
00592 /// [C++11] empty-declaration:
00593 ///           ';'
00594 ///
00595 /// [C++0x/GNU] 'extern' 'template' declaration
00596 Parser::DeclGroupPtrTy
00597 Parser::ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
00598                                  ParsingDeclSpec *DS) {
00599   DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
00600   ParenBraceBracketBalancer BalancerRAIIObj(*this);
00601 
00602   if (PP.isCodeCompletionReached()) {
00603     cutOffParsing();
00604     return DeclGroupPtrTy();
00605   }
00606 
00607   Decl *SingleDecl = nullptr;
00608   switch (Tok.getKind()) {
00609   case tok::annot_pragma_vis:
00610     HandlePragmaVisibility();
00611     return DeclGroupPtrTy();
00612   case tok::annot_pragma_pack:
00613     HandlePragmaPack();
00614     return DeclGroupPtrTy();
00615   case tok::annot_pragma_msstruct:
00616     HandlePragmaMSStruct();
00617     return DeclGroupPtrTy();
00618   case tok::annot_pragma_align:
00619     HandlePragmaAlign();
00620     return DeclGroupPtrTy();
00621   case tok::annot_pragma_weak:
00622     HandlePragmaWeak();
00623     return DeclGroupPtrTy();
00624   case tok::annot_pragma_weakalias:
00625     HandlePragmaWeakAlias();
00626     return DeclGroupPtrTy();
00627   case tok::annot_pragma_redefine_extname:
00628     HandlePragmaRedefineExtname();
00629     return DeclGroupPtrTy();
00630   case tok::annot_pragma_fp_contract:
00631     HandlePragmaFPContract();
00632     return DeclGroupPtrTy();
00633   case tok::annot_pragma_opencl_extension:
00634     HandlePragmaOpenCLExtension();
00635     return DeclGroupPtrTy();
00636   case tok::annot_pragma_openmp:
00637     return ParseOpenMPDeclarativeDirective();
00638   case tok::annot_pragma_ms_pointers_to_members:
00639     HandlePragmaMSPointersToMembers();
00640     return DeclGroupPtrTy();
00641   case tok::annot_pragma_ms_vtordisp:
00642     HandlePragmaMSVtorDisp();
00643     return DeclGroupPtrTy();
00644   case tok::annot_pragma_ms_pragma:
00645     HandlePragmaMSPragma();
00646     return DeclGroupPtrTy();
00647   case tok::semi:
00648     // Either a C++11 empty-declaration or attribute-declaration.
00649     SingleDecl = Actions.ActOnEmptyDeclaration(getCurScope(),
00650                                                attrs.getList(),
00651                                                Tok.getLocation());
00652     ConsumeExtraSemi(OutsideFunction);
00653     break;
00654   case tok::r_brace:
00655     Diag(Tok, diag::err_extraneous_closing_brace);
00656     ConsumeBrace();
00657     return DeclGroupPtrTy();
00658   case tok::eof:
00659     Diag(Tok, diag::err_expected_external_declaration);
00660     return DeclGroupPtrTy();
00661   case tok::kw___extension__: {
00662     // __extension__ silences extension warnings in the subexpression.
00663     ExtensionRAIIObject O(Diags);  // Use RAII to do this.
00664     ConsumeToken();
00665     return ParseExternalDeclaration(attrs);
00666   }
00667   case tok::kw_asm: {
00668     ProhibitAttributes(attrs);
00669 
00670     SourceLocation StartLoc = Tok.getLocation();
00671     SourceLocation EndLoc;
00672     ExprResult Result(ParseSimpleAsm(&EndLoc));
00673 
00674     ExpectAndConsume(tok::semi, diag::err_expected_after,
00675                      "top-level asm block");
00676 
00677     if (Result.isInvalid())
00678       return DeclGroupPtrTy();
00679     SingleDecl = Actions.ActOnFileScopeAsmDecl(Result.get(), StartLoc, EndLoc);
00680     break;
00681   }
00682   case tok::at:
00683     return ParseObjCAtDirectives();
00684   case tok::minus:
00685   case tok::plus:
00686     if (!getLangOpts().ObjC1) {
00687       Diag(Tok, diag::err_expected_external_declaration);
00688       ConsumeToken();
00689       return DeclGroupPtrTy();
00690     }
00691     SingleDecl = ParseObjCMethodDefinition();
00692     break;
00693   case tok::code_completion:
00694       Actions.CodeCompleteOrdinaryName(getCurScope(), 
00695                              CurParsedObjCImpl? Sema::PCC_ObjCImplementation
00696                                               : Sema::PCC_Namespace);
00697     cutOffParsing();
00698     return DeclGroupPtrTy();
00699   case tok::kw_using:
00700   case tok::kw_namespace:
00701   case tok::kw_typedef:
00702   case tok::kw_template:
00703   case tok::kw_export:    // As in 'export template'
00704   case tok::kw_static_assert:
00705   case tok::kw__Static_assert:
00706     // A function definition cannot start with any of these keywords.
00707     {
00708       SourceLocation DeclEnd;
00709       return ParseDeclaration(Declarator::FileContext, DeclEnd, attrs);
00710     }
00711 
00712   case tok::kw_static:
00713     // Parse (then ignore) 'static' prior to a template instantiation. This is
00714     // a GCC extension that we intentionally do not support.
00715     if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
00716       Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
00717         << 0;
00718       SourceLocation DeclEnd;
00719       return ParseDeclaration(Declarator::FileContext, DeclEnd, attrs);
00720     }
00721     goto dont_know;
00722       
00723   case tok::kw_inline:
00724     if (getLangOpts().CPlusPlus) {
00725       tok::TokenKind NextKind = NextToken().getKind();
00726       
00727       // Inline namespaces. Allowed as an extension even in C++03.
00728       if (NextKind == tok::kw_namespace) {
00729         SourceLocation DeclEnd;
00730         return ParseDeclaration(Declarator::FileContext, DeclEnd, attrs);
00731       }
00732       
00733       // Parse (then ignore) 'inline' prior to a template instantiation. This is
00734       // a GCC extension that we intentionally do not support.
00735       if (NextKind == tok::kw_template) {
00736         Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
00737           << 1;
00738         SourceLocation DeclEnd;
00739         return ParseDeclaration(Declarator::FileContext, DeclEnd, attrs);
00740       }
00741     }
00742     goto dont_know;
00743 
00744   case tok::kw_extern:
00745     if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
00746       // Extern templates
00747       SourceLocation ExternLoc = ConsumeToken();
00748       SourceLocation TemplateLoc = ConsumeToken();
00749       Diag(ExternLoc, getLangOpts().CPlusPlus11 ?
00750              diag::warn_cxx98_compat_extern_template :
00751              diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc);
00752       SourceLocation DeclEnd;
00753       return Actions.ConvertDeclToDeclGroup(
00754                   ParseExplicitInstantiation(Declarator::FileContext,
00755                                              ExternLoc, TemplateLoc, DeclEnd));
00756     }
00757     goto dont_know;
00758 
00759   case tok::kw___if_exists:
00760   case tok::kw___if_not_exists:
00761     ParseMicrosoftIfExistsExternalDeclaration();
00762     return DeclGroupPtrTy();
00763       
00764   default:
00765   dont_know:
00766     // We can't tell whether this is a function-definition or declaration yet.
00767     return ParseDeclarationOrFunctionDefinition(attrs, DS);
00768   }
00769 
00770   // This routine returns a DeclGroup, if the thing we parsed only contains a
00771   // single decl, convert it now.
00772   return Actions.ConvertDeclToDeclGroup(SingleDecl);
00773 }
00774 
00775 /// \brief Determine whether the current token, if it occurs after a
00776 /// declarator, continues a declaration or declaration list.
00777 bool Parser::isDeclarationAfterDeclarator() {
00778   // Check for '= delete' or '= default'
00779   if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
00780     const Token &KW = NextToken();
00781     if (KW.is(tok::kw_default) || KW.is(tok::kw_delete))
00782       return false;
00783   }
00784   
00785   return Tok.is(tok::equal) ||      // int X()=  -> not a function def
00786     Tok.is(tok::comma) ||           // int X(),  -> not a function def
00787     Tok.is(tok::semi)  ||           // int X();  -> not a function def
00788     Tok.is(tok::kw_asm) ||          // int X() __asm__ -> not a function def
00789     Tok.is(tok::kw___attribute) ||  // int X() __attr__ -> not a function def
00790     (getLangOpts().CPlusPlus &&
00791      Tok.is(tok::l_paren));         // int X(0) -> not a function def [C++]
00792 }
00793 
00794 /// \brief Determine whether the current token, if it occurs after a
00795 /// declarator, indicates the start of a function definition.
00796 bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) {
00797   assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator");
00798   if (Tok.is(tok::l_brace))   // int X() {}
00799     return true;
00800   
00801   // Handle K&R C argument lists: int X(f) int f; {}
00802   if (!getLangOpts().CPlusPlus &&
00803       Declarator.getFunctionTypeInfo().isKNRPrototype()) 
00804     return isDeclarationSpecifier();
00805 
00806   if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
00807     const Token &KW = NextToken();
00808     return KW.is(tok::kw_default) || KW.is(tok::kw_delete);
00809   }
00810   
00811   return Tok.is(tok::colon) ||         // X() : Base() {} (used for ctors)
00812          Tok.is(tok::kw_try);          // X() try { ... }
00813 }
00814 
00815 /// ParseDeclarationOrFunctionDefinition - Parse either a function-definition or
00816 /// a declaration.  We can't tell which we have until we read up to the
00817 /// compound-statement in function-definition. TemplateParams, if
00818 /// non-NULL, provides the template parameters when we're parsing a
00819 /// C++ template-declaration.
00820 ///
00821 ///       function-definition: [C99 6.9.1]
00822 ///         decl-specs      declarator declaration-list[opt] compound-statement
00823 /// [C90] function-definition: [C99 6.7.1] - implicit int result
00824 /// [C90]   decl-specs[opt] declarator declaration-list[opt] compound-statement
00825 ///
00826 ///       declaration: [C99 6.7]
00827 ///         declaration-specifiers init-declarator-list[opt] ';'
00828 /// [!C99]  init-declarator-list ';'                   [TODO: warn in c99 mode]
00829 /// [OMP]   threadprivate-directive                              [TODO]
00830 ///
00831 Parser::DeclGroupPtrTy
00832 Parser::ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
00833                                        ParsingDeclSpec &DS,
00834                                        AccessSpecifier AS) {
00835   // Parse the common declaration-specifiers piece.
00836   ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC_top_level);
00837 
00838   // If we had a free-standing type definition with a missing semicolon, we
00839   // may get this far before the problem becomes obvious.
00840   if (DS.hasTagDefinition() &&
00841       DiagnoseMissingSemiAfterTagDefinition(DS, AS, DSC_top_level))
00842     return DeclGroupPtrTy();
00843 
00844   // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
00845   // declaration-specifiers init-declarator-list[opt] ';'
00846   if (Tok.is(tok::semi)) {
00847     ProhibitAttributes(attrs);
00848     ConsumeToken();
00849     Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS);
00850     DS.complete(TheDecl);
00851     return Actions.ConvertDeclToDeclGroup(TheDecl);
00852   }
00853 
00854   DS.takeAttributesFrom(attrs);
00855 
00856   // ObjC2 allows prefix attributes on class interfaces and protocols.
00857   // FIXME: This still needs better diagnostics. We should only accept
00858   // attributes here, no types, etc.
00859   if (getLangOpts().ObjC2 && Tok.is(tok::at)) {
00860     SourceLocation AtLoc = ConsumeToken(); // the "@"
00861     if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
00862         !Tok.isObjCAtKeyword(tok::objc_protocol)) {
00863       Diag(Tok, diag::err_objc_unexpected_attr);
00864       SkipUntil(tok::semi); // FIXME: better skip?
00865       return DeclGroupPtrTy();
00866     }
00867 
00868     DS.abort();
00869 
00870     const char *PrevSpec = nullptr;
00871     unsigned DiagID;
00872     if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID,
00873                            Actions.getASTContext().getPrintingPolicy()))
00874       Diag(AtLoc, DiagID) << PrevSpec;
00875 
00876     if (Tok.isObjCAtKeyword(tok::objc_protocol))
00877       return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
00878 
00879     return Actions.ConvertDeclToDeclGroup(
00880             ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes()));
00881   }
00882 
00883   // If the declspec consisted only of 'extern' and we have a string
00884   // literal following it, this must be a C++ linkage specifier like
00885   // 'extern "C"'.
00886   if (getLangOpts().CPlusPlus && isTokenStringLiteral() &&
00887       DS.getStorageClassSpec() == DeclSpec::SCS_extern &&
00888       DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) {
00889     Decl *TheDecl = ParseLinkage(DS, Declarator::FileContext);
00890     return Actions.ConvertDeclToDeclGroup(TheDecl);
00891   }
00892 
00893   return ParseDeclGroup(DS, Declarator::FileContext, true);
00894 }
00895 
00896 Parser::DeclGroupPtrTy
00897 Parser::ParseDeclarationOrFunctionDefinition(ParsedAttributesWithRange &attrs,
00898                                              ParsingDeclSpec *DS,
00899                                              AccessSpecifier AS) {
00900   if (DS) {
00901     return ParseDeclOrFunctionDefInternal(attrs, *DS, AS);
00902   } else {
00903     ParsingDeclSpec PDS(*this);
00904     // Must temporarily exit the objective-c container scope for
00905     // parsing c constructs and re-enter objc container scope
00906     // afterwards.
00907     ObjCDeclContextSwitch ObjCDC(*this);
00908       
00909     return ParseDeclOrFunctionDefInternal(attrs, PDS, AS);
00910   }
00911 }
00912 
00913 /// ParseFunctionDefinition - We parsed and verified that the specified
00914 /// Declarator is well formed.  If this is a K&R-style function, read the
00915 /// parameters declaration-list, then start the compound-statement.
00916 ///
00917 ///       function-definition: [C99 6.9.1]
00918 ///         decl-specs      declarator declaration-list[opt] compound-statement
00919 /// [C90] function-definition: [C99 6.7.1] - implicit int result
00920 /// [C90]   decl-specs[opt] declarator declaration-list[opt] compound-statement
00921 /// [C++] function-definition: [C++ 8.4]
00922 ///         decl-specifier-seq[opt] declarator ctor-initializer[opt]
00923 ///         function-body
00924 /// [C++] function-definition: [C++ 8.4]
00925 ///         decl-specifier-seq[opt] declarator function-try-block
00926 ///
00927 Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
00928                                       const ParsedTemplateInfo &TemplateInfo,
00929                                       LateParsedAttrList *LateParsedAttrs) {
00930   // Poison the SEH identifiers so they are flagged as illegal in function bodies
00931   PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
00932   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
00933 
00934   // If this is C90 and the declspecs were completely missing, fudge in an
00935   // implicit int.  We do this here because this is the only place where
00936   // declaration-specifiers are completely optional in the grammar.
00937   if (getLangOpts().ImplicitInt && D.getDeclSpec().isEmpty()) {
00938     const char *PrevSpec;
00939     unsigned DiagID;
00940     const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
00941     D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int,
00942                                            D.getIdentifierLoc(),
00943                                            PrevSpec, DiagID,
00944                                            Policy);
00945     D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin());
00946   }
00947 
00948   // If this declaration was formed with a K&R-style identifier list for the
00949   // arguments, parse declarations for all of the args next.
00950   // int foo(a,b) int a; float b; {}
00951   if (FTI.isKNRPrototype())
00952     ParseKNRParamDeclarations(D);
00953 
00954   // We should have either an opening brace or, in a C++ constructor,
00955   // we may have a colon.
00956   if (Tok.isNot(tok::l_brace) && 
00957       (!getLangOpts().CPlusPlus ||
00958        (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
00959         Tok.isNot(tok::equal)))) {
00960     Diag(Tok, diag::err_expected_fn_body);
00961 
00962     // Skip over garbage, until we get to '{'.  Don't eat the '{'.
00963     SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
00964 
00965     // If we didn't find the '{', bail out.
00966     if (Tok.isNot(tok::l_brace))
00967       return nullptr;
00968   }
00969 
00970   // Check to make sure that any normal attributes are allowed to be on
00971   // a definition.  Late parsed attributes are checked at the end.
00972   if (Tok.isNot(tok::equal)) {
00973     AttributeList *DtorAttrs = D.getAttributes();
00974     while (DtorAttrs) {
00975       if (DtorAttrs->isKnownToGCC() &&
00976           !DtorAttrs->isCXX11Attribute()) {
00977         Diag(DtorAttrs->getLoc(), diag::warn_attribute_on_function_definition)
00978           << DtorAttrs->getName();
00979       }
00980       DtorAttrs = DtorAttrs->getNext();
00981     }
00982   }
00983 
00984   // In delayed template parsing mode, for function template we consume the
00985   // tokens and store them for late parsing at the end of the translation unit.
00986   if (getLangOpts().DelayedTemplateParsing && Tok.isNot(tok::equal) &&
00987       TemplateInfo.Kind == ParsedTemplateInfo::Template &&
00988       Actions.canDelayFunctionBody(D)) {
00989     MultiTemplateParamsArg TemplateParameterLists(*TemplateInfo.TemplateParams);
00990     
00991     ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
00992     Scope *ParentScope = getCurScope()->getParent();
00993 
00994     D.setFunctionDefinitionKind(FDK_Definition);
00995     Decl *DP = Actions.HandleDeclarator(ParentScope, D,
00996                                         TemplateParameterLists);
00997     D.complete(DP);
00998     D.getMutableDeclSpec().abort();
00999 
01000     CachedTokens Toks;
01001     LexTemplateFunctionForLateParsing(Toks);
01002 
01003     if (DP) {
01004       FunctionDecl *FnD = DP->getAsFunction();
01005       Actions.CheckForFunctionRedefinition(FnD);
01006       Actions.MarkAsLateParsedTemplate(FnD, DP, Toks);
01007     }
01008     return DP;
01009   }
01010   else if (CurParsedObjCImpl && 
01011            !TemplateInfo.TemplateParams &&
01012            (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) ||
01013             Tok.is(tok::colon)) && 
01014       Actions.CurContext->isTranslationUnit()) {
01015     ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
01016     Scope *ParentScope = getCurScope()->getParent();
01017 
01018     D.setFunctionDefinitionKind(FDK_Definition);
01019     Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
01020                                               MultiTemplateParamsArg());
01021     D.complete(FuncDecl);
01022     D.getMutableDeclSpec().abort();
01023     if (FuncDecl) {
01024       // Consume the tokens and store them for later parsing.
01025       StashAwayMethodOrFunctionBodyTokens(FuncDecl);
01026       CurParsedObjCImpl->HasCFunction = true;
01027       return FuncDecl;
01028     }
01029     // FIXME: Should we really fall through here?
01030   }
01031 
01032   // Enter a scope for the function body.
01033   ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
01034 
01035   // Tell the actions module that we have entered a function definition with the
01036   // specified Declarator for the function.
01037   Decl *Res = TemplateInfo.TemplateParams?
01038       Actions.ActOnStartOfFunctionTemplateDef(getCurScope(),
01039                                               *TemplateInfo.TemplateParams, D)
01040     : Actions.ActOnStartOfFunctionDef(getCurScope(), D);
01041 
01042   // Break out of the ParsingDeclarator context before we parse the body.
01043   D.complete(Res);
01044   
01045   // Break out of the ParsingDeclSpec context, too.  This const_cast is
01046   // safe because we're always the sole owner.
01047   D.getMutableDeclSpec().abort();
01048 
01049   if (TryConsumeToken(tok::equal)) {
01050     assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='");
01051     Actions.ActOnFinishFunctionBody(Res, nullptr, false);
01052 
01053     bool Delete = false;
01054     SourceLocation KWLoc;
01055     if (TryConsumeToken(tok::kw_delete, KWLoc)) {
01056       Diag(KWLoc, getLangOpts().CPlusPlus11
01057                       ? diag::warn_cxx98_compat_deleted_function
01058                       : diag::ext_deleted_function);
01059       Actions.SetDeclDeleted(Res, KWLoc);
01060       Delete = true;
01061     } else if (TryConsumeToken(tok::kw_default, KWLoc)) {
01062       Diag(KWLoc, getLangOpts().CPlusPlus11
01063                       ? diag::warn_cxx98_compat_defaulted_function
01064                       : diag::ext_defaulted_function);
01065       Actions.SetDeclDefaulted(Res, KWLoc);
01066     } else {
01067       llvm_unreachable("function definition after = not 'delete' or 'default'");
01068     }
01069 
01070     if (Tok.is(tok::comma)) {
01071       Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
01072         << Delete;
01073       SkipUntil(tok::semi);
01074     } else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
01075                                 Delete ? "delete" : "default")) {
01076       SkipUntil(tok::semi);
01077     }
01078 
01079     return Res;
01080   }
01081 
01082   if (Tok.is(tok::kw_try))
01083     return ParseFunctionTryBlock(Res, BodyScope);
01084 
01085   // If we have a colon, then we're probably parsing a C++
01086   // ctor-initializer.
01087   if (Tok.is(tok::colon)) {
01088     ParseConstructorInitializer(Res);
01089 
01090     // Recover from error.
01091     if (!Tok.is(tok::l_brace)) {
01092       BodyScope.Exit();
01093       Actions.ActOnFinishFunctionBody(Res, nullptr);
01094       return Res;
01095     }
01096   } else
01097     Actions.ActOnDefaultCtorInitializers(Res);
01098 
01099   // Late attributes are parsed in the same scope as the function body.
01100   if (LateParsedAttrs)
01101     ParseLexedAttributeList(*LateParsedAttrs, Res, false, true);
01102 
01103   return ParseFunctionStatementBody(Res, BodyScope);
01104 }
01105 
01106 /// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
01107 /// types for a function with a K&R-style identifier list for arguments.
01108 void Parser::ParseKNRParamDeclarations(Declarator &D) {
01109   // We know that the top-level of this declarator is a function.
01110   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
01111 
01112   // Enter function-declaration scope, limiting any declarators to the
01113   // function prototype scope, including parameter declarators.
01114   ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
01115                             Scope::FunctionDeclarationScope | Scope::DeclScope);
01116 
01117   // Read all the argument declarations.
01118   while (isDeclarationSpecifier()) {
01119     SourceLocation DSStart = Tok.getLocation();
01120 
01121     // Parse the common declaration-specifiers piece.
01122     DeclSpec DS(AttrFactory);
01123     ParseDeclarationSpecifiers(DS);
01124 
01125     // C99 6.9.1p6: 'each declaration in the declaration list shall have at
01126     // least one declarator'.
01127     // NOTE: GCC just makes this an ext-warn.  It's not clear what it does with
01128     // the declarations though.  It's trivial to ignore them, really hard to do
01129     // anything else with them.
01130     if (TryConsumeToken(tok::semi)) {
01131       Diag(DSStart, diag::err_declaration_does_not_declare_param);
01132       continue;
01133     }
01134 
01135     // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
01136     // than register.
01137     if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
01138         DS.getStorageClassSpec() != DeclSpec::SCS_register) {
01139       Diag(DS.getStorageClassSpecLoc(),
01140            diag::err_invalid_storage_class_in_func_decl);
01141       DS.ClearStorageClassSpecs();
01142     }
01143     if (DS.getThreadStorageClassSpec() != DeclSpec::TSCS_unspecified) {
01144       Diag(DS.getThreadStorageClassSpecLoc(),
01145            diag::err_invalid_storage_class_in_func_decl);
01146       DS.ClearStorageClassSpecs();
01147     }
01148 
01149     // Parse the first declarator attached to this declspec.
01150     Declarator ParmDeclarator(DS, Declarator::KNRTypeListContext);
01151     ParseDeclarator(ParmDeclarator);
01152 
01153     // Handle the full declarator list.
01154     while (1) {
01155       // If attributes are present, parse them.
01156       MaybeParseGNUAttributes(ParmDeclarator);
01157 
01158       // Ask the actions module to compute the type for this declarator.
01159       Decl *Param =
01160         Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
01161 
01162       if (Param &&
01163           // A missing identifier has already been diagnosed.
01164           ParmDeclarator.getIdentifier()) {
01165 
01166         // Scan the argument list looking for the correct param to apply this
01167         // type.
01168         for (unsigned i = 0; ; ++i) {
01169           // C99 6.9.1p6: those declarators shall declare only identifiers from
01170           // the identifier list.
01171           if (i == FTI.NumParams) {
01172             Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
01173               << ParmDeclarator.getIdentifier();
01174             break;
01175           }
01176 
01177           if (FTI.Params[i].Ident == ParmDeclarator.getIdentifier()) {
01178             // Reject redefinitions of parameters.
01179             if (FTI.Params[i].Param) {
01180               Diag(ParmDeclarator.getIdentifierLoc(),
01181                    diag::err_param_redefinition)
01182                  << ParmDeclarator.getIdentifier();
01183             } else {
01184               FTI.Params[i].Param = Param;
01185             }
01186             break;
01187           }
01188         }
01189       }
01190 
01191       // If we don't have a comma, it is either the end of the list (a ';') or
01192       // an error, bail out.
01193       if (Tok.isNot(tok::comma))
01194         break;
01195 
01196       ParmDeclarator.clear();
01197 
01198       // Consume the comma.
01199       ParmDeclarator.setCommaLoc(ConsumeToken());
01200 
01201       // Parse the next declarator.
01202       ParseDeclarator(ParmDeclarator);
01203     }
01204 
01205     // Consume ';' and continue parsing.
01206     if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration))
01207       continue;
01208 
01209     // Otherwise recover by skipping to next semi or mandatory function body.
01210     if (SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch))
01211       break;
01212     TryConsumeToken(tok::semi);
01213   }
01214 
01215   // The actions module must verify that all arguments were declared.
01216   Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation());
01217 }
01218 
01219 
01220 /// ParseAsmStringLiteral - This is just a normal string-literal, but is not
01221 /// allowed to be a wide string, and is not subject to character translation.
01222 ///
01223 /// [GNU] asm-string-literal:
01224 ///         string-literal
01225 ///
01226 ExprResult Parser::ParseAsmStringLiteral() {
01227   switch (Tok.getKind()) {
01228     case tok::string_literal:
01229       break;
01230     case tok::utf8_string_literal:
01231     case tok::utf16_string_literal:
01232     case tok::utf32_string_literal:
01233     case tok::wide_string_literal: {
01234       SourceLocation L = Tok.getLocation();
01235       Diag(Tok, diag::err_asm_operand_wide_string_literal)
01236         << (Tok.getKind() == tok::wide_string_literal)
01237         << SourceRange(L, L);
01238       return ExprError();
01239     }
01240     default:
01241       Diag(Tok, diag::err_expected_string_literal)
01242         << /*Source='in...'*/0 << "'asm'";
01243       return ExprError();
01244   }
01245 
01246   return ParseStringLiteralExpression();
01247 }
01248 
01249 /// ParseSimpleAsm
01250 ///
01251 /// [GNU] simple-asm-expr:
01252 ///         'asm' '(' asm-string-literal ')'
01253 ///
01254 ExprResult Parser::ParseSimpleAsm(SourceLocation *EndLoc) {
01255   assert(Tok.is(tok::kw_asm) && "Not an asm!");
01256   SourceLocation Loc = ConsumeToken();
01257 
01258   if (Tok.is(tok::kw_volatile)) {
01259     // Remove from the end of 'asm' to the end of 'volatile'.
01260     SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
01261                              PP.getLocForEndOfToken(Tok.getLocation()));
01262 
01263     Diag(Tok, diag::warn_file_asm_volatile)
01264       << FixItHint::CreateRemoval(RemovalRange);
01265     ConsumeToken();
01266   }
01267 
01268   BalancedDelimiterTracker T(*this, tok::l_paren);
01269   if (T.consumeOpen()) {
01270     Diag(Tok, diag::err_expected_lparen_after) << "asm";
01271     return ExprError();
01272   }
01273 
01274   ExprResult Result(ParseAsmStringLiteral());
01275 
01276   if (!Result.isInvalid()) {
01277     // Close the paren and get the location of the end bracket
01278     T.consumeClose();
01279     if (EndLoc)
01280       *EndLoc = T.getCloseLocation();
01281   } else if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
01282     if (EndLoc)
01283       *EndLoc = Tok.getLocation();
01284     ConsumeParen();
01285   }
01286 
01287   return Result;
01288 }
01289 
01290 /// \brief Get the TemplateIdAnnotation from the token and put it in the
01291 /// cleanup pool so that it gets destroyed when parsing the current top level
01292 /// declaration is finished.
01293 TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) {
01294   assert(tok.is(tok::annot_template_id) && "Expected template-id token");
01295   TemplateIdAnnotation *
01296       Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue());
01297   return Id;
01298 }
01299 
01300 void Parser::AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation) {
01301   // Push the current token back into the token stream (or revert it if it is
01302   // cached) and use an annotation scope token for current token.
01303   if (PP.isBacktrackEnabled())
01304     PP.RevertCachedTokens(1);
01305   else
01306     PP.EnterToken(Tok);
01307   Tok.setKind(tok::annot_cxxscope);
01308   Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
01309   Tok.setAnnotationRange(SS.getRange());
01310 
01311   // In case the tokens were cached, have Preprocessor replace them
01312   // with the annotation token.  We don't need to do this if we've
01313   // just reverted back to a prior state.
01314   if (IsNewAnnotation)
01315     PP.AnnotateCachedTokens(Tok);
01316 }
01317 
01318 /// \brief Attempt to classify the name at the current token position. This may
01319 /// form a type, scope or primary expression annotation, or replace the token
01320 /// with a typo-corrected keyword. This is only appropriate when the current
01321 /// name must refer to an entity which has already been declared.
01322 ///
01323 /// \param IsAddressOfOperand Must be \c true if the name is preceded by an '&'
01324 ///        and might possibly have a dependent nested name specifier.
01325 /// \param CCC Indicates how to perform typo-correction for this name. If NULL,
01326 ///        no typo correction will be performed.
01327 Parser::AnnotatedNameKind
01328 Parser::TryAnnotateName(bool IsAddressOfOperand,
01329                         std::unique_ptr<CorrectionCandidateCallback> CCC) {
01330   assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
01331 
01332   const bool EnteringContext = false;
01333   const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
01334 
01335   CXXScopeSpec SS;
01336   if (getLangOpts().CPlusPlus &&
01337       ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
01338     return ANK_Error;
01339 
01340   if (Tok.isNot(tok::identifier) || SS.isInvalid()) {
01341     if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, false, SS,
01342                                                   !WasScopeAnnotation))
01343       return ANK_Error;
01344     return ANK_Unresolved;
01345   }
01346 
01347   IdentifierInfo *Name = Tok.getIdentifierInfo();
01348   SourceLocation NameLoc = Tok.getLocation();
01349 
01350   // FIXME: Move the tentative declaration logic into ClassifyName so we can
01351   // typo-correct to tentatively-declared identifiers.
01352   if (isTentativelyDeclared(Name)) {
01353     // Identifier has been tentatively declared, and thus cannot be resolved as
01354     // an expression. Fall back to annotating it as a type.
01355     if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, false, SS,
01356                                                   !WasScopeAnnotation))
01357       return ANK_Error;
01358     return Tok.is(tok::annot_typename) ? ANK_Success : ANK_TentativeDecl;
01359   }
01360 
01361   Token Next = NextToken();
01362 
01363   // Look up and classify the identifier. We don't perform any typo-correction
01364   // after a scope specifier, because in general we can't recover from typos
01365   // there (eg, after correcting 'A::tempalte B<X>::C' [sic], we would need to
01366   // jump back into scope specifier parsing).
01367   Sema::NameClassification Classification = Actions.ClassifyName(
01368       getCurScope(), SS, Name, NameLoc, Next, IsAddressOfOperand,
01369       SS.isEmpty() ? std::move(CCC) : nullptr);
01370 
01371   switch (Classification.getKind()) {
01372   case Sema::NC_Error:
01373     return ANK_Error;
01374 
01375   case Sema::NC_Keyword:
01376     // The identifier was typo-corrected to a keyword.
01377     Tok.setIdentifierInfo(Name);
01378     Tok.setKind(Name->getTokenID());
01379     PP.TypoCorrectToken(Tok);
01380     if (SS.isNotEmpty())
01381       AnnotateScopeToken(SS, !WasScopeAnnotation);
01382     // We've "annotated" this as a keyword.
01383     return ANK_Success;
01384 
01385   case Sema::NC_Unknown:
01386     // It's not something we know about. Leave it unannotated.
01387     break;
01388 
01389   case Sema::NC_Type:
01390     Tok.setKind(tok::annot_typename);
01391     setTypeAnnotation(Tok, Classification.getType());
01392     Tok.setAnnotationEndLoc(NameLoc);
01393     if (SS.isNotEmpty())
01394       Tok.setLocation(SS.getBeginLoc());
01395     PP.AnnotateCachedTokens(Tok);
01396     return ANK_Success;
01397 
01398   case Sema::NC_Expression:
01399     Tok.setKind(tok::annot_primary_expr);
01400     setExprAnnotation(Tok, Classification.getExpression());
01401     Tok.setAnnotationEndLoc(NameLoc);
01402     if (SS.isNotEmpty())
01403       Tok.setLocation(SS.getBeginLoc());
01404     PP.AnnotateCachedTokens(Tok);
01405     return ANK_Success;
01406 
01407   case Sema::NC_TypeTemplate:
01408     if (Next.isNot(tok::less)) {
01409       // This may be a type template being used as a template template argument.
01410       if (SS.isNotEmpty())
01411         AnnotateScopeToken(SS, !WasScopeAnnotation);
01412       return ANK_TemplateName;
01413     }
01414     // Fall through.
01415   case Sema::NC_VarTemplate:
01416   case Sema::NC_FunctionTemplate: {
01417     // We have a type, variable or function template followed by '<'.
01418     ConsumeToken();
01419     UnqualifiedId Id;
01420     Id.setIdentifier(Name, NameLoc);
01421     if (AnnotateTemplateIdToken(
01422             TemplateTy::make(Classification.getTemplateName()),
01423             Classification.getTemplateNameKind(), SS, SourceLocation(), Id))
01424       return ANK_Error;
01425     return ANK_Success;
01426   }
01427 
01428   case Sema::NC_NestedNameSpecifier:
01429     llvm_unreachable("already parsed nested name specifier");
01430   }
01431 
01432   // Unable to classify the name, but maybe we can annotate a scope specifier.
01433   if (SS.isNotEmpty())
01434     AnnotateScopeToken(SS, !WasScopeAnnotation);
01435   return ANK_Unresolved;
01436 }
01437 
01438 bool Parser::TryKeywordIdentFallback(bool DisableKeyword) {
01439   assert(Tok.isNot(tok::identifier));
01440   Diag(Tok, diag::ext_keyword_as_ident)
01441     << PP.getSpelling(Tok)
01442     << DisableKeyword;
01443   if (DisableKeyword)
01444     Tok.getIdentifierInfo()->RevertTokenIDToIdentifier();
01445   Tok.setKind(tok::identifier);
01446   return true;
01447 }
01448 
01449 /// TryAnnotateTypeOrScopeToken - If the current token position is on a
01450 /// typename (possibly qualified in C++) or a C++ scope specifier not followed
01451 /// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
01452 /// with a single annotation token representing the typename or C++ scope
01453 /// respectively.
01454 /// This simplifies handling of C++ scope specifiers and allows efficient
01455 /// backtracking without the need to re-parse and resolve nested-names and
01456 /// typenames.
01457 /// It will mainly be called when we expect to treat identifiers as typenames
01458 /// (if they are typenames). For example, in C we do not expect identifiers
01459 /// inside expressions to be treated as typenames so it will not be called
01460 /// for expressions in C.
01461 /// The benefit for C/ObjC is that a typename will be annotated and
01462 /// Actions.getTypeName will not be needed to be called again (e.g. getTypeName
01463 /// will not be called twice, once to check whether we have a declaration
01464 /// specifier, and another one to get the actual type inside
01465 /// ParseDeclarationSpecifiers).
01466 ///
01467 /// This returns true if an error occurred.
01468 ///
01469 /// Note that this routine emits an error if you call it with ::new or ::delete
01470 /// as the current tokens, so only call it in contexts where these are invalid.
01471 bool Parser::TryAnnotateTypeOrScopeToken(bool EnteringContext, bool NeedType) {
01472   assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
01473           Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope) ||
01474           Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id) ||
01475           Tok.is(tok::kw___super)) &&
01476          "Cannot be a type or scope token!");
01477 
01478   if (Tok.is(tok::kw_typename)) {
01479     // MSVC lets you do stuff like:
01480     //   typename typedef T_::D D;
01481     //
01482     // We will consume the typedef token here and put it back after we have
01483     // parsed the first identifier, transforming it into something more like:
01484     //   typename T_::D typedef D;
01485     if (getLangOpts().MSVCCompat && NextToken().is(tok::kw_typedef)) {
01486       Token TypedefToken;
01487       PP.Lex(TypedefToken);
01488       bool Result = TryAnnotateTypeOrScopeToken(EnteringContext, NeedType);
01489       PP.EnterToken(Tok);
01490       Tok = TypedefToken;
01491       if (!Result)
01492         Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename);
01493       return Result;
01494     }
01495 
01496     // Parse a C++ typename-specifier, e.g., "typename T::type".
01497     //
01498     //   typename-specifier:
01499     //     'typename' '::' [opt] nested-name-specifier identifier
01500     //     'typename' '::' [opt] nested-name-specifier template [opt]
01501     //            simple-template-id
01502     SourceLocation TypenameLoc = ConsumeToken();
01503     CXXScopeSpec SS;
01504     if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/ParsedType(), 
01505                                        /*EnteringContext=*/false,
01506                                        nullptr, /*IsTypename*/ true))
01507       return true;
01508     if (!SS.isSet()) {
01509       if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) ||
01510           Tok.is(tok::annot_decltype)) {
01511         // Attempt to recover by skipping the invalid 'typename'
01512         if (Tok.is(tok::annot_decltype) ||
01513             (!TryAnnotateTypeOrScopeToken(EnteringContext, NeedType) &&
01514              Tok.isAnnotation())) {
01515           unsigned DiagID = diag::err_expected_qualified_after_typename;
01516           // MS compatibility: MSVC permits using known types with typename.
01517           // e.g. "typedef typename T* pointer_type"
01518           if (getLangOpts().MicrosoftExt)
01519             DiagID = diag::warn_expected_qualified_after_typename;
01520           Diag(Tok.getLocation(), DiagID);
01521           return false;
01522         }
01523       }
01524 
01525       Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
01526       return true;
01527     }
01528 
01529     TypeResult Ty;
01530     if (Tok.is(tok::identifier)) {
01531       // FIXME: check whether the next token is '<', first!
01532       Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS, 
01533                                      *Tok.getIdentifierInfo(),
01534                                      Tok.getLocation());
01535     } else if (Tok.is(tok::annot_template_id)) {
01536       TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
01537       if (TemplateId->Kind != TNK_Type_template &&
01538           TemplateId->Kind != TNK_Dependent_template_name) {
01539         Diag(Tok, diag::err_typename_refers_to_non_type_template)
01540           << Tok.getAnnotationRange();
01541         return true;
01542       }
01543 
01544       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
01545                                          TemplateId->NumArgs);
01546 
01547       Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
01548                                      TemplateId->TemplateKWLoc,
01549                                      TemplateId->Template,
01550                                      TemplateId->TemplateNameLoc,
01551                                      TemplateId->LAngleLoc,
01552                                      TemplateArgsPtr,
01553                                      TemplateId->RAngleLoc);
01554     } else {
01555       Diag(Tok, diag::err_expected_type_name_after_typename)
01556         << SS.getRange();
01557       return true;
01558     }
01559 
01560     SourceLocation EndLoc = Tok.getLastLoc();
01561     Tok.setKind(tok::annot_typename);
01562     setTypeAnnotation(Tok, Ty.isInvalid() ? ParsedType() : Ty.get());
01563     Tok.setAnnotationEndLoc(EndLoc);
01564     Tok.setLocation(TypenameLoc);
01565     PP.AnnotateCachedTokens(Tok);
01566     return false;
01567   }
01568 
01569   // Remembers whether the token was originally a scope annotation.
01570   bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
01571 
01572   CXXScopeSpec SS;
01573   if (getLangOpts().CPlusPlus)
01574     if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
01575       return true;
01576 
01577   return TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, NeedType,
01578                                                    SS, !WasScopeAnnotation);
01579 }
01580 
01581 /// \brief Try to annotate a type or scope token, having already parsed an
01582 /// optional scope specifier. \p IsNewScope should be \c true unless the scope
01583 /// specifier was extracted from an existing tok::annot_cxxscope annotation.
01584 bool Parser::TryAnnotateTypeOrScopeTokenAfterScopeSpec(bool EnteringContext,
01585                                                        bool NeedType,
01586                                                        CXXScopeSpec &SS,
01587                                                        bool IsNewScope) {
01588   if (Tok.is(tok::identifier)) {
01589     IdentifierInfo *CorrectedII = nullptr;
01590     // Determine whether the identifier is a type name.
01591     if (ParsedType Ty = Actions.getTypeName(*Tok.getIdentifierInfo(),
01592                                             Tok.getLocation(), getCurScope(),
01593                                             &SS, false, 
01594                                             NextToken().is(tok::period),
01595                                             ParsedType(),
01596                                             /*IsCtorOrDtorName=*/false,
01597                                             /*NonTrivialTypeSourceInfo*/ true,
01598                                             NeedType ? &CorrectedII
01599                                                      : nullptr)) {
01600       // A FixIt was applied as a result of typo correction
01601       if (CorrectedII)
01602         Tok.setIdentifierInfo(CorrectedII);
01603       // This is a typename. Replace the current token in-place with an
01604       // annotation type token.
01605       Tok.setKind(tok::annot_typename);
01606       setTypeAnnotation(Tok, Ty);
01607       Tok.setAnnotationEndLoc(Tok.getLocation());
01608       if (SS.isNotEmpty()) // it was a C++ qualified type name.
01609         Tok.setLocation(SS.getBeginLoc());
01610 
01611       // In case the tokens were cached, have Preprocessor replace
01612       // them with the annotation token.
01613       PP.AnnotateCachedTokens(Tok);
01614       return false;
01615     }
01616 
01617     if (!getLangOpts().CPlusPlus) {
01618       // If we're in C, we can't have :: tokens at all (the lexer won't return
01619       // them).  If the identifier is not a type, then it can't be scope either,
01620       // just early exit.
01621       return false;
01622     }
01623 
01624     // If this is a template-id, annotate with a template-id or type token.
01625     if (NextToken().is(tok::less)) {
01626       TemplateTy Template;
01627       UnqualifiedId TemplateName;
01628       TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
01629       bool MemberOfUnknownSpecialization;
01630       if (TemplateNameKind TNK
01631           = Actions.isTemplateName(getCurScope(), SS,
01632                                    /*hasTemplateKeyword=*/false, TemplateName,
01633                                    /*ObjectType=*/ ParsedType(),
01634                                    EnteringContext,
01635                                    Template, MemberOfUnknownSpecialization)) {
01636         // Consume the identifier.
01637         ConsumeToken();
01638         if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
01639                                     TemplateName)) {
01640           // If an unrecoverable error occurred, we need to return true here,
01641           // because the token stream is in a damaged state.  We may not return
01642           // a valid identifier.
01643           return true;
01644         }
01645       }
01646     }
01647 
01648     // The current token, which is either an identifier or a
01649     // template-id, is not part of the annotation. Fall through to
01650     // push that token back into the stream and complete the C++ scope
01651     // specifier annotation.
01652   }
01653 
01654   if (Tok.is(tok::annot_template_id)) {
01655     TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
01656     if (TemplateId->Kind == TNK_Type_template) {
01657       // A template-id that refers to a type was parsed into a
01658       // template-id annotation in a context where we weren't allowed
01659       // to produce a type annotation token. Update the template-id
01660       // annotation token to a type annotation token now.
01661       AnnotateTemplateIdTokenAsType();
01662       return false;
01663     }
01664   }
01665 
01666   if (SS.isEmpty())
01667     return false;
01668 
01669   // A C++ scope specifier that isn't followed by a typename.
01670   AnnotateScopeToken(SS, IsNewScope);
01671   return false;
01672 }
01673 
01674 /// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
01675 /// annotates C++ scope specifiers and template-ids.  This returns
01676 /// true if there was an error that could not be recovered from.
01677 ///
01678 /// Note that this routine emits an error if you call it with ::new or ::delete
01679 /// as the current tokens, so only call it in contexts where these are invalid.
01680 bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) {
01681   assert(getLangOpts().CPlusPlus &&
01682          "Call sites of this function should be guarded by checking for C++");
01683   assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
01684           (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) ||
01685           Tok.is(tok::kw_decltype) || Tok.is(tok::kw___super)) &&
01686          "Cannot be a type or scope token!");
01687 
01688   CXXScopeSpec SS;
01689   if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
01690     return true;
01691   if (SS.isEmpty())
01692     return false;
01693 
01694   AnnotateScopeToken(SS, true);
01695   return false;
01696 }
01697 
01698 bool Parser::isTokenEqualOrEqualTypo() {
01699   tok::TokenKind Kind = Tok.getKind();
01700   switch (Kind) {
01701   default:
01702     return false;
01703   case tok::ampequal:            // &=
01704   case tok::starequal:           // *=
01705   case tok::plusequal:           // +=
01706   case tok::minusequal:          // -=
01707   case tok::exclaimequal:        // !=
01708   case tok::slashequal:          // /=
01709   case tok::percentequal:        // %=
01710   case tok::lessequal:           // <=
01711   case tok::lesslessequal:       // <<=
01712   case tok::greaterequal:        // >=
01713   case tok::greatergreaterequal: // >>=
01714   case tok::caretequal:          // ^=
01715   case tok::pipeequal:           // |=
01716   case tok::equalequal:          // ==
01717     Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal)
01718         << Kind
01719         << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()), "=");
01720   case tok::equal:
01721     return true;
01722   }
01723 }
01724 
01725 SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
01726   assert(Tok.is(tok::code_completion));
01727   PrevTokLocation = Tok.getLocation();
01728 
01729   for (Scope *S = getCurScope(); S; S = S->getParent()) {
01730     if (S->getFlags() & Scope::FnScope) {
01731       Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_RecoveryInFunction);
01732       cutOffParsing();
01733       return PrevTokLocation;
01734     }
01735     
01736     if (S->getFlags() & Scope::ClassScope) {
01737       Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class);
01738       cutOffParsing();
01739       return PrevTokLocation;
01740     }
01741   }
01742   
01743   Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace);
01744   cutOffParsing();
01745   return PrevTokLocation;
01746 }
01747 
01748 // Code-completion pass-through functions
01749 
01750 void Parser::CodeCompleteDirective(bool InConditional) {
01751   Actions.CodeCompletePreprocessorDirective(InConditional);
01752 }
01753 
01754 void Parser::CodeCompleteInConditionalExclusion() {
01755   Actions.CodeCompleteInPreprocessorConditionalExclusion(getCurScope());
01756 }
01757 
01758 void Parser::CodeCompleteMacroName(bool IsDefinition) {
01759   Actions.CodeCompletePreprocessorMacroName(IsDefinition);
01760 }
01761 
01762 void Parser::CodeCompletePreprocessorExpression() { 
01763   Actions.CodeCompletePreprocessorExpression();
01764 }
01765 
01766 void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro,
01767                                        MacroInfo *MacroInfo,
01768                                        unsigned ArgumentIndex) {
01769   Actions.CodeCompletePreprocessorMacroArgument(getCurScope(), Macro, MacroInfo, 
01770                                                 ArgumentIndex);
01771 }
01772 
01773 void Parser::CodeCompleteNaturalLanguage() {
01774   Actions.CodeCompleteNaturalLanguage();
01775 }
01776 
01777 bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) {
01778   assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
01779          "Expected '__if_exists' or '__if_not_exists'");
01780   Result.IsIfExists = Tok.is(tok::kw___if_exists);
01781   Result.KeywordLoc = ConsumeToken();
01782 
01783   BalancedDelimiterTracker T(*this, tok::l_paren);
01784   if (T.consumeOpen()) {
01785     Diag(Tok, diag::err_expected_lparen_after) 
01786       << (Result.IsIfExists? "__if_exists" : "__if_not_exists");
01787     return true;
01788   }
01789   
01790   // Parse nested-name-specifier.
01791   ParseOptionalCXXScopeSpecifier(Result.SS, ParsedType(), 
01792                                  /*EnteringContext=*/false);
01793 
01794   // Check nested-name specifier.
01795   if (Result.SS.isInvalid()) {
01796     T.skipToEnd();
01797     return true;
01798   }
01799 
01800   // Parse the unqualified-id.
01801   SourceLocation TemplateKWLoc; // FIXME: parsed, but unused.
01802   if (ParseUnqualifiedId(Result.SS, false, true, true, ParsedType(),
01803                          TemplateKWLoc, Result.Name)) {
01804     T.skipToEnd();
01805     return true;
01806   }
01807 
01808   if (T.consumeClose())
01809     return true;
01810   
01811   // Check if the symbol exists.
01812   switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc,
01813                                                Result.IsIfExists, Result.SS, 
01814                                                Result.Name)) {
01815   case Sema::IER_Exists:
01816     Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip;
01817     break;
01818 
01819   case Sema::IER_DoesNotExist:
01820     Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip;
01821     break;
01822 
01823   case Sema::IER_Dependent:
01824     Result.Behavior = IEB_Dependent;
01825     break;
01826       
01827   case Sema::IER_Error:
01828     return true;
01829   }
01830 
01831   return false;
01832 }
01833 
01834 void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
01835   IfExistsCondition Result;
01836   if (ParseMicrosoftIfExistsCondition(Result))
01837     return;
01838   
01839   BalancedDelimiterTracker Braces(*this, tok::l_brace);
01840   if (Braces.consumeOpen()) {
01841     Diag(Tok, diag::err_expected) << tok::l_brace;
01842     return;
01843   }
01844 
01845   switch (Result.Behavior) {
01846   case IEB_Parse:
01847     // Parse declarations below.
01848     break;
01849       
01850   case IEB_Dependent:
01851     llvm_unreachable("Cannot have a dependent external declaration");
01852       
01853   case IEB_Skip:
01854     Braces.skipToEnd();
01855     return;
01856   }
01857 
01858   // Parse the declarations.
01859   // FIXME: Support module import within __if_exists?
01860   while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
01861     ParsedAttributesWithRange attrs(AttrFactory);
01862     MaybeParseCXX11Attributes(attrs);
01863     MaybeParseMicrosoftAttributes(attrs);
01864     DeclGroupPtrTy Result = ParseExternalDeclaration(attrs);
01865     if (Result && !getCurScope()->getParent())
01866       Actions.getASTConsumer().HandleTopLevelDecl(Result.get());
01867   }
01868   Braces.consumeClose();
01869 }
01870 
01871 Parser::DeclGroupPtrTy Parser::ParseModuleImport(SourceLocation AtLoc) {
01872   assert(Tok.isObjCAtKeyword(tok::objc_import) && 
01873          "Improper start to module import");
01874   SourceLocation ImportLoc = ConsumeToken();
01875   
01876   SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
01877   
01878   // Parse the module path.
01879   do {
01880     if (!Tok.is(tok::identifier)) {
01881       if (Tok.is(tok::code_completion)) {
01882         Actions.CodeCompleteModuleImport(ImportLoc, Path);
01883         cutOffParsing();
01884         return DeclGroupPtrTy();
01885       }
01886       
01887       Diag(Tok, diag::err_module_expected_ident);
01888       SkipUntil(tok::semi);
01889       return DeclGroupPtrTy();
01890     }
01891     
01892     // Record this part of the module path.
01893     Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation()));
01894     ConsumeToken();
01895     
01896     if (Tok.is(tok::period)) {
01897       ConsumeToken();
01898       continue;
01899     }
01900     
01901     break;
01902   } while (true);
01903 
01904   if (PP.hadModuleLoaderFatalFailure()) {
01905     // With a fatal failure in the module loader, we abort parsing.
01906     cutOffParsing();
01907     return DeclGroupPtrTy();
01908   }
01909 
01910   DeclResult Import = Actions.ActOnModuleImport(AtLoc, ImportLoc, Path);
01911   ExpectAndConsumeSemi(diag::err_module_expected_semi);
01912   if (Import.isInvalid())
01913     return DeclGroupPtrTy();
01914   
01915   return Actions.ConvertDeclToDeclGroup(Import.get());
01916 }
01917 
01918 bool BalancedDelimiterTracker::diagnoseOverflow() {
01919   P.Diag(P.Tok, diag::err_bracket_depth_exceeded)
01920     << P.getLangOpts().BracketDepth;
01921   P.Diag(P.Tok, diag::note_bracket_depth);
01922   P.cutOffParsing();
01923   return true;
01924 }
01925 
01926 bool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID,
01927                                                 const char *Msg,
01928                                                 tok::TokenKind SkipToTok) {
01929   LOpen = P.Tok.getLocation();
01930   if (P.ExpectAndConsume(Kind, DiagID, Msg)) {
01931     if (SkipToTok != tok::unknown)
01932       P.SkipUntil(SkipToTok, Parser::StopAtSemi);
01933     return true;
01934   }
01935 
01936   if (getDepth() < MaxDepth)
01937     return false;
01938     
01939   return diagnoseOverflow();
01940 }
01941 
01942 bool BalancedDelimiterTracker::diagnoseMissingClose() {
01943   assert(!P.Tok.is(Close) && "Should have consumed closing delimiter");
01944 
01945   P.Diag(P.Tok, diag::err_expected) << Close;
01946   P.Diag(LOpen, diag::note_matching) << Kind;
01947 
01948   // If we're not already at some kind of closing bracket, skip to our closing
01949   // token.
01950   if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) &&
01951       P.Tok.isNot(tok::r_square) &&
01952       P.SkipUntil(Close, FinalToken,
01953                   Parser::StopAtSemi | Parser::StopBeforeMatch) &&
01954       P.Tok.is(Close))
01955     LClose = P.ConsumeAnyToken();
01956   return true;
01957 }
01958 
01959 void BalancedDelimiterTracker::skipToEnd() {
01960   P.SkipUntil(Close, Parser::StopBeforeMatch);
01961   consumeClose();
01962 }