23 #include "llvm/Support/raw_ostream.h"
24 using namespace clang;
34 explicit ActionCommentHandler(
Sema &
S) : S(S) { }
44 class DestroyTemplateIdAnnotationsRAIIObj {
48 DestroyTemplateIdAnnotationsRAIIObj(
50 : Container(Container) {}
52 ~DestroyTemplateIdAnnotationsRAIIObj() {
72 : PP(pp), Actions(actions), Diags(PP.getDiagnostics()),
73 GreaterThanIsOperator(
true), ColonIsSacred(
false),
74 InMessageExpression(
false), TemplateParameterDepth(0),
75 ParsingInObjCContainer(
false) {
79 Actions.CurScope =
nullptr;
81 ParenCount = BracketCount = BraceCount = 0;
82 CurParsedObjCImpl =
nullptr;
86 initializePragmaHandlers();
88 CommentSemaHandler.reset(
new ActionCommentHandler(actions));
95 return Diags.
Report(Loc, DiagID);
124 switch (ExpectedTok) {
126 return Tok.
is(tok::colon) || Tok.
is(tok::comma);
127 default:
return false;
131 bool Parser::ExpectAndConsume(
tok::TokenKind ExpectedTok,
unsigned DiagID,
133 if (Tok.
is(ExpectedTok) || Tok.
is(tok::code_completion)) {
145 if (DiagID == diag::err_expected)
147 else if (DiagID == diag::err_expected_after)
148 DB << Msg << ExpectedTok;
159 const char *Spelling =
nullptr;
167 if (DiagID == diag::err_expected)
169 else if (DiagID == diag::err_expected_after)
170 DB << Msg << ExpectedTok;
177 bool Parser::ExpectAndConsumeSemi(
unsigned DiagID) {
181 if (Tok.
is(tok::code_completion)) {
182 handleUnexpectedCodeCompletionToken();
186 if ((Tok.
is(tok::r_paren) || Tok.
is(tok::r_square)) &&
188 Diag(Tok, diag::err_extraneous_token_before_semi)
196 return ExpectAndConsume(tok::semi, DiagID);
199 void Parser::ConsumeExtraSemi(ExtraSemiKind
Kind,
unsigned TST) {
200 if (!Tok.
is(tok::semi))
return;
202 bool HadMultipleSemis =
false;
208 HadMultipleSemis =
true;
217 Diag(StartLoc, diag::warn_cxx98_compat_top_level_semi)
220 Diag(StartLoc, diag::ext_extra_semi_cxx11)
225 if (Kind != AfterMemberFunctionDefinition || HadMultipleSemis)
226 Diag(StartLoc, diag::ext_extra_semi)
232 Diag(StartLoc, diag::warn_extra_semi_after_mem_fn_def)
241 return (static_cast<unsigned>(L) & static_cast<unsigned>(R)) != 0;
255 bool isFirstTokenSkipped =
true;
258 for (
unsigned i = 0, NumToks = Toks.size(); i != NumToks; ++i) {
259 if (Tok.
is(Toks[i])) {
272 if (Toks.size() == 1 && Toks[0] ==
tok::eof &&
285 case tok::annot_pragma_openmp:
286 case tok::annot_pragma_openmp_end:
288 case tok::annot_module_begin:
289 case tok::annot_module_end:
290 case tok::annot_module_include:
296 case tok::code_completion:
298 handleUnexpectedCodeCompletionToken();
332 if (ParenCount && !isFirstTokenSkipped)
337 if (BracketCount && !isFirstTokenSkipped)
342 if (BraceCount && !isFirstTokenSkipped)
347 case tok::string_literal:
348 case tok::wide_string_literal:
349 case tok::utf8_string_literal:
350 case tok::utf16_string_literal:
351 case tok::utf32_string_literal:
352 ConsumeStringToken();
364 isFirstTokenSkipped =
false;
374 if (NumCachedScopes) {
375 Scope *N = ScopeCache[--NumCachedScopes];
377 Actions.CurScope = N;
392 Actions.CurScope = OldScope->
getParent();
394 if (NumCachedScopes == ScopeCacheSize)
397 ScopeCache[NumCachedScopes++] = OldScope;
402 Parser::ParseScopeFlags::ParseScopeFlags(
Parser *Self,
unsigned ScopeFlags,
404 : CurScope(ManageFlags ? Self->getCurScope() : nullptr) {
406 OldFlags = CurScope->getFlags();
407 CurScope->setFlags(ScopeFlags);
413 Parser::ParseScopeFlags::~ParseScopeFlags() {
415 CurScope->setFlags(OldFlags);
426 Actions.CurScope =
nullptr;
429 for (
unsigned i = 0, e = NumCachedScopes; i != e; ++i)
430 delete ScopeCache[i];
432 resetPragmaHandlers();
444 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
447 assert(TemplateIds.empty() &&
"Still alive TemplateIdAnnotations around?");
454 assert(
getCurScope() ==
nullptr &&
"A scope is already active?");
469 ObjCTypeQuals[objc_null_unspecified]
473 Ident_instancetype =
nullptr;
474 Ident_final =
nullptr;
475 Ident_sealed =
nullptr;
476 Ident_override =
nullptr;
480 Ident_vector =
nullptr;
481 Ident_bool =
nullptr;
482 Ident_pixel =
nullptr;
490 Ident_introduced =
nullptr;
491 Ident_deprecated =
nullptr;
492 Ident_obsoleted =
nullptr;
493 Ident_unavailable =
nullptr;
494 Ident_strict =
nullptr;
495 Ident_replacement =
nullptr;
497 Ident__except =
nullptr;
499 Ident__exception_code = Ident__exception_info =
nullptr;
500 Ident__abnormal_termination = Ident___exception_code =
nullptr;
501 Ident___exception_info = Ident___abnormal_termination =
nullptr;
502 Ident_GetExceptionCode = Ident_GetExceptionInfo =
nullptr;
503 Ident_AbnormalTermination =
nullptr;
516 PP.
SetPoisonReason(Ident__exception_code,diag::err_seh___except_block);
517 PP.
SetPoisonReason(Ident___exception_code,diag::err_seh___except_block);
518 PP.
SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block);
519 PP.
SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter);
520 PP.
SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter);
521 PP.
SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter);
522 PP.
SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block);
523 PP.
SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block);
524 PP.
SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block);
533 void Parser::LateTemplateParserCleanupCallback(
void *
P) {
537 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(((
Parser *)P)->TemplateIds);
543 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
552 case tok::annot_pragma_unused:
553 HandlePragmaUnused();
556 case tok::annot_module_include:
558 reinterpret_cast<Module *
>(
563 case tok::annot_module_begin:
569 case tok::annot_module_end:
580 LateTemplateParserCleanupCallback :
nullptr,
591 ParsedAttributesWithRange attrs(AttrFactory);
592 MaybeParseCXX11Attributes(attrs);
593 MaybeParseMicrosoftAttributes(attrs);
595 Result = ParseExternalDeclaration(attrs);
623 Parser::ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
625 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
633 Decl *SingleDecl =
nullptr;
635 case tok::annot_pragma_vis:
636 HandlePragmaVisibility();
638 case tok::annot_pragma_pack:
641 case tok::annot_pragma_msstruct:
642 HandlePragmaMSStruct();
644 case tok::annot_pragma_align:
647 case tok::annot_pragma_weak:
650 case tok::annot_pragma_weakalias:
651 HandlePragmaWeakAlias();
653 case tok::annot_pragma_redefine_extname:
654 HandlePragmaRedefineExtname();
656 case tok::annot_pragma_fp_contract:
657 HandlePragmaFPContract();
659 case tok::annot_pragma_opencl_extension:
660 HandlePragmaOpenCLExtension();
662 case tok::annot_pragma_openmp: {
664 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, attrs);
666 case tok::annot_pragma_ms_pointers_to_members:
667 HandlePragmaMSPointersToMembers();
669 case tok::annot_pragma_ms_vtordisp:
670 HandlePragmaMSVtorDisp();
672 case tok::annot_pragma_ms_pragma:
673 HandlePragmaMSPragma();
675 case tok::annot_pragma_dump:
683 ConsumeExtraSemi(OutsideFunction);
686 Diag(Tok, diag::err_extraneous_closing_brace);
690 Diag(Tok, diag::err_expected_external_declaration);
692 case tok::kw___extension__: {
696 return ParseExternalDeclaration(attrs);
699 ProhibitAttributes(attrs);
710 const auto *SL = cast<StringLiteral>(
Result.get());
711 if (!SL->getString().trim().empty())
712 Diag(StartLoc, diag::err_gnu_inline_asm_disabled);
715 ExpectAndConsume(tok::semi, diag::err_expected_after,
716 "top-level asm block");
724 return ParseObjCAtDirectives();
728 Diag(Tok, diag::err_expected_external_declaration);
732 SingleDecl = ParseObjCMethodDefinition();
734 case tok::code_completion:
741 case tok::kw_namespace:
742 case tok::kw_typedef:
743 case tok::kw_template:
745 case tok::kw_static_assert:
746 case tok::kw__Static_assert:
769 if (NextKind == tok::kw_namespace) {
776 if (NextKind == tok::kw_template) {
791 diag::warn_cxx98_compat_extern_template :
792 diag::ext_extern_template) <<
SourceRange(ExternLoc, TemplateLoc);
796 ExternLoc, TemplateLoc, DeclEnd));
800 case tok::kw___if_exists:
801 case tok::kw___if_not_exists:
802 ParseMicrosoftIfExistsExternalDeclaration();
808 return ParseDeclarationOrFunctionDefinition(attrs, DS);
818 bool Parser::isDeclarationAfterDeclarator() {
822 if (KW.
is(tok::kw_default) || KW.
is(tok::kw_delete))
826 return Tok.
is(tok::equal) ||
827 Tok.
is(tok::comma) ||
829 Tok.
is(tok::kw_asm) ||
830 Tok.
is(tok::kw___attribute) ||
832 Tok.
is(tok::l_paren));
839 if (Tok.
is(tok::l_brace))
845 return isDeclarationSpecifier();
849 return KW.
is(tok::kw_default) || KW.
is(tok::kw_delete);
852 return Tok.
is(tok::colon) ||
873 Parser::ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
877 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC_top_level);
882 DiagnoseMissingSemiAfterTagDefinition(DS, AS, DSC_top_level))
887 if (Tok.
is(tok::semi)) {
888 ProhibitAttributes(attrs);
895 Decl* decls[] = {AnonRecord, TheDecl};
910 Diag(Tok, diag::err_objc_unexpected_attr);
917 const char *PrevSpec =
nullptr;
921 Diag(AtLoc, DiagID) << PrevSpec;
924 return ParseObjCAtProtocolDeclaration(AtLoc, DS.
getAttributes());
933 if (
getLangOpts().CPlusPlus && isTokenStringLiteral() &&
944 Parser::ParseDeclarationOrFunctionDefinition(ParsedAttributesWithRange &attrs,
948 return ParseDeclOrFunctionDefInternal(attrs, *DS, AS);
956 return ParseDeclOrFunctionDefInternal(attrs, PDS, AS);
975 const ParsedTemplateInfo &TemplateInfo,
976 LateParsedAttrList *LateParsedAttrs) {
985 const char *PrevSpec;
999 ParseKNRParamDeclarations(D);
1003 if (Tok.
isNot(tok::l_brace) &&
1005 (Tok.
isNot(tok::colon) && Tok.
isNot(tok::kw_try) &&
1006 Tok.
isNot(tok::equal)))) {
1007 Diag(Tok, diag::err_expected_fn_body);
1013 if (Tok.
isNot(tok::l_brace))
1019 if (Tok.
isNot(tok::equal)) {
1024 Diag(DtorAttrs->
getLoc(), diag::warn_attribute_on_function_definition)
1027 DtorAttrs = DtorAttrs->
getNext();
1034 TemplateInfo.Kind == ParsedTemplateInfo::Template &&
1048 trySkippingFunctionBody()) {
1054 LexTemplateFunctionForLateParsing(Toks);
1063 else if (CurParsedObjCImpl &&
1064 !TemplateInfo.TemplateParams &&
1065 (Tok.
is(tok::l_brace) || Tok.
is(tok::kw_try) ||
1066 Tok.
is(tok::colon)) &&
1078 StashAwayMethodOrFunctionBodyTokens(FuncDecl);
1079 CurParsedObjCImpl->HasCFunction =
true;
1092 TemplateInfo.TemplateParams
1093 ? *TemplateInfo.TemplateParams
1112 bool Delete =
false;
1116 ? diag::warn_cxx98_compat_defaulted_deleted_function
1117 : diag::ext_defaulted_deleted_function)
1123 ? diag::warn_cxx98_compat_defaulted_deleted_function
1124 : diag::ext_defaulted_deleted_function)
1128 llvm_unreachable(
"function definition after = not 'delete' or 'default'");
1131 if (Tok.
is(tok::comma)) {
1132 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
1135 }
else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
1136 Delete ?
"delete" :
"default")) {
1140 Stmt *GeneratedBody = Res ? Res->getBody() :
nullptr;
1146 trySkippingFunctionBody()) {
1152 if (Tok.
is(tok::kw_try))
1153 return ParseFunctionTryBlock(Res, BodyScope);
1157 if (Tok.
is(tok::colon)) {
1158 ParseConstructorInitializer(Res);
1161 if (!Tok.
is(tok::l_brace)) {
1170 if (LateParsedAttrs)
1171 ParseLexedAttributeList(*LateParsedAttrs, Res,
false,
true);
1173 return ParseFunctionStatementBody(Res, BodyScope);
1176 void Parser::SkipFunctionBody() {
1177 if (Tok.
is(tok::equal)) {
1182 bool IsFunctionTryBlock = Tok.
is(tok::kw_try);
1183 if (IsFunctionTryBlock)
1187 if (ConsumeAndStoreFunctionPrologue(Skipped))
1191 while (IsFunctionTryBlock && Tok.
is(tok::kw_catch)) {
1200 void Parser::ParseKNRParamDeclarations(Declarator &D) {
1210 while (isDeclarationSpecifier()) {
1215 ParseDeclarationSpecifiers(DS);
1223 Diag(DSStart, diag::err_declaration_does_not_declare_param);
1232 diag::err_invalid_storage_class_in_func_decl);
1237 diag::err_invalid_storage_class_in_func_decl);
1243 ParseDeclarator(ParmDeclarator);
1248 MaybeParseGNUAttributes(ParmDeclarator);
1256 ParmDeclarator.getIdentifier()) {
1260 for (
unsigned i = 0; ; ++i) {
1264 Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
1265 << ParmDeclarator.getIdentifier();
1269 if (FTI.
Params[i].
Ident == ParmDeclarator.getIdentifier()) {
1272 Diag(ParmDeclarator.getIdentifierLoc(),
1273 diag::err_param_redefinition)
1274 << ParmDeclarator.getIdentifier();
1285 if (Tok.
isNot(tok::comma))
1288 ParmDeclarator.clear();
1294 ParseDeclarator(ParmDeclarator);
1298 if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration))
1319 if (!isTokenStringLiteral()) {
1320 Diag(Tok, diag::err_expected_string_literal)
1325 ExprResult AsmString(ParseStringLiteralExpression());
1326 if (!AsmString.isInvalid()) {
1327 const auto *SL = cast<StringLiteral>(AsmString.get());
1328 if (!SL->isAscii()) {
1329 Diag(Tok, diag::err_asm_operand_wide_string_literal)
1331 << SL->getSourceRange();
1344 assert(Tok.
is(tok::kw_asm) &&
"Not an asm!");
1347 if (Tok.
is(tok::kw_volatile)) {
1352 Diag(Tok, diag::warn_file_asm_volatile)
1358 if (T.consumeOpen()) {
1359 Diag(Tok, diag::err_expected_lparen_after) <<
"asm";
1365 if (!
Result.isInvalid()) {
1369 *EndLoc = T.getCloseLocation();
1383 assert(tok.
is(tok::annot_template_id) &&
"Expected template-id token");
1389 void Parser::AnnotateScopeToken(
CXXScopeSpec &SS,
bool IsNewAnnotation) {
1396 Tok.
setKind(tok::annot_cxxscope);
1403 if (IsNewAnnotation)
1416 Parser::AnnotatedNameKind
1417 Parser::TryAnnotateName(
bool IsAddressOfOperand,
1418 std::unique_ptr<CorrectionCandidateCallback> CCC) {
1419 assert(Tok.
is(tok::identifier) || Tok.
is(tok::annot_cxxscope));
1421 const bool EnteringContext =
false;
1422 const bool WasScopeAnnotation = Tok.
is(tok::annot_cxxscope);
1426 ParseOptionalCXXScopeSpecifier(SS,
nullptr, EnteringContext))
1431 !WasScopeAnnotation))
1433 return ANK_Unresolved;
1441 if (isTentativelyDeclared(Name)) {
1445 !WasScopeAnnotation))
1447 return Tok.
is(tok::annot_typename) ? ANK_Success : ANK_TentativeDecl;
1457 getCurScope(), SS, Name, NameLoc, Next, IsAddressOfOperand,
1458 SS.
isEmpty() ? std::move(CCC) : nullptr);
1460 switch (Classification.
getKind()) {
1470 AnnotateScopeToken(SS, !WasScopeAnnotation);
1493 = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
1500 Tok.
setKind(tok::annot_typename);
1501 setTypeAnnotation(Tok, Ty);
1509 Tok.
setKind(tok::annot_primary_expr);
1518 if (Next.
isNot(tok::less)) {
1521 AnnotateScopeToken(SS, !WasScopeAnnotation);
1522 return ANK_TemplateName;
1531 if (AnnotateTemplateIdToken(
1539 llvm_unreachable(
"already parsed nested name specifier");
1544 AnnotateScopeToken(SS, !WasScopeAnnotation);
1545 return ANK_Unresolved;
1548 bool Parser::TryKeywordIdentFallback(
bool DisableKeyword) {
1549 assert(Tok.
isNot(tok::identifier));
1550 Diag(Tok, diag::ext_keyword_as_ident)
1582 assert((Tok.
is(tok::identifier) || Tok.
is(tok::coloncolon) ||
1583 Tok.
is(tok::kw_typename) || Tok.
is(tok::annot_cxxscope) ||
1584 Tok.
is(tok::kw_decltype) || Tok.
is(tok::annot_template_id) ||
1585 Tok.
is(tok::kw___super)) &&
1586 "Cannot be a type or scope token!");
1588 if (Tok.
is(tok::kw_typename)) {
1597 PP.
Lex(TypedefToken);
1602 Diag(Tok.
getLocation(), diag::warn_expected_qualified_after_typename);
1614 if (ParseOptionalCXXScopeSpecifier(SS,
nullptr,
1619 if (Tok.
is(tok::identifier) || Tok.
is(tok::annot_template_id) ||
1620 Tok.
is(tok::annot_decltype)) {
1622 if (Tok.
is(tok::annot_decltype) ||
1625 unsigned DiagID = diag::err_expected_qualified_after_typename;
1629 DiagID = diag::warn_expected_qualified_after_typename;
1640 if (Tok.
is(tok::identifier)) {
1645 }
else if (Tok.
is(tok::annot_template_id)) {
1649 Diag(Tok, diag::err_typename_refers_to_non_type_template)
1665 Diag(Tok, diag::err_expected_type_name_after_typename)
1671 Tok.
setKind(tok::annot_typename);
1672 setTypeAnnotation(Tok, Ty.
isInvalid() ?
nullptr : Ty.
get());
1680 bool WasScopeAnnotation = Tok.
is(tok::annot_cxxscope);
1684 if (ParseOptionalCXXScopeSpecifier(SS,
nullptr, EnteringContext))
1688 SS, !WasScopeAnnotation);
1698 if (Tok.
is(tok::identifier)) {
1706 NeedType ? &CorrectedII :
nullptr)) {
1724 = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
1733 Tok.
setKind(tok::annot_typename);
1734 setTypeAnnotation(Tok, Ty);
1756 bool MemberOfUnknownSpecialization;
1759 false, TemplateName,
1760 nullptr, EnteringContext,
1761 Template, MemberOfUnknownSpecialization)) {
1780 if (Tok.
is(tok::annot_template_id)) {
1787 AnnotateTemplateIdTokenAsType();
1796 AnnotateScopeToken(SS, IsNewScope);
1808 "Call sites of this function should be guarded by checking for C++");
1809 assert((Tok.
is(tok::identifier) || Tok.
is(tok::coloncolon) ||
1810 (Tok.
is(tok::annot_template_id) &&
NextToken().
is(tok::coloncolon)) ||
1811 Tok.
is(tok::kw_decltype) || Tok.
is(tok::kw___super)) &&
1812 "Cannot be a type or scope token!");
1815 if (ParseOptionalCXXScopeSpecifier(SS,
nullptr, EnteringContext))
1820 AnnotateScopeToken(SS,
true);
1824 bool Parser::isTokenEqualOrEqualTypo() {
1830 case tok::starequal:
1831 case tok::plusequal:
1832 case tok::minusequal:
1833 case tok::exclaimequal:
1834 case tok::slashequal:
1835 case tok::percentequal:
1836 case tok::lessequal:
1837 case tok::lesslessequal:
1838 case tok::greaterequal:
1839 case tok::greatergreaterequal:
1840 case tok::caretequal:
1841 case tok::pipeequal:
1842 case tok::equalequal:
1843 Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal)
1852 assert(Tok.
is(tok::code_completion));
1860 return PrevTokLocation;
1866 return PrevTokLocation;
1872 return PrevTokLocation;
1877 void Parser::CodeCompleteDirective(
bool InConditional) {
1881 void Parser::CodeCompleteInConditionalExclusion() {
1885 void Parser::CodeCompleteMacroName(
bool IsDefinition) {
1889 void Parser::CodeCompletePreprocessorExpression() {
1895 unsigned ArgumentIndex) {
1900 void Parser::CodeCompleteNaturalLanguage() {
1904 bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) {
1905 assert((Tok.
is(tok::kw___if_exists) || Tok.
is(tok::kw___if_not_exists)) &&
1906 "Expected '__if_exists' or '__if_not_exists'");
1907 Result.IsIfExists = Tok.
is(tok::kw___if_exists);
1911 if (T.consumeOpen()) {
1912 Diag(Tok, diag::err_expected_lparen_after)
1913 << (Result.IsIfExists?
"__if_exists" :
"__if_not_exists");
1919 ParseOptionalCXXScopeSpecifier(Result.SS,
nullptr,
1923 if (Result.SS.isInvalid()) {
1936 if (T.consumeClose())
1941 Result.IsIfExists, Result.SS,
1944 Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip;
1948 Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip;
1952 Result.Behavior = IEB_Dependent;
1962 void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
1963 IfExistsCondition
Result;
1964 if (ParseMicrosoftIfExistsCondition(Result))
1968 if (Braces.consumeOpen()) {
1969 Diag(Tok, diag::err_expected) << tok::l_brace;
1973 switch (Result.Behavior) {
1979 llvm_unreachable(
"Cannot have a dependent external declaration");
1988 while (Tok.
isNot(tok::r_brace) && !isEofOrEom()) {
1989 ParsedAttributesWithRange attrs(AttrFactory);
1990 MaybeParseCXX11Attributes(attrs);
1991 MaybeParseMicrosoftAttributes(attrs);
1996 Braces.consumeClose();
2001 "Improper start to module import");
2008 if (!Tok.
is(tok::identifier)) {
2009 if (Tok.
is(tok::code_completion)) {
2015 Diag(Tok, diag::err_module_expected_ident);
2024 if (Tok.
is(tok::period)) {
2039 ExpectAndConsumeSemi(diag::err_module_expected_semi);
2050 bool Parser::parseMisplacedModuleImport() {
2053 case tok::annot_module_end:
2057 case tok::annot_module_begin:
2061 case tok::annot_module_include:
2065 reinterpret_cast<Module *
>(
2077 bool BalancedDelimiterTracker::diagnoseOverflow() {
2078 P.Diag(P.Tok, diag::err_bracket_depth_exceeded)
2079 << P.getLangOpts().BracketDepth;
2080 P.Diag(P.Tok, diag::note_bracket_depth);
2088 LOpen = P.Tok.getLocation();
2089 if (P.ExpectAndConsume(Kind, DiagID, Msg)) {
2090 if (SkipToTok != tok::unknown)
2095 if (getDepth() < MaxDepth)
2098 return diagnoseOverflow();
2101 bool BalancedDelimiterTracker::diagnoseMissingClose() {
2102 assert(!P.Tok.is(Close) &&
"Should have consumed closing delimiter");
2104 if (P.Tok.is(tok::annot_module_end))
2105 P.Diag(P.Tok, diag::err_missing_before_module_end) << Close;
2107 P.Diag(P.Tok, diag::err_expected) << Close;
2108 P.Diag(LOpen, diag::note_matching) << Kind;
2112 if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) &&
2113 P.Tok.isNot(tok::r_square) &&
2114 P.SkipUntil(Close, FinalToken,
2117 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.
const LangOptions & getLangOpts() const
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
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.
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...
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef< Decl * > Group, bool TypeMayContainAuto=true)
BuildDeclaratorGroup - convert a list of declarations into a declaration group, performing any necess...
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.
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...
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.
class LLVM_ALIGNAS(8) DependentTemplateSpecializationType const IdentifierInfo * Name
Represents a template specialization type whose template cannot be resolved, e.g. ...
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.
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.
void diagnoseMisplacedModuleImport(Module *M, SourceLocation ImportLoc)
Check if module import may be found in the current context, emit error if not.
Code completion occurs at top-level or namespace context.
static bool HasFlagsSet(Parser::SkipUntilFlags L, Parser::SkipUntilFlags R)
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
detail::InMemoryDirectory::const_iterator I
SourceRange getRange() const
SourceLocation TemplateKWLoc
TemplateKWLoc - The location of the template keyword within the source.
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.
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...
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, IdentifierInfo **CorrectedII=nullptr)
If the identifier refers to a type name within this scope, return the declaration of that type...
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...
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 ...
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.
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.
bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(bool EnteringContext, bool NeedType, CXXScopeSpec &SS, bool IsNewScope)
Try to annotate a type or scope token, having already parsed an optional scope specifier.
SourceLocation getLastLoc() const
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.
bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, bool AllowDestructorName, bool AllowConstructorName, ParsedType ObjectType, SourceLocation &TemplateKWLoc, UnqualifiedId &Result)
Parse a C++ unqualified-id (or a C identifier), which describes the name of an entity.
void CodeCompletePreprocessorMacroName(bool IsDefinition)
void setFunctionDefinitionKind(FunctionDefinitionKind Val)
The scope of a struct/union/class definition.
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.
detail::InMemoryDirectory::const_iterator E
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
bool TryAnnotateTypeOrScopeToken(bool EnteringContext=false, bool NeedType=false)
TryAnnotateTypeOrScopeToken - If the current token position is on a typename (possibly qualified in C...
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.
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
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.
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