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