1 //===--- Parser.cpp - C Language Family Parser ----------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements the Parser interfaces.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Parse/Parser.h"
15 #include "ParsePragma.h"
16 #include "RAIIObjectsForParser.h"
17 #include "clang/AST/ASTConsumer.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/Parse/ParseDiagnostic.h"
20 #include "clang/Sema/DeclSpec.h"
21 #include "clang/Sema/ParsedTemplate.h"
22 #include "clang/Sema/Scope.h"
23 #include "llvm/Support/raw_ostream.h"
24 using namespace clang;
25 
26 
27 namespace {
28 /// \brief A comment handler that passes comments found by the preprocessor
29 /// to the parser action.
30 class ActionCommentHandler : public CommentHandler {
31   Sema &S;
32 
33 public:
34   explicit ActionCommentHandler(Sema &S) : S(S) { }
35 
36   virtual bool HandleComment(Preprocessor &PP, SourceRange Comment) {
37     S.ActOnComment(Comment);
38     return false;
39   }
40 };
41 } // end anonymous namespace
42 
43 IdentifierInfo *Parser::getSEHExceptKeyword() {
44   // __except is accepted as a (contextual) keyword
45   if (!Ident__except && (getLangOpts().MicrosoftExt || getLangOpts().Borland))
46     Ident__except = PP.getIdentifierInfo("__except");
47 
48   return Ident__except;
49 }
50 
51 Parser::Parser(Preprocessor &pp, Sema &actions, bool skipFunctionBodies)
52   : PP(pp), Actions(actions), Diags(PP.getDiagnostics()),
53     GreaterThanIsOperator(true), ColonIsSacred(false),
54     InMessageExpression(false), TemplateParameterDepth(0),
55     ParsingInObjCContainer(false) {
56   SkipFunctionBodies = pp.isCodeCompletionEnabled() || skipFunctionBodies;
57   Tok.startToken();
58   Tok.setKind(tok::eof);
59   Actions.CurScope = 0;
60   NumCachedScopes = 0;
61   ParenCount = BracketCount = BraceCount = 0;
62   CurParsedObjCImpl = 0;
63 
64   // Add #pragma handlers. These are removed and destroyed in the
65   // destructor.
66   AlignHandler.reset(new PragmaAlignHandler());
67   PP.AddPragmaHandler(AlignHandler.get());
68 
69   GCCVisibilityHandler.reset(new PragmaGCCVisibilityHandler());
70   PP.AddPragmaHandler("GCC", GCCVisibilityHandler.get());
71 
72   OptionsHandler.reset(new PragmaOptionsHandler());
73   PP.AddPragmaHandler(OptionsHandler.get());
74 
75   PackHandler.reset(new PragmaPackHandler());
76   PP.AddPragmaHandler(PackHandler.get());
77 
78   MSStructHandler.reset(new PragmaMSStructHandler());
79   PP.AddPragmaHandler(MSStructHandler.get());
80 
81   UnusedHandler.reset(new PragmaUnusedHandler());
82   PP.AddPragmaHandler(UnusedHandler.get());
83 
84   WeakHandler.reset(new PragmaWeakHandler());
85   PP.AddPragmaHandler(WeakHandler.get());
86 
87   RedefineExtnameHandler.reset(new PragmaRedefineExtnameHandler());
88   PP.AddPragmaHandler(RedefineExtnameHandler.get());
89 
90   FPContractHandler.reset(new PragmaFPContractHandler());
91   PP.AddPragmaHandler("STDC", FPContractHandler.get());
92 
93   if (getLangOpts().OpenCL) {
94     OpenCLExtensionHandler.reset(new PragmaOpenCLExtensionHandler());
95     PP.AddPragmaHandler("OPENCL", OpenCLExtensionHandler.get());
96 
97     PP.AddPragmaHandler("OPENCL", FPContractHandler.get());
98   }
99   if (getLangOpts().OpenMP)
100     OpenMPHandler.reset(new PragmaOpenMPHandler());
101   else
102     OpenMPHandler.reset(new PragmaNoOpenMPHandler());
103   PP.AddPragmaHandler(OpenMPHandler.get());
104 
105   CommentSemaHandler.reset(new ActionCommentHandler(actions));
106   PP.addCommentHandler(CommentSemaHandler.get());
107 
108   PP.setCodeCompletionHandler(*this);
109 }
110 
111 DiagnosticBuilder Parser::Diag(SourceLocation Loc, unsigned DiagID) {
112   return Diags.Report(Loc, DiagID);
113 }
114 
115 DiagnosticBuilder Parser::Diag(const Token &Tok, unsigned DiagID) {
116   return Diag(Tok.getLocation(), DiagID);
117 }
118 
119 /// \brief Emits a diagnostic suggesting parentheses surrounding a
120 /// given range.
121 ///
122 /// \param Loc The location where we'll emit the diagnostic.
123 /// \param DK The kind of diagnostic to emit.
124 /// \param ParenRange Source range enclosing code that should be parenthesized.
125 void Parser::SuggestParentheses(SourceLocation Loc, unsigned DK,
126                                 SourceRange ParenRange) {
127   SourceLocation EndLoc = PP.getLocForEndOfToken(ParenRange.getEnd());
128   if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
129     // We can't display the parentheses, so just dig the
130     // warning/error and return.
131     Diag(Loc, DK);
132     return;
133   }
134 
135   Diag(Loc, DK)
136     << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
137     << FixItHint::CreateInsertion(EndLoc, ")");
138 }
139 
140 static bool IsCommonTypo(tok::TokenKind ExpectedTok, const Token &Tok) {
141   switch (ExpectedTok) {
142   case tok::semi:
143     return Tok.is(tok::colon) || Tok.is(tok::comma); // : or , for ;
144   default: return false;
145   }
146 }
147 
148 /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
149 /// input.  If so, it is consumed and false is returned.
150 ///
151 /// If the input is malformed, this emits the specified diagnostic.  Next, if
152 /// SkipToTok is specified, it calls SkipUntil(SkipToTok).  Finally, true is
153 /// returned.
154 bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID,
155                               const char *Msg, tok::TokenKind SkipToTok) {
156   if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) {
157     ConsumeAnyToken();
158     return false;
159   }
160 
161   // Detect common single-character typos and resume.
162   if (IsCommonTypo(ExpectedTok, Tok)) {
163     SourceLocation Loc = Tok.getLocation();
164     Diag(Loc, DiagID)
165       << Msg
166       << FixItHint::CreateReplacement(SourceRange(Loc),
167                                       getTokenSimpleSpelling(ExpectedTok));
168     ConsumeAnyToken();
169 
170     // Pretend there wasn't a problem.
171     return false;
172   }
173 
174   const char *Spelling = 0;
175   SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
176   if (EndLoc.isValid() &&
177       (Spelling = tok::getTokenSimpleSpelling(ExpectedTok))) {
178     // Show what code to insert to fix this problem.
179     Diag(EndLoc, DiagID)
180       << Msg
181       << FixItHint::CreateInsertion(EndLoc, Spelling);
182   } else
183     Diag(Tok, DiagID) << Msg;
184 
185   if (SkipToTok != tok::unknown)
186     SkipUntil(SkipToTok);
187   return true;
188 }
189 
190 bool Parser::ExpectAndConsumeSemi(unsigned DiagID) {
191   if (Tok.is(tok::semi) || Tok.is(tok::code_completion)) {
192     ConsumeToken();
193     return false;
194   }
195 
196   if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) &&
197       NextToken().is(tok::semi)) {
198     Diag(Tok, diag::err_extraneous_token_before_semi)
199       << PP.getSpelling(Tok)
200       << FixItHint::CreateRemoval(Tok.getLocation());
201     ConsumeAnyToken(); // The ')' or ']'.
202     ConsumeToken(); // The ';'.
203     return false;
204   }
205 
206   return ExpectAndConsume(tok::semi, DiagID);
207 }
208 
209 void Parser::ConsumeExtraSemi(ExtraSemiKind Kind, unsigned TST) {
210   if (!Tok.is(tok::semi)) return;
211 
212   bool HadMultipleSemis = false;
213   SourceLocation StartLoc = Tok.getLocation();
214   SourceLocation EndLoc = Tok.getLocation();
215   ConsumeToken();
216 
217   while ((Tok.is(tok::semi) && !Tok.isAtStartOfLine())) {
218     HadMultipleSemis = true;
219     EndLoc = Tok.getLocation();
220     ConsumeToken();
221   }
222 
223   // C++11 allows extra semicolons at namespace scope, but not in any of the
224   // other contexts.
225   if (Kind == OutsideFunction && getLangOpts().CPlusPlus) {
226     if (getLangOpts().CPlusPlus11)
227       Diag(StartLoc, diag::warn_cxx98_compat_top_level_semi)
228           << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
229     else
230       Diag(StartLoc, diag::ext_extra_semi_cxx11)
231           << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
232     return;
233   }
234 
235   if (Kind != AfterMemberFunctionDefinition || HadMultipleSemis)
236     Diag(StartLoc, diag::ext_extra_semi)
237         << Kind << DeclSpec::getSpecifierName((DeclSpec::TST)TST)
238         << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
239   else
240     // A single semicolon is valid after a member function definition.
241     Diag(StartLoc, diag::warn_extra_semi_after_mem_fn_def)
242       << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
243 }
244 
245 //===----------------------------------------------------------------------===//
246 // Error recovery.
247 //===----------------------------------------------------------------------===//
248 
249 /// SkipUntil - Read tokens until we get to the specified token, then consume
250 /// it (unless DontConsume is true).  Because we cannot guarantee that the
251 /// token will ever occur, this skips to the next token, or to some likely
252 /// good stopping point.  If StopAtSemi is true, skipping will stop at a ';'
253 /// character.
254 ///
255 /// If SkipUntil finds the specified token, it returns true, otherwise it
256 /// returns false.
257 bool Parser::SkipUntil(ArrayRef<tok::TokenKind> Toks, bool StopAtSemi,
258                        bool DontConsume, bool StopAtCodeCompletion) {
259   // We always want this function to skip at least one token if the first token
260   // isn't T and if not at EOF.
261   bool isFirstTokenSkipped = true;
262   while (1) {
263     // If we found one of the tokens, stop and return true.
264     for (unsigned i = 0, NumToks = Toks.size(); i != NumToks; ++i) {
265       if (Tok.is(Toks[i])) {
266         if (DontConsume) {
267           // Noop, don't consume the token.
268         } else {
269           ConsumeAnyToken();
270         }
271         return true;
272       }
273     }
274 
275     switch (Tok.getKind()) {
276     case tok::eof:
277       // Ran out of tokens.
278       return false;
279 
280     case tok::code_completion:
281       if (!StopAtCodeCompletion)
282         ConsumeToken();
283       return false;
284 
285     case tok::l_paren:
286       // Recursively skip properly-nested parens.
287       ConsumeParen();
288       SkipUntil(tok::r_paren, false, false, StopAtCodeCompletion);
289       break;
290     case tok::l_square:
291       // Recursively skip properly-nested square brackets.
292       ConsumeBracket();
293       SkipUntil(tok::r_square, false, false, StopAtCodeCompletion);
294       break;
295     case tok::l_brace:
296       // Recursively skip properly-nested braces.
297       ConsumeBrace();
298       SkipUntil(tok::r_brace, false, false, StopAtCodeCompletion);
299       break;
300 
301     // Okay, we found a ']' or '}' or ')', which we think should be balanced.
302     // Since the user wasn't looking for this token (if they were, it would
303     // already be handled), this isn't balanced.  If there is a LHS token at a
304     // higher level, we will assume that this matches the unbalanced token
305     // and return it.  Otherwise, this is a spurious RHS token, which we skip.
306     case tok::r_paren:
307       if (ParenCount && !isFirstTokenSkipped)
308         return false;  // Matches something.
309       ConsumeParen();
310       break;
311     case tok::r_square:
312       if (BracketCount && !isFirstTokenSkipped)
313         return false;  // Matches something.
314       ConsumeBracket();
315       break;
316     case tok::r_brace:
317       if (BraceCount && !isFirstTokenSkipped)
318         return false;  // Matches something.
319       ConsumeBrace();
320       break;
321 
322     case tok::string_literal:
323     case tok::wide_string_literal:
324     case tok::utf8_string_literal:
325     case tok::utf16_string_literal:
326     case tok::utf32_string_literal:
327       ConsumeStringToken();
328       break;
329 
330     case tok::semi:
331       if (StopAtSemi)
332         return false;
333       // FALL THROUGH.
334     default:
335       // Skip this token.
336       ConsumeToken();
337       break;
338     }
339     isFirstTokenSkipped = false;
340   }
341 }
342 
343 //===----------------------------------------------------------------------===//
344 // Scope manipulation
345 //===----------------------------------------------------------------------===//
346 
347 /// EnterScope - Start a new scope.
348 void Parser::EnterScope(unsigned ScopeFlags) {
349   if (NumCachedScopes) {
350     Scope *N = ScopeCache[--NumCachedScopes];
351     N->Init(getCurScope(), ScopeFlags);
352     Actions.CurScope = N;
353   } else {
354     Actions.CurScope = new Scope(getCurScope(), ScopeFlags, Diags);
355   }
356 }
357 
358 /// ExitScope - Pop a scope off the scope stack.
359 void Parser::ExitScope() {
360   assert(getCurScope() && "Scope imbalance!");
361 
362   // Inform the actions module that this scope is going away if there are any
363   // decls in it.
364   if (!getCurScope()->decl_empty())
365     Actions.ActOnPopScope(Tok.getLocation(), getCurScope());
366 
367   Scope *OldScope = getCurScope();
368   Actions.CurScope = OldScope->getParent();
369 
370   if (NumCachedScopes == ScopeCacheSize)
371     delete OldScope;
372   else
373     ScopeCache[NumCachedScopes++] = OldScope;
374 }
375 
376 /// Set the flags for the current scope to ScopeFlags. If ManageFlags is false,
377 /// this object does nothing.
378 Parser::ParseScopeFlags::ParseScopeFlags(Parser *Self, unsigned ScopeFlags,
379                                  bool ManageFlags)
380   : CurScope(ManageFlags ? Self->getCurScope() : 0) {
381   if (CurScope) {
382     OldFlags = CurScope->getFlags();
383     CurScope->setFlags(ScopeFlags);
384   }
385 }
386 
387 /// Restore the flags for the current scope to what they were before this
388 /// object overrode them.
389 Parser::ParseScopeFlags::~ParseScopeFlags() {
390   if (CurScope)
391     CurScope->setFlags(OldFlags);
392 }
393 
394 
395 //===----------------------------------------------------------------------===//
396 // C99 6.9: External Definitions.
397 //===----------------------------------------------------------------------===//
398 
399 Parser::~Parser() {
400   // If we still have scopes active, delete the scope tree.
401   delete getCurScope();
402   Actions.CurScope = 0;
403 
404   // Free the scope cache.
405   for (unsigned i = 0, e = NumCachedScopes; i != e; ++i)
406     delete ScopeCache[i];
407 
408   // Free LateParsedTemplatedFunction nodes.
409   for (LateParsedTemplateMapT::iterator it = LateParsedTemplateMap.begin();
410       it != LateParsedTemplateMap.end(); ++it)
411     delete it->second;
412 
413   // Remove the pragma handlers we installed.
414   PP.RemovePragmaHandler(AlignHandler.get());
415   AlignHandler.reset();
416   PP.RemovePragmaHandler("GCC", GCCVisibilityHandler.get());
417   GCCVisibilityHandler.reset();
418   PP.RemovePragmaHandler(OptionsHandler.get());
419   OptionsHandler.reset();
420   PP.RemovePragmaHandler(PackHandler.get());
421   PackHandler.reset();
422   PP.RemovePragmaHandler(MSStructHandler.get());
423   MSStructHandler.reset();
424   PP.RemovePragmaHandler(UnusedHandler.get());
425   UnusedHandler.reset();
426   PP.RemovePragmaHandler(WeakHandler.get());
427   WeakHandler.reset();
428   PP.RemovePragmaHandler(RedefineExtnameHandler.get());
429   RedefineExtnameHandler.reset();
430 
431   if (getLangOpts().OpenCL) {
432     PP.RemovePragmaHandler("OPENCL", OpenCLExtensionHandler.get());
433     OpenCLExtensionHandler.reset();
434     PP.RemovePragmaHandler("OPENCL", FPContractHandler.get());
435   }
436   PP.RemovePragmaHandler(OpenMPHandler.get());
437   OpenMPHandler.reset();
438 
439   PP.RemovePragmaHandler("STDC", FPContractHandler.get());
440   FPContractHandler.reset();
441 
442   PP.removeCommentHandler(CommentSemaHandler.get());
443 
444   PP.clearCodeCompletionHandler();
445 
446   assert(TemplateIds.empty() && "Still alive TemplateIdAnnotations around?");
447 }
448 
449 /// Initialize - Warm up the parser.
450 ///
451 void Parser::Initialize() {
452   // Create the translation unit scope.  Install it as the current scope.
453   assert(getCurScope() == 0 && "A scope is already active?");
454   EnterScope(Scope::DeclScope);
455   Actions.ActOnTranslationUnitScope(getCurScope());
456 
457   // Initialization for Objective-C context sensitive keywords recognition.
458   // Referenced in Parser::ParseObjCTypeQualifierList.
459   if (getLangOpts().ObjC1) {
460     ObjCTypeQuals[objc_in] = &PP.getIdentifierTable().get("in");
461     ObjCTypeQuals[objc_out] = &PP.getIdentifierTable().get("out");
462     ObjCTypeQuals[objc_inout] = &PP.getIdentifierTable().get("inout");
463     ObjCTypeQuals[objc_oneway] = &PP.getIdentifierTable().get("oneway");
464     ObjCTypeQuals[objc_bycopy] = &PP.getIdentifierTable().get("bycopy");
465     ObjCTypeQuals[objc_byref] = &PP.getIdentifierTable().get("byref");
466   }
467 
468   Ident_instancetype = 0;
469   Ident_final = 0;
470   Ident_override = 0;
471 
472   Ident_super = &PP.getIdentifierTable().get("super");
473 
474   if (getLangOpts().AltiVec) {
475     Ident_vector = &PP.getIdentifierTable().get("vector");
476     Ident_pixel = &PP.getIdentifierTable().get("pixel");
477   }
478 
479   Ident_introduced = 0;
480   Ident_deprecated = 0;
481   Ident_obsoleted = 0;
482   Ident_unavailable = 0;
483 
484   Ident__except = 0;
485 
486   Ident__exception_code = Ident__exception_info = Ident__abnormal_termination = 0;
487   Ident___exception_code = Ident___exception_info = Ident___abnormal_termination = 0;
488   Ident_GetExceptionCode = Ident_GetExceptionInfo = Ident_AbnormalTermination = 0;
489 
490   if(getLangOpts().Borland) {
491     Ident__exception_info        = PP.getIdentifierInfo("_exception_info");
492     Ident___exception_info       = PP.getIdentifierInfo("__exception_info");
493     Ident_GetExceptionInfo       = PP.getIdentifierInfo("GetExceptionInformation");
494     Ident__exception_code        = PP.getIdentifierInfo("_exception_code");
495     Ident___exception_code       = PP.getIdentifierInfo("__exception_code");
496     Ident_GetExceptionCode       = PP.getIdentifierInfo("GetExceptionCode");
497     Ident__abnormal_termination  = PP.getIdentifierInfo("_abnormal_termination");
498     Ident___abnormal_termination = PP.getIdentifierInfo("__abnormal_termination");
499     Ident_AbnormalTermination    = PP.getIdentifierInfo("AbnormalTermination");
500 
501     PP.SetPoisonReason(Ident__exception_code,diag::err_seh___except_block);
502     PP.SetPoisonReason(Ident___exception_code,diag::err_seh___except_block);
503     PP.SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block);
504     PP.SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter);
505     PP.SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter);
506     PP.SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter);
507     PP.SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block);
508     PP.SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block);
509     PP.SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block);
510   }
511 
512   Actions.Initialize();
513 
514   // Prime the lexer look-ahead.
515   ConsumeToken();
516 }
517 
518 namespace {
519   /// \brief RAIIObject to destroy the contents of a SmallVector of
520   /// TemplateIdAnnotation pointers and clear the vector.
521   class DestroyTemplateIdAnnotationsRAIIObj {
522     SmallVectorImpl<TemplateIdAnnotation *> &Container;
523   public:
524     DestroyTemplateIdAnnotationsRAIIObj(SmallVectorImpl<TemplateIdAnnotation *>
525                                        &Container)
526       : Container(Container) {}
527 
528     ~DestroyTemplateIdAnnotationsRAIIObj() {
529       for (SmallVectorImpl<TemplateIdAnnotation *>::iterator I =
530            Container.begin(), E = Container.end();
531            I != E; ++I)
532         (*I)->Destroy();
533       Container.clear();
534     }
535   };
536 }
537 
538 /// ParseTopLevelDecl - Parse one top-level declaration, return whatever the
539 /// action tells us to.  This returns true if the EOF was encountered.
540 bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result) {
541   DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
542 
543   // Skip over the EOF token, flagging end of previous input for incremental
544   // processing
545   if (PP.isIncrementalProcessingEnabled() && Tok.is(tok::eof))
546     ConsumeToken();
547 
548   while (Tok.is(tok::annot_pragma_unused))
549     HandlePragmaUnused();
550 
551   Result = DeclGroupPtrTy();
552   if (Tok.is(tok::eof)) {
553     // Late template parsing can begin.
554     if (getLangOpts().DelayedTemplateParsing)
555       Actions.SetLateTemplateParser(LateTemplateParserCallback, this);
556     if (!PP.isIncrementalProcessingEnabled())
557       Actions.ActOnEndOfTranslationUnit();
558     //else don't tell Sema that we ended parsing: more input might come.
559 
560     return true;
561   }
562 
563   ParsedAttributesWithRange attrs(AttrFactory);
564   MaybeParseCXX11Attributes(attrs);
565   MaybeParseMicrosoftAttributes(attrs);
566 
567   Result = ParseExternalDeclaration(attrs);
568   return false;
569 }
570 
571 /// ParseExternalDeclaration:
572 ///
573 ///       external-declaration: [C99 6.9], declaration: [C++ dcl.dcl]
574 ///         function-definition
575 ///         declaration
576 /// [GNU]   asm-definition
577 /// [GNU]   __extension__ external-declaration
578 /// [OBJC]  objc-class-definition
579 /// [OBJC]  objc-class-declaration
580 /// [OBJC]  objc-alias-declaration
581 /// [OBJC]  objc-protocol-definition
582 /// [OBJC]  objc-method-definition
583 /// [OBJC]  @end
584 /// [C++]   linkage-specification
585 /// [GNU] asm-definition:
586 ///         simple-asm-expr ';'
587 /// [C++11] empty-declaration
588 /// [C++11] attribute-declaration
589 ///
590 /// [C++11] empty-declaration:
591 ///           ';'
592 ///
593 /// [C++0x/GNU] 'extern' 'template' declaration
594 Parser::DeclGroupPtrTy
595 Parser::ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
596                                  ParsingDeclSpec *DS) {
597   DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
598   ParenBraceBracketBalancer BalancerRAIIObj(*this);
599 
600   if (PP.isCodeCompletionReached()) {
601     cutOffParsing();
602     return DeclGroupPtrTy();
603   }
604 
605   Decl *SingleDecl = 0;
606   switch (Tok.getKind()) {
607   case tok::annot_pragma_vis:
608     HandlePragmaVisibility();
609     return DeclGroupPtrTy();
610   case tok::annot_pragma_pack:
611     HandlePragmaPack();
612     return DeclGroupPtrTy();
613   case tok::annot_pragma_msstruct:
614     HandlePragmaMSStruct();
615     return DeclGroupPtrTy();
616   case tok::annot_pragma_align:
617     HandlePragmaAlign();
618     return DeclGroupPtrTy();
619   case tok::annot_pragma_weak:
620     HandlePragmaWeak();
621     return DeclGroupPtrTy();
622   case tok::annot_pragma_weakalias:
623     HandlePragmaWeakAlias();
624     return DeclGroupPtrTy();
625   case tok::annot_pragma_redefine_extname:
626     HandlePragmaRedefineExtname();
627     return DeclGroupPtrTy();
628   case tok::annot_pragma_fp_contract:
629     HandlePragmaFPContract();
630     return DeclGroupPtrTy();
631   case tok::annot_pragma_opencl_extension:
632     HandlePragmaOpenCLExtension();
633     return DeclGroupPtrTy();
634   case tok::annot_pragma_openmp:
635     ParseOpenMPDeclarativeDirective();
636     return DeclGroupPtrTy();
637   case tok::semi:
638     // Either a C++11 empty-declaration or attribute-declaration.
639     SingleDecl = Actions.ActOnEmptyDeclaration(getCurScope(),
640                                                attrs.getList(),
641                                                Tok.getLocation());
642     ConsumeExtraSemi(OutsideFunction);
643     break;
644   case tok::r_brace:
645     Diag(Tok, diag::err_extraneous_closing_brace);
646     ConsumeBrace();
647     return DeclGroupPtrTy();
648   case tok::eof:
649     Diag(Tok, diag::err_expected_external_declaration);
650     return DeclGroupPtrTy();
651   case tok::kw___extension__: {
652     // __extension__ silences extension warnings in the subexpression.
653     ExtensionRAIIObject O(Diags);  // Use RAII to do this.
654     ConsumeToken();
655     return ParseExternalDeclaration(attrs);
656   }
657   case tok::kw_asm: {
658     ProhibitAttributes(attrs);
659 
660     SourceLocation StartLoc = Tok.getLocation();
661     SourceLocation EndLoc;
662     ExprResult Result(ParseSimpleAsm(&EndLoc));
663 
664     ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
665                      "top-level asm block");
666 
667     if (Result.isInvalid())
668       return DeclGroupPtrTy();
669     SingleDecl = Actions.ActOnFileScopeAsmDecl(Result.get(), StartLoc, EndLoc);
670     break;
671   }
672   case tok::at:
673     return ParseObjCAtDirectives();
674   case tok::minus:
675   case tok::plus:
676     if (!getLangOpts().ObjC1) {
677       Diag(Tok, diag::err_expected_external_declaration);
678       ConsumeToken();
679       return DeclGroupPtrTy();
680     }
681     SingleDecl = ParseObjCMethodDefinition();
682     break;
683   case tok::code_completion:
684       Actions.CodeCompleteOrdinaryName(getCurScope(),
685                              CurParsedObjCImpl? Sema::PCC_ObjCImplementation
686                                               : Sema::PCC_Namespace);
687     cutOffParsing();
688     return DeclGroupPtrTy();
689   case tok::kw_using:
690   case tok::kw_namespace:
691   case tok::kw_typedef:
692   case tok::kw_template:
693   case tok::kw_export:    // As in 'export template'
694   case tok::kw_static_assert:
695   case tok::kw__Static_assert:
696     // A function definition cannot start with any of these keywords.
697     {
698       SourceLocation DeclEnd;
699       StmtVector Stmts;
700       return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
701     }
702 
703   case tok::kw_static:
704     // Parse (then ignore) 'static' prior to a template instantiation. This is
705     // a GCC extension that we intentionally do not support.
706     if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
707       Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
708         << 0;
709       SourceLocation DeclEnd;
710       StmtVector Stmts;
711       return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
712     }
713     goto dont_know;
714 
715   case tok::kw_inline:
716     if (getLangOpts().CPlusPlus) {
717       tok::TokenKind NextKind = NextToken().getKind();
718 
719       // Inline namespaces. Allowed as an extension even in C++03.
720       if (NextKind == tok::kw_namespace) {
721         SourceLocation DeclEnd;
722         StmtVector Stmts;
723         return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
724       }
725 
726       // Parse (then ignore) 'inline' prior to a template instantiation. This is
727       // a GCC extension that we intentionally do not support.
728       if (NextKind == tok::kw_template) {
729         Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
730           << 1;
731         SourceLocation DeclEnd;
732         StmtVector Stmts;
733         return ParseDeclaration(Stmts, Declarator::FileContext, DeclEnd, attrs);
734       }
735     }
736     goto dont_know;
737 
738   case tok::kw_extern:
739     if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
740       // Extern templates
741       SourceLocation ExternLoc = ConsumeToken();
742       SourceLocation TemplateLoc = ConsumeToken();
743       Diag(ExternLoc, getLangOpts().CPlusPlus11 ?
744              diag::warn_cxx98_compat_extern_template :
745              diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc);
746       SourceLocation DeclEnd;
747       return Actions.ConvertDeclToDeclGroup(
748                   ParseExplicitInstantiation(Declarator::FileContext,
749                                              ExternLoc, TemplateLoc, DeclEnd));
750     }
751     // FIXME: Detect C++ linkage specifications here?
752     goto dont_know;
753 
754   case tok::kw___if_exists:
755   case tok::kw___if_not_exists:
756     ParseMicrosoftIfExistsExternalDeclaration();
757     return DeclGroupPtrTy();
758 
759   default:
760   dont_know:
761     // We can't tell whether this is a function-definition or declaration yet.
762     return ParseDeclarationOrFunctionDefinition(attrs, DS);
763   }
764 
765   // This routine returns a DeclGroup, if the thing we parsed only contains a
766   // single decl, convert it now.
767   return Actions.ConvertDeclToDeclGroup(SingleDecl);
768 }
769 
770 /// \brief Determine whether the current token, if it occurs after a
771 /// declarator, continues a declaration or declaration list.
772 bool Parser::isDeclarationAfterDeclarator() {
773   // Check for '= delete' or '= default'
774   if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
775     const Token &KW = NextToken();
776     if (KW.is(tok::kw_default) || KW.is(tok::kw_delete))
777       return false;
778   }
779 
780   return Tok.is(tok::equal) ||      // int X()=  -> not a function def
781     Tok.is(tok::comma) ||           // int X(),  -> not a function def
782     Tok.is(tok::semi)  ||           // int X();  -> not a function def
783     Tok.is(tok::kw_asm) ||          // int X() __asm__ -> not a function def
784     Tok.is(tok::kw___attribute) ||  // int X() __attr__ -> not a function def
785     (getLangOpts().CPlusPlus &&
786      Tok.is(tok::l_paren));         // int X(0) -> not a function def [C++]
787 }
788 
789 /// \brief Determine whether the current token, if it occurs after a
790 /// declarator, indicates the start of a function definition.
791 bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) {
792   assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator");
793   if (Tok.is(tok::l_brace))   // int X() {}
794     return true;
795 
796   // Handle K&R C argument lists: int X(f) int f; {}
797   if (!getLangOpts().CPlusPlus &&
798       Declarator.getFunctionTypeInfo().isKNRPrototype())
799     return isDeclarationSpecifier();
800 
801   if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
802     const Token &KW = NextToken();
803     return KW.is(tok::kw_default) || KW.is(tok::kw_delete);
804   }
805 
806   return Tok.is(tok::colon) ||         // X() : Base() {} (used for ctors)
807          Tok.is(tok::kw_try);          // X() try { ... }
808 }
809 
810 /// ParseDeclarationOrFunctionDefinition - Parse either a function-definition or
811 /// a declaration.  We can't tell which we have until we read up to the
812 /// compound-statement in function-definition. TemplateParams, if
813 /// non-NULL, provides the template parameters when we're parsing a
814 /// C++ template-declaration.
815 ///
816 ///       function-definition: [C99 6.9.1]
817 ///         decl-specs      declarator declaration-list[opt] compound-statement
818 /// [C90] function-definition: [C99 6.7.1] - implicit int result
819 /// [C90]   decl-specs[opt] declarator declaration-list[opt] compound-statement
820 ///
821 ///       declaration: [C99 6.7]
822 ///         declaration-specifiers init-declarator-list[opt] ';'
823 /// [!C99]  init-declarator-list ';'                   [TODO: warn in c99 mode]
824 /// [OMP]   threadprivate-directive                              [TODO]
825 ///
826 Parser::DeclGroupPtrTy
827 Parser::ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
828                                        ParsingDeclSpec &DS,
829                                        AccessSpecifier AS) {
830   // Parse the common declaration-specifiers piece.
831   ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC_top_level);
832 
833   // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
834   // declaration-specifiers init-declarator-list[opt] ';'
835   if (Tok.is(tok::semi)) {
836     ProhibitAttributes(attrs);
837     ConsumeToken();
838     Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS);
839     DS.complete(TheDecl);
840     return Actions.ConvertDeclToDeclGroup(TheDecl);
841   }
842 
843   DS.takeAttributesFrom(attrs);
844 
845   // ObjC2 allows prefix attributes on class interfaces and protocols.
846   // FIXME: This still needs better diagnostics. We should only accept
847   // attributes here, no types, etc.
848   if (getLangOpts().ObjC2 && Tok.is(tok::at)) {
849     SourceLocation AtLoc = ConsumeToken(); // the "@"
850     if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
851         !Tok.isObjCAtKeyword(tok::objc_protocol)) {
852       Diag(Tok, diag::err_objc_unexpected_attr);
853       SkipUntil(tok::semi); // FIXME: better skip?
854       return DeclGroupPtrTy();
855     }
856 
857     DS.abort();
858 
859     const char *PrevSpec = 0;
860     unsigned DiagID;
861     if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID))
862       Diag(AtLoc, DiagID) << PrevSpec;
863 
864     if (Tok.isObjCAtKeyword(tok::objc_protocol))
865       return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
866 
867     return Actions.ConvertDeclToDeclGroup(
868             ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes()));
869   }
870 
871   // If the declspec consisted only of 'extern' and we have a string
872   // literal following it, this must be a C++ linkage specifier like
873   // 'extern "C"'.
874   if (Tok.is(tok::string_literal) && getLangOpts().CPlusPlus &&
875       DS.getStorageClassSpec() == DeclSpec::SCS_extern &&
876       DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) {
877     Decl *TheDecl = ParseLinkage(DS, Declarator::FileContext);
878     return Actions.ConvertDeclToDeclGroup(TheDecl);
879   }
880 
881   return ParseDeclGroup(DS, Declarator::FileContext, true);
882 }
883 
884 Parser::DeclGroupPtrTy
885 Parser::ParseDeclarationOrFunctionDefinition(ParsedAttributesWithRange &attrs,
886                                              ParsingDeclSpec *DS,
887                                              AccessSpecifier AS) {
888   if (DS) {
889     return ParseDeclOrFunctionDefInternal(attrs, *DS, AS);
890   } else {
891     ParsingDeclSpec PDS(*this);
892     // Must temporarily exit the objective-c container scope for
893     // parsing c constructs and re-enter objc container scope
894     // afterwards.
895     ObjCDeclContextSwitch ObjCDC(*this);
896 
897     return ParseDeclOrFunctionDefInternal(attrs, PDS, AS);
898   }
899 }
900 
901 /// ParseFunctionDefinition - We parsed and verified that the specified
902 /// Declarator is well formed.  If this is a K&R-style function, read the
903 /// parameters declaration-list, then start the compound-statement.
904 ///
905 ///       function-definition: [C99 6.9.1]
906 ///         decl-specs      declarator declaration-list[opt] compound-statement
907 /// [C90] function-definition: [C99 6.7.1] - implicit int result
908 /// [C90]   decl-specs[opt] declarator declaration-list[opt] compound-statement
909 /// [C++] function-definition: [C++ 8.4]
910 ///         decl-specifier-seq[opt] declarator ctor-initializer[opt]
911 ///         function-body
912 /// [C++] function-definition: [C++ 8.4]
913 ///         decl-specifier-seq[opt] declarator function-try-block
914 ///
915 Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
916                                       const ParsedTemplateInfo &TemplateInfo,
917                                       LateParsedAttrList *LateParsedAttrs) {
918   // Poison the SEH identifiers so they are flagged as illegal in function bodies
919   PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
920   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
921 
922   // If this is C90 and the declspecs were completely missing, fudge in an
923   // implicit int.  We do this here because this is the only place where
924   // declaration-specifiers are completely optional in the grammar.
925   if (getLangOpts().ImplicitInt && D.getDeclSpec().isEmpty()) {
926     const char *PrevSpec;
927     unsigned DiagID;
928     D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int,
929                                            D.getIdentifierLoc(),
930                                            PrevSpec, DiagID);
931     D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin());
932   }
933 
934   // If this declaration was formed with a K&R-style identifier list for the
935   // arguments, parse declarations for all of the args next.
936   // int foo(a,b) int a; float b; {}
937   if (FTI.isKNRPrototype())
938     ParseKNRParamDeclarations(D);
939 
940   // We should have either an opening brace or, in a C++ constructor,
941   // we may have a colon.
942   if (Tok.isNot(tok::l_brace) &&
943       (!getLangOpts().CPlusPlus ||
944        (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
945         Tok.isNot(tok::equal)))) {
946     Diag(Tok, diag::err_expected_fn_body);
947 
948     // Skip over garbage, until we get to '{'.  Don't eat the '{'.
949     SkipUntil(tok::l_brace, true, true);
950 
951     // If we didn't find the '{', bail out.
952     if (Tok.isNot(tok::l_brace))
953       return 0;
954   }
955 
956   // Check to make sure that any normal attributes are allowed to be on
957   // a definition.  Late parsed attributes are checked at the end.
958   if (Tok.isNot(tok::equal)) {
959     AttributeList *DtorAttrs = D.getAttributes();
960     while (DtorAttrs) {
961       if (!IsThreadSafetyAttribute(DtorAttrs->getName()->getName()) &&
962           !DtorAttrs->isCXX11Attribute()) {
963         Diag(DtorAttrs->getLoc(), diag::warn_attribute_on_function_definition)
964           << DtorAttrs->getName()->getName();
965       }
966       DtorAttrs = DtorAttrs->getNext();
967     }
968   }
969 
970   // In delayed template parsing mode, for function template we consume the
971   // tokens and store them for late parsing at the end of the translation unit.
972   if (getLangOpts().DelayedTemplateParsing &&
973       Tok.isNot(tok::equal) &&
974       TemplateInfo.Kind == ParsedTemplateInfo::Template) {
975     MultiTemplateParamsArg TemplateParameterLists(*TemplateInfo.TemplateParams);
976 
977     ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
978     Scope *ParentScope = getCurScope()->getParent();
979 
980     D.setFunctionDefinitionKind(FDK_Definition);
981     Decl *DP = Actions.HandleDeclarator(ParentScope, D,
982                                         TemplateParameterLists);
983     D.complete(DP);
984     D.getMutableDeclSpec().abort();
985 
986     if (DP) {
987       LateParsedTemplatedFunction *LPT = new LateParsedTemplatedFunction(DP);
988 
989       FunctionDecl *FnD = 0;
990       if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(DP))
991         FnD = FunTmpl->getTemplatedDecl();
992       else
993         FnD = cast<FunctionDecl>(DP);
994       Actions.CheckForFunctionRedefinition(FnD);
995 
996       LateParsedTemplateMap[FnD] = LPT;
997       Actions.MarkAsLateParsedTemplate(FnD);
998       LexTemplateFunctionForLateParsing(LPT->Toks);
999     } else {
1000       CachedTokens Toks;
1001       LexTemplateFunctionForLateParsing(Toks);
1002     }
1003     return DP;
1004   }
1005   else if (CurParsedObjCImpl &&
1006            !TemplateInfo.TemplateParams &&
1007            (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) ||
1008             Tok.is(tok::colon)) &&
1009       Actions.CurContext->isTranslationUnit()) {
1010     ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
1011     Scope *ParentScope = getCurScope()->getParent();
1012 
1013     D.setFunctionDefinitionKind(FDK_Definition);
1014     Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
1015                                               MultiTemplateParamsArg());
1016     D.complete(FuncDecl);
1017     D.getMutableDeclSpec().abort();
1018     if (FuncDecl) {
1019       // Consume the tokens and store them for later parsing.
1020       StashAwayMethodOrFunctionBodyTokens(FuncDecl);
1021       CurParsedObjCImpl->HasCFunction = true;
1022       return FuncDecl;
1023     }
1024   }
1025 
1026   // Enter a scope for the function body.
1027   ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
1028 
1029   // Tell the actions module that we have entered a function definition with the
1030   // specified Declarator for the function.
1031   Decl *Res = TemplateInfo.TemplateParams?
1032       Actions.ActOnStartOfFunctionTemplateDef(getCurScope(),
1033                                               *TemplateInfo.TemplateParams, D)
1034     : Actions.ActOnStartOfFunctionDef(getCurScope(), D);
1035 
1036   // Break out of the ParsingDeclarator context before we parse the body.
1037   D.complete(Res);
1038 
1039   // Break out of the ParsingDeclSpec context, too.  This const_cast is
1040   // safe because we're always the sole owner.
1041   D.getMutableDeclSpec().abort();
1042 
1043   if (Tok.is(tok::equal)) {
1044     assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='");
1045     ConsumeToken();
1046 
1047     Actions.ActOnFinishFunctionBody(Res, 0, false);
1048 
1049     bool Delete = false;
1050     SourceLocation KWLoc;
1051     if (Tok.is(tok::kw_delete)) {
1052       Diag(Tok, getLangOpts().CPlusPlus11 ?
1053            diag::warn_cxx98_compat_deleted_function :
1054            diag::ext_deleted_function);
1055 
1056       KWLoc = ConsumeToken();
1057       Actions.SetDeclDeleted(Res, KWLoc);
1058       Delete = true;
1059     } else if (Tok.is(tok::kw_default)) {
1060       Diag(Tok, getLangOpts().CPlusPlus11 ?
1061            diag::warn_cxx98_compat_defaulted_function :
1062            diag::ext_defaulted_function);
1063 
1064       KWLoc = ConsumeToken();
1065       Actions.SetDeclDefaulted(Res, KWLoc);
1066     } else {
1067       llvm_unreachable("function definition after = not 'delete' or 'default'");
1068     }
1069 
1070     if (Tok.is(tok::comma)) {
1071       Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
1072         << Delete;
1073       SkipUntil(tok::semi);
1074     } else {
1075       ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
1076                        Delete ? "delete" : "default", tok::semi);
1077     }
1078 
1079     return Res;
1080   }
1081 
1082   if (Tok.is(tok::kw_try))
1083     return ParseFunctionTryBlock(Res, BodyScope);
1084 
1085   // If we have a colon, then we're probably parsing a C++
1086   // ctor-initializer.
1087   if (Tok.is(tok::colon)) {
1088     ParseConstructorInitializer(Res);
1089 
1090     // Recover from error.
1091     if (!Tok.is(tok::l_brace)) {
1092       BodyScope.Exit();
1093       Actions.ActOnFinishFunctionBody(Res, 0);
1094       return Res;
1095     }
1096   } else
1097     Actions.ActOnDefaultCtorInitializers(Res);
1098 
1099   // Late attributes are parsed in the same scope as the function body.
1100   if (LateParsedAttrs)
1101     ParseLexedAttributeList(*LateParsedAttrs, Res, false, true);
1102 
1103   return ParseFunctionStatementBody(Res, BodyScope);
1104 }
1105 
1106 /// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides
1107 /// types for a function with a K&R-style identifier list for arguments.
1108 void Parser::ParseKNRParamDeclarations(Declarator &D) {
1109   // We know that the top-level of this declarator is a function.
1110   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
1111 
1112   // Enter function-declaration scope, limiting any declarators to the
1113   // function prototype scope, including parameter declarators.
1114   ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
1115                             Scope::FunctionDeclarationScope | Scope::DeclScope);
1116 
1117   // Read all the argument declarations.
1118   while (isDeclarationSpecifier()) {
1119     SourceLocation DSStart = Tok.getLocation();
1120 
1121     // Parse the common declaration-specifiers piece.
1122     DeclSpec DS(AttrFactory);
1123     ParseDeclarationSpecifiers(DS);
1124 
1125     // C99 6.9.1p6: 'each declaration in the declaration list shall have at
1126     // least one declarator'.
1127     // NOTE: GCC just makes this an ext-warn.  It's not clear what it does with
1128     // the declarations though.  It's trivial to ignore them, really hard to do
1129     // anything else with them.
1130     if (Tok.is(tok::semi)) {
1131       Diag(DSStart, diag::err_declaration_does_not_declare_param);
1132       ConsumeToken();
1133       continue;
1134     }
1135 
1136     // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other
1137     // than register.
1138     if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1139         DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1140       Diag(DS.getStorageClassSpecLoc(),
1141            diag::err_invalid_storage_class_in_func_decl);
1142       DS.ClearStorageClassSpecs();
1143     }
1144     if (DS.getThreadStorageClassSpec() != DeclSpec::TSCS_unspecified) {
1145       Diag(DS.getThreadStorageClassSpecLoc(),
1146            diag::err_invalid_storage_class_in_func_decl);
1147       DS.ClearStorageClassSpecs();
1148     }
1149 
1150     // Parse the first declarator attached to this declspec.
1151     Declarator ParmDeclarator(DS, Declarator::KNRTypeListContext);
1152     ParseDeclarator(ParmDeclarator);
1153 
1154     // Handle the full declarator list.
1155     while (1) {
1156       // If attributes are present, parse them.
1157       MaybeParseGNUAttributes(ParmDeclarator);
1158 
1159       // Ask the actions module to compute the type for this declarator.
1160       Decl *Param =
1161         Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
1162 
1163       if (Param &&
1164           // A missing identifier has already been diagnosed.
1165           ParmDeclarator.getIdentifier()) {
1166 
1167         // Scan the argument list looking for the correct param to apply this
1168         // type.
1169         for (unsigned i = 0; ; ++i) {
1170           // C99 6.9.1p6: those declarators shall declare only identifiers from
1171           // the identifier list.
1172           if (i == FTI.NumArgs) {
1173             Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
1174               << ParmDeclarator.getIdentifier();
1175             break;
1176           }
1177 
1178           if (FTI.ArgInfo[i].Ident == ParmDeclarator.getIdentifier()) {
1179             // Reject redefinitions of parameters.
1180             if (FTI.ArgInfo[i].Param) {
1181               Diag(ParmDeclarator.getIdentifierLoc(),
1182                    diag::err_param_redefinition)
1183                  << ParmDeclarator.getIdentifier();
1184             } else {
1185               FTI.ArgInfo[i].Param = Param;
1186             }
1187             break;
1188           }
1189         }
1190       }
1191 
1192       // If we don't have a comma, it is either the end of the list (a ';') or
1193       // an error, bail out.
1194       if (Tok.isNot(tok::comma))
1195         break;
1196 
1197       ParmDeclarator.clear();
1198 
1199       // Consume the comma.
1200       ParmDeclarator.setCommaLoc(ConsumeToken());
1201 
1202       // Parse the next declarator.
1203       ParseDeclarator(ParmDeclarator);
1204     }
1205 
1206     if (ExpectAndConsumeSemi(diag::err_expected_semi_declaration)) {
1207       // Skip to end of block or statement
1208       SkipUntil(tok::semi, true);
1209       if (Tok.is(tok::semi))
1210         ConsumeToken();
1211     }
1212   }
1213 
1214   // The actions module must verify that all arguments were declared.
1215   Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation());
1216 }
1217 
1218 
1219 /// ParseAsmStringLiteral - This is just a normal string-literal, but is not
1220 /// allowed to be a wide string, and is not subject to character translation.
1221 ///
1222 /// [GNU] asm-string-literal:
1223 ///         string-literal
1224 ///
1225 Parser::ExprResult Parser::ParseAsmStringLiteral() {
1226   switch (Tok.getKind()) {
1227     case tok::string_literal:
1228       break;
1229     case tok::utf8_string_literal:
1230     case tok::utf16_string_literal:
1231     case tok::utf32_string_literal:
1232     case tok::wide_string_literal: {
1233       SourceLocation L = Tok.getLocation();
1234       Diag(Tok, diag::err_asm_operand_wide_string_literal)
1235         << (Tok.getKind() == tok::wide_string_literal)
1236         << SourceRange(L, L);
1237       return ExprError();
1238     }
1239     default:
1240       Diag(Tok, diag::err_expected_string_literal)
1241         << /*Source='in...'*/0 << "'asm'";
1242       return ExprError();
1243   }
1244 
1245   return ParseStringLiteralExpression();
1246 }
1247 
1248 /// ParseSimpleAsm
1249 ///
1250 /// [GNU] simple-asm-expr:
1251 ///         'asm' '(' asm-string-literal ')'
1252 ///
1253 Parser::ExprResult Parser::ParseSimpleAsm(SourceLocation *EndLoc) {
1254   assert(Tok.is(tok::kw_asm) && "Not an asm!");
1255   SourceLocation Loc = ConsumeToken();
1256 
1257   if (Tok.is(tok::kw_volatile)) {
1258     // Remove from the end of 'asm' to the end of 'volatile'.
1259     SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
1260                              PP.getLocForEndOfToken(Tok.getLocation()));
1261 
1262     Diag(Tok, diag::warn_file_asm_volatile)
1263       << FixItHint::CreateRemoval(RemovalRange);
1264     ConsumeToken();
1265   }
1266 
1267   BalancedDelimiterTracker T(*this, tok::l_paren);
1268   if (T.consumeOpen()) {
1269     Diag(Tok, diag::err_expected_lparen_after) << "asm";
1270     return ExprError();
1271   }
1272 
1273   ExprResult Result(ParseAsmStringLiteral());
1274 
1275   if (Result.isInvalid()) {
1276     SkipUntil(tok::r_paren, true, true);
1277     if (EndLoc)
1278       *EndLoc = Tok.getLocation();
1279     ConsumeAnyToken();
1280   } else {
1281     // Close the paren and get the location of the end bracket
1282     T.consumeClose();
1283     if (EndLoc)
1284       *EndLoc = T.getCloseLocation();
1285   }
1286 
1287   return Result;
1288 }
1289 
1290 /// \brief Get the TemplateIdAnnotation from the token and put it in the
1291 /// cleanup pool so that it gets destroyed when parsing the current top level
1292 /// declaration is finished.
1293 TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) {
1294   assert(tok.is(tok::annot_template_id) && "Expected template-id token");
1295   TemplateIdAnnotation *
1296       Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue());
1297   return Id;
1298 }
1299 
1300 void Parser::AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation) {
1301   // Push the current token back into the token stream (or revert it if it is
1302   // cached) and use an annotation scope token for current token.
1303   if (PP.isBacktrackEnabled())
1304     PP.RevertCachedTokens(1);
1305   else
1306     PP.EnterToken(Tok);
1307   Tok.setKind(tok::annot_cxxscope);
1308   Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
1309   Tok.setAnnotationRange(SS.getRange());
1310 
1311   // In case the tokens were cached, have Preprocessor replace them
1312   // with the annotation token.  We don't need to do this if we've
1313   // just reverted back to a prior state.
1314   if (IsNewAnnotation)
1315     PP.AnnotateCachedTokens(Tok);
1316 }
1317 
1318 /// \brief Attempt to classify the name at the current token position. This may
1319 /// form a type, scope or primary expression annotation, or replace the token
1320 /// with a typo-corrected keyword. This is only appropriate when the current
1321 /// name must refer to an entity which has already been declared.
1322 ///
1323 /// \param IsAddressOfOperand Must be \c true if the name is preceded by an '&'
1324 ///        and might possibly have a dependent nested name specifier.
1325 /// \param CCC Indicates how to perform typo-correction for this name. If NULL,
1326 ///        no typo correction will be performed.
1327 Parser::AnnotatedNameKind
1328 Parser::TryAnnotateName(bool IsAddressOfOperand,
1329                         CorrectionCandidateCallback *CCC) {
1330   assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
1331 
1332   const bool EnteringContext = false;
1333   const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1334 
1335   CXXScopeSpec SS;
1336   if (getLangOpts().CPlusPlus &&
1337       ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
1338     return ANK_Error;
1339 
1340   if (Tok.isNot(tok::identifier) || SS.isInvalid()) {
1341     if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, false, SS,
1342                                                   !WasScopeAnnotation))
1343       return ANK_Error;
1344     return ANK_Unresolved;
1345   }
1346 
1347   IdentifierInfo *Name = Tok.getIdentifierInfo();
1348   SourceLocation NameLoc = Tok.getLocation();
1349 
1350   // FIXME: Move the tentative declaration logic into ClassifyName so we can
1351   // typo-correct to tentatively-declared identifiers.
1352   if (isTentativelyDeclared(Name)) {
1353     // Identifier has been tentatively declared, and thus cannot be resolved as
1354     // an expression. Fall back to annotating it as a type.
1355     if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, false, SS,
1356                                                   !WasScopeAnnotation))
1357       return ANK_Error;
1358     return Tok.is(tok::annot_typename) ? ANK_Success : ANK_TentativeDecl;
1359   }
1360 
1361   Token Next = NextToken();
1362 
1363   // Look up and classify the identifier. We don't perform any typo-correction
1364   // after a scope specifier, because in general we can't recover from typos
1365   // there (eg, after correcting 'A::tempalte B<X>::C', we would need to jump
1366   // back into scope specifier parsing).
1367   Sema::NameClassification Classification
1368     = Actions.ClassifyName(getCurScope(), SS, Name, NameLoc, Next,
1369                            IsAddressOfOperand, SS.isEmpty() ? CCC : 0);
1370 
1371   switch (Classification.getKind()) {
1372   case Sema::NC_Error:
1373     return ANK_Error;
1374 
1375   case Sema::NC_Keyword:
1376     // The identifier was typo-corrected to a keyword.
1377     Tok.setIdentifierInfo(Name);
1378     Tok.setKind(Name->getTokenID());
1379     PP.TypoCorrectToken(Tok);
1380     if (SS.isNotEmpty())
1381       AnnotateScopeToken(SS, !WasScopeAnnotation);
1382     // We've "annotated" this as a keyword.
1383     return ANK_Success;
1384 
1385   case Sema::NC_Unknown:
1386     // It's not something we know about. Leave it unannotated.
1387     break;
1388 
1389   case Sema::NC_Type:
1390     Tok.setKind(tok::annot_typename);
1391     setTypeAnnotation(Tok, Classification.getType());
1392     Tok.setAnnotationEndLoc(NameLoc);
1393     if (SS.isNotEmpty())
1394       Tok.setLocation(SS.getBeginLoc());
1395     PP.AnnotateCachedTokens(Tok);
1396     return ANK_Success;
1397 
1398   case Sema::NC_Expression:
1399     Tok.setKind(tok::annot_primary_expr);
1400     setExprAnnotation(Tok, Classification.getExpression());
1401     Tok.setAnnotationEndLoc(NameLoc);
1402     if (SS.isNotEmpty())
1403       Tok.setLocation(SS.getBeginLoc());
1404     PP.AnnotateCachedTokens(Tok);
1405     return ANK_Success;
1406 
1407   case Sema::NC_TypeTemplate:
1408     if (Next.isNot(tok::less)) {
1409       // This may be a type template being used as a template template argument.
1410       if (SS.isNotEmpty())
1411         AnnotateScopeToken(SS, !WasScopeAnnotation);
1412       return ANK_TemplateName;
1413     }
1414     // Fall through.
1415   case Sema::NC_FunctionTemplate: {
1416     // We have a type or function template followed by '<'.
1417     ConsumeToken();
1418     UnqualifiedId Id;
1419     Id.setIdentifier(Name, NameLoc);
1420     if (AnnotateTemplateIdToken(
1421             TemplateTy::make(Classification.getTemplateName()),
1422             Classification.getTemplateNameKind(), SS, SourceLocation(), Id))
1423       return ANK_Error;
1424     return ANK_Success;
1425   }
1426 
1427   case Sema::NC_NestedNameSpecifier:
1428     llvm_unreachable("already parsed nested name specifier");
1429   }
1430 
1431   // Unable to classify the name, but maybe we can annotate a scope specifier.
1432   if (SS.isNotEmpty())
1433     AnnotateScopeToken(SS, !WasScopeAnnotation);
1434   return ANK_Unresolved;
1435 }
1436 
1437 /// TryAnnotateTypeOrScopeToken - If the current token position is on a
1438 /// typename (possibly qualified in C++) or a C++ scope specifier not followed
1439 /// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
1440 /// with a single annotation token representing the typename or C++ scope
1441 /// respectively.
1442 /// This simplifies handling of C++ scope specifiers and allows efficient
1443 /// backtracking without the need to re-parse and resolve nested-names and
1444 /// typenames.
1445 /// It will mainly be called when we expect to treat identifiers as typenames
1446 /// (if they are typenames). For example, in C we do not expect identifiers
1447 /// inside expressions to be treated as typenames so it will not be called
1448 /// for expressions in C.
1449 /// The benefit for C/ObjC is that a typename will be annotated and
1450 /// Actions.getTypeName will not be needed to be called again (e.g. getTypeName
1451 /// will not be called twice, once to check whether we have a declaration
1452 /// specifier, and another one to get the actual type inside
1453 /// ParseDeclarationSpecifiers).
1454 ///
1455 /// This returns true if an error occurred.
1456 ///
1457 /// Note that this routine emits an error if you call it with ::new or ::delete
1458 /// as the current tokens, so only call it in contexts where these are invalid.
1459 bool Parser::TryAnnotateTypeOrScopeToken(bool EnteringContext, bool NeedType) {
1460   assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon)
1461           || Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope)
1462           || Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id))
1463           && "Cannot be a type or scope token!");
1464 
1465   if (Tok.is(tok::kw_typename)) {
1466     // Parse a C++ typename-specifier, e.g., "typename T::type".
1467     //
1468     //   typename-specifier:
1469     //     'typename' '::' [opt] nested-name-specifier identifier
1470     //     'typename' '::' [opt] nested-name-specifier template [opt]
1471     //            simple-template-id
1472     SourceLocation TypenameLoc = ConsumeToken();
1473     CXXScopeSpec SS;
1474     if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/ParsedType(),
1475                                        /*EnteringContext=*/false,
1476                                        0, /*IsTypename*/true))
1477       return true;
1478     if (!SS.isSet()) {
1479       if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) ||
1480           Tok.is(tok::annot_decltype)) {
1481         // Attempt to recover by skipping the invalid 'typename'
1482         if (Tok.is(tok::annot_decltype) ||
1483             (!TryAnnotateTypeOrScopeToken(EnteringContext, NeedType) &&
1484             Tok.isAnnotation())) {
1485           unsigned DiagID = diag::err_expected_qualified_after_typename;
1486           // MS compatibility: MSVC permits using known types with typename.
1487           // e.g. "typedef typename T* pointer_type"
1488           if (getLangOpts().MicrosoftExt)
1489             DiagID = diag::warn_expected_qualified_after_typename;
1490           Diag(Tok.getLocation(), DiagID);
1491           return false;
1492         }
1493       }
1494 
1495       Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
1496       return true;
1497     }
1498 
1499     TypeResult Ty;
1500     if (Tok.is(tok::identifier)) {
1501       // FIXME: check whether the next token is '<', first!
1502       Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
1503                                      *Tok.getIdentifierInfo(),
1504                                      Tok.getLocation());
1505     } else if (Tok.is(tok::annot_template_id)) {
1506       TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1507       if (TemplateId->Kind == TNK_Function_template) {
1508         Diag(Tok, diag::err_typename_refers_to_non_type_template)
1509           << Tok.getAnnotationRange();
1510         return true;
1511       }
1512 
1513       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1514                                          TemplateId->NumArgs);
1515 
1516       Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
1517                                      TemplateId->TemplateKWLoc,
1518                                      TemplateId->Template,
1519                                      TemplateId->TemplateNameLoc,
1520                                      TemplateId->LAngleLoc,
1521                                      TemplateArgsPtr,
1522                                      TemplateId->RAngleLoc);
1523     } else {
1524       Diag(Tok, diag::err_expected_type_name_after_typename)
1525         << SS.getRange();
1526       return true;
1527     }
1528 
1529     SourceLocation EndLoc = Tok.getLastLoc();
1530     Tok.setKind(tok::annot_typename);
1531     setTypeAnnotation(Tok, Ty.isInvalid() ? ParsedType() : Ty.get());
1532     Tok.setAnnotationEndLoc(EndLoc);
1533     Tok.setLocation(TypenameLoc);
1534     PP.AnnotateCachedTokens(Tok);
1535     return false;
1536   }
1537 
1538   // Remembers whether the token was originally a scope annotation.
1539   bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1540 
1541   CXXScopeSpec SS;
1542   if (getLangOpts().CPlusPlus)
1543     if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
1544       return true;
1545 
1546   return TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, NeedType,
1547                                                    SS, !WasScopeAnnotation);
1548 }
1549 
1550 /// \brief Try to annotate a type or scope token, having already parsed an
1551 /// optional scope specifier. \p IsNewScope should be \c true unless the scope
1552 /// specifier was extracted from an existing tok::annot_cxxscope annotation.
1553 bool Parser::TryAnnotateTypeOrScopeTokenAfterScopeSpec(bool EnteringContext,
1554                                                        bool NeedType,
1555                                                        CXXScopeSpec &SS,
1556                                                        bool IsNewScope) {
1557   if (Tok.is(tok::identifier)) {
1558     IdentifierInfo *CorrectedII = 0;
1559     // Determine whether the identifier is a type name.
1560     if (ParsedType Ty = Actions.getTypeName(*Tok.getIdentifierInfo(),
1561                                             Tok.getLocation(), getCurScope(),
1562                                             &SS, false,
1563                                             NextToken().is(tok::period),
1564                                             ParsedType(),
1565                                             /*IsCtorOrDtorName=*/false,
1566                                             /*NonTrivialTypeSourceInfo*/true,
1567                                             NeedType ? &CorrectedII : NULL)) {
1568       // A FixIt was applied as a result of typo correction
1569       if (CorrectedII)
1570         Tok.setIdentifierInfo(CorrectedII);
1571       // This is a typename. Replace the current token in-place with an
1572       // annotation type token.
1573       Tok.setKind(tok::annot_typename);
1574       setTypeAnnotation(Tok, Ty);
1575       Tok.setAnnotationEndLoc(Tok.getLocation());
1576       if (SS.isNotEmpty()) // it was a C++ qualified type name.
1577         Tok.setLocation(SS.getBeginLoc());
1578 
1579       // In case the tokens were cached, have Preprocessor replace
1580       // them with the annotation token.
1581       PP.AnnotateCachedTokens(Tok);
1582       return false;
1583     }
1584 
1585     if (!getLangOpts().CPlusPlus) {
1586       // If we're in C, we can't have :: tokens at all (the lexer won't return
1587       // them).  If the identifier is not a type, then it can't be scope either,
1588       // just early exit.
1589       return false;
1590     }
1591 
1592     // If this is a template-id, annotate with a template-id or type token.
1593     if (NextToken().is(tok::less)) {
1594       TemplateTy Template;
1595       UnqualifiedId TemplateName;
1596       TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1597       bool MemberOfUnknownSpecialization;
1598       if (TemplateNameKind TNK
1599           = Actions.isTemplateName(getCurScope(), SS,
1600                                    /*hasTemplateKeyword=*/false, TemplateName,
1601                                    /*ObjectType=*/ ParsedType(),
1602                                    EnteringContext,
1603                                    Template, MemberOfUnknownSpecialization)) {
1604         // Consume the identifier.
1605         ConsumeToken();
1606         if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
1607                                     TemplateName)) {
1608           // If an unrecoverable error occurred, we need to return true here,
1609           // because the token stream is in a damaged state.  We may not return
1610           // a valid identifier.
1611           return true;
1612         }
1613       }
1614     }
1615 
1616     // The current token, which is either an identifier or a
1617     // template-id, is not part of the annotation. Fall through to
1618     // push that token back into the stream and complete the C++ scope
1619     // specifier annotation.
1620   }
1621 
1622   if (Tok.is(tok::annot_template_id)) {
1623     TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1624     if (TemplateId->Kind == TNK_Type_template) {
1625       // A template-id that refers to a type was parsed into a
1626       // template-id annotation in a context where we weren't allowed
1627       // to produce a type annotation token. Update the template-id
1628       // annotation token to a type annotation token now.
1629       AnnotateTemplateIdTokenAsType();
1630       return false;
1631     }
1632   }
1633 
1634   if (SS.isEmpty())
1635     return false;
1636 
1637   // A C++ scope specifier that isn't followed by a typename.
1638   AnnotateScopeToken(SS, IsNewScope);
1639   return false;
1640 }
1641 
1642 /// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only
1643 /// annotates C++ scope specifiers and template-ids.  This returns
1644 /// true if there was an error that could not be recovered from.
1645 ///
1646 /// Note that this routine emits an error if you call it with ::new or ::delete
1647 /// as the current tokens, so only call it in contexts where these are invalid.
1648 bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) {
1649   assert(getLangOpts().CPlusPlus &&
1650          "Call sites of this function should be guarded by checking for C++");
1651   assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1652           (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) ||
1653          Tok.is(tok::kw_decltype)) && "Cannot be a type or scope token!");
1654 
1655   CXXScopeSpec SS;
1656   if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
1657     return true;
1658   if (SS.isEmpty())
1659     return false;
1660 
1661   AnnotateScopeToken(SS, true);
1662   return false;
1663 }
1664 
1665 bool Parser::isTokenEqualOrEqualTypo() {
1666   tok::TokenKind Kind = Tok.getKind();
1667   switch (Kind) {
1668   default:
1669     return false;
1670   case tok::ampequal:            // &=
1671   case tok::starequal:           // *=
1672   case tok::plusequal:           // +=
1673   case tok::minusequal:          // -=
1674   case tok::exclaimequal:        // !=
1675   case tok::slashequal:          // /=
1676   case tok::percentequal:        // %=
1677   case tok::lessequal:           // <=
1678   case tok::lesslessequal:       // <<=
1679   case tok::greaterequal:        // >=
1680   case tok::greatergreaterequal: // >>=
1681   case tok::caretequal:          // ^=
1682   case tok::pipeequal:           // |=
1683   case tok::equalequal:          // ==
1684     Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal)
1685       << getTokenSimpleSpelling(Kind)
1686       << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()), "=");
1687   case tok::equal:
1688     return true;
1689   }
1690 }
1691 
1692 SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
1693   assert(Tok.is(tok::code_completion));
1694   PrevTokLocation = Tok.getLocation();
1695 
1696   for (Scope *S = getCurScope(); S; S = S->getParent()) {
1697     if (S->getFlags() & Scope::FnScope) {
1698       Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_RecoveryInFunction);
1699       cutOffParsing();
1700       return PrevTokLocation;
1701     }
1702 
1703     if (S->getFlags() & Scope::ClassScope) {
1704       Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class);
1705       cutOffParsing();
1706       return PrevTokLocation;
1707     }
1708   }
1709 
1710   Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace);
1711   cutOffParsing();
1712   return PrevTokLocation;
1713 }
1714 
1715 // Anchor the Parser::FieldCallback vtable to this translation unit.
1716 // We use a spurious method instead of the destructor because
1717 // destroying FieldCallbacks can actually be slightly
1718 // performance-sensitive.
1719 void Parser::FieldCallback::_anchor() {
1720 }
1721 
1722 // Code-completion pass-through functions
1723 
1724 void Parser::CodeCompleteDirective(bool InConditional) {
1725   Actions.CodeCompletePreprocessorDirective(InConditional);
1726 }
1727 
1728 void Parser::CodeCompleteInConditionalExclusion() {
1729   Actions.CodeCompleteInPreprocessorConditionalExclusion(getCurScope());
1730 }
1731 
1732 void Parser::CodeCompleteMacroName(bool IsDefinition) {
1733   Actions.CodeCompletePreprocessorMacroName(IsDefinition);
1734 }
1735 
1736 void Parser::CodeCompletePreprocessorExpression() {
1737   Actions.CodeCompletePreprocessorExpression();
1738 }
1739 
1740 void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro,
1741                                        MacroInfo *MacroInfo,
1742                                        unsigned ArgumentIndex) {
1743   Actions.CodeCompletePreprocessorMacroArgument(getCurScope(), Macro, MacroInfo,
1744                                                 ArgumentIndex);
1745 }
1746 
1747 void Parser::CodeCompleteNaturalLanguage() {
1748   Actions.CodeCompleteNaturalLanguage();
1749 }
1750 
1751 bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) {
1752   assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
1753          "Expected '__if_exists' or '__if_not_exists'");
1754   Result.IsIfExists = Tok.is(tok::kw___if_exists);
1755   Result.KeywordLoc = ConsumeToken();
1756 
1757   BalancedDelimiterTracker T(*this, tok::l_paren);
1758   if (T.consumeOpen()) {
1759     Diag(Tok, diag::err_expected_lparen_after)
1760       << (Result.IsIfExists? "__if_exists" : "__if_not_exists");
1761     return true;
1762   }
1763 
1764   // Parse nested-name-specifier.
1765   ParseOptionalCXXScopeSpecifier(Result.SS, ParsedType(),
1766                                  /*EnteringContext=*/false);
1767 
1768   // Check nested-name specifier.
1769   if (Result.SS.isInvalid()) {
1770     T.skipToEnd();
1771     return true;
1772   }
1773 
1774   // Parse the unqualified-id.
1775   SourceLocation TemplateKWLoc; // FIXME: parsed, but unused.
1776   if (ParseUnqualifiedId(Result.SS, false, true, true, ParsedType(),
1777                          TemplateKWLoc, Result.Name)) {
1778     T.skipToEnd();
1779     return true;
1780   }
1781 
1782   if (T.consumeClose())
1783     return true;
1784 
1785   // Check if the symbol exists.
1786   switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc,
1787                                                Result.IsIfExists, Result.SS,
1788                                                Result.Name)) {
1789   case Sema::IER_Exists:
1790     Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip;
1791     break;
1792 
1793   case Sema::IER_DoesNotExist:
1794     Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip;
1795     break;
1796 
1797   case Sema::IER_Dependent:
1798     Result.Behavior = IEB_Dependent;
1799     break;
1800 
1801   case Sema::IER_Error:
1802     return true;
1803   }
1804 
1805   return false;
1806 }
1807 
1808 void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
1809   IfExistsCondition Result;
1810   if (ParseMicrosoftIfExistsCondition(Result))
1811     return;
1812 
1813   BalancedDelimiterTracker Braces(*this, tok::l_brace);
1814   if (Braces.consumeOpen()) {
1815     Diag(Tok, diag::err_expected_lbrace);
1816     return;
1817   }
1818 
1819   switch (Result.Behavior) {
1820   case IEB_Parse:
1821     // Parse declarations below.
1822     break;
1823 
1824   case IEB_Dependent:
1825     llvm_unreachable("Cannot have a dependent external declaration");
1826 
1827   case IEB_Skip:
1828     Braces.skipToEnd();
1829     return;
1830   }
1831 
1832   // Parse the declarations.
1833   while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
1834     ParsedAttributesWithRange attrs(AttrFactory);
1835     MaybeParseCXX11Attributes(attrs);
1836     MaybeParseMicrosoftAttributes(attrs);
1837     DeclGroupPtrTy Result = ParseExternalDeclaration(attrs);
1838     if (Result && !getCurScope()->getParent())
1839       Actions.getASTConsumer().HandleTopLevelDecl(Result.get());
1840   }
1841   Braces.consumeClose();
1842 }
1843 
1844 Parser::DeclGroupPtrTy Parser::ParseModuleImport(SourceLocation AtLoc) {
1845   assert(Tok.isObjCAtKeyword(tok::objc_import) &&
1846          "Improper start to module import");
1847   SourceLocation ImportLoc = ConsumeToken();
1848 
1849   SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
1850 
1851   // Parse the module path.
1852   do {
1853     if (!Tok.is(tok::identifier)) {
1854       if (Tok.is(tok::code_completion)) {
1855         Actions.CodeCompleteModuleImport(ImportLoc, Path);
1856         ConsumeCodeCompletionToken();
1857         SkipUntil(tok::semi);
1858         return DeclGroupPtrTy();
1859       }
1860 
1861       Diag(Tok, diag::err_module_expected_ident);
1862       SkipUntil(tok::semi);
1863       return DeclGroupPtrTy();
1864     }
1865 
1866     // Record this part of the module path.
1867     Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation()));
1868     ConsumeToken();
1869 
1870     if (Tok.is(tok::period)) {
1871       ConsumeToken();
1872       continue;
1873     }
1874 
1875     break;
1876   } while (true);
1877 
1878   DeclResult Import = Actions.ActOnModuleImport(AtLoc, ImportLoc, Path);
1879   ExpectAndConsumeSemi(diag::err_module_expected_semi);
1880   if (Import.isInvalid())
1881     return DeclGroupPtrTy();
1882 
1883   return Actions.ConvertDeclToDeclGroup(Import.get());
1884 }
1885 
1886 bool BalancedDelimiterTracker::diagnoseOverflow() {
1887   P.Diag(P.Tok, diag::err_bracket_depth_exceeded)
1888     << P.getLangOpts().BracketDepth;
1889   P.Diag(P.Tok, diag::note_bracket_depth);
1890   P.SkipUntil(tok::eof);
1891   return true;
1892 }
1893 
1894 bool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID,
1895                                             const char *Msg,
1896                                             tok::TokenKind SkipToToc ) {
1897   LOpen = P.Tok.getLocation();
1898   if (P.ExpectAndConsume(Kind, DiagID, Msg, SkipToToc))
1899     return true;
1900 
1901   if (getDepth() < MaxDepth)
1902     return false;
1903 
1904   return diagnoseOverflow();
1905 }
1906 
1907 bool BalancedDelimiterTracker::diagnoseMissingClose() {
1908   assert(!P.Tok.is(Close) && "Should have consumed closing delimiter");
1909 
1910   const char *LHSName = "unknown";
1911   diag::kind DID;
1912   switch (Close) {
1913   default: llvm_unreachable("Unexpected balanced token");
1914   case tok::r_paren : LHSName = "("; DID = diag::err_expected_rparen; break;
1915   case tok::r_brace : LHSName = "{"; DID = diag::err_expected_rbrace; break;
1916   case tok::r_square: LHSName = "["; DID = diag::err_expected_rsquare; break;
1917   }
1918   P.Diag(P.Tok, DID);
1919   P.Diag(LOpen, diag::note_matching) << LHSName;
1920   if (P.SkipUntil(Close, /*StopAtSemi*/ true, /*DontConsume*/ true))
1921     LClose = P.ConsumeAnyToken();
1922   return true;
1923 }
1924 
1925 void BalancedDelimiterTracker::skipToEnd() {
1926   P.SkipUntil(Close, false);
1927 }
1928