26#include "llvm/ADT/STLForwardCompat.h"
27#include "llvm/Support/Path.h"
28#include "llvm/Support/TimeProfiler.h"
39 explicit ActionCommentHandler(Sema &S) : S(S) { }
41 bool HandleComment(Preprocessor &PP, SourceRange Comment)
override {
42 S.ActOnComment(Comment);
51 Ident__except = PP.getIdentifierInfo(
"__except");
58 PreferredType(&actions.getASTContext(), pp.isCodeCompletionEnabled()),
59 Actions(actions), Diags(PP.getDiagnostics()), StackHandler(Diags),
60 GreaterThanIsOperator(
true), ColonIsSacred(
false),
61 InMessageExpression(
false), ParsingInObjCContainer(
false),
62 TemplateParameterDepth(0) {
65 Tok.setKind(tok::eof);
66 Actions.CurScope =
nullptr;
68 CurParsedObjCImpl =
nullptr;
72 initializePragmaHandlers();
74 CommentSemaHandler.reset(
new ActionCommentHandler(actions));
75 PP.addCommentHandler(CommentSemaHandler.get());
77 PP.setCodeCompletionHandler(*
this);
79 Actions.ParseTypeFromStringCallback =
80 [
this](StringRef TypeStr, StringRef Context,
SourceLocation IncludeLoc) {
81 return this->ParseTypeFromString(TypeStr, Context, IncludeLoc);
86 return Diags.Report(Loc, DiagID);
90 return Diag(Tok.getLocation(), DiagID);
94 unsigned CompatDiagId) {
100 return DiagCompat(Tok.getLocation(), CompatDiagId);
119 switch (ExpectedTok) {
121 return Tok.is(tok::colon) ||
Tok.is(tok::comma);
122 default:
return false;
126bool Parser::ExpectAndConsume(
tok::TokenKind ExpectedTok,
unsigned DiagID,
128 if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) {
135 SourceLocation Loc = Tok.getLocation();
137 DiagnosticBuilder DB =
Diag(Loc, DiagID);
140 if (DiagID == diag::err_expected)
142 else if (DiagID == diag::err_expected_after)
143 DB << Msg << ExpectedTok;
153 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
154 const char *Spelling =
nullptr;
158 DiagnosticBuilder DB =
162 if (DiagID == diag::err_expected)
164 else if (DiagID == diag::err_expected_after)
165 DB << Msg << ExpectedTok;
172bool Parser::ExpectAndConsumeSemi(
unsigned DiagID, StringRef TokenUsed) {
176 if (Tok.is(tok::code_completion)) {
177 handleUnexpectedCodeCompletionToken();
181 if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) &&
183 Diag(Tok, diag::err_extraneous_token_before_semi)
184 << PP.getSpelling(Tok)
191 return ExpectAndConsume(tok::semi, DiagID , TokenUsed);
195 if (!Tok.is(tok::semi))
return;
197 bool HadMultipleSemis =
false;
198 SourceLocation StartLoc = Tok.getLocation();
199 SourceLocation EndLoc = Tok.getLocation();
202 while ((Tok.is(tok::semi) && !Tok.isAtStartOfLine())) {
203 HadMultipleSemis =
true;
204 EndLoc = Tok.getLocation();
212 Diag(StartLoc, diag::warn_cxx98_compat_top_level_semi)
215 Diag(StartLoc, diag::ext_extra_semi_cxx11)
221 Diag(StartLoc, diag::ext_extra_semi)
224 TST, Actions.getASTContext().getPrintingPolicy())
228 Diag(StartLoc, diag::warn_extra_semi_after_mem_fn_def)
232bool Parser::expectIdentifier() {
233 if (Tok.is(tok::identifier))
235 if (
const auto *II = Tok.getIdentifierInfo()) {
237 Diag(Tok, diag::err_expected_token_instead_of_objcxx_keyword)
238 << tok::identifier << Tok.getIdentifierInfo();
243 Diag(Tok, diag::err_expected) << tok::identifier;
251 SourceLocation SecondTokLoc = Tok.getLocation();
256 PP.getSourceManager().getFileID(FirstTokLoc) !=
257 PP.getSourceManager().getFileID(SecondTokLoc)) {
258 Diag(FirstTokLoc, diag::warn_compound_token_split_by_macro)
259 << (FirstTokKind == Tok.getKind()) << FirstTokKind << Tok.getKind()
260 <<
static_cast<int>(Op) << SourceRange(FirstTokLoc);
261 Diag(SecondTokLoc, diag::note_compound_token_split_second_token_here)
262 << (FirstTokKind == Tok.getKind()) << Tok.getKind()
263 << SourceRange(SecondTokLoc);
268 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
269 SourceLocation SpaceLoc = PP.getLocForEndOfToken(FirstTokLoc);
271 SpaceLoc = FirstTokLoc;
272 Diag(SpaceLoc, diag::warn_compound_token_split_by_whitespace)
273 << (FirstTokKind == Tok.getKind()) << FirstTokKind << Tok.getKind()
274 <<
static_cast<int>(Op) << SourceRange(FirstTokLoc, SecondTokLoc);
284 return (
static_cast<unsigned>(L) &
static_cast<unsigned>(R)) != 0;
290 bool isFirstTokenSkipped =
true;
293 for (
unsigned i = 0, NumToks = Toks.size(); i != NumToks; ++i) {
294 if (Tok.is(Toks[i])) {
307 if (Toks.size() == 1 && Toks[0] == tok::eof &&
310 while (Tok.isNot(tok::eof))
315 switch (Tok.getKind()) {
320 case tok::annot_pragma_openmp:
321 case tok::annot_attr_openmp:
322 case tok::annot_pragma_openmp_end:
324 if (OpenMPDirectiveParsing)
326 ConsumeAnnotationToken();
328 case tok::annot_pragma_openacc:
329 case tok::annot_pragma_openacc_end:
331 if (OpenACCDirectiveParsing)
333 ConsumeAnnotationToken();
335 case tok::annot_module_begin:
336 case tok::annot_module_end:
337 case tok::annot_module_include:
338 case tok::annot_repl_input_end:
344 case tok::code_completion:
346 handleUnexpectedCodeCompletionToken();
388 if (ParenCount && !isFirstTokenSkipped)
393 if (BracketCount && !isFirstTokenSkipped)
398 if (BraceCount && !isFirstTokenSkipped)
412 isFirstTokenSkipped =
false;
421 if (NumCachedScopes) {
422 Scope *N = ScopeCache[--NumCachedScopes];
424 Actions.CurScope = N;
435 Actions.ActOnPopScope(Tok.getLocation(),
getCurScope());
438 Actions.CurScope = OldScope->
getParent();
440 if (NumCachedScopes == ScopeCacheSize)
443 ScopeCache[NumCachedScopes++] = OldScope;
446Parser::ParseScopeFlags::ParseScopeFlags(
Parser *
Self,
unsigned ScopeFlags,
448 : CurScope(ManageFlags ?
Self->getCurScope() :
nullptr) {
450 OldFlags = CurScope->getFlags();
451 CurScope->setFlags(ScopeFlags);
455Parser::ParseScopeFlags::~ParseScopeFlags() {
457 CurScope->setFlags(OldFlags);
468 Actions.CurScope =
nullptr;
471 for (
unsigned i = 0, e = NumCachedScopes; i != e; ++i)
472 delete ScopeCache[i];
474 resetPragmaHandlers();
476 PP.removeCommentHandler(CommentSemaHandler.get());
478 PP.clearCodeCompletionHandler();
480 DestroyTemplateIds();
485 assert(
getCurScope() ==
nullptr &&
"A scope is already active?");
493 &PP.getIdentifierTable().get(
"in");
495 &PP.getIdentifierTable().get(
"out");
497 &PP.getIdentifierTable().get(
"inout");
499 &PP.getIdentifierTable().get(
"oneway");
501 &PP.getIdentifierTable().get(
"bycopy");
503 &PP.getIdentifierTable().get(
"byref");
505 &PP.getIdentifierTable().get(
"nonnull");
507 &PP.getIdentifierTable().get(
"nullable");
509 &PP.getIdentifierTable().get(
"null_unspecified");
512 Ident_instancetype =
nullptr;
513 Ident_final =
nullptr;
514 Ident_sealed =
nullptr;
515 Ident_abstract =
nullptr;
516 Ident_override =
nullptr;
517 Ident_GNU_final =
nullptr;
518 Ident_import =
nullptr;
519 Ident_module =
nullptr;
521 Ident_super = &PP.getIdentifierTable().get(
"super");
523 Ident_vector =
nullptr;
524 Ident_bool =
nullptr;
525 Ident_Bool =
nullptr;
526 Ident_pixel =
nullptr;
528 Ident_vector = &PP.getIdentifierTable().get(
"vector");
529 Ident_bool = &PP.getIdentifierTable().get(
"bool");
530 Ident_Bool = &PP.getIdentifierTable().get(
"_Bool");
533 Ident_pixel = &PP.getIdentifierTable().get(
"pixel");
535 Ident_introduced =
nullptr;
536 Ident_deprecated =
nullptr;
537 Ident_obsoleted =
nullptr;
538 Ident_unavailable =
nullptr;
539 Ident_strict =
nullptr;
540 Ident_replacement =
nullptr;
542 Ident_language = Ident_defined_in = Ident_generated_declaration = Ident_USR =
545 Ident__except =
nullptr;
547 Ident__exception_code = Ident__exception_info =
nullptr;
548 Ident__abnormal_termination = Ident___exception_code =
nullptr;
549 Ident___exception_info = Ident___abnormal_termination =
nullptr;
550 Ident_GetExceptionCode = Ident_GetExceptionInfo =
nullptr;
551 Ident_AbnormalTermination =
nullptr;
554 Ident__exception_info = PP.getIdentifierInfo(
"_exception_info");
555 Ident___exception_info = PP.getIdentifierInfo(
"__exception_info");
556 Ident_GetExceptionInfo = PP.getIdentifierInfo(
"GetExceptionInformation");
557 Ident__exception_code = PP.getIdentifierInfo(
"_exception_code");
558 Ident___exception_code = PP.getIdentifierInfo(
"__exception_code");
559 Ident_GetExceptionCode = PP.getIdentifierInfo(
"GetExceptionCode");
560 Ident__abnormal_termination = PP.getIdentifierInfo(
"_abnormal_termination");
561 Ident___abnormal_termination = PP.getIdentifierInfo(
"__abnormal_termination");
562 Ident_AbnormalTermination = PP.getIdentifierInfo(
"AbnormalTermination");
564 PP.SetPoisonReason(Ident__exception_code,diag::err_seh___except_block);
565 PP.SetPoisonReason(Ident___exception_code,diag::err_seh___except_block);
566 PP.SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block);
567 PP.SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter);
568 PP.SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter);
569 PP.SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter);
570 PP.SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block);
571 PP.SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block);
572 PP.SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block);
576 Ident_import = PP.getIdentifierInfo(
"import");
577 Ident_module = PP.getIdentifierInfo(
"module");
580 Actions.Initialize();
586void Parser::DestroyTemplateIds() {
594 Actions.ActOnStartOfTranslationUnit();
606 if (NoTopLevelDecls && !Actions.getASTContext().getExternalSource() &&
608 Diag(diag::ext_empty_translation_unit);
610 return NoTopLevelDecls;
615 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*
this);
618 switch (Tok.getKind()) {
619 case tok::annot_pragma_unused:
620 HandlePragmaUnused();
634 case tok::identifier: {
636 if ((II == Ident_module || II == Ident_import) &&
638 if (II == Ident_module)
653 Result = ParseModuleDecl(ImportState);
663 case tok::annot_module_include: {
664 auto Loc = Tok.getLocation();
665 Module *Mod =
reinterpret_cast<Module *
>(Tok.getAnnotationValue());
669 Actions.ActOnAnnotModuleInclude(Loc, Mod);
676 ConsumeAnnotationToken();
680 case tok::annot_module_begin:
681 Actions.ActOnAnnotModuleBegin(
683 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
684 ConsumeAnnotationToken();
688 case tok::annot_module_end:
689 Actions.ActOnAnnotModuleEnd(
691 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
692 ConsumeAnnotationToken();
697 case tok::annot_repl_input_end:
699 if (PP.getMaxTokens() != 0 && PP.getTokenCount() > PP.getMaxTokens()) {
700 PP.Diag(Tok.getLocation(), diag::warn_max_tokens_total)
701 << PP.getTokenCount() << PP.getMaxTokens();
704 PP.Diag(OverrideLoc, diag::note_max_tokens_total_override);
709 Actions.SetLateTemplateParser(LateTemplateParserCallback,
this);
710 Actions.ActOnEndOfTranslationUnit();
714 case tok::identifier:
719 if ((Tok.getIdentifierInfo() == Ident_module ||
720 Tok.getIdentifierInfo() == Ident_import) &&
722 if (Tok.getIdentifierInfo() == Ident_module)
739 while (MaybeParseCXX11Attributes(DeclAttrs) ||
740 MaybeParseGNUAttributes(DeclSpecAttrs))
743 Result = ParseExternalDeclaration(DeclAttrs, DeclSpecAttrs);
753 else if (ImportState ==
765 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*
this);
773 Decl *SingleDecl =
nullptr;
774 switch (
Tok.getKind()) {
775 case tok::annot_pragma_vis:
776 HandlePragmaVisibility();
778 case tok::annot_pragma_pack:
781 case tok::annot_pragma_msstruct:
782 HandlePragmaMSStruct();
784 case tok::annot_pragma_align:
787 case tok::annot_pragma_weak:
790 case tok::annot_pragma_weakalias:
791 HandlePragmaWeakAlias();
793 case tok::annot_pragma_redefine_extname:
794 HandlePragmaRedefineExtname();
796 case tok::annot_pragma_fp_contract:
797 HandlePragmaFPContract();
799 case tok::annot_pragma_fenv_access:
800 case tok::annot_pragma_fenv_access_ms:
801 HandlePragmaFEnvAccess();
803 case tok::annot_pragma_fenv_round:
804 HandlePragmaFEnvRound();
806 case tok::annot_pragma_cx_limited_range:
807 HandlePragmaCXLimitedRange();
809 case tok::annot_pragma_float_control:
810 HandlePragmaFloatControl();
812 case tok::annot_pragma_fp:
815 case tok::annot_pragma_opencl_extension:
816 HandlePragmaOpenCLExtension();
818 case tok::annot_attr_openmp:
819 case tok::annot_pragma_openmp: {
821 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
823 case tok::annot_pragma_openacc: {
828 case tok::annot_pragma_ms_pointers_to_members:
829 HandlePragmaMSPointersToMembers();
831 case tok::annot_pragma_ms_vtordisp:
832 HandlePragmaMSVtorDisp();
834 case tok::annot_pragma_ms_pragma:
835 HandlePragmaMSPragma();
837 case tok::annot_pragma_dump:
840 case tok::annot_pragma_attribute:
841 HandlePragmaAttribute();
846 Actions.ActOnEmptyDeclaration(
getCurScope(), Attrs, Tok.getLocation());
850 Diag(Tok, diag::err_extraneous_closing_brace);
854 Diag(Tok, diag::err_expected_external_declaration);
856 case tok::kw___extension__: {
858 ExtensionRAIIObject O(Diags);
860 return ParseExternalDeclaration(Attrs, DeclSpecAttrs);
863 ProhibitAttributes(Attrs);
865 SourceLocation StartLoc = Tok.getLocation();
866 SourceLocation EndLoc;
875 if (!SL->getString().trim().empty())
876 Diag(StartLoc, diag::err_gnu_inline_asm_disabled);
879 ExpectAndConsume(tok::semi, diag::err_expected_after,
880 "top-level asm block");
884 SingleDecl = Actions.ActOnFileScopeAsmDecl(
Result.get(), StartLoc, EndLoc);
888 return ParseObjCAtDirectives(Attrs, DeclSpecAttrs);
892 Diag(Tok, diag::err_expected_external_declaration);
896 SingleDecl = ParseObjCMethodDefinition();
898 case tok::code_completion:
900 if (CurParsedObjCImpl) {
902 Actions.CodeCompletion().CodeCompleteObjCMethodDecl(
909 if (CurParsedObjCImpl) {
911 }
else if (PP.isIncrementalProcessingEnabled()) {
916 Actions.CodeCompletion().CodeCompleteOrdinaryName(
getCurScope(), PCC);
918 case tok::kw_import: {
921 llvm_unreachable(
"not expecting a c++20 import here");
922 ProhibitAttributes(Attrs);
924 SingleDecl = ParseModuleImport(SourceLocation(), IS);
928 ProhibitAttributes(Attrs);
929 SingleDecl = ParseExportDeclaration();
936 case tok::kw_namespace:
937 case tok::kw_typedef:
938 case tok::kw_template:
939 case tok::kw_static_assert:
940 case tok::kw__Static_assert:
943 SourceLocation DeclEnd;
948 case tok::kw_cbuffer:
949 case tok::kw_tbuffer:
951 SourceLocation DeclEnd;
963 SourceLocation DeclEnd;
974 if (NextKind == tok::kw_namespace) {
975 SourceLocation DeclEnd;
982 if (NextKind == tok::kw_template) {
985 SourceLocation DeclEnd;
994 ProhibitAttributes(Attrs);
995 ProhibitAttributes(DeclSpecAttrs);
1000 diag::warn_cxx98_compat_extern_template :
1001 diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc);
1002 SourceLocation DeclEnd;
1004 TemplateLoc, DeclEnd, Attrs);
1008 case tok::kw___if_exists:
1009 case tok::kw___if_not_exists:
1010 ParseMicrosoftIfExistsExternalDeclaration();
1013 case tok::kw_module:
1014 Diag(Tok, diag::err_unexpected_module_decl);
1020 if (Tok.isEditorPlaceholder()) {
1025 !isDeclarationStatement(
true))
1026 return ParseTopLevelStmtDecl();
1030 return ParseDeclarationOrFunctionDefinition(Attrs, DeclSpecAttrs, DS);
1035 return Actions.ConvertDeclToDeclGroup(SingleDecl);
1038bool Parser::isDeclarationAfterDeclarator() {
1042 if (KW.
is(tok::kw_default) || KW.
is(tok::kw_delete))
1046 return Tok.is(tok::equal) ||
1047 Tok.is(tok::comma) ||
1048 Tok.is(tok::semi) ||
1049 Tok.is(tok::kw_asm) ||
1050 Tok.is(tok::kw___attribute) ||
1052 Tok.is(tok::l_paren));
1055bool Parser::isStartOfFunctionDefinition(
const ParsingDeclarator &Declarator) {
1056 assert(
Declarator.isFunctionDeclarator() &&
"Isn't a function declarator");
1057 if (Tok.is(tok::l_brace))
1062 Declarator.getFunctionTypeInfo().isKNRPrototype())
1067 return KW.
is(tok::kw_default) || KW.
is(tok::kw_delete);
1070 return Tok.is(tok::colon) ||
1071 Tok.is(tok::kw_try);
1075 ParsedAttributes &Attrs, ParsedAttributes &DeclSpecAttrs,
1081 "expected uninitialised source range");
1086 ParsedTemplateInfo TemplateInfo;
1089 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
1090 DeclSpecContext::DSC_top_level);
1095 DS, AS, DeclSpecContext::DSC_top_level))
1100 if (Tok.is(tok::semi)) {
1103 SourceLocation CorrectLocationForAttributes{};
1107 if (
const auto *ED = dyn_cast_or_null<EnumDecl>(DS.
getRepAsDecl())) {
1108 CorrectLocationForAttributes =
1109 PP.getLocForEndOfToken(ED->getEnumKeyRange().getEnd());
1112 if (CorrectLocationForAttributes.
isInvalid()) {
1113 const auto &Policy = Actions.getASTContext().getPrintingPolicy();
1116 CorrectLocationForAttributes =
1120 ProhibitAttributes(Attrs, CorrectLocationForAttributes);
1122 RecordDecl *AnonRecord =
nullptr;
1123 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
1126 Actions.ActOnDefinedDeclarationSpecifier(TheDecl);
1128 Decl* decls[] = {AnonRecord, TheDecl};
1129 return Actions.BuildDeclaratorGroup(decls);
1131 return Actions.ConvertDeclToDeclGroup(TheDecl);
1135 Actions.ActOnDefinedDeclarationSpecifier(DS.
getRepAsDecl());
1142 if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
1143 !Tok.isObjCAtKeyword(tok::objc_protocol) &&
1144 !Tok.isObjCAtKeyword(tok::objc_implementation)) {
1145 Diag(Tok, diag::err_objc_unexpected_attr);
1153 const char *PrevSpec =
nullptr;
1156 Actions.getASTContext().getPrintingPolicy()))
1157 Diag(AtLoc, DiagID) << PrevSpec;
1159 if (Tok.isObjCAtKeyword(tok::objc_protocol))
1160 return ParseObjCAtProtocolDeclaration(AtLoc, DS.
getAttributes());
1162 if (Tok.isObjCAtKeyword(tok::objc_implementation))
1163 return ParseObjCAtImplementationDeclaration(AtLoc, DS.
getAttributes());
1165 return Actions.ConvertDeclToDeclGroup(
1166 ParseObjCAtInterfaceDeclaration(AtLoc, DS.
getAttributes()));
1175 ProhibitAttributes(Attrs);
1177 return Actions.ConvertDeclToDeclGroup(TheDecl);
1184 ParsedAttributes &Attrs, ParsedAttributes &DeclSpecAttrs,
1188 llvm::TimeTraceScope TimeScope(
"ParseDeclarationOrFunctionDefinition", [&]() {
1189 return Tok.getLocation().printToString(
1190 Actions.getASTContext().getSourceManager());
1194 return ParseDeclOrFunctionDefInternal(Attrs, DeclSpecAttrs, *DS, AS);
1196 ParsingDeclSpec PDS(*
this);
1200 ObjCDeclContextSwitch ObjCDC(*
this);
1202 return ParseDeclOrFunctionDefInternal(Attrs, DeclSpecAttrs, PDS, AS);
1206Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
1207 const ParsedTemplateInfo &TemplateInfo,
1208 LateParsedAttrList *LateParsedAttrs) {
1209 llvm::TimeTraceScope TimeScope(
"ParseFunctionDefinition", [&]() {
1210 return Actions.GetNameForDeclarator(D).getName().getAsString();
1216 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1224 const char *PrevSpec;
1226 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1238 ParseKNRParamDeclarations(D);
1242 if (Tok.isNot(tok::l_brace) &&
1244 (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
1245 Tok.isNot(tok::equal)))) {
1246 Diag(Tok, diag::err_expected_fn_body);
1252 if (Tok.isNot(tok::l_brace))
1258 if (Tok.isNot(tok::equal)) {
1260 if (AL.isKnownToGCC() && !AL.isStandardAttributeSyntax())
1261 Diag(AL.getLoc(), diag::warn_attribute_on_function_definition) << AL;
1266 if (
getLangOpts().DelayedTemplateParsing && Tok.isNot(tok::equal) &&
1268 LateParsedAttrs->empty() && Actions.canDelayFunctionBody(D)) {
1276 Decl *DP = Actions.HandleDeclarator(ParentScope, D,
1281 if (SkipFunctionBodies && (!DP || Actions.canSkipFunctionBody(DP)) &&
1282 trySkippingFunctionBody()) {
1284 return Actions.ActOnSkippedFunctionBody(DP);
1288 LexTemplateFunctionForLateParsing(Toks);
1292 Actions.CheckForFunctionRedefinition(FnD);
1293 Actions.MarkAsLateParsedTemplate(FnD, DP, Toks);
1297 if (CurParsedObjCImpl && !TemplateInfo.TemplateParams &&
1298 (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) || Tok.is(tok::colon)) &&
1299 Actions.CurContext->isTranslationUnit()) {
1305 Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
1311 StashAwayMethodOrFunctionBodyTokens(FuncDecl);
1312 CurParsedObjCImpl->HasCFunction =
true;
1324 StringLiteral *DeletedMessage =
nullptr;
1326 SourceLocation KWLoc;
1332 ? diag::warn_cxx98_compat_defaulted_deleted_function
1333 : diag::ext_defaulted_deleted_function)
1336 DeletedMessage = ParseCXXDeletedFunctionMessage();
1339 ? diag::warn_cxx98_compat_defaulted_deleted_function
1340 : diag::ext_defaulted_deleted_function)
1344 llvm_unreachable(
"function definition after = not 'delete' or 'default'");
1347 if (Tok.is(tok::comma)) {
1348 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
1351 }
else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
1359 Sema::FPFeaturesStateRAII SaveFPFeatures(Actions);
1363 SkipBodyInfo SkipBody;
1365 TemplateInfo.TemplateParams
1366 ? *TemplateInfo.TemplateParams
1368 &SkipBody, BodyKind);
1385 Actions.PopExpressionEvaluationContext();
1397 Actions.SetFunctionBodyKind(Res, KWLoc, BodyKind, DeletedMessage);
1398 Stmt *GeneratedBody = Res ? Res->
getBody() :
nullptr;
1399 Actions.ActOnFinishFunctionBody(Res, GeneratedBody,
false);
1405 if (
const auto *
Template = dyn_cast_if_present<FunctionTemplateDecl>(Res);
1407 Template->getTemplateParameters()->getParam(0)->isImplicit())
1410 CurTemplateDepthTracker.addDepth(1);
1413 if (LateParsedAttrs)
1414 ParseLexedAttributeList(*LateParsedAttrs, Res,
false,
1417 if (SkipFunctionBodies && (!Res || Actions.canSkipFunctionBody(Res)) &&
1418 trySkippingFunctionBody()) {
1420 Actions.ActOnSkippedFunctionBody(Res);
1421 return Actions.ActOnFinishFunctionBody(Res,
nullptr,
false);
1424 if (Tok.is(tok::kw_try))
1425 return ParseFunctionTryBlock(Res, BodyScope);
1429 if (Tok.is(tok::colon)) {
1430 ParseConstructorInitializer(Res);
1433 if (!Tok.is(tok::l_brace)) {
1435 Actions.ActOnFinishFunctionBody(Res,
nullptr);
1439 Actions.ActOnDefaultCtorInitializers(Res);
1441 return ParseFunctionStatementBody(Res, BodyScope);
1444void Parser::SkipFunctionBody() {
1445 if (Tok.is(tok::equal)) {
1450 bool IsFunctionTryBlock = Tok.is(tok::kw_try);
1451 if (IsFunctionTryBlock)
1455 if (ConsumeAndStoreFunctionPrologue(Skipped))
1459 while (IsFunctionTryBlock && Tok.is(tok::kw_catch)) {
1466void Parser::ParseKNRParamDeclarations(Declarator &D) {
1477 SourceLocation DSStart = Tok.getLocation();
1480 DeclSpec DS(AttrFactory);
1481 ParsedTemplateInfo TemplateInfo;
1482 ParseDeclarationSpecifiers(DS, TemplateInfo);
1490 Diag(DSStart, diag::err_declaration_does_not_declare_param);
1499 diag::err_invalid_storage_class_in_func_decl);
1504 diag::err_invalid_storage_class_in_func_decl);
1511 ParseDeclarator(ParmDeclarator);
1516 MaybeParseGNUAttributes(ParmDeclarator);
1520 Actions.ActOnParamDeclarator(
getCurScope(), ParmDeclarator);
1524 ParmDeclarator.getIdentifier()) {
1528 for (
unsigned i = 0; ; ++i) {
1532 Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
1533 << ParmDeclarator.getIdentifier();
1537 if (FTI.
Params[i].
Ident == ParmDeclarator.getIdentifier()) {
1540 Diag(ParmDeclarator.getIdentifierLoc(),
1541 diag::err_param_redefinition)
1542 << ParmDeclarator.getIdentifier();
1553 if (Tok.isNot(tok::comma))
1556 ParmDeclarator.clear();
1562 ParseDeclarator(ParmDeclarator);
1566 if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration))
1576 Actions.ActOnFinishKNRParamDeclarations(
getCurScope(), D, Tok.getLocation());
1579ExprResult Parser::ParseAsmStringLiteral(
bool ForAsmLabel) {
1582 if (isTokenStringLiteral()) {
1588 if (!SL->isOrdinary()) {
1589 Diag(Tok, diag::err_asm_operand_wide_string_literal)
1590 << SL->isWide() << SL->getSourceRange();
1594 Tok.is(tok::l_paren)) {
1596 SourceLocation RParenLoc;
1599 EnterExpressionEvaluationContext ConstantEvaluated(
1601 AsmString = ParseParenExpression(
1605 AsmString = Actions.ActOnConstantExpression(AsmString);
1610 Diag(Tok, diag::err_asm_expected_string) << (
1611 (
getLangOpts().CPlusPlus11 && !ForAsmLabel) ? 0 : 1);
1614 return Actions.ActOnGCCAsmStmtString(AsmString.
get(), ForAsmLabel);
1617ExprResult Parser::ParseSimpleAsm(
bool ForAsmLabel, SourceLocation *EndLoc) {
1618 assert(Tok.is(tok::kw_asm) &&
"Not an asm!");
1621 if (isGNUAsmQualifier(Tok)) {
1623 SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
1624 PP.getLocForEndOfToken(Tok.getLocation()));
1625 Diag(Tok, diag::err_global_asm_qualifier_ignored)
1626 << GNUAsmQualifiers::getQualifierName(getGNUAsmQualifier(Tok))
1632 if (
T.consumeOpen()) {
1633 Diag(Tok, diag::err_expected_lparen_after) <<
"asm";
1639 if (!
Result.isInvalid()) {
1643 *EndLoc =
T.getCloseLocation();
1646 *EndLoc = Tok.getLocation();
1653TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(
const Token &tok) {
1654 assert(tok.
is(tok::annot_template_id) &&
"Expected template-id token");
1655 TemplateIdAnnotation *
1660void Parser::AnnotateScopeToken(CXXScopeSpec &SS,
bool IsNewAnnotation) {
1663 if (PP.isBacktrackEnabled())
1664 PP.RevertCachedTokens(1);
1666 PP.EnterToken(Tok,
true);
1667 Tok.setKind(tok::annot_cxxscope);
1668 Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
1669 Tok.setAnnotationRange(SS.
getRange());
1674 if (IsNewAnnotation)
1675 PP.AnnotateCachedTokens(Tok);
1679Parser::TryAnnotateName(CorrectionCandidateCallback *CCC,
1681 assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
1683 const bool EnteringContext =
false;
1684 const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1688 ParseOptionalCXXScopeSpecifier(SS,
nullptr,
1693 if (Tok.isNot(tok::identifier) || SS.
isInvalid()) {
1695 AllowImplicitTypename))
1700 IdentifierInfo *Name = Tok.getIdentifierInfo();
1701 SourceLocation NameLoc = Tok.getLocation();
1705 if (isTentativelyDeclared(Name) && SS.
isEmpty()) {
1709 AllowImplicitTypename))
1721 Sema::NameClassification Classification = Actions.ClassifyName(
1729 isTemplateArgumentList(1) == TPResult::False) {
1731 Token FakeNext =
Next;
1732 FakeNext.
setKind(tok::unknown);
1734 Actions.ClassifyName(
getCurScope(), SS, Name, NameLoc, FakeNext,
1735 SS.
isEmpty() ? CCC :
nullptr);
1738 switch (Classification.
getKind()) {
1744 Tok.setIdentifierInfo(Name);
1746 PP.TypoCorrectToken(Tok);
1748 AnnotateScopeToken(SS, !WasScopeAnnotation);
1757 if (TryAltiVecVectorToken())
1762 SourceLocation BeginLoc = NameLoc;
1769 QualType
T = Actions.GetTypeFromParser(Ty);
1774 SourceLocation NewEndLoc;
1776 = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
1781 else if (Tok.is(tok::eof))
1785 Tok.setKind(tok::annot_typename);
1786 setTypeAnnotation(Tok, Ty);
1787 Tok.setAnnotationEndLoc(Tok.getLocation());
1788 Tok.setLocation(BeginLoc);
1789 PP.AnnotateCachedTokens(Tok);
1794 Tok.setKind(tok::annot_overload_set);
1796 Tok.setAnnotationEndLoc(NameLoc);
1799 PP.AnnotateCachedTokens(Tok);
1803 if (TryAltiVecVectorToken())
1808 Tok.setKind(tok::annot_non_type);
1810 Tok.setLocation(NameLoc);
1811 Tok.setAnnotationEndLoc(NameLoc);
1812 PP.AnnotateCachedTokens(Tok);
1814 AnnotateScopeToken(SS, !WasScopeAnnotation);
1819 Tok.setKind(Classification.
getKind() ==
1821 ? tok::annot_non_type_undeclared
1822 : tok::annot_non_type_dependent);
1823 setIdentifierAnnotation(Tok, Name);
1824 Tok.setLocation(NameLoc);
1825 Tok.setAnnotationEndLoc(NameLoc);
1826 PP.AnnotateCachedTokens(Tok);
1828 AnnotateScopeToken(SS, !WasScopeAnnotation);
1832 if (
Next.isNot(tok::less)) {
1836 AnnotateScopeToken(SS, !WasScopeAnnotation);
1844 bool IsConceptName =
1850 if (
Next.is(tok::less))
1852 if (AnnotateTemplateIdToken(
1859 AnnotateScopeToken(SS, !WasScopeAnnotation);
1866 AnnotateScopeToken(SS, !WasScopeAnnotation);
1871 SourceLocation TokenEndLoc = PP.getLocForEndOfToken(PrevTokLocation);
1872 return TokenEndLoc.
isValid() ? TokenEndLoc : Tok.getLocation();
1875bool Parser::TryKeywordIdentFallback(
bool DisableKeyword) {
1876 assert(
Tok.isNot(tok::identifier));
1877 Diag(
Tok, diag::ext_keyword_as_ident)
1881 Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
1882 Tok.setKind(tok::identifier);
1888 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1889 Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope) ||
1890 Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id) ||
1891 Tok.is(tok::kw___super) || Tok.is(tok::kw_auto) ||
1892 Tok.is(tok::annot_pack_indexing_type)) &&
1893 "Cannot be a type or scope token!");
1895 if (Tok.is(tok::kw_typename)) {
1904 PP.Lex(TypedefToken);
1906 PP.EnterToken(Tok,
true);
1909 Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename);
1921 if (ParseOptionalCXXScopeSpecifier(SS,
nullptr,
1927 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) ||
1928 Tok.is(tok::annot_decltype)) {
1930 if (Tok.is(tok::annot_decltype) ||
1932 Tok.isAnnotation())) {
1933 unsigned DiagID = diag::err_expected_qualified_after_typename;
1937 DiagID = diag::warn_expected_qualified_after_typename;
1938 Diag(Tok.getLocation(), DiagID);
1942 if (Tok.isEditorPlaceholder())
1945 Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
1949 bool TemplateKWPresent =
false;
1950 if (Tok.is(tok::kw_template)) {
1952 TemplateKWPresent =
true;
1956 if (Tok.is(tok::identifier)) {
1958 Diag(Tok.getLocation(),
1959 diag::missing_template_arg_list_after_template_kw);
1962 Ty = Actions.ActOnTypenameType(
getCurScope(), TypenameLoc, SS,
1963 *Tok.getIdentifierInfo(),
1965 }
else if (Tok.is(tok::annot_template_id)) {
1968 Diag(Tok, diag::err_typename_refers_to_non_type_template)
1969 << Tok.getAnnotationRange();
1978 : Actions.ActOnTypenameType(
1982 TemplateArgsPtr, TemplateId->
RAngleLoc);
1984 Diag(Tok, diag::err_expected_type_name_after_typename)
1990 Tok.setKind(tok::annot_typename);
1991 setTypeAnnotation(Tok, Ty);
1992 Tok.setAnnotationEndLoc(EndLoc);
1993 Tok.setLocation(TypenameLoc);
1994 PP.AnnotateCachedTokens(Tok);
1999 bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
2003 if (ParseOptionalCXXScopeSpecifier(SS,
nullptr,
2009 AllowImplicitTypename);
2015 if (Tok.is(tok::identifier)) {
2018 *Tok.getIdentifierInfo(), Tok.getLocation(),
getCurScope(), &SS,
2022 true, AllowImplicitTypename)) {
2027 QualType T = Actions.GetTypeFromParser(Ty);
2032 (
T->isObjCObjectType() ||
T->isObjCObjectPointerType())) {
2042 else if (Tok.is(tok::eof))
2048 Tok.setKind(tok::annot_typename);
2049 setTypeAnnotation(Tok, Ty);
2050 Tok.setAnnotationEndLoc(Tok.getLocation());
2051 Tok.setLocation(BeginLoc);
2055 PP.AnnotateCachedTokens(Tok);
2072 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
2073 bool MemberOfUnknownSpecialization;
2078 MemberOfUnknownSpecialization)) {
2082 isTemplateArgumentList(1) != TPResult::False) {
2102 if (Tok.is(tok::annot_template_id)) {
2109 AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
2116 Tok.is(tok::coloncolon)) {
2125 AnnotateScopeToken(SS, IsNewScope);
2131 "Call sites of this function should be guarded by checking for C++");
2135 if (ParseOptionalCXXScopeSpecifier(SS,
nullptr,
2142 AnnotateScopeToken(SS,
true);
2146bool Parser::isTokenEqualOrEqualTypo() {
2152 case tok::starequal:
2153 case tok::plusequal:
2154 case tok::minusequal:
2155 case tok::exclaimequal:
2156 case tok::slashequal:
2157 case tok::percentequal:
2158 case tok::lessequal:
2159 case tok::lesslessequal:
2160 case tok::greaterequal:
2161 case tok::greatergreaterequal:
2162 case tok::caretequal:
2163 case tok::pipeequal:
2164 case tok::equalequal:
2165 Diag(
Tok, diag::err_invalid_token_after_declarator_suggest_equal)
2174SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
2175 assert(Tok.is(tok::code_completion));
2176 PrevTokLocation = Tok.getLocation();
2179 if (S->isFunctionScope()) {
2181 Actions.CodeCompletion().CodeCompleteOrdinaryName(
2183 return PrevTokLocation;
2186 if (S->isClassScope()) {
2188 Actions.CodeCompletion().CodeCompleteOrdinaryName(
2190 return PrevTokLocation;
2195 Actions.CodeCompletion().CodeCompleteOrdinaryName(
2197 return PrevTokLocation;
2202void Parser::CodeCompleteDirective(
bool InConditional) {
2203 Actions.CodeCompletion().CodeCompletePreprocessorDirective(InConditional);
2207 Actions.CodeCompletion().CodeCompleteInPreprocessorConditionalExclusion(
2211void Parser::CodeCompleteMacroName(
bool IsDefinition) {
2212 Actions.CodeCompletion().CodeCompletePreprocessorMacroName(IsDefinition);
2216 Actions.CodeCompletion().CodeCompletePreprocessorExpression();
2219void Parser::CodeCompleteMacroArgument(IdentifierInfo *
Macro,
2220 MacroInfo *MacroInfo,
2221 unsigned ArgumentIndex) {
2222 Actions.CodeCompletion().CodeCompletePreprocessorMacroArgument(
2226void Parser::CodeCompleteIncludedFile(llvm::StringRef Dir,
bool IsAngled) {
2227 Actions.CodeCompletion().CodeCompleteIncludedFile(Dir, IsAngled);
2231 Actions.CodeCompletion().CodeCompleteNaturalLanguage();
2234bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition&
Result) {
2235 assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
2236 "Expected '__if_exists' or '__if_not_exists'");
2237 Result.IsIfExists = Tok.is(tok::kw___if_exists);
2241 if (
T.consumeOpen()) {
2242 Diag(Tok, diag::err_expected_lparen_after)
2243 << (
Result.IsIfExists?
"__if_exists" :
"__if_not_exists");
2249 ParseOptionalCXXScopeSpecifier(
Result.SS,
nullptr,
2254 if (
Result.SS.isInvalid()) {
2260 SourceLocation TemplateKWLoc;
2265 false, &TemplateKWLoc,
2271 if (
T.consumeClose())
2299void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
2300 IfExistsCondition
Result;
2301 if (ParseMicrosoftIfExistsCondition(
Result))
2305 if (
Braces.consumeOpen()) {
2306 Diag(Tok, diag::err_expected) << tok::l_brace;
2310 switch (
Result.Behavior) {
2316 llvm_unreachable(
"Cannot have a dependent external declaration");
2325 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
2326 ParsedAttributes Attrs(AttrFactory);
2327 MaybeParseCXX11Attributes(Attrs);
2328 ParsedAttributes EmptyDeclSpecAttrs(AttrFactory);
2331 Actions.getASTConsumer().HandleTopLevelDecl(
Result.get());
2338 Token Introducer = Tok;
2339 SourceLocation StartLoc = Introducer.
getLocation();
2346 (Tok.is(tok::kw_module) ||
2347 (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_module)) &&
2348 "not a module declaration");
2353 DiagnoseAndSkipCXX11Attributes();
2356 if (
getLangOpts().CPlusPlusModules && Tok.is(tok::semi)) {
2360 Diag(StartLoc, diag::err_global_module_introducer_not_at_start)
2361 << SourceRange(StartLoc, SemiLoc);
2365 Diag(StartLoc, diag::err_module_fragment_exported)
2369 return Actions.ActOnGlobalModuleFragmentDecl(ModuleLoc);
2373 if (
getLangOpts().CPlusPlusModules && Tok.is(tok::colon) &&
2376 Diag(StartLoc, diag::err_module_fragment_exported)
2381 DiagnoseAndSkipCXX11Attributes();
2382 ExpectAndConsumeSemi(diag::err_private_module_fragment_expected_semi);
2386 return Actions.ActOnPrivateModuleFragmentDecl(ModuleLoc, PrivateLoc);
2389 SmallVector<IdentifierLoc, 2> Path;
2390 if (ParseModuleName(ModuleLoc, Path,
false))
2394 SmallVector<IdentifierLoc, 2> Partition;
2395 if (Tok.is(tok::colon)) {
2398 Diag(ColonLoc, diag::err_unsupported_module_partition)
2399 << SourceRange(ColonLoc, Partition.back().getLoc());
2401 else if (ParseModuleName(ModuleLoc, Partition,
false))
2406 ParsedAttributes Attrs(AttrFactory);
2407 MaybeParseCXX11Attributes(Attrs);
2408 ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_module_attr,
2409 diag::err_keyword_not_module_attr,
2413 ExpectAndConsumeSemi(diag::err_module_expected_semi);
2415 return Actions.ActOnModuleDecl(StartLoc, ModuleLoc, MDK, Path, Partition,
2420Decl *Parser::ParseModuleImport(SourceLocation AtLoc,
2422 SourceLocation StartLoc = AtLoc.
isInvalid() ? Tok.getLocation() : AtLoc;
2424 SourceLocation ExportLoc;
2427 assert((AtLoc.
isInvalid() ? Tok.isOneOf(tok::kw_import, tok::identifier)
2428 : Tok.isObjCAtKeyword(tok::objc_import)) &&
2429 "Improper start to module import");
2430 bool IsObjCAtImport = Tok.isObjCAtKeyword(tok::objc_import);
2434 SmallVector<IdentifierLoc, 2> Path;
2435 bool IsPartition =
false;
2436 Module *HeaderUnit =
nullptr;
2437 if (Tok.is(tok::header_name)) {
2442 }
else if (Tok.is(tok::annot_header_unit)) {
2444 HeaderUnit =
reinterpret_cast<Module *
>(Tok.getAnnotationValue());
2445 ConsumeAnnotationToken();
2446 }
else if (Tok.is(tok::colon)) {
2449 Diag(ColonLoc, diag::err_unsupported_module_partition)
2450 << SourceRange(ColonLoc, Path.back().getLoc());
2452 else if (ParseModuleName(ColonLoc, Path,
true))
2457 if (ParseModuleName(ImportLoc, Path,
true))
2461 ParsedAttributes Attrs(AttrFactory);
2462 MaybeParseCXX11Attributes(Attrs);
2464 ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_import_attr,
2465 diag::err_keyword_not_import_attr,
2469 if (PP.hadModuleLoaderFatalFailure()) {
2476 bool SeenError =
true;
2477 switch (ImportState) {
2489 Diag(ImportLoc, diag::err_partition_import_outside_module);
2501 if (IsPartition || (HeaderUnit && HeaderUnit->
Kind !=
2503 Diag(ImportLoc, diag::err_import_in_wrong_fragment)
2512 Diag(ImportLoc, diag::err_import_not_allowed_here);
2517 ExpectAndConsumeSemi(diag::err_module_expected_semi);
2526 Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, HeaderUnit);
2527 else if (!Path.empty())
2528 Import = Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Path,
2535 if (IsObjCAtImport && AtLoc.
isValid()) {
2536 auto &SrcMgr = PP.getSourceManager();
2537 auto FE = SrcMgr.getFileEntryRefForID(SrcMgr.getFileID(AtLoc));
2538 if (FE && llvm::sys::path::parent_path(FE->getDir().getName())
2539 .ends_with(
".framework"))
2540 Diags.Report(AtLoc, diag::warn_atimport_in_framework_header);
2546bool Parser::ParseModuleName(SourceLocation UseLoc,
2547 SmallVectorImpl<IdentifierLoc> &Path,
2551 if (!Tok.is(tok::identifier)) {
2552 if (Tok.is(tok::code_completion)) {
2554 Actions.CodeCompletion().CodeCompleteModuleImport(UseLoc, Path);
2558 Diag(Tok, diag::err_module_expected_ident) << IsImport;
2564 Path.emplace_back(Tok.getLocation(), Tok.getIdentifierInfo());
2567 if (Tok.isNot(tok::period))
2574bool Parser::parseMisplacedModuleImport() {
2576 switch (Tok.getKind()) {
2577 case tok::annot_module_end:
2581 if (MisplacedModuleBeginCount) {
2582 --MisplacedModuleBeginCount;
2583 Actions.ActOnAnnotModuleEnd(
2585 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
2586 ConsumeAnnotationToken();
2593 case tok::annot_module_begin:
2595 Actions.ActOnAnnotModuleBegin(
2597 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
2598 ConsumeAnnotationToken();
2599 ++MisplacedModuleBeginCount;
2601 case tok::annot_module_include:
2604 Actions.ActOnAnnotModuleInclude(
2606 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
2607 ConsumeAnnotationToken();
2617void Parser::diagnoseUseOfC11Keyword(
const Token &Tok) {
2622 : diag::ext_c11_feature)
2626bool BalancedDelimiterTracker::diagnoseOverflow() {
2627 P.Diag(P.Tok, diag::err_bracket_depth_exceeded)
2628 << P.getLangOpts().BracketDepth;
2629 P.Diag(P.Tok, diag::note_bracket_depth);
2637 LOpen = P.Tok.getLocation();
2638 if (P.ExpectAndConsume(Kind, DiagID, Msg)) {
2639 if (SkipToTok != tok::unknown)
2644 if (getDepth() < P.getLangOpts().BracketDepth)
2647 return diagnoseOverflow();
2650bool BalancedDelimiterTracker::diagnoseMissingClose() {
2651 assert(!P.Tok.is(Close) &&
"Should have consumed closing delimiter");
2653 if (P.Tok.is(tok::annot_module_end))
2654 P.Diag(P.Tok, diag::err_missing_before_module_end) << Close;
2656 P.Diag(P.Tok, diag::err_expected) << Close;
2657 P.Diag(LOpen, diag::note_matching) << Kind;
2661 if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) &&
2662 P.Tok.isNot(tok::r_square) &&
2663 P.SkipUntil(Close, FinalToken,
2666 LClose = P.ConsumeAnyToken();
Defines the clang::ASTContext interface.
This file provides some common utility functions for processing Lambda related AST Constructs.
static Decl::Kind getKind(const Decl *D)
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
static bool IsCommonTypo(tok::TokenKind ExpectedTok, const Token &Tok)
static bool HasFlagsSet(Parser::SkipUntilFlags L, Parser::SkipUntilFlags R)
This file declares facilities that support code completion.
Defines a utilitiy for warning once when close to out of stack space.
bool expectAndConsume(unsigned DiagID=diag::err_expected, const char *Msg="", tok::TokenKind SkipToTok=tok::unknown)
Represents a C++ nested-name-specifier or a global scope specifier.
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
SourceRange getRange() const
SourceLocation getBeginLoc() const
bool isInvalid() const
An error occurred during parsing of the scope specifier.
bool isEmpty() const
No scope specifier.
virtual void CodeCompletePreprocessorExpression()
Callback invoked when performing code completion in a preprocessor expression, such as the condition ...
virtual void CodeCompleteNaturalLanguage()
Callback invoked when performing code completion in a part of the file where we expect natural langua...
virtual void CodeCompleteInConditionalExclusion()
Callback invoked when performing code completion within a block of code that was excluded due to prep...
void ClearStorageClassSpecs()
TST getTypeSpecType() const
SourceLocation getStorageClassSpecLoc() const
SCS getStorageClassSpec() const
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
SourceRange getSourceRange() const LLVM_READONLY
void SetRangeEnd(SourceLocation Loc)
void SetRangeStart(SourceLocation Loc)
TSCS getThreadStorageClassSpec() const
ParsedAttributes & getAttributes()
static const TST TST_enum
static bool isDeclRep(TST T)
void takeAttributesAppendingingFrom(ParsedAttributes &attrs)
bool hasTagDefinition() const
unsigned getParsedSpecifiers() const
Return a bitmask of which flavors of specifiers this DeclSpec includes.
static const TSCS TSCS_unspecified
static const char * getSpecifierName(DeclSpec::TST T, const PrintingPolicy &Policy)
Turn a type-specifier-type into a string like "_Bool" or "union".
SourceLocation getThreadStorageClassSpecLoc() const
Decl * getRepAsDecl() const
static const TST TST_unspecified
bool isEmpty() const
isEmpty - Return true if this declaration specifier is completely empty: no tokens were parsed in the...
SourceLocation getTypeSpecTypeLoc() const
@ PQ_StorageClassSpecifier
Decl - This represents one declaration (or definition), e.g.
virtual Stmt * getBody() const
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
void SetRangeBegin(SourceLocation Loc)
SetRangeBegin - Set the start of the source range to Loc, unless it's invalid.
const ParsedAttributes & getAttributes() const
SourceLocation getIdentifierLoc() const
void setFunctionDefinitionKind(FunctionDefinitionKind Val)
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
A little helper class used to produce diagnostics.
static unsigned getCXXCompatDiagId(const LangOptions &LangOpts, unsigned CompatDiagId)
Get the appropriate diagnostic Id to use for issuing a compatibility diagnostic.
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
One of these records is kept for each identifier that is lexed.
tok::TokenKind getTokenID() const
If this is a source-language token (e.g.
A simple pair of identifier info and location.
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Describes a module or submodule.
ModuleKind Kind
The kind of this module.
bool isHeaderUnit() const
Is this module a header unit.
@ ModuleHeaderUnit
This is a C++20 header unit.
static OpaquePtr make(TemplateName P)
RAII object that makes sure paren/bracket/brace count is correct after declaration/statement parsing,...
static const ParsedAttributesView & none()
ParsedAttributes - A collection of parsed attributes.
ParseScope - Introduces a new scope for parsing.
Parser - This implements a parser for the C family of languages.
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
SourceLocation getEndOfPreviousToken() const
bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS, bool IsNewScope, ImplicitTypenameContext AllowImplicitTypename)
Try to annotate a type or scope token, having already parsed an optional scope specifier.
DiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId)
ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral=false)
ParseStringLiteralExpression - This handles the various token types that form string literals,...
SourceLocation ConsumeToken()
ConsumeToken - Consume the current 'peek token' and lex the next one.
Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies)
void EnterScope(unsigned ScopeFlags)
EnterScope - Start a new scope.
bool ParseUnqualifiedId(CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors, bool EnteringContext, bool AllowDestructorName, bool AllowConstructorName, bool AllowDeductionGuide, SourceLocation *TemplateKWLoc, UnqualifiedId &Result)
Parse a C++ unqualified-id (or a C identifier), which describes the name of an entity.
DeclGroupPtrTy ParseOpenACCDirectiveDecl(AccessSpecifier &AS, ParsedAttributes &Attrs, DeclSpec::TST TagType, Decl *TagDecl)
Parse OpenACC directive on a declaration.
SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok=false)
ConsumeAnyToken - Dispatch to the right Consume* method based on the current token type.
const Token & GetLookAheadToken(unsigned N)
GetLookAheadToken - This peeks ahead N tokens and returns that token without consuming any tokens.
bool TryConsumeToken(tok::TokenKind Expected)
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Scope * getCurScope() const
OpaquePtr< TemplateName > TemplateTy
bool SkipUntil(tok::TokenKind T, SkipUntilFlags Flags=static_cast< SkipUntilFlags >(0))
SkipUntil - Read tokens until we get to the specified token, then consume it (unless StopBeforeMatch ...
void SkipMalformedDecl()
SkipMalformedDecl - Read tokens until we get to some likely good stopping point for skipping past a s...
friend class PoisonSEHIdentifiersRAIIObject
void ExitScope()
ExitScope - Pop a scope off the scope stack.
const LangOptions & getLangOpts() const
bool ParseFirstTopLevelDecl(DeclGroupPtrTy &Result, Sema::ModuleImportState &ImportState)
Parse the first top-level declaration in a translation unit.
SkipUntilFlags
Control flags for SkipUntil functions.
@ StopBeforeMatch
Stop skipping at specified token, but don't skip the token itself.
@ StopAtCodeCompletion
Stop at code completion.
@ StopAtSemi
Stop skipping at semicolon.
bool TryAnnotateTypeOrScopeToken(ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No)
TryAnnotateTypeOrScopeToken - If the current token position is on a typename (possibly qualified in C...
bool MightBeCXXScopeToken()
const Token & NextToken()
NextToken - This peeks ahead one token and returns it without consuming it.
friend class BalancedDelimiterTracker
SmallVector< TemplateParameterList *, 4 > TemplateParameterLists
void Initialize()
Initialize - Warm up the parser.
bool TryAnnotateCXXScopeToken(bool EnteringContext=false)
TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only annotates C++ scope specifiers and ...
A class for parsing a DeclSpec.
const ParsingDeclSpec & getDeclSpec() const
ParsingDeclSpec & getMutableDeclSpec() const
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
StringRef getSpelling(SourceLocation loc, SmallVectorImpl< char > &buffer, bool *invalid=nullptr) const
Return the 'spelling' of the token at the given location; does not go up to the spelling location or ...
bool isCodeCompletionEnabled() const
Determine if we are performing code completion.
bool isCodeCompletionReached() const
Returns true if code-completion is enabled and we have hit the code-completion point.
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Computes the source location just past the end of the token at this source location.
A (possibly-)qualified type.
Scope - A scope is a transient data structure that is used while parsing the program.
void Init(Scope *parent, unsigned flags)
Init - This is used by the parser to implement scope caching.
const Scope * getParent() const
getParent - Return the scope that this is nested in.
@ FunctionPrototypeScope
This is a scope that corresponds to the parameters within a function prototype.
@ CompoundStmtScope
This is a compound statement scope.
@ FunctionDeclarationScope
This is a scope that corresponds to the parameters within a function prototype for a function declara...
@ FnScope
This indicates that the scope corresponds to a function, which means that labels are set here.
@ DeclScope
This is a scope that can contain a declaration.
ParserCompletionContext
Describes the context in which code completion occurs.
@ PCC_TopLevelOrExpression
Code completion occurs at top-level in a REPL session.
@ PCC_Class
Code completion occurs within a class, struct, or union.
@ PCC_ObjCImplementation
Code completion occurs within an Objective-C implementation or category implementation.
@ PCC_Namespace
Code completion occurs at top-level or namespace context.
@ PCC_RecoveryInFunction
Code completion occurs within the body of a function on a recovery path, where we do not have a speci...
ExprResult getExpression() const
NameClassificationKind getKind() const
NamedDecl * getNonTypeDecl() const
TemplateName getTemplateName() const
ParsedType getType() const
TemplateNameKind getTemplateNameKind() const
Sema - This implements semantic analysis and AST building for C.
@ Interface
'export module X;'
@ Implementation
'module X;'
@ Other
C++26 [dcl.fct.def.general]p1 function-body: ctor-initializer[opt] compound-statement function-try-bl...
@ Delete
deleted-function-body
ModuleImportState
An enumeration to represent the transition of states in parsing module fragments and imports.
@ PrivateFragmentImportFinished
after 'module :private;' but a non-import decl has already been seen.
@ ImportFinished
after any non-import decl.
@ PrivateFragmentImportAllowed
after 'module :private;' but before any non-import decl.
@ FirstDecl
Parsing the first decl in a TU.
@ GlobalFragment
after 'module;' but before 'module X;'
@ NotACXX20Module
Not a C++20 TU, or an invalid state was found.
@ ImportAllowed
after 'module X;' but before any non-import decl.
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Represents a C++ template name within the type system.
Token - This structure provides full information about a lexed token.
IdentifierInfo * getIdentifierInfo() const
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
void setKind(tok::TokenKind K)
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
void * getAnnotationValue() const
tok::TokenKind getKind() const
bool hasSeenNoTrivialPPDirective() const
bool isObjCObjectType() const
bool isObjCObjectPointerType() const
Represents a C++ unqualified-id that has been parsed.
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
const char * getPunctuatorSpelling(TokenKind Kind) LLVM_READNONE
Determines the spelling of simple punctuation tokens like '!
The JSON file list parser is used to communicate input to InstallAPI.
TypeSpecifierType
Specifies the kind of type.
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
@ Unresolved
The identifier can't be resolved.
@ Success
Annotation was successful.
@ Error
Annotation has failed and emitted an error.
@ TentativeDecl
The identifier is a tentatively-declared name.
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
ActionResult< Decl * > DeclResult
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ Dependent
Parse the block as a dependent block, which may be used in some template instantiations but not other...
@ Skip
Skip the block entirely; this code is never used.
@ Parse
Parse the block; this code is always used.
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
bool isLambdaCallOperator(const CXXMethodDecl *MD)
@ Result
The result type of a method or function.
ActionResult< ParsedType > TypeResult
const FunctionProtoType * T
@ Template
We are parsing a template declaration.
@ FunctionTemplate
The name was classified as a function template name.
@ Keyword
The name has been typo-corrected to a keyword.
@ DependentNonType
The name denotes a member of a dependent type that could not be resolved.
@ UndeclaredTemplate
The name was classified as an ADL-only function template name.
@ NonType
The name was classified as a specific non-type, non-template declaration.
@ Unknown
This name is not a type or template in this context, but might be something else.
@ Error
Classification failed; an error has been produced.
@ Type
The name was classified as a type.
@ TypeTemplate
The name was classified as a template whose specializations are types.
@ Concept
The name was classified as a concept name.
@ OverloadSet
The name was classified as an overload set, and an expression representing that overload set has been...
@ UndeclaredNonType
The name was classified as an ADL-only function name.
@ VarTemplate
The name was classified as a variable template name.
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
ExtraSemiKind
The kind of extra semi diagnostic to emit.
@ AfterMemberFunctionDefinition
TemplateNameKind
Specifies the kind of template name that an identifier refers to.
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
@ TNK_Undeclared_template
Lookup for the name failed, but we're assuming it was a template name anyway.
@ Dependent
The name is a dependent name, so the results will differ from one instantiation to the next.
@ Exists
The symbol exists.
@ Error
An error occurred.
@ DoesNotExist
The symbol does not exist.
U cast(CodeGen::Address addr)
SmallVector< Token, 4 > CachedTokens
A set of tokens that has been cached for later parsing.
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
ParenParseOption
ParenParseOption - Control what ParseParenExpression will parse.
ActionResult< Expr * > ExprResult
@ Braces
New-expression has a C++11 list-initializer.
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
bool isKNRPrototype() const
isKNRPrototype - Return true if this is a K&R style identifier list, like "void foo(a,...
const IdentifierInfo * Ident
Information about a template-id annotation token.
const IdentifierInfo * Name
FIXME: Temporarily stores the name of a specialization.
TemplateNameKind Kind
The kind of template that Template refers to.
unsigned NumArgs
NumArgs - The number of template arguments.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
SourceLocation TemplateKWLoc
TemplateKWLoc - The location of the template keyword.
bool mightBeType() const
Determine whether this might be a type template.
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.