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