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_GNU_final =
nullptr;
519 Ident_import =
nullptr;
520 Ident_module =
nullptr;
522 Ident_super = &PP.getIdentifierTable().get(
"super");
524 Ident_vector =
nullptr;
525 Ident_bool =
nullptr;
526 Ident_Bool =
nullptr;
527 Ident_pixel =
nullptr;
529 Ident_vector = &PP.getIdentifierTable().get(
"vector");
530 Ident_bool = &PP.getIdentifierTable().get(
"bool");
531 Ident_Bool = &PP.getIdentifierTable().get(
"_Bool");
534 Ident_pixel = &PP.getIdentifierTable().get(
"pixel");
536 Ident_introduced =
nullptr;
537 Ident_deprecated =
nullptr;
538 Ident_obsoleted =
nullptr;
539 Ident_unavailable =
nullptr;
540 Ident_strict =
nullptr;
541 Ident_replacement =
nullptr;
543 Ident_language = Ident_defined_in = Ident_generated_declaration = Ident_USR =
546 Ident__except =
nullptr;
548 Ident__exception_code = Ident__exception_info =
nullptr;
549 Ident__abnormal_termination = Ident___exception_code =
nullptr;
550 Ident___exception_info = Ident___abnormal_termination =
nullptr;
551 Ident_GetExceptionCode = Ident_GetExceptionInfo =
nullptr;
552 Ident_AbnormalTermination =
nullptr;
555 Ident__exception_info = PP.getIdentifierInfo(
"_exception_info");
556 Ident___exception_info = PP.getIdentifierInfo(
"__exception_info");
557 Ident_GetExceptionInfo = PP.getIdentifierInfo(
"GetExceptionInformation");
558 Ident__exception_code = PP.getIdentifierInfo(
"_exception_code");
559 Ident___exception_code = PP.getIdentifierInfo(
"__exception_code");
560 Ident_GetExceptionCode = PP.getIdentifierInfo(
"GetExceptionCode");
561 Ident__abnormal_termination = PP.getIdentifierInfo(
"_abnormal_termination");
562 Ident___abnormal_termination = PP.getIdentifierInfo(
"__abnormal_termination");
563 Ident_AbnormalTermination = PP.getIdentifierInfo(
"AbnormalTermination");
565 PP.SetPoisonReason(Ident__exception_code,diag::err_seh___except_block);
566 PP.SetPoisonReason(Ident___exception_code,diag::err_seh___except_block);
567 PP.SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block);
568 PP.SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter);
569 PP.SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter);
570 PP.SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter);
571 PP.SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block);
572 PP.SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block);
573 PP.SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block);
577 Ident_import = PP.getIdentifierInfo(
"import");
578 Ident_module = PP.getIdentifierInfo(
"module");
581 Actions.Initialize();
587void Parser::DestroyTemplateIds() {
595 Actions.ActOnStartOfTranslationUnit();
607 if (NoTopLevelDecls && !Actions.getASTContext().getExternalSource() &&
609 Diag(diag::ext_empty_translation_unit);
611 return NoTopLevelDecls;
616 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*
this);
619 switch (Tok.getKind()) {
620 case tok::annot_pragma_unused:
621 HandlePragmaUnused();
635 case tok::identifier: {
637 if ((II == Ident_module || II == Ident_import) &&
639 if (II == Ident_module)
654 Result = ParseModuleDecl(ImportState);
664 case tok::annot_module_include: {
665 auto Loc = Tok.getLocation();
666 Module *Mod =
reinterpret_cast<Module *
>(Tok.getAnnotationValue());
670 Actions.ActOnAnnotModuleInclude(Loc, Mod);
677 ConsumeAnnotationToken();
681 case tok::annot_module_begin:
682 Actions.ActOnAnnotModuleBegin(
684 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
685 ConsumeAnnotationToken();
689 case tok::annot_module_end:
690 Actions.ActOnAnnotModuleEnd(
692 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
693 ConsumeAnnotationToken();
698 case tok::annot_repl_input_end:
700 if (PP.getMaxTokens() != 0 && PP.getTokenCount() > PP.getMaxTokens()) {
701 PP.Diag(Tok.getLocation(), diag::warn_max_tokens_total)
702 << PP.getTokenCount() << PP.getMaxTokens();
705 PP.Diag(OverrideLoc, diag::note_max_tokens_total_override);
710 Actions.SetLateTemplateParser(LateTemplateParserCallback,
this);
711 Actions.ActOnEndOfTranslationUnit();
715 case tok::identifier:
720 if ((Tok.getIdentifierInfo() == Ident_module ||
721 Tok.getIdentifierInfo() == Ident_import) &&
723 if (Tok.getIdentifierInfo() == Ident_module)
740 while (MaybeParseCXX11Attributes(DeclAttrs) ||
741 MaybeParseGNUAttributes(DeclSpecAttrs))
744 Result = ParseExternalDeclaration(DeclAttrs, DeclSpecAttrs);
754 else if (ImportState ==
766 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*
this);
774 Decl *SingleDecl =
nullptr;
775 switch (
Tok.getKind()) {
776 case tok::annot_pragma_vis:
777 HandlePragmaVisibility();
779 case tok::annot_pragma_pack:
782 case tok::annot_pragma_msstruct:
783 HandlePragmaMSStruct();
785 case tok::annot_pragma_align:
788 case tok::annot_pragma_weak:
791 case tok::annot_pragma_weakalias:
792 HandlePragmaWeakAlias();
794 case tok::annot_pragma_redefine_extname:
795 HandlePragmaRedefineExtname();
797 case tok::annot_pragma_fp_contract:
798 HandlePragmaFPContract();
800 case tok::annot_pragma_fenv_access:
801 case tok::annot_pragma_fenv_access_ms:
802 HandlePragmaFEnvAccess();
804 case tok::annot_pragma_fenv_round:
805 HandlePragmaFEnvRound();
807 case tok::annot_pragma_cx_limited_range:
808 HandlePragmaCXLimitedRange();
810 case tok::annot_pragma_float_control:
811 HandlePragmaFloatControl();
813 case tok::annot_pragma_fp:
816 case tok::annot_pragma_opencl_extension:
817 HandlePragmaOpenCLExtension();
819 case tok::annot_attr_openmp:
820 case tok::annot_pragma_openmp: {
822 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
824 case tok::annot_pragma_openacc: {
829 case tok::annot_pragma_ms_pointers_to_members:
830 HandlePragmaMSPointersToMembers();
832 case tok::annot_pragma_ms_vtordisp:
833 HandlePragmaMSVtorDisp();
835 case tok::annot_pragma_ms_pragma:
836 HandlePragmaMSPragma();
838 case tok::annot_pragma_dump:
841 case tok::annot_pragma_attribute:
842 HandlePragmaAttribute();
847 Actions.ActOnEmptyDeclaration(
getCurScope(), Attrs, Tok.getLocation());
851 Diag(Tok, diag::err_extraneous_closing_brace);
855 Diag(Tok, diag::err_expected_external_declaration);
857 case tok::kw___extension__: {
859 ExtensionRAIIObject O(Diags);
861 return ParseExternalDeclaration(Attrs, DeclSpecAttrs);
864 ProhibitAttributes(Attrs);
866 SourceLocation StartLoc = Tok.getLocation();
867 SourceLocation EndLoc;
876 if (!SL->getString().trim().empty())
877 Diag(StartLoc, diag::err_gnu_inline_asm_disabled);
880 ExpectAndConsume(tok::semi, diag::err_expected_after,
881 "top-level asm block");
885 SingleDecl = Actions.ActOnFileScopeAsmDecl(
Result.get(), StartLoc, EndLoc);
889 return ParseObjCAtDirectives(Attrs, DeclSpecAttrs);
893 Diag(Tok, diag::err_expected_external_declaration);
897 SingleDecl = ParseObjCMethodDefinition();
899 case tok::code_completion:
901 if (CurParsedObjCImpl) {
903 Actions.CodeCompletion().CodeCompleteObjCMethodDecl(
910 if (CurParsedObjCImpl) {
912 }
else if (PP.isIncrementalProcessingEnabled()) {
917 Actions.CodeCompletion().CodeCompleteOrdinaryName(
getCurScope(), PCC);
919 case tok::kw_import: {
922 llvm_unreachable(
"not expecting a c++20 import here");
923 ProhibitAttributes(Attrs);
925 SingleDecl = ParseModuleImport(SourceLocation(), IS);
929 ProhibitAttributes(Attrs);
930 SingleDecl = ParseExportDeclaration();
937 case tok::kw_namespace:
938 case tok::kw_typedef:
939 case tok::kw_template:
940 case tok::kw_static_assert:
941 case tok::kw__Static_assert:
944 SourceLocation DeclEnd;
949 case tok::kw_cbuffer:
950 case tok::kw_tbuffer:
952 SourceLocation DeclEnd;
964 SourceLocation DeclEnd;
975 if (NextKind == tok::kw_namespace) {
976 SourceLocation DeclEnd;
983 if (NextKind == tok::kw_template) {
986 SourceLocation DeclEnd;
995 ProhibitAttributes(Attrs);
996 ProhibitAttributes(DeclSpecAttrs);
1001 diag::warn_cxx98_compat_extern_template :
1002 diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc);
1003 SourceLocation DeclEnd;
1005 TemplateLoc, DeclEnd, Attrs);
1009 case tok::kw___if_exists:
1010 case tok::kw___if_not_exists:
1011 ParseMicrosoftIfExistsExternalDeclaration();
1014 case tok::kw_module:
1015 Diag(Tok, diag::err_unexpected_module_decl);
1021 if (Tok.isEditorPlaceholder()) {
1026 !isDeclarationStatement(
true))
1027 return ParseTopLevelStmtDecl();
1031 return ParseDeclarationOrFunctionDefinition(Attrs, DeclSpecAttrs, DS);
1036 return Actions.ConvertDeclToDeclGroup(SingleDecl);
1039bool Parser::isDeclarationAfterDeclarator() {
1043 if (KW.
is(tok::kw_default) || KW.
is(tok::kw_delete))
1047 return Tok.is(tok::equal) ||
1048 Tok.is(tok::comma) ||
1049 Tok.is(tok::semi) ||
1050 Tok.is(tok::kw_asm) ||
1051 Tok.is(tok::kw___attribute) ||
1053 Tok.is(tok::l_paren));
1056bool Parser::isStartOfFunctionDefinition(
const ParsingDeclarator &Declarator) {
1057 assert(
Declarator.isFunctionDeclarator() &&
"Isn't a function declarator");
1058 if (Tok.is(tok::l_brace))
1063 Declarator.getFunctionTypeInfo().isKNRPrototype())
1068 return KW.
is(tok::kw_default) || KW.
is(tok::kw_delete);
1071 return Tok.is(tok::colon) ||
1072 Tok.is(tok::kw_try);
1076 ParsedAttributes &Attrs, ParsedAttributes &DeclSpecAttrs,
1082 "expected uninitialised source range");
1087 ParsedTemplateInfo TemplateInfo;
1090 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
1091 DeclSpecContext::DSC_top_level);
1096 DS, AS, DeclSpecContext::DSC_top_level))
1101 if (Tok.is(tok::semi)) {
1104 SourceLocation CorrectLocationForAttributes{};
1108 if (
const auto *ED = dyn_cast_or_null<EnumDecl>(DS.
getRepAsDecl())) {
1109 CorrectLocationForAttributes =
1110 PP.getLocForEndOfToken(ED->getEnumKeyRange().getEnd());
1113 if (CorrectLocationForAttributes.
isInvalid()) {
1114 const auto &Policy = Actions.getASTContext().getPrintingPolicy();
1117 CorrectLocationForAttributes =
1121 ProhibitAttributes(Attrs, CorrectLocationForAttributes);
1123 RecordDecl *AnonRecord =
nullptr;
1124 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
1127 Actions.ActOnDefinedDeclarationSpecifier(TheDecl);
1129 Decl* decls[] = {AnonRecord, TheDecl};
1130 return Actions.BuildDeclaratorGroup(decls);
1132 return Actions.ConvertDeclToDeclGroup(TheDecl);
1136 Actions.ActOnDefinedDeclarationSpecifier(DS.
getRepAsDecl());
1143 if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
1144 !Tok.isObjCAtKeyword(tok::objc_protocol) &&
1145 !Tok.isObjCAtKeyword(tok::objc_implementation)) {
1146 Diag(Tok, diag::err_objc_unexpected_attr);
1154 const char *PrevSpec =
nullptr;
1157 Actions.getASTContext().getPrintingPolicy()))
1158 Diag(AtLoc, DiagID) << PrevSpec;
1160 if (Tok.isObjCAtKeyword(tok::objc_protocol))
1161 return ParseObjCAtProtocolDeclaration(AtLoc, DS.
getAttributes());
1163 if (Tok.isObjCAtKeyword(tok::objc_implementation))
1164 return ParseObjCAtImplementationDeclaration(AtLoc, DS.
getAttributes());
1166 return Actions.ConvertDeclToDeclGroup(
1167 ParseObjCAtInterfaceDeclaration(AtLoc, DS.
getAttributes()));
1176 ProhibitAttributes(Attrs);
1178 return Actions.ConvertDeclToDeclGroup(TheDecl);
1185 ParsedAttributes &Attrs, ParsedAttributes &DeclSpecAttrs,
1189 llvm::TimeTraceScope TimeScope(
"ParseDeclarationOrFunctionDefinition", [&]() {
1190 return Tok.getLocation().printToString(
1191 Actions.getASTContext().getSourceManager());
1195 return ParseDeclOrFunctionDefInternal(Attrs, DeclSpecAttrs, *DS, AS);
1197 ParsingDeclSpec PDS(*
this);
1201 ObjCDeclContextSwitch ObjCDC(*
this);
1203 return ParseDeclOrFunctionDefInternal(Attrs, DeclSpecAttrs, PDS, AS);
1207Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
1208 const ParsedTemplateInfo &TemplateInfo,
1209 LateParsedAttrList *LateParsedAttrs) {
1210 llvm::TimeTraceScope TimeScope(
"ParseFunctionDefinition", [&]() {
1211 return Actions.GetNameForDeclarator(D).getName().getAsString();
1217 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1225 const char *PrevSpec;
1227 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1239 ParseKNRParamDeclarations(D);
1243 if (Tok.isNot(tok::l_brace) &&
1245 (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
1246 Tok.isNot(tok::equal)))) {
1247 Diag(Tok, diag::err_expected_fn_body);
1253 if (Tok.isNot(tok::l_brace))
1259 if (Tok.isNot(tok::equal)) {
1261 if (AL.isKnownToGCC() && !AL.isStandardAttributeSyntax())
1262 Diag(AL.getLoc(), diag::warn_attribute_on_function_definition) << AL;
1267 if (
getLangOpts().DelayedTemplateParsing && Tok.isNot(tok::equal) &&
1269 LateParsedAttrs->empty() && Actions.canDelayFunctionBody(D)) {
1277 Decl *DP = Actions.HandleDeclarator(ParentScope, D,
1282 if (SkipFunctionBodies && (!DP || Actions.canSkipFunctionBody(DP)) &&
1283 trySkippingFunctionBody()) {
1285 return Actions.ActOnSkippedFunctionBody(DP);
1289 LexTemplateFunctionForLateParsing(Toks);
1293 Actions.CheckForFunctionRedefinition(FnD);
1294 Actions.MarkAsLateParsedTemplate(FnD, DP, Toks);
1298 if (CurParsedObjCImpl && !TemplateInfo.TemplateParams &&
1299 (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) || Tok.is(tok::colon)) &&
1300 Actions.CurContext->isTranslationUnit()) {
1306 Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
1312 StashAwayMethodOrFunctionBodyTokens(FuncDecl);
1313 CurParsedObjCImpl->HasCFunction =
true;
1325 StringLiteral *DeletedMessage =
nullptr;
1327 SourceLocation KWLoc;
1333 ? diag::warn_cxx98_compat_defaulted_deleted_function
1334 : diag::ext_defaulted_deleted_function)
1337 DeletedMessage = ParseCXXDeletedFunctionMessage();
1340 ? diag::warn_cxx98_compat_defaulted_deleted_function
1341 : diag::ext_defaulted_deleted_function)
1345 llvm_unreachable(
"function definition after = not 'delete' or 'default'");
1348 if (Tok.is(tok::comma)) {
1349 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
1352 }
else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
1360 Sema::FPFeaturesStateRAII SaveFPFeatures(Actions);
1364 SkipBodyInfo SkipBody;
1366 TemplateInfo.TemplateParams
1367 ? *TemplateInfo.TemplateParams
1369 &SkipBody, BodyKind);
1386 Actions.PopExpressionEvaluationContext();
1398 Actions.SetFunctionBodyKind(Res, KWLoc, BodyKind, DeletedMessage);
1399 Stmt *GeneratedBody = Res ? Res->
getBody() :
nullptr;
1400 Actions.ActOnFinishFunctionBody(Res, GeneratedBody,
false);
1406 if (
const auto *
Template = dyn_cast_if_present<FunctionTemplateDecl>(Res);
1408 Template->getTemplateParameters()->getParam(0)->isImplicit())
1411 CurTemplateDepthTracker.addDepth(1);
1414 if (LateParsedAttrs)
1415 ParseLexedAttributeList(*LateParsedAttrs, Res,
false,
1418 if (SkipFunctionBodies && (!Res || Actions.canSkipFunctionBody(Res)) &&
1419 trySkippingFunctionBody()) {
1421 Actions.ActOnSkippedFunctionBody(Res);
1422 return Actions.ActOnFinishFunctionBody(Res,
nullptr,
false);
1425 if (Tok.is(tok::kw_try))
1426 return ParseFunctionTryBlock(Res, BodyScope);
1430 if (Tok.is(tok::colon)) {
1431 ParseConstructorInitializer(Res);
1434 if (!Tok.is(tok::l_brace)) {
1436 Actions.ActOnFinishFunctionBody(Res,
nullptr);
1440 Actions.ActOnDefaultCtorInitializers(Res);
1442 return ParseFunctionStatementBody(Res, BodyScope);
1445void Parser::SkipFunctionBody() {
1446 if (Tok.is(tok::equal)) {
1451 bool IsFunctionTryBlock = Tok.is(tok::kw_try);
1452 if (IsFunctionTryBlock)
1456 if (ConsumeAndStoreFunctionPrologue(Skipped))
1460 while (IsFunctionTryBlock && Tok.is(tok::kw_catch)) {
1467void Parser::ParseKNRParamDeclarations(Declarator &D) {
1478 SourceLocation DSStart = Tok.getLocation();
1481 DeclSpec DS(AttrFactory);
1482 ParsedTemplateInfo TemplateInfo;
1483 ParseDeclarationSpecifiers(DS, TemplateInfo);
1491 Diag(DSStart, diag::err_declaration_does_not_declare_param);
1500 diag::err_invalid_storage_class_in_func_decl);
1505 diag::err_invalid_storage_class_in_func_decl);
1512 ParseDeclarator(ParmDeclarator);
1517 MaybeParseGNUAttributes(ParmDeclarator);
1521 Actions.ActOnParamDeclarator(
getCurScope(), ParmDeclarator);
1525 ParmDeclarator.getIdentifier()) {
1529 for (
unsigned i = 0; ; ++i) {
1533 Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
1534 << ParmDeclarator.getIdentifier();
1538 if (FTI.
Params[i].
Ident == ParmDeclarator.getIdentifier()) {
1541 Diag(ParmDeclarator.getIdentifierLoc(),
1542 diag::err_param_redefinition)
1543 << ParmDeclarator.getIdentifier();
1554 if (Tok.isNot(tok::comma))
1557 ParmDeclarator.clear();
1563 ParseDeclarator(ParmDeclarator);
1567 if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration))
1577 Actions.ActOnFinishKNRParamDeclarations(
getCurScope(), D, Tok.getLocation());
1580ExprResult Parser::ParseAsmStringLiteral(
bool ForAsmLabel) {
1583 if (isTokenStringLiteral()) {
1589 if (!SL->isOrdinary()) {
1590 Diag(Tok, diag::err_asm_operand_wide_string_literal)
1591 << SL->isWide() << SL->getSourceRange();
1595 Tok.is(tok::l_paren)) {
1597 SourceLocation RParenLoc;
1600 EnterExpressionEvaluationContext ConstantEvaluated(
1602 AsmString = ParseParenExpression(
1606 AsmString = Actions.ActOnConstantExpression(AsmString);
1611 Diag(Tok, diag::err_asm_expected_string) << (
1612 (
getLangOpts().CPlusPlus11 && !ForAsmLabel) ? 0 : 1);
1615 return Actions.ActOnGCCAsmStmtString(AsmString.
get(), ForAsmLabel);
1618ExprResult Parser::ParseSimpleAsm(
bool ForAsmLabel, SourceLocation *EndLoc) {
1619 assert(Tok.is(tok::kw_asm) &&
"Not an asm!");
1622 if (isGNUAsmQualifier(Tok)) {
1624 SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
1625 PP.getLocForEndOfToken(Tok.getLocation()));
1626 Diag(Tok, diag::err_global_asm_qualifier_ignored)
1627 << GNUAsmQualifiers::getQualifierName(getGNUAsmQualifier(Tok))
1633 if (
T.consumeOpen()) {
1634 Diag(Tok, diag::err_expected_lparen_after) <<
"asm";
1640 if (!
Result.isInvalid()) {
1644 *EndLoc =
T.getCloseLocation();
1647 *EndLoc = Tok.getLocation();
1654TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(
const Token &tok) {
1655 assert(tok.
is(tok::annot_template_id) &&
"Expected template-id token");
1656 TemplateIdAnnotation *
1661void Parser::AnnotateScopeToken(CXXScopeSpec &SS,
bool IsNewAnnotation) {
1664 if (PP.isBacktrackEnabled())
1665 PP.RevertCachedTokens(1);
1667 PP.EnterToken(Tok,
true);
1668 Tok.setKind(tok::annot_cxxscope);
1669 Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
1670 Tok.setAnnotationRange(SS.
getRange());
1675 if (IsNewAnnotation)
1676 PP.AnnotateCachedTokens(Tok);
1680Parser::TryAnnotateName(CorrectionCandidateCallback *CCC,
1682 assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
1684 const bool EnteringContext =
false;
1685 const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1689 ParseOptionalCXXScopeSpecifier(SS,
nullptr,
1694 if (Tok.isNot(tok::identifier) || SS.
isInvalid()) {
1696 AllowImplicitTypename))
1701 IdentifierInfo *Name = Tok.getIdentifierInfo();
1702 SourceLocation NameLoc = Tok.getLocation();
1706 if (isTentativelyDeclared(Name) && SS.
isEmpty()) {
1710 AllowImplicitTypename))
1722 Sema::NameClassification Classification = Actions.ClassifyName(
1730 isTemplateArgumentList(1) == TPResult::False) {
1732 Token FakeNext =
Next;
1733 FakeNext.
setKind(tok::unknown);
1735 Actions.ClassifyName(
getCurScope(), SS, Name, NameLoc, FakeNext,
1736 SS.
isEmpty() ? CCC :
nullptr);
1739 switch (Classification.
getKind()) {
1745 Tok.setIdentifierInfo(Name);
1747 PP.TypoCorrectToken(Tok);
1749 AnnotateScopeToken(SS, !WasScopeAnnotation);
1758 if (TryAltiVecVectorToken())
1763 SourceLocation BeginLoc = NameLoc;
1770 QualType
T = Actions.GetTypeFromParser(Ty);
1775 SourceLocation NewEndLoc;
1777 = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
1782 else if (Tok.is(tok::eof))
1786 Tok.setKind(tok::annot_typename);
1787 setTypeAnnotation(Tok, Ty);
1788 Tok.setAnnotationEndLoc(Tok.getLocation());
1789 Tok.setLocation(BeginLoc);
1790 PP.AnnotateCachedTokens(Tok);
1795 Tok.setKind(tok::annot_overload_set);
1797 Tok.setAnnotationEndLoc(NameLoc);
1800 PP.AnnotateCachedTokens(Tok);
1804 if (TryAltiVecVectorToken())
1809 Tok.setKind(tok::annot_non_type);
1811 Tok.setLocation(NameLoc);
1812 Tok.setAnnotationEndLoc(NameLoc);
1813 PP.AnnotateCachedTokens(Tok);
1815 AnnotateScopeToken(SS, !WasScopeAnnotation);
1820 Tok.setKind(Classification.
getKind() ==
1822 ? tok::annot_non_type_undeclared
1823 : tok::annot_non_type_dependent);
1824 setIdentifierAnnotation(Tok, Name);
1825 Tok.setLocation(NameLoc);
1826 Tok.setAnnotationEndLoc(NameLoc);
1827 PP.AnnotateCachedTokens(Tok);
1829 AnnotateScopeToken(SS, !WasScopeAnnotation);
1833 if (
Next.isNot(tok::less)) {
1837 AnnotateScopeToken(SS, !WasScopeAnnotation);
1845 bool IsConceptName =
1851 if (
Next.is(tok::less))
1853 if (AnnotateTemplateIdToken(
1860 AnnotateScopeToken(SS, !WasScopeAnnotation);
1867 AnnotateScopeToken(SS, !WasScopeAnnotation);
1872 SourceLocation TokenEndLoc = PP.getLocForEndOfToken(PrevTokLocation);
1873 return TokenEndLoc.
isValid() ? TokenEndLoc : Tok.getLocation();
1876bool Parser::TryKeywordIdentFallback(
bool DisableKeyword) {
1877 assert(
Tok.isNot(tok::identifier));
1878 Diag(
Tok, diag::ext_keyword_as_ident)
1882 Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
1883 Tok.setKind(tok::identifier);
1889 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1890 Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope) ||
1891 Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id) ||
1892 Tok.is(tok::kw___super) || Tok.is(tok::kw_auto) ||
1893 Tok.is(tok::annot_pack_indexing_type)) &&
1894 "Cannot be a type or scope token!");
1896 if (Tok.is(tok::kw_typename)) {
1905 PP.Lex(TypedefToken);
1907 PP.EnterToken(Tok,
true);
1910 Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename);
1922 if (ParseOptionalCXXScopeSpecifier(SS,
nullptr,
1928 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) ||
1929 Tok.is(tok::annot_decltype)) {
1931 if (Tok.is(tok::annot_decltype) ||
1933 Tok.isAnnotation())) {
1934 unsigned DiagID = diag::err_expected_qualified_after_typename;
1938 DiagID = diag::warn_expected_qualified_after_typename;
1939 Diag(Tok.getLocation(), DiagID);
1943 if (Tok.isEditorPlaceholder())
1946 Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
1950 bool TemplateKWPresent =
false;
1951 if (Tok.is(tok::kw_template)) {
1953 TemplateKWPresent =
true;
1957 if (Tok.is(tok::identifier)) {
1959 Diag(Tok.getLocation(),
1960 diag::missing_template_arg_list_after_template_kw);
1963 Ty = Actions.ActOnTypenameType(
getCurScope(), TypenameLoc, SS,
1964 *Tok.getIdentifierInfo(),
1966 }
else if (Tok.is(tok::annot_template_id)) {
1969 Diag(Tok, diag::err_typename_refers_to_non_type_template)
1970 << Tok.getAnnotationRange();
1979 : Actions.ActOnTypenameType(
1983 TemplateArgsPtr, TemplateId->
RAngleLoc);
1985 Diag(Tok, diag::err_expected_type_name_after_typename)
1991 Tok.setKind(tok::annot_typename);
1992 setTypeAnnotation(Tok, Ty);
1993 Tok.setAnnotationEndLoc(EndLoc);
1994 Tok.setLocation(TypenameLoc);
1995 PP.AnnotateCachedTokens(Tok);
2000 bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
2004 if (ParseOptionalCXXScopeSpecifier(SS,
nullptr,
2010 AllowImplicitTypename);
2016 if (Tok.is(tok::identifier)) {
2019 *Tok.getIdentifierInfo(), Tok.getLocation(),
getCurScope(), &SS,
2023 true, AllowImplicitTypename)) {
2028 QualType T = Actions.GetTypeFromParser(Ty);
2033 (
T->isObjCObjectType() ||
T->isObjCObjectPointerType())) {
2043 else if (Tok.is(tok::eof))
2049 Tok.setKind(tok::annot_typename);
2050 setTypeAnnotation(Tok, Ty);
2051 Tok.setAnnotationEndLoc(Tok.getLocation());
2052 Tok.setLocation(BeginLoc);
2056 PP.AnnotateCachedTokens(Tok);
2073 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
2074 bool MemberOfUnknownSpecialization;
2079 MemberOfUnknownSpecialization)) {
2083 isTemplateArgumentList(1) != TPResult::False) {
2103 if (Tok.is(tok::annot_template_id)) {
2110 AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
2117 Tok.is(tok::coloncolon)) {
2126 AnnotateScopeToken(SS, IsNewScope);
2132 "Call sites of this function should be guarded by checking for C++");
2136 if (ParseOptionalCXXScopeSpecifier(SS,
nullptr,
2143 AnnotateScopeToken(SS,
true);
2147bool Parser::isTokenEqualOrEqualTypo() {
2153 case tok::starequal:
2154 case tok::plusequal:
2155 case tok::minusequal:
2156 case tok::exclaimequal:
2157 case tok::slashequal:
2158 case tok::percentequal:
2159 case tok::lessequal:
2160 case tok::lesslessequal:
2161 case tok::greaterequal:
2162 case tok::greatergreaterequal:
2163 case tok::caretequal:
2164 case tok::pipeequal:
2165 case tok::equalequal:
2166 Diag(
Tok, diag::err_invalid_token_after_declarator_suggest_equal)
2175SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
2176 assert(Tok.is(tok::code_completion));
2177 PrevTokLocation = Tok.getLocation();
2180 if (S->isFunctionScope()) {
2182 Actions.CodeCompletion().CodeCompleteOrdinaryName(
2184 return PrevTokLocation;
2187 if (S->isClassScope()) {
2189 Actions.CodeCompletion().CodeCompleteOrdinaryName(
2191 return PrevTokLocation;
2196 Actions.CodeCompletion().CodeCompleteOrdinaryName(
2198 return PrevTokLocation;
2203void Parser::CodeCompleteDirective(
bool InConditional) {
2204 Actions.CodeCompletion().CodeCompletePreprocessorDirective(InConditional);
2208 Actions.CodeCompletion().CodeCompleteInPreprocessorConditionalExclusion(
2212void Parser::CodeCompleteMacroName(
bool IsDefinition) {
2213 Actions.CodeCompletion().CodeCompletePreprocessorMacroName(IsDefinition);
2217 Actions.CodeCompletion().CodeCompletePreprocessorExpression();
2220void Parser::CodeCompleteMacroArgument(IdentifierInfo *
Macro,
2221 MacroInfo *MacroInfo,
2222 unsigned ArgumentIndex) {
2223 Actions.CodeCompletion().CodeCompletePreprocessorMacroArgument(
2227void Parser::CodeCompleteIncludedFile(llvm::StringRef Dir,
bool IsAngled) {
2228 Actions.CodeCompletion().CodeCompleteIncludedFile(Dir, IsAngled);
2232 Actions.CodeCompletion().CodeCompleteNaturalLanguage();
2235bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition&
Result) {
2236 assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
2237 "Expected '__if_exists' or '__if_not_exists'");
2238 Result.IsIfExists = Tok.is(tok::kw___if_exists);
2242 if (
T.consumeOpen()) {
2243 Diag(Tok, diag::err_expected_lparen_after)
2244 << (
Result.IsIfExists?
"__if_exists" :
"__if_not_exists");
2250 ParseOptionalCXXScopeSpecifier(
Result.SS,
nullptr,
2255 if (
Result.SS.isInvalid()) {
2261 SourceLocation TemplateKWLoc;
2266 false, &TemplateKWLoc,
2272 if (
T.consumeClose())
2300void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
2301 IfExistsCondition
Result;
2302 if (ParseMicrosoftIfExistsCondition(
Result))
2306 if (
Braces.consumeOpen()) {
2307 Diag(Tok, diag::err_expected) << tok::l_brace;
2311 switch (
Result.Behavior) {
2317 llvm_unreachable(
"Cannot have a dependent external declaration");
2326 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
2327 ParsedAttributes Attrs(AttrFactory);
2328 MaybeParseCXX11Attributes(Attrs);
2329 ParsedAttributes EmptyDeclSpecAttrs(AttrFactory);
2332 Actions.getASTConsumer().HandleTopLevelDecl(
Result.get());
2339 Token Introducer = Tok;
2340 SourceLocation StartLoc = Introducer.
getLocation();
2347 (Tok.is(tok::kw_module) ||
2348 (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_module)) &&
2349 "not a module declaration");
2354 DiagnoseAndSkipCXX11Attributes();
2357 if (
getLangOpts().CPlusPlusModules && Tok.is(tok::semi)) {
2361 Diag(StartLoc, diag::err_global_module_introducer_not_at_start)
2362 << SourceRange(StartLoc, SemiLoc);
2366 Diag(StartLoc, diag::err_module_fragment_exported)
2370 return Actions.ActOnGlobalModuleFragmentDecl(ModuleLoc);
2374 if (
getLangOpts().CPlusPlusModules && Tok.is(tok::colon) &&
2377 Diag(StartLoc, diag::err_module_fragment_exported)
2382 DiagnoseAndSkipCXX11Attributes();
2383 ExpectAndConsumeSemi(diag::err_private_module_fragment_expected_semi);
2387 return Actions.ActOnPrivateModuleFragmentDecl(ModuleLoc, PrivateLoc);
2390 SmallVector<IdentifierLoc, 2> Path;
2391 if (ParseModuleName(ModuleLoc, Path,
false))
2395 SmallVector<IdentifierLoc, 2> Partition;
2396 if (Tok.is(tok::colon)) {
2399 Diag(ColonLoc, diag::err_unsupported_module_partition)
2400 << SourceRange(ColonLoc, Partition.back().getLoc());
2402 else if (ParseModuleName(ModuleLoc, Partition,
false))
2407 ParsedAttributes Attrs(AttrFactory);
2408 MaybeParseCXX11Attributes(Attrs);
2409 ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_module_attr,
2410 diag::err_keyword_not_module_attr,
2414 ExpectAndConsumeSemi(diag::err_module_expected_semi);
2416 return Actions.ActOnModuleDecl(StartLoc, ModuleLoc, MDK, Path, Partition,
2421Decl *Parser::ParseModuleImport(SourceLocation AtLoc,
2423 SourceLocation StartLoc = AtLoc.
isInvalid() ? Tok.getLocation() : AtLoc;
2425 SourceLocation ExportLoc;
2428 assert((AtLoc.
isInvalid() ? Tok.isOneOf(tok::kw_import, tok::identifier)
2429 : Tok.isObjCAtKeyword(tok::objc_import)) &&
2430 "Improper start to module import");
2431 bool IsObjCAtImport = Tok.isObjCAtKeyword(tok::objc_import);
2435 SmallVector<IdentifierLoc, 2> Path;
2436 bool IsPartition =
false;
2437 Module *HeaderUnit =
nullptr;
2438 if (Tok.is(tok::header_name)) {
2443 }
else if (Tok.is(tok::annot_header_unit)) {
2445 HeaderUnit =
reinterpret_cast<Module *
>(Tok.getAnnotationValue());
2446 ConsumeAnnotationToken();
2447 }
else if (Tok.is(tok::colon)) {
2450 Diag(ColonLoc, diag::err_unsupported_module_partition)
2451 << SourceRange(ColonLoc, Path.back().getLoc());
2453 else if (ParseModuleName(ColonLoc, Path,
true))
2458 if (ParseModuleName(ImportLoc, Path,
true))
2462 ParsedAttributes Attrs(AttrFactory);
2463 MaybeParseCXX11Attributes(Attrs);
2465 ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_import_attr,
2466 diag::err_keyword_not_import_attr,
2470 if (PP.hadModuleLoaderFatalFailure()) {
2477 bool SeenError =
true;
2478 switch (ImportState) {
2490 Diag(ImportLoc, diag::err_partition_import_outside_module);
2502 if (IsPartition || (HeaderUnit && HeaderUnit->
Kind !=
2504 Diag(ImportLoc, diag::err_import_in_wrong_fragment)
2513 Diag(ImportLoc, diag::err_import_not_allowed_here);
2518 ExpectAndConsumeSemi(diag::err_module_expected_semi);
2527 Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, HeaderUnit);
2528 else if (!Path.empty())
2529 Import = Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Path,
2536 if (IsObjCAtImport && AtLoc.
isValid()) {
2537 auto &SrcMgr = PP.getSourceManager();
2538 auto FE = SrcMgr.getFileEntryRefForID(SrcMgr.getFileID(AtLoc));
2539 if (FE && llvm::sys::path::parent_path(FE->getDir().getName())
2540 .ends_with(
".framework"))
2541 Diags.Report(AtLoc, diag::warn_atimport_in_framework_header);
2547bool Parser::ParseModuleName(SourceLocation UseLoc,
2548 SmallVectorImpl<IdentifierLoc> &Path,
2552 if (!Tok.is(tok::identifier)) {
2553 if (Tok.is(tok::code_completion)) {
2555 Actions.CodeCompletion().CodeCompleteModuleImport(UseLoc, Path);
2559 Diag(Tok, diag::err_module_expected_ident) << IsImport;
2565 Path.emplace_back(Tok.getLocation(), Tok.getIdentifierInfo());
2568 if (Tok.isNot(tok::period))
2575bool Parser::parseMisplacedModuleImport() {
2577 switch (Tok.getKind()) {
2578 case tok::annot_module_end:
2582 if (MisplacedModuleBeginCount) {
2583 --MisplacedModuleBeginCount;
2584 Actions.ActOnAnnotModuleEnd(
2586 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
2587 ConsumeAnnotationToken();
2594 case tok::annot_module_begin:
2596 Actions.ActOnAnnotModuleBegin(
2598 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
2599 ConsumeAnnotationToken();
2600 ++MisplacedModuleBeginCount;
2602 case tok::annot_module_include:
2605 Actions.ActOnAnnotModuleInclude(
2607 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
2608 ConsumeAnnotationToken();
2618void Parser::diagnoseUseOfC11Keyword(
const Token &Tok) {
2623 : diag::ext_c11_feature)
2627bool BalancedDelimiterTracker::diagnoseOverflow() {
2628 P.Diag(P.Tok, diag::err_bracket_depth_exceeded)
2629 << P.getLangOpts().BracketDepth;
2630 P.Diag(P.Tok, diag::note_bracket_depth);
2638 LOpen = P.Tok.getLocation();
2639 if (P.ExpectAndConsume(Kind, DiagID, Msg)) {
2640 if (SkipToTok != tok::unknown)
2645 if (getDepth() < P.getLangOpts().BracketDepth)
2648 return diagnoseOverflow();
2651bool BalancedDelimiterTracker::diagnoseMissingClose() {
2652 assert(!P.Tok.is(Close) &&
"Should have consumed closing delimiter");
2654 if (P.Tok.is(tok::annot_module_end))
2655 P.Diag(P.Tok, diag::err_missing_before_module_end) << Close;
2657 P.Diag(P.Tok, diag::err_expected) << Close;
2658 P.Diag(LOpen, diag::note_matching) << Kind;
2662 if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) &&
2663 P.Tok.isNot(tok::r_square) &&
2664 P.SkipUntil(Close, FinalToken,
2667 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.