Path: blob/main/contrib/llvm-project/clang/lib/Parse/Parser.cpp
35233 views
//===--- Parser.cpp - C Language Family Parser ----------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements the Parser interfaces.9//10//===----------------------------------------------------------------------===//1112#include "clang/Parse/Parser.h"13#include "clang/AST/ASTConsumer.h"14#include "clang/AST/ASTContext.h"15#include "clang/AST/ASTLambda.h"16#include "clang/AST/DeclTemplate.h"17#include "clang/Basic/FileManager.h"18#include "clang/Parse/ParseDiagnostic.h"19#include "clang/Parse/RAIIObjectsForParser.h"20#include "clang/Sema/DeclSpec.h"21#include "clang/Sema/ParsedTemplate.h"22#include "clang/Sema/Scope.h"23#include "clang/Sema/SemaCodeCompletion.h"24#include "llvm/Support/Path.h"25#include "llvm/Support/TimeProfiler.h"26using namespace clang;272829namespace {30/// A comment handler that passes comments found by the preprocessor31/// to the parser action.32class ActionCommentHandler : public CommentHandler {33Sema &S;3435public:36explicit ActionCommentHandler(Sema &S) : S(S) { }3738bool HandleComment(Preprocessor &PP, SourceRange Comment) override {39S.ActOnComment(Comment);40return false;41}42};43} // end anonymous namespace4445IdentifierInfo *Parser::getSEHExceptKeyword() {46// __except is accepted as a (contextual) keyword47if (!Ident__except && (getLangOpts().MicrosoftExt || getLangOpts().Borland))48Ident__except = PP.getIdentifierInfo("__except");4950return Ident__except;51}5253Parser::Parser(Preprocessor &pp, Sema &actions, bool skipFunctionBodies)54: PP(pp), PreferredType(pp.isCodeCompletionEnabled()), Actions(actions),55Diags(PP.getDiagnostics()), GreaterThanIsOperator(true),56ColonIsSacred(false), InMessageExpression(false),57TemplateParameterDepth(0), ParsingInObjCContainer(false) {58SkipFunctionBodies = pp.isCodeCompletionEnabled() || skipFunctionBodies;59Tok.startToken();60Tok.setKind(tok::eof);61Actions.CurScope = nullptr;62NumCachedScopes = 0;63CurParsedObjCImpl = nullptr;6465// Add #pragma handlers. These are removed and destroyed in the66// destructor.67initializePragmaHandlers();6869CommentSemaHandler.reset(new ActionCommentHandler(actions));70PP.addCommentHandler(CommentSemaHandler.get());7172PP.setCodeCompletionHandler(*this);7374Actions.ParseTypeFromStringCallback =75[this](StringRef TypeStr, StringRef Context, SourceLocation IncludeLoc) {76return this->ParseTypeFromString(TypeStr, Context, IncludeLoc);77};78}7980DiagnosticBuilder Parser::Diag(SourceLocation Loc, unsigned DiagID) {81return Diags.Report(Loc, DiagID);82}8384DiagnosticBuilder Parser::Diag(const Token &Tok, unsigned DiagID) {85return Diag(Tok.getLocation(), DiagID);86}8788/// Emits a diagnostic suggesting parentheses surrounding a89/// 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,95SourceRange ParenRange) {96SourceLocation EndLoc = PP.getLocForEndOfToken(ParenRange.getEnd());97if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {98// We can't display the parentheses, so just dig the99// warning/error and return.100Diag(Loc, DK);101return;102}103104Diag(Loc, DK)105<< FixItHint::CreateInsertion(ParenRange.getBegin(), "(")106<< FixItHint::CreateInsertion(EndLoc, ")");107}108109static bool IsCommonTypo(tok::TokenKind ExpectedTok, const Token &Tok) {110switch (ExpectedTok) {111case tok::semi:112return Tok.is(tok::colon) || Tok.is(tok::comma); // : or , for ;113default: return false;114}115}116117bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID,118StringRef Msg) {119if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) {120ConsumeAnyToken();121return false;122}123124// Detect common single-character typos and resume.125if (IsCommonTypo(ExpectedTok, Tok)) {126SourceLocation Loc = Tok.getLocation();127{128DiagnosticBuilder DB = Diag(Loc, DiagID);129DB << FixItHint::CreateReplacement(130SourceRange(Loc), tok::getPunctuatorSpelling(ExpectedTok));131if (DiagID == diag::err_expected)132DB << ExpectedTok;133else if (DiagID == diag::err_expected_after)134DB << Msg << ExpectedTok;135else136DB << Msg;137}138139// Pretend there wasn't a problem.140ConsumeAnyToken();141return false;142}143144SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);145const char *Spelling = nullptr;146if (EndLoc.isValid())147Spelling = tok::getPunctuatorSpelling(ExpectedTok);148149DiagnosticBuilder DB =150Spelling151? Diag(EndLoc, DiagID) << FixItHint::CreateInsertion(EndLoc, Spelling)152: Diag(Tok, DiagID);153if (DiagID == diag::err_expected)154DB << ExpectedTok;155else if (DiagID == diag::err_expected_after)156DB << Msg << ExpectedTok;157else158DB << Msg;159160return true;161}162163bool Parser::ExpectAndConsumeSemi(unsigned DiagID, StringRef TokenUsed) {164if (TryConsumeToken(tok::semi))165return false;166167if (Tok.is(tok::code_completion)) {168handleUnexpectedCodeCompletionToken();169return false;170}171172if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) &&173NextToken().is(tok::semi)) {174Diag(Tok, diag::err_extraneous_token_before_semi)175<< PP.getSpelling(Tok)176<< FixItHint::CreateRemoval(Tok.getLocation());177ConsumeAnyToken(); // The ')' or ']'.178ConsumeToken(); // The ';'.179return false;180}181182return ExpectAndConsume(tok::semi, DiagID , TokenUsed);183}184185void Parser::ConsumeExtraSemi(ExtraSemiKind Kind, DeclSpec::TST TST) {186if (!Tok.is(tok::semi)) return;187188bool HadMultipleSemis = false;189SourceLocation StartLoc = Tok.getLocation();190SourceLocation EndLoc = Tok.getLocation();191ConsumeToken();192193while ((Tok.is(tok::semi) && !Tok.isAtStartOfLine())) {194HadMultipleSemis = true;195EndLoc = Tok.getLocation();196ConsumeToken();197}198199// C++11 allows extra semicolons at namespace scope, but not in any of the200// other contexts.201if (Kind == OutsideFunction && getLangOpts().CPlusPlus) {202if (getLangOpts().CPlusPlus11)203Diag(StartLoc, diag::warn_cxx98_compat_top_level_semi)204<< FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));205else206Diag(StartLoc, diag::ext_extra_semi_cxx11)207<< FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));208return;209}210211if (Kind != AfterMemberFunctionDefinition || HadMultipleSemis)212Diag(StartLoc, diag::ext_extra_semi)213<< Kind << DeclSpec::getSpecifierName(TST,214Actions.getASTContext().getPrintingPolicy())215<< FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));216else217// A single semicolon is valid after a member function definition.218Diag(StartLoc, diag::warn_extra_semi_after_mem_fn_def)219<< FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));220}221222bool Parser::expectIdentifier() {223if (Tok.is(tok::identifier))224return false;225if (const auto *II = Tok.getIdentifierInfo()) {226if (II->isCPlusPlusKeyword(getLangOpts())) {227Diag(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.230return false;231}232}233Diag(Tok, diag::err_expected) << tok::identifier;234return true;235}236237void Parser::checkCompoundToken(SourceLocation FirstTokLoc,238tok::TokenKind FirstTokKind, CompoundToken Op) {239if (FirstTokLoc.isInvalid())240return;241SourceLocation SecondTokLoc = Tok.getLocation();242243// If either token is in a macro, we expect both tokens to come from the same244// macro expansion.245if ((FirstTokLoc.isMacroID() || SecondTokLoc.isMacroID()) &&246PP.getSourceManager().getFileID(FirstTokLoc) !=247PP.getSourceManager().getFileID(SecondTokLoc)) {248Diag(FirstTokLoc, diag::warn_compound_token_split_by_macro)249<< (FirstTokKind == Tok.getKind()) << FirstTokKind << Tok.getKind()250<< static_cast<int>(Op) << SourceRange(FirstTokLoc);251Diag(SecondTokLoc, diag::note_compound_token_split_second_token_here)252<< (FirstTokKind == Tok.getKind()) << Tok.getKind()253<< SourceRange(SecondTokLoc);254return;255}256257// We expect the tokens to abut.258if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {259SourceLocation SpaceLoc = PP.getLocForEndOfToken(FirstTokLoc);260if (SpaceLoc.isInvalid())261SpaceLoc = FirstTokLoc;262Diag(SpaceLoc, diag::warn_compound_token_split_by_whitespace)263<< (FirstTokKind == Tok.getKind()) << FirstTokKind << Tok.getKind()264<< static_cast<int>(Op) << SourceRange(FirstTokLoc, SecondTokLoc);265return;266}267}268269//===----------------------------------------------------------------------===//270// Error recovery.271//===----------------------------------------------------------------------===//272273static bool HasFlagsSet(Parser::SkipUntilFlags L, Parser::SkipUntilFlags R) {274return (static_cast<unsigned>(L) & static_cast<unsigned>(R)) != 0;275}276277/// SkipUntil - Read tokens until we get to the specified token, then consume278/// it (unless no flag StopBeforeMatch). Because we cannot guarantee that the279/// token will ever occur, this skips to the next token, or to some likely280/// 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 it284/// 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 token287// isn't T and if not at EOF.288bool isFirstTokenSkipped = true;289while (true) {290// If we found one of the tokens, stop and return true.291for (unsigned i = 0, NumToks = Toks.size(); i != NumToks; ++i) {292if (Tok.is(Toks[i])) {293if (HasFlagsSet(Flags, StopBeforeMatch)) {294// Noop, don't consume the token.295} else {296ConsumeAnyToken();297}298return true;299}300}301302// Important special case: The caller has given up and just wants us to303// skip the rest of the file. Do this without recursing, since we can304// get here precisely because the caller detected too much recursion.305if (Toks.size() == 1 && Toks[0] == tok::eof &&306!HasFlagsSet(Flags, StopAtSemi) &&307!HasFlagsSet(Flags, StopAtCodeCompletion)) {308while (Tok.isNot(tok::eof))309ConsumeAnyToken();310return true;311}312313switch (Tok.getKind()) {314case tok::eof:315// Ran out of tokens.316return false;317318case tok::annot_pragma_openmp:319case tok::annot_attr_openmp:320case tok::annot_pragma_openmp_end:321// Stop before an OpenMP pragma boundary.322if (OpenMPDirectiveParsing)323return false;324ConsumeAnnotationToken();325break;326case tok::annot_pragma_openacc:327case tok::annot_pragma_openacc_end:328// Stop before an OpenACC pragma boundary.329if (OpenACCDirectiveParsing)330return false;331ConsumeAnnotationToken();332break;333case tok::annot_module_begin:334case tok::annot_module_end:335case tok::annot_module_include:336case 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 where339// we're trying to skip to EOF).340return false;341342case tok::code_completion:343if (!HasFlagsSet(Flags, StopAtCodeCompletion))344handleUnexpectedCodeCompletionToken();345return false;346347case tok::l_paren:348// Recursively skip properly-nested parens.349ConsumeParen();350if (HasFlagsSet(Flags, StopAtCodeCompletion))351SkipUntil(tok::r_paren, StopAtCodeCompletion);352else353SkipUntil(tok::r_paren);354break;355case tok::l_square:356// Recursively skip properly-nested square brackets.357ConsumeBracket();358if (HasFlagsSet(Flags, StopAtCodeCompletion))359SkipUntil(tok::r_square, StopAtCodeCompletion);360else361SkipUntil(tok::r_square);362break;363case tok::l_brace:364// Recursively skip properly-nested braces.365ConsumeBrace();366if (HasFlagsSet(Flags, StopAtCodeCompletion))367SkipUntil(tok::r_brace, StopAtCodeCompletion);368else369SkipUntil(tok::r_brace);370break;371case tok::question:372// Recursively skip ? ... : pairs; these function as brackets. But373// still stop at a semicolon if requested.374ConsumeToken();375SkipUntil(tok::colon,376SkipUntilFlags(unsigned(Flags) &377unsigned(StopAtCodeCompletion | StopAtSemi)));378break;379380// 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 would382// already be handled), this isn't balanced. If there is a LHS token at a383// higher level, we will assume that this matches the unbalanced token384// and return it. Otherwise, this is a spurious RHS token, which we skip.385case tok::r_paren:386if (ParenCount && !isFirstTokenSkipped)387return false; // Matches something.388ConsumeParen();389break;390case tok::r_square:391if (BracketCount && !isFirstTokenSkipped)392return false; // Matches something.393ConsumeBracket();394break;395case tok::r_brace:396if (BraceCount && !isFirstTokenSkipped)397return false; // Matches something.398ConsumeBrace();399break;400401case tok::semi:402if (HasFlagsSet(Flags, StopAtSemi))403return false;404[[fallthrough]];405default:406// Skip this token.407ConsumeAnyToken();408break;409}410isFirstTokenSkipped = false;411}412}413414//===----------------------------------------------------------------------===//415// Scope manipulation416//===----------------------------------------------------------------------===//417418/// EnterScope - Start a new scope.419void Parser::EnterScope(unsigned ScopeFlags) {420if (NumCachedScopes) {421Scope *N = ScopeCache[--NumCachedScopes];422N->Init(getCurScope(), ScopeFlags);423Actions.CurScope = N;424} else {425Actions.CurScope = new Scope(getCurScope(), ScopeFlags, Diags);426}427}428429/// ExitScope - Pop a scope off the scope stack.430void Parser::ExitScope() {431assert(getCurScope() && "Scope imbalance!");432433// Inform the actions module that this scope is going away if there are any434// decls in it.435Actions.ActOnPopScope(Tok.getLocation(), getCurScope());436437Scope *OldScope = getCurScope();438Actions.CurScope = OldScope->getParent();439440if (NumCachedScopes == ScopeCacheSize)441delete OldScope;442else443ScopeCache[NumCachedScopes++] = OldScope;444}445446/// 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,449bool ManageFlags)450: CurScope(ManageFlags ? Self->getCurScope() : nullptr) {451if (CurScope) {452OldFlags = CurScope->getFlags();453CurScope->setFlags(ScopeFlags);454}455}456457/// Restore the flags for the current scope to what they were before this458/// object overrode them.459Parser::ParseScopeFlags::~ParseScopeFlags() {460if (CurScope)461CurScope->setFlags(OldFlags);462}463464465//===----------------------------------------------------------------------===//466// C99 6.9: External Definitions.467//===----------------------------------------------------------------------===//468469Parser::~Parser() {470// If we still have scopes active, delete the scope tree.471delete getCurScope();472Actions.CurScope = nullptr;473474// Free the scope cache.475for (unsigned i = 0, e = NumCachedScopes; i != e; ++i)476delete ScopeCache[i];477478resetPragmaHandlers();479480PP.removeCommentHandler(CommentSemaHandler.get());481482PP.clearCodeCompletionHandler();483484DestroyTemplateIds();485}486487/// Initialize - Warm up the parser.488///489void Parser::Initialize() {490// Create the translation unit scope. Install it as the current scope.491assert(getCurScope() == nullptr && "A scope is already active?");492EnterScope(Scope::DeclScope);493Actions.ActOnTranslationUnitScope(getCurScope());494495// Initialization for Objective-C context sensitive keywords recognition.496// Referenced in Parser::ParseObjCTypeQualifierList.497if (getLangOpts().ObjC) {498ObjCTypeQuals[objc_in] = &PP.getIdentifierTable().get("in");499ObjCTypeQuals[objc_out] = &PP.getIdentifierTable().get("out");500ObjCTypeQuals[objc_inout] = &PP.getIdentifierTable().get("inout");501ObjCTypeQuals[objc_oneway] = &PP.getIdentifierTable().get("oneway");502ObjCTypeQuals[objc_bycopy] = &PP.getIdentifierTable().get("bycopy");503ObjCTypeQuals[objc_byref] = &PP.getIdentifierTable().get("byref");504ObjCTypeQuals[objc_nonnull] = &PP.getIdentifierTable().get("nonnull");505ObjCTypeQuals[objc_nullable] = &PP.getIdentifierTable().get("nullable");506ObjCTypeQuals[objc_null_unspecified]507= &PP.getIdentifierTable().get("null_unspecified");508}509510Ident_instancetype = nullptr;511Ident_final = nullptr;512Ident_sealed = nullptr;513Ident_abstract = nullptr;514Ident_override = nullptr;515Ident_GNU_final = nullptr;516Ident_import = nullptr;517Ident_module = nullptr;518519Ident_super = &PP.getIdentifierTable().get("super");520521Ident_vector = nullptr;522Ident_bool = nullptr;523Ident_Bool = nullptr;524Ident_pixel = nullptr;525if (getLangOpts().AltiVec || getLangOpts().ZVector) {526Ident_vector = &PP.getIdentifierTable().get("vector");527Ident_bool = &PP.getIdentifierTable().get("bool");528Ident_Bool = &PP.getIdentifierTable().get("_Bool");529}530if (getLangOpts().AltiVec)531Ident_pixel = &PP.getIdentifierTable().get("pixel");532533Ident_introduced = nullptr;534Ident_deprecated = nullptr;535Ident_obsoleted = nullptr;536Ident_unavailable = nullptr;537Ident_strict = nullptr;538Ident_replacement = nullptr;539540Ident_language = Ident_defined_in = Ident_generated_declaration = Ident_USR =541nullptr;542543Ident__except = nullptr;544545Ident__exception_code = Ident__exception_info = nullptr;546Ident__abnormal_termination = Ident___exception_code = nullptr;547Ident___exception_info = Ident___abnormal_termination = nullptr;548Ident_GetExceptionCode = Ident_GetExceptionInfo = nullptr;549Ident_AbnormalTermination = nullptr;550551if(getLangOpts().Borland) {552Ident__exception_info = PP.getIdentifierInfo("_exception_info");553Ident___exception_info = PP.getIdentifierInfo("__exception_info");554Ident_GetExceptionInfo = PP.getIdentifierInfo("GetExceptionInformation");555Ident__exception_code = PP.getIdentifierInfo("_exception_code");556Ident___exception_code = PP.getIdentifierInfo("__exception_code");557Ident_GetExceptionCode = PP.getIdentifierInfo("GetExceptionCode");558Ident__abnormal_termination = PP.getIdentifierInfo("_abnormal_termination");559Ident___abnormal_termination = PP.getIdentifierInfo("__abnormal_termination");560Ident_AbnormalTermination = PP.getIdentifierInfo("AbnormalTermination");561562PP.SetPoisonReason(Ident__exception_code,diag::err_seh___except_block);563PP.SetPoisonReason(Ident___exception_code,diag::err_seh___except_block);564PP.SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block);565PP.SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter);566PP.SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter);567PP.SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter);568PP.SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block);569PP.SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block);570PP.SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block);571}572573if (getLangOpts().CPlusPlusModules) {574Ident_import = PP.getIdentifierInfo("import");575Ident_module = PP.getIdentifierInfo("module");576}577578Actions.Initialize();579580// Prime the lexer look-ahead.581ConsumeToken();582}583584void Parser::DestroyTemplateIds() {585for (TemplateIdAnnotation *Id : TemplateIds)586Id->Destroy();587TemplateIds.clear();588}589590/// Parse the first top-level declaration in a translation unit.591///592/// translation-unit:593/// [C] external-declaration594/// [C] translation-unit external-declaration595/// [C++] top-level-declaration-seq[opt]596/// [C++20] global-module-fragment[opt] module-declaration597/// 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,601Sema::ModuleImportState &ImportState) {602Actions.ActOnStartOfTranslationUnit();603604// For C++20 modules, a module decl must be the first in the TU. We also605// need to track module imports.606ImportState = Sema::ModuleImportState::FirstDecl;607bool NoTopLevelDecls = ParseTopLevelDecl(Result, ImportState);608609// C11 6.9p1 says translation units must have at least one top-level610// declaration. C++ doesn't have this restriction. We also don't want to611// complain if we have a precompiled header, although technically if the PCH612// 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.614if (NoTopLevelDecls && !Actions.getASTContext().getExternalSource() &&615!getLangOpts().CPlusPlus && !getLangOpts().IsHeaderFile)616Diag(diag::ext_empty_translation_unit);617618return NoTopLevelDecls;619}620621/// ParseTopLevelDecl - Parse one top-level declaration, return whatever the622/// action tells us to. This returns true if the EOF was encountered.623///624/// top-level-declaration:625/// declaration626/// [C++20] module-import-declaration627bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result,628Sema::ModuleImportState &ImportState) {629DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*this);630631// Skip over the EOF token, flagging end of previous input for incremental632// processing633if (PP.isIncrementalProcessingEnabled() && Tok.is(tok::eof))634ConsumeToken();635636Result = nullptr;637switch (Tok.getKind()) {638case tok::annot_pragma_unused:639HandlePragmaUnused();640return false;641642case tok::kw_export:643switch (NextToken().getKind()) {644case tok::kw_module:645goto module_decl;646647// Note: no need to handle kw_import here. We only form kw_import under648// the Standard C++ Modules, and in that case 'export import' is parsed as649// an export-declaration containing an import-declaration.650651// Recognize context-sensitive C++20 'export module' and 'export import'652// declarations.653case tok::identifier: {654IdentifierInfo *II = NextToken().getIdentifierInfo();655if ((II == Ident_module || II == Ident_import) &&656GetLookAheadToken(2).isNot(tok::coloncolon)) {657if (II == Ident_module)658goto module_decl;659else660goto import_decl;661}662break;663}664665default:666break;667}668break;669670case tok::kw_module:671module_decl:672Result = ParseModuleDecl(ImportState);673return false;674675case tok::kw_import:676import_decl: {677Decl *ImportDecl = ParseModuleImport(SourceLocation(), ImportState);678Result = Actions.ConvertDeclToDeclGroup(ImportDecl);679return false;680}681682case tok::annot_module_include: {683auto Loc = Tok.getLocation();684Module *Mod = reinterpret_cast<Module *>(Tok.getAnnotationValue());685// FIXME: We need a better way to disambiguate C++ clang modules and686// standard C++ modules.687if (!getLangOpts().CPlusPlusModules || !Mod->isHeaderUnit())688Actions.ActOnAnnotModuleInclude(Loc, Mod);689else {690DeclResult Import =691Actions.ActOnModuleImport(Loc, SourceLocation(), Loc, Mod);692Decl *ImportDecl = Import.isInvalid() ? nullptr : Import.get();693Result = Actions.ConvertDeclToDeclGroup(ImportDecl);694}695ConsumeAnnotationToken();696return false;697}698699case tok::annot_module_begin:700Actions.ActOnAnnotModuleBegin(701Tok.getLocation(),702reinterpret_cast<Module *>(Tok.getAnnotationValue()));703ConsumeAnnotationToken();704ImportState = Sema::ModuleImportState::NotACXX20Module;705return false;706707case tok::annot_module_end:708Actions.ActOnAnnotModuleEnd(709Tok.getLocation(),710reinterpret_cast<Module *>(Tok.getAnnotationValue()));711ConsumeAnnotationToken();712ImportState = Sema::ModuleImportState::NotACXX20Module;713return false;714715case tok::eof:716case tok::annot_repl_input_end:717// Check whether -fmax-tokens= was reached.718if (PP.getMaxTokens() != 0 && PP.getTokenCount() > PP.getMaxTokens()) {719PP.Diag(Tok.getLocation(), diag::warn_max_tokens_total)720<< PP.getTokenCount() << PP.getMaxTokens();721SourceLocation OverrideLoc = PP.getMaxTokensOverrideLoc();722if (OverrideLoc.isValid()) {723PP.Diag(OverrideLoc, diag::note_max_tokens_total_override);724}725}726727// Late template parsing can begin.728Actions.SetLateTemplateParser(LateTemplateParserCallback, nullptr, this);729Actions.ActOnEndOfTranslationUnit();730//else don't tell Sema that we ended parsing: more input might come.731return true;732733case tok::identifier:734// C++2a [basic.link]p3:735// A token sequence beginning with 'export[opt] module' or736// 'export[opt] import' and not immediately followed by '::'737// is never interpreted as the declaration of a top-level-declaration.738if ((Tok.getIdentifierInfo() == Ident_module ||739Tok.getIdentifierInfo() == Ident_import) &&740NextToken().isNot(tok::coloncolon)) {741if (Tok.getIdentifierInfo() == Ident_module)742goto module_decl;743else744goto import_decl;745}746break;747748default:749break;750}751752ParsedAttributes DeclAttrs(AttrFactory);753ParsedAttributes DeclSpecAttrs(AttrFactory);754// GNU attributes are applied to the declaration specification while the755// standard attributes are applied to the declaration. We parse the two756// attribute sets into different containters so we can apply them during757// the regular parsing process.758while (MaybeParseCXX11Attributes(DeclAttrs) ||759MaybeParseGNUAttributes(DeclSpecAttrs))760;761762Result = ParseExternalDeclaration(DeclAttrs, DeclSpecAttrs);763// An empty Result might mean a line with ';' or some parsing error, ignore764// it.765if (Result) {766if (ImportState == Sema::ModuleImportState::FirstDecl)767// First decl was not modular.768ImportState = Sema::ModuleImportState::NotACXX20Module;769else if (ImportState == Sema::ModuleImportState::ImportAllowed)770// Non-imports disallow further imports.771ImportState = Sema::ModuleImportState::ImportFinished;772else if (ImportState ==773Sema::ModuleImportState::PrivateFragmentImportAllowed)774// Non-imports disallow further imports.775ImportState = Sema::ModuleImportState::PrivateFragmentImportFinished;776}777return false;778}779780/// ParseExternalDeclaration:781///782/// The `Attrs` that are passed in are C++11 attributes and appertain to the783/// declaration.784///785/// external-declaration: [C99 6.9], declaration: [C++ dcl.dcl]786/// function-definition787/// declaration788/// [GNU] asm-definition789/// [GNU] __extension__ external-declaration790/// [OBJC] objc-class-definition791/// [OBJC] objc-class-declaration792/// [OBJC] objc-alias-declaration793/// [OBJC] objc-protocol-definition794/// [OBJC] objc-method-definition795/// [OBJC] @end796/// [C++] linkage-specification797/// [GNU] asm-definition:798/// simple-asm-expr ';'799/// [C++11] empty-declaration800/// [C++11] attribute-declaration801///802/// [C++11] empty-declaration:803/// ';'804///805/// [C++0x/GNU] 'extern' 'template' declaration806///807/// [C++20] module-import-declaration808///809Parser::DeclGroupPtrTy810Parser::ParseExternalDeclaration(ParsedAttributes &Attrs,811ParsedAttributes &DeclSpecAttrs,812ParsingDeclSpec *DS) {813DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*this);814ParenBraceBracketBalancer BalancerRAIIObj(*this);815816if (PP.isCodeCompletionReached()) {817cutOffParsing();818return nullptr;819}820821Decl *SingleDecl = nullptr;822switch (Tok.getKind()) {823case tok::annot_pragma_vis:824HandlePragmaVisibility();825return nullptr;826case tok::annot_pragma_pack:827HandlePragmaPack();828return nullptr;829case tok::annot_pragma_msstruct:830HandlePragmaMSStruct();831return nullptr;832case tok::annot_pragma_align:833HandlePragmaAlign();834return nullptr;835case tok::annot_pragma_weak:836HandlePragmaWeak();837return nullptr;838case tok::annot_pragma_weakalias:839HandlePragmaWeakAlias();840return nullptr;841case tok::annot_pragma_redefine_extname:842HandlePragmaRedefineExtname();843return nullptr;844case tok::annot_pragma_fp_contract:845HandlePragmaFPContract();846return nullptr;847case tok::annot_pragma_fenv_access:848case tok::annot_pragma_fenv_access_ms:849HandlePragmaFEnvAccess();850return nullptr;851case tok::annot_pragma_fenv_round:852HandlePragmaFEnvRound();853return nullptr;854case tok::annot_pragma_cx_limited_range:855HandlePragmaCXLimitedRange();856return nullptr;857case tok::annot_pragma_float_control:858HandlePragmaFloatControl();859return nullptr;860case tok::annot_pragma_fp:861HandlePragmaFP();862break;863case tok::annot_pragma_opencl_extension:864HandlePragmaOpenCLExtension();865return nullptr;866case tok::annot_attr_openmp:867case tok::annot_pragma_openmp: {868AccessSpecifier AS = AS_none;869return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);870}871case tok::annot_pragma_openacc:872return ParseOpenACCDirectiveDecl();873case tok::annot_pragma_ms_pointers_to_members:874HandlePragmaMSPointersToMembers();875return nullptr;876case tok::annot_pragma_ms_vtordisp:877HandlePragmaMSVtorDisp();878return nullptr;879case tok::annot_pragma_ms_pragma:880HandlePragmaMSPragma();881return nullptr;882case tok::annot_pragma_dump:883HandlePragmaDump();884return nullptr;885case tok::annot_pragma_attribute:886HandlePragmaAttribute();887return nullptr;888case tok::semi:889// Either a C++11 empty-declaration or attribute-declaration.890SingleDecl =891Actions.ActOnEmptyDeclaration(getCurScope(), Attrs, Tok.getLocation());892ConsumeExtraSemi(OutsideFunction);893break;894case tok::r_brace:895Diag(Tok, diag::err_extraneous_closing_brace);896ConsumeBrace();897return nullptr;898case tok::eof:899Diag(Tok, diag::err_expected_external_declaration);900return nullptr;901case tok::kw___extension__: {902// __extension__ silences extension warnings in the subexpression.903ExtensionRAIIObject O(Diags); // Use RAII to do this.904ConsumeToken();905return ParseExternalDeclaration(Attrs, DeclSpecAttrs);906}907case tok::kw_asm: {908ProhibitAttributes(Attrs);909910SourceLocation StartLoc = Tok.getLocation();911SourceLocation EndLoc;912913ExprResult Result(ParseSimpleAsm(/*ForAsmLabel*/ false, &EndLoc));914915// Check if GNU-style InlineAsm is disabled.916// Empty asm string is allowed because it will not introduce917// any assembly code.918if (!(getLangOpts().GNUAsm || Result.isInvalid())) {919const auto *SL = cast<StringLiteral>(Result.get());920if (!SL->getString().trim().empty())921Diag(StartLoc, diag::err_gnu_inline_asm_disabled);922}923924ExpectAndConsume(tok::semi, diag::err_expected_after,925"top-level asm block");926927if (Result.isInvalid())928return nullptr;929SingleDecl = Actions.ActOnFileScopeAsmDecl(Result.get(), StartLoc, EndLoc);930break;931}932case tok::at:933return ParseObjCAtDirectives(Attrs, DeclSpecAttrs);934case tok::minus:935case tok::plus:936if (!getLangOpts().ObjC) {937Diag(Tok, diag::err_expected_external_declaration);938ConsumeToken();939return nullptr;940}941SingleDecl = ParseObjCMethodDefinition();942break;943case tok::code_completion:944cutOffParsing();945if (CurParsedObjCImpl) {946// Code-complete Objective-C methods even without leading '-'/'+' prefix.947Actions.CodeCompletion().CodeCompleteObjCMethodDecl(948getCurScope(),949/*IsInstanceMethod=*/std::nullopt,950/*ReturnType=*/nullptr);951}952953SemaCodeCompletion::ParserCompletionContext PCC;954if (CurParsedObjCImpl) {955PCC = SemaCodeCompletion::PCC_ObjCImplementation;956} else if (PP.isIncrementalProcessingEnabled()) {957PCC = SemaCodeCompletion::PCC_TopLevelOrExpression;958} else {959PCC = SemaCodeCompletion::PCC_Namespace;960};961Actions.CodeCompletion().CodeCompleteOrdinaryName(getCurScope(), PCC);962return nullptr;963case tok::kw_import: {964Sema::ModuleImportState IS = Sema::ModuleImportState::NotACXX20Module;965if (getLangOpts().CPlusPlusModules) {966llvm_unreachable("not expecting a c++20 import here");967ProhibitAttributes(Attrs);968}969SingleDecl = ParseModuleImport(SourceLocation(), IS);970} break;971case tok::kw_export:972if (getLangOpts().CPlusPlusModules || getLangOpts().HLSL) {973ProhibitAttributes(Attrs);974SingleDecl = ParseExportDeclaration();975break;976}977// This must be 'export template'. Parse it so we can diagnose our lack978// of support.979[[fallthrough]];980case tok::kw_using:981case tok::kw_namespace:982case tok::kw_typedef:983case tok::kw_template:984case tok::kw_static_assert:985case tok::kw__Static_assert:986// A function definition cannot start with any of these keywords.987{988SourceLocation DeclEnd;989return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs,990DeclSpecAttrs);991}992993case tok::kw_cbuffer:994case tok::kw_tbuffer:995if (getLangOpts().HLSL) {996SourceLocation DeclEnd;997return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs,998DeclSpecAttrs);999}1000goto dont_know;10011002case tok::kw_static:1003// Parse (then ignore) 'static' prior to a template instantiation. This is1004// a GCC extension that we intentionally do not support.1005if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {1006Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)1007<< 0;1008SourceLocation DeclEnd;1009return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs,1010DeclSpecAttrs);1011}1012goto dont_know;10131014case tok::kw_inline:1015if (getLangOpts().CPlusPlus) {1016tok::TokenKind NextKind = NextToken().getKind();10171018// Inline namespaces. Allowed as an extension even in C++03.1019if (NextKind == tok::kw_namespace) {1020SourceLocation DeclEnd;1021return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs,1022DeclSpecAttrs);1023}10241025// Parse (then ignore) 'inline' prior to a template instantiation. This is1026// a GCC extension that we intentionally do not support.1027if (NextKind == tok::kw_template) {1028Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)1029<< 1;1030SourceLocation DeclEnd;1031return ParseDeclaration(DeclaratorContext::File, DeclEnd, Attrs,1032DeclSpecAttrs);1033}1034}1035goto dont_know;10361037case tok::kw_extern:1038if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {1039// Extern templates1040SourceLocation ExternLoc = ConsumeToken();1041SourceLocation TemplateLoc = ConsumeToken();1042Diag(ExternLoc, getLangOpts().CPlusPlus11 ?1043diag::warn_cxx98_compat_extern_template :1044diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc);1045SourceLocation DeclEnd;1046return ParseExplicitInstantiation(DeclaratorContext::File, ExternLoc,1047TemplateLoc, DeclEnd, Attrs);1048}1049goto dont_know;10501051case tok::kw___if_exists:1052case tok::kw___if_not_exists:1053ParseMicrosoftIfExistsExternalDeclaration();1054return nullptr;10551056case tok::kw_module:1057Diag(Tok, diag::err_unexpected_module_decl);1058SkipUntil(tok::semi);1059return nullptr;10601061default:1062dont_know:1063if (Tok.isEditorPlaceholder()) {1064ConsumeToken();1065return nullptr;1066}1067if (getLangOpts().IncrementalExtensions &&1068!isDeclarationStatement(/*DisambiguatingWithExpression=*/true))1069return ParseTopLevelStmtDecl();10701071// We can't tell whether this is a function-definition or declaration yet.1072if (!SingleDecl)1073return ParseDeclarationOrFunctionDefinition(Attrs, DeclSpecAttrs, DS);1074}10751076// This routine returns a DeclGroup, if the thing we parsed only contains a1077// single decl, convert it now.1078return Actions.ConvertDeclToDeclGroup(SingleDecl);1079}10801081/// Determine whether the current token, if it occurs after a1082/// declarator, continues a declaration or declaration list.1083bool Parser::isDeclarationAfterDeclarator() {1084// Check for '= delete' or '= default'1085if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {1086const Token &KW = NextToken();1087if (KW.is(tok::kw_default) || KW.is(tok::kw_delete))1088return false;1089}10901091return Tok.is(tok::equal) || // int X()= -> not a function def1092Tok.is(tok::comma) || // int X(), -> not a function def1093Tok.is(tok::semi) || // int X(); -> not a function def1094Tok.is(tok::kw_asm) || // int X() __asm__ -> not a function def1095Tok.is(tok::kw___attribute) || // int X() __attr__ -> not a function def1096(getLangOpts().CPlusPlus &&1097Tok.is(tok::l_paren)); // int X(0) -> not a function def [C++]1098}10991100/// Determine whether the current token, if it occurs after a1101/// declarator, indicates the start of a function definition.1102bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) {1103assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator");1104if (Tok.is(tok::l_brace)) // int X() {}1105return true;11061107// Handle K&R C argument lists: int X(f) int f; {}1108if (!getLangOpts().CPlusPlus &&1109Declarator.getFunctionTypeInfo().isKNRPrototype())1110return isDeclarationSpecifier(ImplicitTypenameContext::No);11111112if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {1113const Token &KW = NextToken();1114return KW.is(tok::kw_default) || KW.is(tok::kw_delete);1115}11161117return Tok.is(tok::colon) || // X() : Base() {} (used for ctors)1118Tok.is(tok::kw_try); // X() try { ... }1119}11201121/// Parse either a function-definition or a declaration. We can't tell which1122/// we have until we read up to the compound-statement in function-definition.1123/// TemplateParams, if non-NULL, provides the template parameters when we're1124/// parsing a C++ template-declaration.1125///1126/// function-definition: [C99 6.9.1]1127/// decl-specs declarator declaration-list[opt] compound-statement1128/// [C90] function-definition: [C99 6.7.1] - implicit int result1129/// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement1130///1131/// declaration: [C99 6.7]1132/// declaration-specifiers init-declarator-list[opt] ';'1133/// [!C99] init-declarator-list ';' [TODO: warn in c99 mode]1134/// [OMP] threadprivate-directive1135/// [OMP] allocate-directive [TODO]1136///1137Parser::DeclGroupPtrTy Parser::ParseDeclOrFunctionDefInternal(1138ParsedAttributes &Attrs, ParsedAttributes &DeclSpecAttrs,1139ParsingDeclSpec &DS, AccessSpecifier AS) {1140// Because we assume that the DeclSpec has not yet been initialised, we simply1141// overwrite the source range and attribute the provided leading declspec1142// attributes.1143assert(DS.getSourceRange().isInvalid() &&1144"expected uninitialised source range");1145DS.SetRangeStart(DeclSpecAttrs.Range.getBegin());1146DS.SetRangeEnd(DeclSpecAttrs.Range.getEnd());1147DS.takeAttributesFrom(DeclSpecAttrs);11481149ParsedTemplateInfo TemplateInfo;1150MaybeParseMicrosoftAttributes(DS.getAttributes());1151// Parse the common declaration-specifiers piece.1152ParseDeclarationSpecifiers(DS, TemplateInfo, AS,1153DeclSpecContext::DSC_top_level);11541155// If we had a free-standing type definition with a missing semicolon, we1156// may get this far before the problem becomes obvious.1157if (DS.hasTagDefinition() && DiagnoseMissingSemiAfterTagDefinition(1158DS, AS, DeclSpecContext::DSC_top_level))1159return nullptr;11601161// C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"1162// declaration-specifiers init-declarator-list[opt] ';'1163if (Tok.is(tok::semi)) {1164auto LengthOfTSTToken = [](DeclSpec::TST TKind) {1165assert(DeclSpec::isDeclRep(TKind));1166switch(TKind) {1167case DeclSpec::TST_class:1168return 5;1169case DeclSpec::TST_struct:1170return 6;1171case DeclSpec::TST_union:1172return 5;1173case DeclSpec::TST_enum:1174return 4;1175case DeclSpec::TST_interface:1176return 9;1177default:1178llvm_unreachable("we only expect to get the length of the class/struct/union/enum");1179}11801181};1182// Suggest correct location to fix '[[attrib]] struct' to 'struct [[attrib]]'1183SourceLocation CorrectLocationForAttributes =1184DeclSpec::isDeclRep(DS.getTypeSpecType())1185? DS.getTypeSpecTypeLoc().getLocWithOffset(1186LengthOfTSTToken(DS.getTypeSpecType()))1187: SourceLocation();1188ProhibitAttributes(Attrs, CorrectLocationForAttributes);1189ConsumeToken();1190RecordDecl *AnonRecord = nullptr;1191Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(1192getCurScope(), AS_none, DS, ParsedAttributesView::none(), AnonRecord);1193DS.complete(TheDecl);1194Actions.ActOnDefinedDeclarationSpecifier(TheDecl);1195if (AnonRecord) {1196Decl* decls[] = {AnonRecord, TheDecl};1197return Actions.BuildDeclaratorGroup(decls);1198}1199return Actions.ConvertDeclToDeclGroup(TheDecl);1200}12011202if (DS.hasTagDefinition())1203Actions.ActOnDefinedDeclarationSpecifier(DS.getRepAsDecl());12041205// ObjC2 allows prefix attributes on class interfaces and protocols.1206// FIXME: This still needs better diagnostics. We should only accept1207// attributes here, no types, etc.1208if (getLangOpts().ObjC && Tok.is(tok::at)) {1209SourceLocation AtLoc = ConsumeToken(); // the "@"1210if (!Tok.isObjCAtKeyword(tok::objc_interface) &&1211!Tok.isObjCAtKeyword(tok::objc_protocol) &&1212!Tok.isObjCAtKeyword(tok::objc_implementation)) {1213Diag(Tok, diag::err_objc_unexpected_attr);1214SkipUntil(tok::semi);1215return nullptr;1216}12171218DS.abort();1219DS.takeAttributesFrom(Attrs);12201221const char *PrevSpec = nullptr;1222unsigned DiagID;1223if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID,1224Actions.getASTContext().getPrintingPolicy()))1225Diag(AtLoc, DiagID) << PrevSpec;12261227if (Tok.isObjCAtKeyword(tok::objc_protocol))1228return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());12291230if (Tok.isObjCAtKeyword(tok::objc_implementation))1231return ParseObjCAtImplementationDeclaration(AtLoc, DS.getAttributes());12321233return Actions.ConvertDeclToDeclGroup(1234ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes()));1235}12361237// If the declspec consisted only of 'extern' and we have a string1238// literal following it, this must be a C++ linkage specifier like1239// 'extern "C"'.1240if (getLangOpts().CPlusPlus && isTokenStringLiteral() &&1241DS.getStorageClassSpec() == DeclSpec::SCS_extern &&1242DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) {1243ProhibitAttributes(Attrs);1244Decl *TheDecl = ParseLinkage(DS, DeclaratorContext::File);1245return Actions.ConvertDeclToDeclGroup(TheDecl);1246}12471248return ParseDeclGroup(DS, DeclaratorContext::File, Attrs, TemplateInfo);1249}12501251Parser::DeclGroupPtrTy Parser::ParseDeclarationOrFunctionDefinition(1252ParsedAttributes &Attrs, ParsedAttributes &DeclSpecAttrs,1253ParsingDeclSpec *DS, AccessSpecifier AS) {1254// Add an enclosing time trace scope for a bunch of small scopes with1255// "EvaluateAsConstExpr".1256llvm::TimeTraceScope TimeScope("ParseDeclarationOrFunctionDefinition", [&]() {1257return Tok.getLocation().printToString(1258Actions.getASTContext().getSourceManager());1259});12601261if (DS) {1262return ParseDeclOrFunctionDefInternal(Attrs, DeclSpecAttrs, *DS, AS);1263} else {1264ParsingDeclSpec PDS(*this);1265// Must temporarily exit the objective-c container scope for1266// parsing c constructs and re-enter objc container scope1267// afterwards.1268ObjCDeclContextSwitch ObjCDC(*this);12691270return ParseDeclOrFunctionDefInternal(Attrs, DeclSpecAttrs, PDS, AS);1271}1272}12731274/// ParseFunctionDefinition - We parsed and verified that the specified1275/// Declarator is well formed. If this is a K&R-style function, read the1276/// parameters declaration-list, then start the compound-statement.1277///1278/// function-definition: [C99 6.9.1]1279/// decl-specs declarator declaration-list[opt] compound-statement1280/// [C90] function-definition: [C99 6.7.1] - implicit int result1281/// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement1282/// [C++] function-definition: [C++ 8.4]1283/// decl-specifier-seq[opt] declarator ctor-initializer[opt]1284/// function-body1285/// [C++] function-definition: [C++ 8.4]1286/// decl-specifier-seq[opt] declarator function-try-block1287///1288Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,1289const ParsedTemplateInfo &TemplateInfo,1290LateParsedAttrList *LateParsedAttrs) {1291llvm::TimeTraceScope TimeScope("ParseFunctionDefinition", [&]() {1292return Actions.GetNameForDeclarator(D).getName().getAsString();1293});12941295// Poison SEH identifiers so they are flagged as illegal in function bodies.1296PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);1297const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();1298TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);12991300// If this is C89 and the declspecs were completely missing, fudge in an1301// implicit int. We do this here because this is the only place where1302// declaration-specifiers are completely optional in the grammar.1303if (getLangOpts().isImplicitIntRequired() && D.getDeclSpec().isEmpty()) {1304Diag(D.getIdentifierLoc(), diag::warn_missing_type_specifier)1305<< D.getDeclSpec().getSourceRange();1306const char *PrevSpec;1307unsigned DiagID;1308const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();1309D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int,1310D.getIdentifierLoc(),1311PrevSpec, DiagID,1312Policy);1313D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin());1314}13151316// If this declaration was formed with a K&R-style identifier list for the1317// arguments, parse declarations for all of the args next.1318// int foo(a,b) int a; float b; {}1319if (FTI.isKNRPrototype())1320ParseKNRParamDeclarations(D);13211322// We should have either an opening brace or, in a C++ constructor,1323// we may have a colon.1324if (Tok.isNot(tok::l_brace) &&1325(!getLangOpts().CPlusPlus ||1326(Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&1327Tok.isNot(tok::equal)))) {1328Diag(Tok, diag::err_expected_fn_body);13291330// Skip over garbage, until we get to '{'. Don't eat the '{'.1331SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);13321333// If we didn't find the '{', bail out.1334if (Tok.isNot(tok::l_brace))1335return nullptr;1336}13371338// Check to make sure that any normal attributes are allowed to be on1339// a definition. Late parsed attributes are checked at the end.1340if (Tok.isNot(tok::equal)) {1341for (const ParsedAttr &AL : D.getAttributes())1342if (AL.isKnownToGCC() && !AL.isStandardAttributeSyntax())1343Diag(AL.getLoc(), diag::warn_attribute_on_function_definition) << AL;1344}13451346// In delayed template parsing mode, for function template we consume the1347// tokens and store them for late parsing at the end of the translation unit.1348if (getLangOpts().DelayedTemplateParsing && Tok.isNot(tok::equal) &&1349TemplateInfo.Kind == ParsedTemplateInfo::Template &&1350Actions.canDelayFunctionBody(D)) {1351MultiTemplateParamsArg TemplateParameterLists(*TemplateInfo.TemplateParams);13521353ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |1354Scope::CompoundStmtScope);1355Scope *ParentScope = getCurScope()->getParent();13561357D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);1358Decl *DP = Actions.HandleDeclarator(ParentScope, D,1359TemplateParameterLists);1360D.complete(DP);1361D.getMutableDeclSpec().abort();13621363if (SkipFunctionBodies && (!DP || Actions.canSkipFunctionBody(DP)) &&1364trySkippingFunctionBody()) {1365BodyScope.Exit();1366return Actions.ActOnSkippedFunctionBody(DP);1367}13681369CachedTokens Toks;1370LexTemplateFunctionForLateParsing(Toks);13711372if (DP) {1373FunctionDecl *FnD = DP->getAsFunction();1374Actions.CheckForFunctionRedefinition(FnD);1375Actions.MarkAsLateParsedTemplate(FnD, DP, Toks);1376}1377return DP;1378}1379else if (CurParsedObjCImpl &&1380!TemplateInfo.TemplateParams &&1381(Tok.is(tok::l_brace) || Tok.is(tok::kw_try) ||1382Tok.is(tok::colon)) &&1383Actions.CurContext->isTranslationUnit()) {1384ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |1385Scope::CompoundStmtScope);1386Scope *ParentScope = getCurScope()->getParent();13871388D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);1389Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,1390MultiTemplateParamsArg());1391D.complete(FuncDecl);1392D.getMutableDeclSpec().abort();1393if (FuncDecl) {1394// Consume the tokens and store them for later parsing.1395StashAwayMethodOrFunctionBodyTokens(FuncDecl);1396CurParsedObjCImpl->HasCFunction = true;1397return FuncDecl;1398}1399// FIXME: Should we really fall through here?1400}14011402// Enter a scope for the function body.1403ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |1404Scope::CompoundStmtScope);14051406// Parse function body eagerly if it is either '= delete;' or '= default;' as1407// ActOnStartOfFunctionDef needs to know whether the function is deleted.1408StringLiteral *DeletedMessage = nullptr;1409Sema::FnBodyKind BodyKind = Sema::FnBodyKind::Other;1410SourceLocation KWLoc;1411if (TryConsumeToken(tok::equal)) {1412assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='");14131414if (TryConsumeToken(tok::kw_delete, KWLoc)) {1415Diag(KWLoc, getLangOpts().CPlusPlus111416? diag::warn_cxx98_compat_defaulted_deleted_function1417: diag::ext_defaulted_deleted_function)1418<< 1 /* deleted */;1419BodyKind = Sema::FnBodyKind::Delete;1420DeletedMessage = ParseCXXDeletedFunctionMessage();1421} else if (TryConsumeToken(tok::kw_default, KWLoc)) {1422Diag(KWLoc, getLangOpts().CPlusPlus111423? diag::warn_cxx98_compat_defaulted_deleted_function1424: diag::ext_defaulted_deleted_function)1425<< 0 /* defaulted */;1426BodyKind = Sema::FnBodyKind::Default;1427} else {1428llvm_unreachable("function definition after = not 'delete' or 'default'");1429}14301431if (Tok.is(tok::comma)) {1432Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)1433<< (BodyKind == Sema::FnBodyKind::Delete);1434SkipUntil(tok::semi);1435} else if (ExpectAndConsume(tok::semi, diag::err_expected_after,1436BodyKind == Sema::FnBodyKind::Delete1437? "delete"1438: "default")) {1439SkipUntil(tok::semi);1440}1441}14421443Sema::FPFeaturesStateRAII SaveFPFeatures(Actions);14441445// Tell the actions module that we have entered a function definition with the1446// specified Declarator for the function.1447SkipBodyInfo SkipBody;1448Decl *Res = Actions.ActOnStartOfFunctionDef(getCurScope(), D,1449TemplateInfo.TemplateParams1450? *TemplateInfo.TemplateParams1451: MultiTemplateParamsArg(),1452&SkipBody, BodyKind);14531454if (SkipBody.ShouldSkip) {1455// Do NOT enter SkipFunctionBody if we already consumed the tokens.1456if (BodyKind == Sema::FnBodyKind::Other)1457SkipFunctionBody();14581459// ExpressionEvaluationContext is pushed in ActOnStartOfFunctionDef1460// and it would be popped in ActOnFinishFunctionBody.1461// We pop it explcitly here since ActOnFinishFunctionBody won't get called.1462//1463// Do not call PopExpressionEvaluationContext() if it is a lambda because1464// one is already popped when finishing the lambda in BuildLambdaExpr().1465//1466// FIXME: It looks not easy to balance PushExpressionEvaluationContext()1467// and PopExpressionEvaluationContext().1468if (!isLambdaCallOperator(dyn_cast_if_present<FunctionDecl>(Res)))1469Actions.PopExpressionEvaluationContext();1470return Res;1471}14721473// Break out of the ParsingDeclarator context before we parse the body.1474D.complete(Res);14751476// Break out of the ParsingDeclSpec context, too. This const_cast is1477// safe because we're always the sole owner.1478D.getMutableDeclSpec().abort();14791480if (BodyKind != Sema::FnBodyKind::Other) {1481Actions.SetFunctionBodyKind(Res, KWLoc, BodyKind, DeletedMessage);1482Stmt *GeneratedBody = Res ? Res->getBody() : nullptr;1483Actions.ActOnFinishFunctionBody(Res, GeneratedBody, false);1484return Res;1485}14861487// With abbreviated function templates - we need to explicitly add depth to1488// account for the implicit template parameter list induced by the template.1489if (const auto *Template = dyn_cast_if_present<FunctionTemplateDecl>(Res);1490Template && Template->isAbbreviated() &&1491Template->getTemplateParameters()->getParam(0)->isImplicit())1492// First template parameter is implicit - meaning no explicit template1493// parameter list was specified.1494CurTemplateDepthTracker.addDepth(1);14951496if (SkipFunctionBodies && (!Res || Actions.canSkipFunctionBody(Res)) &&1497trySkippingFunctionBody()) {1498BodyScope.Exit();1499Actions.ActOnSkippedFunctionBody(Res);1500return Actions.ActOnFinishFunctionBody(Res, nullptr, false);1501}15021503if (Tok.is(tok::kw_try))1504return ParseFunctionTryBlock(Res, BodyScope);15051506// If we have a colon, then we're probably parsing a C++1507// ctor-initializer.1508if (Tok.is(tok::colon)) {1509ParseConstructorInitializer(Res);15101511// Recover from error.1512if (!Tok.is(tok::l_brace)) {1513BodyScope.Exit();1514Actions.ActOnFinishFunctionBody(Res, nullptr);1515return Res;1516}1517} else1518Actions.ActOnDefaultCtorInitializers(Res);15191520// Late attributes are parsed in the same scope as the function body.1521if (LateParsedAttrs)1522ParseLexedAttributeList(*LateParsedAttrs, Res, false, true);15231524return ParseFunctionStatementBody(Res, BodyScope);1525}15261527void Parser::SkipFunctionBody() {1528if (Tok.is(tok::equal)) {1529SkipUntil(tok::semi);1530return;1531}15321533bool IsFunctionTryBlock = Tok.is(tok::kw_try);1534if (IsFunctionTryBlock)1535ConsumeToken();15361537CachedTokens Skipped;1538if (ConsumeAndStoreFunctionPrologue(Skipped))1539SkipMalformedDecl();1540else {1541SkipUntil(tok::r_brace);1542while (IsFunctionTryBlock && Tok.is(tok::kw_catch)) {1543SkipUntil(tok::l_brace);1544SkipUntil(tok::r_brace);1545}1546}1547}15481549/// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides1550/// types for a function with a K&R-style identifier list for arguments.1551void Parser::ParseKNRParamDeclarations(Declarator &D) {1552// We know that the top-level of this declarator is a function.1553DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();15541555// Enter function-declaration scope, limiting any declarators to the1556// function prototype scope, including parameter declarators.1557ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |1558Scope::FunctionDeclarationScope | Scope::DeclScope);15591560// Read all the argument declarations.1561while (isDeclarationSpecifier(ImplicitTypenameContext::No)) {1562SourceLocation DSStart = Tok.getLocation();15631564// Parse the common declaration-specifiers piece.1565DeclSpec DS(AttrFactory);1566ParsedTemplateInfo TemplateInfo;1567ParseDeclarationSpecifiers(DS, TemplateInfo);15681569// C99 6.9.1p6: 'each declaration in the declaration list shall have at1570// least one declarator'.1571// NOTE: GCC just makes this an ext-warn. It's not clear what it does with1572// the declarations though. It's trivial to ignore them, really hard to do1573// anything else with them.1574if (TryConsumeToken(tok::semi)) {1575Diag(DSStart, diag::err_declaration_does_not_declare_param);1576continue;1577}15781579// C99 6.9.1p6: Declarations shall contain no storage-class specifiers other1580// than register.1581if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&1582DS.getStorageClassSpec() != DeclSpec::SCS_register) {1583Diag(DS.getStorageClassSpecLoc(),1584diag::err_invalid_storage_class_in_func_decl);1585DS.ClearStorageClassSpecs();1586}1587if (DS.getThreadStorageClassSpec() != DeclSpec::TSCS_unspecified) {1588Diag(DS.getThreadStorageClassSpecLoc(),1589diag::err_invalid_storage_class_in_func_decl);1590DS.ClearStorageClassSpecs();1591}15921593// Parse the first declarator attached to this declspec.1594Declarator ParmDeclarator(DS, ParsedAttributesView::none(),1595DeclaratorContext::KNRTypeList);1596ParseDeclarator(ParmDeclarator);15971598// Handle the full declarator list.1599while (true) {1600// If attributes are present, parse them.1601MaybeParseGNUAttributes(ParmDeclarator);16021603// Ask the actions module to compute the type for this declarator.1604Decl *Param =1605Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);16061607if (Param &&1608// A missing identifier has already been diagnosed.1609ParmDeclarator.getIdentifier()) {16101611// Scan the argument list looking for the correct param to apply this1612// type.1613for (unsigned i = 0; ; ++i) {1614// C99 6.9.1p6: those declarators shall declare only identifiers from1615// the identifier list.1616if (i == FTI.NumParams) {1617Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)1618<< ParmDeclarator.getIdentifier();1619break;1620}16211622if (FTI.Params[i].Ident == ParmDeclarator.getIdentifier()) {1623// Reject redefinitions of parameters.1624if (FTI.Params[i].Param) {1625Diag(ParmDeclarator.getIdentifierLoc(),1626diag::err_param_redefinition)1627<< ParmDeclarator.getIdentifier();1628} else {1629FTI.Params[i].Param = Param;1630}1631break;1632}1633}1634}16351636// If we don't have a comma, it is either the end of the list (a ';') or1637// an error, bail out.1638if (Tok.isNot(tok::comma))1639break;16401641ParmDeclarator.clear();16421643// Consume the comma.1644ParmDeclarator.setCommaLoc(ConsumeToken());16451646// Parse the next declarator.1647ParseDeclarator(ParmDeclarator);1648}16491650// Consume ';' and continue parsing.1651if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration))1652continue;16531654// Otherwise recover by skipping to next semi or mandatory function body.1655if (SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch))1656break;1657TryConsumeToken(tok::semi);1658}16591660// The actions module must verify that all arguments were declared.1661Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation());1662}166316641665/// ParseAsmStringLiteral - This is just a normal string-literal, but is not1666/// allowed to be a wide string, and is not subject to character translation.1667/// Unlike GCC, we also diagnose an empty string literal when parsing for an1668/// asm label as opposed to an asm statement, because such a construct does not1669/// behave well.1670///1671/// [GNU] asm-string-literal:1672/// string-literal1673///1674ExprResult Parser::ParseAsmStringLiteral(bool ForAsmLabel) {1675if (!isTokenStringLiteral()) {1676Diag(Tok, diag::err_expected_string_literal)1677<< /*Source='in...'*/0 << "'asm'";1678return ExprError();1679}16801681ExprResult AsmString(ParseStringLiteralExpression());1682if (!AsmString.isInvalid()) {1683const auto *SL = cast<StringLiteral>(AsmString.get());1684if (!SL->isOrdinary()) {1685Diag(Tok, diag::err_asm_operand_wide_string_literal)1686<< SL->isWide()1687<< SL->getSourceRange();1688return ExprError();1689}1690if (ForAsmLabel && SL->getString().empty()) {1691Diag(Tok, diag::err_asm_operand_wide_string_literal)1692<< 2 /* an empty */ << SL->getSourceRange();1693return ExprError();1694}1695}1696return AsmString;1697}16981699/// ParseSimpleAsm1700///1701/// [GNU] simple-asm-expr:1702/// 'asm' '(' asm-string-literal ')'1703///1704ExprResult Parser::ParseSimpleAsm(bool ForAsmLabel, SourceLocation *EndLoc) {1705assert(Tok.is(tok::kw_asm) && "Not an asm!");1706SourceLocation Loc = ConsumeToken();17071708if (isGNUAsmQualifier(Tok)) {1709// Remove from the end of 'asm' to the end of the asm qualifier.1710SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),1711PP.getLocForEndOfToken(Tok.getLocation()));1712Diag(Tok, diag::err_global_asm_qualifier_ignored)1713<< GNUAsmQualifiers::getQualifierName(getGNUAsmQualifier(Tok))1714<< FixItHint::CreateRemoval(RemovalRange);1715ConsumeToken();1716}17171718BalancedDelimiterTracker T(*this, tok::l_paren);1719if (T.consumeOpen()) {1720Diag(Tok, diag::err_expected_lparen_after) << "asm";1721return ExprError();1722}17231724ExprResult Result(ParseAsmStringLiteral(ForAsmLabel));17251726if (!Result.isInvalid()) {1727// Close the paren and get the location of the end bracket1728T.consumeClose();1729if (EndLoc)1730*EndLoc = T.getCloseLocation();1731} else if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {1732if (EndLoc)1733*EndLoc = Tok.getLocation();1734ConsumeParen();1735}17361737return Result;1738}17391740/// Get the TemplateIdAnnotation from the token and put it in the1741/// cleanup pool so that it gets destroyed when parsing the current top level1742/// declaration is finished.1743TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) {1744assert(tok.is(tok::annot_template_id) && "Expected template-id token");1745TemplateIdAnnotation *1746Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue());1747return Id;1748}17491750void Parser::AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation) {1751// Push the current token back into the token stream (or revert it if it is1752// cached) and use an annotation scope token for current token.1753if (PP.isBacktrackEnabled())1754PP.RevertCachedTokens(1);1755else1756PP.EnterToken(Tok, /*IsReinject=*/true);1757Tok.setKind(tok::annot_cxxscope);1758Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));1759Tok.setAnnotationRange(SS.getRange());17601761// In case the tokens were cached, have Preprocessor replace them1762// with the annotation token. We don't need to do this if we've1763// just reverted back to a prior state.1764if (IsNewAnnotation)1765PP.AnnotateCachedTokens(Tok);1766}17671768/// Attempt to classify the name at the current token position. This may1769/// form a type, scope or primary expression annotation, or replace the token1770/// with a typo-corrected keyword. This is only appropriate when the current1771/// name must refer to an entity which has already been declared.1772///1773/// \param CCC Indicates how to perform typo-correction for this name. If NULL,1774/// no typo correction will be performed.1775/// \param AllowImplicitTypename Whether we are in a context where a dependent1776/// nested-name-specifier without typename is treated as a type (e.g.1777/// T::type).1778Parser::AnnotatedNameKind1779Parser::TryAnnotateName(CorrectionCandidateCallback *CCC,1780ImplicitTypenameContext AllowImplicitTypename) {1781assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));17821783const bool EnteringContext = false;1784const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);17851786CXXScopeSpec SS;1787if (getLangOpts().CPlusPlus &&1788ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,1789/*ObjectHasErrors=*/false,1790EnteringContext))1791return ANK_Error;17921793if (Tok.isNot(tok::identifier) || SS.isInvalid()) {1794if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation,1795AllowImplicitTypename))1796return ANK_Error;1797return ANK_Unresolved;1798}17991800IdentifierInfo *Name = Tok.getIdentifierInfo();1801SourceLocation NameLoc = Tok.getLocation();18021803// FIXME: Move the tentative declaration logic into ClassifyName so we can1804// typo-correct to tentatively-declared identifiers.1805if (isTentativelyDeclared(Name) && SS.isEmpty()) {1806// Identifier has been tentatively declared, and thus cannot be resolved as1807// an expression. Fall back to annotating it as a type.1808if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation,1809AllowImplicitTypename))1810return ANK_Error;1811return Tok.is(tok::annot_typename) ? ANK_Success : ANK_TentativeDecl;1812}18131814Token Next = NextToken();18151816// Look up and classify the identifier. We don't perform any typo-correction1817// after a scope specifier, because in general we can't recover from typos1818// there (eg, after correcting 'A::template B<X>::C' [sic], we would need to1819// jump back into scope specifier parsing).1820Sema::NameClassification Classification = Actions.ClassifyName(1821getCurScope(), SS, Name, NameLoc, Next, SS.isEmpty() ? CCC : nullptr);18221823// If name lookup found nothing and we guessed that this was a template name,1824// double-check before committing to that interpretation. C++20 requires that1825// we interpret this as a template-id if it can be, but if it can't be, then1826// this is an error recovery case.1827if (Classification.getKind() == Sema::NC_UndeclaredTemplate &&1828isTemplateArgumentList(1) == TPResult::False) {1829// It's not a template-id; re-classify without the '<' as a hint.1830Token FakeNext = Next;1831FakeNext.setKind(tok::unknown);1832Classification =1833Actions.ClassifyName(getCurScope(), SS, Name, NameLoc, FakeNext,1834SS.isEmpty() ? CCC : nullptr);1835}18361837switch (Classification.getKind()) {1838case Sema::NC_Error:1839return ANK_Error;18401841case Sema::NC_Keyword:1842// The identifier was typo-corrected to a keyword.1843Tok.setIdentifierInfo(Name);1844Tok.setKind(Name->getTokenID());1845PP.TypoCorrectToken(Tok);1846if (SS.isNotEmpty())1847AnnotateScopeToken(SS, !WasScopeAnnotation);1848// We've "annotated" this as a keyword.1849return ANK_Success;18501851case Sema::NC_Unknown:1852// It's not something we know about. Leave it unannotated.1853break;18541855case Sema::NC_Type: {1856if (TryAltiVecVectorToken())1857// vector has been found as a type id when altivec is enabled but1858// this is followed by a declaration specifier so this is really the1859// altivec vector token. Leave it unannotated.1860break;1861SourceLocation BeginLoc = NameLoc;1862if (SS.isNotEmpty())1863BeginLoc = SS.getBeginLoc();18641865/// An Objective-C object type followed by '<' is a specialization of1866/// a parameterized class type or a protocol-qualified type.1867ParsedType Ty = Classification.getType();1868if (getLangOpts().ObjC && NextToken().is(tok::less) &&1869(Ty.get()->isObjCObjectType() ||1870Ty.get()->isObjCObjectPointerType())) {1871// Consume the name.1872SourceLocation IdentifierLoc = ConsumeToken();1873SourceLocation NewEndLoc;1874TypeResult NewType1875= parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,1876/*consumeLastToken=*/false,1877NewEndLoc);1878if (NewType.isUsable())1879Ty = NewType.get();1880else if (Tok.is(tok::eof)) // Nothing to do here, bail out...1881return ANK_Error;1882}18831884Tok.setKind(tok::annot_typename);1885setTypeAnnotation(Tok, Ty);1886Tok.setAnnotationEndLoc(Tok.getLocation());1887Tok.setLocation(BeginLoc);1888PP.AnnotateCachedTokens(Tok);1889return ANK_Success;1890}18911892case Sema::NC_OverloadSet:1893Tok.setKind(tok::annot_overload_set);1894setExprAnnotation(Tok, Classification.getExpression());1895Tok.setAnnotationEndLoc(NameLoc);1896if (SS.isNotEmpty())1897Tok.setLocation(SS.getBeginLoc());1898PP.AnnotateCachedTokens(Tok);1899return ANK_Success;19001901case Sema::NC_NonType:1902if (TryAltiVecVectorToken())1903// vector has been found as a non-type id when altivec is enabled but1904// this is followed by a declaration specifier so this is really the1905// altivec vector token. Leave it unannotated.1906break;1907Tok.setKind(tok::annot_non_type);1908setNonTypeAnnotation(Tok, Classification.getNonTypeDecl());1909Tok.setLocation(NameLoc);1910Tok.setAnnotationEndLoc(NameLoc);1911PP.AnnotateCachedTokens(Tok);1912if (SS.isNotEmpty())1913AnnotateScopeToken(SS, !WasScopeAnnotation);1914return ANK_Success;19151916case Sema::NC_UndeclaredNonType:1917case Sema::NC_DependentNonType:1918Tok.setKind(Classification.getKind() == Sema::NC_UndeclaredNonType1919? tok::annot_non_type_undeclared1920: tok::annot_non_type_dependent);1921setIdentifierAnnotation(Tok, Name);1922Tok.setLocation(NameLoc);1923Tok.setAnnotationEndLoc(NameLoc);1924PP.AnnotateCachedTokens(Tok);1925if (SS.isNotEmpty())1926AnnotateScopeToken(SS, !WasScopeAnnotation);1927return ANK_Success;19281929case Sema::NC_TypeTemplate:1930if (Next.isNot(tok::less)) {1931// This may be a type template being used as a template template argument.1932if (SS.isNotEmpty())1933AnnotateScopeToken(SS, !WasScopeAnnotation);1934return ANK_TemplateName;1935}1936[[fallthrough]];1937case Sema::NC_Concept:1938case Sema::NC_VarTemplate:1939case Sema::NC_FunctionTemplate:1940case Sema::NC_UndeclaredTemplate: {1941bool IsConceptName = Classification.getKind() == Sema::NC_Concept;1942// We have a template name followed by '<'. Consume the identifier token so1943// we reach the '<' and annotate it.1944if (Next.is(tok::less))1945ConsumeToken();1946UnqualifiedId Id;1947Id.setIdentifier(Name, NameLoc);1948if (AnnotateTemplateIdToken(1949TemplateTy::make(Classification.getTemplateName()),1950Classification.getTemplateNameKind(), SS, SourceLocation(), Id,1951/*AllowTypeAnnotation=*/!IsConceptName,1952/*TypeConstraint=*/IsConceptName))1953return ANK_Error;1954if (SS.isNotEmpty())1955AnnotateScopeToken(SS, !WasScopeAnnotation);1956return ANK_Success;1957}1958}19591960// Unable to classify the name, but maybe we can annotate a scope specifier.1961if (SS.isNotEmpty())1962AnnotateScopeToken(SS, !WasScopeAnnotation);1963return ANK_Unresolved;1964}19651966bool Parser::TryKeywordIdentFallback(bool DisableKeyword) {1967assert(Tok.isNot(tok::identifier));1968Diag(Tok, diag::ext_keyword_as_ident)1969<< PP.getSpelling(Tok)1970<< DisableKeyword;1971if (DisableKeyword)1972Tok.getIdentifierInfo()->revertTokenIDToIdentifier();1973Tok.setKind(tok::identifier);1974return true;1975}19761977/// TryAnnotateTypeOrScopeToken - If the current token position is on a1978/// typename (possibly qualified in C++) or a C++ scope specifier not followed1979/// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens1980/// with a single annotation token representing the typename or C++ scope1981/// respectively.1982/// This simplifies handling of C++ scope specifiers and allows efficient1983/// backtracking without the need to re-parse and resolve nested-names and1984/// typenames.1985/// It will mainly be called when we expect to treat identifiers as typenames1986/// (if they are typenames). For example, in C we do not expect identifiers1987/// inside expressions to be treated as typenames so it will not be called1988/// for expressions in C.1989/// The benefit for C/ObjC is that a typename will be annotated and1990/// Actions.getTypeName will not be needed to be called again (e.g. getTypeName1991/// will not be called twice, once to check whether we have a declaration1992/// specifier, and another one to get the actual type inside1993/// ParseDeclarationSpecifiers).1994///1995/// This returns true if an error occurred.1996///1997/// Note that this routine emits an error if you call it with ::new or ::delete1998/// as the current tokens, so only call it in contexts where these are invalid.1999bool Parser::TryAnnotateTypeOrScopeToken(2000ImplicitTypenameContext AllowImplicitTypename) {2001assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||2002Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope) ||2003Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id) ||2004Tok.is(tok::kw___super) || Tok.is(tok::kw_auto) ||2005Tok.is(tok::annot_pack_indexing_type)) &&2006"Cannot be a type or scope token!");20072008if (Tok.is(tok::kw_typename)) {2009// MSVC lets you do stuff like:2010// typename typedef T_::D D;2011//2012// We will consume the typedef token here and put it back after we have2013// parsed the first identifier, transforming it into something more like:2014// typename T_::D typedef D;2015if (getLangOpts().MSVCCompat && NextToken().is(tok::kw_typedef)) {2016Token TypedefToken;2017PP.Lex(TypedefToken);2018bool Result = TryAnnotateTypeOrScopeToken(AllowImplicitTypename);2019PP.EnterToken(Tok, /*IsReinject=*/true);2020Tok = TypedefToken;2021if (!Result)2022Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename);2023return Result;2024}20252026// Parse a C++ typename-specifier, e.g., "typename T::type".2027//2028// typename-specifier:2029// 'typename' '::' [opt] nested-name-specifier identifier2030// 'typename' '::' [opt] nested-name-specifier template [opt]2031// simple-template-id2032SourceLocation TypenameLoc = ConsumeToken();2033CXXScopeSpec SS;2034if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,2035/*ObjectHasErrors=*/false,2036/*EnteringContext=*/false, nullptr,2037/*IsTypename*/ true))2038return true;2039if (SS.isEmpty()) {2040if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) ||2041Tok.is(tok::annot_decltype)) {2042// Attempt to recover by skipping the invalid 'typename'2043if (Tok.is(tok::annot_decltype) ||2044(!TryAnnotateTypeOrScopeToken(AllowImplicitTypename) &&2045Tok.isAnnotation())) {2046unsigned DiagID = diag::err_expected_qualified_after_typename;2047// MS compatibility: MSVC permits using known types with typename.2048// e.g. "typedef typename T* pointer_type"2049if (getLangOpts().MicrosoftExt)2050DiagID = diag::warn_expected_qualified_after_typename;2051Diag(Tok.getLocation(), DiagID);2052return false;2053}2054}2055if (Tok.isEditorPlaceholder())2056return true;20572058Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);2059return true;2060}20612062bool TemplateKWPresent = false;2063if (Tok.is(tok::kw_template)) {2064ConsumeToken();2065TemplateKWPresent = true;2066}20672068TypeResult Ty;2069if (Tok.is(tok::identifier)) {2070if (TemplateKWPresent && NextToken().isNot(tok::less)) {2071Diag(Tok.getLocation(),2072diag::missing_template_arg_list_after_template_kw);2073return true;2074}2075Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,2076*Tok.getIdentifierInfo(),2077Tok.getLocation());2078} else if (Tok.is(tok::annot_template_id)) {2079TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);2080if (!TemplateId->mightBeType()) {2081Diag(Tok, diag::err_typename_refers_to_non_type_template)2082<< Tok.getAnnotationRange();2083return true;2084}20852086ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),2087TemplateId->NumArgs);20882089Ty = TemplateId->isInvalid()2090? TypeError()2091: Actions.ActOnTypenameType(2092getCurScope(), TypenameLoc, SS, TemplateId->TemplateKWLoc,2093TemplateId->Template, TemplateId->Name,2094TemplateId->TemplateNameLoc, TemplateId->LAngleLoc,2095TemplateArgsPtr, TemplateId->RAngleLoc);2096} else {2097Diag(Tok, diag::err_expected_type_name_after_typename)2098<< SS.getRange();2099return true;2100}21012102SourceLocation EndLoc = Tok.getLastLoc();2103Tok.setKind(tok::annot_typename);2104setTypeAnnotation(Tok, Ty);2105Tok.setAnnotationEndLoc(EndLoc);2106Tok.setLocation(TypenameLoc);2107PP.AnnotateCachedTokens(Tok);2108return false;2109}21102111// Remembers whether the token was originally a scope annotation.2112bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);21132114CXXScopeSpec SS;2115if (getLangOpts().CPlusPlus)2116if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,2117/*ObjectHasErrors=*/false,2118/*EnteringContext*/ false))2119return true;21202121return TryAnnotateTypeOrScopeTokenAfterScopeSpec(SS, !WasScopeAnnotation,2122AllowImplicitTypename);2123}21242125/// Try to annotate a type or scope token, having already parsed an2126/// optional scope specifier. \p IsNewScope should be \c true unless the scope2127/// specifier was extracted from an existing tok::annot_cxxscope annotation.2128bool Parser::TryAnnotateTypeOrScopeTokenAfterScopeSpec(2129CXXScopeSpec &SS, bool IsNewScope,2130ImplicitTypenameContext AllowImplicitTypename) {2131if (Tok.is(tok::identifier)) {2132// Determine whether the identifier is a type name.2133if (ParsedType Ty = Actions.getTypeName(2134*Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), &SS,2135false, NextToken().is(tok::period), nullptr,2136/*IsCtorOrDtorName=*/false,2137/*NonTrivialTypeSourceInfo=*/true,2138/*IsClassTemplateDeductionContext=*/true, AllowImplicitTypename)) {2139SourceLocation BeginLoc = Tok.getLocation();2140if (SS.isNotEmpty()) // it was a C++ qualified type name.2141BeginLoc = SS.getBeginLoc();21422143/// An Objective-C object type followed by '<' is a specialization of2144/// a parameterized class type or a protocol-qualified type.2145if (getLangOpts().ObjC && NextToken().is(tok::less) &&2146(Ty.get()->isObjCObjectType() ||2147Ty.get()->isObjCObjectPointerType())) {2148// Consume the name.2149SourceLocation IdentifierLoc = ConsumeToken();2150SourceLocation NewEndLoc;2151TypeResult NewType2152= parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,2153/*consumeLastToken=*/false,2154NewEndLoc);2155if (NewType.isUsable())2156Ty = NewType.get();2157else if (Tok.is(tok::eof)) // Nothing to do here, bail out...2158return false;2159}21602161// This is a typename. Replace the current token in-place with an2162// annotation type token.2163Tok.setKind(tok::annot_typename);2164setTypeAnnotation(Tok, Ty);2165Tok.setAnnotationEndLoc(Tok.getLocation());2166Tok.setLocation(BeginLoc);21672168// In case the tokens were cached, have Preprocessor replace2169// them with the annotation token.2170PP.AnnotateCachedTokens(Tok);2171return false;2172}21732174if (!getLangOpts().CPlusPlus) {2175// If we're in C, the only place we can have :: tokens is C232176// attribute which is parsed elsewhere. If the identifier is not a type,2177// then it can't be scope either, just early exit.2178return false;2179}21802181// If this is a template-id, annotate with a template-id or type token.2182// FIXME: This appears to be dead code. We already have formed template-id2183// tokens when parsing the scope specifier; this can never form a new one.2184if (NextToken().is(tok::less)) {2185TemplateTy Template;2186UnqualifiedId TemplateName;2187TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());2188bool MemberOfUnknownSpecialization;2189if (TemplateNameKind TNK = Actions.isTemplateName(2190getCurScope(), SS,2191/*hasTemplateKeyword=*/false, TemplateName,2192/*ObjectType=*/nullptr, /*EnteringContext*/false, Template,2193MemberOfUnknownSpecialization)) {2194// Only annotate an undeclared template name as a template-id if the2195// following tokens have the form of a template argument list.2196if (TNK != TNK_Undeclared_template ||2197isTemplateArgumentList(1) != TPResult::False) {2198// Consume the identifier.2199ConsumeToken();2200if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),2201TemplateName)) {2202// If an unrecoverable error occurred, we need to return true here,2203// because the token stream is in a damaged state. We may not2204// return a valid identifier.2205return true;2206}2207}2208}2209}22102211// The current token, which is either an identifier or a2212// template-id, is not part of the annotation. Fall through to2213// push that token back into the stream and complete the C++ scope2214// specifier annotation.2215}22162217if (Tok.is(tok::annot_template_id)) {2218TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);2219if (TemplateId->Kind == TNK_Type_template) {2220// A template-id that refers to a type was parsed into a2221// template-id annotation in a context where we weren't allowed2222// to produce a type annotation token. Update the template-id2223// annotation token to a type annotation token now.2224AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);2225return false;2226}2227}22282229if (SS.isEmpty())2230return false;22312232// A C++ scope specifier that isn't followed by a typename.2233AnnotateScopeToken(SS, IsNewScope);2234return false;2235}22362237/// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only2238/// annotates C++ scope specifiers and template-ids. This returns2239/// true if there was an error that could not be recovered from.2240///2241/// Note that this routine emits an error if you call it with ::new or ::delete2242/// as the current tokens, so only call it in contexts where these are invalid.2243bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) {2244assert(getLangOpts().CPlusPlus &&2245"Call sites of this function should be guarded by checking for C++");2246assert(MightBeCXXScopeToken() && "Cannot be a type or scope token!");22472248CXXScopeSpec SS;2249if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,2250/*ObjectHasErrors=*/false,2251EnteringContext))2252return true;2253if (SS.isEmpty())2254return false;22552256AnnotateScopeToken(SS, true);2257return false;2258}22592260bool Parser::isTokenEqualOrEqualTypo() {2261tok::TokenKind Kind = Tok.getKind();2262switch (Kind) {2263default:2264return false;2265case tok::ampequal: // &=2266case tok::starequal: // *=2267case tok::plusequal: // +=2268case tok::minusequal: // -=2269case tok::exclaimequal: // !=2270case tok::slashequal: // /=2271case tok::percentequal: // %=2272case tok::lessequal: // <=2273case tok::lesslessequal: // <<=2274case tok::greaterequal: // >=2275case tok::greatergreaterequal: // >>=2276case tok::caretequal: // ^=2277case tok::pipeequal: // |=2278case tok::equalequal: // ==2279Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal)2280<< Kind2281<< FixItHint::CreateReplacement(SourceRange(Tok.getLocation()), "=");2282[[fallthrough]];2283case tok::equal:2284return true;2285}2286}22872288SourceLocation Parser::handleUnexpectedCodeCompletionToken() {2289assert(Tok.is(tok::code_completion));2290PrevTokLocation = Tok.getLocation();22912292for (Scope *S = getCurScope(); S; S = S->getParent()) {2293if (S->isFunctionScope()) {2294cutOffParsing();2295Actions.CodeCompletion().CodeCompleteOrdinaryName(2296getCurScope(), SemaCodeCompletion::PCC_RecoveryInFunction);2297return PrevTokLocation;2298}22992300if (S->isClassScope()) {2301cutOffParsing();2302Actions.CodeCompletion().CodeCompleteOrdinaryName(2303getCurScope(), SemaCodeCompletion::PCC_Class);2304return PrevTokLocation;2305}2306}23072308cutOffParsing();2309Actions.CodeCompletion().CodeCompleteOrdinaryName(2310getCurScope(), SemaCodeCompletion::PCC_Namespace);2311return PrevTokLocation;2312}23132314// Code-completion pass-through functions23152316void Parser::CodeCompleteDirective(bool InConditional) {2317Actions.CodeCompletion().CodeCompletePreprocessorDirective(InConditional);2318}23192320void Parser::CodeCompleteInConditionalExclusion() {2321Actions.CodeCompletion().CodeCompleteInPreprocessorConditionalExclusion(2322getCurScope());2323}23242325void Parser::CodeCompleteMacroName(bool IsDefinition) {2326Actions.CodeCompletion().CodeCompletePreprocessorMacroName(IsDefinition);2327}23282329void Parser::CodeCompletePreprocessorExpression() {2330Actions.CodeCompletion().CodeCompletePreprocessorExpression();2331}23322333void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro,2334MacroInfo *MacroInfo,2335unsigned ArgumentIndex) {2336Actions.CodeCompletion().CodeCompletePreprocessorMacroArgument(2337getCurScope(), Macro, MacroInfo, ArgumentIndex);2338}23392340void Parser::CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) {2341Actions.CodeCompletion().CodeCompleteIncludedFile(Dir, IsAngled);2342}23432344void Parser::CodeCompleteNaturalLanguage() {2345Actions.CodeCompletion().CodeCompleteNaturalLanguage();2346}23472348bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) {2349assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&2350"Expected '__if_exists' or '__if_not_exists'");2351Result.IsIfExists = Tok.is(tok::kw___if_exists);2352Result.KeywordLoc = ConsumeToken();23532354BalancedDelimiterTracker T(*this, tok::l_paren);2355if (T.consumeOpen()) {2356Diag(Tok, diag::err_expected_lparen_after)2357<< (Result.IsIfExists? "__if_exists" : "__if_not_exists");2358return true;2359}23602361// Parse nested-name-specifier.2362if (getLangOpts().CPlusPlus)2363ParseOptionalCXXScopeSpecifier(Result.SS, /*ObjectType=*/nullptr,2364/*ObjectHasErrors=*/false,2365/*EnteringContext=*/false);23662367// Check nested-name specifier.2368if (Result.SS.isInvalid()) {2369T.skipToEnd();2370return true;2371}23722373// Parse the unqualified-id.2374SourceLocation TemplateKWLoc; // FIXME: parsed, but unused.2375if (ParseUnqualifiedId(Result.SS, /*ObjectType=*/nullptr,2376/*ObjectHadErrors=*/false, /*EnteringContext*/ false,2377/*AllowDestructorName*/ true,2378/*AllowConstructorName*/ true,2379/*AllowDeductionGuide*/ false, &TemplateKWLoc,2380Result.Name)) {2381T.skipToEnd();2382return true;2383}23842385if (T.consumeClose())2386return true;23872388// Check if the symbol exists.2389switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc,2390Result.IsIfExists, Result.SS,2391Result.Name)) {2392case Sema::IER_Exists:2393Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip;2394break;23952396case Sema::IER_DoesNotExist:2397Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip;2398break;23992400case Sema::IER_Dependent:2401Result.Behavior = IEB_Dependent;2402break;24032404case Sema::IER_Error:2405return true;2406}24072408return false;2409}24102411void Parser::ParseMicrosoftIfExistsExternalDeclaration() {2412IfExistsCondition Result;2413if (ParseMicrosoftIfExistsCondition(Result))2414return;24152416BalancedDelimiterTracker Braces(*this, tok::l_brace);2417if (Braces.consumeOpen()) {2418Diag(Tok, diag::err_expected) << tok::l_brace;2419return;2420}24212422switch (Result.Behavior) {2423case IEB_Parse:2424// Parse declarations below.2425break;24262427case IEB_Dependent:2428llvm_unreachable("Cannot have a dependent external declaration");24292430case IEB_Skip:2431Braces.skipToEnd();2432return;2433}24342435// Parse the declarations.2436// FIXME: Support module import within __if_exists?2437while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {2438ParsedAttributes Attrs(AttrFactory);2439MaybeParseCXX11Attributes(Attrs);2440ParsedAttributes EmptyDeclSpecAttrs(AttrFactory);2441DeclGroupPtrTy Result = ParseExternalDeclaration(Attrs, EmptyDeclSpecAttrs);2442if (Result && !getCurScope()->getParent())2443Actions.getASTConsumer().HandleTopLevelDecl(Result.get());2444}2445Braces.consumeClose();2446}24472448/// Parse a declaration beginning with the 'module' keyword or C++202449/// context-sensitive keyword (optionally preceded by 'export').2450///2451/// module-declaration: [C++20]2452/// 'export'[opt] 'module' module-name attribute-specifier-seq[opt] ';'2453///2454/// global-module-fragment: [C++2a]2455/// 'module' ';' top-level-declaration-seq[opt]2456/// module-declaration: [C++2a]2457/// 'export'[opt] 'module' module-name module-partition[opt]2458/// attribute-specifier-seq[opt] ';'2459/// private-module-fragment: [C++2a]2460/// 'module' ':' 'private' ';' top-level-declaration-seq[opt]2461Parser::DeclGroupPtrTy2462Parser::ParseModuleDecl(Sema::ModuleImportState &ImportState) {2463SourceLocation StartLoc = Tok.getLocation();24642465Sema::ModuleDeclKind MDK = TryConsumeToken(tok::kw_export)2466? Sema::ModuleDeclKind::Interface2467: Sema::ModuleDeclKind::Implementation;24682469assert(2470(Tok.is(tok::kw_module) ||2471(Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_module)) &&2472"not a module declaration");2473SourceLocation ModuleLoc = ConsumeToken();24742475// Attributes appear after the module name, not before.2476// FIXME: Suggest moving the attributes later with a fixit.2477DiagnoseAndSkipCXX11Attributes();24782479// Parse a global-module-fragment, if present.2480if (getLangOpts().CPlusPlusModules && Tok.is(tok::semi)) {2481SourceLocation SemiLoc = ConsumeToken();2482if (ImportState != Sema::ModuleImportState::FirstDecl) {2483Diag(StartLoc, diag::err_global_module_introducer_not_at_start)2484<< SourceRange(StartLoc, SemiLoc);2485return nullptr;2486}2487if (MDK == Sema::ModuleDeclKind::Interface) {2488Diag(StartLoc, diag::err_module_fragment_exported)2489<< /*global*/0 << FixItHint::CreateRemoval(StartLoc);2490}2491ImportState = Sema::ModuleImportState::GlobalFragment;2492return Actions.ActOnGlobalModuleFragmentDecl(ModuleLoc);2493}24942495// Parse a private-module-fragment, if present.2496if (getLangOpts().CPlusPlusModules && Tok.is(tok::colon) &&2497NextToken().is(tok::kw_private)) {2498if (MDK == Sema::ModuleDeclKind::Interface) {2499Diag(StartLoc, diag::err_module_fragment_exported)2500<< /*private*/1 << FixItHint::CreateRemoval(StartLoc);2501}2502ConsumeToken();2503SourceLocation PrivateLoc = ConsumeToken();2504DiagnoseAndSkipCXX11Attributes();2505ExpectAndConsumeSemi(diag::err_private_module_fragment_expected_semi);2506ImportState = ImportState == Sema::ModuleImportState::ImportAllowed2507? Sema::ModuleImportState::PrivateFragmentImportAllowed2508: Sema::ModuleImportState::PrivateFragmentImportFinished;2509return Actions.ActOnPrivateModuleFragmentDecl(ModuleLoc, PrivateLoc);2510}25112512SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;2513if (ParseModuleName(ModuleLoc, Path, /*IsImport*/ false))2514return nullptr;25152516// Parse the optional module-partition.2517SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Partition;2518if (Tok.is(tok::colon)) {2519SourceLocation ColonLoc = ConsumeToken();2520if (!getLangOpts().CPlusPlusModules)2521Diag(ColonLoc, diag::err_unsupported_module_partition)2522<< SourceRange(ColonLoc, Partition.back().second);2523// Recover by ignoring the partition name.2524else if (ParseModuleName(ModuleLoc, Partition, /*IsImport*/ false))2525return nullptr;2526}25272528// We don't support any module attributes yet; just parse them and diagnose.2529ParsedAttributes Attrs(AttrFactory);2530MaybeParseCXX11Attributes(Attrs);2531ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_module_attr,2532diag::err_keyword_not_module_attr,2533/*DiagnoseEmptyAttrs=*/false,2534/*WarnOnUnknownAttrs=*/true);25352536ExpectAndConsumeSemi(diag::err_module_expected_semi);25372538return Actions.ActOnModuleDecl(StartLoc, ModuleLoc, MDK, Path, Partition,2539ImportState);2540}25412542/// Parse a module import declaration. This is essentially the same for2543/// Objective-C and C++20 except for the leading '@' (in ObjC) and the2544/// trailing optional attributes (in C++).2545///2546/// [ObjC] @import declaration:2547/// '@' 'import' module-name ';'2548/// [ModTS] module-import-declaration:2549/// 'import' module-name attribute-specifier-seq[opt] ';'2550/// [C++20] module-import-declaration:2551/// 'export'[opt] 'import' module-name2552/// attribute-specifier-seq[opt] ';'2553/// 'export'[opt] 'import' module-partition2554/// attribute-specifier-seq[opt] ';'2555/// 'export'[opt] 'import' header-name2556/// attribute-specifier-seq[opt] ';'2557Decl *Parser::ParseModuleImport(SourceLocation AtLoc,2558Sema::ModuleImportState &ImportState) {2559SourceLocation StartLoc = AtLoc.isInvalid() ? Tok.getLocation() : AtLoc;25602561SourceLocation ExportLoc;2562TryConsumeToken(tok::kw_export, ExportLoc);25632564assert((AtLoc.isInvalid() ? Tok.isOneOf(tok::kw_import, tok::identifier)2565: Tok.isObjCAtKeyword(tok::objc_import)) &&2566"Improper start to module import");2567bool IsObjCAtImport = Tok.isObjCAtKeyword(tok::objc_import);2568SourceLocation ImportLoc = ConsumeToken();25692570// For C++20 modules, we can have "name" or ":Partition name" as valid input.2571SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;2572bool IsPartition = false;2573Module *HeaderUnit = nullptr;2574if (Tok.is(tok::header_name)) {2575// This is a header import that the preprocessor decided we should skip2576// because it was malformed in some way. Parse and ignore it; it's already2577// been diagnosed.2578ConsumeToken();2579} else if (Tok.is(tok::annot_header_unit)) {2580// This is a header import that the preprocessor mapped to a module import.2581HeaderUnit = reinterpret_cast<Module *>(Tok.getAnnotationValue());2582ConsumeAnnotationToken();2583} else if (Tok.is(tok::colon)) {2584SourceLocation ColonLoc = ConsumeToken();2585if (!getLangOpts().CPlusPlusModules)2586Diag(ColonLoc, diag::err_unsupported_module_partition)2587<< SourceRange(ColonLoc, Path.back().second);2588// Recover by leaving partition empty.2589else if (ParseModuleName(ColonLoc, Path, /*IsImport*/ true))2590return nullptr;2591else2592IsPartition = true;2593} else {2594if (ParseModuleName(ImportLoc, Path, /*IsImport*/ true))2595return nullptr;2596}25972598ParsedAttributes Attrs(AttrFactory);2599MaybeParseCXX11Attributes(Attrs);2600// We don't support any module import attributes yet.2601ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_import_attr,2602diag::err_keyword_not_import_attr,2603/*DiagnoseEmptyAttrs=*/false,2604/*WarnOnUnknownAttrs=*/true);26052606if (PP.hadModuleLoaderFatalFailure()) {2607// With a fatal failure in the module loader, we abort parsing.2608cutOffParsing();2609return nullptr;2610}26112612// Diagnose mis-imports.2613bool SeenError = true;2614switch (ImportState) {2615case Sema::ModuleImportState::ImportAllowed:2616SeenError = false;2617break;2618case Sema::ModuleImportState::FirstDecl:2619// If we found an import decl as the first declaration, we must be not in2620// a C++20 module unit or we are in an invalid state.2621ImportState = Sema::ModuleImportState::NotACXX20Module;2622[[fallthrough]];2623case Sema::ModuleImportState::NotACXX20Module:2624// We can only import a partition within a module purview.2625if (IsPartition)2626Diag(ImportLoc, diag::err_partition_import_outside_module);2627else2628SeenError = false;2629break;2630case Sema::ModuleImportState::GlobalFragment:2631case Sema::ModuleImportState::PrivateFragmentImportAllowed:2632// We can only have pre-processor directives in the global module fragment2633// which allows pp-import, but not of a partition (since the global module2634// does not have partitions).2635// We cannot import a partition into a private module fragment, since2636// [module.private.frag]/1 disallows private module fragments in a multi-2637// TU module.2638if (IsPartition || (HeaderUnit && HeaderUnit->Kind !=2639Module::ModuleKind::ModuleHeaderUnit))2640Diag(ImportLoc, diag::err_import_in_wrong_fragment)2641<< IsPartition2642<< (ImportState == Sema::ModuleImportState::GlobalFragment ? 0 : 1);2643else2644SeenError = false;2645break;2646case Sema::ModuleImportState::ImportFinished:2647case Sema::ModuleImportState::PrivateFragmentImportFinished:2648if (getLangOpts().CPlusPlusModules)2649Diag(ImportLoc, diag::err_import_not_allowed_here);2650else2651SeenError = false;2652break;2653}2654if (SeenError) {2655ExpectAndConsumeSemi(diag::err_module_expected_semi);2656return nullptr;2657}26582659DeclResult Import;2660if (HeaderUnit)2661Import =2662Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, HeaderUnit);2663else if (!Path.empty())2664Import = Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Path,2665IsPartition);2666ExpectAndConsumeSemi(diag::err_module_expected_semi);2667if (Import.isInvalid())2668return nullptr;26692670// Using '@import' in framework headers requires modules to be enabled so that2671// the header is parseable. Emit a warning to make the user aware.2672if (IsObjCAtImport && AtLoc.isValid()) {2673auto &SrcMgr = PP.getSourceManager();2674auto FE = SrcMgr.getFileEntryRefForID(SrcMgr.getFileID(AtLoc));2675if (FE && llvm::sys::path::parent_path(FE->getDir().getName())2676.ends_with(".framework"))2677Diags.Report(AtLoc, diag::warn_atimport_in_framework_header);2678}26792680return Import.get();2681}26822683/// Parse a C++ / Objective-C module name (both forms use the same2684/// grammar).2685///2686/// module-name:2687/// module-name-qualifier[opt] identifier2688/// module-name-qualifier:2689/// module-name-qualifier[opt] identifier '.'2690bool Parser::ParseModuleName(2691SourceLocation UseLoc,2692SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path,2693bool IsImport) {2694// Parse the module path.2695while (true) {2696if (!Tok.is(tok::identifier)) {2697if (Tok.is(tok::code_completion)) {2698cutOffParsing();2699Actions.CodeCompletion().CodeCompleteModuleImport(UseLoc, Path);2700return true;2701}27022703Diag(Tok, diag::err_module_expected_ident) << IsImport;2704SkipUntil(tok::semi);2705return true;2706}27072708// Record this part of the module path.2709Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation()));2710ConsumeToken();27112712if (Tok.isNot(tok::period))2713return false;27142715ConsumeToken();2716}2717}27182719/// Try recover parser when module annotation appears where it must not2720/// be found.2721/// \returns false if the recover was successful and parsing may be continued, or2722/// true if parser must bail out to top level and handle the token there.2723bool Parser::parseMisplacedModuleImport() {2724while (true) {2725switch (Tok.getKind()) {2726case tok::annot_module_end:2727// If we recovered from a misplaced module begin, we expect to hit a2728// misplaced module end too. Stay in the current context when this2729// happens.2730if (MisplacedModuleBeginCount) {2731--MisplacedModuleBeginCount;2732Actions.ActOnAnnotModuleEnd(2733Tok.getLocation(),2734reinterpret_cast<Module *>(Tok.getAnnotationValue()));2735ConsumeAnnotationToken();2736continue;2737}2738// Inform caller that recovery failed, the error must be handled at upper2739// level. This will generate the desired "missing '}' at end of module"2740// diagnostics on the way out.2741return true;2742case tok::annot_module_begin:2743// Recover by entering the module (Sema will diagnose).2744Actions.ActOnAnnotModuleBegin(2745Tok.getLocation(),2746reinterpret_cast<Module *>(Tok.getAnnotationValue()));2747ConsumeAnnotationToken();2748++MisplacedModuleBeginCount;2749continue;2750case tok::annot_module_include:2751// Module import found where it should not be, for instance, inside a2752// namespace. Recover by importing the module.2753Actions.ActOnAnnotModuleInclude(2754Tok.getLocation(),2755reinterpret_cast<Module *>(Tok.getAnnotationValue()));2756ConsumeAnnotationToken();2757// If there is another module import, process it.2758continue;2759default:2760return false;2761}2762}2763return false;2764}27652766void Parser::diagnoseUseOfC11Keyword(const Token &Tok) {2767// Warn that this is a C11 extension if in an older mode or if in C++.2768// Otherwise, warn that it is incompatible with standards before C11 if in2769// C11 or later.2770Diag(Tok, getLangOpts().C11 ? diag::warn_c11_compat_keyword2771: diag::ext_c11_feature)2772<< Tok.getName();2773}27742775bool BalancedDelimiterTracker::diagnoseOverflow() {2776P.Diag(P.Tok, diag::err_bracket_depth_exceeded)2777<< P.getLangOpts().BracketDepth;2778P.Diag(P.Tok, diag::note_bracket_depth);2779P.cutOffParsing();2780return true;2781}27822783bool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID,2784const char *Msg,2785tok::TokenKind SkipToTok) {2786LOpen = P.Tok.getLocation();2787if (P.ExpectAndConsume(Kind, DiagID, Msg)) {2788if (SkipToTok != tok::unknown)2789P.SkipUntil(SkipToTok, Parser::StopAtSemi);2790return true;2791}27922793if (getDepth() < P.getLangOpts().BracketDepth)2794return false;27952796return diagnoseOverflow();2797}27982799bool BalancedDelimiterTracker::diagnoseMissingClose() {2800assert(!P.Tok.is(Close) && "Should have consumed closing delimiter");28012802if (P.Tok.is(tok::annot_module_end))2803P.Diag(P.Tok, diag::err_missing_before_module_end) << Close;2804else2805P.Diag(P.Tok, diag::err_expected) << Close;2806P.Diag(LOpen, diag::note_matching) << Kind;28072808// If we're not already at some kind of closing bracket, skip to our closing2809// token.2810if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) &&2811P.Tok.isNot(tok::r_square) &&2812P.SkipUntil(Close, FinalToken,2813Parser::StopAtSemi | Parser::StopBeforeMatch) &&2814P.Tok.is(Close))2815LClose = P.ConsumeAnyToken();2816return true;2817}28182819void BalancedDelimiterTracker::skipToEnd() {2820P.SkipUntil(Close, Parser::StopBeforeMatch);2821consumeClose();2822}282328242825