handle_class.cpp 24 KB

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