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);
198 if (!Tok.is(tok::semi))
return;
200 bool HadMultipleSemis =
false;
201 SourceLocation StartLoc = Tok.getLocation();
202 SourceLocation EndLoc = Tok.getLocation();
205 while ((Tok.is(tok::semi) && !Tok.isAtStartOfLine())) {
206 HadMultipleSemis =
true;
207 EndLoc = Tok.getLocation();
215 Diag(StartLoc, diag::warn_cxx98_compat_top_level_semi)
218 Diag(StartLoc, diag::ext_extra_semi_cxx11)
224 Diag(StartLoc, diag::ext_extra_semi)
227 TST, Actions.getASTContext().getPrintingPolicy())
231 Diag(StartLoc, diag::warn_extra_semi_after_mem_fn_def)
235bool Parser::expectIdentifier() {
236 if (Tok.is(tok::identifier))
238 if (
const auto *II = Tok.getIdentifierInfo()) {
240 Diag(Tok, diag::err_expected_token_instead_of_objcxx_keyword)
241 << tok::identifier << Tok.getIdentifierInfo();
246 Diag(Tok, diag::err_expected) << tok::identifier;
254 SourceLocation SecondTokLoc = Tok.getLocation();
259 PP.getSourceManager().getFileID(FirstTokLoc) !=
260 PP.getSourceManager().getFileID(SecondTokLoc)) {
261 Diag(FirstTokLoc, diag::warn_compound_token_split_by_macro)
262 << (FirstTokKind == Tok.getKind()) << FirstTokKind << Tok.getKind()
263 <<
static_cast<int>(Op) << SourceRange(FirstTokLoc);
264 Diag(SecondTokLoc, diag::note_compound_token_split_second_token_here)
265 << (FirstTokKind == Tok.getKind()) << Tok.getKind()
266 << SourceRange(SecondTokLoc);
271 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
272 SourceLocation SpaceLoc = PP.getLocForEndOfToken(FirstTokLoc);
274 SpaceLoc = FirstTokLoc;
275 Diag(SpaceLoc, diag::warn_compound_token_split_by_whitespace)
276 << (FirstTokKind == Tok.getKind()) << FirstTokKind << Tok.getKind()
277 <<
static_cast<int>(Op) << SourceRange(FirstTokLoc, SecondTokLoc);
287 return (
static_cast<unsigned>(L) &
static_cast<unsigned>(R)) != 0;
293 bool isFirstTokenSkipped =
true;
296 for (
unsigned i = 0, NumToks = Toks.size(); i != NumToks; ++i) {
297 if (Tok.is(Toks[i])) {
310 if (Toks.size() == 1 && Toks[0] == tok::eof &&
313 while (Tok.isNot(tok::eof))
318 switch (Tok.getKind()) {
323 case tok::annot_pragma_openmp:
324 case tok::annot_attr_openmp:
325 case tok::annot_pragma_openmp_end:
327 if (OpenMPDirectiveParsing)
329 ConsumeAnnotationToken();
331 case tok::annot_pragma_openacc:
332 case tok::annot_pragma_openacc_end:
334 if (OpenACCDirectiveParsing)
336 ConsumeAnnotationToken();
338 case tok::annot_module_begin:
339 case tok::annot_module_end:
340 case tok::annot_module_include:
341 case tok::annot_repl_input_end:
347 case tok::code_completion:
349 handleUnexpectedCodeCompletionToken();
391 if (ParenCount && !isFirstTokenSkipped)
396 if (BracketCount && !isFirstTokenSkipped)
401 if (BraceCount && !isFirstTokenSkipped)
415 isFirstTokenSkipped =
false;
424 if (NumCachedScopes) {
425 Scope *N = ScopeCache[--NumCachedScopes];
427 Actions.CurScope = N;
438 Actions.ActOnPopScope(Tok.getLocation(),
getCurScope());
441 Actions.CurScope = OldScope->
getParent();
443 if (NumCachedScopes == ScopeCacheSize)
446 ScopeCache[NumCachedScopes++] = OldScope;
449Parser::ParseScopeFlags::ParseScopeFlags(
Parser *
Self,
unsigned ScopeFlags,
451 : CurScope(ManageFlags ?
Self->getCurScope() :
nullptr) {
453 OldFlags = CurScope->getFlags();
454 CurScope->setFlags(ScopeFlags);
458Parser::ParseScopeFlags::~ParseScopeFlags() {
460 CurScope->setFlags(OldFlags);
471 Actions.CurScope =
nullptr;
474 for (
unsigned i = 0, e = NumCachedScopes; i != e; ++i)
475 delete ScopeCache[i];
477 resetPragmaHandlers();
479 PP.removeCommentHandler(CommentSemaHandler.get());
481 PP.clearCodeCompletionHandler();
483 DestroyTemplateIds();
488 assert(
getCurScope() ==
nullptr &&
"A scope is already active?");
496 &PP.getIdentifierTable().get(
"in");
498 &PP.getIdentifierTable().get(
"out");
500 &PP.getIdentifierTable().get(
"inout");
502 &PP.getIdentifierTable().get(
"oneway");
504 &PP.getIdentifierTable().get(
"bycopy");
506 &PP.getIdentifierTable().get(
"byref");
508 &PP.getIdentifierTable().get(
"nonnull");
510 &PP.getIdentifierTable().get(
"nullable");
512 &PP.getIdentifierTable().get(
"null_unspecified");
515 Ident_instancetype =
nullptr;
516 Ident_final =
nullptr;
517 Ident_sealed =
nullptr;
518 Ident_abstract =
nullptr;
519 Ident_override =
nullptr;
520 Ident_GNU_final =
nullptr;
522 Ident_super = &PP.getIdentifierTable().get(
"super");
524 Ident_vector =
nullptr;
525 Ident_bool =
nullptr;
526 Ident_Bool =
nullptr;
527 Ident_pixel =
nullptr;
529 Ident_vector = &PP.getIdentifierTable().get(
"vector");
530 Ident_bool = &PP.getIdentifierTable().get(
"bool");
531 Ident_Bool = &PP.getIdentifierTable().get(
"_Bool");
534 Ident_pixel = &PP.getIdentifierTable().get(
"pixel");
536 Ident_introduced =
nullptr;
537 Ident_deprecated =
nullptr;
538 Ident_obsoleted =
nullptr;
539 Ident_unavailable =
nullptr;
540 Ident_strict =
nullptr;
541 Ident_replacement =
nullptr;
543 Ident_language = Ident_defined_in = Ident_generated_declaration = Ident_USR =
546 Ident__except =
nullptr;
548 Ident__exception_code = Ident__exception_info =
nullptr;
549 Ident__abnormal_termination = Ident___exception_code =
nullptr;
550 Ident___exception_info = Ident___abnormal_termination =
nullptr;
551 Ident_GetExceptionCode = Ident_GetExceptionInfo =
nullptr;
552 Ident_AbnormalTermination =
nullptr;
555 Ident__exception_info = PP.getIdentifierInfo(
"_exception_info");
556 Ident___exception_info = PP.getIdentifierInfo(
"__exception_info");
557 Ident_GetExceptionInfo = PP.getIdentifierInfo(
"GetExceptionInformation");
558 Ident__exception_code = PP.getIdentifierInfo(
"_exception_code");
559 Ident___exception_code = PP.getIdentifierInfo(
"__exception_code");
560 Ident_GetExceptionCode = PP.getIdentifierInfo(
"GetExceptionCode");
561 Ident__abnormal_termination = PP.getIdentifierInfo(
"_abnormal_termination");
562 Ident___abnormal_termination = PP.getIdentifierInfo(
"__abnormal_termination");
563 Ident_AbnormalTermination = PP.getIdentifierInfo(
"AbnormalTermination");
565 PP.SetPoisonReason(Ident__exception_code,diag::err_seh___except_block);
566 PP.SetPoisonReason(Ident___exception_code,diag::err_seh___except_block);
567 PP.SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block);
568 PP.SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter);
569 PP.SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter);
570 PP.SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter);
571 PP.SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block);
572 PP.SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block);
573 PP.SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block);
576 Actions.Initialize();
582void Parser::DestroyTemplateIds() {
590 Actions.ActOnStartOfTranslationUnit();
602 if (NoTopLevelDecls && !Actions.getASTContext().getExternalSource() &&
604 Diag(diag::ext_empty_translation_unit);
606 return NoTopLevelDecls;
611 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*
this);
614 switch (Tok.getKind()) {
615 case tok::annot_pragma_unused:
616 HandlePragmaUnused();
632 Result = ParseModuleDecl(ImportState);
642 case tok::annot_module_include: {
643 auto Loc = Tok.getLocation();
644 Module *Mod =
reinterpret_cast<Module *
>(Tok.getAnnotationValue());
648 Actions.ActOnAnnotModuleInclude(Loc, Mod);
655 ConsumeAnnotationToken();
659 case tok::annot_module_begin:
660 Actions.ActOnAnnotModuleBegin(
662 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
663 ConsumeAnnotationToken();
667 case tok::annot_module_end:
668 Actions.ActOnAnnotModuleEnd(
670 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
671 ConsumeAnnotationToken();
676 case tok::annot_repl_input_end:
678 if (PP.getMaxTokens() != 0 && PP.getTokenCount() > PP.getMaxTokens()) {
679 PP.Diag(Tok.getLocation(), diag::warn_max_tokens_total)
680 << PP.getTokenCount() << PP.getMaxTokens();
683 PP.Diag(OverrideLoc, diag::note_max_tokens_total_override);
688 Actions.SetLateTemplateParser(LateTemplateParserCallback,
this);
689 Actions.ActOnEndOfTranslationUnit();
702 while (MaybeParseCXX11Attributes(DeclAttrs) ||
703 MaybeParseGNUAttributes(DeclSpecAttrs))
706 Result = ParseExternalDeclaration(DeclAttrs, DeclSpecAttrs);
716 else if (ImportState ==
728 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*
this);
736 Decl *SingleDecl =
nullptr;
737 switch (
Tok.getKind()) {
738 case tok::annot_pragma_vis:
739 HandlePragmaVisibility();
741 case tok::annot_pragma_pack:
744 case tok::annot_pragma_msstruct:
745 HandlePragmaMSStruct();
747 case tok::annot_pragma_align:
750 case tok::annot_pragma_weak:
753 case tok::annot_pragma_weakalias:
754 HandlePragmaWeakAlias();
756 case tok::annot_pragma_redefine_extname:
757 HandlePragmaRedefineExtname();
759 case tok::annot_pragma_fp_contract:
760 HandlePragmaFPContract();
762 case tok::annot_pragma_fenv_access:
763 case tok::annot_pragma_fenv_access_ms:
764 HandlePragmaFEnvAccess();
766 case tok::annot_pragma_fenv_round:
767 HandlePragmaFEnvRound();
769 case tok::annot_pragma_cx_limited_range:
770 HandlePragmaCXLimitedRange();
772 case tok::annot_pragma_float_control:
773 HandlePragmaFloatControl();
775 case tok::annot_pragma_fp:
778 case tok::annot_pragma_opencl_extension:
779 HandlePragmaOpenCLExtension();
781 case tok::annot_attr_openmp:
782 case tok::annot_pragma_openmp: {
784 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
786 case tok::annot_pragma_openacc: {
791 case tok::annot_pragma_ms_pointers_to_members:
792 HandlePragmaMSPointersToMembers();
794 case tok::annot_pragma_ms_vtordisp:
795 HandlePragmaMSVtorDisp();
797 case tok::annot_pragma_ms_pragma:
798 HandlePragmaMSPragma();
800 case tok::annot_pragma_dump:
803 case tok::annot_pragma_attribute:
804 HandlePragmaAttribute();
806 case tok::annot_pragma_export:
807 HandlePragmaExport();
812 Actions.ActOnEmptyDeclaration(
getCurScope(), Attrs, Tok.getLocation());
816 Diag(Tok, diag::err_extraneous_closing_brace);
820 Diag(Tok, diag::err_expected_external_declaration);
822 case tok::kw___extension__: {
824 ExtensionRAIIObject O(Diags);
826 return ParseExternalDeclaration(Attrs, DeclSpecAttrs);
829 ProhibitAttributes(Attrs);
831 SourceLocation StartLoc = Tok.getLocation();
832 SourceLocation EndLoc;
841 if (!SL->getString().trim().empty())
842 Diag(StartLoc, diag::err_gnu_inline_asm_disabled);
845 ExpectAndConsume(tok::semi, diag::err_expected_after,
846 "top-level asm block");
850 SingleDecl = Actions.ActOnFileScopeAsmDecl(
Result.get(), StartLoc, EndLoc);
854 return ParseObjCAtDirectives(Attrs, DeclSpecAttrs);
858 Diag(Tok, diag::err_expected_external_declaration);
862 SingleDecl = ParseObjCMethodDefinition();
864 case tok::code_completion:
866 if (CurParsedObjCImpl) {
868 Actions.CodeCompletion().CodeCompleteObjCMethodDecl(
875 if (CurParsedObjCImpl) {
877 }
else if (PP.isIncrementalProcessingEnabled()) {
882 Actions.CodeCompletion().CodeCompleteOrdinaryName(
getCurScope(), PCC);
884 case tok::kw_import: {
887 Diag(Tok, diag::err_unexpected_module_or_import_decl)
892 SingleDecl = ParseModuleImport(SourceLocation(), IS);
896 ProhibitAttributes(Attrs);
897 SingleDecl = ParseExportDeclaration();
904 case tok::kw_namespace:
905 case tok::kw_typedef:
906 case tok::kw_template:
907 case tok::kw_static_assert:
908 case tok::kw__Static_assert:
911 SourceLocation DeclEnd;
916 case tok::kw_cbuffer:
917 case tok::kw_tbuffer:
919 SourceLocation DeclEnd;
931 SourceLocation DeclEnd;
942 if (NextKind == tok::kw_namespace) {
943 SourceLocation DeclEnd;
950 if (NextKind == tok::kw_template) {
953 SourceLocation DeclEnd;
962 ProhibitAttributes(Attrs);
963 ProhibitAttributes(DeclSpecAttrs);
968 diag::warn_cxx98_compat_extern_template :
969 diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc);
970 SourceLocation DeclEnd;
972 TemplateLoc, DeclEnd, Attrs);
976 case tok::kw___if_exists:
977 case tok::kw___if_not_exists:
978 ParseMicrosoftIfExistsExternalDeclaration();
982 Diag(Tok, diag::err_unexpected_module_or_import_decl) <<
false;
988 if (Tok.isEditorPlaceholder()) {
993 !isDeclarationStatement(
true))
994 return ParseTopLevelStmtDecl();
998 return ParseDeclarationOrFunctionDefinition(Attrs, DeclSpecAttrs, DS);
1003 return Actions.ConvertDeclToDeclGroup(SingleDecl);
1006bool Parser::isDeclarationAfterDeclarator() {
1010 if (KW.
is(tok::kw_default) || KW.
is(tok::kw_delete))
1014 return Tok.is(tok::equal) ||
1015 Tok.is(tok::comma) ||
1016 Tok.is(tok::semi) ||
1017 Tok.is(tok::kw_asm) ||
1018 Tok.is(tok::kw___attribute) ||
1020 Tok.is(tok::l_paren));
1023bool Parser::isStartOfFunctionDefinition(
const ParsingDeclarator &Declarator) {
1024 assert(
Declarator.isFunctionDeclarator() &&
"Isn't a function declarator");
1025 if (Tok.is(tok::l_brace))
1030 Declarator.getFunctionTypeInfo().isKNRPrototype())
1035 return KW.
is(tok::kw_default) || KW.
is(tok::kw_delete);
1038 return Tok.is(tok::colon) ||
1039 Tok.is(tok::kw_try);
1043 ParsedAttributes &Attrs, ParsedAttributes &DeclSpecAttrs,
1049 "expected uninitialised source range");
1054 ParsedTemplateInfo TemplateInfo;
1057 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
1058 DeclSpecContext::DSC_top_level);
1063 DS, AS, DeclSpecContext::DSC_top_level))
1068 if (Tok.is(tok::semi)) {
1071 SourceLocation CorrectLocationForAttributes{};
1075 if (
const auto *ED = dyn_cast_or_null<EnumDecl>(DS.
getRepAsDecl())) {
1076 CorrectLocationForAttributes =
1077 PP.getLocForEndOfToken(ED->getEnumKeyRange().getEnd());
1080 if (CorrectLocationForAttributes.
isInvalid()) {
1081 const auto &Policy = Actions.getASTContext().getPrintingPolicy();
1084 CorrectLocationForAttributes =
1088 ProhibitAttributes(Attrs, CorrectLocationForAttributes);
1090 RecordDecl *AnonRecord =
nullptr;
1091 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
1094 Actions.ActOnDefinedDeclarationSpecifier(TheDecl);
1096 Decl* decls[] = {AnonRecord, TheDecl};
1097 return Actions.BuildDeclaratorGroup(decls);
1099 return Actions.ConvertDeclToDeclGroup(TheDecl);
1103 Actions.ActOnDefinedDeclarationSpecifier(DS.
getRepAsDecl());
1110 if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
1111 !Tok.isObjCAtKeyword(tok::objc_protocol) &&
1112 !Tok.isObjCAtKeyword(tok::objc_implementation)) {
1113 Diag(Tok, diag::err_objc_unexpected_attr);
1121 const char *PrevSpec =
nullptr;
1124 Actions.getASTContext().getPrintingPolicy()))
1125 Diag(AtLoc, DiagID) << PrevSpec;
1127 if (Tok.isObjCAtKeyword(tok::objc_protocol))
1128 return ParseObjCAtProtocolDeclaration(AtLoc, DS.
getAttributes());
1130 if (Tok.isObjCAtKeyword(tok::objc_implementation))
1131 return ParseObjCAtImplementationDeclaration(AtLoc, DS.
getAttributes());
1133 return Actions.ConvertDeclToDeclGroup(
1134 ParseObjCAtInterfaceDeclaration(AtLoc, DS.
getAttributes()));
1143 ProhibitAttributes(Attrs);
1145 return Actions.ConvertDeclToDeclGroup(TheDecl);
1152 ParsedAttributes &Attrs, ParsedAttributes &DeclSpecAttrs,
1156 llvm::TimeTraceScope TimeScope(
"ParseDeclarationOrFunctionDefinition", [&]() {
1157 return Tok.getLocation().printToString(
1158 Actions.getASTContext().getSourceManager());
1162 return ParseDeclOrFunctionDefInternal(Attrs, DeclSpecAttrs, *DS, AS);
1164 ParsingDeclSpec PDS(*
this);
1168 ObjCDeclContextSwitch ObjCDC(*
this);
1170 return ParseDeclOrFunctionDefInternal(Attrs, DeclSpecAttrs, PDS, AS);
1174Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
1175 const ParsedTemplateInfo &TemplateInfo,
1176 LateParsedAttrList *LateParsedAttrs) {
1177 llvm::TimeTraceScope TimeScope(
"ParseFunctionDefinition", [&]() {
1178 return Actions.GetNameForDeclarator(D).getName().getAsString();
1184 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1193 const char *PrevSpec;
1195 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1207 ParseKNRParamDeclarations(D);
1211 if (Tok.isNot(tok::l_brace) &&
1213 (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
1214 Tok.isNot(tok::equal)))) {
1215 Diag(Tok, diag::err_expected_fn_body);
1221 if (Tok.isNot(tok::l_brace))
1227 if (Tok.isNot(tok::equal)) {
1229 if (AL.isKnownToGCC() && !AL.isStandardAttributeSyntax())
1230 Diag(AL.getLoc(), diag::warn_attribute_on_function_definition) << AL;
1235 if (
getLangOpts().DelayedTemplateParsing && Tok.isNot(tok::equal) &&
1237 LateParsedAttrs->empty() && Actions.canDelayFunctionBody(D)) {
1245 Decl *DP = Actions.HandleDeclarator(ParentScope, D,
1250 if (SkipFunctionBodies && (!DP || Actions.canSkipFunctionBody(DP)) &&
1251 trySkippingFunctionBody()) {
1253 return Actions.ActOnSkippedFunctionBody(DP);
1257 LexTemplateFunctionForLateParsing(Toks);
1261 Actions.CheckForFunctionRedefinition(FnD);
1262 Actions.MarkAsLateParsedTemplate(FnD, DP, Toks);
1266 if (CurParsedObjCImpl && !TemplateInfo.TemplateParams &&
1267 (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) || Tok.is(tok::colon)) &&
1268 Actions.CurContext->isTranslationUnit()) {
1274 Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
1280 StashAwayMethodOrFunctionBodyTokens(FuncDecl);
1281 CurParsedObjCImpl->HasCFunction =
true;
1293 StringLiteral *DeletedMessage =
nullptr;
1295 SourceLocation KWLoc;
1301 ? diag::warn_cxx98_compat_defaulted_deleted_function
1302 : diag::ext_defaulted_deleted_function)
1305 DeletedMessage = ParseCXXDeletedFunctionMessage();
1308 ? diag::warn_cxx98_compat_defaulted_deleted_function
1309 : diag::ext_defaulted_deleted_function)
1313 llvm_unreachable(
"function definition after = not 'delete' or 'default'");
1316 if (Tok.is(tok::comma)) {
1317 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
1320 }
else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
1328 Sema::FPFeaturesStateRAII SaveFPFeatures(Actions);
1332 SkipBodyInfo SkipBody;
1334 TemplateInfo.TemplateParams
1335 ? *TemplateInfo.TemplateParams
1337 &SkipBody, BodyKind);
1354 Actions.PopExpressionEvaluationContext();
1366 Actions.SetFunctionBodyKind(Res, KWLoc, BodyKind, DeletedMessage);
1367 Stmt *GeneratedBody = Res ? Res->
getBody() :
nullptr;
1368 Actions.ActOnFinishFunctionBody(Res, GeneratedBody,
false);
1374 if (
const auto *
Template = dyn_cast_if_present<FunctionTemplateDecl>(Res);
1376 Template->getTemplateParameters()->getParam(0)->isImplicit())
1379 CurTemplateDepthTracker.addDepth(1);
1382 if (LateParsedAttrs)
1383 ParseLexedAttributeList(*LateParsedAttrs, Res,
false,
1386 if (SkipFunctionBodies && (!Res || Actions.canSkipFunctionBody(Res)) &&
1387 trySkippingFunctionBody()) {
1389 Actions.ActOnSkippedFunctionBody(Res);
1390 return Actions.ActOnFinishFunctionBody(Res,
nullptr,
false);
1393 if (Tok.is(tok::kw_try))
1394 return ParseFunctionTryBlock(Res, BodyScope);
1398 if (Tok.is(tok::colon)) {
1399 ParseConstructorInitializer(Res);
1402 if (!Tok.is(tok::l_brace)) {
1404 Actions.ActOnFinishFunctionBody(Res,
nullptr);
1408 Actions.ActOnDefaultCtorInitializers(Res);
1410 return ParseFunctionStatementBody(Res, BodyScope);
1413void Parser::SkipFunctionBody() {
1414 if (Tok.is(tok::equal)) {
1419 bool IsFunctionTryBlock = Tok.is(tok::kw_try);
1420 if (IsFunctionTryBlock)
1424 if (ConsumeAndStoreFunctionPrologue(Skipped))
1428 while (IsFunctionTryBlock && Tok.is(tok::kw_catch)) {
1435void Parser::ParseKNRParamDeclarations(Declarator &D) {
1446 SourceLocation DSStart = Tok.getLocation();
1449 DeclSpec DS(AttrFactory);
1450 ParsedTemplateInfo TemplateInfo;
1451 ParseDeclarationSpecifiers(DS, TemplateInfo);
1459 Diag(DSStart, diag::err_declaration_does_not_declare_param);
1468 diag::err_invalid_storage_class_in_func_decl);
1473 diag::err_invalid_storage_class_in_func_decl);
1480 ParseDeclarator(ParmDeclarator);
1485 MaybeParseGNUAttributes(ParmDeclarator);
1489 Actions.ActOnParamDeclarator(
getCurScope(), ParmDeclarator);
1493 ParmDeclarator.getIdentifier()) {
1497 for (
unsigned i = 0; ; ++i) {
1501 Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
1502 << ParmDeclarator.getIdentifier();
1506 if (FTI.
Params[i].
Ident == ParmDeclarator.getIdentifier()) {
1509 Diag(ParmDeclarator.getIdentifierLoc(),
1510 diag::err_param_redefinition)
1511 << ParmDeclarator.getIdentifier();
1522 if (Tok.isNot(tok::comma))
1525 ParmDeclarator.clear();
1531 ParseDeclarator(ParmDeclarator);
1535 if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration))
1545 Actions.ActOnFinishKNRParamDeclarations(
getCurScope(), D, Tok.getLocation());
1548ExprResult Parser::ParseAsmStringLiteral(
bool ForAsmLabel) {
1551 if (isTokenStringLiteral()) {
1557 if (!SL->isOrdinary()) {
1558 Diag(Tok, diag::err_asm_operand_wide_string_literal)
1559 << SL->isWide() << SL->getSourceRange();
1563 Tok.is(tok::l_paren)) {
1565 SourceLocation RParenLoc;
1568 EnterExpressionEvaluationContext ConstantEvaluated(
1570 AsmString = ParseParenExpression(
1574 AsmString = Actions.ActOnConstantExpression(AsmString);
1579 Diag(Tok, diag::err_asm_expected_string) << (
1580 (
getLangOpts().CPlusPlus11 && !ForAsmLabel) ? 0 : 1);
1583 return Actions.ActOnGCCAsmStmtString(AsmString.
get(), ForAsmLabel);
1586ExprResult Parser::ParseSimpleAsm(
bool ForAsmLabel, SourceLocation *EndLoc) {
1587 assert(Tok.is(tok::kw_asm) &&
"Not an asm!");
1590 if (isGNUAsmQualifier(Tok)) {
1592 SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
1593 PP.getLocForEndOfToken(Tok.getLocation()));
1594 Diag(Tok, diag::err_global_asm_qualifier_ignored)
1595 << GNUAsmQualifiers::getQualifierName(getGNUAsmQualifier(Tok))
1601 if (T.consumeOpen()) {
1602 Diag(Tok, diag::err_expected_lparen_after) <<
"asm";
1608 if (!
Result.isInvalid()) {
1612 *EndLoc = T.getCloseLocation();
1615 *EndLoc = Tok.getLocation();
1622TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(
const Token &tok) {
1623 assert(tok.
is(tok::annot_template_id) &&
"Expected template-id token");
1624 TemplateIdAnnotation *
1629void Parser::AnnotateScopeToken(CXXScopeSpec &SS,
bool IsNewAnnotation) {
1632 if (PP.isBacktrackEnabled())
1633 PP.RevertCachedTokens(1);
1635 PP.EnterToken(Tok,
true);
1636 Tok.setKind(tok::annot_cxxscope);
1637 Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
1638 Tok.setAnnotationRange(SS.
getRange());
1643 if (IsNewAnnotation)
1644 PP.AnnotateCachedTokens(Tok);
1648Parser::TryAnnotateName(CorrectionCandidateCallback *CCC,
1650 assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
1652 const bool EnteringContext =
false;
1653 const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1657 ParseOptionalCXXScopeSpecifier(SS,
nullptr,
1662 if (Tok.isNot(tok::identifier) || SS.
isInvalid()) {
1664 AllowImplicitTypename))
1669 IdentifierInfo *Name = Tok.getIdentifierInfo();
1670 SourceLocation NameLoc = Tok.getLocation();
1674 if (isTentativelyDeclared(Name) && SS.
isEmpty()) {
1678 AllowImplicitTypename))
1690 Sema::NameClassification Classification = Actions.ClassifyName(
1698 isTemplateArgumentList(1) == TPResult::False) {
1700 Token FakeNext =
Next;
1701 FakeNext.
setKind(tok::unknown);
1703 Actions.ClassifyName(
getCurScope(), SS, Name, NameLoc, FakeNext,
1704 SS.
isEmpty() ? CCC :
nullptr);
1707 switch (Classification.
getKind()) {
1713 Tok.setIdentifierInfo(Name);
1715 PP.TypoCorrectToken(Tok);
1717 AnnotateScopeToken(SS, !WasScopeAnnotation);
1726 if (TryAltiVecVectorToken())
1731 SourceLocation BeginLoc = NameLoc;
1738 QualType T = Actions.GetTypeFromParser(Ty);
1743 SourceLocation NewEndLoc;
1745 = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
1750 else if (Tok.is(tok::eof))
1754 Tok.setKind(tok::annot_typename);
1755 setTypeAnnotation(Tok, Ty);
1756 Tok.setAnnotationEndLoc(Tok.getLocation());
1757 Tok.setLocation(BeginLoc);
1758 PP.AnnotateCachedTokens(Tok);
1763 Tok.setKind(tok::annot_overload_set);
1765 Tok.setAnnotationEndLoc(NameLoc);
1768 PP.AnnotateCachedTokens(Tok);
1772 if (TryAltiVecVectorToken())
1777 Tok.setKind(tok::annot_non_type);
1779 Tok.setLocation(NameLoc);
1780 Tok.setAnnotationEndLoc(NameLoc);
1781 PP.AnnotateCachedTokens(Tok);
1783 AnnotateScopeToken(SS, !WasScopeAnnotation);
1788 Tok.setKind(Classification.
getKind() ==
1790 ? tok::annot_non_type_undeclared
1791 : tok::annot_non_type_dependent);
1792 setIdentifierAnnotation(Tok, Name);
1793 Tok.setLocation(NameLoc);
1794 Tok.setAnnotationEndLoc(NameLoc);
1795 PP.AnnotateCachedTokens(Tok);
1797 AnnotateScopeToken(SS, !WasScopeAnnotation);
1801 if (
Next.isNot(tok::less)) {
1805 AnnotateScopeToken(SS, !WasScopeAnnotation);
1813 bool IsConceptName =
1819 if (
Next.is(tok::less))
1821 if (AnnotateTemplateIdToken(
1828 AnnotateScopeToken(SS, !WasScopeAnnotation);
1835 AnnotateScopeToken(SS, !WasScopeAnnotation);
1840 SourceLocation TokenEndLoc = PP.getLocForEndOfToken(PrevTokLocation);
1841 return TokenEndLoc.
isValid() ? TokenEndLoc : Tok.getLocation();
1844bool Parser::TryKeywordIdentFallback(
bool DisableKeyword) {
1845 assert(
Tok.isNot(tok::identifier));
1846 Diag(
Tok, diag::ext_keyword_as_ident)
1850 Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
1851 Tok.setKind(tok::identifier);
1857 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1858 Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope) ||
1859 Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id) ||
1860 Tok.is(tok::kw___super) || Tok.is(tok::kw_auto) ||
1861 Tok.is(tok::annot_pack_indexing_type)) &&
1862 "Cannot be a type or scope token!");
1864 if (Tok.is(tok::kw_typename)) {
1873 PP.Lex(TypedefToken);
1875 PP.EnterToken(Tok,
true);
1878 Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename);
1890 if (ParseOptionalCXXScopeSpecifier(SS,
nullptr,
1896 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) ||
1897 Tok.is(tok::annot_decltype)) {
1899 if (Tok.is(tok::annot_decltype) ||
1901 Tok.isAnnotation())) {
1902 unsigned DiagID = diag::err_expected_qualified_after_typename;
1906 DiagID = diag::warn_expected_qualified_after_typename;
1907 Diag(Tok.getLocation(), DiagID);
1911 if (Tok.isEditorPlaceholder())
1914 Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
1918 bool TemplateKWPresent =
false;
1919 if (Tok.is(tok::kw_template)) {
1921 TemplateKWPresent =
true;
1925 if (Tok.is(tok::identifier)) {
1927 Diag(Tok.getLocation(),
1928 diag::missing_template_arg_list_after_template_kw);
1931 Ty = Actions.ActOnTypenameType(
getCurScope(), TypenameLoc, SS,
1932 *Tok.getIdentifierInfo(),
1934 }
else if (Tok.is(tok::annot_template_id)) {
1937 Diag(Tok, diag::err_typename_refers_to_non_type_template)
1938 << Tok.getAnnotationRange();
1947 : Actions.ActOnTypenameType(
1951 TemplateArgsPtr, TemplateId->
RAngleLoc);
1953 Diag(Tok, diag::err_expected_type_name_after_typename)
1959 Tok.setKind(tok::annot_typename);
1960 setTypeAnnotation(Tok, Ty);
1961 Tok.setAnnotationEndLoc(EndLoc);
1962 Tok.setLocation(TypenameLoc);
1963 PP.AnnotateCachedTokens(Tok);
1968 bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1972 if (ParseOptionalCXXScopeSpecifier(SS,
nullptr,
1978 AllowImplicitTypename);
1984 if (Tok.is(tok::identifier)) {
1987 *Tok.getIdentifierInfo(), Tok.getLocation(),
getCurScope(), &SS,
1991 true, AllowImplicitTypename)) {
1996 QualType T = Actions.GetTypeFromParser(Ty);
2001 (T->isObjCObjectType() || T->isObjCObjectPointerType())) {
2011 else if (Tok.is(tok::eof))
2017 Tok.setKind(tok::annot_typename);
2018 setTypeAnnotation(Tok, Ty);
2019 Tok.setAnnotationEndLoc(Tok.getLocation());
2020 Tok.setLocation(BeginLoc);
2024 PP.AnnotateCachedTokens(Tok);
2041 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
2042 bool MemberOfUnknownSpecialization;
2047 MemberOfUnknownSpecialization)) {
2051 isTemplateArgumentList(1) != TPResult::False) {
2071 if (Tok.is(tok::annot_template_id)) {
2078 AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
2085 Tok.is(tok::coloncolon)) {
2094 AnnotateScopeToken(SS, IsNewScope);
2100 "Call sites of this function should be guarded by checking for C++");
2104 if (ParseOptionalCXXScopeSpecifier(SS,
nullptr,
2111 AnnotateScopeToken(SS,
true);
2115bool Parser::isTokenEqualOrEqualTypo() {
2121 case tok::starequal:
2122 case tok::plusequal:
2123 case tok::minusequal:
2124 case tok::exclaimequal:
2125 case tok::slashequal:
2126 case tok::percentequal:
2127 case tok::lessequal:
2128 case tok::lesslessequal:
2129 case tok::greaterequal:
2130 case tok::greatergreaterequal:
2131 case tok::caretequal:
2132 case tok::pipeequal:
2133 case tok::equalequal:
2134 Diag(
Tok, diag::err_invalid_token_after_declarator_suggest_equal)
2143SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
2144 assert(Tok.is(tok::code_completion));
2145 PrevTokLocation = Tok.getLocation();
2148 if (S->isFunctionScope()) {
2150 Actions.CodeCompletion().CodeCompleteOrdinaryName(
2152 return PrevTokLocation;
2155 if (S->isClassScope()) {
2157 Actions.CodeCompletion().CodeCompleteOrdinaryName(
2159 return PrevTokLocation;
2164 Actions.CodeCompletion().CodeCompleteOrdinaryName(
2166 return PrevTokLocation;
2171void Parser::CodeCompleteDirective(
bool InConditional) {
2172 Actions.CodeCompletion().CodeCompletePreprocessorDirective(InConditional);
2176 Actions.CodeCompletion().CodeCompleteInPreprocessorConditionalExclusion(
2180void Parser::CodeCompleteMacroName(
bool IsDefinition) {
2181 Actions.CodeCompletion().CodeCompletePreprocessorMacroName(IsDefinition);
2185 Actions.CodeCompletion().CodeCompletePreprocessorExpression();
2188void Parser::CodeCompleteMacroArgument(IdentifierInfo *
Macro,
2189 MacroInfo *MacroInfo,
2190 unsigned ArgumentIndex) {
2191 Actions.CodeCompletion().CodeCompletePreprocessorMacroArgument(
2195void Parser::CodeCompleteIncludedFile(llvm::StringRef Dir,
bool IsAngled) {
2196 Actions.CodeCompletion().CodeCompleteIncludedFile(Dir, IsAngled);
2200 Actions.CodeCompletion().CodeCompleteNaturalLanguage();
2203void Parser::CodeCompleteModuleImport(SourceLocation ImportLoc,
2205 Actions.CodeCompletion().CodeCompleteModuleImport(ImportLoc, Path);
2208bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition&
Result) {
2209 assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
2210 "Expected '__if_exists' or '__if_not_exists'");
2211 Result.IsIfExists = Tok.is(tok::kw___if_exists);
2215 if (T.consumeOpen()) {
2216 Diag(Tok, diag::err_expected_lparen_after)
2217 << (
Result.IsIfExists?
"__if_exists" :
"__if_not_exists");
2223 ParseOptionalCXXScopeSpecifier(
Result.SS,
nullptr,
2228 if (
Result.SS.isInvalid()) {
2234 SourceLocation TemplateKWLoc;
2239 false, &TemplateKWLoc,
2245 if (T.consumeClose())
2273void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
2274 IfExistsCondition
Result;
2275 if (ParseMicrosoftIfExistsCondition(
Result))
2279 if (
Braces.consumeOpen()) {
2280 Diag(Tok, diag::err_expected) << tok::l_brace;
2284 switch (
Result.Behavior) {
2290 llvm_unreachable(
"Cannot have a dependent external declaration");
2299 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
2300 ParsedAttributes Attrs(AttrFactory);
2301 MaybeParseCXX11Attributes(Attrs);
2302 ParsedAttributes EmptyDeclSpecAttrs(AttrFactory);
2305 Actions.getASTConsumer().HandleTopLevelDecl(
Result.get());
2312 Token Introducer = Tok;
2313 SourceLocation StartLoc = Introducer.
getLocation();
2319 assert(Tok.is(tok::kw_module) &&
"not a module declaration");
2325 DiagnoseAndSkipCXX11Attributes();
2328 if (
getLangOpts().CPlusPlusModules && Tok.is(tok::semi)) {
2332 Diag(StartLoc, diag::err_global_module_introducer_not_at_start)
2333 << SourceRange(StartLoc, SemiLoc);
2337 Diag(StartLoc, diag::err_module_fragment_exported)
2341 return Actions.ActOnGlobalModuleFragmentDecl(ModuleLoc);
2345 if (
getLangOpts().CPlusPlusModules && Tok.is(tok::colon) &&
2348 Diag(StartLoc, diag::err_module_fragment_exported)
2353 DiagnoseAndSkipCXX11Attributes();
2354 ExpectAndConsumeSemi(diag::err_private_module_fragment_expected_semi);
2358 return Actions.ActOnPrivateModuleFragmentDecl(ModuleLoc, PrivateLoc);
2361 SmallVector<IdentifierLoc, 2> Path;
2362 if (ParseModuleName(ModuleLoc, Path,
false))
2366 SmallVector<IdentifierLoc, 2> Partition;
2367 if (Tok.is(tok::colon)) {
2370 Diag(ColonLoc, diag::err_unsupported_module_partition)
2371 << SourceRange(ColonLoc, Partition.back().getLoc());
2373 else if (ParseModuleName(ModuleLoc, Partition,
false))
2378 if (!Tok.isOneOf(tok::semi, tok::l_square))
2382 ParsedAttributes Attrs(AttrFactory);
2383 MaybeParseCXX11Attributes(Attrs);
2384 ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_module_attr,
2385 diag::err_keyword_not_module_attr,
2389 if (ExpectAndConsumeSemi(diag::err_expected_semi_after_module_or_import,
2393 return Actions.ActOnModuleDecl(StartLoc, ModuleLoc, MDK, Path, Partition,
2398Decl *Parser::ParseModuleImport(SourceLocation AtLoc,
2400 SourceLocation StartLoc = AtLoc.
isInvalid() ? Tok.getLocation() : AtLoc;
2402 SourceLocation ExportLoc;
2405 assert((AtLoc.
isInvalid() ? Tok.is(tok::kw_import)
2406 : Tok.isObjCAtKeyword(tok::objc_import)) &&
2407 "Improper start to module import");
2408 bool IsObjCAtImport = Tok.isObjCAtKeyword(tok::objc_import);
2412 SmallVector<IdentifierLoc, 2> Path;
2413 bool IsPartition =
false;
2414 Module *HeaderUnit =
nullptr;
2415 if (Tok.is(tok::header_name)) {
2420 }
else if (Tok.is(tok::annot_header_unit)) {
2422 HeaderUnit =
reinterpret_cast<Module *
>(Tok.getAnnotationValue());
2423 ConsumeAnnotationToken();
2424 }
else if (Tok.is(tok::colon)) {
2427 Diag(ColonLoc, diag::err_unsupported_module_partition)
2428 << SourceRange(ColonLoc, Path.back().getLoc());
2430 else if (ParseModuleName(ColonLoc, Path,
true))
2435 if (ParseModuleName(ImportLoc, Path,
true))
2439 ParsedAttributes Attrs(AttrFactory);
2440 MaybeParseCXX11Attributes(Attrs);
2442 ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_import_attr,
2443 diag::err_keyword_not_import_attr,
2447 if (PP.hadModuleLoaderFatalFailure()) {
2454 bool SeenError =
true;
2455 switch (ImportState) {
2467 Diag(ImportLoc, diag::err_partition_import_outside_module);
2479 if (IsPartition || (HeaderUnit && HeaderUnit->
Kind !=
2481 Diag(ImportLoc, diag::err_import_in_wrong_fragment)
2490 Diag(ImportLoc, diag::err_import_not_allowed_here);
2496 bool LexedSemi =
false;
2499 !ExpectAndConsumeSemi(diag::err_expected_semi_after_module_or_import,
2502 LexedSemi = !ExpectAndConsumeSemi(diag::err_module_expected_semi);
2513 Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, HeaderUnit);
2514 else if (!Path.empty())
2515 Import = Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Path,
2522 if (IsObjCAtImport && AtLoc.
isValid()) {
2523 auto &SrcMgr = PP.getSourceManager();
2524 auto FE = SrcMgr.getFileEntryRefForID(SrcMgr.getFileID(AtLoc));
2525 if (FE && llvm::sys::path::parent_path(FE->getDir().getName())
2526 .ends_with(
".framework"))
2527 Diags.Report(AtLoc, diag::warn_atimport_in_framework_header);
2533bool Parser::ParseModuleName(SourceLocation UseLoc,
2534 SmallVectorImpl<IdentifierLoc> &Path,
2536 if (Tok.isNot(tok::annot_module_name)) {
2540 ModuleNameLoc *NameLoc =
2541 static_cast<ModuleNameLoc *
>(Tok.getAnnotationValue());
2544 ConsumeAnnotationToken();
2548bool Parser::parseMisplacedModuleImport() {
2550 switch (Tok.getKind()) {
2551 case tok::annot_module_end:
2555 if (MisplacedModuleBeginCount) {
2556 --MisplacedModuleBeginCount;
2557 Actions.ActOnAnnotModuleEnd(
2559 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
2560 ConsumeAnnotationToken();
2567 case tok::annot_module_begin:
2569 Actions.ActOnAnnotModuleBegin(
2571 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
2572 ConsumeAnnotationToken();
2573 ++MisplacedModuleBeginCount;
2575 case tok::annot_module_include:
2578 Actions.ActOnAnnotModuleInclude(
2580 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
2581 ConsumeAnnotationToken();
2591void Parser::diagnoseUseOfC11Keyword(
const Token &Tok) {
2596 : diag::ext_c11_feature)
2600bool BalancedDelimiterTracker::diagnoseOverflow() {
2601 P.Diag(P.Tok, diag::err_bracket_depth_exceeded)
2602 << P.getLangOpts().BracketDepth;
2603 P.Diag(P.Tok, diag::note_bracket_depth);
2611 LOpen = P.Tok.getLocation();
2612 if (P.ExpectAndConsume(Kind, DiagID, Msg)) {
2613 if (SkipToTok != tok::unknown)
2618 if (getDepth() < P.getLangOpts().BracketDepth)
2621 return diagnoseOverflow();
2624bool BalancedDelimiterTracker::diagnoseMissingClose() {
2625 assert(!P.Tok.is(Close) &&
"Should have consumed closing delimiter");
2627 if (P.Tok.is(tok::annot_module_end))
2628 P.Diag(P.Tok, diag::err_missing_before_module_end) << Close;
2630 P.Diag(P.Tok, diag::err_expected) << Close;
2631 P.Diag(LOpen, diag::note_matching) << Kind;
2635 if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) &&
2636 P.Tok.isNot(tok::r_square) &&
2637 P.SkipUntil(Close, FinalToken,
2640 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.
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 TryAnnotateTypeOrScopeToken(ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No)
TryAnnotateTypeOrScopeToken - If the current token position is on a typename (possibly qualified in C...
bool MightBeCXXScopeToken()
const Token & NextToken()
NextToken - This peeks ahead one token and returns it without consuming it.
friend class BalancedDelimiterTracker
SmallVector< TemplateParameterList *, 4 > TemplateParameterLists
void Initialize()
Initialize - Warm up the parser.
bool TryAnnotateCXXScopeToken(bool EnteringContext=false)
TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only annotates C++ scope specifiers and ...
A class for parsing a DeclSpec.
const ParsingDeclSpec & getDeclSpec() const
ParsingDeclSpec & getMutableDeclSpec() const
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
StringRef getSpelling(SourceLocation loc, SmallVectorImpl< char > &buffer, bool *invalid=nullptr) const
Return the 'spelling' of the token at the given location; does not go up to the spelling location or ...
bool isCodeCompletionEnabled() const
Determine if we are performing code completion.
bool isCodeCompletionReached() const
Returns true if code-completion is enabled and we have hit the code-completion point.
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Computes the source location just past the end of the token at this source location.
A (possibly-)qualified type.
Scope - A scope is a transient data structure that is used while parsing the program.
void Init(Scope *parent, unsigned flags)
Init - This is used by the parser to implement scope caching.
const Scope * getParent() const
getParent - Return the scope that this is nested in.
@ FunctionPrototypeScope
This is a scope that corresponds to the parameters within a function prototype.
@ CompoundStmtScope
This is a compound statement scope.
@ FunctionDeclarationScope
This is a scope that corresponds to the parameters within a function prototype for a function declara...
@ FnScope
This indicates that the scope corresponds to a function, which means that labels are set here.
@ DeclScope
This is a scope that can contain a declaration.
ParserCompletionContext
Describes the context in which code completion occurs.
@ PCC_TopLevelOrExpression
Code completion occurs at top-level in a REPL session.
@ PCC_Class
Code completion occurs within a class, struct, or union.
@ PCC_ObjCImplementation
Code completion occurs within an Objective-C implementation or category implementation.
@ PCC_Namespace
Code completion occurs at top-level or namespace context.
@ PCC_RecoveryInFunction
Code completion occurs within the body of a function on a recovery path, where we do not have a speci...
ExprResult getExpression() const
NameClassificationKind getKind() const
NamedDecl * getNonTypeDecl() const
TemplateName getTemplateName() const
ParsedType getType() const
TemplateNameKind getTemplateNameKind() const
Sema - This implements semantic analysis and AST building for C.
@ Interface
'export module X;'
@ Implementation
'module X;'
@ Other
C++26 [dcl.fct.def.general]p1 function-body: ctor-initializer[opt] compound-statement function-try-bl...
@ Delete
deleted-function-body
ModuleImportState
An enumeration to represent the transition of states in parsing module fragments and imports.
@ PrivateFragmentImportFinished
after 'module :private;' but a non-import decl has already been seen.
@ ImportFinished
after any non-import decl.
@ PrivateFragmentImportAllowed
after 'module :private;' but before any non-import decl.
@ FirstDecl
Parsing the first decl in a TU.
@ GlobalFragment
after 'module;' but before 'module X;'
@ NotACXX20Module
Not a C++20 TU, or an invalid state was found.
@ ImportAllowed
after 'module X;' but before any non-import decl.
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Represents a C++ template name within the type system.
Token - This structure provides full information about a lexed token.
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.