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;
495 Ident__except =
nullptr;
497 Ident__exception_code = Ident__exception_info =
nullptr;
498 Ident__abnormal_termination = Ident___exception_code =
nullptr;
499 Ident___exception_info = Ident___abnormal_termination =
nullptr;
500 Ident_GetExceptionCode = Ident_GetExceptionInfo =
nullptr;
501 Ident_AbnormalTermination =
nullptr;
514 PP.
SetPoisonReason(Ident__exception_code,diag::err_seh___except_block);
515 PP.
SetPoisonReason(Ident___exception_code,diag::err_seh___except_block);
516 PP.
SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block);
517 PP.
SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter);
518 PP.
SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter);
519 PP.
SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter);
520 PP.
SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block);
521 PP.
SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block);
522 PP.
SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block);
531 void Parser::LateTemplateParserCleanupCallback(
void *
P) {
535 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(((
Parser *)P)->TemplateIds);
541 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
550 case tok::annot_pragma_unused:
551 HandlePragmaUnused();
554 case tok::annot_module_include:
556 reinterpret_cast<Module *
>(
561 case tok::annot_module_begin:
567 case tok::annot_module_end:
578 LateTemplateParserCleanupCallback :
nullptr,
589 ParsedAttributesWithRange attrs(AttrFactory);
590 MaybeParseCXX11Attributes(attrs);
591 MaybeParseMicrosoftAttributes(attrs);
593 Result = ParseExternalDeclaration(attrs);
621 Parser::ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
623 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds);
631 Decl *SingleDecl =
nullptr;
633 case tok::annot_pragma_vis:
634 HandlePragmaVisibility();
636 case tok::annot_pragma_pack:
639 case tok::annot_pragma_msstruct:
640 HandlePragmaMSStruct();
642 case tok::annot_pragma_align:
645 case tok::annot_pragma_weak:
648 case tok::annot_pragma_weakalias:
649 HandlePragmaWeakAlias();
651 case tok::annot_pragma_redefine_extname:
652 HandlePragmaRedefineExtname();
654 case tok::annot_pragma_fp_contract:
655 HandlePragmaFPContract();
657 case tok::annot_pragma_opencl_extension:
658 HandlePragmaOpenCLExtension();
660 case tok::annot_pragma_openmp:
661 return ParseOpenMPDeclarativeDirective();
662 case tok::annot_pragma_ms_pointers_to_members:
663 HandlePragmaMSPointersToMembers();
665 case tok::annot_pragma_ms_vtordisp:
666 HandlePragmaMSVtorDisp();
668 case tok::annot_pragma_ms_pragma:
669 HandlePragmaMSPragma();
671 case tok::annot_pragma_dump:
679 ConsumeExtraSemi(OutsideFunction);
682 Diag(Tok, diag::err_extraneous_closing_brace);
686 Diag(Tok, diag::err_expected_external_declaration);
688 case tok::kw___extension__: {
692 return ParseExternalDeclaration(attrs);
695 ProhibitAttributes(attrs);
706 const auto *SL = cast<StringLiteral>(
Result.get());
707 if (!SL->getString().trim().empty())
708 Diag(StartLoc, diag::err_gnu_inline_asm_disabled);
711 ExpectAndConsume(tok::semi, diag::err_expected_after,
712 "top-level asm block");
720 return ParseObjCAtDirectives();
724 Diag(Tok, diag::err_expected_external_declaration);
728 SingleDecl = ParseObjCMethodDefinition();
730 case tok::code_completion:
737 case tok::kw_namespace:
738 case tok::kw_typedef:
739 case tok::kw_template:
741 case tok::kw_static_assert:
742 case tok::kw__Static_assert:
765 if (NextKind == tok::kw_namespace) {
772 if (NextKind == tok::kw_template) {
787 diag::warn_cxx98_compat_extern_template :
788 diag::ext_extern_template) <<
SourceRange(ExternLoc, TemplateLoc);
792 ExternLoc, TemplateLoc, DeclEnd));
796 case tok::kw___if_exists:
797 case tok::kw___if_not_exists:
798 ParseMicrosoftIfExistsExternalDeclaration();
804 return ParseDeclarationOrFunctionDefinition(attrs, DS);
814 bool Parser::isDeclarationAfterDeclarator() {
818 if (KW.
is(tok::kw_default) || KW.
is(tok::kw_delete))
822 return Tok.
is(tok::equal) ||
823 Tok.
is(tok::comma) ||
825 Tok.
is(tok::kw_asm) ||
826 Tok.
is(tok::kw___attribute) ||
828 Tok.
is(tok::l_paren));
835 if (Tok.
is(tok::l_brace))
841 return isDeclarationSpecifier();
845 return KW.
is(tok::kw_default) || KW.
is(tok::kw_delete);
848 return Tok.
is(tok::colon) ||
869 Parser::ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
873 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC_top_level);
878 DiagnoseMissingSemiAfterTagDefinition(DS, AS, DSC_top_level))
883 if (Tok.
is(tok::semi)) {
884 ProhibitAttributes(attrs);
900 Diag(Tok, diag::err_objc_unexpected_attr);
907 const char *PrevSpec =
nullptr;
911 Diag(AtLoc, DiagID) << PrevSpec;
914 return ParseObjCAtProtocolDeclaration(AtLoc, DS.
getAttributes());
923 if (
getLangOpts().CPlusPlus && isTokenStringLiteral() &&
934 Parser::ParseDeclarationOrFunctionDefinition(ParsedAttributesWithRange &attrs,
938 return ParseDeclOrFunctionDefInternal(attrs, *DS, AS);
946 return ParseDeclOrFunctionDefInternal(attrs, PDS, AS);
965 const ParsedTemplateInfo &TemplateInfo,
966 LateParsedAttrList *LateParsedAttrs) {
975 const char *PrevSpec;
989 ParseKNRParamDeclarations(D);
993 if (Tok.
isNot(tok::l_brace) &&
995 (Tok.
isNot(tok::colon) && Tok.
isNot(tok::kw_try) &&
996 Tok.
isNot(tok::equal)))) {
997 Diag(Tok, diag::err_expected_fn_body);
1003 if (Tok.
isNot(tok::l_brace))
1009 if (Tok.
isNot(tok::equal)) {
1014 Diag(DtorAttrs->
getLoc(), diag::warn_attribute_on_function_definition)
1017 DtorAttrs = DtorAttrs->
getNext();
1024 TemplateInfo.Kind == ParsedTemplateInfo::Template &&
1038 LexTemplateFunctionForLateParsing(Toks);
1047 else if (CurParsedObjCImpl &&
1048 !TemplateInfo.TemplateParams &&
1049 (Tok.
is(tok::l_brace) || Tok.
is(tok::kw_try) ||
1050 Tok.
is(tok::colon)) &&
1062 StashAwayMethodOrFunctionBodyTokens(FuncDecl);
1063 CurParsedObjCImpl->HasCFunction =
true;
1076 TemplateInfo.TemplateParams
1077 ? *TemplateInfo.TemplateParams
1096 bool Delete =
false;
1100 ? diag::warn_cxx98_compat_defaulted_deleted_function
1101 : diag::ext_defaulted_deleted_function)
1107 ? diag::warn_cxx98_compat_defaulted_deleted_function
1108 : diag::ext_defaulted_deleted_function)
1112 llvm_unreachable(
"function definition after = not 'delete' or 'default'");
1115 if (Tok.
is(tok::comma)) {
1116 Diag(KWLoc, diag::err_default_delete_in_multiple_declaration)
1119 }
else if (ExpectAndConsume(tok::semi, diag::err_expected_after,
1120 Delete ?
"delete" :
"default")) {
1124 Stmt *GeneratedBody = Res ? Res->
getBody() :
nullptr;
1129 if (Tok.
is(tok::kw_try))
1130 return ParseFunctionTryBlock(Res, BodyScope);
1134 if (Tok.
is(tok::colon)) {
1135 ParseConstructorInitializer(Res);
1138 if (!Tok.
is(tok::l_brace)) {
1147 if (LateParsedAttrs)
1148 ParseLexedAttributeList(*LateParsedAttrs, Res,
false,
true);
1150 return ParseFunctionStatementBody(Res, BodyScope);
1153 void Parser::SkipFunctionBody() {
1154 if (Tok.
is(tok::equal)) {
1159 bool IsFunctionTryBlock = Tok.
is(tok::kw_try);
1160 if (IsFunctionTryBlock)
1164 if (ConsumeAndStoreFunctionPrologue(Skipped))
1168 while (IsFunctionTryBlock && Tok.
is(tok::kw_catch)) {
1177 void Parser::ParseKNRParamDeclarations(Declarator &D) {
1187 while (isDeclarationSpecifier()) {
1192 ParseDeclarationSpecifiers(DS);
1200 Diag(DSStart, diag::err_declaration_does_not_declare_param);
1209 diag::err_invalid_storage_class_in_func_decl);
1214 diag::err_invalid_storage_class_in_func_decl);
1220 ParseDeclarator(ParmDeclarator);
1225 MaybeParseGNUAttributes(ParmDeclarator);
1233 ParmDeclarator.getIdentifier()) {
1237 for (
unsigned i = 0; ; ++i) {
1241 Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param)
1242 << ParmDeclarator.getIdentifier();
1246 if (FTI.
Params[i].
Ident == ParmDeclarator.getIdentifier()) {
1249 Diag(ParmDeclarator.getIdentifierLoc(),
1250 diag::err_param_redefinition)
1251 << ParmDeclarator.getIdentifier();
1262 if (Tok.
isNot(tok::comma))
1265 ParmDeclarator.clear();
1271 ParseDeclarator(ParmDeclarator);
1275 if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration))
1296 if (!isTokenStringLiteral()) {
1297 Diag(Tok, diag::err_expected_string_literal)
1302 ExprResult AsmString(ParseStringLiteralExpression());
1303 if (!AsmString.isInvalid()) {
1304 const auto *SL = cast<StringLiteral>(AsmString.get());
1305 if (!SL->isAscii()) {
1306 Diag(Tok, diag::err_asm_operand_wide_string_literal)
1308 << SL->getSourceRange();
1321 assert(Tok.
is(tok::kw_asm) &&
"Not an asm!");
1324 if (Tok.
is(tok::kw_volatile)) {
1329 Diag(Tok, diag::warn_file_asm_volatile)
1335 if (T.consumeOpen()) {
1336 Diag(Tok, diag::err_expected_lparen_after) <<
"asm";
1342 if (!
Result.isInvalid()) {
1346 *EndLoc = T.getCloseLocation();
1360 assert(tok.
is(tok::annot_template_id) &&
"Expected template-id token");
1366 void Parser::AnnotateScopeToken(
CXXScopeSpec &SS,
bool IsNewAnnotation) {
1373 Tok.
setKind(tok::annot_cxxscope);
1380 if (IsNewAnnotation)
1393 Parser::AnnotatedNameKind
1394 Parser::TryAnnotateName(
bool IsAddressOfOperand,
1395 std::unique_ptr<CorrectionCandidateCallback> CCC) {
1396 assert(Tok.
is(tok::identifier) || Tok.
is(tok::annot_cxxscope));
1398 const bool EnteringContext =
false;
1399 const bool WasScopeAnnotation = Tok.
is(tok::annot_cxxscope);
1403 ParseOptionalCXXScopeSpecifier(SS,
ParsedType(), EnteringContext))
1408 !WasScopeAnnotation))
1410 return ANK_Unresolved;
1418 if (isTentativelyDeclared(Name)) {
1422 !WasScopeAnnotation))
1424 return Tok.
is(tok::annot_typename) ? ANK_Success : ANK_TentativeDecl;
1434 getCurScope(), SS, Name, NameLoc, Next, IsAddressOfOperand,
1435 SS.
isEmpty() ? std::move(CCC) : nullptr);
1437 switch (Classification.
getKind()) {
1447 AnnotateScopeToken(SS, !WasScopeAnnotation);
1470 = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
1477 Tok.
setKind(tok::annot_typename);
1478 setTypeAnnotation(Tok, Ty);
1486 Tok.
setKind(tok::annot_primary_expr);
1495 if (Next.
isNot(tok::less)) {
1498 AnnotateScopeToken(SS, !WasScopeAnnotation);
1499 return ANK_TemplateName;
1508 if (AnnotateTemplateIdToken(
1516 llvm_unreachable(
"already parsed nested name specifier");
1521 AnnotateScopeToken(SS, !WasScopeAnnotation);
1522 return ANK_Unresolved;
1525 bool Parser::TryKeywordIdentFallback(
bool DisableKeyword) {
1526 assert(Tok.
isNot(tok::identifier));
1527 Diag(Tok, diag::ext_keyword_as_ident)
1559 assert((Tok.
is(tok::identifier) || Tok.
is(tok::coloncolon) ||
1560 Tok.
is(tok::kw_typename) || Tok.
is(tok::annot_cxxscope) ||
1561 Tok.
is(tok::kw_decltype) || Tok.
is(tok::annot_template_id) ||
1562 Tok.
is(tok::kw___super)) &&
1563 "Cannot be a type or scope token!");
1565 if (Tok.
is(tok::kw_typename)) {
1574 PP.
Lex(TypedefToken);
1579 Diag(Tok.
getLocation(), diag::warn_expected_qualified_after_typename);
1591 if (ParseOptionalCXXScopeSpecifier(SS,
ParsedType(),
1596 if (Tok.
is(tok::identifier) || Tok.
is(tok::annot_template_id) ||
1597 Tok.
is(tok::annot_decltype)) {
1599 if (Tok.
is(tok::annot_decltype) ||
1602 unsigned DiagID = diag::err_expected_qualified_after_typename;
1606 DiagID = diag::warn_expected_qualified_after_typename;
1617 if (Tok.
is(tok::identifier)) {
1622 }
else if (Tok.
is(tok::annot_template_id)) {
1626 Diag(Tok, diag::err_typename_refers_to_non_type_template)
1642 Diag(Tok, diag::err_expected_type_name_after_typename)
1648 Tok.
setKind(tok::annot_typename);
1657 bool WasScopeAnnotation = Tok.
is(tok::annot_cxxscope);
1661 if (ParseOptionalCXXScopeSpecifier(SS,
ParsedType(), EnteringContext))
1665 SS, !WasScopeAnnotation);
1675 if (Tok.
is(tok::identifier)) {
1685 NeedType ? &CorrectedII
1704 = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty,
1713 Tok.
setKind(tok::annot_typename);
1714 setTypeAnnotation(Tok, Ty);
1736 bool MemberOfUnknownSpecialization;
1739 false, TemplateName,
1742 Template, MemberOfUnknownSpecialization)) {
1761 if (Tok.
is(tok::annot_template_id)) {
1768 AnnotateTemplateIdTokenAsType();
1777 AnnotateScopeToken(SS, IsNewScope);
1789 "Call sites of this function should be guarded by checking for C++");
1790 assert((Tok.
is(tok::identifier) || Tok.
is(tok::coloncolon) ||
1791 (Tok.
is(tok::annot_template_id) &&
NextToken().
is(tok::coloncolon)) ||
1792 Tok.
is(tok::kw_decltype) || Tok.
is(tok::kw___super)) &&
1793 "Cannot be a type or scope token!");
1796 if (ParseOptionalCXXScopeSpecifier(SS,
ParsedType(), EnteringContext))
1801 AnnotateScopeToken(SS,
true);
1805 bool Parser::isTokenEqualOrEqualTypo() {
1811 case tok::starequal:
1812 case tok::plusequal:
1813 case tok::minusequal:
1814 case tok::exclaimequal:
1815 case tok::slashequal:
1816 case tok::percentequal:
1817 case tok::lessequal:
1818 case tok::lesslessequal:
1819 case tok::greaterequal:
1820 case tok::greatergreaterequal:
1821 case tok::caretequal:
1822 case tok::pipeequal:
1823 case tok::equalequal:
1824 Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal)
1833 assert(Tok.
is(tok::code_completion));
1841 return PrevTokLocation;
1847 return PrevTokLocation;
1853 return PrevTokLocation;
1858 void Parser::CodeCompleteDirective(
bool InConditional) {
1862 void Parser::CodeCompleteInConditionalExclusion() {
1866 void Parser::CodeCompleteMacroName(
bool IsDefinition) {
1870 void Parser::CodeCompletePreprocessorExpression() {
1876 unsigned ArgumentIndex) {
1881 void Parser::CodeCompleteNaturalLanguage() {
1885 bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) {
1886 assert((Tok.
is(tok::kw___if_exists) || Tok.
is(tok::kw___if_not_exists)) &&
1887 "Expected '__if_exists' or '__if_not_exists'");
1888 Result.IsIfExists = Tok.
is(tok::kw___if_exists);
1892 if (T.consumeOpen()) {
1893 Diag(Tok, diag::err_expected_lparen_after)
1894 << (Result.IsIfExists?
"__if_exists" :
"__if_not_exists");
1900 ParseOptionalCXXScopeSpecifier(Result.SS,
ParsedType(),
1904 if (Result.SS.isInvalid()) {
1912 TemplateKWLoc, Result.Name)) {
1917 if (T.consumeClose())
1922 Result.IsIfExists, Result.SS,
1925 Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip;
1929 Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip;
1933 Result.Behavior = IEB_Dependent;
1943 void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
1944 IfExistsCondition
Result;
1945 if (ParseMicrosoftIfExistsCondition(Result))
1949 if (Braces.consumeOpen()) {
1950 Diag(Tok, diag::err_expected) << tok::l_brace;
1954 switch (Result.Behavior) {
1960 llvm_unreachable(
"Cannot have a dependent external declaration");
1969 while (Tok.
isNot(tok::r_brace) && !isEofOrEom()) {
1970 ParsedAttributesWithRange attrs(AttrFactory);
1971 MaybeParseCXX11Attributes(attrs);
1972 MaybeParseMicrosoftAttributes(attrs);
1977 Braces.consumeClose();
1982 "Improper start to module import");
1989 if (!Tok.
is(tok::identifier)) {
1990 if (Tok.
is(tok::code_completion)) {
1996 Diag(Tok, diag::err_module_expected_ident);
2005 if (Tok.
is(tok::period)) {
2020 ExpectAndConsumeSemi(diag::err_module_expected_semi);
2031 bool Parser::parseMisplacedModuleImport() {
2034 case tok::annot_module_end:
2038 case tok::annot_module_begin:
2042 case tok::annot_module_include:
2046 reinterpret_cast<Module *
>(
2058 bool BalancedDelimiterTracker::diagnoseOverflow() {
2059 P.Diag(P.Tok, diag::err_bracket_depth_exceeded)
2060 << P.getLangOpts().BracketDepth;
2061 P.Diag(P.Tok, diag::note_bracket_depth);
2069 LOpen = P.Tok.getLocation();
2070 if (P.ExpectAndConsume(Kind, DiagID, Msg)) {
2071 if (SkipToTok != tok::unknown)
2076 if (getDepth() < MaxDepth)
2079 return diagnoseOverflow();
2082 bool BalancedDelimiterTracker::diagnoseMissingClose() {
2083 assert(!P.Tok.is(Close) &&
"Should have consumed closing delimiter");
2085 if (P.Tok.is(tok::annot_module_end))
2086 P.Diag(P.Tok, diag::err_missing_before_module_end) << Close;
2088 P.Diag(P.Tok, diag::err_expected) << Close;
2089 P.Diag(LOpen, diag::note_matching) << Kind;
2093 if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) &&
2094 P.Tok.isNot(tok::r_square) &&
2095 P.SkipUntil(Close, FinalToken,
2098 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.
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.
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...
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)
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.
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
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.
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS=nullptr, bool isClassName=false, bool HasTrailingDot=false, ParsedType ObjectType=ParsedType(), 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...
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)
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...
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)
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.
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
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.
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)
Decl * ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS)
ParsedFreeStandingDeclSpec - This method is invoked when a declspec with no declarator (e...
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