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