clang API Documentation

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