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 ParsingGenericAssociationType(
false), InMessageExpression(
false),
78 ParsingInObjCContainer(
false), TemplateParameterDepth(0) {
81 Actions.CurScope =
nullptr;
83 CurParsedObjCImpl =
nullptr;
87 initializePragmaHandlers();
89 CommentSemaHandler.reset(
new ActionCommentHandler(actions));
90 PP.addCommentHandler(CommentSemaHandler.get());
92 PP.setCodeCompletionHandler(*
this);
94 Actions.ParseTypeFromStringCallback =
95 [
this](StringRef TypeStr, StringRef Context,
SourceLocation IncludeLoc) {
96 return this->ParseTypeFromString(TypeStr, Context, IncludeLoc);
101 return Diags.Report(Loc, DiagID);
105 return Diag(Tok.getLocation(), DiagID);
109 unsigned CompatDiagId) {
114 return DiagCompat(Tok.getLocation(), CompatDiagId);
133 switch (ExpectedTok) {
135 return Tok.is(tok::colon) ||
Tok.is(tok::comma);
136 default:
return false;
140bool Parser::ExpectAndConsume(
tok::TokenKind ExpectedTok,
unsigned DiagID,
142 if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) {
149 SourceLocation Loc = Tok.getLocation();
151 DiagnosticBuilder DB =
Diag(Loc, DiagID);
154 if (DiagID == diag::err_expected)
156 else if (DiagID == diag::err_expected_after)
157 DB << Msg << ExpectedTok;
167 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
168 const char *Spelling =
nullptr;
172 DiagnosticBuilder DB =
176 if (DiagID == diag::err_expected)
178 else if (DiagID == diag::err_expected_after)
179 DB << Msg << ExpectedTok;
186bool Parser::ExpectAndConsumeSemi(
unsigned DiagID, StringRef TokenUsed) {
190 if (Tok.is(tok::code_completion)) {
191 handleUnexpectedCodeCompletionToken();
195 if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) &&
197 Diag(Tok, diag::err_extraneous_token_before_semi)
198 << PP.getSpelling(Tok)
205 return ExpectAndConsume(tok::semi, DiagID , TokenUsed);
208bool Parser::isLikelyAtStartOfNewDeclaration() {
209 return Tok.isAtStartOfLine() &&
214 if (!Tok.is(tok::semi))
return;
216 bool HadMultipleSemis =
false;
217 SourceLocation StartLoc = Tok.getLocation();
218 SourceLocation EndLoc = Tok.getLocation();
221 while ((Tok.is(tok::semi) && !Tok.isAtStartOfLine())) {
222 HadMultipleSemis =
true;
223 EndLoc = Tok.getLocation();
231 Diag(StartLoc, diag::warn_cxx98_compat_top_level_semi)
234 Diag(StartLoc, diag::ext_extra_semi_cxx11)
240 Diag(StartLoc, diag::ext_extra_semi)
243 TST, Actions.getASTContext().getPrintingPolicy())
247 Diag(StartLoc, diag::warn_extra_semi_after_mem_fn_def)
251bool Parser::expectIdentifier() {
252 if (Tok.is(tok::identifier))
254 if (
const auto *II = Tok.getIdentifierInfo()) {
256 Diag(Tok, diag::err_expected_token_instead_of_objcxx_keyword)
257 << tok::identifier << Tok.getIdentifierInfo();
262 Diag(Tok, diag::err_expected) << tok::identifier;
270 SourceLocation SecondTokLoc = Tok.getLocation();
275 PP.getSourceManager().getFileID(FirstTokLoc) !=
276 PP.getSourceManager().getFileID(SecondTokLoc)) {
277 Diag(FirstTokLoc, diag::warn_compound_token_split_by_macro)
278 << (FirstTokKind == Tok.getKind()) << FirstTokKind << Tok.getKind()
279 <<
static_cast<int>(Op) << SourceRange(FirstTokLoc);
280 Diag(SecondTokLoc, diag::note_compound_token_split_second_token_here)
281 << (FirstTokKind == Tok.getKind()) << Tok.getKind()
282 << SourceRange(SecondTokLoc);
287 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
288 SourceLocation SpaceLoc = PP.getLocForEndOfToken(FirstTokLoc);
290 SpaceLoc = FirstTokLoc;
291 Diag(SpaceLoc, diag::warn_compound_token_split_by_whitespace)
292 << (FirstTokKind == Tok.getKind()) << FirstTokKind << Tok.getKind()
293 <<
static_cast<int>(Op) << SourceRange(FirstTokLoc, SecondTokLoc);
303 return (
static_cast<unsigned>(L) &
static_cast<unsigned>(R)) != 0;
309 bool isFirstTokenSkipped =
true;
312 for (
unsigned i = 0, NumToks = Toks.size(); i != NumToks; ++i) {
313 if (Tok.is(Toks[i])) {
326 if (Toks.size() == 1 && Toks[0] == tok::eof &&
329 while (Tok.isNot(tok::eof))
334 switch (Tok.getKind()) {
339 case tok::annot_pragma_openmp:
340 case tok::annot_attr_openmp:
341 case tok::annot_pragma_openmp_end:
343 if (OpenMPDirectiveParsing)
345 ConsumeAnnotationToken();
347 case tok::annot_pragma_openacc:
348 case tok::annot_pragma_openacc_end:
350 if (OpenACCDirectiveParsing)
352 ConsumeAnnotationToken();
354 case tok::annot_module_begin:
355 case tok::annot_module_end:
356 case tok::annot_module_include:
357 case tok::annot_repl_input_end:
363 case tok::code_completion:
365 handleUnexpectedCodeCompletionToken();
407 if (ParenCount && !isFirstTokenSkipped)
412 if (BracketCount && !isFirstTokenSkipped)
417 if (BraceCount && !isFirstTokenSkipped)
431 isFirstTokenSkipped =
false;
440 if (NumCachedScopes) {
441 Scope *N = ScopeCache[--NumCachedScopes];
443 Actions.CurScope = N;
454 Actions.ActOnPopScope(Tok.getLocation(),
getCurScope());
457 Actions.CurScope = OldScope->
getParent();
459 if (NumCachedScopes == ScopeCacheSize)
462 ScopeCache[NumCachedScopes++] = OldScope;
465Parser::ParseScopeFlags::ParseScopeFlags(
Parser *
Self,
unsigned ScopeFlags,
467 : CurScope(ManageFlags ?
Self->getCurScope() :
nullptr) {
469 OldFlags = CurScope->getFlags();
470 CurScope->setFlags(ScopeFlags);
474Parser::ParseScopeFlags::~ParseScopeFlags() {
476 CurScope->setFlags(OldFlags);
487 Actions.CurScope =
nullptr;
490 for (
unsigned i = 0, e = NumCachedScopes; i != e; ++i)
491 delete ScopeCache[i];
493 resetPragmaHandlers();
495 PP.removeCommentHandler(CommentSemaHandler.get());
497 PP.clearCodeCompletionHandler();
499 DestroyTemplateIds();
504 assert(
getCurScope() ==
nullptr &&
"A scope is already active?");
512 &PP.getIdentifierTable().get(
"in");
514 &PP.getIdentifierTable().get(
"out");
516 &PP.getIdentifierTable().get(
"inout");
518 &PP.getIdentifierTable().get(
"oneway");
520 &PP.getIdentifierTable().get(
"bycopy");
522 &PP.getIdentifierTable().get(
"byref");
524 &PP.getIdentifierTable().get(
"nonnull");
526 &PP.getIdentifierTable().get(
"nullable");
528 &PP.getIdentifierTable().get(
"null_unspecified");
531 Ident_instancetype =
nullptr;
532 Ident_final =
nullptr;
533 Ident_sealed =
nullptr;
534 Ident_abstract =
nullptr;
535 Ident_override =
nullptr;
536 Ident_GNU_final =
nullptr;
538 Ident_super = &PP.getIdentifierTable().get(
"super");
540 Ident_vector =
nullptr;
541 Ident_bool =
nullptr;
542 Ident_Bool =
nullptr;
543 Ident_pixel =
nullptr;
545 Ident_vector = &PP.getIdentifierTable().get(
"vector");
546 Ident_bool = &PP.getIdentifierTable().get(
"bool");
547 Ident_Bool = &PP.getIdentifierTable().get(
"_Bool");
550 Ident_pixel = &PP.getIdentifierTable().get(
"pixel");
552 Ident_introduced =
nullptr;
553 Ident_deprecated =
nullptr;
554 Ident_obsoleted =
nullptr;
555 Ident_unavailable =
nullptr;
556 Ident_strict =
nullptr;
557 Ident_replacement =
nullptr;
559 Ident_language = Ident_defined_in = Ident_generated_declaration = Ident_USR =
562 Ident__except =
nullptr;
563 Ident_except =
nullptr;
565 Ident__exception_code = Ident__exception_info =
nullptr;
566 Ident__abnormal_termination = Ident___exception_code =
nullptr;
567 Ident___exception_info = Ident___abnormal_termination =
nullptr;
568 Ident_GetExceptionCode = Ident_GetExceptionInfo =
nullptr;
569 Ident_AbnormalTermination =
nullptr;
572 Ident__exception_info = PP.getIdentifierInfo(
"_exception_info");
573 Ident___exception_info = PP.getIdentifierInfo(
"__exception_info");
574 Ident_GetExceptionInfo = PP.getIdentifierInfo(
"GetExceptionInformation");
575 Ident__exception_code = PP.getIdentifierInfo(
"_exception_code");
576 Ident___exception_code = PP.getIdentifierInfo(
"__exception_code");
577 Ident_GetExceptionCode = PP.getIdentifierInfo(
"GetExceptionCode");
578 Ident__abnormal_termination = PP.getIdentifierInfo(
"_abnormal_termination");
579 Ident___abnormal_termination = PP.getIdentifierInfo(
"__abnormal_termination");
580 Ident_AbnormalTermination = PP.getIdentifierInfo(
"AbnormalTermination");
582 PP.SetPoisonReason(Ident__exception_code,diag::err_seh___except_block);
583 PP.SetPoisonReason(Ident___exception_code,diag::err_seh___except_block);
584 PP.SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block);
585 PP.SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter);
586 PP.SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter);
587 PP.SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter);
588 PP.SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block);
589 PP.SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block);
590 PP.SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block);
593 Actions.Initialize();
599void Parser::DestroyTemplateIds() {
607 Actions.ActOnStartOfTranslationUnit();
619 if (NoTopLevelDecls && !Actions.getASTContext().getExternalSource() &&
621 Diag(diag::ext_empty_translation_unit);
623 return NoTopLevelDecls;
628 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*
this);
631 switch (Tok.getKind()) {
632 case tok::annot_pragma_unused:
633 HandlePragmaUnused();
649 Result = ParseModuleDecl(ImportState);
659 case tok::annot_module_include: {
660 auto Loc = Tok.getLocation();
661 Module *Mod =
reinterpret_cast<Module *
>(Tok.getAnnotationValue());
665 Actions.ActOnAnnotModuleInclude(Loc, Mod);
672 ConsumeAnnotationToken();
676 case tok::annot_module_begin:
677 Actions.ActOnAnnotModuleBegin(
679 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
680 ConsumeAnnotationToken();
684 case tok::annot_module_end:
685 Actions.ActOnAnnotModuleEnd(
687 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
688 ConsumeAnnotationToken();
693 case tok::annot_repl_input_end:
695 if (PP.getMaxTokens() != 0 && PP.getTokenCount() > PP.getMaxTokens()) {
696 PP.Diag(Tok.getLocation(), diag::warn_max_tokens_total)
697 << PP.getTokenCount() << PP.getMaxTokens();
700 PP.Diag(OverrideLoc, diag::note_max_tokens_total_override);
705 Actions.SetLateTemplateParser(LateTemplateParserCallback,
this);
706 Actions.ActOnEndOfTranslationUnit();
719 while (MaybeParseCXX11Attributes(DeclAttrs) ||
720 MaybeParseGNUAttributes(DeclSpecAttrs))
723 Result = ParseExternalDeclaration(DeclAttrs, DeclSpecAttrs);
733 else if (ImportState ==
745 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*
this);
753 Decl *SingleDecl =
nullptr;
754 switch (
Tok.getKind()) {
755 case tok::annot_pragma_vis:
756 HandlePragmaVisibility();
758 case tok::annot_pragma_pack:
761 case tok::annot_pragma_msstruct:
762 HandlePragmaMSStruct();
764 case tok::annot_pragma_align:
767 case tok::annot_pragma_weak:
770 case tok::annot_pragma_weakalias:
771 HandlePragmaWeakAlias();
773 case tok::annot_pragma_redefine_extname:
774 HandlePragmaRedefineExtname();
776 case tok::annot_pragma_fp_contract:
777 HandlePragmaFPContract();
779 case tok::annot_pragma_fenv_access:
780 case tok::annot_pragma_fenv_access_ms:
781 HandlePragmaFEnvAccess();
783 case tok::annot_pragma_fenv_round:
784 HandlePragmaFEnvRound();
786 case tok::annot_pragma_cx_limited_range:
787 HandlePragmaCXLimitedRange();
789 case tok::annot_pragma_float_control:
790 HandlePragmaFloatControl();
792 case tok::annot_pragma_fp:
795 case tok::annot_pragma_opencl_extension:
796 HandlePragmaOpenCLExtension();
798 case tok::annot_attr_openmp:
799 case tok::annot_pragma_openmp: {
801 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
803 case tok::annot_pragma_openacc: {
808 case tok::annot_pragma_ms_pointers_to_members:
809 HandlePragmaMSPointersToMembers();
811 case tok::annot_pragma_ms_vtordisp:
812 HandlePragmaMSVtorDisp();
814 case tok::annot_pragma_ms_pragma:
815 HandlePragmaMSPragma();
817 case tok::annot_pragma_dump:
820 case tok::annot_pragma_attribute:
821 HandlePragmaAttribute();
823 case tok::annot_pragma_export:
824 HandlePragmaExport();
829 Actions.ActOnEmptyDeclaration(
getCurScope(), Attrs, Tok.getLocation());
833 Diag(Tok, diag::err_extraneous_closing_brace);
837 Diag(Tok, diag::err_expected_external_declaration);
839 case tok::kw___extension__: {
841 ExtensionRAIIObject O(Diags);
843 return ParseExternalDeclaration(Attrs, DeclSpecAttrs);
846 ProhibitAttributes(Attrs);
848 SourceLocation StartLoc = Tok.getLocation();
849 SourceLocation EndLoc;
858 if (!SL->getString().trim().empty())
859 Diag(StartLoc, diag::err_gnu_inline_asm_disabled);
862 ExpectAndConsume(tok::semi, diag::err_expected_after,
863 "top-level asm block");
867 SingleDecl = Actions.ActOnFileScopeAsmDecl(
Result.get(), StartLoc, EndLoc);
871 return ParseObjCAtDirectives(Attrs, DeclSpecAttrs);
875 Diag(Tok, diag::err_expected_external_declaration);
879 SingleDecl = ParseObjCMethodDefinition();
881 case tok::code_completion:
883 if (CurParsedObjCImpl) {
885 Actions.CodeCompletion().CodeCompleteObjCMethodDecl(
892 if (CurParsedObjCImpl) {
894 }
else if (PP.isIncrementalProcessingEnabled()) {
899 Actions.CodeCompletion().CodeCompleteOrdinaryName(
getCurScope(), PCC);
901 case tok::kw_import: {
904 Diag(Tok, diag::err_unexpected_module_or_import_decl)
909 SingleDecl = ParseModuleImport(SourceLocation(), IS);
913 ProhibitAttributes(Attrs);
914 SingleDecl = ParseExportDeclaration();
921 case tok::kw_namespace:
922 case tok::kw_typedef:
923 case tok::kw_template:
924 case tok::kw_static_assert:
925 case tok::kw__Static_assert:
928 SourceLocation DeclEnd;
933 case tok::kw_cbuffer:
934 case tok::kw_tbuffer:
936 SourceLocation DeclEnd;
948 SourceLocation DeclEnd;
959 if (NextKind == tok::kw_namespace) {
960 SourceLocation DeclEnd;
967 if (NextKind == tok::kw_template) {
970 SourceLocation DeclEnd;
979 ProhibitAttributes(Attrs);
980 ProhibitAttributes(DeclSpecAttrs);
984 DiagCompat(ExternLoc, diag_compat::extern_template)
985 << SourceRange(ExternLoc, TemplateLoc);
986 SourceLocation DeclEnd;
988 TemplateLoc, DeclEnd, Attrs);
992 case tok::kw___if_exists:
993 case tok::kw___if_not_exists:
994 ParseMicrosoftIfExistsExternalDeclaration();
998 Diag(Tok, diag::err_unexpected_module_or_import_decl) <<
false;
1004 if (Tok.isEditorPlaceholder()) {
1009 !isDeclarationStatement(
true))
1010 return ParseTopLevelStmtDecl();
1014 return ParseDeclarationOrFunctionDefinition(Attrs, DeclSpecAttrs, DS);
1019 return Actions.ConvertDeclToDeclGroup(SingleDecl);
1022bool Parser::isDeclarationAfterDeclarator() {
1026 if (KW.
is(tok::kw_default) || KW.
is(tok::kw_delete))
1030 return Tok.is(tok::equal) ||
1031 Tok.is(tok::comma) ||
1032 Tok.is(tok::semi) ||
1033 Tok.is(tok::kw_asm) ||
1034 Tok.is(tok::kw___attribute) ||
1036 Tok.is(tok::l_paren));
1039bool Parser::isStartOfFunctionDefinition(
const ParsingDeclarator &Declarator) {
1040 assert(
Declarator.isFunctionDeclarator() &&
"Isn't a function declarator");
1041 if (Tok.is(tok::l_brace))
1046 Declarator.getFunctionTypeInfo().isKNRPrototype())
1051 return KW.
is(tok::kw_default) || KW.
is(tok::kw_delete);
1054 return Tok.is(tok::colon) ||
1055 Tok.is(tok::kw_try);
1059 ParsedAttributes &Attrs, ParsedAttributes &DeclSpecAttrs,
1065 "expected uninitialised source range");
1070 ParsedTemplateInfo TemplateInfo;
1073 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
1074 DeclSpecContext::DSC_top_level);
1079 DS, AS, DeclSpecContext::DSC_top_level))
1084 if (Tok.is(tok::semi)) {
1087 SourceLocation CorrectLocationForAttributes{};
1091 if (
const auto *ED = dyn_cast_or_null<EnumDecl>(DS.
getRepAsDecl())) {
1092 CorrectLocationForAttributes =
1093 PP.getLocForEndOfToken(ED->getEnumKeyRange().getEnd());
1096 if (CorrectLocationForAttributes.
isInvalid()) {
1097 const auto &Policy = Actions.getASTContext().getPrintingPolicy();
1100 CorrectLocationForAttributes =
1104 ProhibitAttributes(Attrs, CorrectLocationForAttributes);
1106 RecordDecl *AnonRecord =
nullptr;
1107 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
1110 Actions.ActOnDefinedDeclarationSpecifier(TheDecl);
1112 Decl* decls[] = {AnonRecord, TheDecl};
1113 return Actions.BuildDeclaratorGroup(decls);
1115 return Actions.ConvertDeclToDeclGroup(TheDecl);
1119 Actions.ActOnDefinedDeclarationSpecifier(DS.
getRepAsDecl());
1126 if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
1127 !Tok.isObjCAtKeyword(tok::objc_protocol) &&
1128 !Tok.isObjCAtKeyword(tok::objc_implementation)) {
1129 Diag(Tok, diag::err_objc_unexpected_attr);
1137 const char *PrevSpec =
nullptr;
1140 Actions.getASTContext().getPrintingPolicy()))
1141 Diag(AtLoc, DiagID) << PrevSpec;
1143 if (Tok.isObjCAtKeyword(tok::objc_protocol))
1144 return ParseObjCAtProtocolDeclaration(AtLoc, DS.
getAttributes());
1146 if (Tok.isObjCAtKeyword(tok::objc_implementation))
1147 return ParseObjCAtImplementationDeclaration(AtLoc, DS.
getAttributes());
1149 return Actions.ConvertDeclToDeclGroup(
1150 ParseObjCAtInterfaceDeclaration(AtLoc, DS.
getAttributes()));
1159 ProhibitAttributes(Attrs);
1161 return Actions.ConvertDeclToDeclGroup(TheDecl);
1168 ParsedAttributes &Attrs, ParsedAttributes &DeclSpecAttrs,
1172 llvm::TimeTraceScope TimeScope(
"ParseDeclarationOrFunctionDefinition", [&]() {
1173 return Tok.getLocation().printToString(
1174 Actions.getASTContext().getSourceManager());
1178 return ParseDeclOrFunctionDefInternal(Attrs, DeclSpecAttrs, *DS, AS);
1180 ParsingDeclSpec PDS(*
this);
1184 ObjCDeclContextSwitch ObjCDC(*
this);
1186 return ParseDeclOrFunctionDefInternal(Attrs, DeclSpecAttrs, PDS, AS);
1190Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
1191 const ParsedTemplateInfo &TemplateInfo,
1192 LateParsedAttrList *LateParsedAttrs) {
1193 llvm::TimeTraceScope TimeScope(
"ParseFunctionDefinition", [&]() {
1194 return Actions.GetNameForDeclarator(D).getName().getAsString();
1200 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1209 const char *PrevSpec;
1211 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1223 ParseKNRParamDeclarations(D);
1227 if (Tok.isNot(tok::l_brace) &&
1229 (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
1230 Tok.isNot(tok::equal)))) {
1231 Diag(Tok, diag::err_expected_fn_body);
1237 if (Tok.isNot(tok::l_brace))
1243 if (Tok.isNot(tok::equal)) {
1245 if (AL.isKnownToGCC() && !AL.isStandardAttributeSyntax())
1246 Diag(AL.getLoc(), diag::warn_attribute_on_function_definition) << AL;
1251 if (
getLangOpts().DelayedTemplateParsing && Tok.isNot(tok::equal) &&
1253 LateParsedAttrs->empty() && Actions.canDelayFunctionBody(D)) {
1261 Decl *DP = Actions.HandleDeclarator(ParentScope, D,
1266 if (SkipFunctionBodies && (!DP || Actions.canSkipFunctionBody(DP)) &&
1267 trySkippingFunctionBody()) {
1269 return Actions.ActOnSkippedFunctionBody(DP);
1273 LexTemplateFunctionForLateParsing(Toks);
1277 Actions.CheckForFunctionRedefinition(FnD);
1278 Actions.MarkAsLateParsedTemplate(FnD, DP, Toks);
1282 if (CurParsedObjCImpl && !TemplateInfo.TemplateParams &&
1283 (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) || Tok.is(tok::colon)) &&
1284 Actions.CurContext->isTranslationUnit()) {
1290 Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
1296 StashAwayMethodOrFunctionBodyTokens(FuncDecl);
1297 CurParsedObjCImpl->HasCFunction =
true;
1309 StringLiteral *DeletedMessage =
nullptr;
1311 SourceLocation KWLoc;
1316 DiagCompat(KWLoc, diag_compat::defaulted_deleted_function)
1319 DeletedMessage = ParseCXXDeletedFunctionMessage();
1322 DiagCompat(KWLoc, diag_compat::defaulted_deleted_function)
1327 llvm_unreachable(
"function definition after = not 'delete' or 'default'");
1330 if (Tok.is(tok::comma)) {
1331 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
1334 }
else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
1342 Sema::FPFeaturesStateRAII SaveFPFeatures(Actions);
1346 SkipBodyInfo SkipBody;
1348 TemplateInfo.TemplateParams
1349 ? *TemplateInfo.TemplateParams
1351 &SkipBody, BodyKind);
1368 Actions.PopExpressionEvaluationContext();
1380 Actions.SetFunctionBodyKind(Res, KWLoc, BodyKind, DeletedMessage);
1381 Stmt *GeneratedBody = Res ? Res->
getBody() :
nullptr;
1382 Actions.ActOnFinishFunctionBody(Res, GeneratedBody,
false);
1388 if (
const auto *
Template = dyn_cast_if_present<FunctionTemplateDecl>(Res);
1390 Template->getTemplateParameters()->getParam(0)->isImplicit())
1393 CurTemplateDepthTracker.addDepth(1);
1396 if (LateParsedAttrs)
1397 ParseLexedAttributeList(*LateParsedAttrs, Res,
false,
1400 if (SkipFunctionBodies && (!Res || Actions.canSkipFunctionBody(Res)) &&
1401 trySkippingFunctionBody()) {
1403 Actions.ActOnSkippedFunctionBody(Res);
1404 return Actions.ActOnFinishFunctionBody(Res,
nullptr,
false);
1407 return ParseFunctionBody(Res, BodyScope);
1411 if (Tok.is(tok::kw_try))
1412 return ParseFunctionTryBlock(D, BodyScope);
1416 if (Tok.is(tok::colon)) {
1417 ParseConstructorInitializer(D);
1420 if (!Tok.is(tok::l_brace)) {
1424 Actions.ActOnFinishFunctionBody(D,
nullptr);
1428 Actions.ActOnDefaultCtorInitializers(D);
1430 return ParseFunctionStatementBody(D, BodyScope);
1433void Parser::SkipFunctionBody() {
1434 if (Tok.is(tok::equal)) {
1439 bool IsFunctionTryBlock = Tok.is(tok::kw_try);
1440 if (IsFunctionTryBlock)
1444 if (ConsumeAndStoreFunctionPrologue(Skipped))
1448 while (IsFunctionTryBlock && Tok.is(tok::kw_catch)) {
1455void Parser::ParseKNRParamDeclarations(Declarator &D) {
1466 SourceLocation DSStart = Tok.getLocation();
1469 DeclSpec DS(AttrFactory);
1470 ParsedTemplateInfo TemplateInfo;
1471 ParseDeclarationSpecifiers(DS, TemplateInfo);
1479 Diag(DSStart, diag::err_declaration_does_not_declare_param);
1488 diag::err_invalid_storage_class_in_func_decl);
1493 diag::err_invalid_storage_class_in_func_decl);
1500 ParseDeclarator(ParmDeclarator);
1505 MaybeParseGNUAttributes(ParmDeclarator);
1509 Actions.ActOnParamDeclarator(
getCurScope(), ParmDeclarator);
1513 ParmDeclarator.getIdentifier()) {
1517 for (
unsigned i = 0; ; ++i) {
1521 Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
1522 << ParmDeclarator.getIdentifier();
1526 if (FTI.
Params[i].
Ident == ParmDeclarator.getIdentifier()) {
1529 Diag(ParmDeclarator.getIdentifierLoc(),
1530 diag::err_param_redefinition)
1531 << ParmDeclarator.getIdentifier();
1542 if (Tok.isNot(tok::comma))
1545 ParmDeclarator.clear();
1551 ParseDeclarator(ParmDeclarator);
1555 if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration))
1565 Actions.ActOnFinishKNRParamDeclarations(
getCurScope(), D, Tok.getLocation());
1568ExprResult Parser::ParseAsmStringLiteral(
bool ForAsmLabel) {
1571 if (isTokenStringLiteral()) {
1577 if (!SL->isOrdinary()) {
1578 Diag(Tok, diag::err_asm_operand_wide_string_literal)
1579 << SL->isWide() << SL->getSourceRange();
1583 Tok.is(tok::l_paren)) {
1585 SourceLocation RParenLoc;
1588 EnterExpressionEvaluationContext ConstantEvaluated(
1590 AsmString = ParseParenExpression(
1594 AsmString = Actions.ActOnConstantExpression(AsmString);
1599 Diag(Tok, diag::err_asm_expected_string) << (
1600 (
getLangOpts().CPlusPlus11 && !ForAsmLabel) ? 0 : 1);
1603 return Actions.ActOnGCCAsmStmtString(AsmString.
get(), ForAsmLabel);
1606ExprResult Parser::ParseSimpleAsm(
bool ForAsmLabel, SourceLocation *EndLoc) {
1607 assert(Tok.is(tok::kw_asm) &&
"Not an asm!");
1610 if (isGNUAsmQualifier(Tok)) {
1612 SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
1613 PP.getLocForEndOfToken(Tok.getLocation()));
1614 Diag(Tok, diag::err_global_asm_qualifier_ignored)
1615 << GNUAsmQualifiers::getQualifierName(getGNUAsmQualifier(Tok))
1621 if (
T.consumeOpen()) {
1622 Diag(Tok, diag::err_expected_lparen_after) <<
"asm";
1628 if (!
Result.isInvalid()) {
1632 *EndLoc =
T.getCloseLocation();
1635 *EndLoc = Tok.getLocation();
1642TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(
const Token &tok) {
1643 assert(tok.
is(tok::annot_template_id) &&
"Expected template-id token");
1644 TemplateIdAnnotation *
1649void Parser::AnnotateScopeToken(CXXScopeSpec &SS,
bool IsNewAnnotation) {
1652 if (PP.isBacktrackEnabled())
1653 PP.RevertCachedTokens(1);
1655 PP.EnterToken(Tok,
true);
1656 Tok.setKind(tok::annot_cxxscope);
1657 Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
1658 Tok.setAnnotationRange(SS.
getRange());
1663 if (IsNewAnnotation)
1664 PP.AnnotateCachedTokens(Tok);
1668Parser::TryAnnotateName(CorrectionCandidateCallback *CCC,
1670 assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
1672 const bool EnteringContext =
false;
1673 const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1677 ParseOptionalCXXScopeSpecifier(SS,
nullptr,
1682 if (Tok.isNot(tok::identifier) || SS.
isInvalid()) {
1684 AllowImplicitTypename))
1689 IdentifierInfo *Name = Tok.getIdentifierInfo();
1690 SourceLocation NameLoc = Tok.getLocation();
1694 if (isTentativelyDeclared(Name) && SS.
isEmpty()) {
1698 AllowImplicitTypename))
1710 Sema::NameClassification Classification = Actions.ClassifyName(
1718 isTemplateArgumentList(1) == TPResult::False) {
1720 Token FakeNext =
Next;
1721 FakeNext.
setKind(tok::unknown);
1723 Actions.ClassifyName(
getCurScope(), SS, Name, NameLoc, FakeNext,
1724 SS.
isEmpty() ? CCC :
nullptr);
1727 switch (Classification.
getKind()) {
1733 Tok.setIdentifierInfo(Name);
1735 PP.TypoCorrectToken(Tok);
1737 AnnotateScopeToken(SS, !WasScopeAnnotation);
1746 if (TryAltiVecVectorToken())
1751 SourceLocation BeginLoc = NameLoc;
1758 QualType
T = Actions.GetTypeFromParser(Ty);
1763 SourceLocation NewEndLoc;
1765 = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
1770 else if (Tok.is(tok::eof))
1774 Tok.setKind(tok::annot_typename);
1775 setTypeAnnotation(Tok, Ty);
1776 Tok.setAnnotationEndLoc(Tok.getLocation());
1777 Tok.setLocation(BeginLoc);
1778 PP.AnnotateCachedTokens(Tok);
1783 Tok.setKind(tok::annot_overload_set);
1785 Tok.setAnnotationEndLoc(NameLoc);
1788 PP.AnnotateCachedTokens(Tok);
1792 if (TryAltiVecVectorToken())
1797 Tok.setKind(tok::annot_non_type);
1799 Tok.setLocation(NameLoc);
1800 Tok.setAnnotationEndLoc(NameLoc);
1801 PP.AnnotateCachedTokens(Tok);
1803 AnnotateScopeToken(SS, !WasScopeAnnotation);
1808 Tok.setKind(Classification.
getKind() ==
1810 ? tok::annot_non_type_undeclared
1811 : tok::annot_non_type_dependent);
1812 setIdentifierAnnotation(Tok, Name);
1813 Tok.setLocation(NameLoc);
1814 Tok.setAnnotationEndLoc(NameLoc);
1815 PP.AnnotateCachedTokens(Tok);
1817 AnnotateScopeToken(SS, !WasScopeAnnotation);
1821 if (
Next.isNot(tok::less)) {
1825 AnnotateScopeToken(SS, !WasScopeAnnotation);
1833 bool IsConceptName =
1839 if (
Next.is(tok::less))
1841 if (AnnotateTemplateIdToken(
1848 AnnotateScopeToken(SS, !WasScopeAnnotation);
1855 AnnotateScopeToken(SS, !WasScopeAnnotation);
1860 SourceLocation TokenEndLoc = PP.getLocForEndOfToken(PrevTokLocation);
1861 return TokenEndLoc.
isValid() ? TokenEndLoc : Tok.getLocation();
1864bool Parser::TryKeywordIdentFallback(
bool DisableKeyword) {
1865 assert(
Tok.isNot(tok::identifier));
1871 Tok.setKind(tok::identifier);
1875 Diag(
Tok, diag::ext_keyword_as_ident)
1880 Tok.setKind(tok::identifier);
1886 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1887 Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope) ||
1888 Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id) ||
1889 Tok.is(tok::kw___super) || Tok.is(tok::kw_auto) ||
1890 Tok.is(tok::annot_pack_indexing_type)) &&
1891 "Cannot be a type or scope token!");
1893 if (Tok.is(tok::kw_typename)) {
1902 PP.Lex(TypedefToken);
1904 PP.EnterToken(Tok,
true);
1907 Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename);
1919 if (ParseOptionalCXXScopeSpecifier(SS,
nullptr,
1925 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) ||
1926 Tok.is(tok::annot_decltype)) {
1928 if (Tok.is(tok::annot_decltype) ||
1930 Tok.isAnnotation())) {
1931 unsigned DiagID = diag::err_expected_qualified_after_typename;
1935 DiagID = diag::warn_expected_qualified_after_typename;
1936 Diag(Tok.getLocation(), DiagID);
1940 if (Tok.isEditorPlaceholder())
1943 Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
1947 bool TemplateKWPresent =
false;
1948 if (Tok.is(tok::kw_template)) {
1950 TemplateKWPresent =
true;
1954 if (Tok.is(tok::identifier)) {
1956 Diag(Tok.getLocation(),
1957 diag::missing_template_arg_list_after_template_kw);
1960 Ty = Actions.ActOnTypenameType(
getCurScope(), TypenameLoc, SS,
1961 *Tok.getIdentifierInfo(),
1963 }
else if (Tok.is(tok::annot_template_id)) {
1966 Diag(Tok, diag::err_typename_refers_to_non_type_template)
1967 << Tok.getAnnotationRange();
1976 : Actions.ActOnTypenameType(
1980 TemplateArgsPtr, TemplateId->
RAngleLoc);
1982 Diag(Tok, diag::err_expected_type_name_after_typename)
1988 Tok.setKind(tok::annot_typename);
1989 setTypeAnnotation(Tok, Ty);
1990 Tok.setAnnotationEndLoc(EndLoc);
1991 Tok.setLocation(TypenameLoc);
1992 PP.AnnotateCachedTokens(Tok);
1997 bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
2001 if (ParseOptionalCXXScopeSpecifier(
2005 IsAddressOfOperand))
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();
2234void Parser::CodeCompleteModuleImport(SourceLocation ImportLoc,
2236 Actions.CodeCompletion().CodeCompleteModuleImport(ImportLoc, Path);
2239bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition&
Result) {
2240 assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
2241 "Expected '__if_exists' or '__if_not_exists'");
2242 Result.IsIfExists = Tok.is(tok::kw___if_exists);
2246 if (
T.consumeOpen()) {
2247 Diag(Tok, diag::err_expected_lparen_after)
2248 << (
Result.IsIfExists?
"__if_exists" :
"__if_not_exists");
2254 ParseOptionalCXXScopeSpecifier(
Result.SS,
nullptr,
2259 if (
Result.SS.isInvalid()) {
2265 SourceLocation TemplateKWLoc;
2270 false, &TemplateKWLoc,
2276 if (
T.consumeClose())
2304void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
2305 IfExistsCondition
Result;
2306 if (ParseMicrosoftIfExistsCondition(
Result))
2310 if (
Braces.consumeOpen()) {
2311 Diag(Tok, diag::err_expected) << tok::l_brace;
2315 switch (
Result.Behavior) {
2321 llvm_unreachable(
"Cannot have a dependent external declaration");
2330 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
2331 ParsedAttributes Attrs(AttrFactory);
2332 MaybeParseCXX11Attributes(Attrs);
2333 ParsedAttributes EmptyDeclSpecAttrs(AttrFactory);
2336 Actions.getASTConsumer().HandleTopLevelDecl(
Result.get());
2343 Token Introducer = Tok;
2344 SourceLocation StartLoc = Introducer.
getLocation();
2350 assert(Tok.is(tok::kw_module) &&
"not a module declaration");
2356 DiagnoseAndSkipCXX11Attributes();
2359 if (
getLangOpts().CPlusPlusModules && Tok.is(tok::semi)) {
2363 Diag(StartLoc, diag::err_global_module_introducer_not_at_start)
2364 << SourceRange(StartLoc, SemiLoc);
2368 Diag(StartLoc, diag::err_module_fragment_exported)
2372 return Actions.ActOnGlobalModuleFragmentDecl(ModuleLoc);
2376 if (
getLangOpts().CPlusPlusModules && Tok.is(tok::colon) &&
2379 Diag(StartLoc, diag::err_module_fragment_exported)
2384 DiagnoseAndSkipCXX11Attributes();
2385 ExpectAndConsumeSemi(diag::err_private_module_fragment_expected_semi);
2386 auto Result = Actions.ActOnPrivateModuleFragmentDecl(ModuleLoc, PrivateLoc);
2395 SmallVector<IdentifierLoc, 2> Path;
2396 if (ParseModuleName(ModuleLoc, Path,
false))
2400 SmallVector<IdentifierLoc, 2> Partition;
2401 if (Tok.is(tok::colon)) {
2404 Diag(ColonLoc, diag::err_unsupported_module_partition)
2405 << SourceRange(ColonLoc, Partition.back().getLoc());
2407 else if (ParseModuleName(ModuleLoc, Partition,
false))
2411 if (Tok.isNoneOf(tok::semi, tok::l_square, tok::eof)) {
2412 Diag(Tok, diag::err_unexpected_tok_after_module_name)
2413 << PP.getSpelling(Tok);
2418 ParsedAttributes Attrs(AttrFactory);
2419 MaybeParseCXX11Attributes(Attrs);
2420 ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_module_attr,
2421 diag::err_keyword_not_module_attr,
2425 if (ExpectAndConsumeSemi(diag::err_expected_semi_after_module_or_import,
2429 return Actions.ActOnModuleDecl(StartLoc, ModuleLoc, MDK, Path, Partition,
2434Decl *Parser::ParseModuleImport(SourceLocation AtLoc,
2436 SourceLocation StartLoc = AtLoc.
isInvalid() ? Tok.getLocation() : AtLoc;
2438 SourceLocation ExportLoc;
2441 assert((AtLoc.
isInvalid() ? Tok.is(tok::kw_import)
2442 : Tok.isObjCAtKeyword(tok::objc_import)) &&
2443 "Improper start to module import");
2444 bool IsObjCAtImport = Tok.isObjCAtKeyword(tok::objc_import);
2448 SmallVector<IdentifierLoc, 2> Path;
2449 bool IsPartition =
false;
2450 Module *HeaderUnit =
nullptr;
2451 if (Tok.is(tok::header_name)) {
2456 }
else if (Tok.is(tok::annot_header_unit)) {
2458 HeaderUnit =
reinterpret_cast<Module *
>(Tok.getAnnotationValue());
2459 ConsumeAnnotationToken();
2460 }
else if (Tok.is(tok::colon)) {
2463 Diag(ColonLoc, diag::err_unsupported_module_partition)
2464 << SourceRange(ColonLoc, Path.back().getLoc());
2466 else if (ParseModuleName(ColonLoc, Path,
true))
2471 if (ParseModuleName(ImportLoc, Path,
true))
2475 ParsedAttributes Attrs(AttrFactory);
2476 MaybeParseCXX11Attributes(Attrs);
2478 ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_import_attr,
2479 diag::err_keyword_not_import_attr,
2486 bool IsCXX20NamedModuleImport =
2487 getLangOpts().CPlusPlusModules && !IsObjCAtImport && !Path.empty();
2489 if (PP.hadModuleLoaderFatalFailure() && !IsCXX20NamedModuleImport) {
2496 bool SeenError =
true;
2497 switch (ImportState) {
2509 Diag(ImportLoc, diag::err_partition_import_outside_module);
2521 if (IsPartition || (HeaderUnit && HeaderUnit->
Kind !=
2523 Diag(ImportLoc, diag::err_import_in_wrong_fragment)
2532 Diag(ImportLoc, diag::err_import_not_allowed_here);
2548 bool LexedSemi =
false;
2551 !ExpectAndConsumeSemi(diag::err_expected_semi_after_module_or_import,
2554 LexedSemi = !ExpectAndConsumeSemi(diag::err_module_expected_semi);
2565 Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, HeaderUnit);
2566 else if (!Path.empty())
2567 Import = Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Path,
2574 if (IsObjCAtImport && AtLoc.
isValid()) {
2575 auto &SrcMgr = PP.getSourceManager();
2576 auto FE = SrcMgr.getFileEntryRefForID(SrcMgr.getFileID(AtLoc));
2577 if (FE && llvm::sys::path::parent_path(FE->getDir().getName())
2578 .ends_with(
".framework"))
2579 Diags.Report(AtLoc, diag::warn_atimport_in_framework_header);
2585bool Parser::ParseModuleName(SourceLocation UseLoc,
2586 SmallVectorImpl<IdentifierLoc> &Path,
2588 if (Tok.isNot(tok::annot_module_name)) {
2592 ModuleNameLoc *NameLoc =
2593 static_cast<ModuleNameLoc *
>(Tok.getAnnotationValue());
2596 ConsumeAnnotationToken();
2600bool Parser::parseMisplacedModuleImport() {
2602 switch (Tok.getKind()) {
2603 case tok::annot_module_end:
2607 if (MisplacedModuleBeginCount) {
2608 --MisplacedModuleBeginCount;
2609 Actions.ActOnAnnotModuleEnd(
2611 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
2612 ConsumeAnnotationToken();
2619 case tok::annot_module_begin:
2621 Actions.ActOnAnnotModuleBegin(
2623 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
2624 ConsumeAnnotationToken();
2625 ++MisplacedModuleBeginCount;
2627 case tok::annot_module_include:
2630 Actions.ActOnAnnotModuleInclude(
2632 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
2633 ConsumeAnnotationToken();
2643void Parser::diagnoseUseOfC11Keyword(
const Token &Tok) {
2648 : diag::ext_c11_feature)
2652bool BalancedDelimiterTracker::diagnoseOverflow() {
2653 P.Diag(P.Tok, diag::err_bracket_depth_exceeded)
2654 << P.getLangOpts().BracketDepth;
2655 P.Diag(P.Tok, diag::note_bracket_depth);
2663 LOpen = P.Tok.getLocation();
2664 if (P.ExpectAndConsume(Kind, DiagID, Msg)) {
2665 if (SkipToTok != tok::unknown)
2670 if (getDepth() < P.getLangOpts().BracketDepth)
2673 return diagnoseOverflow();
2676bool BalancedDelimiterTracker::diagnoseMissingClose() {
2677 assert(!P.Tok.is(Close) &&
"Should have consumed closing delimiter");
2679 if (P.Tok.is(tok::annot_module_end))
2680 P.Diag(P.Tok, diag::err_missing_before_module_end) << Close;
2682 P.Diag(P.Tok, diag::err_expected) << Close;
2683 P.Diag(LOpen, diag::note_matching) << Kind;
2687 if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) &&
2688 P.Tok.isNot(tok::r_square) &&
2689 P.SkipUntil(Close, FinalToken,
2692 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)
static Token createEof(SourceLocation Loc=SourceLocation(), const void *Data=nullptr)
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.