29#include "llvm/ADT/STLForwardCompat.h"
30#include "llvm/Support/Path.h"
31#include "llvm/Support/TimeProfiler.h"
42 explicit ActionCommentHandler(Sema &S) : S(S) { }
44 bool HandleComment(Preprocessor &PP, SourceRange Comment)
override {
45 S.ActOnComment(Comment);
51bool Parser::isTokenSEHExcept() {
52 if (!Tok.is(tok::identifier))
56 Ident__except = PP.getIdentifierInfo(
"__except");
58 const IdentifierInfo *Identifier = Tok.getIdentifierInfo();
59 if (Identifier == Ident__except)
64 Ident_except = PP.getIdentifierInfo(
"_except");
65 if (Identifier == Ident_except)
74 PreferredType(&actions.getASTContext(), pp.isCodeCompletionEnabled()),
75 Actions(actions), Diags(PP.getDiagnostics()), StackHandler(Diags),
76 GreaterThanIsOperator(
true), ColonIsSacred(
false),
77 InMessageExpression(
false), ParsingInObjCContainer(
false),
78 TemplateParameterDepth(0) {
81 Tok.setKind(tok::eof);
82 Actions.CurScope =
nullptr;
84 CurParsedObjCImpl =
nullptr;
88 initializePragmaHandlers();
90 CommentSemaHandler.reset(
new ActionCommentHandler(actions));
91 PP.addCommentHandler(CommentSemaHandler.get());
93 PP.setCodeCompletionHandler(*
this);
95 Actions.ParseTypeFromStringCallback =
96 [
this](StringRef TypeStr, StringRef Context,
SourceLocation IncludeLoc) {
97 return this->ParseTypeFromString(TypeStr, Context, IncludeLoc);
102 return Diags.Report(Loc, DiagID);
106 return Diag(Tok.getLocation(), DiagID);
110 unsigned CompatDiagId) {
115 return DiagCompat(Tok.getLocation(), CompatDiagId);
134 switch (ExpectedTok) {
136 return Tok.is(tok::colon) ||
Tok.is(tok::comma);
137 default:
return false;
141bool Parser::ExpectAndConsume(
tok::TokenKind ExpectedTok,
unsigned DiagID,
143 if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) {
150 SourceLocation Loc = Tok.getLocation();
152 DiagnosticBuilder DB =
Diag(Loc, DiagID);
155 if (DiagID == diag::err_expected)
157 else if (DiagID == diag::err_expected_after)
158 DB << Msg << ExpectedTok;
168 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
169 const char *Spelling =
nullptr;
173 DiagnosticBuilder DB =
177 if (DiagID == diag::err_expected)
179 else if (DiagID == diag::err_expected_after)
180 DB << Msg << ExpectedTok;
187bool Parser::ExpectAndConsumeSemi(
unsigned DiagID, StringRef TokenUsed) {
191 if (Tok.is(tok::code_completion)) {
192 handleUnexpectedCodeCompletionToken();
196 if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) &&
198 Diag(Tok, diag::err_extraneous_token_before_semi)
199 << PP.getSpelling(Tok)
206 return ExpectAndConsume(tok::semi, DiagID , TokenUsed);
209bool Parser::isLikelyAtStartOfNewDeclaration() {
210 return Tok.isAtStartOfLine() &&
215 if (!Tok.is(tok::semi))
return;
217 bool HadMultipleSemis =
false;
218 SourceLocation StartLoc = Tok.getLocation();
219 SourceLocation EndLoc = Tok.getLocation();
222 while ((Tok.is(tok::semi) && !Tok.isAtStartOfLine())) {
223 HadMultipleSemis =
true;
224 EndLoc = Tok.getLocation();
232 Diag(StartLoc, diag::warn_cxx98_compat_top_level_semi)
235 Diag(StartLoc, diag::ext_extra_semi_cxx11)
241 Diag(StartLoc, diag::ext_extra_semi)
244 TST, Actions.getASTContext().getPrintingPolicy())
248 Diag(StartLoc, diag::warn_extra_semi_after_mem_fn_def)
252bool Parser::expectIdentifier() {
253 if (Tok.is(tok::identifier))
255 if (
const auto *II = Tok.getIdentifierInfo()) {
257 Diag(Tok, diag::err_expected_token_instead_of_objcxx_keyword)
258 << tok::identifier << Tok.getIdentifierInfo();
263 Diag(Tok, diag::err_expected) << tok::identifier;
271 SourceLocation SecondTokLoc = Tok.getLocation();
276 PP.getSourceManager().getFileID(FirstTokLoc) !=
277 PP.getSourceManager().getFileID(SecondTokLoc)) {
278 Diag(FirstTokLoc, diag::warn_compound_token_split_by_macro)
279 << (FirstTokKind == Tok.getKind()) << FirstTokKind << Tok.getKind()
280 <<
static_cast<int>(Op) << SourceRange(FirstTokLoc);
281 Diag(SecondTokLoc, diag::note_compound_token_split_second_token_here)
282 << (FirstTokKind == Tok.getKind()) << Tok.getKind()
283 << SourceRange(SecondTokLoc);
288 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
289 SourceLocation SpaceLoc = PP.getLocForEndOfToken(FirstTokLoc);
291 SpaceLoc = FirstTokLoc;
292 Diag(SpaceLoc, diag::warn_compound_token_split_by_whitespace)
293 << (FirstTokKind == Tok.getKind()) << FirstTokKind << Tok.getKind()
294 <<
static_cast<int>(Op) << SourceRange(FirstTokLoc, SecondTokLoc);
304 return (
static_cast<unsigned>(L) &
static_cast<unsigned>(R)) != 0;
310 bool isFirstTokenSkipped =
true;
313 for (
unsigned i = 0, NumToks = Toks.size(); i != NumToks; ++i) {
314 if (Tok.is(Toks[i])) {
327 if (Toks.size() == 1 && Toks[0] == tok::eof &&
330 while (Tok.isNot(tok::eof))
335 switch (Tok.getKind()) {
340 case tok::annot_pragma_openmp:
341 case tok::annot_attr_openmp:
342 case tok::annot_pragma_openmp_end:
344 if (OpenMPDirectiveParsing)
346 ConsumeAnnotationToken();
348 case tok::annot_pragma_openacc:
349 case tok::annot_pragma_openacc_end:
351 if (OpenACCDirectiveParsing)
353 ConsumeAnnotationToken();
355 case tok::annot_module_begin:
356 case tok::annot_module_end:
357 case tok::annot_module_include:
358 case tok::annot_repl_input_end:
364 case tok::code_completion:
366 handleUnexpectedCodeCompletionToken();
408 if (ParenCount && !isFirstTokenSkipped)
413 if (BracketCount && !isFirstTokenSkipped)
418 if (BraceCount && !isFirstTokenSkipped)
432 isFirstTokenSkipped =
false;
441 if (NumCachedScopes) {
442 Scope *N = ScopeCache[--NumCachedScopes];
444 Actions.CurScope = N;
455 Actions.ActOnPopScope(Tok.getLocation(),
getCurScope());
458 Actions.CurScope = OldScope->
getParent();
460 if (NumCachedScopes == ScopeCacheSize)
463 ScopeCache[NumCachedScopes++] = OldScope;
466Parser::ParseScopeFlags::ParseScopeFlags(
Parser *
Self,
unsigned ScopeFlags,
468 : CurScope(ManageFlags ?
Self->getCurScope() :
nullptr) {
470 OldFlags = CurScope->getFlags();
471 CurScope->setFlags(ScopeFlags);
475Parser::ParseScopeFlags::~ParseScopeFlags() {
477 CurScope->setFlags(OldFlags);
488 Actions.CurScope =
nullptr;
491 for (
unsigned i = 0, e = NumCachedScopes; i != e; ++i)
492 delete ScopeCache[i];
494 resetPragmaHandlers();
496 PP.removeCommentHandler(CommentSemaHandler.get());
498 PP.clearCodeCompletionHandler();
500 DestroyTemplateIds();
505 assert(
getCurScope() ==
nullptr &&
"A scope is already active?");
513 &PP.getIdentifierTable().get(
"in");
515 &PP.getIdentifierTable().get(
"out");
517 &PP.getIdentifierTable().get(
"inout");
519 &PP.getIdentifierTable().get(
"oneway");
521 &PP.getIdentifierTable().get(
"bycopy");
523 &PP.getIdentifierTable().get(
"byref");
525 &PP.getIdentifierTable().get(
"nonnull");
527 &PP.getIdentifierTable().get(
"nullable");
529 &PP.getIdentifierTable().get(
"null_unspecified");
532 Ident_instancetype =
nullptr;
533 Ident_final =
nullptr;
534 Ident_sealed =
nullptr;
535 Ident_abstract =
nullptr;
536 Ident_override =
nullptr;
537 Ident_GNU_final =
nullptr;
539 Ident_super = &PP.getIdentifierTable().get(
"super");
541 Ident_vector =
nullptr;
542 Ident_bool =
nullptr;
543 Ident_Bool =
nullptr;
544 Ident_pixel =
nullptr;
546 Ident_vector = &PP.getIdentifierTable().get(
"vector");
547 Ident_bool = &PP.getIdentifierTable().get(
"bool");
548 Ident_Bool = &PP.getIdentifierTable().get(
"_Bool");
551 Ident_pixel = &PP.getIdentifierTable().get(
"pixel");
553 Ident_introduced =
nullptr;
554 Ident_deprecated =
nullptr;
555 Ident_obsoleted =
nullptr;
556 Ident_unavailable =
nullptr;
557 Ident_strict =
nullptr;
558 Ident_replacement =
nullptr;
560 Ident_language = Ident_defined_in = Ident_generated_declaration = Ident_USR =
563 Ident__except =
nullptr;
564 Ident_except =
nullptr;
566 Ident__exception_code = Ident__exception_info =
nullptr;
567 Ident__abnormal_termination = Ident___exception_code =
nullptr;
568 Ident___exception_info = Ident___abnormal_termination =
nullptr;
569 Ident_GetExceptionCode = Ident_GetExceptionInfo =
nullptr;
570 Ident_AbnormalTermination =
nullptr;
573 Ident__exception_info = PP.getIdentifierInfo(
"_exception_info");
574 Ident___exception_info = PP.getIdentifierInfo(
"__exception_info");
575 Ident_GetExceptionInfo = PP.getIdentifierInfo(
"GetExceptionInformation");
576 Ident__exception_code = PP.getIdentifierInfo(
"_exception_code");
577 Ident___exception_code = PP.getIdentifierInfo(
"__exception_code");
578 Ident_GetExceptionCode = PP.getIdentifierInfo(
"GetExceptionCode");
579 Ident__abnormal_termination = PP.getIdentifierInfo(
"_abnormal_termination");
580 Ident___abnormal_termination = PP.getIdentifierInfo(
"__abnormal_termination");
581 Ident_AbnormalTermination = PP.getIdentifierInfo(
"AbnormalTermination");
583 PP.SetPoisonReason(Ident__exception_code,diag::err_seh___except_block);
584 PP.SetPoisonReason(Ident___exception_code,diag::err_seh___except_block);
585 PP.SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block);
586 PP.SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter);
587 PP.SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter);
588 PP.SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter);
589 PP.SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block);
590 PP.SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block);
591 PP.SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block);
594 Actions.Initialize();
600void Parser::DestroyTemplateIds() {
608 Actions.ActOnStartOfTranslationUnit();
620 if (NoTopLevelDecls && !Actions.getASTContext().getExternalSource() &&
622 Diag(diag::ext_empty_translation_unit);
624 return NoTopLevelDecls;
629 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*
this);
632 switch (Tok.getKind()) {
633 case tok::annot_pragma_unused:
634 HandlePragmaUnused();
650 Result = ParseModuleDecl(ImportState);
660 case tok::annot_module_include: {
661 auto Loc = Tok.getLocation();
662 Module *Mod =
reinterpret_cast<Module *
>(Tok.getAnnotationValue());
666 Actions.ActOnAnnotModuleInclude(Loc, Mod);
673 ConsumeAnnotationToken();
677 case tok::annot_module_begin:
678 Actions.ActOnAnnotModuleBegin(
680 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
681 ConsumeAnnotationToken();
685 case tok::annot_module_end:
686 Actions.ActOnAnnotModuleEnd(
688 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
689 ConsumeAnnotationToken();
694 case tok::annot_repl_input_end:
696 if (PP.getMaxTokens() != 0 && PP.getTokenCount() > PP.getMaxTokens()) {
697 PP.Diag(Tok.getLocation(), diag::warn_max_tokens_total)
698 << PP.getTokenCount() << PP.getMaxTokens();
701 PP.Diag(OverrideLoc, diag::note_max_tokens_total_override);
706 Actions.SetLateTemplateParser(LateTemplateParserCallback,
this);
707 Actions.ActOnEndOfTranslationUnit();
720 while (MaybeParseCXX11Attributes(DeclAttrs) ||
721 MaybeParseGNUAttributes(DeclSpecAttrs))
724 Result = ParseExternalDeclaration(DeclAttrs, DeclSpecAttrs);
734 else if (ImportState ==
746 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*
this);
754 Decl *SingleDecl =
nullptr;
755 switch (
Tok.getKind()) {
756 case tok::annot_pragma_vis:
757 HandlePragmaVisibility();
759 case tok::annot_pragma_pack:
762 case tok::annot_pragma_msstruct:
763 HandlePragmaMSStruct();
765 case tok::annot_pragma_align:
768 case tok::annot_pragma_weak:
771 case tok::annot_pragma_weakalias:
772 HandlePragmaWeakAlias();
774 case tok::annot_pragma_redefine_extname:
775 HandlePragmaRedefineExtname();
777 case tok::annot_pragma_fp_contract:
778 HandlePragmaFPContract();
780 case tok::annot_pragma_fenv_access:
781 case tok::annot_pragma_fenv_access_ms:
782 HandlePragmaFEnvAccess();
784 case tok::annot_pragma_fenv_round:
785 HandlePragmaFEnvRound();
787 case tok::annot_pragma_cx_limited_range:
788 HandlePragmaCXLimitedRange();
790 case tok::annot_pragma_float_control:
791 HandlePragmaFloatControl();
793 case tok::annot_pragma_fp:
796 case tok::annot_pragma_opencl_extension:
797 HandlePragmaOpenCLExtension();
799 case tok::annot_attr_openmp:
800 case tok::annot_pragma_openmp: {
802 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
804 case tok::annot_pragma_openacc: {
809 case tok::annot_pragma_ms_pointers_to_members:
810 HandlePragmaMSPointersToMembers();
812 case tok::annot_pragma_ms_vtordisp:
813 HandlePragmaMSVtorDisp();
815 case tok::annot_pragma_ms_pragma:
816 HandlePragmaMSPragma();
818 case tok::annot_pragma_dump:
821 case tok::annot_pragma_attribute:
822 HandlePragmaAttribute();
824 case tok::annot_pragma_export:
825 HandlePragmaExport();
830 Actions.ActOnEmptyDeclaration(
getCurScope(), Attrs, Tok.getLocation());
834 Diag(Tok, diag::err_extraneous_closing_brace);
838 Diag(Tok, diag::err_expected_external_declaration);
840 case tok::kw___extension__: {
842 ExtensionRAIIObject O(Diags);
844 return ParseExternalDeclaration(Attrs, DeclSpecAttrs);
847 ProhibitAttributes(Attrs);
849 SourceLocation StartLoc = Tok.getLocation();
850 SourceLocation EndLoc;
859 if (!SL->getString().trim().empty())
860 Diag(StartLoc, diag::err_gnu_inline_asm_disabled);
863 ExpectAndConsume(tok::semi, diag::err_expected_after,
864 "top-level asm block");
868 SingleDecl = Actions.ActOnFileScopeAsmDecl(
Result.get(), StartLoc, EndLoc);
872 return ParseObjCAtDirectives(Attrs, DeclSpecAttrs);
876 Diag(Tok, diag::err_expected_external_declaration);
880 SingleDecl = ParseObjCMethodDefinition();
882 case tok::code_completion:
884 if (CurParsedObjCImpl) {
886 Actions.CodeCompletion().CodeCompleteObjCMethodDecl(
893 if (CurParsedObjCImpl) {
895 }
else if (PP.isIncrementalProcessingEnabled()) {
900 Actions.CodeCompletion().CodeCompleteOrdinaryName(
getCurScope(), PCC);
902 case tok::kw_import: {
905 Diag(Tok, diag::err_unexpected_module_or_import_decl)
910 SingleDecl = ParseModuleImport(SourceLocation(), IS);
914 ProhibitAttributes(Attrs);
915 SingleDecl = ParseExportDeclaration();
922 case tok::kw_namespace:
923 case tok::kw_typedef:
924 case tok::kw_template:
925 case tok::kw_static_assert:
926 case tok::kw__Static_assert:
929 SourceLocation DeclEnd;
934 case tok::kw_cbuffer:
935 case tok::kw_tbuffer:
937 SourceLocation DeclEnd;
949 SourceLocation DeclEnd;
960 if (NextKind == tok::kw_namespace) {
961 SourceLocation DeclEnd;
968 if (NextKind == tok::kw_template) {
971 SourceLocation DeclEnd;
980 ProhibitAttributes(Attrs);
981 ProhibitAttributes(DeclSpecAttrs);
985 DiagCompat(ExternLoc, diag_compat::extern_template)
986 << SourceRange(ExternLoc, TemplateLoc);
987 SourceLocation DeclEnd;
989 TemplateLoc, DeclEnd, Attrs);
993 case tok::kw___if_exists:
994 case tok::kw___if_not_exists:
995 ParseMicrosoftIfExistsExternalDeclaration();
999 Diag(Tok, diag::err_unexpected_module_or_import_decl) <<
false;
1005 if (Tok.isEditorPlaceholder()) {
1010 !isDeclarationStatement(
true))
1011 return ParseTopLevelStmtDecl();
1015 return ParseDeclarationOrFunctionDefinition(Attrs, DeclSpecAttrs, DS);
1020 return Actions.ConvertDeclToDeclGroup(SingleDecl);
1023bool Parser::isDeclarationAfterDeclarator() {
1027 if (KW.
is(tok::kw_default) || KW.
is(tok::kw_delete))
1031 return Tok.is(tok::equal) ||
1032 Tok.is(tok::comma) ||
1033 Tok.is(tok::semi) ||
1034 Tok.is(tok::kw_asm) ||
1035 Tok.is(tok::kw___attribute) ||
1037 Tok.is(tok::l_paren));
1040bool Parser::isStartOfFunctionDefinition(
const ParsingDeclarator &Declarator) {
1041 assert(
Declarator.isFunctionDeclarator() &&
"Isn't a function declarator");
1042 if (Tok.is(tok::l_brace))
1047 Declarator.getFunctionTypeInfo().isKNRPrototype())
1052 return KW.
is(tok::kw_default) || KW.
is(tok::kw_delete);
1055 return Tok.is(tok::colon) ||
1056 Tok.is(tok::kw_try);
1060 ParsedAttributes &Attrs, ParsedAttributes &DeclSpecAttrs,
1066 "expected uninitialised source range");
1071 ParsedTemplateInfo TemplateInfo;
1074 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
1075 DeclSpecContext::DSC_top_level);
1080 DS, AS, DeclSpecContext::DSC_top_level))
1085 if (Tok.is(tok::semi)) {
1088 SourceLocation CorrectLocationForAttributes{};
1092 if (
const auto *ED = dyn_cast_or_null<EnumDecl>(DS.
getRepAsDecl())) {
1093 CorrectLocationForAttributes =
1094 PP.getLocForEndOfToken(ED->getEnumKeyRange().getEnd());
1097 if (CorrectLocationForAttributes.
isInvalid()) {
1098 const auto &Policy = Actions.getASTContext().getPrintingPolicy();
1101 CorrectLocationForAttributes =
1105 ProhibitAttributes(Attrs, CorrectLocationForAttributes);
1107 RecordDecl *AnonRecord =
nullptr;
1108 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
1111 Actions.ActOnDefinedDeclarationSpecifier(TheDecl);
1113 Decl* decls[] = {AnonRecord, TheDecl};
1114 return Actions.BuildDeclaratorGroup(decls);
1116 return Actions.ConvertDeclToDeclGroup(TheDecl);
1120 Actions.ActOnDefinedDeclarationSpecifier(DS.
getRepAsDecl());
1127 if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
1128 !Tok.isObjCAtKeyword(tok::objc_protocol) &&
1129 !Tok.isObjCAtKeyword(tok::objc_implementation)) {
1130 Diag(Tok, diag::err_objc_unexpected_attr);
1138 const char *PrevSpec =
nullptr;
1141 Actions.getASTContext().getPrintingPolicy()))
1142 Diag(AtLoc, DiagID) << PrevSpec;
1144 if (Tok.isObjCAtKeyword(tok::objc_protocol))
1145 return ParseObjCAtProtocolDeclaration(AtLoc, DS.
getAttributes());
1147 if (Tok.isObjCAtKeyword(tok::objc_implementation))
1148 return ParseObjCAtImplementationDeclaration(AtLoc, DS.
getAttributes());
1150 return Actions.ConvertDeclToDeclGroup(
1151 ParseObjCAtInterfaceDeclaration(AtLoc, DS.
getAttributes()));
1160 ProhibitAttributes(Attrs);
1162 return Actions.ConvertDeclToDeclGroup(TheDecl);
1169 ParsedAttributes &Attrs, ParsedAttributes &DeclSpecAttrs,
1173 llvm::TimeTraceScope TimeScope(
"ParseDeclarationOrFunctionDefinition", [&]() {
1174 return Tok.getLocation().printToString(
1175 Actions.getASTContext().getSourceManager());
1179 return ParseDeclOrFunctionDefInternal(Attrs, DeclSpecAttrs, *DS, AS);
1181 ParsingDeclSpec PDS(*
this);
1185 ObjCDeclContextSwitch ObjCDC(*
this);
1187 return ParseDeclOrFunctionDefInternal(Attrs, DeclSpecAttrs, PDS, AS);
1191Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
1192 const ParsedTemplateInfo &TemplateInfo,
1193 LateParsedAttrList *LateParsedAttrs) {
1194 llvm::TimeTraceScope TimeScope(
"ParseFunctionDefinition", [&]() {
1195 return Actions.GetNameForDeclarator(D).getName().getAsString();
1201 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1210 const char *PrevSpec;
1212 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1224 ParseKNRParamDeclarations(D);
1228 if (Tok.isNot(tok::l_brace) &&
1230 (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
1231 Tok.isNot(tok::equal)))) {
1232 Diag(Tok, diag::err_expected_fn_body);
1238 if (Tok.isNot(tok::l_brace))
1244 if (Tok.isNot(tok::equal)) {
1246 if (AL.isKnownToGCC() && !AL.isStandardAttributeSyntax())
1247 Diag(AL.getLoc(), diag::warn_attribute_on_function_definition) << AL;
1252 if (
getLangOpts().DelayedTemplateParsing && Tok.isNot(tok::equal) &&
1254 LateParsedAttrs->empty() && Actions.canDelayFunctionBody(D)) {
1262 Decl *DP = Actions.HandleDeclarator(ParentScope, D,
1267 if (SkipFunctionBodies && (!DP || Actions.canSkipFunctionBody(DP)) &&
1268 trySkippingFunctionBody()) {
1270 return Actions.ActOnSkippedFunctionBody(DP);
1274 LexTemplateFunctionForLateParsing(Toks);
1278 Actions.CheckForFunctionRedefinition(FnD);
1279 Actions.MarkAsLateParsedTemplate(FnD, DP, Toks);
1283 if (CurParsedObjCImpl && !TemplateInfo.TemplateParams &&
1284 (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) || Tok.is(tok::colon)) &&
1285 Actions.CurContext->isTranslationUnit()) {
1291 Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
1297 StashAwayMethodOrFunctionBodyTokens(FuncDecl);
1298 CurParsedObjCImpl->HasCFunction =
true;
1310 StringLiteral *DeletedMessage =
nullptr;
1312 SourceLocation KWLoc;
1317 DiagCompat(KWLoc, diag_compat::defaulted_deleted_function)
1320 DeletedMessage = ParseCXXDeletedFunctionMessage();
1323 DiagCompat(KWLoc, diag_compat::defaulted_deleted_function)
1328 llvm_unreachable(
"function definition after = not 'delete' or 'default'");
1331 if (Tok.is(tok::comma)) {
1332 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
1335 }
else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
1343 Sema::FPFeaturesStateRAII SaveFPFeatures(Actions);
1347 SkipBodyInfo SkipBody;
1349 TemplateInfo.TemplateParams
1350 ? *TemplateInfo.TemplateParams
1352 &SkipBody, BodyKind);
1369 Actions.PopExpressionEvaluationContext();
1381 Actions.SetFunctionBodyKind(Res, KWLoc, BodyKind, DeletedMessage);
1382 Stmt *GeneratedBody = Res ? Res->
getBody() :
nullptr;
1383 Actions.ActOnFinishFunctionBody(Res, GeneratedBody,
false);
1389 if (
const auto *
Template = dyn_cast_if_present<FunctionTemplateDecl>(Res);
1391 Template->getTemplateParameters()->getParam(0)->isImplicit())
1394 CurTemplateDepthTracker.addDepth(1);
1397 if (LateParsedAttrs)
1398 ParseLexedAttributeList(*LateParsedAttrs, Res,
false,
1401 if (SkipFunctionBodies && (!Res || Actions.canSkipFunctionBody(Res)) &&
1402 trySkippingFunctionBody()) {
1404 Actions.ActOnSkippedFunctionBody(Res);
1405 return Actions.ActOnFinishFunctionBody(Res,
nullptr,
false);
1408 return ParseFunctionBody(Res, BodyScope);
1412 if (Tok.is(tok::kw_try))
1413 return ParseFunctionTryBlock(D, BodyScope);
1417 if (Tok.is(tok::colon)) {
1418 ParseConstructorInitializer(D);
1421 if (!Tok.is(tok::l_brace)) {
1425 Actions.ActOnFinishFunctionBody(D,
nullptr);
1429 Actions.ActOnDefaultCtorInitializers(D);
1431 return ParseFunctionStatementBody(D, BodyScope);
1434void Parser::SkipFunctionBody() {
1435 if (Tok.is(tok::equal)) {
1440 bool IsFunctionTryBlock = Tok.is(tok::kw_try);
1441 if (IsFunctionTryBlock)
1445 if (ConsumeAndStoreFunctionPrologue(Skipped))
1449 while (IsFunctionTryBlock && Tok.is(tok::kw_catch)) {
1456void Parser::ParseKNRParamDeclarations(Declarator &D) {
1467 SourceLocation DSStart = Tok.getLocation();
1470 DeclSpec DS(AttrFactory);
1471 ParsedTemplateInfo TemplateInfo;
1472 ParseDeclarationSpecifiers(DS, TemplateInfo);
1480 Diag(DSStart, diag::err_declaration_does_not_declare_param);
1489 diag::err_invalid_storage_class_in_func_decl);
1494 diag::err_invalid_storage_class_in_func_decl);
1501 ParseDeclarator(ParmDeclarator);
1506 MaybeParseGNUAttributes(ParmDeclarator);
1510 Actions.ActOnParamDeclarator(
getCurScope(), ParmDeclarator);
1514 ParmDeclarator.getIdentifier()) {
1518 for (
unsigned i = 0; ; ++i) {
1522 Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
1523 << ParmDeclarator.getIdentifier();
1527 if (FTI.
Params[i].
Ident == ParmDeclarator.getIdentifier()) {
1530 Diag(ParmDeclarator.getIdentifierLoc(),
1531 diag::err_param_redefinition)
1532 << ParmDeclarator.getIdentifier();
1543 if (Tok.isNot(tok::comma))
1546 ParmDeclarator.clear();
1552 ParseDeclarator(ParmDeclarator);
1556 if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration))
1566 Actions.ActOnFinishKNRParamDeclarations(
getCurScope(), D, Tok.getLocation());
1569ExprResult Parser::ParseAsmStringLiteral(
bool ForAsmLabel) {
1572 if (isTokenStringLiteral()) {
1578 if (!SL->isOrdinary()) {
1579 Diag(Tok, diag::err_asm_operand_wide_string_literal)
1580 << SL->isWide() << SL->getSourceRange();
1584 Tok.is(tok::l_paren)) {
1586 SourceLocation RParenLoc;
1589 EnterExpressionEvaluationContext ConstantEvaluated(
1591 AsmString = ParseParenExpression(
1595 AsmString = Actions.ActOnConstantExpression(AsmString);
1600 Diag(Tok, diag::err_asm_expected_string) << (
1601 (
getLangOpts().CPlusPlus11 && !ForAsmLabel) ? 0 : 1);
1604 return Actions.ActOnGCCAsmStmtString(AsmString.
get(), ForAsmLabel);
1607ExprResult Parser::ParseSimpleAsm(
bool ForAsmLabel, SourceLocation *EndLoc) {
1608 assert(Tok.is(tok::kw_asm) &&
"Not an asm!");
1611 if (isGNUAsmQualifier(Tok)) {
1613 SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
1614 PP.getLocForEndOfToken(Tok.getLocation()));
1615 Diag(Tok, diag::err_global_asm_qualifier_ignored)
1616 << GNUAsmQualifiers::getQualifierName(getGNUAsmQualifier(Tok))
1622 if (
T.consumeOpen()) {
1623 Diag(Tok, diag::err_expected_lparen_after) <<
"asm";
1629 if (!
Result.isInvalid()) {
1633 *EndLoc =
T.getCloseLocation();
1636 *EndLoc = Tok.getLocation();
1643TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(
const Token &tok) {
1644 assert(tok.
is(tok::annot_template_id) &&
"Expected template-id token");
1645 TemplateIdAnnotation *
1650void Parser::AnnotateScopeToken(CXXScopeSpec &SS,
bool IsNewAnnotation) {
1653 if (PP.isBacktrackEnabled())
1654 PP.RevertCachedTokens(1);
1656 PP.EnterToken(Tok,
true);
1657 Tok.setKind(tok::annot_cxxscope);
1658 Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
1659 Tok.setAnnotationRange(SS.
getRange());
1664 if (IsNewAnnotation)
1665 PP.AnnotateCachedTokens(Tok);
1669Parser::TryAnnotateName(CorrectionCandidateCallback *CCC,
1671 assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
1673 const bool EnteringContext =
false;
1674 const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1678 ParseOptionalCXXScopeSpecifier(SS,
nullptr,
1683 if (Tok.isNot(tok::identifier) || SS.
isInvalid()) {
1685 AllowImplicitTypename))
1690 IdentifierInfo *Name = Tok.getIdentifierInfo();
1691 SourceLocation NameLoc = Tok.getLocation();
1695 if (isTentativelyDeclared(Name) && SS.
isEmpty()) {
1699 AllowImplicitTypename))
1711 Sema::NameClassification Classification = Actions.ClassifyName(
1719 isTemplateArgumentList(1) == TPResult::False) {
1721 Token FakeNext =
Next;
1722 FakeNext.
setKind(tok::unknown);
1724 Actions.ClassifyName(
getCurScope(), SS, Name, NameLoc, FakeNext,
1725 SS.
isEmpty() ? CCC :
nullptr);
1728 switch (Classification.
getKind()) {
1734 Tok.setIdentifierInfo(Name);
1736 PP.TypoCorrectToken(Tok);
1738 AnnotateScopeToken(SS, !WasScopeAnnotation);
1747 if (TryAltiVecVectorToken())
1752 SourceLocation BeginLoc = NameLoc;
1759 QualType
T = Actions.GetTypeFromParser(Ty);
1764 SourceLocation NewEndLoc;
1766 = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
1771 else if (Tok.is(tok::eof))
1775 Tok.setKind(tok::annot_typename);
1776 setTypeAnnotation(Tok, Ty);
1777 Tok.setAnnotationEndLoc(Tok.getLocation());
1778 Tok.setLocation(BeginLoc);
1779 PP.AnnotateCachedTokens(Tok);
1784 Tok.setKind(tok::annot_overload_set);
1786 Tok.setAnnotationEndLoc(NameLoc);
1789 PP.AnnotateCachedTokens(Tok);
1793 if (TryAltiVecVectorToken())
1798 Tok.setKind(tok::annot_non_type);
1800 Tok.setLocation(NameLoc);
1801 Tok.setAnnotationEndLoc(NameLoc);
1802 PP.AnnotateCachedTokens(Tok);
1804 AnnotateScopeToken(SS, !WasScopeAnnotation);
1809 Tok.setKind(Classification.
getKind() ==
1811 ? tok::annot_non_type_undeclared
1812 : tok::annot_non_type_dependent);
1813 setIdentifierAnnotation(Tok, Name);
1814 Tok.setLocation(NameLoc);
1815 Tok.setAnnotationEndLoc(NameLoc);
1816 PP.AnnotateCachedTokens(Tok);
1818 AnnotateScopeToken(SS, !WasScopeAnnotation);
1822 if (
Next.isNot(tok::less)) {
1826 AnnotateScopeToken(SS, !WasScopeAnnotation);
1834 bool IsConceptName =
1840 if (
Next.is(tok::less))
1842 if (AnnotateTemplateIdToken(
1849 AnnotateScopeToken(SS, !WasScopeAnnotation);
1856 AnnotateScopeToken(SS, !WasScopeAnnotation);
1861 SourceLocation TokenEndLoc = PP.getLocForEndOfToken(PrevTokLocation);
1862 return TokenEndLoc.
isValid() ? TokenEndLoc : Tok.getLocation();
1865bool Parser::TryKeywordIdentFallback(
bool DisableKeyword) {
1866 assert(
Tok.isNot(tok::identifier));
1872 Tok.setKind(tok::identifier);
1876 Diag(
Tok, diag::ext_keyword_as_ident)
1881 Tok.setKind(tok::identifier);
1887 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1888 Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope) ||
1889 Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id) ||
1890 Tok.is(tok::kw___super) || Tok.is(tok::kw_auto) ||
1891 Tok.is(tok::annot_pack_indexing_type)) &&
1892 "Cannot be a type or scope token!");
1894 if (Tok.is(tok::kw_typename)) {
1903 PP.Lex(TypedefToken);
1905 PP.EnterToken(Tok,
true);
1908 Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename);
1920 if (ParseOptionalCXXScopeSpecifier(SS,
nullptr,
1926 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) ||
1927 Tok.is(tok::annot_decltype)) {
1929 if (Tok.is(tok::annot_decltype) ||
1931 Tok.isAnnotation())) {
1932 unsigned DiagID = diag::err_expected_qualified_after_typename;
1936 DiagID = diag::warn_expected_qualified_after_typename;
1937 Diag(Tok.getLocation(), DiagID);
1941 if (Tok.isEditorPlaceholder())
1944 Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
1948 bool TemplateKWPresent =
false;
1949 if (Tok.is(tok::kw_template)) {
1951 TemplateKWPresent =
true;
1955 if (Tok.is(tok::identifier)) {
1957 Diag(Tok.getLocation(),
1958 diag::missing_template_arg_list_after_template_kw);
1961 Ty = Actions.ActOnTypenameType(
getCurScope(), TypenameLoc, SS,
1962 *Tok.getIdentifierInfo(),
1964 }
else if (Tok.is(tok::annot_template_id)) {
1967 Diag(Tok, diag::err_typename_refers_to_non_type_template)
1968 << Tok.getAnnotationRange();
1977 : Actions.ActOnTypenameType(
1981 TemplateArgsPtr, TemplateId->
RAngleLoc);
1983 Diag(Tok, diag::err_expected_type_name_after_typename)
1989 Tok.setKind(tok::annot_typename);
1990 setTypeAnnotation(Tok, Ty);
1991 Tok.setAnnotationEndLoc(EndLoc);
1992 Tok.setLocation(TypenameLoc);
1993 PP.AnnotateCachedTokens(Tok);
1998 bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
2002 if (ParseOptionalCXXScopeSpecifier(
2006 IsAddressOfOperand))
2010 AllowImplicitTypename);
2016 if (Tok.is(tok::identifier)) {
2019 *Tok.getIdentifierInfo(), Tok.getLocation(),
getCurScope(), &SS,
2023 true, AllowImplicitTypename)) {
2028 QualType T = Actions.GetTypeFromParser(Ty);
2033 (
T->isObjCObjectType() ||
T->isObjCObjectPointerType())) {
2043 else if (Tok.is(tok::eof))
2049 Tok.setKind(tok::annot_typename);
2050 setTypeAnnotation(Tok, Ty);
2051 Tok.setAnnotationEndLoc(Tok.getLocation());
2052 Tok.setLocation(BeginLoc);
2056 PP.AnnotateCachedTokens(Tok);
2073 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
2074 bool MemberOfUnknownSpecialization;
2079 MemberOfUnknownSpecialization)) {
2083 isTemplateArgumentList(1) != TPResult::False) {
2103 if (Tok.is(tok::annot_template_id)) {
2110 AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
2117 Tok.is(tok::coloncolon)) {
2126 AnnotateScopeToken(SS, IsNewScope);
2132 "Call sites of this function should be guarded by checking for C++");
2136 if (ParseOptionalCXXScopeSpecifier(SS,
nullptr,
2143 AnnotateScopeToken(SS,
true);
2147bool Parser::isTokenEqualOrEqualTypo() {
2153 case tok::starequal:
2154 case tok::plusequal:
2155 case tok::minusequal:
2156 case tok::exclaimequal:
2157 case tok::slashequal:
2158 case tok::percentequal:
2159 case tok::lessequal:
2160 case tok::lesslessequal:
2161 case tok::greaterequal:
2162 case tok::greatergreaterequal:
2163 case tok::caretequal:
2164 case tok::pipeequal:
2165 case tok::equalequal:
2166 Diag(
Tok, diag::err_invalid_token_after_declarator_suggest_equal)
2175SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
2176 assert(Tok.is(tok::code_completion));
2177 PrevTokLocation = Tok.getLocation();
2180 if (S->isFunctionScope()) {
2182 Actions.CodeCompletion().CodeCompleteOrdinaryName(
2184 return PrevTokLocation;
2187 if (S->isClassScope()) {
2189 Actions.CodeCompletion().CodeCompleteOrdinaryName(
2191 return PrevTokLocation;
2196 Actions.CodeCompletion().CodeCompleteOrdinaryName(
2198 return PrevTokLocation;
2203void Parser::CodeCompleteDirective(
bool InConditional) {
2204 Actions.CodeCompletion().CodeCompletePreprocessorDirective(InConditional);
2208 Actions.CodeCompletion().CodeCompleteInPreprocessorConditionalExclusion(
2212void Parser::CodeCompleteMacroName(
bool IsDefinition) {
2213 Actions.CodeCompletion().CodeCompletePreprocessorMacroName(IsDefinition);
2217 Actions.CodeCompletion().CodeCompletePreprocessorExpression();
2220void Parser::CodeCompleteMacroArgument(IdentifierInfo *
Macro,
2221 MacroInfo *MacroInfo,
2222 unsigned ArgumentIndex) {
2223 Actions.CodeCompletion().CodeCompletePreprocessorMacroArgument(
2227void Parser::CodeCompleteIncludedFile(llvm::StringRef Dir,
bool IsAngled) {
2228 Actions.CodeCompletion().CodeCompleteIncludedFile(Dir, IsAngled);
2232 Actions.CodeCompletion().CodeCompleteNaturalLanguage();
2235void Parser::CodeCompleteModuleImport(SourceLocation ImportLoc,
2237 Actions.CodeCompletion().CodeCompleteModuleImport(ImportLoc, Path);
2240bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition&
Result) {
2241 assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
2242 "Expected '__if_exists' or '__if_not_exists'");
2243 Result.IsIfExists = Tok.is(tok::kw___if_exists);
2247 if (
T.consumeOpen()) {
2248 Diag(Tok, diag::err_expected_lparen_after)
2249 << (
Result.IsIfExists?
"__if_exists" :
"__if_not_exists");
2255 ParseOptionalCXXScopeSpecifier(
Result.SS,
nullptr,
2260 if (
Result.SS.isInvalid()) {
2266 SourceLocation TemplateKWLoc;
2271 false, &TemplateKWLoc,
2277 if (
T.consumeClose())
2305void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
2306 IfExistsCondition
Result;
2307 if (ParseMicrosoftIfExistsCondition(
Result))
2311 if (
Braces.consumeOpen()) {
2312 Diag(Tok, diag::err_expected) << tok::l_brace;
2316 switch (
Result.Behavior) {
2322 llvm_unreachable(
"Cannot have a dependent external declaration");
2331 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
2332 ParsedAttributes Attrs(AttrFactory);
2333 MaybeParseCXX11Attributes(Attrs);
2334 ParsedAttributes EmptyDeclSpecAttrs(AttrFactory);
2337 Actions.getASTConsumer().HandleTopLevelDecl(
Result.get());
2344 Token Introducer = Tok;
2345 SourceLocation StartLoc = Introducer.
getLocation();
2351 assert(Tok.is(tok::kw_module) &&
"not a module declaration");
2357 DiagnoseAndSkipCXX11Attributes();
2360 if (
getLangOpts().CPlusPlusModules && Tok.is(tok::semi)) {
2364 Diag(StartLoc, diag::err_global_module_introducer_not_at_start)
2365 << SourceRange(StartLoc, SemiLoc);
2369 Diag(StartLoc, diag::err_module_fragment_exported)
2373 return Actions.ActOnGlobalModuleFragmentDecl(ModuleLoc);
2377 if (
getLangOpts().CPlusPlusModules && Tok.is(tok::colon) &&
2380 Diag(StartLoc, diag::err_module_fragment_exported)
2385 DiagnoseAndSkipCXX11Attributes();
2386 ExpectAndConsumeSemi(diag::err_private_module_fragment_expected_semi);
2387 auto Result = Actions.ActOnPrivateModuleFragmentDecl(ModuleLoc, PrivateLoc);
2396 SmallVector<IdentifierLoc, 2> Path;
2397 if (ParseModuleName(ModuleLoc, Path,
false))
2401 SmallVector<IdentifierLoc, 2> Partition;
2402 if (Tok.is(tok::colon)) {
2405 Diag(ColonLoc, diag::err_unsupported_module_partition)
2406 << SourceRange(ColonLoc, Partition.back().getLoc());
2408 else if (ParseModuleName(ModuleLoc, Partition,
false))
2412 if (Tok.isNoneOf(tok::semi, tok::l_square, tok::eof)) {
2413 Diag(Tok, diag::err_unexpected_tok_after_module_name)
2414 << PP.getSpelling(Tok);
2419 ParsedAttributes Attrs(AttrFactory);
2420 MaybeParseCXX11Attributes(Attrs);
2421 ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_module_attr,
2422 diag::err_keyword_not_module_attr,
2426 if (ExpectAndConsumeSemi(diag::err_expected_semi_after_module_or_import,
2430 return Actions.ActOnModuleDecl(StartLoc, ModuleLoc, MDK, Path, Partition,
2435Decl *Parser::ParseModuleImport(SourceLocation AtLoc,
2437 SourceLocation StartLoc = AtLoc.
isInvalid() ? Tok.getLocation() : AtLoc;
2439 SourceLocation ExportLoc;
2442 assert((AtLoc.
isInvalid() ? Tok.is(tok::kw_import)
2443 : Tok.isObjCAtKeyword(tok::objc_import)) &&
2444 "Improper start to module import");
2445 bool IsObjCAtImport = Tok.isObjCAtKeyword(tok::objc_import);
2449 SmallVector<IdentifierLoc, 2> Path;
2450 bool IsPartition =
false;
2451 Module *HeaderUnit =
nullptr;
2452 if (Tok.is(tok::header_name)) {
2457 }
else if (Tok.is(tok::annot_header_unit)) {
2459 HeaderUnit =
reinterpret_cast<Module *
>(Tok.getAnnotationValue());
2460 ConsumeAnnotationToken();
2461 }
else if (Tok.is(tok::colon)) {
2464 Diag(ColonLoc, diag::err_unsupported_module_partition)
2465 << SourceRange(ColonLoc, Path.back().getLoc());
2467 else if (ParseModuleName(ColonLoc, Path,
true))
2472 if (ParseModuleName(ImportLoc, Path,
true))
2476 ParsedAttributes Attrs(AttrFactory);
2477 MaybeParseCXX11Attributes(Attrs);
2479 ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_import_attr,
2480 diag::err_keyword_not_import_attr,
2487 bool IsCXX20NamedModuleImport =
2488 getLangOpts().CPlusPlusModules && !IsObjCAtImport && !Path.empty();
2490 if (PP.hadModuleLoaderFatalFailure() && !IsCXX20NamedModuleImport) {
2497 bool SeenError =
true;
2498 switch (ImportState) {
2510 Diag(ImportLoc, diag::err_partition_import_outside_module);
2522 if (IsPartition || (HeaderUnit && HeaderUnit->
Kind !=
2524 Diag(ImportLoc, diag::err_import_in_wrong_fragment)
2533 Diag(ImportLoc, diag::err_import_not_allowed_here);
2549 bool LexedSemi =
false;
2552 !ExpectAndConsumeSemi(diag::err_expected_semi_after_module_or_import,
2555 LexedSemi = !ExpectAndConsumeSemi(diag::err_module_expected_semi);
2566 Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, HeaderUnit);
2567 else if (!Path.empty())
2568 Import = Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Path,
2575 if (IsObjCAtImport && AtLoc.
isValid()) {
2576 auto &SrcMgr = PP.getSourceManager();
2577 auto FE = SrcMgr.getFileEntryRefForID(SrcMgr.getFileID(AtLoc));
2578 if (FE && llvm::sys::path::parent_path(FE->getDir().getName())
2579 .ends_with(
".framework"))
2580 Diags.Report(AtLoc, diag::warn_atimport_in_framework_header);
2586bool Parser::ParseModuleName(SourceLocation UseLoc,
2587 SmallVectorImpl<IdentifierLoc> &Path,
2589 if (Tok.isNot(tok::annot_module_name)) {
2593 ModuleNameLoc *NameLoc =
2594 static_cast<ModuleNameLoc *
>(Tok.getAnnotationValue());
2597 ConsumeAnnotationToken();
2601bool Parser::parseMisplacedModuleImport() {
2603 switch (Tok.getKind()) {
2604 case tok::annot_module_end:
2608 if (MisplacedModuleBeginCount) {
2609 --MisplacedModuleBeginCount;
2610 Actions.ActOnAnnotModuleEnd(
2612 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
2613 ConsumeAnnotationToken();
2620 case tok::annot_module_begin:
2622 Actions.ActOnAnnotModuleBegin(
2624 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
2625 ConsumeAnnotationToken();
2626 ++MisplacedModuleBeginCount;
2628 case tok::annot_module_include:
2631 Actions.ActOnAnnotModuleInclude(
2633 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
2634 ConsumeAnnotationToken();
2644void Parser::diagnoseUseOfC11Keyword(
const Token &Tok) {
2649 : diag::ext_c11_feature)
2653bool BalancedDelimiterTracker::diagnoseOverflow() {
2654 P.Diag(P.Tok, diag::err_bracket_depth_exceeded)
2655 << P.getLangOpts().BracketDepth;
2656 P.Diag(P.Tok, diag::note_bracket_depth);
2664 LOpen = P.Tok.getLocation();
2665 if (P.ExpectAndConsume(Kind, DiagID, Msg)) {
2666 if (SkipToTok != tok::unknown)
2671 if (getDepth() < P.getLangOpts().BracketDepth)
2674 return diagnoseOverflow();
2677bool BalancedDelimiterTracker::diagnoseMissingClose() {
2678 assert(!P.Tok.is(Close) &&
"Should have consumed closing delimiter");
2680 if (P.Tok.is(tok::annot_module_end))
2681 P.Diag(P.Tok, diag::err_missing_before_module_end) << Close;
2683 P.Diag(P.Tok, diag::err_expected) << Close;
2684 P.Diag(LOpen, diag::note_matching) << Kind;
2688 if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) &&
2689 P.Tok.isNot(tok::r_square) &&
2690 P.SkipUntil(Close, FinalToken,
2693 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)
Defines the clang::Preprocessor interface.
This file declares facilities that support code completion.
Defines a utilitiy for warning once when close to out of stack space.
Defines the clang::TokenKind enum and support functions.
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)
SourceLocation getBeginLoc() const LLVM_READONLY
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.
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
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)
void SetRangeEnd(SourceLocation Loc)
SetRangeEnd - Set the end of the source range to Loc, unless it's invalid.
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
A little helper class used to produce diagnostics.
static unsigned getCompatDiagId(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.
void revertTokenIDToIdentifier()
Revert TokenID to tok::identifier; used for GNU libstdc++ 4.2 compatibility.
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...
ModuleIdPath getModuleIdPath() const
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.
bool TryAnnotateTypeOrScopeToken(ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No, bool IsAddressOfOperand=false)
TryAnnotateTypeOrScopeToken - If the current token position is on a typename (possibly qualified in C...
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.
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 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.
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.
const char * getKeywordSpelling(TokenKind Kind) LLVM_READNONE
Determines the spelling of simple keyword and contextual keyword tokens like 'int' and 'dynamic_cast'...
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 '!
Top level wrappers for InstallAPI frontend operations.
TypeSpecifierType
Specifies the kind of type.
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
ArrayRef< IdentifierLoc > ModuleIdPath
A sequence of identifier/location pairs used to describe a particular module or submodule,...
@ 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.