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