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