29#include "llvm/ADT/STLForwardCompat.h"
30#include "llvm/Support/Path.h"
31#include "llvm/Support/TimeProfiler.h"
42 explicit ActionCommentHandler(Sema &S) : S(S) { }
44 bool HandleComment(Preprocessor &PP, SourceRange Comment)
override {
45 S.ActOnComment(Comment);
54 Ident__except = PP.getIdentifierInfo(
"__except");
61 PreferredType(&actions.getASTContext(), pp.isCodeCompletionEnabled()),
62 Actions(actions), Diags(PP.getDiagnostics()), StackHandler(Diags),
63 GreaterThanIsOperator(
true), ColonIsSacred(
false),
64 InMessageExpression(
false), ParsingInObjCContainer(
false),
65 TemplateParameterDepth(0) {
68 Tok.setKind(tok::eof);
69 Actions.CurScope =
nullptr;
71 CurParsedObjCImpl =
nullptr;
75 initializePragmaHandlers();
77 CommentSemaHandler.reset(
new ActionCommentHandler(actions));
78 PP.addCommentHandler(CommentSemaHandler.get());
80 PP.setCodeCompletionHandler(*
this);
82 Actions.ParseTypeFromStringCallback =
83 [
this](StringRef TypeStr, StringRef Context,
SourceLocation IncludeLoc) {
84 return this->ParseTypeFromString(TypeStr, Context, IncludeLoc);
89 return Diags.Report(Loc, DiagID);
93 return Diag(Tok.getLocation(), DiagID);
97 unsigned CompatDiagId) {
102 return DiagCompat(Tok.getLocation(), CompatDiagId);
121 switch (ExpectedTok) {
123 return Tok.is(tok::colon) ||
Tok.is(tok::comma);
124 default:
return false;
128bool Parser::ExpectAndConsume(
tok::TokenKind ExpectedTok,
unsigned DiagID,
130 if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) {
137 SourceLocation Loc = Tok.getLocation();
139 DiagnosticBuilder DB =
Diag(Loc, DiagID);
142 if (DiagID == diag::err_expected)
144 else if (DiagID == diag::err_expected_after)
145 DB << Msg << ExpectedTok;
155 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
156 const char *Spelling =
nullptr;
160 DiagnosticBuilder DB =
164 if (DiagID == diag::err_expected)
166 else if (DiagID == diag::err_expected_after)
167 DB << Msg << ExpectedTok;
174bool Parser::ExpectAndConsumeSemi(
unsigned DiagID, StringRef TokenUsed) {
178 if (Tok.is(tok::code_completion)) {
179 handleUnexpectedCodeCompletionToken();
183 if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) &&
185 Diag(Tok, diag::err_extraneous_token_before_semi)
186 << PP.getSpelling(Tok)
193 return ExpectAndConsume(tok::semi, DiagID , TokenUsed);
196bool Parser::isLikelyAtStartOfNewDeclaration() {
197 return Tok.isAtStartOfLine() &&
202 if (!Tok.is(tok::semi))
return;
204 bool HadMultipleSemis =
false;
205 SourceLocation StartLoc = Tok.getLocation();
206 SourceLocation EndLoc = Tok.getLocation();
209 while ((Tok.is(tok::semi) && !Tok.isAtStartOfLine())) {
210 HadMultipleSemis =
true;
211 EndLoc = Tok.getLocation();
219 Diag(StartLoc, diag::warn_cxx98_compat_top_level_semi)
222 Diag(StartLoc, diag::ext_extra_semi_cxx11)
228 Diag(StartLoc, diag::ext_extra_semi)
231 TST, Actions.getASTContext().getPrintingPolicy())
235 Diag(StartLoc, diag::warn_extra_semi_after_mem_fn_def)
239bool Parser::expectIdentifier() {
240 if (Tok.is(tok::identifier))
242 if (
const auto *II = Tok.getIdentifierInfo()) {
244 Diag(Tok, diag::err_expected_token_instead_of_objcxx_keyword)
245 << tok::identifier << Tok.getIdentifierInfo();
250 Diag(Tok, diag::err_expected) << tok::identifier;
258 SourceLocation SecondTokLoc = Tok.getLocation();
263 PP.getSourceManager().getFileID(FirstTokLoc) !=
264 PP.getSourceManager().getFileID(SecondTokLoc)) {
265 Diag(FirstTokLoc, diag::warn_compound_token_split_by_macro)
266 << (FirstTokKind == Tok.getKind()) << FirstTokKind << Tok.getKind()
267 <<
static_cast<int>(Op) << SourceRange(FirstTokLoc);
268 Diag(SecondTokLoc, diag::note_compound_token_split_second_token_here)
269 << (FirstTokKind == Tok.getKind()) << Tok.getKind()
270 << SourceRange(SecondTokLoc);
275 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
276 SourceLocation SpaceLoc = PP.getLocForEndOfToken(FirstTokLoc);
278 SpaceLoc = FirstTokLoc;
279 Diag(SpaceLoc, diag::warn_compound_token_split_by_whitespace)
280 << (FirstTokKind == Tok.getKind()) << FirstTokKind << Tok.getKind()
281 <<
static_cast<int>(Op) << SourceRange(FirstTokLoc, SecondTokLoc);
291 return (
static_cast<unsigned>(L) &
static_cast<unsigned>(R)) != 0;
297 bool isFirstTokenSkipped =
true;
300 for (
unsigned i = 0, NumToks = Toks.size(); i != NumToks; ++i) {
301 if (Tok.is(Toks[i])) {
314 if (Toks.size() == 1 && Toks[0] == tok::eof &&
317 while (Tok.isNot(tok::eof))
322 switch (Tok.getKind()) {
327 case tok::annot_pragma_openmp:
328 case tok::annot_attr_openmp:
329 case tok::annot_pragma_openmp_end:
331 if (OpenMPDirectiveParsing)
333 ConsumeAnnotationToken();
335 case tok::annot_pragma_openacc:
336 case tok::annot_pragma_openacc_end:
338 if (OpenACCDirectiveParsing)
340 ConsumeAnnotationToken();
342 case tok::annot_module_begin:
343 case tok::annot_module_end:
344 case tok::annot_module_include:
345 case tok::annot_repl_input_end:
351 case tok::code_completion:
353 handleUnexpectedCodeCompletionToken();
395 if (ParenCount && !isFirstTokenSkipped)
400 if (BracketCount && !isFirstTokenSkipped)
405 if (BraceCount && !isFirstTokenSkipped)
419 isFirstTokenSkipped =
false;
428 if (NumCachedScopes) {
429 Scope *N = ScopeCache[--NumCachedScopes];
431 Actions.CurScope = N;
442 Actions.ActOnPopScope(Tok.getLocation(),
getCurScope());
445 Actions.CurScope = OldScope->
getParent();
447 if (NumCachedScopes == ScopeCacheSize)
450 ScopeCache[NumCachedScopes++] = OldScope;
453Parser::ParseScopeFlags::ParseScopeFlags(
Parser *
Self,
unsigned ScopeFlags,
455 : CurScope(ManageFlags ?
Self->getCurScope() :
nullptr) {
457 OldFlags = CurScope->getFlags();
458 CurScope->setFlags(ScopeFlags);
462Parser::ParseScopeFlags::~ParseScopeFlags() {
464 CurScope->setFlags(OldFlags);
475 Actions.CurScope =
nullptr;
478 for (
unsigned i = 0, e = NumCachedScopes; i != e; ++i)
479 delete ScopeCache[i];
481 resetPragmaHandlers();
483 PP.removeCommentHandler(CommentSemaHandler.get());
485 PP.clearCodeCompletionHandler();
487 DestroyTemplateIds();
492 assert(
getCurScope() ==
nullptr &&
"A scope is already active?");
500 &PP.getIdentifierTable().get(
"in");
502 &PP.getIdentifierTable().get(
"out");
504 &PP.getIdentifierTable().get(
"inout");
506 &PP.getIdentifierTable().get(
"oneway");
508 &PP.getIdentifierTable().get(
"bycopy");
510 &PP.getIdentifierTable().get(
"byref");
512 &PP.getIdentifierTable().get(
"nonnull");
514 &PP.getIdentifierTable().get(
"nullable");
516 &PP.getIdentifierTable().get(
"null_unspecified");
519 Ident_instancetype =
nullptr;
520 Ident_final =
nullptr;
521 Ident_sealed =
nullptr;
522 Ident_abstract =
nullptr;
523 Ident_override =
nullptr;
524 Ident_GNU_final =
nullptr;
526 Ident_super = &PP.getIdentifierTable().get(
"super");
528 Ident_vector =
nullptr;
529 Ident_bool =
nullptr;
530 Ident_Bool =
nullptr;
531 Ident_pixel =
nullptr;
533 Ident_vector = &PP.getIdentifierTable().get(
"vector");
534 Ident_bool = &PP.getIdentifierTable().get(
"bool");
535 Ident_Bool = &PP.getIdentifierTable().get(
"_Bool");
538 Ident_pixel = &PP.getIdentifierTable().get(
"pixel");
540 Ident_introduced =
nullptr;
541 Ident_deprecated =
nullptr;
542 Ident_obsoleted =
nullptr;
543 Ident_unavailable =
nullptr;
544 Ident_strict =
nullptr;
545 Ident_replacement =
nullptr;
547 Ident_language = Ident_defined_in = Ident_generated_declaration = Ident_USR =
550 Ident__except =
nullptr;
552 Ident__exception_code = Ident__exception_info =
nullptr;
553 Ident__abnormal_termination = Ident___exception_code =
nullptr;
554 Ident___exception_info = Ident___abnormal_termination =
nullptr;
555 Ident_GetExceptionCode = Ident_GetExceptionInfo =
nullptr;
556 Ident_AbnormalTermination =
nullptr;
559 Ident__exception_info = PP.getIdentifierInfo(
"_exception_info");
560 Ident___exception_info = PP.getIdentifierInfo(
"__exception_info");
561 Ident_GetExceptionInfo = PP.getIdentifierInfo(
"GetExceptionInformation");
562 Ident__exception_code = PP.getIdentifierInfo(
"_exception_code");
563 Ident___exception_code = PP.getIdentifierInfo(
"__exception_code");
564 Ident_GetExceptionCode = PP.getIdentifierInfo(
"GetExceptionCode");
565 Ident__abnormal_termination = PP.getIdentifierInfo(
"_abnormal_termination");
566 Ident___abnormal_termination = PP.getIdentifierInfo(
"__abnormal_termination");
567 Ident_AbnormalTermination = PP.getIdentifierInfo(
"AbnormalTermination");
569 PP.SetPoisonReason(Ident__exception_code,diag::err_seh___except_block);
570 PP.SetPoisonReason(Ident___exception_code,diag::err_seh___except_block);
571 PP.SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block);
572 PP.SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter);
573 PP.SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter);
574 PP.SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter);
575 PP.SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block);
576 PP.SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block);
577 PP.SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block);
580 Actions.Initialize();
586void Parser::DestroyTemplateIds() {
594 Actions.ActOnStartOfTranslationUnit();
606 if (NoTopLevelDecls && !Actions.getASTContext().getExternalSource() &&
608 Diag(diag::ext_empty_translation_unit);
610 return NoTopLevelDecls;
615 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*
this);
618 switch (Tok.getKind()) {
619 case tok::annot_pragma_unused:
620 HandlePragmaUnused();
636 Result = ParseModuleDecl(ImportState);
646 case tok::annot_module_include: {
647 auto Loc = Tok.getLocation();
648 Module *Mod =
reinterpret_cast<Module *
>(Tok.getAnnotationValue());
652 Actions.ActOnAnnotModuleInclude(Loc, Mod);
659 ConsumeAnnotationToken();
663 case tok::annot_module_begin:
664 Actions.ActOnAnnotModuleBegin(
666 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
667 ConsumeAnnotationToken();
671 case tok::annot_module_end:
672 Actions.ActOnAnnotModuleEnd(
674 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
675 ConsumeAnnotationToken();
680 case tok::annot_repl_input_end:
682 if (PP.getMaxTokens() != 0 && PP.getTokenCount() > PP.getMaxTokens()) {
683 PP.Diag(Tok.getLocation(), diag::warn_max_tokens_total)
684 << PP.getTokenCount() << PP.getMaxTokens();
687 PP.Diag(OverrideLoc, diag::note_max_tokens_total_override);
692 Actions.SetLateTemplateParser(LateTemplateParserCallback,
this);
693 Actions.ActOnEndOfTranslationUnit();
706 while (MaybeParseCXX11Attributes(DeclAttrs) ||
707 MaybeParseGNUAttributes(DeclSpecAttrs))
710 Result = ParseExternalDeclaration(DeclAttrs, DeclSpecAttrs);
720 else if (ImportState ==
732 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*
this);
740 Decl *SingleDecl =
nullptr;
741 switch (
Tok.getKind()) {
742 case tok::annot_pragma_vis:
743 HandlePragmaVisibility();
745 case tok::annot_pragma_pack:
748 case tok::annot_pragma_msstruct:
749 HandlePragmaMSStruct();
751 case tok::annot_pragma_align:
754 case tok::annot_pragma_weak:
757 case tok::annot_pragma_weakalias:
758 HandlePragmaWeakAlias();
760 case tok::annot_pragma_redefine_extname:
761 HandlePragmaRedefineExtname();
763 case tok::annot_pragma_fp_contract:
764 HandlePragmaFPContract();
766 case tok::annot_pragma_fenv_access:
767 case tok::annot_pragma_fenv_access_ms:
768 HandlePragmaFEnvAccess();
770 case tok::annot_pragma_fenv_round:
771 HandlePragmaFEnvRound();
773 case tok::annot_pragma_cx_limited_range:
774 HandlePragmaCXLimitedRange();
776 case tok::annot_pragma_float_control:
777 HandlePragmaFloatControl();
779 case tok::annot_pragma_fp:
782 case tok::annot_pragma_opencl_extension:
783 HandlePragmaOpenCLExtension();
785 case tok::annot_attr_openmp:
786 case tok::annot_pragma_openmp: {
788 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
790 case tok::annot_pragma_openacc: {
795 case tok::annot_pragma_ms_pointers_to_members:
796 HandlePragmaMSPointersToMembers();
798 case tok::annot_pragma_ms_vtordisp:
799 HandlePragmaMSVtorDisp();
801 case tok::annot_pragma_ms_pragma:
802 HandlePragmaMSPragma();
804 case tok::annot_pragma_dump:
807 case tok::annot_pragma_attribute:
808 HandlePragmaAttribute();
810 case tok::annot_pragma_export:
811 HandlePragmaExport();
816 Actions.ActOnEmptyDeclaration(
getCurScope(), Attrs, Tok.getLocation());
820 Diag(Tok, diag::err_extraneous_closing_brace);
824 Diag(Tok, diag::err_expected_external_declaration);
826 case tok::kw___extension__: {
828 ExtensionRAIIObject O(Diags);
830 return ParseExternalDeclaration(Attrs, DeclSpecAttrs);
833 ProhibitAttributes(Attrs);
835 SourceLocation StartLoc = Tok.getLocation();
836 SourceLocation EndLoc;
845 if (!SL->getString().trim().empty())
846 Diag(StartLoc, diag::err_gnu_inline_asm_disabled);
849 ExpectAndConsume(tok::semi, diag::err_expected_after,
850 "top-level asm block");
854 SingleDecl = Actions.ActOnFileScopeAsmDecl(
Result.get(), StartLoc, EndLoc);
858 return ParseObjCAtDirectives(Attrs, DeclSpecAttrs);
862 Diag(Tok, diag::err_expected_external_declaration);
866 SingleDecl = ParseObjCMethodDefinition();
868 case tok::code_completion:
870 if (CurParsedObjCImpl) {
872 Actions.CodeCompletion().CodeCompleteObjCMethodDecl(
879 if (CurParsedObjCImpl) {
881 }
else if (PP.isIncrementalProcessingEnabled()) {
886 Actions.CodeCompletion().CodeCompleteOrdinaryName(
getCurScope(), PCC);
888 case tok::kw_import: {
891 Diag(Tok, diag::err_unexpected_module_or_import_decl)
896 SingleDecl = ParseModuleImport(SourceLocation(), IS);
900 ProhibitAttributes(Attrs);
901 SingleDecl = ParseExportDeclaration();
908 case tok::kw_namespace:
909 case tok::kw_typedef:
910 case tok::kw_template:
911 case tok::kw_static_assert:
912 case tok::kw__Static_assert:
915 SourceLocation DeclEnd;
920 case tok::kw_cbuffer:
921 case tok::kw_tbuffer:
923 SourceLocation DeclEnd;
935 SourceLocation DeclEnd;
946 if (NextKind == tok::kw_namespace) {
947 SourceLocation DeclEnd;
954 if (NextKind == tok::kw_template) {
957 SourceLocation DeclEnd;
966 ProhibitAttributes(Attrs);
967 ProhibitAttributes(DeclSpecAttrs);
972 diag::warn_cxx98_compat_extern_template :
973 diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc);
974 SourceLocation DeclEnd;
976 TemplateLoc, DeclEnd, Attrs);
980 case tok::kw___if_exists:
981 case tok::kw___if_not_exists:
982 ParseMicrosoftIfExistsExternalDeclaration();
986 Diag(Tok, diag::err_unexpected_module_or_import_decl) <<
false;
992 if (Tok.isEditorPlaceholder()) {
997 !isDeclarationStatement(
true))
998 return ParseTopLevelStmtDecl();
1002 return ParseDeclarationOrFunctionDefinition(Attrs, DeclSpecAttrs, DS);
1007 return Actions.ConvertDeclToDeclGroup(SingleDecl);
1010bool Parser::isDeclarationAfterDeclarator() {
1014 if (KW.
is(tok::kw_default) || KW.
is(tok::kw_delete))
1018 return Tok.is(tok::equal) ||
1019 Tok.is(tok::comma) ||
1020 Tok.is(tok::semi) ||
1021 Tok.is(tok::kw_asm) ||
1022 Tok.is(tok::kw___attribute) ||
1024 Tok.is(tok::l_paren));
1027bool Parser::isStartOfFunctionDefinition(
const ParsingDeclarator &Declarator) {
1028 assert(
Declarator.isFunctionDeclarator() &&
"Isn't a function declarator");
1029 if (Tok.is(tok::l_brace))
1034 Declarator.getFunctionTypeInfo().isKNRPrototype())
1039 return KW.
is(tok::kw_default) || KW.
is(tok::kw_delete);
1042 return Tok.is(tok::colon) ||
1043 Tok.is(tok::kw_try);
1047 ParsedAttributes &Attrs, ParsedAttributes &DeclSpecAttrs,
1053 "expected uninitialised source range");
1058 ParsedTemplateInfo TemplateInfo;
1061 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
1062 DeclSpecContext::DSC_top_level);
1067 DS, AS, DeclSpecContext::DSC_top_level))
1072 if (Tok.is(tok::semi)) {
1075 SourceLocation CorrectLocationForAttributes{};
1079 if (
const auto *ED = dyn_cast_or_null<EnumDecl>(DS.
getRepAsDecl())) {
1080 CorrectLocationForAttributes =
1081 PP.getLocForEndOfToken(ED->getEnumKeyRange().getEnd());
1084 if (CorrectLocationForAttributes.
isInvalid()) {
1085 const auto &Policy = Actions.getASTContext().getPrintingPolicy();
1088 CorrectLocationForAttributes =
1092 ProhibitAttributes(Attrs, CorrectLocationForAttributes);
1094 RecordDecl *AnonRecord =
nullptr;
1095 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
1098 Actions.ActOnDefinedDeclarationSpecifier(TheDecl);
1100 Decl* decls[] = {AnonRecord, TheDecl};
1101 return Actions.BuildDeclaratorGroup(decls);
1103 return Actions.ConvertDeclToDeclGroup(TheDecl);
1107 Actions.ActOnDefinedDeclarationSpecifier(DS.
getRepAsDecl());
1114 if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
1115 !Tok.isObjCAtKeyword(tok::objc_protocol) &&
1116 !Tok.isObjCAtKeyword(tok::objc_implementation)) {
1117 Diag(Tok, diag::err_objc_unexpected_attr);
1125 const char *PrevSpec =
nullptr;
1128 Actions.getASTContext().getPrintingPolicy()))
1129 Diag(AtLoc, DiagID) << PrevSpec;
1131 if (Tok.isObjCAtKeyword(tok::objc_protocol))
1132 return ParseObjCAtProtocolDeclaration(AtLoc, DS.
getAttributes());
1134 if (Tok.isObjCAtKeyword(tok::objc_implementation))
1135 return ParseObjCAtImplementationDeclaration(AtLoc, DS.
getAttributes());
1137 return Actions.ConvertDeclToDeclGroup(
1138 ParseObjCAtInterfaceDeclaration(AtLoc, DS.
getAttributes()));
1147 ProhibitAttributes(Attrs);
1149 return Actions.ConvertDeclToDeclGroup(TheDecl);
1156 ParsedAttributes &Attrs, ParsedAttributes &DeclSpecAttrs,
1160 llvm::TimeTraceScope TimeScope(
"ParseDeclarationOrFunctionDefinition", [&]() {
1161 return Tok.getLocation().printToString(
1162 Actions.getASTContext().getSourceManager());
1166 return ParseDeclOrFunctionDefInternal(Attrs, DeclSpecAttrs, *DS, AS);
1168 ParsingDeclSpec PDS(*
this);
1172 ObjCDeclContextSwitch ObjCDC(*
this);
1174 return ParseDeclOrFunctionDefInternal(Attrs, DeclSpecAttrs, PDS, AS);
1178Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
1179 const ParsedTemplateInfo &TemplateInfo,
1180 LateParsedAttrList *LateParsedAttrs) {
1181 llvm::TimeTraceScope TimeScope(
"ParseFunctionDefinition", [&]() {
1182 return Actions.GetNameForDeclarator(D).getName().getAsString();
1188 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1197 const char *PrevSpec;
1199 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1211 ParseKNRParamDeclarations(D);
1215 if (Tok.isNot(tok::l_brace) &&
1217 (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
1218 Tok.isNot(tok::equal)))) {
1219 Diag(Tok, diag::err_expected_fn_body);
1225 if (Tok.isNot(tok::l_brace))
1231 if (Tok.isNot(tok::equal)) {
1233 if (AL.isKnownToGCC() && !AL.isStandardAttributeSyntax())
1234 Diag(AL.getLoc(), diag::warn_attribute_on_function_definition) << AL;
1239 if (
getLangOpts().DelayedTemplateParsing && Tok.isNot(tok::equal) &&
1241 LateParsedAttrs->empty() && Actions.canDelayFunctionBody(D)) {
1249 Decl *DP = Actions.HandleDeclarator(ParentScope, D,
1254 if (SkipFunctionBodies && (!DP || Actions.canSkipFunctionBody(DP)) &&
1255 trySkippingFunctionBody()) {
1257 return Actions.ActOnSkippedFunctionBody(DP);
1261 LexTemplateFunctionForLateParsing(Toks);
1265 Actions.CheckForFunctionRedefinition(FnD);
1266 Actions.MarkAsLateParsedTemplate(FnD, DP, Toks);
1270 if (CurParsedObjCImpl && !TemplateInfo.TemplateParams &&
1271 (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) || Tok.is(tok::colon)) &&
1272 Actions.CurContext->isTranslationUnit()) {
1278 Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
1284 StashAwayMethodOrFunctionBodyTokens(FuncDecl);
1285 CurParsedObjCImpl->HasCFunction =
true;
1297 StringLiteral *DeletedMessage =
nullptr;
1299 SourceLocation KWLoc;
1304 DiagCompat(KWLoc, diag_compat::defaulted_deleted_function)
1307 DeletedMessage = ParseCXXDeletedFunctionMessage();
1310 DiagCompat(KWLoc, diag_compat::defaulted_deleted_function)
1315 llvm_unreachable(
"function definition after = not 'delete' or 'default'");
1318 if (Tok.is(tok::comma)) {
1319 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
1322 }
else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
1330 Sema::FPFeaturesStateRAII SaveFPFeatures(Actions);
1334 SkipBodyInfo SkipBody;
1336 TemplateInfo.TemplateParams
1337 ? *TemplateInfo.TemplateParams
1339 &SkipBody, BodyKind);
1356 Actions.PopExpressionEvaluationContext();
1368 Actions.SetFunctionBodyKind(Res, KWLoc, BodyKind, DeletedMessage);
1369 Stmt *GeneratedBody = Res ? Res->
getBody() :
nullptr;
1370 Actions.ActOnFinishFunctionBody(Res, GeneratedBody,
false);
1376 if (
const auto *
Template = dyn_cast_if_present<FunctionTemplateDecl>(Res);
1378 Template->getTemplateParameters()->getParam(0)->isImplicit())
1381 CurTemplateDepthTracker.addDepth(1);
1384 if (LateParsedAttrs)
1385 ParseLexedAttributeList(*LateParsedAttrs, Res,
false,
1388 if (SkipFunctionBodies && (!Res || Actions.canSkipFunctionBody(Res)) &&
1389 trySkippingFunctionBody()) {
1391 Actions.ActOnSkippedFunctionBody(Res);
1392 return Actions.ActOnFinishFunctionBody(Res,
nullptr,
false);
1395 return ParseFunctionBody(Res, BodyScope);
1399 if (Tok.is(tok::kw_try))
1400 return ParseFunctionTryBlock(D, BodyScope);
1404 if (Tok.is(tok::colon)) {
1405 ParseConstructorInitializer(D);
1408 if (!Tok.is(tok::l_brace)) {
1412 Actions.ActOnFinishFunctionBody(D,
nullptr);
1416 Actions.ActOnDefaultCtorInitializers(D);
1418 return ParseFunctionStatementBody(D, BodyScope);
1421void Parser::SkipFunctionBody() {
1422 if (Tok.is(tok::equal)) {
1427 bool IsFunctionTryBlock = Tok.is(tok::kw_try);
1428 if (IsFunctionTryBlock)
1432 if (ConsumeAndStoreFunctionPrologue(Skipped))
1436 while (IsFunctionTryBlock && Tok.is(tok::kw_catch)) {
1443void Parser::ParseKNRParamDeclarations(Declarator &D) {
1454 SourceLocation DSStart = Tok.getLocation();
1457 DeclSpec DS(AttrFactory);
1458 ParsedTemplateInfo TemplateInfo;
1459 ParseDeclarationSpecifiers(DS, TemplateInfo);
1467 Diag(DSStart, diag::err_declaration_does_not_declare_param);
1476 diag::err_invalid_storage_class_in_func_decl);
1481 diag::err_invalid_storage_class_in_func_decl);
1488 ParseDeclarator(ParmDeclarator);
1493 MaybeParseGNUAttributes(ParmDeclarator);
1497 Actions.ActOnParamDeclarator(
getCurScope(), ParmDeclarator);
1501 ParmDeclarator.getIdentifier()) {
1505 for (
unsigned i = 0; ; ++i) {
1509 Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
1510 << ParmDeclarator.getIdentifier();
1514 if (FTI.
Params[i].
Ident == ParmDeclarator.getIdentifier()) {
1517 Diag(ParmDeclarator.getIdentifierLoc(),
1518 diag::err_param_redefinition)
1519 << ParmDeclarator.getIdentifier();
1530 if (Tok.isNot(tok::comma))
1533 ParmDeclarator.clear();
1539 ParseDeclarator(ParmDeclarator);
1543 if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration))
1553 Actions.ActOnFinishKNRParamDeclarations(
getCurScope(), D, Tok.getLocation());
1556ExprResult Parser::ParseAsmStringLiteral(
bool ForAsmLabel) {
1559 if (isTokenStringLiteral()) {
1565 if (!SL->isOrdinary()) {
1566 Diag(Tok, diag::err_asm_operand_wide_string_literal)
1567 << SL->isWide() << SL->getSourceRange();
1571 Tok.is(tok::l_paren)) {
1573 SourceLocation RParenLoc;
1576 EnterExpressionEvaluationContext ConstantEvaluated(
1578 AsmString = ParseParenExpression(
1582 AsmString = Actions.ActOnConstantExpression(AsmString);
1587 Diag(Tok, diag::err_asm_expected_string) << (
1588 (
getLangOpts().CPlusPlus11 && !ForAsmLabel) ? 0 : 1);
1591 return Actions.ActOnGCCAsmStmtString(AsmString.
get(), ForAsmLabel);
1594ExprResult Parser::ParseSimpleAsm(
bool ForAsmLabel, SourceLocation *EndLoc) {
1595 assert(Tok.is(tok::kw_asm) &&
"Not an asm!");
1598 if (isGNUAsmQualifier(Tok)) {
1600 SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
1601 PP.getLocForEndOfToken(Tok.getLocation()));
1602 Diag(Tok, diag::err_global_asm_qualifier_ignored)
1603 << GNUAsmQualifiers::getQualifierName(getGNUAsmQualifier(Tok))
1609 if (
T.consumeOpen()) {
1610 Diag(Tok, diag::err_expected_lparen_after) <<
"asm";
1616 if (!
Result.isInvalid()) {
1620 *EndLoc =
T.getCloseLocation();
1623 *EndLoc = Tok.getLocation();
1630TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(
const Token &tok) {
1631 assert(tok.
is(tok::annot_template_id) &&
"Expected template-id token");
1632 TemplateIdAnnotation *
1637void Parser::AnnotateScopeToken(CXXScopeSpec &SS,
bool IsNewAnnotation) {
1640 if (PP.isBacktrackEnabled())
1641 PP.RevertCachedTokens(1);
1643 PP.EnterToken(Tok,
true);
1644 Tok.setKind(tok::annot_cxxscope);
1645 Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
1646 Tok.setAnnotationRange(SS.
getRange());
1651 if (IsNewAnnotation)
1652 PP.AnnotateCachedTokens(Tok);
1656Parser::TryAnnotateName(CorrectionCandidateCallback *CCC,
1658 assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
1660 const bool EnteringContext =
false;
1661 const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1665 ParseOptionalCXXScopeSpecifier(SS,
nullptr,
1670 if (Tok.isNot(tok::identifier) || SS.
isInvalid()) {
1672 AllowImplicitTypename))
1677 IdentifierInfo *Name = Tok.getIdentifierInfo();
1678 SourceLocation NameLoc = Tok.getLocation();
1682 if (isTentativelyDeclared(Name) && SS.
isEmpty()) {
1686 AllowImplicitTypename))
1698 Sema::NameClassification Classification = Actions.ClassifyName(
1706 isTemplateArgumentList(1) == TPResult::False) {
1708 Token FakeNext =
Next;
1709 FakeNext.
setKind(tok::unknown);
1711 Actions.ClassifyName(
getCurScope(), SS, Name, NameLoc, FakeNext,
1712 SS.
isEmpty() ? CCC :
nullptr);
1715 switch (Classification.
getKind()) {
1721 Tok.setIdentifierInfo(Name);
1723 PP.TypoCorrectToken(Tok);
1725 AnnotateScopeToken(SS, !WasScopeAnnotation);
1734 if (TryAltiVecVectorToken())
1739 SourceLocation BeginLoc = NameLoc;
1746 QualType
T = Actions.GetTypeFromParser(Ty);
1751 SourceLocation NewEndLoc;
1753 = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
1758 else if (Tok.is(tok::eof))
1762 Tok.setKind(tok::annot_typename);
1763 setTypeAnnotation(Tok, Ty);
1764 Tok.setAnnotationEndLoc(Tok.getLocation());
1765 Tok.setLocation(BeginLoc);
1766 PP.AnnotateCachedTokens(Tok);
1771 Tok.setKind(tok::annot_overload_set);
1773 Tok.setAnnotationEndLoc(NameLoc);
1776 PP.AnnotateCachedTokens(Tok);
1780 if (TryAltiVecVectorToken())
1785 Tok.setKind(tok::annot_non_type);
1787 Tok.setLocation(NameLoc);
1788 Tok.setAnnotationEndLoc(NameLoc);
1789 PP.AnnotateCachedTokens(Tok);
1791 AnnotateScopeToken(SS, !WasScopeAnnotation);
1796 Tok.setKind(Classification.
getKind() ==
1798 ? tok::annot_non_type_undeclared
1799 : tok::annot_non_type_dependent);
1800 setIdentifierAnnotation(Tok, Name);
1801 Tok.setLocation(NameLoc);
1802 Tok.setAnnotationEndLoc(NameLoc);
1803 PP.AnnotateCachedTokens(Tok);
1805 AnnotateScopeToken(SS, !WasScopeAnnotation);
1809 if (
Next.isNot(tok::less)) {
1813 AnnotateScopeToken(SS, !WasScopeAnnotation);
1821 bool IsConceptName =
1827 if (
Next.is(tok::less))
1829 if (AnnotateTemplateIdToken(
1836 AnnotateScopeToken(SS, !WasScopeAnnotation);
1843 AnnotateScopeToken(SS, !WasScopeAnnotation);
1848 SourceLocation TokenEndLoc = PP.getLocForEndOfToken(PrevTokLocation);
1849 return TokenEndLoc.
isValid() ? TokenEndLoc : Tok.getLocation();
1852bool Parser::TryKeywordIdentFallback(
bool DisableKeyword) {
1853 assert(
Tok.isNot(tok::identifier));
1859 Tok.setKind(tok::identifier);
1863 Diag(
Tok, diag::ext_keyword_as_ident)
1868 Tok.setKind(tok::identifier);
1874 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1875 Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope) ||
1876 Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id) ||
1877 Tok.is(tok::kw___super) || Tok.is(tok::kw_auto) ||
1878 Tok.is(tok::annot_pack_indexing_type)) &&
1879 "Cannot be a type or scope token!");
1881 if (Tok.is(tok::kw_typename)) {
1890 PP.Lex(TypedefToken);
1892 PP.EnterToken(Tok,
true);
1895 Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename);
1907 if (ParseOptionalCXXScopeSpecifier(SS,
nullptr,
1913 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) ||
1914 Tok.is(tok::annot_decltype)) {
1916 if (Tok.is(tok::annot_decltype) ||
1918 Tok.isAnnotation())) {
1919 unsigned DiagID = diag::err_expected_qualified_after_typename;
1923 DiagID = diag::warn_expected_qualified_after_typename;
1924 Diag(Tok.getLocation(), DiagID);
1928 if (Tok.isEditorPlaceholder())
1931 Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
1935 bool TemplateKWPresent =
false;
1936 if (Tok.is(tok::kw_template)) {
1938 TemplateKWPresent =
true;
1942 if (Tok.is(tok::identifier)) {
1944 Diag(Tok.getLocation(),
1945 diag::missing_template_arg_list_after_template_kw);
1948 Ty = Actions.ActOnTypenameType(
getCurScope(), TypenameLoc, SS,
1949 *Tok.getIdentifierInfo(),
1951 }
else if (Tok.is(tok::annot_template_id)) {
1954 Diag(Tok, diag::err_typename_refers_to_non_type_template)
1955 << Tok.getAnnotationRange();
1964 : Actions.ActOnTypenameType(
1968 TemplateArgsPtr, TemplateId->
RAngleLoc);
1970 Diag(Tok, diag::err_expected_type_name_after_typename)
1976 Tok.setKind(tok::annot_typename);
1977 setTypeAnnotation(Tok, Ty);
1978 Tok.setAnnotationEndLoc(EndLoc);
1979 Tok.setLocation(TypenameLoc);
1980 PP.AnnotateCachedTokens(Tok);
1985 bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1989 if (ParseOptionalCXXScopeSpecifier(
1993 IsAddressOfOperand))
1997 AllowImplicitTypename);
2003 if (Tok.is(tok::identifier)) {
2006 *Tok.getIdentifierInfo(), Tok.getLocation(),
getCurScope(), &SS,
2010 true, AllowImplicitTypename)) {
2015 QualType T = Actions.GetTypeFromParser(Ty);
2020 (
T->isObjCObjectType() ||
T->isObjCObjectPointerType())) {
2030 else if (Tok.is(tok::eof))
2036 Tok.setKind(tok::annot_typename);
2037 setTypeAnnotation(Tok, Ty);
2038 Tok.setAnnotationEndLoc(Tok.getLocation());
2039 Tok.setLocation(BeginLoc);
2043 PP.AnnotateCachedTokens(Tok);
2060 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
2061 bool MemberOfUnknownSpecialization;
2066 MemberOfUnknownSpecialization)) {
2070 isTemplateArgumentList(1) != TPResult::False) {
2090 if (Tok.is(tok::annot_template_id)) {
2097 AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
2104 Tok.is(tok::coloncolon)) {
2113 AnnotateScopeToken(SS, IsNewScope);
2119 "Call sites of this function should be guarded by checking for C++");
2123 if (ParseOptionalCXXScopeSpecifier(SS,
nullptr,
2130 AnnotateScopeToken(SS,
true);
2134bool Parser::isTokenEqualOrEqualTypo() {
2140 case tok::starequal:
2141 case tok::plusequal:
2142 case tok::minusequal:
2143 case tok::exclaimequal:
2144 case tok::slashequal:
2145 case tok::percentequal:
2146 case tok::lessequal:
2147 case tok::lesslessequal:
2148 case tok::greaterequal:
2149 case tok::greatergreaterequal:
2150 case tok::caretequal:
2151 case tok::pipeequal:
2152 case tok::equalequal:
2153 Diag(
Tok, diag::err_invalid_token_after_declarator_suggest_equal)
2162SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
2163 assert(Tok.is(tok::code_completion));
2164 PrevTokLocation = Tok.getLocation();
2167 if (S->isFunctionScope()) {
2169 Actions.CodeCompletion().CodeCompleteOrdinaryName(
2171 return PrevTokLocation;
2174 if (S->isClassScope()) {
2176 Actions.CodeCompletion().CodeCompleteOrdinaryName(
2178 return PrevTokLocation;
2183 Actions.CodeCompletion().CodeCompleteOrdinaryName(
2185 return PrevTokLocation;
2190void Parser::CodeCompleteDirective(
bool InConditional) {
2191 Actions.CodeCompletion().CodeCompletePreprocessorDirective(InConditional);
2195 Actions.CodeCompletion().CodeCompleteInPreprocessorConditionalExclusion(
2199void Parser::CodeCompleteMacroName(
bool IsDefinition) {
2200 Actions.CodeCompletion().CodeCompletePreprocessorMacroName(IsDefinition);
2204 Actions.CodeCompletion().CodeCompletePreprocessorExpression();
2207void Parser::CodeCompleteMacroArgument(IdentifierInfo *
Macro,
2208 MacroInfo *MacroInfo,
2209 unsigned ArgumentIndex) {
2210 Actions.CodeCompletion().CodeCompletePreprocessorMacroArgument(
2214void Parser::CodeCompleteIncludedFile(llvm::StringRef Dir,
bool IsAngled) {
2215 Actions.CodeCompletion().CodeCompleteIncludedFile(Dir, IsAngled);
2219 Actions.CodeCompletion().CodeCompleteNaturalLanguage();
2222void Parser::CodeCompleteModuleImport(SourceLocation ImportLoc,
2224 Actions.CodeCompletion().CodeCompleteModuleImport(ImportLoc, Path);
2227bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition&
Result) {
2228 assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
2229 "Expected '__if_exists' or '__if_not_exists'");
2230 Result.IsIfExists = Tok.is(tok::kw___if_exists);
2234 if (
T.consumeOpen()) {
2235 Diag(Tok, diag::err_expected_lparen_after)
2236 << (
Result.IsIfExists?
"__if_exists" :
"__if_not_exists");
2242 ParseOptionalCXXScopeSpecifier(
Result.SS,
nullptr,
2247 if (
Result.SS.isInvalid()) {
2253 SourceLocation TemplateKWLoc;
2258 false, &TemplateKWLoc,
2264 if (
T.consumeClose())
2292void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
2293 IfExistsCondition
Result;
2294 if (ParseMicrosoftIfExistsCondition(
Result))
2298 if (
Braces.consumeOpen()) {
2299 Diag(Tok, diag::err_expected) << tok::l_brace;
2303 switch (
Result.Behavior) {
2309 llvm_unreachable(
"Cannot have a dependent external declaration");
2318 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
2319 ParsedAttributes Attrs(AttrFactory);
2320 MaybeParseCXX11Attributes(Attrs);
2321 ParsedAttributes EmptyDeclSpecAttrs(AttrFactory);
2324 Actions.getASTConsumer().HandleTopLevelDecl(
Result.get());
2331 Token Introducer = Tok;
2332 SourceLocation StartLoc = Introducer.
getLocation();
2338 assert(Tok.is(tok::kw_module) &&
"not a module declaration");
2344 DiagnoseAndSkipCXX11Attributes();
2347 if (
getLangOpts().CPlusPlusModules && Tok.is(tok::semi)) {
2351 Diag(StartLoc, diag::err_global_module_introducer_not_at_start)
2352 << SourceRange(StartLoc, SemiLoc);
2356 Diag(StartLoc, diag::err_module_fragment_exported)
2360 return Actions.ActOnGlobalModuleFragmentDecl(ModuleLoc);
2364 if (
getLangOpts().CPlusPlusModules && Tok.is(tok::colon) &&
2367 Diag(StartLoc, diag::err_module_fragment_exported)
2372 DiagnoseAndSkipCXX11Attributes();
2373 ExpectAndConsumeSemi(diag::err_private_module_fragment_expected_semi);
2377 return Actions.ActOnPrivateModuleFragmentDecl(ModuleLoc, PrivateLoc);
2380 SmallVector<IdentifierLoc, 2> Path;
2381 if (ParseModuleName(ModuleLoc, Path,
false))
2385 SmallVector<IdentifierLoc, 2> Partition;
2386 if (Tok.is(tok::colon)) {
2389 Diag(ColonLoc, diag::err_unsupported_module_partition)
2390 << SourceRange(ColonLoc, Partition.back().getLoc());
2392 else if (ParseModuleName(ModuleLoc, Partition,
false))
2396 if (Tok.isNoneOf(tok::semi, tok::l_square, tok::eof)) {
2397 Diag(Tok, diag::err_unexpected_tok_after_module_name)
2398 << PP.getSpelling(Tok);
2403 ParsedAttributes Attrs(AttrFactory);
2404 MaybeParseCXX11Attributes(Attrs);
2405 ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_module_attr,
2406 diag::err_keyword_not_module_attr,
2410 if (ExpectAndConsumeSemi(diag::err_expected_semi_after_module_or_import,
2414 return Actions.ActOnModuleDecl(StartLoc, ModuleLoc, MDK, Path, Partition,
2419Decl *Parser::ParseModuleImport(SourceLocation AtLoc,
2421 SourceLocation StartLoc = AtLoc.
isInvalid() ? Tok.getLocation() : AtLoc;
2423 SourceLocation ExportLoc;
2426 assert((AtLoc.
isInvalid() ? Tok.is(tok::kw_import)
2427 : Tok.isObjCAtKeyword(tok::objc_import)) &&
2428 "Improper start to module import");
2429 bool IsObjCAtImport = Tok.isObjCAtKeyword(tok::objc_import);
2433 SmallVector<IdentifierLoc, 2> Path;
2434 bool IsPartition =
false;
2435 Module *HeaderUnit =
nullptr;
2436 if (Tok.is(tok::header_name)) {
2441 }
else if (Tok.is(tok::annot_header_unit)) {
2443 HeaderUnit =
reinterpret_cast<Module *
>(Tok.getAnnotationValue());
2444 ConsumeAnnotationToken();
2445 }
else if (Tok.is(tok::colon)) {
2448 Diag(ColonLoc, diag::err_unsupported_module_partition)
2449 << SourceRange(ColonLoc, Path.back().getLoc());
2451 else if (ParseModuleName(ColonLoc, Path,
true))
2456 if (ParseModuleName(ImportLoc, Path,
true))
2460 ParsedAttributes Attrs(AttrFactory);
2461 MaybeParseCXX11Attributes(Attrs);
2463 ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_import_attr,
2464 diag::err_keyword_not_import_attr,
2471 bool IsCXX20NamedModuleImport =
2472 getLangOpts().CPlusPlusModules && !IsObjCAtImport && !Path.empty();
2474 if (PP.hadModuleLoaderFatalFailure() && !IsCXX20NamedModuleImport) {
2481 bool SeenError =
true;
2482 switch (ImportState) {
2494 Diag(ImportLoc, diag::err_partition_import_outside_module);
2506 if (IsPartition || (HeaderUnit && HeaderUnit->
Kind !=
2508 Diag(ImportLoc, diag::err_import_in_wrong_fragment)
2517 Diag(ImportLoc, diag::err_import_not_allowed_here);
2533 bool LexedSemi =
false;
2536 !ExpectAndConsumeSemi(diag::err_expected_semi_after_module_or_import,
2539 LexedSemi = !ExpectAndConsumeSemi(diag::err_module_expected_semi);
2550 Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, HeaderUnit);
2551 else if (!Path.empty())
2552 Import = Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Path,
2559 if (IsObjCAtImport && AtLoc.
isValid()) {
2560 auto &SrcMgr = PP.getSourceManager();
2561 auto FE = SrcMgr.getFileEntryRefForID(SrcMgr.getFileID(AtLoc));
2562 if (FE && llvm::sys::path::parent_path(FE->getDir().getName())
2563 .ends_with(
".framework"))
2564 Diags.Report(AtLoc, diag::warn_atimport_in_framework_header);
2570bool Parser::ParseModuleName(SourceLocation UseLoc,
2571 SmallVectorImpl<IdentifierLoc> &Path,
2573 if (Tok.isNot(tok::annot_module_name)) {
2577 ModuleNameLoc *NameLoc =
2578 static_cast<ModuleNameLoc *
>(Tok.getAnnotationValue());
2581 ConsumeAnnotationToken();
2585bool Parser::parseMisplacedModuleImport() {
2587 switch (Tok.getKind()) {
2588 case tok::annot_module_end:
2592 if (MisplacedModuleBeginCount) {
2593 --MisplacedModuleBeginCount;
2594 Actions.ActOnAnnotModuleEnd(
2596 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
2597 ConsumeAnnotationToken();
2604 case tok::annot_module_begin:
2606 Actions.ActOnAnnotModuleBegin(
2608 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
2609 ConsumeAnnotationToken();
2610 ++MisplacedModuleBeginCount;
2612 case tok::annot_module_include:
2615 Actions.ActOnAnnotModuleInclude(
2617 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
2618 ConsumeAnnotationToken();
2628void Parser::diagnoseUseOfC11Keyword(
const Token &Tok) {
2633 : diag::ext_c11_feature)
2637bool BalancedDelimiterTracker::diagnoseOverflow() {
2638 P.Diag(P.Tok, diag::err_bracket_depth_exceeded)
2639 << P.getLangOpts().BracketDepth;
2640 P.Diag(P.Tok, diag::note_bracket_depth);
2648 LOpen = P.Tok.getLocation();
2649 if (P.ExpectAndConsume(Kind, DiagID, Msg)) {
2650 if (SkipToTok != tok::unknown)
2655 if (getDepth() < P.getLangOpts().BracketDepth)
2658 return diagnoseOverflow();
2661bool BalancedDelimiterTracker::diagnoseMissingClose() {
2662 assert(!P.Tok.is(Close) &&
"Should have consumed closing delimiter");
2664 if (P.Tok.is(tok::annot_module_end))
2665 P.Diag(P.Tok, diag::err_missing_before_module_end) << Close;
2667 P.Diag(P.Tok, diag::err_expected) << Close;
2668 P.Diag(LOpen, diag::note_matching) << Kind;
2672 if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) &&
2673 P.Tok.isNot(tok::r_square) &&
2674 P.SkipUntil(Close, FinalToken,
2677 LClose = P.ConsumeAnyToken();
Defines the clang::ASTContext interface.
This file provides some common utility functions for processing Lambda related AST Constructs.
static Decl::Kind getKind(const Decl *D)
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
static bool IsCommonTypo(tok::TokenKind ExpectedTok, const Token &Tok)
static bool HasFlagsSet(Parser::SkipUntilFlags L, Parser::SkipUntilFlags R)
Defines the clang::Preprocessor interface.
This file declares facilities that support code completion.
Defines a utilitiy for warning once when close to out of stack space.
Defines the clang::TokenKind enum and support functions.
bool expectAndConsume(unsigned DiagID=diag::err_expected, const char *Msg="", tok::TokenKind SkipToTok=tok::unknown)
Represents a C++ nested-name-specifier or a global scope specifier.
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
SourceRange getRange() const
SourceLocation getBeginLoc() const
bool isInvalid() const
An error occurred during parsing of the scope specifier.
bool isEmpty() const
No scope specifier.
virtual void CodeCompletePreprocessorExpression()
Callback invoked when performing code completion in a preprocessor expression, such as the condition ...
virtual void CodeCompleteNaturalLanguage()
Callback invoked when performing code completion in a part of the file where we expect natural langua...
virtual void CodeCompleteInConditionalExclusion()
Callback invoked when performing code completion within a block of code that was excluded due to prep...
void ClearStorageClassSpecs()
TST getTypeSpecType() const
SourceLocation getStorageClassSpecLoc() const
SCS getStorageClassSpec() const
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
SourceLocation getBeginLoc() const LLVM_READONLY
SourceRange getSourceRange() const LLVM_READONLY
void SetRangeEnd(SourceLocation Loc)
void SetRangeStart(SourceLocation Loc)
TSCS getThreadStorageClassSpec() const
ParsedAttributes & getAttributes()
static const TST TST_enum
static bool isDeclRep(TST T)
void takeAttributesAppendingingFrom(ParsedAttributes &attrs)
bool hasTagDefinition() const
unsigned getParsedSpecifiers() const
Return a bitmask of which flavors of specifiers this DeclSpec includes.
static const TSCS TSCS_unspecified
static const char * getSpecifierName(DeclSpec::TST T, const PrintingPolicy &Policy)
Turn a type-specifier-type into a string like "_Bool" or "union".
SourceLocation getThreadStorageClassSpecLoc() const
Decl * getRepAsDecl() const
static const TST TST_unspecified
bool isEmpty() const
isEmpty - Return true if this declaration specifier is completely empty: no tokens were parsed in the...
SourceLocation getTypeSpecTypeLoc() const
@ PQ_StorageClassSpecifier
Decl - This represents one declaration (or definition), e.g.
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
virtual Stmt * getBody() const
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
void SetRangeBegin(SourceLocation Loc)
SetRangeBegin - Set the start of the source range to Loc, unless it's invalid.
const ParsedAttributes & getAttributes() const
SourceLocation getIdentifierLoc() const
void setFunctionDefinitionKind(FunctionDefinitionKind Val)
void SetRangeEnd(SourceLocation Loc)
SetRangeEnd - Set the end of the source range to Loc, unless it's invalid.
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
A little helper class used to produce diagnostics.
static unsigned getCompatDiagId(const LangOptions &LangOpts, unsigned CompatDiagId)
Get the appropriate diagnostic Id to use for issuing a compatibility diagnostic.
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
One of these records is kept for each identifier that is lexed.
tok::TokenKind getTokenID() const
If this is a source-language token (e.g.
void revertTokenIDToIdentifier()
Revert TokenID to tok::identifier; used for GNU libstdc++ 4.2 compatibility.
A simple pair of identifier info and location.
Describes a module import declaration, which makes the contents of the named module visible in the cu...
ModuleIdPath getModuleIdPath() const
Describes a module or submodule.
ModuleKind Kind
The kind of this module.
bool isHeaderUnit() const
Is this module a header unit.
@ ModuleHeaderUnit
This is a C++20 header unit.
static OpaquePtr make(TemplateName P)
RAII object that makes sure paren/bracket/brace count is correct after declaration/statement parsing,...
static const ParsedAttributesView & none()
ParsedAttributes - A collection of parsed attributes.
ParseScope - Introduces a new scope for parsing.
Parser - This implements a parser for the C family of languages.
bool TryAnnotateTypeOrScopeToken(ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No, bool IsAddressOfOperand=false)
TryAnnotateTypeOrScopeToken - If the current token position is on a typename (possibly qualified in C...
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
SourceLocation getEndOfPreviousToken() const
bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS, bool IsNewScope, ImplicitTypenameContext AllowImplicitTypename)
Try to annotate a type or scope token, having already parsed an optional scope specifier.
DiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId)
ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral=false)
ParseStringLiteralExpression - This handles the various token types that form string literals,...
SourceLocation ConsumeToken()
ConsumeToken - Consume the current 'peek token' and lex the next one.
Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies)
void EnterScope(unsigned ScopeFlags)
EnterScope - Start a new scope.
bool ParseUnqualifiedId(CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors, bool EnteringContext, bool AllowDestructorName, bool AllowConstructorName, bool AllowDeductionGuide, SourceLocation *TemplateKWLoc, UnqualifiedId &Result)
Parse a C++ unqualified-id (or a C identifier), which describes the name of an entity.
DeclGroupPtrTy ParseOpenACCDirectiveDecl(AccessSpecifier &AS, ParsedAttributes &Attrs, DeclSpec::TST TagType, Decl *TagDecl)
Parse OpenACC directive on a declaration.
SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok=false)
ConsumeAnyToken - Dispatch to the right Consume* method based on the current token type.
bool TryConsumeToken(tok::TokenKind Expected)
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Scope * getCurScope() const
OpaquePtr< TemplateName > TemplateTy
bool SkipUntil(tok::TokenKind T, SkipUntilFlags Flags=static_cast< SkipUntilFlags >(0))
SkipUntil - Read tokens until we get to the specified token, then consume it (unless StopBeforeMatch ...
void SkipMalformedDecl()
SkipMalformedDecl - Read tokens until we get to some likely good stopping point for skipping past a s...
friend class PoisonSEHIdentifiersRAIIObject
void ExitScope()
ExitScope - Pop a scope off the scope stack.
const LangOptions & getLangOpts() const
bool ParseFirstTopLevelDecl(DeclGroupPtrTy &Result, Sema::ModuleImportState &ImportState)
Parse the first top-level declaration in a translation unit.
SkipUntilFlags
Control flags for SkipUntil functions.
@ StopBeforeMatch
Stop skipping at specified token, but don't skip the token itself.
@ StopAtCodeCompletion
Stop at code completion.
@ StopAtSemi
Stop skipping at semicolon.
bool MightBeCXXScopeToken()
const Token & NextToken()
NextToken - This peeks ahead one token and returns it without consuming it.
friend class BalancedDelimiterTracker
SmallVector< TemplateParameterList *, 4 > TemplateParameterLists
void Initialize()
Initialize - Warm up the parser.
bool TryAnnotateCXXScopeToken(bool EnteringContext=false)
TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only annotates C++ scope specifiers and ...
A class for parsing a DeclSpec.
const ParsingDeclSpec & getDeclSpec() const
ParsingDeclSpec & getMutableDeclSpec() const
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
StringRef getSpelling(SourceLocation loc, SmallVectorImpl< char > &buffer, bool *invalid=nullptr) const
Return the 'spelling' of the token at the given location; does not go up to the spelling location or ...
bool isCodeCompletionEnabled() const
Determine if we are performing code completion.
bool isCodeCompletionReached() const
Returns true if code-completion is enabled and we have hit the code-completion point.
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Computes the source location just past the end of the token at this source location.
A (possibly-)qualified type.
Scope - A scope is a transient data structure that is used while parsing the program.
void Init(Scope *parent, unsigned flags)
Init - This is used by the parser to implement scope caching.
const Scope * getParent() const
getParent - Return the scope that this is nested in.
@ FunctionPrototypeScope
This is a scope that corresponds to the parameters within a function prototype.
@ CompoundStmtScope
This is a compound statement scope.
@ FunctionDeclarationScope
This is a scope that corresponds to the parameters within a function prototype for a function declara...
@ FnScope
This indicates that the scope corresponds to a function, which means that labels are set here.
@ DeclScope
This is a scope that can contain a declaration.
ParserCompletionContext
Describes the context in which code completion occurs.
@ PCC_TopLevelOrExpression
Code completion occurs at top-level in a REPL session.
@ PCC_Class
Code completion occurs within a class, struct, or union.
@ PCC_ObjCImplementation
Code completion occurs within an Objective-C implementation or category implementation.
@ PCC_Namespace
Code completion occurs at top-level or namespace context.
@ PCC_RecoveryInFunction
Code completion occurs within the body of a function on a recovery path, where we do not have a speci...
ExprResult getExpression() const
NameClassificationKind getKind() const
NamedDecl * getNonTypeDecl() const
TemplateName getTemplateName() const
ParsedType getType() const
TemplateNameKind getTemplateNameKind() const
Sema - This implements semantic analysis and AST building for C.
@ Interface
'export module X;'
@ Implementation
'module X;'
@ Other
C++26 [dcl.fct.def.general]p1 function-body: ctor-initializer[opt] compound-statement function-try-bl...
@ Delete
deleted-function-body
ModuleImportState
An enumeration to represent the transition of states in parsing module fragments and imports.
@ PrivateFragmentImportFinished
after 'module :private;' but a non-import decl has already been seen.
@ ImportFinished
after any non-import decl.
@ PrivateFragmentImportAllowed
after 'module :private;' but before any non-import decl.
@ FirstDecl
Parsing the first decl in a TU.
@ GlobalFragment
after 'module;' but before 'module X;'
@ NotACXX20Module
Not a C++20 TU, or an invalid state was found.
@ ImportAllowed
after 'module X;' but before any non-import decl.
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Represents a C++ template name within the type system.
Token - This structure provides full information about a lexed token.
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
void setKind(tok::TokenKind K)
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
void * getAnnotationValue() const
tok::TokenKind getKind() const
bool hasSeenNoTrivialPPDirective() const
bool isObjCObjectType() const
bool isObjCObjectPointerType() const
Represents a C++ unqualified-id that has been parsed.
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
const char * getKeywordSpelling(TokenKind Kind) LLVM_READNONE
Determines the spelling of simple keyword and contextual keyword tokens like 'int' and 'dynamic_cast'...
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
const char * getPunctuatorSpelling(TokenKind Kind) LLVM_READNONE
Determines the spelling of simple punctuation tokens like '!
Top level wrappers for InstallAPI frontend operations.
TypeSpecifierType
Specifies the kind of type.
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
ArrayRef< IdentifierLoc > ModuleIdPath
A sequence of identifier/location pairs used to describe a particular module or submodule,...
@ Unresolved
The identifier can't be resolved.
@ Success
Annotation was successful.
@ Error
Annotation has failed and emitted an error.
@ TentativeDecl
The identifier is a tentatively-declared name.
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
ActionResult< Decl * > DeclResult
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ Dependent
Parse the block as a dependent block, which may be used in some template instantiations but not other...
@ Skip
Skip the block entirely; this code is never used.
@ Parse
Parse the block; this code is always used.
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
bool isLambdaCallOperator(const CXXMethodDecl *MD)
@ Result
The result type of a method or function.
ActionResult< ParsedType > TypeResult
const FunctionProtoType * T
@ Template
We are parsing a template declaration.
@ FunctionTemplate
The name was classified as a function template name.
@ Keyword
The name has been typo-corrected to a keyword.
@ DependentNonType
The name denotes a member of a dependent type that could not be resolved.
@ UndeclaredTemplate
The name was classified as an ADL-only function template name.
@ NonType
The name was classified as a specific non-type, non-template declaration.
@ Unknown
This name is not a type or template in this context, but might be something else.
@ Error
Classification failed; an error has been produced.
@ Type
The name was classified as a type.
@ TypeTemplate
The name was classified as a template whose specializations are types.
@ Concept
The name was classified as a concept name.
@ OverloadSet
The name was classified as an overload set, and an expression representing that overload set has been...
@ UndeclaredNonType
The name was classified as an ADL-only function name.
@ VarTemplate
The name was classified as a variable template name.
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
ExtraSemiKind
The kind of extra semi diagnostic to emit.
@ AfterMemberFunctionDefinition
TemplateNameKind
Specifies the kind of template name that an identifier refers to.
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
@ TNK_Undeclared_template
Lookup for the name failed, but we're assuming it was a template name anyway.
@ Dependent
The name is a dependent name, so the results will differ from one instantiation to the next.
@ Exists
The symbol exists.
@ Error
An error occurred.
@ DoesNotExist
The symbol does not exist.
U cast(CodeGen::Address addr)
SmallVector< Token, 4 > CachedTokens
A set of tokens that has been cached for later parsing.
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
ParenParseOption
ParenParseOption - Control what ParseParenExpression will parse.
ActionResult< Expr * > ExprResult
@ Braces
New-expression has a C++11 list-initializer.
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
bool isKNRPrototype() const
isKNRPrototype - Return true if this is a K&R style identifier list, like "void foo(a,...
const IdentifierInfo * Ident
Information about a template-id annotation token.
const IdentifierInfo * Name
FIXME: Temporarily stores the name of a specialization.
TemplateNameKind Kind
The kind of template that Template refers to.
unsigned NumArgs
NumArgs - The number of template arguments.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
SourceLocation TemplateKWLoc
TemplateKWLoc - The location of the template keyword.
bool mightBeType() const
Determine whether this might be a type template.
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.