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);
1192 const char *PrevSpec;
1194 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1206 ParseKNRParamDeclarations(D);
1210 if (Tok.isNot(tok::l_brace) &&
1212 (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
1213 Tok.isNot(tok::equal)))) {
1214 Diag(Tok, diag::err_expected_fn_body);
1220 if (Tok.isNot(tok::l_brace))
1226 if (Tok.isNot(tok::equal)) {
1228 if (AL.isKnownToGCC() && !AL.isStandardAttributeSyntax())
1229 Diag(AL.getLoc(), diag::warn_attribute_on_function_definition) << AL;
1234 if (
getLangOpts().DelayedTemplateParsing && Tok.isNot(tok::equal) &&
1236 LateParsedAttrs->empty() && Actions.canDelayFunctionBody(D)) {
1244 Decl *DP = Actions.HandleDeclarator(ParentScope, D,
1249 if (SkipFunctionBodies && (!DP || Actions.canSkipFunctionBody(DP)) &&
1250 trySkippingFunctionBody()) {
1252 return Actions.ActOnSkippedFunctionBody(DP);
1256 LexTemplateFunctionForLateParsing(Toks);
1260 Actions.CheckForFunctionRedefinition(FnD);
1261 Actions.MarkAsLateParsedTemplate(FnD, DP, Toks);
1265 if (CurParsedObjCImpl && !TemplateInfo.TemplateParams &&
1266 (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) || Tok.is(tok::colon)) &&
1267 Actions.CurContext->isTranslationUnit()) {
1273 Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D,
1279 StashAwayMethodOrFunctionBodyTokens(FuncDecl);
1280 CurParsedObjCImpl->HasCFunction =
true;
1292 StringLiteral *DeletedMessage =
nullptr;
1294 SourceLocation KWLoc;
1300 ? diag::warn_cxx98_compat_defaulted_deleted_function
1301 : diag::ext_defaulted_deleted_function)
1304 DeletedMessage = ParseCXXDeletedFunctionMessage();
1307 ? diag::warn_cxx98_compat_defaulted_deleted_function
1308 : diag::ext_defaulted_deleted_function)
1312 llvm_unreachable(
"function definition after = not 'delete' or 'default'");
1315 if (Tok.is(tok::comma)) {
1316 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
1319 }
else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
1327 Sema::FPFeaturesStateRAII SaveFPFeatures(Actions);
1331 SkipBodyInfo SkipBody;
1333 TemplateInfo.TemplateParams
1334 ? *TemplateInfo.TemplateParams
1336 &SkipBody, BodyKind);
1353 Actions.PopExpressionEvaluationContext();
1365 Actions.SetFunctionBodyKind(Res, KWLoc, BodyKind, DeletedMessage);
1366 Stmt *GeneratedBody = Res ? Res->
getBody() :
nullptr;
1367 Actions.ActOnFinishFunctionBody(Res, GeneratedBody,
false);
1373 if (
const auto *
Template = dyn_cast_if_present<FunctionTemplateDecl>(Res);
1375 Template->getTemplateParameters()->getParam(0)->isImplicit())
1378 CurTemplateDepthTracker.addDepth(1);
1381 if (LateParsedAttrs)
1382 ParseLexedAttributeList(*LateParsedAttrs, Res,
false,
1385 if (SkipFunctionBodies && (!Res || Actions.canSkipFunctionBody(Res)) &&
1386 trySkippingFunctionBody()) {
1388 Actions.ActOnSkippedFunctionBody(Res);
1389 return Actions.ActOnFinishFunctionBody(Res,
nullptr,
false);
1392 if (Tok.is(tok::kw_try))
1393 return ParseFunctionTryBlock(Res, BodyScope);
1397 if (Tok.is(tok::colon)) {
1398 ParseConstructorInitializer(Res);
1401 if (!Tok.is(tok::l_brace)) {
1403 Actions.ActOnFinishFunctionBody(Res,
nullptr);
1407 Actions.ActOnDefaultCtorInitializers(Res);
1409 return ParseFunctionStatementBody(Res, BodyScope);
1412void Parser::SkipFunctionBody() {
1413 if (Tok.is(tok::equal)) {
1418 bool IsFunctionTryBlock = Tok.is(tok::kw_try);
1419 if (IsFunctionTryBlock)
1423 if (ConsumeAndStoreFunctionPrologue(Skipped))
1427 while (IsFunctionTryBlock && Tok.is(tok::kw_catch)) {
1434void Parser::ParseKNRParamDeclarations(Declarator &D) {
1445 SourceLocation DSStart = Tok.getLocation();
1448 DeclSpec DS(AttrFactory);
1449 ParsedTemplateInfo TemplateInfo;
1450 ParseDeclarationSpecifiers(DS, TemplateInfo);
1458 Diag(DSStart, diag::err_declaration_does_not_declare_param);
1467 diag::err_invalid_storage_class_in_func_decl);
1472 diag::err_invalid_storage_class_in_func_decl);
1479 ParseDeclarator(ParmDeclarator);
1484 MaybeParseGNUAttributes(ParmDeclarator);
1488 Actions.ActOnParamDeclarator(
getCurScope(), ParmDeclarator);
1492 ParmDeclarator.getIdentifier()) {
1496 for (
unsigned i = 0; ; ++i) {
1500 Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
1501 << ParmDeclarator.getIdentifier();
1505 if (FTI.
Params[i].
Ident == ParmDeclarator.getIdentifier()) {
1508 Diag(ParmDeclarator.getIdentifierLoc(),
1509 diag::err_param_redefinition)
1510 << ParmDeclarator.getIdentifier();
1521 if (Tok.isNot(tok::comma))
1524 ParmDeclarator.clear();
1530 ParseDeclarator(ParmDeclarator);
1534 if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration))
1544 Actions.ActOnFinishKNRParamDeclarations(
getCurScope(), D, Tok.getLocation());
1547ExprResult Parser::ParseAsmStringLiteral(
bool ForAsmLabel) {
1550 if (isTokenStringLiteral()) {
1556 if (!SL->isOrdinary()) {
1557 Diag(Tok, diag::err_asm_operand_wide_string_literal)
1558 << SL->isWide() << SL->getSourceRange();
1562 Tok.is(tok::l_paren)) {
1564 SourceLocation RParenLoc;
1567 EnterExpressionEvaluationContext ConstantEvaluated(
1569 AsmString = ParseParenExpression(
1573 AsmString = Actions.ActOnConstantExpression(AsmString);
1578 Diag(Tok, diag::err_asm_expected_string) << (
1579 (
getLangOpts().CPlusPlus11 && !ForAsmLabel) ? 0 : 1);
1582 return Actions.ActOnGCCAsmStmtString(AsmString.
get(), ForAsmLabel);
1585ExprResult Parser::ParseSimpleAsm(
bool ForAsmLabel, SourceLocation *EndLoc) {
1586 assert(Tok.is(tok::kw_asm) &&
"Not an asm!");
1589 if (isGNUAsmQualifier(Tok)) {
1591 SourceRange RemovalRange(PP.getLocForEndOfToken(Loc),
1592 PP.getLocForEndOfToken(Tok.getLocation()));
1593 Diag(Tok, diag::err_global_asm_qualifier_ignored)
1594 << GNUAsmQualifiers::getQualifierName(getGNUAsmQualifier(Tok))
1600 if (
T.consumeOpen()) {
1601 Diag(Tok, diag::err_expected_lparen_after) <<
"asm";
1607 if (!
Result.isInvalid()) {
1611 *EndLoc =
T.getCloseLocation();
1614 *EndLoc = Tok.getLocation();
1621TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(
const Token &tok) {
1622 assert(tok.
is(tok::annot_template_id) &&
"Expected template-id token");
1623 TemplateIdAnnotation *
1628void Parser::AnnotateScopeToken(CXXScopeSpec &SS,
bool IsNewAnnotation) {
1631 if (PP.isBacktrackEnabled())
1632 PP.RevertCachedTokens(1);
1634 PP.EnterToken(Tok,
true);
1635 Tok.setKind(tok::annot_cxxscope);
1636 Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS));
1637 Tok.setAnnotationRange(SS.
getRange());
1642 if (IsNewAnnotation)
1643 PP.AnnotateCachedTokens(Tok);
1647Parser::TryAnnotateName(CorrectionCandidateCallback *CCC,
1649 assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope));
1651 const bool EnteringContext =
false;
1652 const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1656 ParseOptionalCXXScopeSpecifier(SS,
nullptr,
1661 if (Tok.isNot(tok::identifier) || SS.
isInvalid()) {
1663 AllowImplicitTypename))
1668 IdentifierInfo *Name = Tok.getIdentifierInfo();
1669 SourceLocation NameLoc = Tok.getLocation();
1673 if (isTentativelyDeclared(Name) && SS.
isEmpty()) {
1677 AllowImplicitTypename))
1689 Sema::NameClassification Classification = Actions.ClassifyName(
1697 isTemplateArgumentList(1) == TPResult::False) {
1699 Token FakeNext =
Next;
1700 FakeNext.
setKind(tok::unknown);
1702 Actions.ClassifyName(
getCurScope(), SS, Name, NameLoc, FakeNext,
1703 SS.
isEmpty() ? CCC :
nullptr);
1706 switch (Classification.
getKind()) {
1712 Tok.setIdentifierInfo(Name);
1714 PP.TypoCorrectToken(Tok);
1716 AnnotateScopeToken(SS, !WasScopeAnnotation);
1725 if (TryAltiVecVectorToken())
1730 SourceLocation BeginLoc = NameLoc;
1737 QualType
T = Actions.GetTypeFromParser(Ty);
1742 SourceLocation NewEndLoc;
1744 = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
1749 else if (Tok.is(tok::eof))
1753 Tok.setKind(tok::annot_typename);
1754 setTypeAnnotation(Tok, Ty);
1755 Tok.setAnnotationEndLoc(Tok.getLocation());
1756 Tok.setLocation(BeginLoc);
1757 PP.AnnotateCachedTokens(Tok);
1762 Tok.setKind(tok::annot_overload_set);
1764 Tok.setAnnotationEndLoc(NameLoc);
1767 PP.AnnotateCachedTokens(Tok);
1771 if (TryAltiVecVectorToken())
1776 Tok.setKind(tok::annot_non_type);
1778 Tok.setLocation(NameLoc);
1779 Tok.setAnnotationEndLoc(NameLoc);
1780 PP.AnnotateCachedTokens(Tok);
1782 AnnotateScopeToken(SS, !WasScopeAnnotation);
1787 Tok.setKind(Classification.
getKind() ==
1789 ? tok::annot_non_type_undeclared
1790 : tok::annot_non_type_dependent);
1791 setIdentifierAnnotation(Tok, Name);
1792 Tok.setLocation(NameLoc);
1793 Tok.setAnnotationEndLoc(NameLoc);
1794 PP.AnnotateCachedTokens(Tok);
1796 AnnotateScopeToken(SS, !WasScopeAnnotation);
1800 if (
Next.isNot(tok::less)) {
1804 AnnotateScopeToken(SS, !WasScopeAnnotation);
1812 bool IsConceptName =
1818 if (
Next.is(tok::less))
1820 if (AnnotateTemplateIdToken(
1827 AnnotateScopeToken(SS, !WasScopeAnnotation);
1834 AnnotateScopeToken(SS, !WasScopeAnnotation);
1839 SourceLocation TokenEndLoc = PP.getLocForEndOfToken(PrevTokLocation);
1840 return TokenEndLoc.
isValid() ? TokenEndLoc : Tok.getLocation();
1843bool Parser::TryKeywordIdentFallback(
bool DisableKeyword) {
1844 assert(
Tok.isNot(tok::identifier));
1845 Diag(
Tok, diag::ext_keyword_as_ident)
1849 Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
1850 Tok.setKind(tok::identifier);
1856 assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1857 Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope) ||
1858 Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id) ||
1859 Tok.is(tok::kw___super) || Tok.is(tok::kw_auto) ||
1860 Tok.is(tok::annot_pack_indexing_type)) &&
1861 "Cannot be a type or scope token!");
1863 if (Tok.is(tok::kw_typename)) {
1872 PP.Lex(TypedefToken);
1874 PP.EnterToken(Tok,
true);
1877 Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename);
1889 if (ParseOptionalCXXScopeSpecifier(SS,
nullptr,
1895 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) ||
1896 Tok.is(tok::annot_decltype)) {
1898 if (Tok.is(tok::annot_decltype) ||
1900 Tok.isAnnotation())) {
1901 unsigned DiagID = diag::err_expected_qualified_after_typename;
1905 DiagID = diag::warn_expected_qualified_after_typename;
1906 Diag(Tok.getLocation(), DiagID);
1910 if (Tok.isEditorPlaceholder())
1913 Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename);
1917 bool TemplateKWPresent =
false;
1918 if (Tok.is(tok::kw_template)) {
1920 TemplateKWPresent =
true;
1924 if (Tok.is(tok::identifier)) {
1926 Diag(Tok.getLocation(),
1927 diag::missing_template_arg_list_after_template_kw);
1930 Ty = Actions.ActOnTypenameType(
getCurScope(), TypenameLoc, SS,
1931 *Tok.getIdentifierInfo(),
1933 }
else if (Tok.is(tok::annot_template_id)) {
1936 Diag(Tok, diag::err_typename_refers_to_non_type_template)
1937 << Tok.getAnnotationRange();
1946 : Actions.ActOnTypenameType(
1950 TemplateArgsPtr, TemplateId->
RAngleLoc);
1952 Diag(Tok, diag::err_expected_type_name_after_typename)
1958 Tok.setKind(tok::annot_typename);
1959 setTypeAnnotation(Tok, Ty);
1960 Tok.setAnnotationEndLoc(EndLoc);
1961 Tok.setLocation(TypenameLoc);
1962 PP.AnnotateCachedTokens(Tok);
1967 bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
1971 if (ParseOptionalCXXScopeSpecifier(SS,
nullptr,
1977 AllowImplicitTypename);
1983 if (Tok.is(tok::identifier)) {
1986 *Tok.getIdentifierInfo(), Tok.getLocation(),
getCurScope(), &SS,
1990 true, AllowImplicitTypename)) {
1995 QualType T = Actions.GetTypeFromParser(Ty);
2000 (
T->isObjCObjectType() ||
T->isObjCObjectPointerType())) {
2010 else if (Tok.is(tok::eof))
2016 Tok.setKind(tok::annot_typename);
2017 setTypeAnnotation(Tok, Ty);
2018 Tok.setAnnotationEndLoc(Tok.getLocation());
2019 Tok.setLocation(BeginLoc);
2023 PP.AnnotateCachedTokens(Tok);
2040 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
2041 bool MemberOfUnknownSpecialization;
2046 MemberOfUnknownSpecialization)) {
2050 isTemplateArgumentList(1) != TPResult::False) {
2070 if (Tok.is(tok::annot_template_id)) {
2077 AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
2084 Tok.is(tok::coloncolon)) {
2093 AnnotateScopeToken(SS, IsNewScope);
2099 "Call sites of this function should be guarded by checking for C++");
2103 if (ParseOptionalCXXScopeSpecifier(SS,
nullptr,
2110 AnnotateScopeToken(SS,
true);
2114bool Parser::isTokenEqualOrEqualTypo() {
2120 case tok::starequal:
2121 case tok::plusequal:
2122 case tok::minusequal:
2123 case tok::exclaimequal:
2124 case tok::slashequal:
2125 case tok::percentequal:
2126 case tok::lessequal:
2127 case tok::lesslessequal:
2128 case tok::greaterequal:
2129 case tok::greatergreaterequal:
2130 case tok::caretequal:
2131 case tok::pipeequal:
2132 case tok::equalequal:
2133 Diag(
Tok, diag::err_invalid_token_after_declarator_suggest_equal)
2142SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
2143 assert(Tok.is(tok::code_completion));
2144 PrevTokLocation = Tok.getLocation();
2147 if (S->isFunctionScope()) {
2149 Actions.CodeCompletion().CodeCompleteOrdinaryName(
2151 return PrevTokLocation;
2154 if (S->isClassScope()) {
2156 Actions.CodeCompletion().CodeCompleteOrdinaryName(
2158 return PrevTokLocation;
2163 Actions.CodeCompletion().CodeCompleteOrdinaryName(
2165 return PrevTokLocation;
2170void Parser::CodeCompleteDirective(
bool InConditional) {
2171 Actions.CodeCompletion().CodeCompletePreprocessorDirective(InConditional);
2175 Actions.CodeCompletion().CodeCompleteInPreprocessorConditionalExclusion(
2179void Parser::CodeCompleteMacroName(
bool IsDefinition) {
2180 Actions.CodeCompletion().CodeCompletePreprocessorMacroName(IsDefinition);
2184 Actions.CodeCompletion().CodeCompletePreprocessorExpression();
2187void Parser::CodeCompleteMacroArgument(IdentifierInfo *
Macro,
2188 MacroInfo *MacroInfo,
2189 unsigned ArgumentIndex) {
2190 Actions.CodeCompletion().CodeCompletePreprocessorMacroArgument(
2194void Parser::CodeCompleteIncludedFile(llvm::StringRef Dir,
bool IsAngled) {
2195 Actions.CodeCompletion().CodeCompleteIncludedFile(Dir, IsAngled);
2199 Actions.CodeCompletion().CodeCompleteNaturalLanguage();
2202void Parser::CodeCompleteModuleImport(SourceLocation ImportLoc,
2204 Actions.CodeCompletion().CodeCompleteModuleImport(ImportLoc, Path);
2207bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition&
Result) {
2208 assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) &&
2209 "Expected '__if_exists' or '__if_not_exists'");
2210 Result.IsIfExists = Tok.is(tok::kw___if_exists);
2214 if (
T.consumeOpen()) {
2215 Diag(Tok, diag::err_expected_lparen_after)
2216 << (
Result.IsIfExists?
"__if_exists" :
"__if_not_exists");
2222 ParseOptionalCXXScopeSpecifier(
Result.SS,
nullptr,
2227 if (
Result.SS.isInvalid()) {
2233 SourceLocation TemplateKWLoc;
2238 false, &TemplateKWLoc,
2244 if (
T.consumeClose())
2272void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
2273 IfExistsCondition
Result;
2274 if (ParseMicrosoftIfExistsCondition(
Result))
2278 if (
Braces.consumeOpen()) {
2279 Diag(Tok, diag::err_expected) << tok::l_brace;
2283 switch (
Result.Behavior) {
2289 llvm_unreachable(
"Cannot have a dependent external declaration");
2298 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
2299 ParsedAttributes Attrs(AttrFactory);
2300 MaybeParseCXX11Attributes(Attrs);
2301 ParsedAttributes EmptyDeclSpecAttrs(AttrFactory);
2304 Actions.getASTConsumer().HandleTopLevelDecl(
Result.get());
2311 Token Introducer = Tok;
2312 SourceLocation StartLoc = Introducer.
getLocation();
2318 assert(Tok.is(tok::kw_module) &&
"not a module declaration");
2324 DiagnoseAndSkipCXX11Attributes();
2327 if (
getLangOpts().CPlusPlusModules && Tok.is(tok::semi)) {
2331 Diag(StartLoc, diag::err_global_module_introducer_not_at_start)
2332 << SourceRange(StartLoc, SemiLoc);
2336 Diag(StartLoc, diag::err_module_fragment_exported)
2340 return Actions.ActOnGlobalModuleFragmentDecl(ModuleLoc);
2344 if (
getLangOpts().CPlusPlusModules && Tok.is(tok::colon) &&
2347 Diag(StartLoc, diag::err_module_fragment_exported)
2352 DiagnoseAndSkipCXX11Attributes();
2353 ExpectAndConsumeSemi(diag::err_private_module_fragment_expected_semi);
2357 return Actions.ActOnPrivateModuleFragmentDecl(ModuleLoc, PrivateLoc);
2360 SmallVector<IdentifierLoc, 2> Path;
2361 if (ParseModuleName(ModuleLoc, Path,
false))
2365 SmallVector<IdentifierLoc, 2> Partition;
2366 if (Tok.is(tok::colon)) {
2369 Diag(ColonLoc, diag::err_unsupported_module_partition)
2370 << SourceRange(ColonLoc, Partition.back().getLoc());
2372 else if (ParseModuleName(ModuleLoc, Partition,
false))
2377 if (!Tok.isOneOf(tok::semi, tok::l_square))
2381 ParsedAttributes Attrs(AttrFactory);
2382 MaybeParseCXX11Attributes(Attrs);
2383 ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_module_attr,
2384 diag::err_keyword_not_module_attr,
2388 if (ExpectAndConsumeSemi(diag::err_expected_semi_after_module_or_import,
2392 return Actions.ActOnModuleDecl(StartLoc, ModuleLoc, MDK, Path, Partition,
2397Decl *Parser::ParseModuleImport(SourceLocation AtLoc,
2399 SourceLocation StartLoc = AtLoc.
isInvalid() ? Tok.getLocation() : AtLoc;
2401 SourceLocation ExportLoc;
2404 assert((AtLoc.
isInvalid() ? Tok.is(tok::kw_import)
2405 : Tok.isObjCAtKeyword(tok::objc_import)) &&
2406 "Improper start to module import");
2407 bool IsObjCAtImport = Tok.isObjCAtKeyword(tok::objc_import);
2411 SmallVector<IdentifierLoc, 2> Path;
2412 bool IsPartition =
false;
2413 Module *HeaderUnit =
nullptr;
2414 if (Tok.is(tok::header_name)) {
2419 }
else if (Tok.is(tok::annot_header_unit)) {
2421 HeaderUnit =
reinterpret_cast<Module *
>(Tok.getAnnotationValue());
2422 ConsumeAnnotationToken();
2423 }
else if (Tok.is(tok::colon)) {
2426 Diag(ColonLoc, diag::err_unsupported_module_partition)
2427 << SourceRange(ColonLoc, Path.back().getLoc());
2429 else if (ParseModuleName(ColonLoc, Path,
true))
2434 if (ParseModuleName(ImportLoc, Path,
true))
2438 ParsedAttributes Attrs(AttrFactory);
2439 MaybeParseCXX11Attributes(Attrs);
2441 ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_import_attr,
2442 diag::err_keyword_not_import_attr,
2446 if (PP.hadModuleLoaderFatalFailure()) {
2453 bool SeenError =
true;
2454 switch (ImportState) {
2466 Diag(ImportLoc, diag::err_partition_import_outside_module);
2478 if (IsPartition || (HeaderUnit && HeaderUnit->
Kind !=
2480 Diag(ImportLoc, diag::err_import_in_wrong_fragment)
2489 Diag(ImportLoc, diag::err_import_not_allowed_here);
2495 bool LexedSemi =
false;
2498 !ExpectAndConsumeSemi(diag::err_expected_semi_after_module_or_import,
2501 LexedSemi = !ExpectAndConsumeSemi(diag::err_module_expected_semi);
2512 Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, HeaderUnit);
2513 else if (!Path.empty())
2514 Import = Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Path,
2521 if (IsObjCAtImport && AtLoc.
isValid()) {
2522 auto &SrcMgr = PP.getSourceManager();
2523 auto FE = SrcMgr.getFileEntryRefForID(SrcMgr.getFileID(AtLoc));
2524 if (FE && llvm::sys::path::parent_path(FE->getDir().getName())
2525 .ends_with(
".framework"))
2526 Diags.Report(AtLoc, diag::warn_atimport_in_framework_header);
2532bool Parser::ParseModuleName(SourceLocation UseLoc,
2533 SmallVectorImpl<IdentifierLoc> &Path,
2535 if (Tok.isNot(tok::annot_module_name)) {
2539 ModuleNameLoc *NameLoc =
2540 static_cast<ModuleNameLoc *
>(Tok.getAnnotationValue());
2543 ConsumeAnnotationToken();
2547bool Parser::parseMisplacedModuleImport() {
2549 switch (Tok.getKind()) {
2550 case tok::annot_module_end:
2554 if (MisplacedModuleBeginCount) {
2555 --MisplacedModuleBeginCount;
2556 Actions.ActOnAnnotModuleEnd(
2558 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
2559 ConsumeAnnotationToken();
2566 case tok::annot_module_begin:
2568 Actions.ActOnAnnotModuleBegin(
2570 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
2571 ConsumeAnnotationToken();
2572 ++MisplacedModuleBeginCount;
2574 case tok::annot_module_include:
2577 Actions.ActOnAnnotModuleInclude(
2579 reinterpret_cast<Module *
>(Tok.getAnnotationValue()));
2580 ConsumeAnnotationToken();
2590void Parser::diagnoseUseOfC11Keyword(
const Token &Tok) {
2595 : diag::ext_c11_feature)
2599bool BalancedDelimiterTracker::diagnoseOverflow() {
2600 P.Diag(P.Tok, diag::err_bracket_depth_exceeded)
2601 << P.getLangOpts().BracketDepth;
2602 P.Diag(P.Tok, diag::note_bracket_depth);
2610 LOpen = P.Tok.getLocation();
2611 if (P.ExpectAndConsume(Kind, DiagID, Msg)) {
2612 if (SkipToTok != tok::unknown)
2617 if (getDepth() < P.getLangOpts().BracketDepth)
2620 return diagnoseOverflow();
2623bool BalancedDelimiterTracker::diagnoseMissingClose() {
2624 assert(!P.Tok.is(Close) &&
"Should have consumed closing delimiter");
2626 if (P.Tok.is(tok::annot_module_end))
2627 P.Diag(P.Tok, diag::err_missing_before_module_end) << Close;
2629 P.Diag(P.Tok, diag::err_expected) << Close;
2630 P.Diag(LOpen, diag::note_matching) << Kind;
2634 if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) &&
2635 P.Tok.isNot(tok::r_square) &&
2636 P.SkipUntil(Close, FinalToken,
2639 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)
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
const FunctionProtoType * T
@ Template
We are parsing a template declaration.
@ FunctionTemplate
The name was classified as a function template name.
@ Keyword
The name has been typo-corrected to a keyword.
@ DependentNonType
The name denotes a member of a dependent type that could not be resolved.
@ UndeclaredTemplate
The name was classified as an ADL-only function template name.
@ NonType
The name was classified as a specific non-type, non-template declaration.
@ Unknown
This name is not a type or template in this context, but might be something else.
@ Error
Classification failed; an error has been produced.
@ Type
The name was classified as a type.
@ TypeTemplate
The name was classified as a template whose specializations are types.
@ Concept
The name was classified as a concept name.
@ OverloadSet
The name was classified as an overload set, and an expression representing that overload set has been...
@ UndeclaredNonType
The name was classified as an ADL-only function name.
@ VarTemplate
The name was classified as a variable template name.
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
ExtraSemiKind
The kind of extra semi diagnostic to emit.
@ AfterMemberFunctionDefinition
TemplateNameKind
Specifies the kind of template name that an identifier refers to.
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
@ TNK_Undeclared_template
Lookup for the name failed, but we're assuming it was a template name anyway.
@ Dependent
The name is a dependent name, so the results will differ from one instantiation to the next.
@ Exists
The symbol exists.
@ Error
An error occurred.
@ DoesNotExist
The symbol does not exist.
U cast(CodeGen::Address addr)
SmallVector< Token, 4 > CachedTokens
A set of tokens that has been cached for later parsing.
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
ParenParseOption
ParenParseOption - Control what ParseParenExpression will parse.
ActionResult< Expr * > ExprResult
@ Braces
New-expression has a C++11 list-initializer.
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
bool isKNRPrototype() const
isKNRPrototype - Return true if this is a K&R style identifier list, like "void foo(a,...
const IdentifierInfo * Ident
Information about a template-id annotation token.
const IdentifierInfo * Name
FIXME: Temporarily stores the name of a specialization.
TemplateNameKind Kind
The kind of template that Template refers to.
unsigned NumArgs
NumArgs - The number of template arguments.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
SourceLocation TemplateKWLoc
TemplateKWLoc - The location of the template keyword.
bool mightBeType() const
Determine whether this might be a type template.
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.