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