23 using namespace clang;
33 explicit ActionCommentHandler(
Sema &
S) : S(S) { }
51 : PP(pp), Actions(actions), Diags(PP.getDiagnostics()),
52 GreaterThanIsOperator(
true), ColonIsSacred(
false),
53 InMessageExpression(
false), TemplateParameterDepth(0),
54 ParsingInObjCContainer(
false) {
58 Actions.CurScope =
nullptr;
60 CurParsedObjCImpl =
nullptr;
64 initializePragmaHandlers();
66 CommentSemaHandler.reset(
new ActionCommentHandler(actions));
73 return Diags.
Report(Loc, DiagID);
102 switch (ExpectedTok) {
104 return Tok.
is(tok::colon) || Tok.
is(tok::comma);
105 default:
return false;
109 bool Parser::ExpectAndConsume(
tok::TokenKind ExpectedTok,
unsigned DiagID,
111 if (Tok.
is(ExpectedTok) || Tok.
is(tok::code_completion)) {
123 if (DiagID == diag::err_expected)
125 else if (DiagID == diag::err_expected_after)
126 DB << Msg << ExpectedTok;
137 const char *Spelling =
nullptr;
145 if (DiagID == diag::err_expected)
147 else if (DiagID == diag::err_expected_after)
148 DB << Msg << ExpectedTok;
155 bool Parser::ExpectAndConsumeSemi(
unsigned DiagID) {
159 if (Tok.
is(tok::code_completion)) {
160 handleUnexpectedCodeCompletionToken();
164 if ((Tok.
is(tok::r_paren) || Tok.
is(tok::r_square)) &&
166 Diag(Tok, diag::err_extraneous_token_before_semi)
174 return ExpectAndConsume(tok::semi, DiagID);
177 void Parser::ConsumeExtraSemi(ExtraSemiKind
Kind,
unsigned TST) {
178 if (!Tok.
is(tok::semi))
return;
180 bool HadMultipleSemis =
false;
186 HadMultipleSemis =
true;
195 Diag(StartLoc, diag::warn_cxx98_compat_top_level_semi)
198 Diag(StartLoc, diag::ext_extra_semi_cxx11)
203 if (Kind != AfterMemberFunctionDefinition || HadMultipleSemis)
204 Diag(StartLoc, diag::ext_extra_semi)
210 Diag(StartLoc, diag::warn_extra_semi_after_mem_fn_def)
214 bool Parser::expectIdentifier() {
215 if (Tok.
is(tok::identifier))
219 Diag(Tok, diag::err_expected_token_instead_of_objcxx_keyword)
225 Diag(Tok, diag::err_expected) << tok::identifier;
234 return (static_cast<unsigned>(L) & static_cast<unsigned>(R)) != 0;
248 bool isFirstTokenSkipped =
true;
251 for (
unsigned i = 0, NumToks = Toks.size(); i != NumToks; ++i) {
252 if (Tok.
is(Toks[i])) {
265 if (Toks.size() == 1 && Toks[0] ==
tok::eof &&
278 case tok::annot_pragma_openmp:
279 case tok::annot_pragma_openmp_end:
281 case tok::annot_module_begin:
282 case tok::annot_module_end:
283 case tok::annot_module_include:
289 case tok::code_completion:
291 handleUnexpectedCodeCompletionToken();
325 if (ParenCount && !isFirstTokenSkipped)
330 if (BracketCount && !isFirstTokenSkipped)
335 if (BraceCount && !isFirstTokenSkipped)
349 isFirstTokenSkipped =
false;
359 if (NumCachedScopes) {
360 Scope *N = ScopeCache[--NumCachedScopes];
362 Actions.CurScope = N;
377 Actions.CurScope = OldScope->
getParent();
379 if (NumCachedScopes == ScopeCacheSize)
382 ScopeCache[NumCachedScopes++] = OldScope;
387 Parser::ParseScopeFlags::ParseScopeFlags(
Parser *Self,
unsigned ScopeFlags,
389 : CurScope(ManageFlags ? Self->getCurScope() : nullptr) {
391 OldFlags = CurScope->getFlags();
392 CurScope->setFlags(ScopeFlags);
398 Parser::ParseScopeFlags::~ParseScopeFlags() {
400 CurScope->setFlags(OldFlags);
411 Actions.CurScope =
nullptr;
414 for (
unsigned i = 0, e = NumCachedScopes; i != e; ++i)
415 delete ScopeCache[i];
417 resetPragmaHandlers();
432 assert(TemplateIds.empty() &&
"Still alive TemplateIdAnnotations around?");
439 assert(
getCurScope() ==
nullptr &&
"A scope is already active?");
454 ObjCTypeQuals[objc_null_unspecified]
458 Ident_instancetype =
nullptr;
459 Ident_final =
nullptr;
460 Ident_sealed =
nullptr;
461 Ident_override =
nullptr;
462 Ident_GNU_final =
nullptr;
466 Ident_vector =
nullptr;
467 Ident_bool =
nullptr;
468 Ident_pixel =
nullptr;
476 Ident_introduced =
nullptr;
477 Ident_deprecated =
nullptr;
478 Ident_obsoleted =
nullptr;
479 Ident_unavailable =
nullptr;
480 Ident_strict =
nullptr;
481 Ident_replacement =
nullptr;
483 Ident_language = Ident_defined_in = Ident_generated_declaration =
nullptr;
485 Ident__except =
nullptr;
487 Ident__exception_code = Ident__exception_info =
nullptr;
488 Ident__abnormal_termination = Ident___exception_code =
nullptr;
489 Ident___exception_info = Ident___abnormal_termination =
nullptr;
490 Ident_GetExceptionCode = Ident_GetExceptionInfo =
nullptr;
491 Ident_AbnormalTermination =
nullptr;
504 PP.
SetPoisonReason(Ident__exception_code,diag::err_seh___except_block);
505 PP.
SetPoisonReason(Ident___exception_code,diag::err_seh___except_block);
506 PP.
SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block);
507 PP.
SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter);
508 PP.
SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter);
509 PP.
SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter);
510 PP.
SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block);
511 PP.
SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block);
512 PP.
SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block);
521 void Parser::LateTemplateParserCleanupCallback(
void *
P) {
538 Diag(diag::ext_empty_translation_unit);
540 return NoTopLevelDecls;
555 case tok::annot_pragma_unused:
556 HandlePragmaUnused();
568 Result = ParseModuleDecl();
571 case tok::annot_module_include:
573 reinterpret_cast<Module *
>(
575 ConsumeAnnotationToken();
578 case tok::annot_module_begin:
581 ConsumeAnnotationToken();
584 case tok::annot_module_end:
587 ConsumeAnnotationToken();
590 case tok::annot_pragma_attribute:
591 HandlePragmaAttribute();
599 LateTemplateParserCleanupCallback :
nullptr,
610 ParsedAttributesWithRange attrs(AttrFactory);
611 MaybeParseCXX11Attributes(attrs);
613 Result = ParseExternalDeclaration(attrs);
641 Parser::ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
651 Decl *SingleDecl =
nullptr;
653 case tok::annot_pragma_vis:
654 HandlePragmaVisibility();
656 case tok::annot_pragma_pack:
659 case tok::annot_pragma_msstruct:
660 HandlePragmaMSStruct();
662 case tok::annot_pragma_align:
665 case tok::annot_pragma_weak:
668 case tok::annot_pragma_weakalias:
669 HandlePragmaWeakAlias();
671 case tok::annot_pragma_redefine_extname:
672 HandlePragmaRedefineExtname();
674 case tok::annot_pragma_fp_contract:
675 HandlePragmaFPContract();
677 case tok::annot_pragma_fp:
680 case tok::annot_pragma_opencl_extension:
681 HandlePragmaOpenCLExtension();
683 case tok::annot_pragma_openmp: {
685 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, attrs);
687 case tok::annot_pragma_ms_pointers_to_members:
688 HandlePragmaMSPointersToMembers();
690 case tok::annot_pragma_ms_vtordisp:
691 HandlePragmaMSVtorDisp();
693 case tok::annot_pragma_ms_pragma:
694 HandlePragmaMSPragma();
696 case tok::annot_pragma_dump:
704 ConsumeExtraSemi(OutsideFunction);
707 Diag(Tok, diag::err_extraneous_closing_brace);
711 Diag(Tok, diag::err_expected_external_declaration);
713 case tok::kw___extension__: {
717 return ParseExternalDeclaration(attrs);
720 ProhibitAttributes(attrs);
731 const auto *SL = cast<StringLiteral>(
Result.get());
732 if (!SL->getString().trim().empty())
733 Diag(StartLoc, diag::err_gnu_inline_asm_disabled);
736 ExpectAndConsume(tok::semi, diag::err_expected_after,
737 "top-level asm block");
745 return ParseObjCAtDirectives();
749 Diag(Tok, diag::err_expected_external_declaration);
753 SingleDecl = ParseObjCMethodDefinition();
755 case tok::code_completion:
763 SingleDecl = ParseExportDeclaration();
770 case tok::kw_namespace:
771 case tok::kw_typedef:
772 case tok::kw_template:
773 case tok::kw_static_assert:
774 case tok::kw__Static_assert:
797 if (NextKind == tok::kw_namespace) {
804 if (NextKind == tok::kw_template) {
819 diag::warn_cxx98_compat_extern_template :
820 diag::ext_extern_template) <<
SourceRange(ExternLoc, TemplateLoc);
824 ExternLoc, TemplateLoc, DeclEnd));
828 case tok::kw___if_exists:
829 case tok::kw___if_not_exists:
830 ParseMicrosoftIfExistsExternalDeclaration();
834 Diag(Tok, diag::err_unexpected_module_decl);
845 return ParseDeclarationOrFunctionDefinition(attrs, DS);
855 bool Parser::isDeclarationAfterDeclarator() {
859 if (KW.
is(tok::kw_default) || KW.
is(tok::kw_delete))
863 return Tok.
is(tok::equal) ||
864 Tok.
is(tok::comma) ||
866 Tok.
is(tok::kw_asm) ||
867 Tok.
is(tok::kw___attribute) ||
869 Tok.
is(tok::l_paren));
876 if (Tok.
is(tok::l_brace))
882 return isDeclarationSpecifier();
886 return KW.
is(tok::kw_default) || KW.
is(tok::kw_delete);
889 return Tok.
is(tok::colon) ||
909 Parser::ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
914 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC_top_level);
919 DiagnoseMissingSemiAfterTagDefinition(DS, AS, DSC_top_level))
924 if (Tok.
is(tok::semi)) {
925 ProhibitAttributes(attrs);
934 Decl* decls[] = {AnonRecord, TheDecl};
949 Diag(Tok, diag::err_objc_unexpected_attr);
956 const char *PrevSpec =
nullptr;
960 Diag(AtLoc, DiagID) << PrevSpec;
963 return ParseObjCAtProtocolDeclaration(AtLoc, DS.
getAttributes());
972 if (
getLangOpts().CPlusPlus && isTokenStringLiteral() &&
983 Parser::ParseDeclarationOrFunctionDefinition(ParsedAttributesWithRange &attrs,
987 return ParseDeclOrFunctionDefInternal(attrs, *DS, AS);
995 return ParseDeclOrFunctionDefInternal(attrs, PDS, AS);
1014 const ParsedTemplateInfo &TemplateInfo,
1015 LateParsedAttrList *LateParsedAttrs) {
1024 const char *PrevSpec;
1038 ParseKNRParamDeclarations(D);
1042 if (Tok.
isNot(tok::l_brace) &&
1044 (Tok.
isNot(tok::colon) && Tok.
isNot(tok::kw_try) &&
1045 Tok.
isNot(tok::equal)))) {
1046 Diag(Tok, diag::err_expected_fn_body);
1052 if (Tok.
isNot(tok::l_brace))
1058 if (Tok.
isNot(tok::equal)) {
1063 Diag(DtorAttrs->
getLoc(), diag::warn_attribute_on_function_definition)
1066 DtorAttrs = DtorAttrs->
getNext();
1073 TemplateInfo.Kind == ParsedTemplateInfo::Template &&
1087 trySkippingFunctionBody()) {
1093 LexTemplateFunctionForLateParsing(Toks);
1102 else if (CurParsedObjCImpl &&
1103 !TemplateInfo.TemplateParams &&
1104 (Tok.
is(tok::l_brace) || Tok.
is(tok::kw_try) ||
1105 Tok.
is(tok::colon)) &&
1117 StashAwayMethodOrFunctionBodyTokens(FuncDecl);
1118 CurParsedObjCImpl->HasCFunction =
true;
1131 TemplateInfo.TemplateParams
1132 ? *TemplateInfo.TemplateParams
1151 bool Delete =
false;
1155 ? diag::warn_cxx98_compat_defaulted_deleted_function
1156 : diag::ext_defaulted_deleted_function)
1162 ? diag::warn_cxx98_compat_defaulted_deleted_function
1163 : diag::ext_defaulted_deleted_function)
1167 llvm_unreachable(
"function definition after = not 'delete' or 'default'");
1170 if (Tok.
is(tok::comma)) {
1171 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
1174 }
else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
1175 Delete ?
"delete" :
"default")) {
1179 Stmt *GeneratedBody = Res ? Res->
getBody() :
nullptr;
1185 trySkippingFunctionBody()) {
1191 if (Tok.
is(tok::kw_try))
1192 return ParseFunctionTryBlock(Res, BodyScope);
1196 if (Tok.
is(tok::colon)) {
1197 ParseConstructorInitializer(Res);
1200 if (!Tok.
is(tok::l_brace)) {
1209 if (LateParsedAttrs)
1210 ParseLexedAttributeList(*LateParsedAttrs, Res,
false,
true);
1212 return ParseFunctionStatementBody(Res, BodyScope);
1215 void Parser::SkipFunctionBody() {
1216 if (Tok.
is(tok::equal)) {
1221 bool IsFunctionTryBlock = Tok.
is(tok::kw_try);
1222 if (IsFunctionTryBlock)
1226 if (ConsumeAndStoreFunctionPrologue(Skipped))
1230 while (IsFunctionTryBlock && Tok.
is(tok::kw_catch)) {
1239 void Parser::ParseKNRParamDeclarations(Declarator &D) {
1249 while (isDeclarationSpecifier()) {
1254 ParseDeclarationSpecifiers(DS);
1262 Diag(DSStart, diag::err_declaration_does_not_declare_param);
1271 diag::err_invalid_storage_class_in_func_decl);
1276 diag::err_invalid_storage_class_in_func_decl);
1282 ParseDeclarator(ParmDeclarator);
1287 MaybeParseGNUAttributes(ParmDeclarator);
1295 ParmDeclarator.getIdentifier()) {
1299 for (
unsigned i = 0; ; ++i) {
1303 Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
1304 << ParmDeclarator.getIdentifier();
1308 if (FTI.
Params[i].
Ident == ParmDeclarator.getIdentifier()) {
1311 Diag(ParmDeclarator.getIdentifierLoc(),
1312 diag::err_param_redefinition)
1313 << ParmDeclarator.getIdentifier();
1324 if (Tok.
isNot(tok::comma))
1327 ParmDeclarator.clear();
1333 ParseDeclarator(ParmDeclarator);
1337 if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration))
1358 if (!isTokenStringLiteral()) {
1359 Diag(Tok, diag::err_expected_string_literal)
1364 ExprResult AsmString(ParseStringLiteralExpression());
1365 if (!AsmString.isInvalid()) {
1366 const auto *SL = cast<StringLiteral>(AsmString.get());
1367 if (!SL->isAscii()) {
1368 Diag(Tok, diag::err_asm_operand_wide_string_literal)
1370 << SL->getSourceRange();
1383 assert(Tok.
is(tok::kw_asm) &&
"Not an asm!");
1386 if (Tok.
is(tok::kw_volatile)) {
1391 Diag(Tok, diag::warn_file_asm_volatile)
1397 if (T.consumeOpen()) {
1398 Diag(Tok, diag::err_expected_lparen_after) <<
"asm";
1404 if (!
Result.isInvalid()) {
1408 *EndLoc = T.getCloseLocation();
1422 assert(tok.
is(tok::annot_template_id) &&
"Expected template-id token");
1428 void Parser::AnnotateScopeToken(
CXXScopeSpec &SS,
bool IsNewAnnotation) {
1435 Tok.
setKind(tok::annot_cxxscope);
1442 if (IsNewAnnotation)
1455 Parser::AnnotatedNameKind
1456 Parser::TryAnnotateName(
bool IsAddressOfOperand,
1457 std::unique_ptr<CorrectionCandidateCallback> CCC) {
1458 assert(Tok.
is(tok::identifier) || Tok.
is(tok::annot_cxxscope));
1460 const bool EnteringContext =
false;
1461 const bool WasScopeAnnotation = Tok.
is(tok::annot_cxxscope);
1465 ParseOptionalCXXScopeSpecifier(SS,
nullptr, EnteringContext))
1471 return ANK_Unresolved;
1479 if (isTentativelyDeclared(Name)) {
1484 return Tok.
is(tok::annot_typename) ? ANK_Success : ANK_TentativeDecl;
1494 getCurScope(), SS, Name, NameLoc, Next, IsAddressOfOperand,
1495 SS.
isEmpty() ? std::move(CCC) : nullptr);
1497 switch (Classification.
getKind()) {
1507 AnnotateScopeToken(SS, !WasScopeAnnotation);
1530 = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
1539 Tok.
setKind(tok::annot_typename);
1540 setTypeAnnotation(Tok, Ty);
1548 Tok.
setKind(tok::annot_primary_expr);
1557 if (Next.
isNot(tok::less)) {
1560 AnnotateScopeToken(SS, !WasScopeAnnotation);
1561 return ANK_TemplateName;
1570 if (AnnotateTemplateIdToken(
1578 llvm_unreachable(
"already parsed nested name specifier");
1583 AnnotateScopeToken(SS, !WasScopeAnnotation);
1584 return ANK_Unresolved;
1587 bool Parser::TryKeywordIdentFallback(
bool DisableKeyword) {
1588 assert(Tok.
isNot(tok::identifier));
1589 Diag(Tok, diag::ext_keyword_as_ident)
1621 assert((Tok.
is(tok::identifier) || Tok.
is(tok::coloncolon) ||
1622 Tok.
is(tok::kw_typename) || Tok.
is(tok::annot_cxxscope) ||
1623 Tok.
is(tok::kw_decltype) || Tok.
is(tok::annot_template_id) ||
1624 Tok.
is(tok::kw___super)) &&
1625 "Cannot be a type or scope token!");
1627 if (Tok.
is(tok::kw_typename)) {
1636 PP.
Lex(TypedefToken);
1641 Diag(Tok.
getLocation(), diag::warn_expected_qualified_after_typename);
1653 if (ParseOptionalCXXScopeSpecifier(SS,
nullptr,
1658 if (Tok.
is(tok::identifier) || Tok.
is(tok::annot_template_id) ||
1659 Tok.
is(tok::annot_decltype)) {
1661 if (Tok.
is(tok::annot_decltype) ||
1663 unsigned DiagID = diag::err_expected_qualified_after_typename;
1667 DiagID = diag::warn_expected_qualified_after_typename;
1680 if (Tok.
is(tok::identifier)) {
1685 }
else if (Tok.
is(tok::annot_template_id)) {
1689 Diag(Tok, diag::err_typename_refers_to_non_type_template)
1706 Diag(Tok, diag::err_expected_type_name_after_typename)
1712 Tok.
setKind(tok::annot_typename);
1713 setTypeAnnotation(Tok, Ty.
isInvalid() ?
nullptr : Ty.
get());
1721 bool WasScopeAnnotation = Tok.
is(tok::annot_cxxscope);
1725 if (ParseOptionalCXXScopeSpecifier(SS,
nullptr,
false))
1736 if (Tok.
is(tok::identifier)) {
1743 GreaterThanIsOperator)) {
1757 = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
1768 Tok.
setKind(tok::annot_typename);
1769 setTypeAnnotation(Tok, Ty);
1791 bool MemberOfUnknownSpecialization;
1794 false, TemplateName,
1795 nullptr,
false, Template,
1796 MemberOfUnknownSpecialization)) {
1815 if (Tok.
is(tok::annot_template_id)) {
1822 AnnotateTemplateIdTokenAsType();
1831 AnnotateScopeToken(SS, IsNewScope);
1843 "Call sites of this function should be guarded by checking for C++");
1844 assert((Tok.
is(tok::identifier) || Tok.
is(tok::coloncolon) ||
1845 (Tok.
is(tok::annot_template_id) &&
NextToken().
is(tok::coloncolon)) ||
1846 Tok.
is(tok::kw_decltype) || Tok.
is(tok::kw___super)) &&
1847 "Cannot be a type or scope token!");
1850 if (ParseOptionalCXXScopeSpecifier(SS,
nullptr, EnteringContext))
1855 AnnotateScopeToken(SS,
true);
1859 bool Parser::isTokenEqualOrEqualTypo() {
1865 case tok::starequal:
1866 case tok::plusequal:
1867 case tok::minusequal:
1868 case tok::exclaimequal:
1869 case tok::slashequal:
1870 case tok::percentequal:
1871 case tok::lessequal:
1872 case tok::lesslessequal:
1873 case tok::greaterequal:
1874 case tok::greatergreaterequal:
1875 case tok::caretequal:
1876 case tok::pipeequal:
1877 case tok::equalequal:
1878 Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal)
1888 assert(Tok.
is(tok::code_completion));
1896 return PrevTokLocation;
1902 return PrevTokLocation;
1908 return PrevTokLocation;
1913 void Parser::CodeCompleteDirective(
bool InConditional) {
1917 void Parser::CodeCompleteInConditionalExclusion() {
1921 void Parser::CodeCompleteMacroName(
bool IsDefinition) {
1925 void Parser::CodeCompletePreprocessorExpression() {
1931 unsigned ArgumentIndex) {
1936 void Parser::CodeCompleteNaturalLanguage() {
1940 bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) {
1941 assert((Tok.
is(tok::kw___if_exists) || Tok.
is(tok::kw___if_not_exists)) &&
1942 "Expected '__if_exists' or '__if_not_exists'");
1943 Result.IsIfExists = Tok.
is(tok::kw___if_exists);
1947 if (T.consumeOpen()) {
1948 Diag(Tok, diag::err_expected_lparen_after)
1949 << (Result.IsIfExists?
"__if_exists" :
"__if_not_exists");
1955 ParseOptionalCXXScopeSpecifier(Result.SS,
nullptr,
1959 if (Result.SS.isInvalid()) {
1967 Result.SS,
false,
true,
1968 true,
false,
nullptr,
1969 TemplateKWLoc, Result.Name)) {
1974 if (T.consumeClose())
1979 Result.IsIfExists, Result.SS,
1982 Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip;
1986 Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip;
1990 Result.Behavior = IEB_Dependent;
2000 void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
2001 IfExistsCondition
Result;
2002 if (ParseMicrosoftIfExistsCondition(Result))
2006 if (Braces.consumeOpen()) {
2007 Diag(Tok, diag::err_expected) << tok::l_brace;
2011 switch (Result.Behavior) {
2017 llvm_unreachable(
"Cannot have a dependent external declaration");
2026 while (Tok.
isNot(tok::r_brace) && !isEofOrEom()) {
2027 ParsedAttributesWithRange attrs(AttrFactory);
2028 MaybeParseCXX11Attributes(attrs);
2033 Braces.consumeClose();
2051 assert(Tok.
is(tok::kw_module) &&
"not a module declaration");
2054 if (Tok.
is(tok::identifier) &&
NextToken().
is(tok::identifier) &&
2059 << FixItHint::CreateInsertion(ModuleLoc,
"export ");
2065 if (ParseModuleName(ModuleLoc, Path,
false))
2069 ParsedAttributesWithRange Attrs(AttrFactory);
2070 MaybeParseCXX11Attributes(Attrs);
2071 ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_module_attr);
2073 ExpectAndConsumeSemi(diag::err_module_expected_semi);
2087 assert((AtLoc.
isInvalid() ? Tok.
is(tok::kw_import)
2089 "Improper start to module import");
2094 if (ParseModuleName(ImportLoc, Path,
true))
2097 ParsedAttributesWithRange Attrs(AttrFactory);
2098 MaybeParseCXX11Attributes(Attrs);
2100 ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_import_attr);
2109 ExpectAndConsumeSemi(diag::err_module_expected_semi);
2123 bool Parser::ParseModuleName(
2129 if (!Tok.
is(tok::identifier)) {
2130 if (Tok.
is(tok::code_completion)) {
2136 Diag(Tok, diag::err_module_expected_ident) << IsImport;
2145 if (Tok.
isNot(tok::period))
2156 bool Parser::parseMisplacedModuleImport() {
2159 case tok::annot_module_end:
2163 if (MisplacedModuleBeginCount) {
2164 --MisplacedModuleBeginCount;
2166 reinterpret_cast<Module *
>(
2168 ConsumeAnnotationToken();
2175 case tok::annot_module_begin:
2178 reinterpret_cast<Module *
>(
2180 ConsumeAnnotationToken();
2181 ++MisplacedModuleBeginCount;
2183 case tok::annot_module_include:
2187 reinterpret_cast<Module *
>(
2189 ConsumeAnnotationToken();
2199 bool BalancedDelimiterTracker::diagnoseOverflow() {
2200 P.Diag(P.Tok, diag::err_bracket_depth_exceeded)
2201 << P.getLangOpts().BracketDepth;
2202 P.Diag(P.Tok, diag::note_bracket_depth);
2210 LOpen = P.Tok.getLocation();
2211 if (P.ExpectAndConsume(Kind, DiagID, Msg)) {
2212 if (SkipToTok != tok::unknown)
2217 if (getDepth() < MaxDepth)
2220 return diagnoseOverflow();
2223 bool BalancedDelimiterTracker::diagnoseMissingClose() {
2224 assert(!P.Tok.is(Close) &&
"Should have consumed closing delimiter");
2226 if (P.Tok.is(tok::annot_module_end))
2227 P.Diag(P.Tok, diag::err_missing_before_module_end) << Close;
2229 P.Diag(P.Tok, diag::err_expected) << Close;
2230 P.Diag(LOpen, diag::note_matching) << Kind;
2234 if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) &&
2235 P.Tok.isNot(tok::r_square) &&
2236 P.SkipUntil(Close, FinalToken,
2239 LClose = P.ConsumeAnyToken();
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
bool isAtStartOfLine() const
isAtStartOfLine - Return true if this token is at the start of a line.
SourceLocation getThreadStorageClassSpecLoc() const
Defines the clang::ASTContext interface.
SourceLocation getEnd() const
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
This is a scope that corresponds to the parameters within a function prototype.
void Initialize()
Perform initialization that occurs after the parser has been initialized but before it parses anythin...
void Initialize()
Initialize - Warm up the parser.
Code completion occurs within a class, struct, or union.
IdentifierInfo * Name
FIXME: Temporarily stores the name of a specialization.
const LangOptions & getLangOpts() const
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
Stmt - This represents one statement.
const Scope * getParent() const
getParent - Return the scope that this is nested in.
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
The name refers to a dependent template name:
Decl - This represents one declaration (or definition), e.g.
Defines the C++ template declaration subclasses.
SCS getStorageClassSpec() const
void CodeCompleteNaturalLanguage()
bool TryAnnotateCXXScopeToken(bool EnteringContext=false)
TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only annotates C++ scope specifiers and ...
This indicates that the scope corresponds to a function, which means that labels are set here...
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
static const char * getSpecifierName(DeclSpec::TST T, const PrintingPolicy &Policy)
Turn a type-specifier-type into a string like "_Bool" or "union".
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
TemplateNameKind Kind
The kind of template that Template refers to.
Wrapper for void* pointer.
Parser - This implements a parser for the C family of languages.
void * SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS)
Given a C++ nested-name-specifier, produce an annotation value that the parser can use later to recon...
void ActOnDefaultCtorInitializers(Decl *CDtorDecl)
static const TSCS TSCS_unspecified
void EnterToken(const Token &Tok)
Enters a token in the token stream to be lexed next.
Information about one declarator, including the parsed type information and the identifier.
TypeSpecifierType
Specifies the kind of type.
RAIIObject to destroy the contents of a SmallVector of TemplateIdAnnotation pointers and clear the ve...
Describes how types, statements, expressions, and declarations should be printed. ...
Code completion occurs within an Objective-C implementation or category implementation.
RAII object that makes sure paren/bracket/brace count is correct after declaration/statement parsing...
Decl * ActOnParamDeclarator(Scope *S, Declarator &D)
ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() to introduce parameters into fun...
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS=nullptr, bool isClassName=false, bool HasTrailingDot=false, ParsedType ObjectType=nullptr, bool IsCtorOrDtorName=false, bool WantNontrivialTypeSourceInfo=false, bool IsClassTemplateDeductionContext=true, IdentifierInfo **CorrectedII=nullptr)
If the identifier refers to a type name within this scope, return the declaration of that type...
bool canSkipFunctionBody(Decl *D)
Determine whether we can skip parsing the body of a function definition, assuming we don't care about...
const ParsingDeclSpec & getDeclSpec() const
friend class ObjCDeclContextSwitch
void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, CachedTokens &Toks)
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 isEmpty() const
No scope specifier.
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 ...
Information about a template-id annotation token.
void CodeCompleteOrdinaryName(Scope *S, ParserCompletionContext CompletionContext)
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr)
RecordDecl - Represents a struct/union/class.
const Token & NextToken()
NextToken - This peeks ahead one token and returns it without consuming it.
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Computes the source location just past the end of the token at this source location.
bool TryConsumeToken(tok::TokenKind Expected)
void SetPoisonReason(IdentifierInfo *II, unsigned DiagID)
Specifies the reason for poisoning an identifier.
One of these records is kept for each identifier that is lexed.
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
bool isEmpty() const
isEmpty - Return true if this declaration specifier is completely empty: no tokens were parsed in the...
void ActOnEndOfTranslationUnit()
ActOnEndOfTranslationUnit - This is called at the very end of the translation unit when EOF is reache...
bool isTranslationUnit() const
Token - This structure provides full information about a lexed token.
bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, bool AllowDestructorName, bool AllowConstructorName, bool AllowDeductionGuide, ParsedType ObjectType, SourceLocation &TemplateKWLoc, UnqualifiedId &Result)
Parse a C++ unqualified-id (or a C identifier), which describes the name of an entity.
void CodeCompletePreprocessorMacroArgument(Scope *S, IdentifierInfo *Macro, MacroInfo *MacroInfo, unsigned Argument)
void setKind(tok::TokenKind K)
RAII class that helps handle the parsing of an open/close delimiter pair, such as braces { ...
void removeCommentHandler(CommentHandler *Handler)
Remove the specified comment handler.
void ClearStorageClassSpecs()
Describes a module or submodule.
Code completion occurs at top-level or namespace context.
static bool HasFlagsSet(Parser::SkipUntilFlags L, Parser::SkipUntilFlags R)
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef< Decl * > Group)
BuildDeclaratorGroup - convert a list of declarations into a declaration group, performing any necess...
Code completion occurs within the body of a function on a recovery path, where we do not have a speci...
Represents a C++ unqualified-id that has been parsed.
void SetRangeBegin(SourceLocation Loc)
SetRangeBegin - Set the start of the source range to Loc, unless it's invalid.
tok::TokenKind getTokenID() const
If this is a source-language token (e.g.
void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path)
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
bool hadModuleLoaderFatalFailure() const
IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, const DeclarationNameInfo &TargetNameInfo)
void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod)
The parser has processed a module import translated from a #include or similar preprocessing directiv...
Scope - A scope is a transient data structure that is used while parsing the program.
Decl * ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc, SourceLocation RParenLoc)
Represents a C++ nested-name-specifier or a global scope specifier.
tok::TokenKind getKind() const
void setCodeCompletionHandler(CodeCompletionHandler &Handler)
Set the code completion handler to the given object.
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body)
SourceRange getSourceRange() const LLVM_READONLY
SourceRange getRange() const
SourceLocation TemplateKWLoc
TemplateKWLoc - The location of the template keyword.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
void * getAnnotationValue() const
Sema - This implements semantic analysis and AST building for C.
Decl * ActOnEmptyDeclaration(Scope *S, AttributeList *AttrList, SourceLocation SemiLoc)
Handle a C++11 empty-declaration and attribute-declaration.
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
A little helper class used to produce diagnostics.
A class for parsing a declarator.
void clearCodeCompletionHandler()
Clear out the code completion handler.
NameClassificationKind getKind() const
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
bool isEditorPlaceholder() const
Returns true if this token is an editor placeholder.
void setAnnotationRange(SourceRange R)
SourceRange getAnnotationRange() const
SourceRange of the group of tokens that this annotation token represents.
void setAnnotationValue(void *val)
Decl * ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, RecordDecl *&AnonRecord)
ParsedFreeStandingDeclSpec - This method is invoked when a declspec with no declarator (e...
TemplateNameKind getTemplateNameKind() const
void AnnotateCachedTokens(const Token &Tok)
We notify the Preprocessor that if it is caching tokens (because backtrack is enabled) it should repl...
This file defines the classes used to store parsed information about declaration-specifiers and decla...
void SkipMalformedDecl()
SkipMalformedDecl - Read tokens until we get to some likely good stopping point for skipping past a s...
void RevertCachedTokens(unsigned N)
When backtracking is enabled and tokens are cached, this allows to revert a specific number of tokens...
DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc, SourceLocation ModuleLoc, ModuleDeclKind MDK, ModuleIdPath Path)
The parser has processed a module-declaration that begins the definition of a module interface or imp...
Represents a C++ template name within the type system.
void CodeCompletePreprocessorExpression()
const char * getPunctuatorSpelling(TokenKind Kind) LLVM_READNONE
Determines the spelling of simple punctuation tokens like '!' or '', and returns NULL for literal and...
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file. ...
TemplateNameKind
Specifies the kind of template name that an identifier refers to.
bool isNot(tok::TokenKind K) const
void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc)
Wraps an identifier and optional source location for the identifier.
TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization)
The result type of a method or function.
SourceLocation getStorageClassSpecLoc() const
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
const clang::PrintingPolicy & getPrintingPolicy() const
NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc, const Token &NextToken, bool IsAddressOfOperand, std::unique_ptr< CorrectionCandidateCallback > CCC=nullptr)
Perform name lookup on the given name, classifying it based on the results of name lookup and the fol...
This is a scope that corresponds to the parameters within a function prototype for a function declara...
void CheckForFunctionRedefinition(FunctionDecl *FD, const FunctionDecl *EffectiveDefinition=nullptr, SkipBodyInfo *SkipBody=nullptr)
Decl * ActOnSkippedFunctionBody(Decl *Decl)
A class for parsing a DeclSpec.
bool isKNRPrototype() const
isKNRPrototype - Return true if this is a K&R style identifier list, like "void foo(a,b,c)".
void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, SourceLocation LocAfterDecls)
Stop skipping at semicolon.
void TypoCorrectToken(const Token &Tok)
Update the current token to represent the provided identifier, in order to cache an action performed ...
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Encodes a location in the source.
bool isIncrementalProcessingEnabled() const
Returns true if incremental processing is enabled.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
void setCurrentOpenCLExtensionForDecl(Decl *FD)
Set current OpenCL extensions for a declaration which can only be used when these OpenCL extensions a...
bool TryAnnotateTypeOrScopeToken()
TryAnnotateTypeOrScopeToken - If the current token position is on a typename (possibly qualified in C...
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any...
bool isValid() const
Return true if this is a valid SourceLocation object.
void ExitScope()
ExitScope - Pop a scope off the scope stack.
ASTContext & getASTContext() const
bool isCodeCompletionReached() const
Returns true if code-completion is enabled and we have hit the code-completion point.
Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies)
void setAnnotationEndLoc(SourceLocation L)
IdentifierTable & getIdentifierTable()
Scope * getCurScope() const
bool isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const
Return true if we have an ObjC keyword identifier.
void setIdentifierInfo(IdentifierInfo *II)
ExtensionRAIIObject - This saves the state of extension warnings when constructed and disables them...
void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc)
bool canDelayFunctionBody(const Declarator &D)
Determine whether we can delay parsing the body of a function or function template until it is used...
void CodeCompletePreprocessorDirective(bool InConditional)
void Lex(Token &Result)
Lex the next token for this preprocessor.
void EnterScope(unsigned ScopeFlags)
EnterScope - Start a new scope.
bool isInvalid() const
An error occurred during parsing of the scope specifier.
SourceLocation getLastLoc() const
virtual Stmt * getBody() const
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
ASTConsumer & getASTConsumer() const
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
static bool IsCommonTypo(tok::TokenKind ExpectedTok, const Token &Tok)
void SetLateTemplateParser(LateTemplateParserCB *LTP, LateTemplateParserCleanupCB *LTPCleanup, void *P)
SourceLocation getBegin() const
SourceLocation getBeginLoc() const
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)) {...
The name is a dependent name, so the results will differ from one instantiation to the next...
void Init(Scope *parent, unsigned flags)
Init - This is used by the parser to implement scope caching.
void ActOnStartOfTranslationUnit()
This is called before the very first declaration in the translation unit is parsed.
void CodeCompletePreprocessorMacroName(bool IsDefinition)
void setFunctionDefinitionKind(FunctionDefinitionKind Val)
The scope of a struct/union/class definition.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
TSCS getThreadStorageClassSpec() const
bool expectAndConsume(unsigned DiagID=diag::err_expected, const char *Msg="", tok::TokenKind SkipToTok=tok::unknown)
void addCommentHandler(CommentHandler *Handler)
Add the specified comment handler to the preprocessor.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod)
The parsed has entered a submodule.
bool hasTagDefinition() const
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
ParsingDeclSpec & getMutableDeclSpec() const
SkipUntilFlags
Control flags for SkipUntil functions.
TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, const IdentifierInfo &II, SourceLocation IdLoc)
Called when the parser has parsed a C++ typename specifier, e.g., "typename T::type".
The name refers to a template whose specialization produces a type.
static const TST TST_unspecified
Encapsulates the data about a macro definition (e.g.
bool isObjCObjectType() const
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
ExprResult getExpression() const
IdentifierInfo * getName() const
void takeAttributesFrom(ParsedAttributes &attrs)
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
bool isKnownToGCC() const
bool isCodeCompletionEnabled() const
Determine if we are performing code completion.
TemplateName getTemplateName() const
SourceLocation getLoc() const
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.
SmallVector< TemplateParameterList *, 4 > TemplateParameterLists
DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc, ModuleIdPath Path)
The parser has processed a module import declaration.
This is a scope that can contain a declaration.
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
void ActOnTranslationUnitScope(Scope *S)
bool isCXX11Attribute() const
Captures information about "declaration specifiers".
SourceLocation getIdentifierLoc() const
SourceLocation ConsumeToken()
ConsumeToken - Consume the current 'peek token' and lex the next one.
bool isObjCObjectPointerType() const
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
void ActOnPopScope(SourceLocation Loc, Scope *S)
Scope actions.
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string...
void revertTokenIDToIdentifier()
Revert TokenID to tok::identifier; used for GNU libstdc++ 4.2 compatibility.
bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS, bool IsNewScope)
Try to annotate a type or scope token, having already parsed an optional scope specifier.
void ActOnComment(SourceRange Comment)
static OpaquePtr make(TemplateNameP)
unsigned getParsedSpecifiers() const
Return a bitmask of which flavors of specifiers this DeclSpec includes.
bool isSet() const
Deprecated.
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
void setLocation(SourceLocation L)
void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod)
The parser has left a submodule.
AttributeList * getNext() const
'module implementation X;'
A trivial tuple used to represent a source range.
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
unsigned NumArgs
NumArgs - The number of template arguments.
bool isAnnotation() const
Return true if this is any of tok::annot_* kind tokens.
ParsedType getType() const
The symbol does not exist.
void CodeCompleteInPreprocessorConditionalExclusion(Scope *S)
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
ParsedAttributes & getAttributes()
void startToken()
Reset all flags to cleared.
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.
bool ParseFirstTopLevelDecl(DeclGroupPtrTy &Result)
Parse the first top-level declaration in a translation unit.
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
AttributeList - Represents a syntactic attribute.
bool isBacktrackEnabled() const
True if EnableBacktrackAtThisPos() was called and caching of tokens is on.
Stop skipping at specified token, but don't skip the token itself.
IdentifierInfo * getIdentifierInfo() const
const AttributeList * getAttributes() const