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