handle_class.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "toolchain/base/kind_switch.h"
  5. #include "toolchain/check/class.h"
  6. #include "toolchain/check/context.h"
  7. #include "toolchain/check/convert.h"
  8. #include "toolchain/check/decl_name_stack.h"
  9. #include "toolchain/check/merge.h"
  10. #include "toolchain/check/modifiers.h"
  11. #include "toolchain/sem_ir/ids.h"
  12. #include "toolchain/sem_ir/typed_insts.h"
  13. namespace Carbon::Check {
  14. // If `type_id` is a class type, get its corresponding `SemIR::Class` object.
  15. // Otherwise returns `nullptr`.
  16. static auto TryGetAsClass(Context& context, SemIR::TypeId type_id)
  17. -> SemIR::Class* {
  18. auto class_type = context.types().TryGetAs<SemIR::ClassType>(type_id);
  19. if (!class_type) {
  20. return nullptr;
  21. }
  22. return &context.classes().Get(class_type->class_id);
  23. }
  24. auto HandleClassIntroducer(Context& context, Parse::ClassIntroducerId node_id)
  25. -> bool {
  26. // Create an instruction block to hold the instructions created as part of the
  27. // class signature, such as generic parameters.
  28. context.inst_block_stack().Push();
  29. // Push the bracketing node.
  30. context.node_stack().Push(node_id);
  31. // Optional modifiers and the name follow.
  32. context.decl_state_stack().Push(DeclState::Class);
  33. context.decl_name_stack().PushScopeAndStartName();
  34. return true;
  35. }
  36. // Adds the name to name lookup. If there's a conflict, tries to merge. May
  37. // update class_decl and class_info when merging.
  38. static auto MergeOrAddName(Context& context, Parse::AnyClassDeclId node_id,
  39. const DeclNameStack::NameContext& name_context,
  40. SemIR::InstId class_decl_id,
  41. SemIR::ClassDecl& class_decl,
  42. SemIR::Class& class_info, bool is_definition,
  43. bool is_extern) -> void {
  44. auto prev_id =
  45. context.decl_name_stack().LookupOrAddName(name_context, class_decl_id);
  46. if (prev_id.is_valid()) {
  47. auto prev_inst_for_merge =
  48. ResolvePrevInstForMerge(context, node_id, prev_id);
  49. auto prev_class_id = SemIR::ClassId::Invalid;
  50. CARBON_KIND_SWITCH(prev_inst_for_merge.inst) {
  51. case CARBON_KIND(SemIR::ClassDecl class_decl): {
  52. prev_class_id = class_decl.class_id;
  53. break;
  54. }
  55. case CARBON_KIND(SemIR::ClassType class_type): {
  56. prev_class_id = class_type.class_id;
  57. break;
  58. }
  59. default:
  60. // This is a redeclaration of something other than a class.
  61. context.DiagnoseDuplicateName(class_decl_id, prev_id);
  62. break;
  63. }
  64. if (prev_class_id.is_valid()) {
  65. if (MergeClassRedecl(context, node_id, class_info,
  66. /*new_is_import=*/false, is_definition, is_extern,
  67. prev_class_id, prev_inst_for_merge.is_extern,
  68. prev_inst_for_merge.import_ir_inst_id)) {
  69. // When merging, use the existing entity rather than adding a new one.
  70. class_decl.class_id = prev_class_id;
  71. }
  72. } else {
  73. // This is a redeclaration of something other than a class.
  74. context.DiagnoseDuplicateName(class_decl_id, prev_id);
  75. }
  76. }
  77. }
  78. static auto BuildClassDecl(Context& context, Parse::AnyClassDeclId node_id,
  79. bool is_definition)
  80. -> std::tuple<SemIR::ClassId, SemIR::InstId> {
  81. if (context.node_stack().PopIf<Parse::NodeKind::TuplePattern>()) {
  82. context.TODO(node_id, "generic class");
  83. }
  84. if (context.node_stack().PopIf<Parse::NodeKind::ImplicitParamList>()) {
  85. context.TODO(node_id, "generic class");
  86. }
  87. auto name_context = context.decl_name_stack().FinishName();
  88. context.node_stack()
  89. .PopAndDiscardSoloNodeId<Parse::NodeKind::ClassIntroducer>();
  90. // Process modifiers.
  91. CheckAccessModifiersOnDecl(context, Lex::TokenKind::Class,
  92. name_context.target_scope_id);
  93. LimitModifiersOnDecl(context,
  94. KeywordModifierSet::Class | KeywordModifierSet::Access |
  95. KeywordModifierSet::Extern,
  96. Lex::TokenKind::Class);
  97. RestrictExternModifierOnDecl(context, Lex::TokenKind::Class,
  98. name_context.target_scope_id, is_definition);
  99. auto modifiers = context.decl_state_stack().innermost().modifier_set;
  100. if (!!(modifiers & KeywordModifierSet::Access)) {
  101. context.TODO(context.decl_state_stack().innermost().modifier_node_id(
  102. ModifierOrder::Access),
  103. "access modifier");
  104. }
  105. bool is_extern = !!(modifiers & KeywordModifierSet::Extern);
  106. auto inheritance_kind =
  107. !!(modifiers & KeywordModifierSet::Abstract) ? SemIR::Class::Abstract
  108. : !!(modifiers & KeywordModifierSet::Base) ? SemIR::Class::Base
  109. : SemIR::Class::Final;
  110. context.decl_state_stack().Pop(DeclState::Class);
  111. auto decl_block_id = context.inst_block_stack().Pop();
  112. // Add the class declaration.
  113. auto class_decl = SemIR::ClassDecl{SemIR::TypeId::TypeType,
  114. SemIR::ClassId::Invalid, decl_block_id};
  115. auto class_decl_id = context.AddPlaceholderInst({node_id, class_decl});
  116. SemIR::Class class_info = {
  117. .name_id = name_context.name_id_for_new_inst(),
  118. .enclosing_scope_id = name_context.enclosing_scope_id_for_new_inst(),
  119. // `.self_type_id` depends on the ClassType, so is set below.
  120. .self_type_id = SemIR::TypeId::Invalid,
  121. .decl_id = class_decl_id,
  122. .inheritance_kind = inheritance_kind};
  123. auto extern_decl_id = SemIR::InstId::Invalid;
  124. if (is_extern) {
  125. extern_decl_id = context.AddPlaceholderInst(
  126. {node_id, SemIR::ExternDecl{SemIR::TypeId::TypeType, class_decl_id}});
  127. }
  128. MergeOrAddName(context, node_id, name_context,
  129. extern_decl_id.is_valid() ? extern_decl_id : class_decl_id,
  130. class_decl, class_info, is_definition, is_extern);
  131. // Create a new class if this isn't a valid redeclaration.
  132. bool is_new_class = !class_decl.class_id.is_valid();
  133. if (is_new_class) {
  134. // TODO: If this is an invalid redeclaration of a non-class entity or there
  135. // was an error in the qualifier, we will have lost track of the class name
  136. // here. We should keep track of it even if the name is invalid.
  137. class_decl.class_id = context.classes().Add(class_info);
  138. }
  139. // Write the class ID into the ClassDecl.
  140. context.ReplaceInstBeforeConstantUse(class_decl_id, class_decl);
  141. if (is_new_class) {
  142. // Build the `Self` type using the resulting type constant.
  143. auto& class_info = context.classes().Get(class_decl.class_id);
  144. class_info.self_type_id = context.GetTypeIdForTypeInst(class_decl_id);
  145. }
  146. if (is_extern) {
  147. context.ReplaceInstBeforeConstantUse(
  148. extern_decl_id,
  149. SemIR::ExternDecl{SemIR::TypeId::TypeType, class_decl_id});
  150. }
  151. return {class_decl.class_id, class_decl_id};
  152. }
  153. auto HandleClassDecl(Context& context, Parse::ClassDeclId node_id) -> bool {
  154. BuildClassDecl(context, node_id, /*is_definition=*/false);
  155. context.decl_name_stack().PopScope();
  156. return true;
  157. }
  158. auto HandleClassDefinitionStart(Context& context,
  159. Parse::ClassDefinitionStartId node_id) -> bool {
  160. auto [class_id, class_decl_id] =
  161. BuildClassDecl(context, node_id, /*is_definition=*/true);
  162. auto& class_info = context.classes().Get(class_id);
  163. // Track that this declaration is the definition.
  164. if (!class_info.is_defined()) {
  165. class_info.definition_id = class_decl_id;
  166. class_info.scope_id = context.name_scopes().Add(
  167. class_decl_id, SemIR::NameId::Invalid, class_info.enclosing_scope_id);
  168. }
  169. // Enter the class scope.
  170. context.scope_stack().Push(class_decl_id, class_info.scope_id);
  171. // Introduce `Self`.
  172. context.name_scopes()
  173. .Get(class_info.scope_id)
  174. .names.insert({SemIR::NameId::SelfType,
  175. context.types().GetInstId(class_info.self_type_id)});
  176. context.inst_block_stack().Push();
  177. context.node_stack().Push(node_id, class_id);
  178. context.args_type_info_stack().Push();
  179. // TODO: Handle the case where there's control flow in the class body. For
  180. // example:
  181. //
  182. // class C {
  183. // var v: if true then i32 else f64;
  184. // }
  185. //
  186. // We may need to track a list of instruction blocks here, as we do for a
  187. // function.
  188. class_info.body_block_id = context.inst_block_stack().PeekOrAdd();
  189. return true;
  190. }
  191. // Diagnoses a class-specific declaration appearing outside a class.
  192. static auto DiagnoseClassSpecificDeclOutsideClass(Context& context,
  193. SemIRLoc loc,
  194. Lex::TokenKind tok) -> void {
  195. CARBON_DIAGNOSTIC(ClassSpecificDeclOutsideClass, Error,
  196. "`{0}` declaration can only be used in a class.",
  197. Lex::TokenKind);
  198. context.emitter().Emit(loc, ClassSpecificDeclOutsideClass, tok);
  199. }
  200. // Returns the declaration of the immediately-enclosing class scope, or
  201. // diagonses if there isn't one.
  202. static auto GetEnclosingClassOrDiagnose(Context& context, SemIRLoc loc,
  203. Lex::TokenKind tok)
  204. -> std::optional<SemIR::ClassDecl> {
  205. auto class_scope = context.GetCurrentScopeAs<SemIR::ClassDecl>();
  206. if (!class_scope) {
  207. DiagnoseClassSpecificDeclOutsideClass(context, loc, tok);
  208. }
  209. return class_scope;
  210. }
  211. // Diagnoses a class-specific declaration that is repeated within a class, but
  212. // is not permitted to be repeated.
  213. static auto DiagnoseClassSpecificDeclRepeated(Context& context,
  214. SemIRLoc new_loc,
  215. SemIRLoc prev_loc,
  216. Lex::TokenKind tok) -> void {
  217. CARBON_DIAGNOSTIC(ClassSpecificDeclRepeated, Error,
  218. "Multiple `{0}` declarations in class.{1}", Lex::TokenKind,
  219. std::string);
  220. const llvm::StringRef extra = tok == Lex::TokenKind::Base
  221. ? " Multiple inheritance is not permitted."
  222. : "";
  223. CARBON_DIAGNOSTIC(ClassSpecificDeclPrevious, Note,
  224. "Previous `{0}` declaration is here.", Lex::TokenKind);
  225. context.emitter()
  226. .Build(new_loc, ClassSpecificDeclRepeated, tok, extra.str())
  227. .Note(prev_loc, ClassSpecificDeclPrevious, tok)
  228. .Emit();
  229. }
  230. auto HandleAdaptIntroducer(Context& context,
  231. Parse::AdaptIntroducerId /*node_id*/) -> bool {
  232. context.decl_state_stack().Push(DeclState::Adapt);
  233. return true;
  234. }
  235. auto HandleAdaptDecl(Context& context, Parse::AdaptDeclId node_id) -> bool {
  236. auto [adapted_type_node, adapted_type_expr_id] =
  237. context.node_stack().PopExprWithNodeId();
  238. // Process modifiers. `extend` is permitted, no others are allowed.
  239. LimitModifiersOnDecl(context, KeywordModifierSet::Extend,
  240. Lex::TokenKind::Adapt);
  241. auto modifiers = context.decl_state_stack().innermost().modifier_set;
  242. context.decl_state_stack().Pop(DeclState::Adapt);
  243. auto enclosing_class_decl =
  244. GetEnclosingClassOrDiagnose(context, node_id, Lex::TokenKind::Adapt);
  245. if (!enclosing_class_decl) {
  246. return true;
  247. }
  248. auto& class_info = context.classes().Get(enclosing_class_decl->class_id);
  249. if (class_info.adapt_id.is_valid()) {
  250. DiagnoseClassSpecificDeclRepeated(context, node_id, class_info.adapt_id,
  251. Lex::TokenKind::Adapt);
  252. return true;
  253. }
  254. auto adapted_type_id = ExprAsType(context, node_id, adapted_type_expr_id);
  255. adapted_type_id = context.AsCompleteType(adapted_type_id, [&] {
  256. CARBON_DIAGNOSTIC(IncompleteTypeInAdaptDecl, Error,
  257. "Adapted type `{0}` is an incomplete type.",
  258. SemIR::TypeId);
  259. return context.emitter().Build(node_id, IncompleteTypeInAdaptDecl,
  260. adapted_type_id);
  261. });
  262. // Build a SemIR representation for the declaration.
  263. class_info.adapt_id =
  264. context.AddInst({node_id, SemIR::AdaptDecl{adapted_type_id}});
  265. // Extend the class scope with the adapted type's scope if requested.
  266. if (!!(modifiers & KeywordModifierSet::Extend)) {
  267. auto extended_scope_id = SemIR::NameScopeId::Invalid;
  268. if (adapted_type_id == SemIR::TypeId::Error) {
  269. // Recover by not extending any scope. We instead set has_error to true
  270. // below.
  271. } else if (auto* adapted_class_info =
  272. TryGetAsClass(context, adapted_type_id)) {
  273. extended_scope_id = adapted_class_info->scope_id;
  274. CARBON_CHECK(adapted_class_info->scope_id.is_valid())
  275. << "Complete class should have a scope";
  276. } else {
  277. // TODO: Accept any type that has a scope.
  278. context.TODO(node_id, "extending non-class type");
  279. }
  280. auto& class_scope = context.name_scopes().Get(class_info.scope_id);
  281. if (extended_scope_id.is_valid()) {
  282. class_scope.extended_scopes.push_back(extended_scope_id);
  283. } else {
  284. class_scope.has_error = true;
  285. }
  286. }
  287. return true;
  288. }
  289. auto HandleBaseIntroducer(Context& context, Parse::BaseIntroducerId /*node_id*/)
  290. -> bool {
  291. context.decl_state_stack().Push(DeclState::Base);
  292. return true;
  293. }
  294. auto HandleBaseColon(Context& /*context*/, Parse::BaseColonId /*node_id*/)
  295. -> bool {
  296. return true;
  297. }
  298. namespace {
  299. // Information gathered about a base type specified in a `base` declaration.
  300. struct BaseInfo {
  301. // A `BaseInfo` representing an erroneous base.
  302. static const BaseInfo Error;
  303. SemIR::TypeId type_id;
  304. SemIR::NameScopeId scope_id;
  305. };
  306. constexpr BaseInfo BaseInfo::Error = {.type_id = SemIR::TypeId::Error,
  307. .scope_id = SemIR::NameScopeId::Invalid};
  308. } // namespace
  309. // Diagnoses an attempt to derive from a final type.
  310. static auto DiagnoseBaseIsFinal(Context& context, Parse::NodeId node_id,
  311. SemIR::TypeId base_type_id) -> void {
  312. CARBON_DIAGNOSTIC(BaseIsFinal, Error,
  313. "Deriving from final type `{0}`. Base type must be an "
  314. "`abstract` or `base` class.",
  315. SemIR::TypeId);
  316. context.emitter().Emit(node_id, BaseIsFinal, base_type_id);
  317. }
  318. // Checks that the specified base type is valid.
  319. static auto CheckBaseType(Context& context, Parse::NodeId node_id,
  320. SemIR::InstId base_expr_id) -> BaseInfo {
  321. auto base_type_id = ExprAsType(context, node_id, base_expr_id);
  322. base_type_id = context.AsCompleteType(base_type_id, [&] {
  323. CARBON_DIAGNOSTIC(IncompleteTypeInBaseDecl, Error,
  324. "Base `{0}` is an incomplete type.", SemIR::TypeId);
  325. return context.emitter().Build(node_id, IncompleteTypeInBaseDecl,
  326. base_type_id);
  327. });
  328. if (base_type_id == SemIR::TypeId::Error) {
  329. return BaseInfo::Error;
  330. }
  331. auto* base_class_info = TryGetAsClass(context, base_type_id);
  332. // The base must not be a final class.
  333. if (!base_class_info) {
  334. // For now, we treat all types that aren't introduced by a `class`
  335. // declaration as being final classes.
  336. // TODO: Once we have a better idea of which types are considered to be
  337. // classes, produce a better diagnostic for deriving from a non-class type.
  338. DiagnoseBaseIsFinal(context, node_id, base_type_id);
  339. return BaseInfo::Error;
  340. }
  341. if (base_class_info->inheritance_kind == SemIR::Class::Final) {
  342. DiagnoseBaseIsFinal(context, node_id, base_type_id);
  343. }
  344. CARBON_CHECK(base_class_info->scope_id.is_valid())
  345. << "Complete class should have a scope";
  346. return {.type_id = base_type_id, .scope_id = base_class_info->scope_id};
  347. }
  348. auto HandleBaseDecl(Context& context, Parse::BaseDeclId node_id) -> bool {
  349. auto [base_type_node_id, base_type_expr_id] =
  350. context.node_stack().PopExprWithNodeId();
  351. // Process modifiers. `extend` is required, no others are allowed.
  352. LimitModifiersOnDecl(context, KeywordModifierSet::Extend,
  353. Lex::TokenKind::Base);
  354. auto modifiers = context.decl_state_stack().innermost().modifier_set;
  355. if (!(modifiers & KeywordModifierSet::Extend)) {
  356. CARBON_DIAGNOSTIC(BaseMissingExtend, Error,
  357. "Missing `extend` before `base` declaration in class.");
  358. context.emitter().Emit(node_id, BaseMissingExtend);
  359. }
  360. context.decl_state_stack().Pop(DeclState::Base);
  361. auto enclosing_class_decl =
  362. GetEnclosingClassOrDiagnose(context, node_id, Lex::TokenKind::Base);
  363. if (!enclosing_class_decl) {
  364. return true;
  365. }
  366. auto& class_info = context.classes().Get(enclosing_class_decl->class_id);
  367. if (class_info.base_id.is_valid()) {
  368. DiagnoseClassSpecificDeclRepeated(context, node_id, class_info.base_id,
  369. Lex::TokenKind::Base);
  370. return true;
  371. }
  372. auto base_info = CheckBaseType(context, base_type_node_id, base_type_expr_id);
  373. // The `base` value in the class scope has an unbound element type. Instance
  374. // binding will be performed when it's found by name lookup into an instance.
  375. auto field_type_id =
  376. context.GetUnboundElementType(class_info.self_type_id, base_info.type_id);
  377. class_info.base_id = context.AddInst(
  378. {node_id,
  379. SemIR::BaseDecl{field_type_id, base_info.type_id,
  380. SemIR::ElementIndex(context.args_type_info_stack()
  381. .PeekCurrentBlockContents()
  382. .size())}});
  383. // Add a corresponding field to the object representation of the class.
  384. // TODO: Consider whether we want to use `partial T` here.
  385. // TODO: Should we diagnose if there are already any fields?
  386. context.args_type_info_stack().AddInstId(context.AddInstInNoBlock(
  387. {node_id,
  388. SemIR::StructTypeField{SemIR::NameId::Base, base_info.type_id}}));
  389. // Bind the name `base` in the class to the base field.
  390. context.decl_name_stack().AddNameToLookup(
  391. context.decl_name_stack().MakeUnqualifiedName(node_id,
  392. SemIR::NameId::Base),
  393. class_info.base_id);
  394. // Extend the class scope with the base class.
  395. if (!!(modifiers & KeywordModifierSet::Extend)) {
  396. auto& class_scope = context.name_scopes().Get(class_info.scope_id);
  397. if (base_info.scope_id.is_valid()) {
  398. class_scope.extended_scopes.push_back(base_info.scope_id);
  399. } else {
  400. class_scope.has_error = true;
  401. }
  402. }
  403. return true;
  404. }
  405. auto HandleClassDefinition(Context& context,
  406. Parse::ClassDefinitionId /*node_id*/) -> bool {
  407. auto fields_id = context.args_type_info_stack().Pop();
  408. auto class_id =
  409. context.node_stack().Pop<Parse::NodeKind::ClassDefinitionStart>();
  410. context.inst_block_stack().Pop();
  411. // The class type is now fully defined. Compute its object representation.
  412. auto& class_info = context.classes().Get(class_id);
  413. if (class_info.adapt_id.is_valid()) {
  414. class_info.object_repr_id = SemIR::TypeId::Error;
  415. if (class_info.base_id.is_valid()) {
  416. CARBON_DIAGNOSTIC(AdaptWithBase, Error,
  417. "Adapter cannot have a base class.");
  418. CARBON_DIAGNOSTIC(AdaptBaseHere, Note, "`base` declaration is here.");
  419. context.emitter()
  420. .Build(class_info.adapt_id, AdaptWithBase)
  421. .Note(class_info.base_id, AdaptBaseHere)
  422. .Emit();
  423. } else if (!context.inst_blocks().Get(fields_id).empty()) {
  424. auto first_field_id = context.inst_blocks().Get(fields_id).front();
  425. CARBON_DIAGNOSTIC(AdaptWithFields, Error, "Adapter cannot have fields.");
  426. CARBON_DIAGNOSTIC(AdaptFieldHere, Note,
  427. "First field declaration is here.");
  428. context.emitter()
  429. .Build(class_info.adapt_id, AdaptWithFields)
  430. .Note(first_field_id, AdaptFieldHere)
  431. .Emit();
  432. } else {
  433. // The object representation of the adapter is the object representation
  434. // of the adapted type.
  435. auto adapted_type_id = context.insts()
  436. .GetAs<SemIR::AdaptDecl>(class_info.adapt_id)
  437. .adapted_type_id;
  438. // If we adapt an adapter, directly track the non-adapter type we're
  439. // adapting so that we have constant-time access to it.
  440. if (auto adapted_class =
  441. context.types().TryGetAs<SemIR::ClassType>(adapted_type_id)) {
  442. auto& adapted_class_info =
  443. context.classes().Get(adapted_class->class_id);
  444. if (adapted_class_info.adapt_id.is_valid()) {
  445. adapted_type_id = adapted_class_info.object_repr_id;
  446. }
  447. }
  448. class_info.object_repr_id = adapted_type_id;
  449. }
  450. } else {
  451. class_info.object_repr_id = context.GetStructType(fields_id);
  452. }
  453. // The decl_name_stack and scopes are popped by `ProcessNodeIds`.
  454. return true;
  455. }
  456. } // namespace Carbon::Check