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