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);
91 return Diags.Report(Loc, DiagID);
95 return Diag(Tok.getLocation(), DiagID);
99 unsigned CompatDiagId) {
104 return DiagCompat(Tok.getLocation(), CompatDiagId);
123 switch (ExpectedTok) {
125 return Tok.is(tok::colon) ||
Tok.is(tok::comma);
126 default:
return false;
130bool Parser::ExpectAndConsume(
tok::TokenKind ExpectedTok,
unsigned DiagID,
132 if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) {
139 SourceLocation Loc = Tok.getLocation();
141 DiagnosticBuilder DB =
Diag(Loc, DiagID);
144 if (DiagID == diag::err_expected)
146 else if (DiagID == diag::err_expected_after)
147 DB << Msg << ExpectedTok;
157 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
158 const char *Spelling =
nullptr;
162 DiagnosticBuilder DB =
166 if (DiagID == diag::err_expected)
168 else if (DiagID == diag::err_expected_after)
169 DB << Msg << ExpectedTok;
176bool Parser::ExpectAndConsumeSemi(
unsigned DiagID, StringRef TokenUsed) {
180 if (Tok.is(tok::code_completion)) {
181 handleUnexpectedCodeCompletionToken();
185 if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) &&
187 Diag(Tok, diag::err_extraneous_token_before_semi)
188 << PP.getSpelling(Tok)
195 return ExpectAndConsume(tok::semi, DiagID , TokenUsed);
198bool Parser::isLikelyAtStartOfNewDeclaration() {
199 return Tok.isAtStartOfLine() &&
204 if (!Tok.is(tok::semi))
return;
206 bool HadMultipleSemis =
false;
207 SourceLocation StartLoc = Tok.getLocation();
208 SourceLocation EndLoc = Tok.getLocation();
211 while ((Tok.is(tok::semi) && !Tok.isAtStartOfLine())) {
212 HadMultipleSemis =
true;
213 EndLoc = Tok.getLocation();
221 Diag(StartLoc, diag::warn_cxx98_compat_top_level_semi)
224 Diag(StartLoc, diag::ext_extra_semi_cxx11)
230 Diag(StartLoc, diag::ext_extra_semi)
233 TST, Actions.getASTContext().getPrintingPolicy())
237 Diag(StartLoc, diag::warn_extra_semi_after_mem_fn_def)
241bool Parser::expectIdentifier() {
242 if (Tok.is(tok::identifier))
244 if (
const auto *II = Tok.getIdentifierInfo()) {
246 Diag(Tok, diag::err_expected_token_instead_of_objcxx_keyword)
247 << tok::identifier << Tok.getIdentifierInfo();
252 Diag(Tok, diag::err_expected) << tok::identifier;
260 SourceLocation SecondTokLoc = Tok.getLocation();
265 PP.getSourceManager().getFileID(FirstTokLoc) !=
266 PP.getSourceManager().getFileID(SecondTokLoc)) {
267 Diag(FirstTokLoc, diag::warn_compound_token_split_by_macro)
268 << (FirstTokKind == Tok.getKind()) << FirstTokKind << Tok.getKind()
269 <<
static_cast<int>(Op) << SourceRange(FirstTokLoc);
270 Diag(SecondTokLoc, diag::note_compound_token_split_second_token_here)
271 << (FirstTokKind == Tok.getKind()) << Tok.getKind()
272 << SourceRange(SecondTokLoc);
277 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
278 SourceLocation SpaceLoc = PP.getLocForEndOfToken(FirstTokLoc);
280 SpaceLoc = FirstTokLoc;
281 Diag(SpaceLoc, diag::warn_compound_token_split_by_whitespace)
282 << (FirstTokKind == Tok.getKind()) << FirstTokKind << Tok.getKind()
283 <<
static_cast<int>(Op) << SourceRange(FirstTokLoc, SecondTokLoc);
293 return (
static_cast<unsigned>(L) &
static_cast<unsigned>(R)) != 0;
299 bool isFirstTokenSkipped =
true;
302 for (
unsigned i = 0, NumToks = Toks.size(); i != NumToks; ++i) {
303 if (Tok.is(Toks[i])) {
316 if (Toks.size() == 1 && Toks[0] == tok::eof &&
319 while (Tok.isNot(tok::eof))
324 switch (Tok.getKind()) {
329 case tok::annot_pragma_openmp:
330 case tok::annot_attr_openmp:
331 case tok::annot_pragma_openmp_end:
333 if (OpenMPDirectiveParsing)
335 ConsumeAnnotationToken();
337 case tok::annot_pragma_openacc:
338 case tok::annot_pragma_openacc_end:
340 if (OpenACCDirectiveParsing)
342 ConsumeAnnotationToken();
344 case tok::annot_module_begin:
345 case tok::annot_module_end:
346 case tok::annot_module_include:
347 case tok::annot_repl_input_end:
353 case tok::code_completion:
355 handleUnexpectedCodeCompletionToken();
397 if (ParenCount && !isFirstTokenSkipped)
402 if (BracketCount && !isFirstTokenSkipped)
407 if (BraceCount && !isFirstTokenSkipped)
421 isFirstTokenSkipped =
false;
430 if (NumCachedScopes) {
431 Scope *N = ScopeCache[--NumCachedScopes];
433 Actions.CurScope = N;
444 Actions.ActOnPopScope(Tok.getLocation(),
getCurScope());
447 Actions.CurScope = OldScope->
getParent();
449 if (NumCachedScopes == ScopeCacheSize)
452 ScopeCache[NumCachedScopes++] = OldScope;
455Parser::ParseScopeFlags::ParseScopeFlags(
Parser *
Self,
unsigned ScopeFlags,
457 : CurScope(ManageFlags ?
Self->getCurScope() :
nullptr) {
459 OldFlags = CurScope->getFlags();
460 CurScope->setFlags(ScopeFlags);
464Parser::ParseScopeFlags::~ParseScopeFlags() {
466 CurScope->setFlags(OldFlags);
477 Actions.CurScope =
nullptr;
480 for (
unsigned i = 0, e = NumCachedScopes; i != e; ++i)
481 delete ScopeCache[i];
483 resetPragmaHandlers();
485 PP.removeCommentHandler(CommentSemaHandler.get());
487 PP.clearCodeCompletionHandler();
489 DestroyTemplateIds();
492void Parser::Initialize() {
494 assert(
getCurScope() ==
nullptr &&
"A scope is already active?");
521 Ident_instancetype =
nullptr;
522 Ident_final =
nullptr;
523 Ident_sealed =
nullptr;
524 Ident_abstract =
nullptr;
525 Ident_override =
nullptr;
526 Ident_GNU_final =
nullptr;
530 Ident_vector =
nullptr;
531 Ident_bool =
nullptr;
532 Ident_Bool =
nullptr;
533 Ident_pixel =
nullptr;
540 Ident_pixel = &PP.getIdentifierTable().get(
"pixel");
542 Ident_introduced =
nullptr;
543 Ident_deprecated =
nullptr;
544 Ident_obsoleted =
nullptr;
545 Ident_unavailable =
nullptr;
546 Ident_strict =
nullptr;
547 Ident_replacement =
nullptr;
549 Ident_language = Ident_defined_in = Ident_generated_declaration = Ident_USR =
552 Ident__except =
nullptr;
554 Ident__exception_code = Ident__exception_info =
nullptr;
555 Ident__abnormal_termination = Ident___exception_code =
nullptr;
556 Ident___exception_info = Ident___abnormal_termination =
nullptr;
557 Ident_GetExceptionCode = Ident_GetExceptionInfo =
nullptr;
558 Ident_AbnormalTermination =
nullptr;
561 Ident__exception_info = PP.getIdentifierInfo(
"_exception_info");
562 Ident___exception_info = PP.getIdentifierInfo(
"__exception_info");
563 Ident_GetExceptionInfo = PP.getIdentifierInfo(
"GetExceptionInformation");
564 Ident__exception_code = PP.getIdentifierInfo(
"_exception_code");
565 Ident___exception_code = PP.getIdentifierInfo(
"__exception_code");
566 Ident_GetExceptionCode = PP.getIdentifierInfo(
"GetExceptionCode");
567 Ident__abnormal_termination = PP.getIdentifierInfo(
"_abnormal_termination");
568 Ident___abnormal_termination = PP.getIdentifierInfo(
"__abnormal_termination");
569 Ident_AbnormalTermination = PP.getIdentifierInfo(
"AbnormalTermination");
571 PP.SetPoisonReason(Ident__exception_code,diag::err_seh___except_block);
572 PP.SetPoisonReason(Ident___exception_code,diag::err_seh___except_block);
573 PP.SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block);
574 PP.SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter);
575 PP.SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter);
576 PP.SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter);
577 PP.SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block);
578 PP.SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block);
579 PP.SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block);
582 Actions.Initialize();
585void Parser::DestroyTemplateIds() {
586 for (TemplateIdAnnotation *Id : TemplateIds)
593 Actions.ActOnStartOfTranslationUnit();
605 if (NoTopLevelDecls && !Actions.getASTContext().getExternalSource() &&
607 Diag(diag::ext_empty_translation_unit);
609 return NoTopLevelDecls;
614 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*
this);
617 switch (Tok.getKind()) {
618 case tok::annot_pragma_unused:
619 HandlePragmaUnused();
635 Result = ParseModuleDecl(ImportState);
645 case tok::annot_module_include: {
646 auto Loc = Tok.getLocation();
647 Module *Mod =
reinterpret_cast<Module *
>(Tok.getAnnotationValue());
651 Actions.ActOnAnnotModuleInclude(Loc, Mod);
658 ConsumeAnnotationToken();
662 case tok::annot_module_begin:
663 Actions.ActOnAnnotModuleBegin(
665 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
666 ConsumeAnnotationToken();
670 case tok::annot_module_end:
671 Actions.ActOnAnnotModuleEnd(
673 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
674 ConsumeAnnotationToken();
679 case tok::annot_repl_input_end:
681 if (PP.getMaxTokens() != 0 && PP.getTokenCount() > PP.getMaxTokens()) {
682 PP.Diag(Tok.getLocation(), diag::warn_max_tokens_total)
683 << PP.getTokenCount() << PP.getMaxTokens();
686 PP.Diag(OverrideLoc, diag::note_max_tokens_total_override);
691 Actions.SetLateTemplateParser(LateTemplateParserCallback,
this);
692 Actions.ActOnEndOfTranslationUnit();
705 while (MaybeParseCXX11Attributes(DeclAttrs) ||
706 MaybeParseGNUAttributes(DeclSpecAttrs))
709 Result = ParseExternalDeclaration(DeclAttrs, DeclSpecAttrs);
719 else if (ImportState ==
731 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*
this);
739 Decl *SingleDecl =
nullptr;
740 switch (
Tok.getKind()) {
741 case tok::annot_pragma_vis:
742 HandlePragmaVisibility();
744 case tok::annot_pragma_pack:
747 case tok::annot_pragma_msstruct:
748 HandlePragmaMSStruct();
750 case tok::annot_pragma_align:
753 case tok::annot_pragma_weak:
756 case tok::annot_pragma_weakalias:
757 HandlePragmaWeakAlias();
759 case tok::annot_pragma_redefine_extname:
760 HandlePragmaRedefineExtname();
762 case tok::annot_pragma_fp_contract:
763 HandlePragmaFPContract();
765 case tok::annot_pragma_fenv_access:
766 case tok::annot_pragma_fenv_access_ms:
767 HandlePragmaFEnvAccess();
769 case tok::annot_pragma_fenv_round:
770 HandlePragmaFEnvRound();
772 case tok::annot_pragma_cx_limited_range:
773 HandlePragmaCXLimitedRange();
775 case tok::annot_pragma_float_control:
776 HandlePragmaFloatControl();
778 case tok::annot_pragma_fp:
781 case tok::annot_pragma_opencl_extension:
782 HandlePragmaOpenCLExtension();
784 case tok::annot_attr_openmp:
785 case tok::annot_pragma_openmp: {
787 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
789 case tok::annot_pragma_openacc: {
794 case tok::annot_pragma_ms_pointers_to_members:
795 HandlePragmaMSPointersToMembers();
797 case tok::annot_pragma_ms_vtordisp:
798 HandlePragmaMSVtorDisp();
800 case tok::annot_pragma_ms_pragma:
801 HandlePragmaMSPragma();
803 case tok::annot_pragma_dump:
806 case tok::annot_pragma_attribute:
807 HandlePragmaAttribute();
809 case tok::annot_pragma_export:
810 HandlePragmaExport();
815 Actions.ActOnEmptyDeclaration(
getCurScope(), Attrs, Tok.getLocation());
819 Diag(Tok, diag::err_extraneous_closing_brace);
823 Diag(Tok, diag::err_expected_external_declaration);
825 case tok::kw___extension__: {
827 ExtensionRAIIObject O(Diags);
829 return ParseExternalDeclaration(Attrs, DeclSpecAttrs);
832 ProhibitAttributes(Attrs);
834 SourceLocation StartLoc = Tok.getLocation();
835 SourceLocation EndLoc;
844 if (!SL->getString().trim().empty())
845 Diag(StartLoc, diag::err_gnu_inline_asm_disabled);
848 ExpectAndConsume(tok::semi, diag::err_expected_after,
849 "top-level asm block");
853 SingleDecl = Actions.ActOnFileScopeAsmDecl(
Result.get(), StartLoc, EndLoc);
857 return ParseObjCAtDirectives(Attrs, DeclSpecAttrs);
861 Diag(Tok, diag::err_expected_external_declaration);
865 SingleDecl = ParseObjCMethodDefinition();
867 case tok::code_completion:
869 if (CurParsedObjCImpl) {
871 Actions.CodeCompletion().CodeCompleteObjCMethodDecl(
878 if (CurParsedObjCImpl) {
880 }
else if (PP.isIncrementalProcessingEnabled()) {
885 Actions.CodeCompletion().CodeCompleteOrdinaryName(
getCurScope(), PCC);
887 case tok::kw_import: {
890 Diag(Tok, diag::err_unexpected_module_or_import_decl)
895 SingleDecl = ParseModuleImport(SourceLocation(), IS);
899 ProhibitAttributes(Attrs);
900 SingleDecl = ParseExportDeclaration();
907 case tok::kw_namespace:
908 case tok::kw_typedef:
909 case tok::kw_template:
910 case tok::kw_static_assert:
911 case tok::kw__Static_assert:
914 SourceLocation DeclEnd;
919 case tok::kw_cbuffer:
920 case tok::kw_tbuffer:
922 SourceLocation DeclEnd;
934 SourceLocation DeclEnd;
945 if (NextKind == tok::kw_namespace) {
946 SourceLocation DeclEnd;
953 if (NextKind == tok::kw_template) {
956 SourceLocation DeclEnd;
965 ProhibitAttributes(Attrs);
966 ProhibitAttributes(DeclSpecAttrs);
971 diag::warn_cxx98_compat_extern_template :
972 diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc);
973 SourceLocation DeclEnd;
975 TemplateLoc, DeclEnd, Attrs);
979 case tok::kw___if_exists:
980 case tok::kw___if_not_exists:
981 ParseMicrosoftIfExistsExternalDeclaration();
985 Diag(Tok, diag::err_unexpected_module_or_import_decl) <<
false;
991 if (Tok.isEditorPlaceholder()) {
996 !isDeclarationStatement(
true))
997 return ParseTopLevelStmtDecl();
1001 return ParseDeclarationOrFunctionDefinition(Attrs, DeclSpecAttrs, DS);
1006 return Actions.ConvertDeclToDeclGroup(SingleDecl);
1009bool Parser::isDeclarationAfterDeclarator() {
1013 if (KW.
is(tok::kw_default) || KW.
is(tok::kw_delete))
1017 return Tok.is(tok::equal) ||
1018 Tok.is(tok::comma) ||
1019 Tok.is(tok::semi) ||
1020 Tok.is(tok::kw_asm) ||
1021 Tok.is(tok::kw___attribute) ||
1023 Tok.is(tok::l_paren));
1026bool Parser::isStartOfFunctionDefinition(
const ParsingDeclarator &Declarator) {
1027 assert(
Declarator.isFunctionDeclarator() &&
"Isn't a function declarator");
1028 if (Tok.is(tok::l_brace))
1033 Declarator.getFunctionTypeInfo().isKNRPrototype())
1038 return KW.
is(tok::kw_default) || KW.
is(tok::kw_delete);
1041 return Tok.is(tok::colon) ||
1042 Tok.is(tok::kw_try);
1046 ParsedAttributes &Attrs, ParsedAttributes &DeclSpecAttrs,
1052 "expected uninitialised source range");
1057 ParsedTemplateInfo TemplateInfo;
1060 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
1061 DeclSpecContext::DSC_top_level);
1066 DS, AS, DeclSpecContext::DSC_top_level))
1071 if (Tok.is(tok::semi)) {
1074 SourceLocation CorrectLocationForAttributes{};
1078 if (
const auto *ED = dyn_cast_or_null<EnumDecl>(DS.
getRepAsDecl())) {
1079 CorrectLocationForAttributes =
1080 PP.getLocForEndOfToken(ED->getEnumKeyRange().getEnd());
1083 if (CorrectLocationForAttributes.
isInvalid()) {
1084 const auto &Policy = Actions.getASTContext().getPrintingPolicy();
1087 CorrectLocationForAttributes =
1091 ProhibitAttributes(Attrs, CorrectLocationForAttributes);
1093 RecordDecl *AnonRecord =
nullptr;
1094 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
1097 Actions.ActOnDefinedDeclarationSpecifier(TheDecl);
1099 Decl* decls[] = {AnonRecord, TheDecl};
1100 return Actions.BuildDeclaratorGroup(decls);
1102 return Actions.ConvertDeclToDeclGroup(TheDecl);
1106 Actions.ActOnDefinedDeclarationSpecifier(DS.
getRepAsDecl());
1113 if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
1114 !Tok.isObjCAtKeyword(tok::objc_protocol) &&
1115 !Tok.isObjCAtKeyword(tok::objc_implementation)) {
1116 Diag(Tok, diag::err_objc_unexpected_attr);
1124 const char *PrevSpec =
nullptr;
1127 Actions.getASTContext().getPrintingPolicy()))
1128 Diag(AtLoc, DiagID) << PrevSpec;
1130 if (Tok.isObjCAtKeyword(tok::objc_protocol))
1131 return ParseObjCAtProtocolDeclaration(AtLoc, DS.
getAttributes());
1133 if (Tok.isObjCAtKeyword(tok::objc_implementation))
1134 return ParseObjCAtImplementationDeclaration(AtLoc, DS.
getAttributes());
1136 return Actions.ConvertDeclToDeclGroup(
1137 ParseObjCAtInterfaceDeclaration(AtLoc, DS.
getAttributes()));
1146 ProhibitAttributes(Attrs);
1148 return Actions.ConvertDeclToDeclGroup(TheDecl);
1155 ParsedAttributes &Attrs, ParsedAttributes &DeclSpecAttrs,
1159 llvm::TimeTraceScope TimeScope(
"ParseDeclarationOrFunctionDefinition", [&]() {
1160 return Tok.getLocation().printToString(
1161 Actions.getASTContext().getSourceManager());
1165 return ParseDeclOrFunctionDefInternal(Attrs, DeclSpecAttrs, *DS, AS);
1167 ParsingDeclSpec PDS(*
this);
1171 ObjCDeclContextSwitch ObjCDC(*
this);
1173 return ParseDeclOrFunctionDefInternal(Attrs, DeclSpecAttrs, PDS, AS);
1177Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
1178 const ParsedTemplateInfo &TemplateInfo,
1179 LateParsedAttrList *LateParsedAttrs) {
1180 llvm::TimeTraceScope TimeScope(
"ParseFunctionDefinition", [&]() {
1181 return Actions.GetNameForDeclarator(D).getName().getAsString();
1187 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1196 const char *PrevSpec;
1198 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1210 ParseKNRParamDeclarations(D);
1214 if (Tok.isNot(tok::l_brace) &&
1216 (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
1217 Tok.isNot(tok::equal)))) {
1218 Diag(Tok, diag::err_expected_fn_body);
1224 if (Tok.isNot(tok::l_brace))
1230 if (Tok.isNot(tok::equal)) {
1232 if (AL.isKnownToGCC() && !AL.isStandardAttributeSyntax())
1233 Diag(AL.getLoc(), diag::warn_attribute_on_function_definition) << AL;
1238 if (
getLangOpts().DelayedTemplateParsing && Tok.isNot(tok::equal) &&
1240 LateParsedAttrs->empty() && Actions.canDelayFunctionBody(D)) {
1248 Decl *DP = Actions.HandleDeclarator(ParentScope, D,
1253 if (SkipFunctionBodies && (!DP || Actions.canSkipFunctionBody(DP)) &&
1254 trySkippingFunctionBody()) {
1256 return Actions.ActOnSkippedFunctionBody(DP);
1260 LexTemplateFunctionForLateParsing(Toks);
1264 Actions.CheckForFunctionRedefinition(FnD);
1265 Actions.MarkAsLateParsedTemplate(FnD, DP, Toks);
1269 if (CurParsedObjCImpl && !TemplateInfo.TemplateParams &&
1270 (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) || Tok.is(tok::colon)) &&
1271 Actions.CurContext->isTranslationUnit()) {
1277 Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
1283 StashAwayMethodOrFunctionBodyTokens(FuncDecl);
1284 CurParsedObjCImpl->HasCFunction =
true;
1296 StringLiteral *DeletedMessage =
nullptr;
1298 SourceLocation KWLoc;
1304 ? diag::warn_cxx98_compat_defaulted_deleted_function
1305 : diag::ext_defaulted_deleted_function)
1308 DeletedMessage = ParseCXXDeletedFunctionMessage();
1312 ? diag::warn_cxx98_compat_defaulted_deleted_function
1313 : diag::ext_defaulted_deleted_function)
1318 llvm_unreachable(
"function definition after = not 'delete' or 'default'");
1321 if (Tok.is(tok::comma)) {
1322 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
1325 }
else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
1333 Sema::FPFeaturesStateRAII SaveFPFeatures(Actions);
1337 SkipBodyInfo SkipBody;
1339 TemplateInfo.TemplateParams
1340 ? *TemplateInfo.TemplateParams
1342 &SkipBody, BodyKind);
1359 Actions.PopExpressionEvaluationContext();
1371 Actions.SetFunctionBodyKind(Res, KWLoc, BodyKind, DeletedMessage);
1372 Stmt *GeneratedBody = Res ? Res->
getBody() :
nullptr;
1373 Actions.ActOnFinishFunctionBody(Res, GeneratedBody,
false);
1379 if (
const auto *
Template = dyn_cast_if_present<FunctionTemplateDecl>(Res);
1381 Template->getTemplateParameters()->getParam(0)->isImplicit())
1384 CurTemplateDepthTracker.addDepth(1);
1387 if (LateParsedAttrs)
1388 ParseLexedAttributeList(*LateParsedAttrs, Res,
false,
1391 if (SkipFunctionBodies && (!Res || Actions.canSkipFunctionBody(Res)) &&
1392 trySkippingFunctionBody()) {
1394 Actions.ActOnSkippedFunctionBody(Res);
1395 return Actions.ActOnFinishFunctionBody(Res,
nullptr,
false);
1398 if (Tok.is(tok::kw_try))
1399 return ParseFunctionTryBlock(Res, BodyScope);
1403 if (Tok.is(tok::colon)) {
1404 ParseConstructorInitializer(Res);
1407 if (!Tok.is(tok::l_brace)) {
1409 Actions.ActOnFinishFunctionBody(Res,
nullptr);
1413 Actions.ActOnDefaultCtorInitializers(Res);
1415 return ParseFunctionStatementBody(Res, BodyScope);
1418void Parser::SkipFunctionBody() {
1419 if (Tok.is(tok::equal)) {
1424 bool IsFunctionTryBlock = Tok.is(tok::kw_try);
1425 if (IsFunctionTryBlock)
1429 if (ConsumeAndStoreFunctionPrologue(Skipped))
1433 while (IsFunctionTryBlock && Tok.is(tok::kw_catch)) {
1440void Parser::ParseKNRParamDeclarations(Declarator &D) {
1451 SourceLocation DSStart = Tok.getLocation();
1454 DeclSpec DS(AttrFactory);
1455 ParsedTemplateInfo TemplateInfo;
1456 ParseDeclarationSpecifiers(DS, TemplateInfo);
1464 Diag(DSStart, diag::err_declaration_does_not_declare_param);
1473 diag::err_invalid_storage_class_in_func_decl);
1478 diag::err_invalid_storage_class_in_func_decl);
1485 ParseDeclarator(ParmDeclarator);
1490 MaybeParseGNUAttributes(ParmDeclarator);
1494 Actions.ActOnParamDeclarator(
getCurScope(), ParmDeclarator);
1498 ParmDeclarator.getIdentifier()) {
1502 for (
unsigned i = 0; ; ++i) {
1506 Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
1507 << ParmDeclarator.getIdentifier();
1511 if (FTI.
Params[i].
Ident == ParmDeclarator.getIdentifier()) {
1514 Diag(ParmDeclarator.getIdentifierLoc(),
1515 diag::err_param_redefinition)
1516 << ParmDeclarator.getIdentifier();
1527 if (Tok.isNot(tok::comma))
1530 ParmDeclarator.clear();
1536 ParseDeclarator(ParmDeclarator);
1540 if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration))
1550 Actions.ActOnFinishKNRParamDeclarations(
getCurScope(), D, Tok.getLocation());
1553ExprResult Parser::ParseAsmStringLiteral(
bool ForAsmLabel) {
1556 if (isTokenStringLiteral()) {
1562 if (!SL->isOrdinary()) {
1563 Diag(Tok, diag::err_asm_operand_wide_string_literal)
1564 << SL->isWide() << SL->getSourceRange();
1568 Tok.is(tok::l_paren)) {
1570 SourceLocation RParenLoc;
1573 EnterExpressionEvaluationContext ConstantEvaluated(
1575 AsmString = ParseParenExpression(
1579 AsmString = Actions.ActOnConstantExpression(AsmString);
1584 Diag(Tok, diag::err_asm_expected_string) << (
1585 (
getLangOpts().CPlusPlus11 && !ForAsmLabel) ? 0 : 1);
1588 return Actions.ActOnGCCAsmStmtString(AsmString.
get(), ForAsmLabel);
1591ExprResult Parser::ParseSimpleAsm(
bool ForAsmLabel, SourceLocation *EndLoc) {
1592 assert(Tok.is(tok::kw_asm) &&
"Not an asm!");
1595 if (isGNUAsmQualifier(Tok)) {
1597 SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
1598 PP.getLocForEndOfToken(Tok.getLocation()));
1599 Diag(Tok, diag::err_global_asm_qualifier_ignored)
1600 << GNUAsmQualifiers::getQualifierName(getGNUAsmQualifier(Tok))
1606 if (
T.consumeOpen()) {
1607 Diag(Tok, diag::err_expected_lparen_after) <<
"asm";
1613 if (!
Result.isInvalid()) {
1617 *EndLoc =
T.getCloseLocation();
1620 *EndLoc = Tok.getLocation();
1627TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(
const Token &tok) {
1628 assert(tok.
is(tok::annot_template_id) &&
"Expected template-id token");
1629 TemplateIdAnnotation *
1634void Parser::AnnotateScopeToken(CXXScopeSpec &SS,
bool IsNewAnnotation) {
1637 if (PP.isBacktrackEnabled())
1638 PP.RevertCachedTokens(1);
1640 PP.EnterToken(Tok,
true);
1641 Tok.setKind(tok::annot_cxxscope);
1642 Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
1643 Tok.setAnnotationRange(SS.
getRange());
1648 if (IsNewAnnotation)
1649 PP.AnnotateCachedTokens(Tok);
1653Parser::TryAnnotateName(CorrectionCandidateCallback *CCC,
1655 assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
1657 const bool EnteringContext =
false;
1658 const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1662 ParseOptionalCXXScopeSpecifier(SS,
nullptr,
1667 if (Tok.isNot(tok::identifier) || SS.
isInvalid()) {
1669 AllowImplicitTypename))
1674 IdentifierInfo *Name = Tok.getIdentifierInfo();
1675 SourceLocation NameLoc = Tok.getLocation();
1679 if (isTentativelyDeclared(Name) && SS.
isEmpty()) {
1683 AllowImplicitTypename))
1695 Sema::NameClassification Classification = Actions.ClassifyName(
1703 isTemplateArgumentList(1) == TPResult::False) {
1705 Token FakeNext =
Next;
1706 FakeNext.
setKind(tok::unknown);
1708 Actions.ClassifyName(
getCurScope(), SS, Name, NameLoc, FakeNext,
1709 SS.
isEmpty() ? CCC :
nullptr);
1712 switch (Classification.
getKind()) {
1718 Tok.setIdentifierInfo(Name);
1720 PP.TypoCorrectToken(Tok);
1722 AnnotateScopeToken(SS, !WasScopeAnnotation);
1731 if (TryAltiVecVectorToken())
1736 SourceLocation BeginLoc = NameLoc;
1743 QualType
T = Actions.GetTypeFromParser(Ty);
1748 SourceLocation NewEndLoc;
1750 = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
1755 else if (Tok.is(tok::eof))
1759 Tok.setKind(tok::annot_typename);
1760 setTypeAnnotation(Tok, Ty);
1761 Tok.setAnnotationEndLoc(Tok.getLocation());
1762 Tok.setLocation(BeginLoc);
1763 PP.AnnotateCachedTokens(Tok);
1768 Tok.setKind(tok::annot_overload_set);
1770 Tok.setAnnotationEndLoc(NameLoc);
1773 PP.AnnotateCachedTokens(Tok);
1777 if (TryAltiVecVectorToken())
1782 Tok.setKind(tok::annot_non_type);
1784 Tok.setLocation(NameLoc);
1785 Tok.setAnnotationEndLoc(NameLoc);
1786 PP.AnnotateCachedTokens(Tok);
1788 AnnotateScopeToken(SS, !WasScopeAnnotation);
1793 Tok.setKind(Classification.
getKind() ==
1795 ? tok::annot_non_type_undeclared
1796 : tok::annot_non_type_dependent);
1797 setIdentifierAnnotation(Tok, Name);
1798 Tok.setLocation(NameLoc);
1799 Tok.setAnnotationEndLoc(NameLoc);
1800 PP.AnnotateCachedTokens(Tok);
1802 AnnotateScopeToken(SS, !WasScopeAnnotation);
1806 if (
Next.isNot(tok::less)) {
1810 AnnotateScopeToken(SS, !WasScopeAnnotation);
1818 bool IsConceptName =
1824 if (
Next.is(tok::less))
1826 if (AnnotateTemplateIdToken(
1833 AnnotateScopeToken(SS, !WasScopeAnnotation);
1840 AnnotateScopeToken(SS, !WasScopeAnnotation);
1845 SourceLocation TokenEndLoc = PP.getLocForEndOfToken(PrevTokLocation);
1846 return TokenEndLoc.
isValid() ? TokenEndLoc : Tok.getLocation();
1849bool Parser::TryKeywordIdentFallback(
bool DisableKeyword) {
1850 assert(
Tok.isNot(tok::identifier));
1851 Diag(
Tok, diag::ext_keyword_as_ident)
1855 Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
1856 Tok.setKind(tok::identifier);
1862 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1863 Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope) ||
1864 Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id) ||
1865 Tok.is(tok::kw___super) || Tok.is(tok::kw_auto) ||
1866 Tok.is(tok::annot_pack_indexing_type)) &&
1867 "Cannot be a type or scope token!");
1869 if (Tok.is(tok::kw_typename)) {
1878 PP.Lex(TypedefToken);
1880 PP.EnterToken(Tok,
true);
1883 Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename);
1895 if (ParseOptionalCXXScopeSpecifier(SS,
nullptr,
1901 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) ||
1902 Tok.is(tok::annot_decltype)) {
1904 if (Tok.is(tok::annot_decltype) ||
1906 Tok.isAnnotation())) {
1907 unsigned DiagID = diag::err_expected_qualified_after_typename;
1911 DiagID = diag::warn_expected_qualified_after_typename;
1912 Diag(Tok.getLocation(), DiagID);
1916 if (Tok.isEditorPlaceholder())
1919 Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
1923 bool TemplateKWPresent =
false;
1924 if (Tok.is(tok::kw_template)) {
1926 TemplateKWPresent =
true;
1930 if (Tok.is(tok::identifier)) {
1932 Diag(Tok.getLocation(),
1933 diag::missing_template_arg_list_after_template_kw);
1936 Ty = Actions.ActOnTypenameType(
getCurScope(), TypenameLoc, SS,
1937 *Tok.getIdentifierInfo(),
1939 }
else if (Tok.is(tok::annot_template_id)) {
1942 Diag(Tok, diag::err_typename_refers_to_non_type_template)
1943 << Tok.getAnnotationRange();
1952 : Actions.ActOnTypenameType(
1956 TemplateArgsPtr, TemplateId->
RAngleLoc);
1958 Diag(Tok, diag::err_expected_type_name_after_typename)
1964 Tok.setKind(tok::annot_typename);
1965 setTypeAnnotation(Tok, Ty);
1966 Tok.setAnnotationEndLoc(EndLoc);
1967 Tok.setLocation(TypenameLoc);
1968 PP.AnnotateCachedTokens(Tok);
1973 bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1977 if (ParseOptionalCXXScopeSpecifier(
1981 IsAddressOfOperand))
1985 AllowImplicitTypename);
1991 if (Tok.is(tok::identifier)) {
1994 *Tok.getIdentifierInfo(), Tok.getLocation(),
getCurScope(), &SS,
1998 true, AllowImplicitTypename)) {
2003 QualType T = Actions.GetTypeFromParser(Ty);
2008 (
T->isObjCObjectType() ||
T->isObjCObjectPointerType())) {
2018 else if (Tok.is(tok::eof))
2024 Tok.setKind(tok::annot_typename);
2025 setTypeAnnotation(Tok, Ty);
2026 Tok.setAnnotationEndLoc(Tok.getLocation());
2027 Tok.setLocation(BeginLoc);
2031 PP.AnnotateCachedTokens(Tok);
2048 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
2049 bool MemberOfUnknownSpecialization;
2054 MemberOfUnknownSpecialization)) {
2058 isTemplateArgumentList(1) != TPResult::False) {
2078 if (Tok.is(tok::annot_template_id)) {
2085 AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
2092 Tok.is(tok::coloncolon)) {
2101 AnnotateScopeToken(SS, IsNewScope);
2107 "Call sites of this function should be guarded by checking for C++");
2111 if (ParseOptionalCXXScopeSpecifier(SS,
nullptr,
2118 AnnotateScopeToken(SS,
true);
2122bool Parser::isTokenEqualOrEqualTypo() {
2128 case tok::starequal:
2129 case tok::plusequal:
2130 case tok::minusequal:
2131 case tok::exclaimequal:
2132 case tok::slashequal:
2133 case tok::percentequal:
2134 case tok::lessequal:
2135 case tok::lesslessequal:
2136 case tok::greaterequal:
2137 case tok::greatergreaterequal:
2138 case tok::caretequal:
2139 case tok::pipeequal:
2140 case tok::equalequal:
2141 Diag(
Tok, diag::err_invalid_token_after_declarator_suggest_equal)
2150SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
2151 assert(Tok.is(tok::code_completion));
2152 PrevTokLocation = Tok.getLocation();
2155 if (S->isFunctionScope()) {
2157 Actions.CodeCompletion().CodeCompleteOrdinaryName(
2159 return PrevTokLocation;
2162 if (S->isClassScope()) {
2164 Actions.CodeCompletion().CodeCompleteOrdinaryName(
2166 return PrevTokLocation;
2171 Actions.CodeCompletion().CodeCompleteOrdinaryName(
2173 return PrevTokLocation;
2178void Parser::CodeCompleteDirective(
bool InConditional) {
2179 Actions.CodeCompletion().CodeCompletePreprocessorDirective(InConditional);
2183 Actions.CodeCompletion().CodeCompleteInPreprocessorConditionalExclusion(
2187void Parser::CodeCompleteMacroName(
bool IsDefinition) {
2188 Actions.CodeCompletion().CodeCompletePreprocessorMacroName(IsDefinition);
2192 Actions.CodeCompletion().CodeCompletePreprocessorExpression();
2195void Parser::CodeCompleteMacroArgument(IdentifierInfo *
Macro,
2196 MacroInfo *MacroInfo,
2197 unsigned ArgumentIndex) {
2198 Actions.CodeCompletion().CodeCompletePreprocessorMacroArgument(
2202void Parser::CodeCompleteIncludedFile(llvm::StringRef Dir,
bool IsAngled) {
2203 Actions.CodeCompletion().CodeCompleteIncludedFile(Dir, IsAngled);
2207 Actions.CodeCompletion().CodeCompleteNaturalLanguage();
2210void Parser::CodeCompleteModuleImport(SourceLocation ImportLoc,
2212 Actions.CodeCompletion().CodeCompleteModuleImport(ImportLoc, Path);
2215bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition&
Result) {
2216 assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
2217 "Expected '__if_exists' or '__if_not_exists'");
2218 Result.IsIfExists = Tok.is(tok::kw___if_exists);
2222 if (
T.consumeOpen()) {
2223 Diag(Tok, diag::err_expected_lparen_after)
2224 << (
Result.IsIfExists?
"__if_exists" :
"__if_not_exists");
2230 ParseOptionalCXXScopeSpecifier(
Result.SS,
nullptr,
2235 if (
Result.SS.isInvalid()) {
2241 SourceLocation TemplateKWLoc;
2246 false, &TemplateKWLoc,
2252 if (
T.consumeClose())
2280void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
2281 IfExistsCondition
Result;
2282 if (ParseMicrosoftIfExistsCondition(
Result))
2286 if (
Braces.consumeOpen()) {
2287 Diag(Tok, diag::err_expected) << tok::l_brace;
2291 switch (
Result.Behavior) {
2297 llvm_unreachable(
"Cannot have a dependent external declaration");
2306 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
2307 ParsedAttributes Attrs(AttrFactory);
2308 MaybeParseCXX11Attributes(Attrs);
2309 ParsedAttributes EmptyDeclSpecAttrs(AttrFactory);
2312 Actions.getASTConsumer().HandleTopLevelDecl(
Result.get());
2319 Token Introducer = Tok;
2320 SourceLocation StartLoc = Introducer.
getLocation();
2326 assert(Tok.is(tok::kw_module) &&
"not a module declaration");
2332 DiagnoseAndSkipCXX11Attributes();
2335 if (
getLangOpts().CPlusPlusModules && Tok.is(tok::semi)) {
2339 Diag(StartLoc, diag::err_global_module_introducer_not_at_start)
2340 << SourceRange(StartLoc, SemiLoc);
2344 Diag(StartLoc, diag::err_module_fragment_exported)
2348 return Actions.ActOnGlobalModuleFragmentDecl(ModuleLoc);
2352 if (
getLangOpts().CPlusPlusModules && Tok.is(tok::colon) &&
2355 Diag(StartLoc, diag::err_module_fragment_exported)
2360 DiagnoseAndSkipCXX11Attributes();
2361 ExpectAndConsumeSemi(diag::err_private_module_fragment_expected_semi);
2365 return Actions.ActOnPrivateModuleFragmentDecl(ModuleLoc, PrivateLoc);
2368 SmallVector<IdentifierLoc, 2> Path;
2369 if (ParseModuleName(ModuleLoc, Path,
false))
2373 SmallVector<IdentifierLoc, 2> Partition;
2374 if (Tok.is(tok::colon)) {
2377 Diag(ColonLoc, diag::err_unsupported_module_partition)
2378 << SourceRange(ColonLoc, Partition.back().getLoc());
2380 else if (ParseModuleName(ModuleLoc, Partition,
false))
2385 if (!Tok.isOneOf(tok::semi, tok::l_square))
2389 ParsedAttributes Attrs(AttrFactory);
2390 MaybeParseCXX11Attributes(Attrs);
2391 ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_module_attr,
2392 diag::err_keyword_not_module_attr,
2396 if (ExpectAndConsumeSemi(diag::err_expected_semi_after_module_or_import,
2400 return Actions.ActOnModuleDecl(StartLoc, ModuleLoc, MDK, Path, Partition,
2405Decl *Parser::ParseModuleImport(SourceLocation AtLoc,
2407 SourceLocation StartLoc = AtLoc.
isInvalid() ? Tok.getLocation() : AtLoc;
2409 SourceLocation ExportLoc;
2412 assert((AtLoc.
isInvalid() ? Tok.is(tok::kw_import)
2413 : Tok.isObjCAtKeyword(tok::objc_import)) &&
2414 "Improper start to module import");
2415 bool IsObjCAtImport = Tok.isObjCAtKeyword(tok::objc_import);
2419 SmallVector<IdentifierLoc, 2> Path;
2420 bool IsPartition =
false;
2421 Module *HeaderUnit =
nullptr;
2422 if (Tok.is(tok::header_name)) {
2427 }
else if (Tok.is(tok::annot_header_unit)) {
2429 HeaderUnit =
reinterpret_cast<Module *
>(Tok.getAnnotationValue());
2430 ConsumeAnnotationToken();
2431 }
else if (Tok.is(tok::colon)) {
2434 Diag(ColonLoc, diag::err_unsupported_module_partition)
2435 << SourceRange(ColonLoc, Path.back().getLoc());
2437 else if (ParseModuleName(ColonLoc, Path,
true))
2442 if (ParseModuleName(ImportLoc, Path,
true))
2446 ParsedAttributes Attrs(AttrFactory);
2447 MaybeParseCXX11Attributes(Attrs);
2449 ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_import_attr,
2450 diag::err_keyword_not_import_attr,
2457 bool IsCXX20NamedModuleImport =
2458 getLangOpts().CPlusPlusModules && !IsObjCAtImport && !Path.empty();
2460 if (PP.hadModuleLoaderFatalFailure() && !IsCXX20NamedModuleImport) {
2467 bool SeenError =
true;
2468 switch (ImportState) {
2480 Diag(ImportLoc, diag::err_partition_import_outside_module);
2492 if (IsPartition || (HeaderUnit && HeaderUnit->
Kind !=
2494 Diag(ImportLoc, diag::err_import_in_wrong_fragment)
2503 Diag(ImportLoc, diag::err_import_not_allowed_here);
2509 bool LexedSemi =
false;
2512 !ExpectAndConsumeSemi(diag::err_expected_semi_after_module_or_import,
2515 LexedSemi = !ExpectAndConsumeSemi(diag::err_module_expected_semi);
2526 Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, HeaderUnit);
2527 else if (!Path.empty())
2528 Import = Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Path,
2535 if (IsObjCAtImport && AtLoc.
isValid()) {
2536 auto &SrcMgr = PP.getSourceManager();
2537 auto FE = SrcMgr.getFileEntryRefForID(SrcMgr.getFileID(AtLoc));
2538 if (FE && llvm::sys::path::parent_path(FE->getDir().getName())
2539 .ends_with(
".framework"))
2540 Diags.Report(AtLoc, diag::warn_atimport_in_framework_header);
2546bool Parser::ParseModuleName(SourceLocation UseLoc,
2547 SmallVectorImpl<IdentifierLoc> &Path,
2549 if (Tok.isNot(tok::annot_module_name)) {
2553 ModuleNameLoc *NameLoc =
2554 static_cast<ModuleNameLoc *
>(Tok.getAnnotationValue());
2557 ConsumeAnnotationToken();
2561bool Parser::parseMisplacedModuleImport() {
2563 switch (Tok.getKind()) {
2564 case tok::annot_module_end:
2568 if (MisplacedModuleBeginCount) {
2569 --MisplacedModuleBeginCount;
2570 Actions.ActOnAnnotModuleEnd(
2572 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
2573 ConsumeAnnotationToken();
2580 case tok::annot_module_begin:
2582 Actions.ActOnAnnotModuleBegin(
2584 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
2585 ConsumeAnnotationToken();
2586 ++MisplacedModuleBeginCount;
2588 case tok::annot_module_include:
2591 Actions.ActOnAnnotModuleInclude(
2593 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
2594 ConsumeAnnotationToken();
2604void Parser::diagnoseUseOfC11Keyword(
const Token &Tok) {
2609 : diag::ext_c11_feature)
2613bool BalancedDelimiterTracker::diagnoseOverflow() {
2614 P.Diag(P.Tok, diag::err_bracket_depth_exceeded)
2615 << P.getLangOpts().BracketDepth;
2616 P.Diag(P.Tok, diag::note_bracket_depth);
2624 LOpen = P.Tok.getLocation();
2625 if (P.ExpectAndConsume(Kind, DiagID, Msg)) {
2626 if (SkipToTok != tok::unknown)
2631 if (getDepth() < P.getLangOpts().BracketDepth)
2634 return diagnoseOverflow();
2637bool BalancedDelimiterTracker::diagnoseMissingClose() {
2638 assert(!P.Tok.is(Close) &&
"Should have consumed closing delimiter");
2640 if (P.Tok.is(tok::annot_module_end))
2641 P.Diag(P.Tok, diag::err_missing_before_module_end) << Close;
2643 P.Diag(P.Tok, diag::err_expected) << Close;
2644 P.Diag(LOpen, diag::note_matching) << Kind;
2648 if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) &&
2649 P.Tok.isNot(tok::r_square) &&
2650 P.SkipUntil(Close, FinalToken,
2653 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.
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.
A simple pair of identifier info and location.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
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
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.
IdentifierTable & getIdentifierTable()
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
void ActOnTranslationUnitScope(Scope *S)
Scope actions.
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 '!
The JSON file list parser is used to communicate input to InstallAPI.
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.