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