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) {
103 return DiagCompat(Tok.getLocation(), CompatDiagId);
122 switch (ExpectedTok) {
124 return Tok.is(tok::colon) ||
Tok.is(tok::comma);
125 default:
return false;
129bool Parser::ExpectAndConsume(
tok::TokenKind ExpectedTok,
unsigned DiagID,
131 if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) {
138 SourceLocation Loc = Tok.getLocation();
140 DiagnosticBuilder DB =
Diag(Loc, DiagID);
143 if (DiagID == diag::err_expected)
145 else if (DiagID == diag::err_expected_after)
146 DB << Msg << ExpectedTok;
156 SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation);
157 const char *Spelling =
nullptr;
161 DiagnosticBuilder DB =
165 if (DiagID == diag::err_expected)
167 else if (DiagID == diag::err_expected_after)
168 DB << Msg << ExpectedTok;
175bool Parser::ExpectAndConsumeSemi(
unsigned DiagID, StringRef TokenUsed) {
179 if (Tok.is(tok::code_completion)) {
180 handleUnexpectedCodeCompletionToken();
184 if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) &&
186 Diag(Tok, diag::err_extraneous_token_before_semi)
187 << PP.getSpelling(Tok)
194 return ExpectAndConsume(tok::semi, DiagID , TokenUsed);
197bool Parser::isLikelyAtStartOfNewDeclaration() {
198 return Tok.isAtStartOfLine() &&
203 if (!Tok.is(tok::semi))
return;
205 bool HadMultipleSemis =
false;
206 SourceLocation StartLoc = Tok.getLocation();
207 SourceLocation EndLoc = Tok.getLocation();
210 while ((Tok.is(tok::semi) && !Tok.isAtStartOfLine())) {
211 HadMultipleSemis =
true;
212 EndLoc = Tok.getLocation();
220 Diag(StartLoc, diag::warn_cxx98_compat_top_level_semi)
223 Diag(StartLoc, diag::ext_extra_semi_cxx11)
229 Diag(StartLoc, diag::ext_extra_semi)
232 TST, Actions.getASTContext().getPrintingPolicy())
236 Diag(StartLoc, diag::warn_extra_semi_after_mem_fn_def)
240bool Parser::expectIdentifier() {
241 if (Tok.is(tok::identifier))
243 if (
const auto *II = Tok.getIdentifierInfo()) {
245 Diag(Tok, diag::err_expected_token_instead_of_objcxx_keyword)
246 << tok::identifier << Tok.getIdentifierInfo();
251 Diag(Tok, diag::err_expected) << tok::identifier;
259 SourceLocation SecondTokLoc = Tok.getLocation();
264 PP.getSourceManager().getFileID(FirstTokLoc) !=
265 PP.getSourceManager().getFileID(SecondTokLoc)) {
266 Diag(FirstTokLoc, diag::warn_compound_token_split_by_macro)
267 << (FirstTokKind == Tok.getKind()) << FirstTokKind << Tok.getKind()
268 <<
static_cast<int>(Op) << SourceRange(FirstTokLoc);
269 Diag(SecondTokLoc, diag::note_compound_token_split_second_token_here)
270 << (FirstTokKind == Tok.getKind()) << Tok.getKind()
271 << SourceRange(SecondTokLoc);
276 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
277 SourceLocation SpaceLoc = PP.getLocForEndOfToken(FirstTokLoc);
279 SpaceLoc = FirstTokLoc;
280 Diag(SpaceLoc, diag::warn_compound_token_split_by_whitespace)
281 << (FirstTokKind == Tok.getKind()) << FirstTokKind << Tok.getKind()
282 <<
static_cast<int>(Op) << SourceRange(FirstTokLoc, SecondTokLoc);
292 return (
static_cast<unsigned>(L) &
static_cast<unsigned>(R)) != 0;
298 bool isFirstTokenSkipped =
true;
301 for (
unsigned i = 0, NumToks = Toks.size(); i != NumToks; ++i) {
302 if (Tok.is(Toks[i])) {
315 if (Toks.size() == 1 && Toks[0] == tok::eof &&
318 while (Tok.isNot(tok::eof))
323 switch (Tok.getKind()) {
328 case tok::annot_pragma_openmp:
329 case tok::annot_attr_openmp:
330 case tok::annot_pragma_openmp_end:
332 if (OpenMPDirectiveParsing)
334 ConsumeAnnotationToken();
336 case tok::annot_pragma_openacc:
337 case tok::annot_pragma_openacc_end:
339 if (OpenACCDirectiveParsing)
341 ConsumeAnnotationToken();
343 case tok::annot_module_begin:
344 case tok::annot_module_end:
345 case tok::annot_module_include:
346 case tok::annot_repl_input_end:
352 case tok::code_completion:
354 handleUnexpectedCodeCompletionToken();
396 if (ParenCount && !isFirstTokenSkipped)
401 if (BracketCount && !isFirstTokenSkipped)
406 if (BraceCount && !isFirstTokenSkipped)
420 isFirstTokenSkipped =
false;
429 if (NumCachedScopes) {
430 Scope *N = ScopeCache[--NumCachedScopes];
432 Actions.CurScope = N;
443 Actions.ActOnPopScope(Tok.getLocation(),
getCurScope());
446 Actions.CurScope = OldScope->
getParent();
448 if (NumCachedScopes == ScopeCacheSize)
451 ScopeCache[NumCachedScopes++] = OldScope;
454Parser::ParseScopeFlags::ParseScopeFlags(
Parser *
Self,
unsigned ScopeFlags,
456 : CurScope(ManageFlags ?
Self->getCurScope() :
nullptr) {
458 OldFlags = CurScope->getFlags();
459 CurScope->setFlags(ScopeFlags);
463Parser::ParseScopeFlags::~ParseScopeFlags() {
465 CurScope->setFlags(OldFlags);
476 Actions.CurScope =
nullptr;
479 for (
unsigned i = 0, e = NumCachedScopes; i != e; ++i)
480 delete ScopeCache[i];
482 resetPragmaHandlers();
484 PP.removeCommentHandler(CommentSemaHandler.get());
486 PP.clearCodeCompletionHandler();
488 DestroyTemplateIds();
493 assert(
getCurScope() ==
nullptr &&
"A scope is already active?");
501 &PP.getIdentifierTable().get(
"in");
503 &PP.getIdentifierTable().get(
"out");
505 &PP.getIdentifierTable().get(
"inout");
507 &PP.getIdentifierTable().get(
"oneway");
509 &PP.getIdentifierTable().get(
"bycopy");
511 &PP.getIdentifierTable().get(
"byref");
513 &PP.getIdentifierTable().get(
"nonnull");
515 &PP.getIdentifierTable().get(
"nullable");
517 &PP.getIdentifierTable().get(
"null_unspecified");
520 Ident_instancetype =
nullptr;
521 Ident_final =
nullptr;
522 Ident_sealed =
nullptr;
523 Ident_abstract =
nullptr;
524 Ident_override =
nullptr;
525 Ident_GNU_final =
nullptr;
527 Ident_super = &PP.getIdentifierTable().get(
"super");
529 Ident_vector =
nullptr;
530 Ident_bool =
nullptr;
531 Ident_Bool =
nullptr;
532 Ident_pixel =
nullptr;
534 Ident_vector = &PP.getIdentifierTable().get(
"vector");
535 Ident_bool = &PP.getIdentifierTable().get(
"bool");
536 Ident_Bool = &PP.getIdentifierTable().get(
"_Bool");
539 Ident_pixel = &PP.getIdentifierTable().get(
"pixel");
541 Ident_introduced =
nullptr;
542 Ident_deprecated =
nullptr;
543 Ident_obsoleted =
nullptr;
544 Ident_unavailable =
nullptr;
545 Ident_strict =
nullptr;
546 Ident_replacement =
nullptr;
548 Ident_language = Ident_defined_in = Ident_generated_declaration = Ident_USR =
551 Ident__except =
nullptr;
553 Ident__exception_code = Ident__exception_info =
nullptr;
554 Ident__abnormal_termination = Ident___exception_code =
nullptr;
555 Ident___exception_info = Ident___abnormal_termination =
nullptr;
556 Ident_GetExceptionCode = Ident_GetExceptionInfo =
nullptr;
557 Ident_AbnormalTermination =
nullptr;
560 Ident__exception_info = PP.getIdentifierInfo(
"_exception_info");
561 Ident___exception_info = PP.getIdentifierInfo(
"__exception_info");
562 Ident_GetExceptionInfo = PP.getIdentifierInfo(
"GetExceptionInformation");
563 Ident__exception_code = PP.getIdentifierInfo(
"_exception_code");
564 Ident___exception_code = PP.getIdentifierInfo(
"__exception_code");
565 Ident_GetExceptionCode = PP.getIdentifierInfo(
"GetExceptionCode");
566 Ident__abnormal_termination = PP.getIdentifierInfo(
"_abnormal_termination");
567 Ident___abnormal_termination = PP.getIdentifierInfo(
"__abnormal_termination");
568 Ident_AbnormalTermination = PP.getIdentifierInfo(
"AbnormalTermination");
570 PP.SetPoisonReason(Ident__exception_code,diag::err_seh___except_block);
571 PP.SetPoisonReason(Ident___exception_code,diag::err_seh___except_block);
572 PP.SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block);
573 PP.SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter);
574 PP.SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter);
575 PP.SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter);
576 PP.SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block);
577 PP.SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block);
578 PP.SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block);
581 Actions.Initialize();
587void Parser::DestroyTemplateIds() {
595 Actions.ActOnStartOfTranslationUnit();
607 if (NoTopLevelDecls && !Actions.getASTContext().getExternalSource() &&
609 Diag(diag::ext_empty_translation_unit);
611 return NoTopLevelDecls;
616 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*
this);
619 switch (Tok.getKind()) {
620 case tok::annot_pragma_unused:
621 HandlePragmaUnused();
637 Result = ParseModuleDecl(ImportState);
647 case tok::annot_module_include: {
648 auto Loc = Tok.getLocation();
649 Module *Mod =
reinterpret_cast<Module *
>(Tok.getAnnotationValue());
653 Actions.ActOnAnnotModuleInclude(Loc, Mod);
660 ConsumeAnnotationToken();
664 case tok::annot_module_begin:
665 Actions.ActOnAnnotModuleBegin(
667 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
668 ConsumeAnnotationToken();
672 case tok::annot_module_end:
673 Actions.ActOnAnnotModuleEnd(
675 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
676 ConsumeAnnotationToken();
681 case tok::annot_repl_input_end:
683 if (PP.getMaxTokens() != 0 && PP.getTokenCount() > PP.getMaxTokens()) {
684 PP.Diag(Tok.getLocation(), diag::warn_max_tokens_total)
685 << PP.getTokenCount() << PP.getMaxTokens();
688 PP.Diag(OverrideLoc, diag::note_max_tokens_total_override);
693 Actions.SetLateTemplateParser(LateTemplateParserCallback,
this);
694 Actions.ActOnEndOfTranslationUnit();
707 while (MaybeParseCXX11Attributes(DeclAttrs) ||
708 MaybeParseGNUAttributes(DeclSpecAttrs))
711 Result = ParseExternalDeclaration(DeclAttrs, DeclSpecAttrs);
721 else if (ImportState ==
733 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*
this);
741 Decl *SingleDecl =
nullptr;
742 switch (
Tok.getKind()) {
743 case tok::annot_pragma_vis:
744 HandlePragmaVisibility();
746 case tok::annot_pragma_pack:
749 case tok::annot_pragma_msstruct:
750 HandlePragmaMSStruct();
752 case tok::annot_pragma_align:
755 case tok::annot_pragma_weak:
758 case tok::annot_pragma_weakalias:
759 HandlePragmaWeakAlias();
761 case tok::annot_pragma_redefine_extname:
762 HandlePragmaRedefineExtname();
764 case tok::annot_pragma_fp_contract:
765 HandlePragmaFPContract();
767 case tok::annot_pragma_fenv_access:
768 case tok::annot_pragma_fenv_access_ms:
769 HandlePragmaFEnvAccess();
771 case tok::annot_pragma_fenv_round:
772 HandlePragmaFEnvRound();
774 case tok::annot_pragma_cx_limited_range:
775 HandlePragmaCXLimitedRange();
777 case tok::annot_pragma_float_control:
778 HandlePragmaFloatControl();
780 case tok::annot_pragma_fp:
783 case tok::annot_pragma_opencl_extension:
784 HandlePragmaOpenCLExtension();
786 case tok::annot_attr_openmp:
787 case tok::annot_pragma_openmp: {
789 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
791 case tok::annot_pragma_openacc: {
796 case tok::annot_pragma_ms_pointers_to_members:
797 HandlePragmaMSPointersToMembers();
799 case tok::annot_pragma_ms_vtordisp:
800 HandlePragmaMSVtorDisp();
802 case tok::annot_pragma_ms_pragma:
803 HandlePragmaMSPragma();
805 case tok::annot_pragma_dump:
808 case tok::annot_pragma_attribute:
809 HandlePragmaAttribute();
811 case tok::annot_pragma_export:
812 HandlePragmaExport();
817 Actions.ActOnEmptyDeclaration(
getCurScope(), Attrs, Tok.getLocation());
821 Diag(Tok, diag::err_extraneous_closing_brace);
825 Diag(Tok, diag::err_expected_external_declaration);
827 case tok::kw___extension__: {
829 ExtensionRAIIObject O(Diags);
831 return ParseExternalDeclaration(Attrs, DeclSpecAttrs);
834 ProhibitAttributes(Attrs);
836 SourceLocation StartLoc = Tok.getLocation();
837 SourceLocation EndLoc;
846 if (!SL->getString().trim().empty())
847 Diag(StartLoc, diag::err_gnu_inline_asm_disabled);
850 ExpectAndConsume(tok::semi, diag::err_expected_after,
851 "top-level asm block");
855 SingleDecl = Actions.ActOnFileScopeAsmDecl(
Result.get(), StartLoc, EndLoc);
859 return ParseObjCAtDirectives(Attrs, DeclSpecAttrs);
863 Diag(Tok, diag::err_expected_external_declaration);
867 SingleDecl = ParseObjCMethodDefinition();
869 case tok::code_completion:
871 if (CurParsedObjCImpl) {
873 Actions.CodeCompletion().CodeCompleteObjCMethodDecl(
880 if (CurParsedObjCImpl) {
882 }
else if (PP.isIncrementalProcessingEnabled()) {
887 Actions.CodeCompletion().CodeCompleteOrdinaryName(
getCurScope(), PCC);
889 case tok::kw_import: {
892 Diag(Tok, diag::err_unexpected_module_or_import_decl)
897 SingleDecl = ParseModuleImport(SourceLocation(), IS);
901 ProhibitAttributes(Attrs);
902 SingleDecl = ParseExportDeclaration();
909 case tok::kw_namespace:
910 case tok::kw_typedef:
911 case tok::kw_template:
912 case tok::kw_static_assert:
913 case tok::kw__Static_assert:
916 SourceLocation DeclEnd;
921 case tok::kw_cbuffer:
922 case tok::kw_tbuffer:
924 SourceLocation DeclEnd;
936 SourceLocation DeclEnd;
947 if (NextKind == tok::kw_namespace) {
948 SourceLocation DeclEnd;
955 if (NextKind == tok::kw_template) {
958 SourceLocation DeclEnd;
967 ProhibitAttributes(Attrs);
968 ProhibitAttributes(DeclSpecAttrs);
973 diag::warn_cxx98_compat_extern_template :
974 diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc);
975 SourceLocation DeclEnd;
977 TemplateLoc, DeclEnd, Attrs);
981 case tok::kw___if_exists:
982 case tok::kw___if_not_exists:
983 ParseMicrosoftIfExistsExternalDeclaration();
987 Diag(Tok, diag::err_unexpected_module_or_import_decl) <<
false;
993 if (Tok.isEditorPlaceholder()) {
998 !isDeclarationStatement(
true))
999 return ParseTopLevelStmtDecl();
1003 return ParseDeclarationOrFunctionDefinition(Attrs, DeclSpecAttrs, DS);
1008 return Actions.ConvertDeclToDeclGroup(SingleDecl);
1011bool Parser::isDeclarationAfterDeclarator() {
1015 if (KW.
is(tok::kw_default) || KW.
is(tok::kw_delete))
1019 return Tok.is(tok::equal) ||
1020 Tok.is(tok::comma) ||
1021 Tok.is(tok::semi) ||
1022 Tok.is(tok::kw_asm) ||
1023 Tok.is(tok::kw___attribute) ||
1025 Tok.is(tok::l_paren));
1028bool Parser::isStartOfFunctionDefinition(
const ParsingDeclarator &Declarator) {
1029 assert(
Declarator.isFunctionDeclarator() &&
"Isn't a function declarator");
1030 if (Tok.is(tok::l_brace))
1035 Declarator.getFunctionTypeInfo().isKNRPrototype())
1040 return KW.
is(tok::kw_default) || KW.
is(tok::kw_delete);
1043 return Tok.is(tok::colon) ||
1044 Tok.is(tok::kw_try);
1048 ParsedAttributes &Attrs, ParsedAttributes &DeclSpecAttrs,
1054 "expected uninitialised source range");
1059 ParsedTemplateInfo TemplateInfo;
1062 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
1063 DeclSpecContext::DSC_top_level);
1068 DS, AS, DeclSpecContext::DSC_top_level))
1073 if (Tok.is(tok::semi)) {
1076 SourceLocation CorrectLocationForAttributes{};
1080 if (
const auto *ED = dyn_cast_or_null<EnumDecl>(DS.
getRepAsDecl())) {
1081 CorrectLocationForAttributes =
1082 PP.getLocForEndOfToken(ED->getEnumKeyRange().getEnd());
1085 if (CorrectLocationForAttributes.
isInvalid()) {
1086 const auto &Policy = Actions.getASTContext().getPrintingPolicy();
1089 CorrectLocationForAttributes =
1093 ProhibitAttributes(Attrs, CorrectLocationForAttributes);
1095 RecordDecl *AnonRecord =
nullptr;
1096 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
1099 Actions.ActOnDefinedDeclarationSpecifier(TheDecl);
1101 Decl* decls[] = {AnonRecord, TheDecl};
1102 return Actions.BuildDeclaratorGroup(decls);
1104 return Actions.ConvertDeclToDeclGroup(TheDecl);
1108 Actions.ActOnDefinedDeclarationSpecifier(DS.
getRepAsDecl());
1115 if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
1116 !Tok.isObjCAtKeyword(tok::objc_protocol) &&
1117 !Tok.isObjCAtKeyword(tok::objc_implementation)) {
1118 Diag(Tok, diag::err_objc_unexpected_attr);
1126 const char *PrevSpec =
nullptr;
1129 Actions.getASTContext().getPrintingPolicy()))
1130 Diag(AtLoc, DiagID) << PrevSpec;
1132 if (Tok.isObjCAtKeyword(tok::objc_protocol))
1133 return ParseObjCAtProtocolDeclaration(AtLoc, DS.
getAttributes());
1135 if (Tok.isObjCAtKeyword(tok::objc_implementation))
1136 return ParseObjCAtImplementationDeclaration(AtLoc, DS.
getAttributes());
1138 return Actions.ConvertDeclToDeclGroup(
1139 ParseObjCAtInterfaceDeclaration(AtLoc, DS.
getAttributes()));
1148 ProhibitAttributes(Attrs);
1150 return Actions.ConvertDeclToDeclGroup(TheDecl);
1157 ParsedAttributes &Attrs, ParsedAttributes &DeclSpecAttrs,
1161 llvm::TimeTraceScope TimeScope(
"ParseDeclarationOrFunctionDefinition", [&]() {
1162 return Tok.getLocation().printToString(
1163 Actions.getASTContext().getSourceManager());
1167 return ParseDeclOrFunctionDefInternal(Attrs, DeclSpecAttrs, *DS, AS);
1169 ParsingDeclSpec PDS(*
this);
1173 ObjCDeclContextSwitch ObjCDC(*
this);
1175 return ParseDeclOrFunctionDefInternal(Attrs, DeclSpecAttrs, PDS, AS);
1179Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
1180 const ParsedTemplateInfo &TemplateInfo,
1181 LateParsedAttrList *LateParsedAttrs) {
1182 llvm::TimeTraceScope TimeScope(
"ParseFunctionDefinition", [&]() {
1183 return Actions.GetNameForDeclarator(D).getName().getAsString();
1189 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1198 const char *PrevSpec;
1200 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1212 ParseKNRParamDeclarations(D);
1216 if (Tok.isNot(tok::l_brace) &&
1218 (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
1219 Tok.isNot(tok::equal)))) {
1220 Diag(Tok, diag::err_expected_fn_body);
1226 if (Tok.isNot(tok::l_brace))
1232 if (Tok.isNot(tok::equal)) {
1234 if (AL.isKnownToGCC() && !AL.isStandardAttributeSyntax())
1235 Diag(AL.getLoc(), diag::warn_attribute_on_function_definition) << AL;
1240 if (
getLangOpts().DelayedTemplateParsing && Tok.isNot(tok::equal) &&
1242 LateParsedAttrs->empty() && Actions.canDelayFunctionBody(D)) {
1250 Decl *DP = Actions.HandleDeclarator(ParentScope, D,
1255 if (SkipFunctionBodies && (!DP || Actions.canSkipFunctionBody(DP)) &&
1256 trySkippingFunctionBody()) {
1258 return Actions.ActOnSkippedFunctionBody(DP);
1262 LexTemplateFunctionForLateParsing(Toks);
1266 Actions.CheckForFunctionRedefinition(FnD);
1267 Actions.MarkAsLateParsedTemplate(FnD, DP, Toks);
1271 if (CurParsedObjCImpl && !TemplateInfo.TemplateParams &&
1272 (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) || Tok.is(tok::colon)) &&
1273 Actions.CurContext->isTranslationUnit()) {
1279 Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
1285 StashAwayMethodOrFunctionBodyTokens(FuncDecl);
1286 CurParsedObjCImpl->HasCFunction =
true;
1298 StringLiteral *DeletedMessage =
nullptr;
1300 SourceLocation KWLoc;
1306 ? diag::warn_cxx98_compat_defaulted_deleted_function
1307 : diag::ext_defaulted_deleted_function)
1310 DeletedMessage = ParseCXXDeletedFunctionMessage();
1313 ? diag::warn_cxx98_compat_defaulted_deleted_function
1314 : 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,
2454 if (PP.hadModuleLoaderFatalFailure()) {
2461 bool SeenError =
true;
2462 switch (ImportState) {
2474 Diag(ImportLoc, diag::err_partition_import_outside_module);
2486 if (IsPartition || (HeaderUnit && HeaderUnit->
Kind !=
2488 Diag(ImportLoc, diag::err_import_in_wrong_fragment)
2497 Diag(ImportLoc, diag::err_import_not_allowed_here);
2503 bool LexedSemi =
false;
2506 !ExpectAndConsumeSemi(diag::err_expected_semi_after_module_or_import,
2509 LexedSemi = !ExpectAndConsumeSemi(diag::err_module_expected_semi);
2520 Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, HeaderUnit);
2521 else if (!Path.empty())
2522 Import = Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Path,
2529 if (IsObjCAtImport && AtLoc.
isValid()) {
2530 auto &SrcMgr = PP.getSourceManager();
2531 auto FE = SrcMgr.getFileEntryRefForID(SrcMgr.getFileID(AtLoc));
2532 if (FE && llvm::sys::path::parent_path(FE->getDir().getName())
2533 .ends_with(
".framework"))
2534 Diags.Report(AtLoc, diag::warn_atimport_in_framework_header);
2540bool Parser::ParseModuleName(SourceLocation UseLoc,
2541 SmallVectorImpl<IdentifierLoc> &Path,
2543 if (Tok.isNot(tok::annot_module_name)) {
2547 ModuleNameLoc *NameLoc =
2548 static_cast<ModuleNameLoc *
>(Tok.getAnnotationValue());
2551 ConsumeAnnotationToken();
2555bool Parser::parseMisplacedModuleImport() {
2557 switch (Tok.getKind()) {
2558 case tok::annot_module_end:
2562 if (MisplacedModuleBeginCount) {
2563 --MisplacedModuleBeginCount;
2564 Actions.ActOnAnnotModuleEnd(
2566 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
2567 ConsumeAnnotationToken();
2574 case tok::annot_module_begin:
2576 Actions.ActOnAnnotModuleBegin(
2578 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
2579 ConsumeAnnotationToken();
2580 ++MisplacedModuleBeginCount;
2582 case tok::annot_module_include:
2585 Actions.ActOnAnnotModuleInclude(
2587 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
2588 ConsumeAnnotationToken();
2598void Parser::diagnoseUseOfC11Keyword(
const Token &Tok) {
2603 : diag::ext_c11_feature)
2607bool BalancedDelimiterTracker::diagnoseOverflow() {
2608 P.Diag(P.Tok, diag::err_bracket_depth_exceeded)
2609 << P.getLangOpts().BracketDepth;
2610 P.Diag(P.Tok, diag::note_bracket_depth);
2618 LOpen = P.Tok.getLocation();
2619 if (P.ExpectAndConsume(Kind, DiagID, Msg)) {
2620 if (SkipToTok != tok::unknown)
2625 if (getDepth() < P.getLangOpts().BracketDepth)
2628 return diagnoseOverflow();
2631bool BalancedDelimiterTracker::diagnoseMissingClose() {
2632 assert(!P.Tok.is(Close) &&
"Should have consumed closing delimiter");
2634 if (P.Tok.is(tok::annot_module_end))
2635 P.Diag(P.Tok, diag::err_missing_before_module_end) << Close;
2637 P.Diag(P.Tok, diag::err_expected) << Close;
2638 P.Diag(LOpen, diag::note_matching) << Kind;
2642 if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) &&
2643 P.Tok.isNot(tok::r_square) &&
2644 P.SkipUntil(Close, FinalToken,
2647 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)
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
A little helper class used to produce diagnostics.
static unsigned getCXXCompatDiagId(const LangOptions &LangOpts, unsigned CompatDiagId)
Get the appropriate diagnostic Id to use for issuing a compatibility diagnostic.
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
One of these records is kept for each identifier that is lexed.
tok::TokenKind getTokenID() const
If this is a source-language token (e.g.
A simple pair of identifier info and location.
Describes a module import declaration, which makes the contents of the named module visible in the cu...
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 '!
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
@ 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.