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