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