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