26#include "llvm/ADT/STLForwardCompat.h"
27#include "llvm/Support/Path.h"
28#include "llvm/Support/TimeProfiler.h"
39 explicit ActionCommentHandler(Sema &S) : S(S) { }
41 bool HandleComment(Preprocessor &PP, SourceRange Comment)
override {
42 S.ActOnComment(Comment);
51 Ident__except = PP.getIdentifierInfo(
"__except");
58 PreferredType(&actions.getASTContext(), pp.isCodeCompletionEnabled()),
59 Actions(actions), Diags(PP.getDiagnostics()), StackHandler(Diags),
60 GreaterThanIsOperator(
true), ColonIsSacred(
false),
61 InMessageExpression(
false), ParsingInObjCContainer(
false),
62 TemplateParameterDepth(0) {
65 Tok.setKind(tok::eof);
66 Actions.CurScope =
nullptr;
68 CurParsedObjCImpl =
nullptr;
72 initializePragmaHandlers();
74 CommentSemaHandler.reset(
new ActionCommentHandler(actions));
75 PP.addCommentHandler(CommentSemaHandler.get());
77 PP.setCodeCompletionHandler(*
this);
79 Actions.ParseTypeFromStringCallback =
80 [
this](StringRef TypeStr, StringRef Context,
SourceLocation IncludeLoc) {
81 return this->ParseTypeFromString(TypeStr, Context, IncludeLoc);
86 return Diags.Report(Loc, DiagID);
90 return Diag(Tok.getLocation(), DiagID);
94 unsigned CompatDiagId) {
100 return DiagCompat(Tok.getLocation(), CompatDiagId);
119 switch (ExpectedTok) {
121 return Tok.is(tok::colon) ||
Tok.is(tok::comma);
122 default:
return false;
126bool Parser::ExpectAndConsume(
tok::TokenKind ExpectedTok,
unsigned DiagID,
128 if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) {
135 SourceLocation Loc = Tok.getLocation();
137 DiagnosticBuilder DB =
Diag(Loc, DiagID);
140 if (DiagID == diag::err_expected)
142 else if (DiagID == diag::err_expected_after)
143 DB << Msg << ExpectedTok;
153 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
154 const char *Spelling =
nullptr;
158 DiagnosticBuilder DB =
162 if (DiagID == diag::err_expected)
164 else if (DiagID == diag::err_expected_after)
165 DB << Msg << ExpectedTok;
172bool Parser::ExpectAndConsumeSemi(
unsigned DiagID, StringRef TokenUsed) {
176 if (Tok.is(tok::code_completion)) {
177 handleUnexpectedCodeCompletionToken();
181 if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) &&
183 Diag(Tok, diag::err_extraneous_token_before_semi)
184 << PP.getSpelling(Tok)
191 return ExpectAndConsume(tok::semi, DiagID , TokenUsed);
195 if (!Tok.is(tok::semi))
return;
197 bool HadMultipleSemis =
false;
198 SourceLocation StartLoc = Tok.getLocation();
199 SourceLocation EndLoc = Tok.getLocation();
202 while ((Tok.is(tok::semi) && !Tok.isAtStartOfLine())) {
203 HadMultipleSemis =
true;
204 EndLoc = Tok.getLocation();
212 Diag(StartLoc, diag::warn_cxx98_compat_top_level_semi)
215 Diag(StartLoc, diag::ext_extra_semi_cxx11)
221 Diag(StartLoc, diag::ext_extra_semi)
224 TST, Actions.getASTContext().getPrintingPolicy())
228 Diag(StartLoc, diag::warn_extra_semi_after_mem_fn_def)
232bool Parser::expectIdentifier() {
233 if (Tok.is(tok::identifier))
235 if (
const auto *II = Tok.getIdentifierInfo()) {
237 Diag(Tok, diag::err_expected_token_instead_of_objcxx_keyword)
238 << tok::identifier << Tok.getIdentifierInfo();
243 Diag(Tok, diag::err_expected) << tok::identifier;
251 SourceLocation SecondTokLoc = Tok.getLocation();
256 PP.getSourceManager().getFileID(FirstTokLoc) !=
257 PP.getSourceManager().getFileID(SecondTokLoc)) {
258 Diag(FirstTokLoc, diag::warn_compound_token_split_by_macro)
259 << (FirstTokKind == Tok.getKind()) << FirstTokKind << Tok.getKind()
260 <<
static_cast<int>(Op) << SourceRange(FirstTokLoc);
261 Diag(SecondTokLoc, diag::note_compound_token_split_second_token_here)
262 << (FirstTokKind == Tok.getKind()) << Tok.getKind()
263 << SourceRange(SecondTokLoc);
268 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
269 SourceLocation SpaceLoc = PP.getLocForEndOfToken(FirstTokLoc);
271 SpaceLoc = FirstTokLoc;
272 Diag(SpaceLoc, diag::warn_compound_token_split_by_whitespace)
273 << (FirstTokKind == Tok.getKind()) << FirstTokKind << Tok.getKind()
274 <<
static_cast<int>(Op) << SourceRange(FirstTokLoc, SecondTokLoc);
284 return (
static_cast<unsigned>(L) &
static_cast<unsigned>(R)) != 0;
290 bool isFirstTokenSkipped =
true;
293 for (
unsigned i = 0, NumToks = Toks.size(); i != NumToks; ++i) {
294 if (Tok.is(Toks[i])) {
307 if (Toks.size() == 1 && Toks[0] == tok::eof &&
310 while (Tok.isNot(tok::eof))
315 switch (Tok.getKind()) {
320 case tok::annot_pragma_openmp:
321 case tok::annot_attr_openmp:
322 case tok::annot_pragma_openmp_end:
324 if (OpenMPDirectiveParsing)
326 ConsumeAnnotationToken();
328 case tok::annot_pragma_openacc:
329 case tok::annot_pragma_openacc_end:
331 if (OpenACCDirectiveParsing)
333 ConsumeAnnotationToken();
335 case tok::annot_module_begin:
336 case tok::annot_module_end:
337 case tok::annot_module_include:
338 case tok::annot_repl_input_end:
344 case tok::code_completion:
346 handleUnexpectedCodeCompletionToken();
388 if (ParenCount && !isFirstTokenSkipped)
393 if (BracketCount && !isFirstTokenSkipped)
398 if (BraceCount && !isFirstTokenSkipped)
412 isFirstTokenSkipped =
false;
421 if (NumCachedScopes) {
422 Scope *N = ScopeCache[--NumCachedScopes];
424 Actions.CurScope = N;
435 Actions.ActOnPopScope(Tok.getLocation(),
getCurScope());
438 Actions.CurScope = OldScope->
getParent();
440 if (NumCachedScopes == ScopeCacheSize)
443 ScopeCache[NumCachedScopes++] = OldScope;
446Parser::ParseScopeFlags::ParseScopeFlags(
Parser *
Self,
unsigned ScopeFlags,
448 : CurScope(ManageFlags ?
Self->getCurScope() :
nullptr) {
450 OldFlags = CurScope->getFlags();
451 CurScope->setFlags(ScopeFlags);
455Parser::ParseScopeFlags::~ParseScopeFlags() {
457 CurScope->setFlags(OldFlags);
468 Actions.CurScope =
nullptr;
471 for (
unsigned i = 0, e = NumCachedScopes; i != e; ++i)
472 delete ScopeCache[i];
474 resetPragmaHandlers();
476 PP.removeCommentHandler(CommentSemaHandler.get());
478 PP.clearCodeCompletionHandler();
480 DestroyTemplateIds();
485 assert(
getCurScope() ==
nullptr &&
"A scope is already active?");
493 &PP.getIdentifierTable().get(
"in");
495 &PP.getIdentifierTable().get(
"out");
497 &PP.getIdentifierTable().get(
"inout");
499 &PP.getIdentifierTable().get(
"oneway");
501 &PP.getIdentifierTable().get(
"bycopy");
503 &PP.getIdentifierTable().get(
"byref");
505 &PP.getIdentifierTable().get(
"nonnull");
507 &PP.getIdentifierTable().get(
"nullable");
509 &PP.getIdentifierTable().get(
"null_unspecified");
512 Ident_instancetype =
nullptr;
513 Ident_final =
nullptr;
514 Ident_sealed =
nullptr;
515 Ident_abstract =
nullptr;
516 Ident_override =
nullptr;
517 Ident_trivially_relocatable_if_eligible =
nullptr;
518 Ident_replaceable_if_eligible =
nullptr;
519 Ident_GNU_final =
nullptr;
520 Ident_import =
nullptr;
521 Ident_module =
nullptr;
523 Ident_super = &PP.getIdentifierTable().get(
"super");
525 Ident_vector =
nullptr;
526 Ident_bool =
nullptr;
527 Ident_Bool =
nullptr;
528 Ident_pixel =
nullptr;
530 Ident_vector = &PP.getIdentifierTable().get(
"vector");
531 Ident_bool = &PP.getIdentifierTable().get(
"bool");
532 Ident_Bool = &PP.getIdentifierTable().get(
"_Bool");
535 Ident_pixel = &PP.getIdentifierTable().get(
"pixel");
537 Ident_introduced =
nullptr;
538 Ident_deprecated =
nullptr;
539 Ident_obsoleted =
nullptr;
540 Ident_unavailable =
nullptr;
541 Ident_strict =
nullptr;
542 Ident_replacement =
nullptr;
544 Ident_language = Ident_defined_in = Ident_generated_declaration = Ident_USR =
547 Ident__except =
nullptr;
549 Ident__exception_code = Ident__exception_info =
nullptr;
550 Ident__abnormal_termination = Ident___exception_code =
nullptr;
551 Ident___exception_info = Ident___abnormal_termination =
nullptr;
552 Ident_GetExceptionCode = Ident_GetExceptionInfo =
nullptr;
553 Ident_AbnormalTermination =
nullptr;
556 Ident__exception_info = PP.getIdentifierInfo(
"_exception_info");
557 Ident___exception_info = PP.getIdentifierInfo(
"__exception_info");
558 Ident_GetExceptionInfo = PP.getIdentifierInfo(
"GetExceptionInformation");
559 Ident__exception_code = PP.getIdentifierInfo(
"_exception_code");
560 Ident___exception_code = PP.getIdentifierInfo(
"__exception_code");
561 Ident_GetExceptionCode = PP.getIdentifierInfo(
"GetExceptionCode");
562 Ident__abnormal_termination = PP.getIdentifierInfo(
"_abnormal_termination");
563 Ident___abnormal_termination = PP.getIdentifierInfo(
"__abnormal_termination");
564 Ident_AbnormalTermination = PP.getIdentifierInfo(
"AbnormalTermination");
566 PP.SetPoisonReason(Ident__exception_code,diag::err_seh___except_block);
567 PP.SetPoisonReason(Ident___exception_code,diag::err_seh___except_block);
568 PP.SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block);
569 PP.SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter);
570 PP.SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter);
571 PP.SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter);
572 PP.SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block);
573 PP.SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block);
574 PP.SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block);
578 Ident_import = PP.getIdentifierInfo(
"import");
579 Ident_module = PP.getIdentifierInfo(
"module");
582 Actions.Initialize();
588void Parser::DestroyTemplateIds() {
596 Actions.ActOnStartOfTranslationUnit();
608 if (NoTopLevelDecls && !Actions.getASTContext().getExternalSource() &&
610 Diag(diag::ext_empty_translation_unit);
612 return NoTopLevelDecls;
617 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*
this);
620 switch (Tok.getKind()) {
621 case tok::annot_pragma_unused:
622 HandlePragmaUnused();
636 case tok::identifier: {
638 if ((II == Ident_module || II == Ident_import) &&
640 if (II == Ident_module)
655 Result = ParseModuleDecl(ImportState);
665 case tok::annot_module_include: {
666 auto Loc = Tok.getLocation();
667 Module *Mod =
reinterpret_cast<Module *
>(Tok.getAnnotationValue());
671 Actions.ActOnAnnotModuleInclude(Loc, Mod);
678 ConsumeAnnotationToken();
682 case tok::annot_module_begin:
683 Actions.ActOnAnnotModuleBegin(
685 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
686 ConsumeAnnotationToken();
690 case tok::annot_module_end:
691 Actions.ActOnAnnotModuleEnd(
693 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
694 ConsumeAnnotationToken();
699 case tok::annot_repl_input_end:
701 if (PP.getMaxTokens() != 0 && PP.getTokenCount() > PP.getMaxTokens()) {
702 PP.Diag(Tok.getLocation(), diag::warn_max_tokens_total)
703 << PP.getTokenCount() << PP.getMaxTokens();
706 PP.Diag(OverrideLoc, diag::note_max_tokens_total_override);
711 Actions.SetLateTemplateParser(LateTemplateParserCallback,
this);
712 Actions.ActOnEndOfTranslationUnit();
716 case tok::identifier:
721 if ((Tok.getIdentifierInfo() == Ident_module ||
722 Tok.getIdentifierInfo() == Ident_import) &&
724 if (Tok.getIdentifierInfo() == Ident_module)
741 while (MaybeParseCXX11Attributes(DeclAttrs) ||
742 MaybeParseGNUAttributes(DeclSpecAttrs))
745 Result = ParseExternalDeclaration(DeclAttrs, DeclSpecAttrs);
755 else if (ImportState ==
767 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*
this);
775 Decl *SingleDecl =
nullptr;
776 switch (
Tok.getKind()) {
777 case tok::annot_pragma_vis:
778 HandlePragmaVisibility();
780 case tok::annot_pragma_pack:
783 case tok::annot_pragma_msstruct:
784 HandlePragmaMSStruct();
786 case tok::annot_pragma_align:
789 case tok::annot_pragma_weak:
792 case tok::annot_pragma_weakalias:
793 HandlePragmaWeakAlias();
795 case tok::annot_pragma_redefine_extname:
796 HandlePragmaRedefineExtname();
798 case tok::annot_pragma_fp_contract:
799 HandlePragmaFPContract();
801 case tok::annot_pragma_fenv_access:
802 case tok::annot_pragma_fenv_access_ms:
803 HandlePragmaFEnvAccess();
805 case tok::annot_pragma_fenv_round:
806 HandlePragmaFEnvRound();
808 case tok::annot_pragma_cx_limited_range:
809 HandlePragmaCXLimitedRange();
811 case tok::annot_pragma_float_control:
812 HandlePragmaFloatControl();
814 case tok::annot_pragma_fp:
817 case tok::annot_pragma_opencl_extension:
818 HandlePragmaOpenCLExtension();
820 case tok::annot_attr_openmp:
821 case tok::annot_pragma_openmp: {
823 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
825 case tok::annot_pragma_openacc: {
830 case tok::annot_pragma_ms_pointers_to_members:
831 HandlePragmaMSPointersToMembers();
833 case tok::annot_pragma_ms_vtordisp:
834 HandlePragmaMSVtorDisp();
836 case tok::annot_pragma_ms_pragma:
837 HandlePragmaMSPragma();
839 case tok::annot_pragma_dump:
842 case tok::annot_pragma_attribute:
843 HandlePragmaAttribute();
848 Actions.ActOnEmptyDeclaration(
getCurScope(), Attrs, Tok.getLocation());
852 Diag(Tok, diag::err_extraneous_closing_brace);
856 Diag(Tok, diag::err_expected_external_declaration);
858 case tok::kw___extension__: {
860 ExtensionRAIIObject O(Diags);
862 return ParseExternalDeclaration(Attrs, DeclSpecAttrs);
865 ProhibitAttributes(Attrs);
867 SourceLocation StartLoc = Tok.getLocation();
868 SourceLocation EndLoc;
877 if (!SL->getString().trim().empty())
878 Diag(StartLoc, diag::err_gnu_inline_asm_disabled);
881 ExpectAndConsume(tok::semi, diag::err_expected_after,
882 "top-level asm block");
886 SingleDecl = Actions.ActOnFileScopeAsmDecl(
Result.get(), StartLoc, EndLoc);
890 return ParseObjCAtDirectives(Attrs, DeclSpecAttrs);
894 Diag(Tok, diag::err_expected_external_declaration);
898 SingleDecl = ParseObjCMethodDefinition();
900 case tok::code_completion:
902 if (CurParsedObjCImpl) {
904 Actions.CodeCompletion().CodeCompleteObjCMethodDecl(
911 if (CurParsedObjCImpl) {
913 }
else if (PP.isIncrementalProcessingEnabled()) {
918 Actions.CodeCompletion().CodeCompleteOrdinaryName(
getCurScope(), PCC);
920 case tok::kw_import: {
923 llvm_unreachable(
"not expecting a c++20 import here");
924 ProhibitAttributes(Attrs);
926 SingleDecl = ParseModuleImport(SourceLocation(), IS);
930 ProhibitAttributes(Attrs);
931 SingleDecl = ParseExportDeclaration();
938 case tok::kw_namespace:
939 case tok::kw_typedef:
940 case tok::kw_template:
941 case tok::kw_static_assert:
942 case tok::kw__Static_assert:
945 SourceLocation DeclEnd;
950 case tok::kw_cbuffer:
951 case tok::kw_tbuffer:
953 SourceLocation DeclEnd;
965 SourceLocation DeclEnd;
976 if (NextKind == tok::kw_namespace) {
977 SourceLocation DeclEnd;
984 if (NextKind == tok::kw_template) {
987 SourceLocation DeclEnd;
996 ProhibitAttributes(Attrs);
997 ProhibitAttributes(DeclSpecAttrs);
1002 diag::warn_cxx98_compat_extern_template :
1003 diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc);
1004 SourceLocation DeclEnd;
1006 TemplateLoc, DeclEnd, Attrs);
1010 case tok::kw___if_exists:
1011 case tok::kw___if_not_exists:
1012 ParseMicrosoftIfExistsExternalDeclaration();
1015 case tok::kw_module:
1016 Diag(Tok, diag::err_unexpected_module_decl);
1022 if (Tok.isEditorPlaceholder()) {
1027 !isDeclarationStatement(
true))
1028 return ParseTopLevelStmtDecl();
1032 return ParseDeclarationOrFunctionDefinition(Attrs, DeclSpecAttrs, DS);
1037 return Actions.ConvertDeclToDeclGroup(SingleDecl);
1040bool Parser::isDeclarationAfterDeclarator() {
1044 if (KW.
is(tok::kw_default) || KW.
is(tok::kw_delete))
1048 return Tok.is(tok::equal) ||
1049 Tok.is(tok::comma) ||
1050 Tok.is(tok::semi) ||
1051 Tok.is(tok::kw_asm) ||
1052 Tok.is(tok::kw___attribute) ||
1054 Tok.is(tok::l_paren));
1057bool Parser::isStartOfFunctionDefinition(
const ParsingDeclarator &Declarator) {
1058 assert(
Declarator.isFunctionDeclarator() &&
"Isn't a function declarator");
1059 if (Tok.is(tok::l_brace))
1064 Declarator.getFunctionTypeInfo().isKNRPrototype())
1069 return KW.
is(tok::kw_default) || KW.
is(tok::kw_delete);
1072 return Tok.is(tok::colon) ||
1073 Tok.is(tok::kw_try);
1077 ParsedAttributes &Attrs, ParsedAttributes &DeclSpecAttrs,
1083 "expected uninitialised source range");
1088 ParsedTemplateInfo TemplateInfo;
1091 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
1092 DeclSpecContext::DSC_top_level);
1097 DS, AS, DeclSpecContext::DSC_top_level))
1102 if (Tok.is(tok::semi)) {
1105 SourceLocation CorrectLocationForAttributes{};
1109 if (
const auto *ED = dyn_cast_or_null<EnumDecl>(DS.
getRepAsDecl())) {
1110 CorrectLocationForAttributes =
1111 PP.getLocForEndOfToken(ED->getEnumKeyRange().getEnd());
1114 if (CorrectLocationForAttributes.
isInvalid()) {
1115 const auto &Policy = Actions.getASTContext().getPrintingPolicy();
1118 CorrectLocationForAttributes =
1122 ProhibitAttributes(Attrs, CorrectLocationForAttributes);
1124 RecordDecl *AnonRecord =
nullptr;
1125 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
1128 Actions.ActOnDefinedDeclarationSpecifier(TheDecl);
1130 Decl* decls[] = {AnonRecord, TheDecl};
1131 return Actions.BuildDeclaratorGroup(decls);
1133 return Actions.ConvertDeclToDeclGroup(TheDecl);
1137 Actions.ActOnDefinedDeclarationSpecifier(DS.
getRepAsDecl());
1144 if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
1145 !Tok.isObjCAtKeyword(tok::objc_protocol) &&
1146 !Tok.isObjCAtKeyword(tok::objc_implementation)) {
1147 Diag(Tok, diag::err_objc_unexpected_attr);
1155 const char *PrevSpec =
nullptr;
1158 Actions.getASTContext().getPrintingPolicy()))
1159 Diag(AtLoc, DiagID) << PrevSpec;
1161 if (Tok.isObjCAtKeyword(tok::objc_protocol))
1162 return ParseObjCAtProtocolDeclaration(AtLoc, DS.
getAttributes());
1164 if (Tok.isObjCAtKeyword(tok::objc_implementation))
1165 return ParseObjCAtImplementationDeclaration(AtLoc, DS.
getAttributes());
1167 return Actions.ConvertDeclToDeclGroup(
1168 ParseObjCAtInterfaceDeclaration(AtLoc, DS.
getAttributes()));
1177 ProhibitAttributes(Attrs);
1179 return Actions.ConvertDeclToDeclGroup(TheDecl);
1186 ParsedAttributes &Attrs, ParsedAttributes &DeclSpecAttrs,
1190 llvm::TimeTraceScope TimeScope(
"ParseDeclarationOrFunctionDefinition", [&]() {
1191 return Tok.getLocation().printToString(
1192 Actions.getASTContext().getSourceManager());
1196 return ParseDeclOrFunctionDefInternal(Attrs, DeclSpecAttrs, *DS, AS);
1198 ParsingDeclSpec PDS(*
this);
1202 ObjCDeclContextSwitch ObjCDC(*
this);
1204 return ParseDeclOrFunctionDefInternal(Attrs, DeclSpecAttrs, PDS, AS);
1208Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
1209 const ParsedTemplateInfo &TemplateInfo,
1210 LateParsedAttrList *LateParsedAttrs) {
1211 llvm::TimeTraceScope TimeScope(
"ParseFunctionDefinition", [&]() {
1212 return Actions.GetNameForDeclarator(D).getName().getAsString();
1218 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1226 const char *PrevSpec;
1228 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1240 ParseKNRParamDeclarations(D);
1244 if (Tok.isNot(tok::l_brace) &&
1246 (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
1247 Tok.isNot(tok::equal)))) {
1248 Diag(Tok, diag::err_expected_fn_body);
1254 if (Tok.isNot(tok::l_brace))
1260 if (Tok.isNot(tok::equal)) {
1262 if (AL.isKnownToGCC() && !AL.isStandardAttributeSyntax())
1263 Diag(AL.getLoc(), diag::warn_attribute_on_function_definition) << AL;
1268 if (
getLangOpts().DelayedTemplateParsing && Tok.isNot(tok::equal) &&
1270 LateParsedAttrs->empty() && Actions.canDelayFunctionBody(D)) {
1278 Decl *DP = Actions.HandleDeclarator(ParentScope, D,
1283 if (SkipFunctionBodies && (!DP || Actions.canSkipFunctionBody(DP)) &&
1284 trySkippingFunctionBody()) {
1286 return Actions.ActOnSkippedFunctionBody(DP);
1290 LexTemplateFunctionForLateParsing(Toks);
1294 Actions.CheckForFunctionRedefinition(FnD);
1295 Actions.MarkAsLateParsedTemplate(FnD, DP, Toks);
1299 if (CurParsedObjCImpl && !TemplateInfo.TemplateParams &&
1300 (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) || Tok.is(tok::colon)) &&
1301 Actions.CurContext->isTranslationUnit()) {
1307 Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
1313 StashAwayMethodOrFunctionBodyTokens(FuncDecl);
1314 CurParsedObjCImpl->HasCFunction =
true;
1326 StringLiteral *DeletedMessage =
nullptr;
1328 SourceLocation KWLoc;
1334 ? diag::warn_cxx98_compat_defaulted_deleted_function
1335 : diag::ext_defaulted_deleted_function)
1338 DeletedMessage = ParseCXXDeletedFunctionMessage();
1341 ? diag::warn_cxx98_compat_defaulted_deleted_function
1342 : diag::ext_defaulted_deleted_function)
1346 llvm_unreachable(
"function definition after = not 'delete' or 'default'");
1349 if (Tok.is(tok::comma)) {
1350 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
1353 }
else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
1361 Sema::FPFeaturesStateRAII SaveFPFeatures(Actions);
1365 SkipBodyInfo SkipBody;
1367 TemplateInfo.TemplateParams
1368 ? *TemplateInfo.TemplateParams
1370 &SkipBody, BodyKind);
1387 Actions.PopExpressionEvaluationContext();
1399 Actions.SetFunctionBodyKind(Res, KWLoc, BodyKind, DeletedMessage);
1400 Stmt *GeneratedBody = Res ? Res->
getBody() :
nullptr;
1401 Actions.ActOnFinishFunctionBody(Res, GeneratedBody,
false);
1407 if (
const auto *
Template = dyn_cast_if_present<FunctionTemplateDecl>(Res);
1409 Template->getTemplateParameters()->getParam(0)->isImplicit())
1412 CurTemplateDepthTracker.addDepth(1);
1415 if (LateParsedAttrs)
1416 ParseLexedAttributeList(*LateParsedAttrs, Res,
false,
1419 if (SkipFunctionBodies && (!Res || Actions.canSkipFunctionBody(Res)) &&
1420 trySkippingFunctionBody()) {
1422 Actions.ActOnSkippedFunctionBody(Res);
1423 return Actions.ActOnFinishFunctionBody(Res,
nullptr,
false);
1426 if (Tok.is(tok::kw_try))
1427 return ParseFunctionTryBlock(Res, BodyScope);
1431 if (Tok.is(tok::colon)) {
1432 ParseConstructorInitializer(Res);
1435 if (!Tok.is(tok::l_brace)) {
1437 Actions.ActOnFinishFunctionBody(Res,
nullptr);
1441 Actions.ActOnDefaultCtorInitializers(Res);
1443 return ParseFunctionStatementBody(Res, BodyScope);
1446void Parser::SkipFunctionBody() {
1447 if (Tok.is(tok::equal)) {
1452 bool IsFunctionTryBlock = Tok.is(tok::kw_try);
1453 if (IsFunctionTryBlock)
1457 if (ConsumeAndStoreFunctionPrologue(Skipped))
1461 while (IsFunctionTryBlock && Tok.is(tok::kw_catch)) {
1468void Parser::ParseKNRParamDeclarations(Declarator &D) {
1479 SourceLocation DSStart = Tok.getLocation();
1482 DeclSpec DS(AttrFactory);
1483 ParsedTemplateInfo TemplateInfo;
1484 ParseDeclarationSpecifiers(DS, TemplateInfo);
1492 Diag(DSStart, diag::err_declaration_does_not_declare_param);
1501 diag::err_invalid_storage_class_in_func_decl);
1506 diag::err_invalid_storage_class_in_func_decl);
1513 ParseDeclarator(ParmDeclarator);
1518 MaybeParseGNUAttributes(ParmDeclarator);
1522 Actions.ActOnParamDeclarator(
getCurScope(), ParmDeclarator);
1526 ParmDeclarator.getIdentifier()) {
1530 for (
unsigned i = 0; ; ++i) {
1534 Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
1535 << ParmDeclarator.getIdentifier();
1539 if (FTI.
Params[i].
Ident == ParmDeclarator.getIdentifier()) {
1542 Diag(ParmDeclarator.getIdentifierLoc(),
1543 diag::err_param_redefinition)
1544 << ParmDeclarator.getIdentifier();
1555 if (Tok.isNot(tok::comma))
1558 ParmDeclarator.clear();
1564 ParseDeclarator(ParmDeclarator);
1568 if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration))
1578 Actions.ActOnFinishKNRParamDeclarations(
getCurScope(), D, Tok.getLocation());
1581ExprResult Parser::ParseAsmStringLiteral(
bool ForAsmLabel) {
1584 if (isTokenStringLiteral()) {
1590 if (!SL->isOrdinary()) {
1591 Diag(Tok, diag::err_asm_operand_wide_string_literal)
1592 << SL->isWide() << SL->getSourceRange();
1596 Tok.is(tok::l_paren)) {
1598 SourceLocation RParenLoc;
1601 EnterExpressionEvaluationContext ConstantEvaluated(
1603 AsmString = ParseParenExpression(
1607 AsmString = Actions.ActOnConstantExpression(AsmString);
1612 Diag(Tok, diag::err_asm_expected_string) << (
1613 (
getLangOpts().CPlusPlus11 && !ForAsmLabel) ? 0 : 1);
1616 return Actions.ActOnGCCAsmStmtString(AsmString.
get(), ForAsmLabel);
1619ExprResult Parser::ParseSimpleAsm(
bool ForAsmLabel, SourceLocation *EndLoc) {
1620 assert(Tok.is(tok::kw_asm) &&
"Not an asm!");
1623 if (isGNUAsmQualifier(Tok)) {
1625 SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
1626 PP.getLocForEndOfToken(Tok.getLocation()));
1627 Diag(Tok, diag::err_global_asm_qualifier_ignored)
1628 << GNUAsmQualifiers::getQualifierName(getGNUAsmQualifier(Tok))
1634 if (
T.consumeOpen()) {
1635 Diag(Tok, diag::err_expected_lparen_after) <<
"asm";
1641 if (!
Result.isInvalid()) {
1645 *EndLoc =
T.getCloseLocation();
1648 *EndLoc = Tok.getLocation();
1655TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(
const Token &tok) {
1656 assert(tok.
is(tok::annot_template_id) &&
"Expected template-id token");
1657 TemplateIdAnnotation *
1662void Parser::AnnotateScopeToken(CXXScopeSpec &SS,
bool IsNewAnnotation) {
1665 if (PP.isBacktrackEnabled())
1666 PP.RevertCachedTokens(1);
1668 PP.EnterToken(Tok,
true);
1669 Tok.setKind(tok::annot_cxxscope);
1670 Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
1671 Tok.setAnnotationRange(SS.
getRange());
1676 if (IsNewAnnotation)
1677 PP.AnnotateCachedTokens(Tok);
1681Parser::TryAnnotateName(CorrectionCandidateCallback *CCC,
1683 assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
1685 const bool EnteringContext =
false;
1686 const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1690 ParseOptionalCXXScopeSpecifier(SS,
nullptr,
1695 if (Tok.isNot(tok::identifier) || SS.
isInvalid()) {
1697 AllowImplicitTypename))
1702 IdentifierInfo *Name = Tok.getIdentifierInfo();
1703 SourceLocation NameLoc = Tok.getLocation();
1707 if (isTentativelyDeclared(Name) && SS.
isEmpty()) {
1711 AllowImplicitTypename))
1723 Sema::NameClassification Classification = Actions.ClassifyName(
1731 isTemplateArgumentList(1) == TPResult::False) {
1733 Token FakeNext =
Next;
1734 FakeNext.
setKind(tok::unknown);
1736 Actions.ClassifyName(
getCurScope(), SS, Name, NameLoc, FakeNext,
1737 SS.
isEmpty() ? CCC :
nullptr);
1740 switch (Classification.
getKind()) {
1746 Tok.setIdentifierInfo(Name);
1748 PP.TypoCorrectToken(Tok);
1750 AnnotateScopeToken(SS, !WasScopeAnnotation);
1759 if (TryAltiVecVectorToken())
1764 SourceLocation BeginLoc = NameLoc;
1771 QualType
T = Actions.GetTypeFromParser(Ty);
1776 SourceLocation NewEndLoc;
1778 = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
1783 else if (Tok.is(tok::eof))
1787 Tok.setKind(tok::annot_typename);
1788 setTypeAnnotation(Tok, Ty);
1789 Tok.setAnnotationEndLoc(Tok.getLocation());
1790 Tok.setLocation(BeginLoc);
1791 PP.AnnotateCachedTokens(Tok);
1796 Tok.setKind(tok::annot_overload_set);
1798 Tok.setAnnotationEndLoc(NameLoc);
1801 PP.AnnotateCachedTokens(Tok);
1805 if (TryAltiVecVectorToken())
1810 Tok.setKind(tok::annot_non_type);
1812 Tok.setLocation(NameLoc);
1813 Tok.setAnnotationEndLoc(NameLoc);
1814 PP.AnnotateCachedTokens(Tok);
1816 AnnotateScopeToken(SS, !WasScopeAnnotation);
1821 Tok.setKind(Classification.
getKind() ==
1823 ? tok::annot_non_type_undeclared
1824 : tok::annot_non_type_dependent);
1825 setIdentifierAnnotation(Tok, Name);
1826 Tok.setLocation(NameLoc);
1827 Tok.setAnnotationEndLoc(NameLoc);
1828 PP.AnnotateCachedTokens(Tok);
1830 AnnotateScopeToken(SS, !WasScopeAnnotation);
1834 if (
Next.isNot(tok::less)) {
1838 AnnotateScopeToken(SS, !WasScopeAnnotation);
1846 bool IsConceptName =
1852 if (
Next.is(tok::less))
1854 if (AnnotateTemplateIdToken(
1861 AnnotateScopeToken(SS, !WasScopeAnnotation);
1868 AnnotateScopeToken(SS, !WasScopeAnnotation);
1873 SourceLocation TokenEndLoc = PP.getLocForEndOfToken(PrevTokLocation);
1874 return TokenEndLoc.
isValid() ? TokenEndLoc : Tok.getLocation();
1877bool Parser::TryKeywordIdentFallback(
bool DisableKeyword) {
1878 assert(
Tok.isNot(tok::identifier));
1879 Diag(
Tok, diag::ext_keyword_as_ident)
1883 Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
1884 Tok.setKind(tok::identifier);
1890 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1891 Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope) ||
1892 Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id) ||
1893 Tok.is(tok::kw___super) || Tok.is(tok::kw_auto) ||
1894 Tok.is(tok::annot_pack_indexing_type)) &&
1895 "Cannot be a type or scope token!");
1897 if (Tok.is(tok::kw_typename)) {
1906 PP.Lex(TypedefToken);
1908 PP.EnterToken(Tok,
true);
1911 Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename);
1923 if (ParseOptionalCXXScopeSpecifier(SS,
nullptr,
1929 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) ||
1930 Tok.is(tok::annot_decltype)) {
1932 if (Tok.is(tok::annot_decltype) ||
1934 Tok.isAnnotation())) {
1935 unsigned DiagID = diag::err_expected_qualified_after_typename;
1939 DiagID = diag::warn_expected_qualified_after_typename;
1940 Diag(Tok.getLocation(), DiagID);
1944 if (Tok.isEditorPlaceholder())
1947 Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
1951 bool TemplateKWPresent =
false;
1952 if (Tok.is(tok::kw_template)) {
1954 TemplateKWPresent =
true;
1958 if (Tok.is(tok::identifier)) {
1960 Diag(Tok.getLocation(),
1961 diag::missing_template_arg_list_after_template_kw);
1964 Ty = Actions.ActOnTypenameType(
getCurScope(), TypenameLoc, SS,
1965 *Tok.getIdentifierInfo(),
1967 }
else if (Tok.is(tok::annot_template_id)) {
1970 Diag(Tok, diag::err_typename_refers_to_non_type_template)
1971 << Tok.getAnnotationRange();
1980 : Actions.ActOnTypenameType(
1984 TemplateArgsPtr, TemplateId->
RAngleLoc);
1986 Diag(Tok, diag::err_expected_type_name_after_typename)
1992 Tok.setKind(tok::annot_typename);
1993 setTypeAnnotation(Tok, Ty);
1994 Tok.setAnnotationEndLoc(EndLoc);
1995 Tok.setLocation(TypenameLoc);
1996 PP.AnnotateCachedTokens(Tok);
2001 bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
2005 if (ParseOptionalCXXScopeSpecifier(SS,
nullptr,
2011 AllowImplicitTypename);
2017 if (Tok.is(tok::identifier)) {
2020 *Tok.getIdentifierInfo(), Tok.getLocation(),
getCurScope(), &SS,
2024 true, AllowImplicitTypename)) {
2029 QualType T = Actions.GetTypeFromParser(Ty);
2034 (
T->isObjCObjectType() ||
T->isObjCObjectPointerType())) {
2044 else if (Tok.is(tok::eof))
2050 Tok.setKind(tok::annot_typename);
2051 setTypeAnnotation(Tok, Ty);
2052 Tok.setAnnotationEndLoc(Tok.getLocation());
2053 Tok.setLocation(BeginLoc);
2057 PP.AnnotateCachedTokens(Tok);
2074 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
2075 bool MemberOfUnknownSpecialization;
2080 MemberOfUnknownSpecialization)) {
2084 isTemplateArgumentList(1) != TPResult::False) {
2104 if (Tok.is(tok::annot_template_id)) {
2111 AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
2118 Tok.is(tok::coloncolon)) {
2127 AnnotateScopeToken(SS, IsNewScope);
2133 "Call sites of this function should be guarded by checking for C++");
2137 if (ParseOptionalCXXScopeSpecifier(SS,
nullptr,
2144 AnnotateScopeToken(SS,
true);
2148bool Parser::isTokenEqualOrEqualTypo() {
2154 case tok::starequal:
2155 case tok::plusequal:
2156 case tok::minusequal:
2157 case tok::exclaimequal:
2158 case tok::slashequal:
2159 case tok::percentequal:
2160 case tok::lessequal:
2161 case tok::lesslessequal:
2162 case tok::greaterequal:
2163 case tok::greatergreaterequal:
2164 case tok::caretequal:
2165 case tok::pipeequal:
2166 case tok::equalequal:
2167 Diag(
Tok, diag::err_invalid_token_after_declarator_suggest_equal)
2176SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
2177 assert(Tok.is(tok::code_completion));
2178 PrevTokLocation = Tok.getLocation();
2181 if (S->isFunctionScope()) {
2183 Actions.CodeCompletion().CodeCompleteOrdinaryName(
2185 return PrevTokLocation;
2188 if (S->isClassScope()) {
2190 Actions.CodeCompletion().CodeCompleteOrdinaryName(
2192 return PrevTokLocation;
2197 Actions.CodeCompletion().CodeCompleteOrdinaryName(
2199 return PrevTokLocation;
2204void Parser::CodeCompleteDirective(
bool InConditional) {
2205 Actions.CodeCompletion().CodeCompletePreprocessorDirective(InConditional);
2209 Actions.CodeCompletion().CodeCompleteInPreprocessorConditionalExclusion(
2213void Parser::CodeCompleteMacroName(
bool IsDefinition) {
2214 Actions.CodeCompletion().CodeCompletePreprocessorMacroName(IsDefinition);
2218 Actions.CodeCompletion().CodeCompletePreprocessorExpression();
2221void Parser::CodeCompleteMacroArgument(IdentifierInfo *
Macro,
2222 MacroInfo *MacroInfo,
2223 unsigned ArgumentIndex) {
2224 Actions.CodeCompletion().CodeCompletePreprocessorMacroArgument(
2228void Parser::CodeCompleteIncludedFile(llvm::StringRef Dir,
bool IsAngled) {
2229 Actions.CodeCompletion().CodeCompleteIncludedFile(Dir, IsAngled);
2233 Actions.CodeCompletion().CodeCompleteNaturalLanguage();
2236bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition&
Result) {
2237 assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
2238 "Expected '__if_exists' or '__if_not_exists'");
2239 Result.IsIfExists = Tok.is(tok::kw___if_exists);
2243 if (
T.consumeOpen()) {
2244 Diag(Tok, diag::err_expected_lparen_after)
2245 << (
Result.IsIfExists?
"__if_exists" :
"__if_not_exists");
2251 ParseOptionalCXXScopeSpecifier(
Result.SS,
nullptr,
2256 if (
Result.SS.isInvalid()) {
2262 SourceLocation TemplateKWLoc;
2267 false, &TemplateKWLoc,
2273 if (
T.consumeClose())
2301void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
2302 IfExistsCondition
Result;
2303 if (ParseMicrosoftIfExistsCondition(
Result))
2307 if (
Braces.consumeOpen()) {
2308 Diag(Tok, diag::err_expected) << tok::l_brace;
2312 switch (
Result.Behavior) {
2318 llvm_unreachable(
"Cannot have a dependent external declaration");
2327 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
2328 ParsedAttributes Attrs(AttrFactory);
2329 MaybeParseCXX11Attributes(Attrs);
2330 ParsedAttributes EmptyDeclSpecAttrs(AttrFactory);
2333 Actions.getASTConsumer().HandleTopLevelDecl(
Result.get());
2340 Token Introducer = Tok;
2341 SourceLocation StartLoc = Introducer.
getLocation();
2348 (Tok.is(tok::kw_module) ||
2349 (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_module)) &&
2350 "not a module declaration");
2355 DiagnoseAndSkipCXX11Attributes();
2358 if (
getLangOpts().CPlusPlusModules && Tok.is(tok::semi)) {
2362 Diag(StartLoc, diag::err_global_module_introducer_not_at_start)
2363 << SourceRange(StartLoc, SemiLoc);
2367 Diag(StartLoc, diag::err_module_fragment_exported)
2371 return Actions.ActOnGlobalModuleFragmentDecl(ModuleLoc);
2375 if (
getLangOpts().CPlusPlusModules && Tok.is(tok::colon) &&
2378 Diag(StartLoc, diag::err_module_fragment_exported)
2383 DiagnoseAndSkipCXX11Attributes();
2384 ExpectAndConsumeSemi(diag::err_private_module_fragment_expected_semi);
2388 return Actions.ActOnPrivateModuleFragmentDecl(ModuleLoc, PrivateLoc);
2391 SmallVector<IdentifierLoc, 2> Path;
2392 if (ParseModuleName(ModuleLoc, Path,
false))
2396 SmallVector<IdentifierLoc, 2> Partition;
2397 if (Tok.is(tok::colon)) {
2400 Diag(ColonLoc, diag::err_unsupported_module_partition)
2401 << SourceRange(ColonLoc, Partition.back().getLoc());
2403 else if (ParseModuleName(ModuleLoc, Partition,
false))
2408 ParsedAttributes Attrs(AttrFactory);
2409 MaybeParseCXX11Attributes(Attrs);
2410 ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_module_attr,
2411 diag::err_keyword_not_module_attr,
2415 ExpectAndConsumeSemi(diag::err_module_expected_semi);
2417 return Actions.ActOnModuleDecl(StartLoc, ModuleLoc, MDK, Path, Partition,
2422Decl *Parser::ParseModuleImport(SourceLocation AtLoc,
2424 SourceLocation StartLoc = AtLoc.
isInvalid() ? Tok.getLocation() : AtLoc;
2426 SourceLocation ExportLoc;
2429 assert((AtLoc.
isInvalid() ? Tok.isOneOf(tok::kw_import, tok::identifier)
2430 : Tok.isObjCAtKeyword(tok::objc_import)) &&
2431 "Improper start to module import");
2432 bool IsObjCAtImport = Tok.isObjCAtKeyword(tok::objc_import);
2436 SmallVector<IdentifierLoc, 2> Path;
2437 bool IsPartition =
false;
2438 Module *HeaderUnit =
nullptr;
2439 if (Tok.is(tok::header_name)) {
2444 }
else if (Tok.is(tok::annot_header_unit)) {
2446 HeaderUnit =
reinterpret_cast<Module *
>(Tok.getAnnotationValue());
2447 ConsumeAnnotationToken();
2448 }
else if (Tok.is(tok::colon)) {
2451 Diag(ColonLoc, diag::err_unsupported_module_partition)
2452 << SourceRange(ColonLoc, Path.back().getLoc());
2454 else if (ParseModuleName(ColonLoc, Path,
true))
2459 if (ParseModuleName(ImportLoc, Path,
true))
2463 ParsedAttributes Attrs(AttrFactory);
2464 MaybeParseCXX11Attributes(Attrs);
2466 ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_import_attr,
2467 diag::err_keyword_not_import_attr,
2471 if (PP.hadModuleLoaderFatalFailure()) {
2478 bool SeenError =
true;
2479 switch (ImportState) {
2491 Diag(ImportLoc, diag::err_partition_import_outside_module);
2503 if (IsPartition || (HeaderUnit && HeaderUnit->
Kind !=
2505 Diag(ImportLoc, diag::err_import_in_wrong_fragment)
2514 Diag(ImportLoc, diag::err_import_not_allowed_here);
2519 ExpectAndConsumeSemi(diag::err_module_expected_semi);
2528 Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, HeaderUnit);
2529 else if (!Path.empty())
2530 Import = Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Path,
2537 if (IsObjCAtImport && AtLoc.
isValid()) {
2538 auto &SrcMgr = PP.getSourceManager();
2539 auto FE = SrcMgr.getFileEntryRefForID(SrcMgr.getFileID(AtLoc));
2540 if (FE && llvm::sys::path::parent_path(FE->getDir().getName())
2541 .ends_with(
".framework"))
2542 Diags.Report(AtLoc, diag::warn_atimport_in_framework_header);
2548bool Parser::ParseModuleName(SourceLocation UseLoc,
2549 SmallVectorImpl<IdentifierLoc> &Path,
2553 if (!Tok.is(tok::identifier)) {
2554 if (Tok.is(tok::code_completion)) {
2556 Actions.CodeCompletion().CodeCompleteModuleImport(UseLoc, Path);
2560 Diag(Tok, diag::err_module_expected_ident) << IsImport;
2566 Path.emplace_back(Tok.getLocation(), Tok.getIdentifierInfo());
2569 if (Tok.isNot(tok::period))
2576bool Parser::parseMisplacedModuleImport() {
2578 switch (Tok.getKind()) {
2579 case tok::annot_module_end:
2583 if (MisplacedModuleBeginCount) {
2584 --MisplacedModuleBeginCount;
2585 Actions.ActOnAnnotModuleEnd(
2587 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
2588 ConsumeAnnotationToken();
2595 case tok::annot_module_begin:
2597 Actions.ActOnAnnotModuleBegin(
2599 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
2600 ConsumeAnnotationToken();
2601 ++MisplacedModuleBeginCount;
2603 case tok::annot_module_include:
2606 Actions.ActOnAnnotModuleInclude(
2608 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
2609 ConsumeAnnotationToken();
2619void Parser::diagnoseUseOfC11Keyword(
const Token &Tok) {
2624 : diag::ext_c11_feature)
2628bool BalancedDelimiterTracker::diagnoseOverflow() {
2629 P.Diag(P.Tok, diag::err_bracket_depth_exceeded)
2630 << P.getLangOpts().BracketDepth;
2631 P.Diag(P.Tok, diag::note_bracket_depth);
2639 LOpen = P.Tok.getLocation();
2640 if (P.ExpectAndConsume(Kind, DiagID, Msg)) {
2641 if (SkipToTok != tok::unknown)
2646 if (getDepth() < P.getLangOpts().BracketDepth)
2649 return diagnoseOverflow();
2652bool BalancedDelimiterTracker::diagnoseMissingClose() {
2653 assert(!P.Tok.is(Close) &&
"Should have consumed closing delimiter");
2655 if (P.Tok.is(tok::annot_module_end))
2656 P.Diag(P.Tok, diag::err_missing_before_module_end) << Close;
2658 P.Diag(P.Tok, diag::err_expected) << Close;
2659 P.Diag(LOpen, diag::note_matching) << Kind;
2663 if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) &&
2664 P.Tok.isNot(tok::r_square) &&
2665 P.SkipUntil(Close, FinalToken,
2668 LClose = P.ConsumeAnyToken();
Defines the clang::ASTContext interface.
This file provides some common utility functions for processing Lambda related AST Constructs.
static Decl::Kind getKind(const Decl *D)
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
static bool IsCommonTypo(tok::TokenKind ExpectedTok, const Token &Tok)
static bool HasFlagsSet(Parser::SkipUntilFlags L, Parser::SkipUntilFlags R)
This file declares facilities that support code completion.
Defines a utilitiy for warning once when close to out of stack space.
bool expectAndConsume(unsigned DiagID=diag::err_expected, const char *Msg="", tok::TokenKind SkipToTok=tok::unknown)
Represents a C++ nested-name-specifier or a global scope specifier.
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
SourceRange getRange() const
SourceLocation getBeginLoc() const
bool isInvalid() const
An error occurred during parsing of the scope specifier.
bool isEmpty() const
No scope specifier.
virtual void CodeCompletePreprocessorExpression()
Callback invoked when performing code completion in a preprocessor expression, such as the condition ...
virtual void CodeCompleteNaturalLanguage()
Callback invoked when performing code completion in a part of the file where we expect natural langua...
virtual void CodeCompleteInConditionalExclusion()
Callback invoked when performing code completion within a block of code that was excluded due to prep...
void ClearStorageClassSpecs()
TST getTypeSpecType() const
SourceLocation getStorageClassSpecLoc() const
SCS getStorageClassSpec() const
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
SourceRange getSourceRange() const LLVM_READONLY
void SetRangeEnd(SourceLocation Loc)
void SetRangeStart(SourceLocation Loc)
TSCS getThreadStorageClassSpec() const
ParsedAttributes & getAttributes()
static const TST TST_enum
static bool isDeclRep(TST T)
void takeAttributesAppendingingFrom(ParsedAttributes &attrs)
bool hasTagDefinition() const
unsigned getParsedSpecifiers() const
Return a bitmask of which flavors of specifiers this DeclSpec includes.
static const TSCS TSCS_unspecified
static const char * getSpecifierName(DeclSpec::TST T, const PrintingPolicy &Policy)
Turn a type-specifier-type into a string like "_Bool" or "union".
SourceLocation getThreadStorageClassSpecLoc() const
Decl * getRepAsDecl() const
static const TST TST_unspecified
bool isEmpty() const
isEmpty - Return true if this declaration specifier is completely empty: no tokens were parsed in the...
SourceLocation getTypeSpecTypeLoc() const
@ PQ_StorageClassSpecifier
Decl - This represents one declaration (or definition), e.g.
virtual Stmt * getBody() const
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
void SetRangeBegin(SourceLocation Loc)
SetRangeBegin - Set the start of the source range to Loc, unless it's invalid.
const ParsedAttributes & getAttributes() const
SourceLocation getIdentifierLoc() const
void setFunctionDefinitionKind(FunctionDefinitionKind Val)
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
A little helper class used to produce diagnostics.
static unsigned getCXXCompatDiagId(const LangOptions &LangOpts, unsigned CompatDiagId)
Get the appropriate diagnostic Id to use for issuing a compatibility diagnostic.
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
One of these records is kept for each identifier that is lexed.
tok::TokenKind getTokenID() const
If this is a source-language token (e.g.
A simple pair of identifier info and location.
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Describes a module or submodule.
ModuleKind Kind
The kind of this module.
bool isHeaderUnit() const
Is this module a header unit.
@ ModuleHeaderUnit
This is a C++20 header unit.
static OpaquePtr make(TemplateName P)
RAII object that makes sure paren/bracket/brace count is correct after declaration/statement parsing,...
static const ParsedAttributesView & none()
ParsedAttributes - A collection of parsed attributes.
ParseScope - Introduces a new scope for parsing.
Parser - This implements a parser for the C family of languages.
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
SourceLocation getEndOfPreviousToken() const
bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS, bool IsNewScope, ImplicitTypenameContext AllowImplicitTypename)
Try to annotate a type or scope token, having already parsed an optional scope specifier.
DiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId)
ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral=false)
ParseStringLiteralExpression - This handles the various token types that form string literals,...
SourceLocation ConsumeToken()
ConsumeToken - Consume the current 'peek token' and lex the next one.
Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies)
void EnterScope(unsigned ScopeFlags)
EnterScope - Start a new scope.
bool ParseUnqualifiedId(CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors, bool EnteringContext, bool AllowDestructorName, bool AllowConstructorName, bool AllowDeductionGuide, SourceLocation *TemplateKWLoc, UnqualifiedId &Result)
Parse a C++ unqualified-id (or a C identifier), which describes the name of an entity.
DeclGroupPtrTy ParseOpenACCDirectiveDecl(AccessSpecifier &AS, ParsedAttributes &Attrs, DeclSpec::TST TagType, Decl *TagDecl)
Parse OpenACC directive on a declaration.
SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok=false)
ConsumeAnyToken - Dispatch to the right Consume* method based on the current token type.
const Token & GetLookAheadToken(unsigned N)
GetLookAheadToken - This peeks ahead N tokens and returns that token without consuming any tokens.
bool TryConsumeToken(tok::TokenKind Expected)
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Scope * getCurScope() const
OpaquePtr< TemplateName > TemplateTy
bool SkipUntil(tok::TokenKind T, SkipUntilFlags Flags=static_cast< SkipUntilFlags >(0))
SkipUntil - Read tokens until we get to the specified token, then consume it (unless StopBeforeMatch ...
void SkipMalformedDecl()
SkipMalformedDecl - Read tokens until we get to some likely good stopping point for skipping past a s...
friend class PoisonSEHIdentifiersRAIIObject
void ExitScope()
ExitScope - Pop a scope off the scope stack.
const LangOptions & getLangOpts() const
bool ParseFirstTopLevelDecl(DeclGroupPtrTy &Result, Sema::ModuleImportState &ImportState)
Parse the first top-level declaration in a translation unit.
SkipUntilFlags
Control flags for SkipUntil functions.
@ StopBeforeMatch
Stop skipping at specified token, but don't skip the token itself.
@ StopAtCodeCompletion
Stop at code completion.
@ StopAtSemi
Stop skipping at semicolon.
bool TryAnnotateTypeOrScopeToken(ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No)
TryAnnotateTypeOrScopeToken - If the current token position is on a typename (possibly qualified in C...
bool MightBeCXXScopeToken()
const Token & NextToken()
NextToken - This peeks ahead one token and returns it without consuming it.
friend class BalancedDelimiterTracker
SmallVector< TemplateParameterList *, 4 > TemplateParameterLists
void Initialize()
Initialize - Warm up the parser.
bool TryAnnotateCXXScopeToken(bool EnteringContext=false)
TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only annotates C++ scope specifiers and ...
A class for parsing a DeclSpec.
const ParsingDeclSpec & getDeclSpec() const
ParsingDeclSpec & getMutableDeclSpec() const
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
StringRef getSpelling(SourceLocation loc, SmallVectorImpl< char > &buffer, bool *invalid=nullptr) const
Return the 'spelling' of the token at the given location; does not go up to the spelling location or ...
bool isCodeCompletionEnabled() const
Determine if we are performing code completion.
bool isCodeCompletionReached() const
Returns true if code-completion is enabled and we have hit the code-completion point.
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Computes the source location just past the end of the token at this source location.
A (possibly-)qualified type.
Scope - A scope is a transient data structure that is used while parsing the program.
void Init(Scope *parent, unsigned flags)
Init - This is used by the parser to implement scope caching.
const Scope * getParent() const
getParent - Return the scope that this is nested in.
@ FunctionPrototypeScope
This is a scope that corresponds to the parameters within a function prototype.
@ CompoundStmtScope
This is a compound statement scope.
@ FunctionDeclarationScope
This is a scope that corresponds to the parameters within a function prototype for a function declara...
@ FnScope
This indicates that the scope corresponds to a function, which means that labels are set here.
@ DeclScope
This is a scope that can contain a declaration.
ParserCompletionContext
Describes the context in which code completion occurs.
@ PCC_TopLevelOrExpression
Code completion occurs at top-level in a REPL session.
@ PCC_Class
Code completion occurs within a class, struct, or union.
@ PCC_ObjCImplementation
Code completion occurs within an Objective-C implementation or category implementation.
@ PCC_Namespace
Code completion occurs at top-level or namespace context.
@ PCC_RecoveryInFunction
Code completion occurs within the body of a function on a recovery path, where we do not have a speci...
ExprResult getExpression() const
NameClassificationKind getKind() const
NamedDecl * getNonTypeDecl() const
TemplateName getTemplateName() const
ParsedType getType() const
TemplateNameKind getTemplateNameKind() const
Sema - This implements semantic analysis and AST building for C.
@ Interface
'export module X;'
@ Implementation
'module X;'
@ Other
C++26 [dcl.fct.def.general]p1 function-body: ctor-initializer[opt] compound-statement function-try-bl...
@ Delete
deleted-function-body
ModuleImportState
An enumeration to represent the transition of states in parsing module fragments and imports.
@ PrivateFragmentImportFinished
after 'module :private;' but a non-import decl has already been seen.
@ ImportFinished
after any non-import decl.
@ PrivateFragmentImportAllowed
after 'module :private;' but before any non-import decl.
@ FirstDecl
Parsing the first decl in a TU.
@ GlobalFragment
after 'module;' but before 'module X;'
@ NotACXX20Module
Not a C++20 TU, or an invalid state was found.
@ ImportAllowed
after 'module X;' but before any non-import decl.
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Represents a C++ template name within the type system.
Token - This structure provides full information about a lexed token.
IdentifierInfo * getIdentifierInfo() const
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
void setKind(tok::TokenKind K)
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
void * getAnnotationValue() const
tok::TokenKind getKind() const
bool hasSeenNoTrivialPPDirective() const
bool isObjCObjectType() const
bool isObjCObjectPointerType() const
Represents a C++ unqualified-id that has been parsed.
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
const char * getPunctuatorSpelling(TokenKind Kind) LLVM_READNONE
Determines the spelling of simple punctuation tokens like '!
The JSON file list parser is used to communicate input to InstallAPI.
TypeSpecifierType
Specifies the kind of type.
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
@ Unresolved
The identifier can't be resolved.
@ Success
Annotation was successful.
@ Error
Annotation has failed and emitted an error.
@ TentativeDecl
The identifier is a tentatively-declared name.
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
ActionResult< Decl * > DeclResult
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ Dependent
Parse the block as a dependent block, which may be used in some template instantiations but not other...
@ Skip
Skip the block entirely; this code is never used.
@ Parse
Parse the block; this code is always used.
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
bool isLambdaCallOperator(const CXXMethodDecl *MD)
@ Result
The result type of a method or function.
ActionResult< ParsedType > TypeResult
const FunctionProtoType * T
@ Template
We are parsing a template declaration.
@ FunctionTemplate
The name was classified as a function template name.
@ Keyword
The name has been typo-corrected to a keyword.
@ DependentNonType
The name denotes a member of a dependent type that could not be resolved.
@ UndeclaredTemplate
The name was classified as an ADL-only function template name.
@ NonType
The name was classified as a specific non-type, non-template declaration.
@ Unknown
This name is not a type or template in this context, but might be something else.
@ Error
Classification failed; an error has been produced.
@ Type
The name was classified as a type.
@ TypeTemplate
The name was classified as a template whose specializations are types.
@ Concept
The name was classified as a concept name.
@ OverloadSet
The name was classified as an overload set, and an expression representing that overload set has been...
@ UndeclaredNonType
The name was classified as an ADL-only function name.
@ VarTemplate
The name was classified as a variable template name.
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
ExtraSemiKind
The kind of extra semi diagnostic to emit.
@ AfterMemberFunctionDefinition
TemplateNameKind
Specifies the kind of template name that an identifier refers to.
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
@ TNK_Undeclared_template
Lookup for the name failed, but we're assuming it was a template name anyway.
@ Dependent
The name is a dependent name, so the results will differ from one instantiation to the next.
@ Exists
The symbol exists.
@ Error
An error occurred.
@ DoesNotExist
The symbol does not exist.
U cast(CodeGen::Address addr)
SmallVector< Token, 4 > CachedTokens
A set of tokens that has been cached for later parsing.
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
ParenParseOption
ParenParseOption - Control what ParseParenExpression will parse.
ActionResult< Expr * > ExprResult
@ Braces
New-expression has a C++11 list-initializer.
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
bool isKNRPrototype() const
isKNRPrototype - Return true if this is a K&R style identifier list, like "void foo(a,...
const IdentifierInfo * Ident
Information about a template-id annotation token.
const IdentifierInfo * Name
FIXME: Temporarily stores the name of a specialization.
TemplateNameKind Kind
The kind of template that Template refers to.
unsigned NumArgs
NumArgs - The number of template arguments.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
SourceLocation TemplateKWLoc
TemplateKWLoc - The location of the template keyword.
bool mightBeType() const
Determine whether this might be a type template.
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.