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