handle_class.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  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 <optional>
  5. #include <tuple>
  6. #include "toolchain/base/kind_switch.h"
  7. #include "toolchain/check/class.h"
  8. #include "toolchain/check/context.h"
  9. #include "toolchain/check/convert.h"
  10. #include "toolchain/check/decl_name_stack.h"
  11. #include "toolchain/check/diagnostic_helpers.h"
  12. #include "toolchain/check/eval.h"
  13. #include "toolchain/check/generic.h"
  14. #include "toolchain/check/handle.h"
  15. #include "toolchain/check/impl.h"
  16. #include "toolchain/check/import.h"
  17. #include "toolchain/check/import_ref.h"
  18. #include "toolchain/check/inst.h"
  19. #include "toolchain/check/merge.h"
  20. #include "toolchain/check/modifiers.h"
  21. #include "toolchain/check/name_component.h"
  22. #include "toolchain/check/name_lookup.h"
  23. #include "toolchain/check/type.h"
  24. #include "toolchain/check/type_completion.h"
  25. #include "toolchain/diagnostics/emitter.h"
  26. #include "toolchain/parse/node_ids.h"
  27. #include "toolchain/sem_ir/function.h"
  28. #include "toolchain/sem_ir/ids.h"
  29. #include "toolchain/sem_ir/inst.h"
  30. #include "toolchain/sem_ir/typed_insts.h"
  31. namespace Carbon::Check {
  32. auto HandleParseNode(Context& context, Parse::ClassIntroducerId node_id)
  33. -> bool {
  34. // This class is potentially generic.
  35. StartGenericDecl(context);
  36. // Create an instruction block to hold the instructions created as part of the
  37. // class signature, such as generic parameters.
  38. context.inst_block_stack().Push();
  39. // Push the bracketing node.
  40. context.node_stack().Push(node_id);
  41. // Optional modifiers and the name follow.
  42. context.decl_introducer_state_stack().Push<Lex::TokenKind::Class>();
  43. context.decl_name_stack().PushScopeAndStartName();
  44. return true;
  45. }
  46. // Tries to merge new_class into prev_class_id. Since new_class won't have a
  47. // definition even if one is upcoming, set is_definition to indicate the planned
  48. // result.
  49. //
  50. // If merging is successful, returns true and may update the previous class.
  51. // Otherwise, returns false. Prints a diagnostic when appropriate.
  52. static auto MergeClassRedecl(Context& context, Parse::AnyClassDeclId node_id,
  53. SemIR::Class& new_class, bool new_is_definition,
  54. SemIR::ClassId prev_class_id,
  55. SemIR::ImportIRId prev_import_ir_id) -> bool {
  56. auto& prev_class = context.classes().Get(prev_class_id);
  57. SemIR::LocId prev_loc_id(prev_class.latest_decl_id());
  58. // Check the generic parameters match, if they were specified.
  59. if (!CheckRedeclParamsMatch(context, DeclParams(new_class),
  60. DeclParams(prev_class))) {
  61. return false;
  62. }
  63. DiagnoseIfInvalidRedecl(
  64. context, Lex::TokenKind::Class, prev_class.name_id,
  65. RedeclInfo(new_class, node_id, new_is_definition),
  66. RedeclInfo(prev_class, prev_loc_id, prev_class.has_definition_started()),
  67. prev_import_ir_id);
  68. if (new_is_definition && prev_class.has_definition_started()) {
  69. // Don't attempt to merge multiple definitions.
  70. return false;
  71. }
  72. if (new_is_definition) {
  73. prev_class.MergeDefinition(new_class);
  74. }
  75. if (prev_import_ir_id.has_value() ||
  76. (prev_class.is_extern && !new_class.is_extern)) {
  77. prev_class.first_owning_decl_id = new_class.first_owning_decl_id;
  78. ReplacePrevInstForMerge(context, new_class.parent_scope_id,
  79. prev_class.name_id, new_class.first_owning_decl_id);
  80. }
  81. return true;
  82. }
  83. // Adds the name to name lookup. If there's a conflict, tries to merge. May
  84. // update class_decl and class_info when merging.
  85. static auto MergeOrAddName(Context& context, Parse::AnyClassDeclId node_id,
  86. const DeclNameStack::NameContext& name_context,
  87. SemIR::InstId class_decl_id,
  88. SemIR::ClassDecl& class_decl,
  89. SemIR::Class& class_info, bool is_definition,
  90. SemIR::AccessKind access_kind) -> void {
  91. SemIR::ScopeLookupResult lookup_result =
  92. context.decl_name_stack().LookupOrAddName(name_context, class_decl_id,
  93. access_kind);
  94. if (lookup_result.is_poisoned()) {
  95. // This is a declaration of a poisoned name.
  96. DiagnosePoisonedName(context, name_context.name_id_for_new_inst(),
  97. lookup_result.poisoning_loc_id(), name_context.loc_id);
  98. return;
  99. }
  100. if (!lookup_result.is_found()) {
  101. return;
  102. }
  103. SemIR::InstId prev_id = lookup_result.target_inst_id();
  104. auto prev_class_id = SemIR::ClassId::None;
  105. auto prev_import_ir_id = SemIR::ImportIRId::None;
  106. auto prev = context.insts().Get(prev_id);
  107. CARBON_KIND_SWITCH(prev) {
  108. case CARBON_KIND(SemIR::ClassDecl class_decl): {
  109. prev_class_id = class_decl.class_id;
  110. break;
  111. }
  112. case CARBON_KIND(SemIR::ImportRefLoaded import_ref): {
  113. auto import_ir_inst =
  114. context.import_ir_insts().Get(import_ref.import_ir_inst_id);
  115. // Verify the decl so that things like aliases are name conflicts.
  116. const auto* import_ir =
  117. context.import_irs().Get(import_ir_inst.ir_id()).sem_ir;
  118. if (!import_ir->insts().Is<SemIR::ClassDecl>(import_ir_inst.inst_id())) {
  119. break;
  120. }
  121. // Use the constant value to get the ID.
  122. auto decl_value = context.insts().Get(
  123. context.constant_values().GetConstantInstId(prev_id));
  124. if (auto class_type = decl_value.TryAs<SemIR::ClassType>()) {
  125. prev_class_id = class_type->class_id;
  126. prev_import_ir_id = import_ir_inst.ir_id();
  127. } else if (auto generic_class_type =
  128. context.types().TryGetAs<SemIR::GenericClassType>(
  129. decl_value.type_id())) {
  130. prev_class_id = generic_class_type->class_id;
  131. prev_import_ir_id = import_ir_inst.ir_id();
  132. }
  133. break;
  134. }
  135. default:
  136. break;
  137. }
  138. if (!prev_class_id.has_value()) {
  139. // This is a redeclaration of something other than a class.
  140. DiagnoseDuplicateName(context, name_context.name_id, name_context.loc_id,
  141. SemIR::LocId(prev_id));
  142. return;
  143. }
  144. // TODO: Fix `extern` logic. It doesn't work correctly, but doesn't seem worth
  145. // ripping out because existing code may incrementally help.
  146. if (MergeClassRedecl(context, node_id, class_info, is_definition,
  147. prev_class_id, prev_import_ir_id)) {
  148. // When merging, use the existing entity rather than adding a new one.
  149. class_decl.class_id = prev_class_id;
  150. class_decl.type_id = prev.type_id();
  151. // TODO: Validate that the redeclaration doesn't set an access modifier.
  152. }
  153. }
  154. static auto BuildClassDecl(Context& context, Parse::AnyClassDeclId node_id,
  155. bool is_definition)
  156. -> std::tuple<SemIR::ClassId, SemIR::InstId> {
  157. auto name = PopNameComponent(context);
  158. auto name_context = context.decl_name_stack().FinishName(name);
  159. context.node_stack()
  160. .PopAndDiscardSoloNodeId<Parse::NodeKind::ClassIntroducer>();
  161. // Process modifiers.
  162. auto [_, parent_scope_inst] =
  163. context.name_scopes().GetInstIfValid(name_context.parent_scope_id);
  164. auto introducer =
  165. context.decl_introducer_state_stack().Pop<Lex::TokenKind::Class>();
  166. CheckAccessModifiersOnDecl(context, introducer, parent_scope_inst);
  167. auto always_acceptable_modifiers =
  168. KeywordModifierSet::Access | KeywordModifierSet::Extern;
  169. LimitModifiersOnDecl(context, introducer,
  170. always_acceptable_modifiers | KeywordModifierSet::Class);
  171. if (!is_definition) {
  172. LimitModifiersOnNotDefinition(context, introducer,
  173. always_acceptable_modifiers);
  174. }
  175. RestrictExternModifierOnDecl(context, introducer, parent_scope_inst,
  176. is_definition);
  177. bool is_extern = introducer.modifier_set.HasAnyOf(KeywordModifierSet::Extern);
  178. if (introducer.extern_library.has_value()) {
  179. context.TODO(node_id, "extern library");
  180. }
  181. auto inheritance_kind =
  182. introducer.modifier_set.ToEnum<SemIR::Class::InheritanceKind>()
  183. .Case(KeywordModifierSet::Abstract, SemIR::Class::Abstract)
  184. .Case(KeywordModifierSet::Base, SemIR::Class::Base)
  185. .Default(SemIR::Class::Final);
  186. auto decl_block_id = context.inst_block_stack().Pop();
  187. // Add the class declaration.
  188. auto class_decl = SemIR::ClassDecl{.type_id = SemIR::TypeType::TypeId,
  189. .class_id = SemIR::ClassId::None,
  190. .decl_block_id = decl_block_id};
  191. auto class_decl_id = AddPlaceholderInst(context, node_id, class_decl);
  192. // TODO: Store state regarding is_extern.
  193. SemIR::Class class_info = {
  194. name_context.MakeEntityWithParamsBase(name, class_decl_id, is_extern,
  195. SemIR::LibraryNameId::None),
  196. {// `.self_type_id` depends on the ClassType, so is set below.
  197. .self_type_id = SemIR::TypeId::None,
  198. .inheritance_kind = inheritance_kind}};
  199. DiagnoseIfGenericMissingExplicitParameters(context, class_info);
  200. MergeOrAddName(context, node_id, name_context, class_decl_id, class_decl,
  201. class_info, is_definition,
  202. introducer.modifier_set.GetAccessKind());
  203. // Create a new class if this isn't a valid redeclaration.
  204. bool is_new_class = !class_decl.class_id.has_value();
  205. if (is_new_class) {
  206. // TODO: If this is an invalid redeclaration of a non-class entity or there
  207. // was an error in the qualifier, we will have lost track of the class name
  208. // here. We should keep track of it even if the name is invalid.
  209. class_info.generic_id = BuildGenericDecl(context, class_decl_id);
  210. class_decl.class_id = context.classes().Add(class_info);
  211. if (class_info.has_parameters()) {
  212. class_decl.type_id = GetGenericClassType(
  213. context, class_decl.class_id, context.scope_stack().PeekSpecificId());
  214. }
  215. } else {
  216. auto prev_decl_generic_id =
  217. context.classes().Get(class_decl.class_id).generic_id;
  218. FinishGenericRedecl(context, prev_decl_generic_id);
  219. }
  220. // Write the class ID into the ClassDecl.
  221. ReplaceInstBeforeConstantUse(context, class_decl_id, class_decl);
  222. if (is_new_class) {
  223. // TODO: Form this as part of building the definition, not as part of the
  224. // declaration.
  225. SetClassSelfType(context, class_decl.class_id);
  226. }
  227. if (!is_definition && context.sem_ir().is_impl() && !is_extern) {
  228. context.definitions_required_by_decl().push_back(class_decl_id);
  229. }
  230. return {class_decl.class_id, class_decl_id};
  231. }
  232. auto HandleParseNode(Context& context, Parse::ClassDeclId node_id) -> bool {
  233. BuildClassDecl(context, node_id, /*is_definition=*/false);
  234. context.decl_name_stack().PopScope();
  235. return true;
  236. }
  237. auto HandleParseNode(Context& context, Parse::ClassDefinitionStartId node_id)
  238. -> bool {
  239. auto [class_id, class_decl_id] =
  240. BuildClassDecl(context, node_id, /*is_definition=*/true);
  241. auto& class_info = context.classes().Get(class_id);
  242. StartClassDefinition(context, class_info, class_decl_id);
  243. // Enter the class scope.
  244. context.scope_stack().PushForEntity(
  245. class_decl_id, class_info.scope_id,
  246. context.generics().GetSelfSpecific(class_info.generic_id));
  247. StartGenericDefinition(context, class_info.generic_id);
  248. context.inst_block_stack().Push();
  249. context.node_stack().Push(node_id, class_id);
  250. context.field_decls_stack().PushArray();
  251. context.vtable_stack().Push();
  252. // TODO: Handle the case where there's control flow in the class body. For
  253. // example:
  254. //
  255. // class C {
  256. // var v: if true then i32 else f64;
  257. // }
  258. //
  259. // We may need to track a list of instruction blocks here, as we do for a
  260. // function.
  261. class_info.body_block_id = context.inst_block_stack().PeekOrAdd();
  262. return true;
  263. }
  264. // Diagnoses a class-specific declaration appearing outside a class.
  265. static auto DiagnoseClassSpecificDeclOutsideClass(Context& context,
  266. SemIR::LocId loc_id,
  267. Lex::TokenKind tok) -> void {
  268. CARBON_DIAGNOSTIC(ClassSpecificDeclOutsideClass, Error,
  269. "`{0}` declaration outside class", Lex::TokenKind);
  270. context.emitter().Emit(loc_id, ClassSpecificDeclOutsideClass, tok);
  271. }
  272. // Returns the current scope's class declaration, or diagnoses if it isn't a
  273. // class.
  274. static auto GetCurrentScopeAsClassOrDiagnose(Context& context,
  275. SemIR::LocId loc_id,
  276. Lex::TokenKind tok)
  277. -> std::optional<SemIR::ClassDecl> {
  278. auto class_scope =
  279. context.scope_stack().TryGetCurrentScopeAs<SemIR::ClassDecl>();
  280. if (!class_scope) {
  281. DiagnoseClassSpecificDeclOutsideClass(context, loc_id, tok);
  282. }
  283. return class_scope;
  284. }
  285. // Diagnoses a class-specific declaration that is repeated within a class, but
  286. // is not permitted to be repeated.
  287. static auto DiagnoseClassSpecificDeclRepeated(Context& context,
  288. SemIR::LocId new_loc_id,
  289. SemIR::LocId prev_loc_id,
  290. Lex::TokenKind tok) -> void {
  291. CARBON_DIAGNOSTIC(AdaptDeclRepeated, Error,
  292. "multiple `adapt` declarations in class");
  293. CARBON_DIAGNOSTIC(BaseDeclRepeated, Error,
  294. "multiple `base` declarations in class; multiple "
  295. "inheritance is not permitted");
  296. CARBON_DIAGNOSTIC(ClassSpecificDeclPrevious, Note,
  297. "previous `{0}` declaration is here", Lex::TokenKind);
  298. CARBON_CHECK(tok == Lex::TokenKind::Adapt || tok == Lex::TokenKind::Base);
  299. context.emitter()
  300. .Build(new_loc_id, tok == Lex::TokenKind::Adapt ? AdaptDeclRepeated
  301. : BaseDeclRepeated)
  302. .Note(prev_loc_id, ClassSpecificDeclPrevious, tok)
  303. .Emit();
  304. }
  305. auto HandleParseNode(Context& context, Parse::AdaptIntroducerId /*node_id*/)
  306. -> bool {
  307. context.decl_introducer_state_stack().Push<Lex::TokenKind::Adapt>();
  308. return true;
  309. }
  310. auto HandleParseNode(Context& context, Parse::AdaptDeclId node_id) -> bool {
  311. auto [adapted_type_node, adapted_type_expr_id] =
  312. context.node_stack().PopExprWithNodeId();
  313. // Process modifiers. `extend` is permitted, no others are allowed.
  314. auto introducer =
  315. context.decl_introducer_state_stack().Pop<Lex::TokenKind::Adapt>();
  316. LimitModifiersOnDecl(context, introducer, KeywordModifierSet::Extend);
  317. auto parent_class_decl =
  318. GetCurrentScopeAsClassOrDiagnose(context, node_id, Lex::TokenKind::Adapt);
  319. if (!parent_class_decl) {
  320. return true;
  321. }
  322. auto& class_info = context.classes().Get(parent_class_decl->class_id);
  323. if (class_info.adapt_id.has_value()) {
  324. DiagnoseClassSpecificDeclRepeated(context, node_id,
  325. SemIR::LocId(class_info.adapt_id),
  326. Lex::TokenKind::Adapt);
  327. return true;
  328. }
  329. auto [adapted_type_inst_id, adapted_type_id] =
  330. ExprAsType(context, node_id, adapted_type_expr_id);
  331. if (!RequireConcreteType(
  332. context, adapted_type_id, node_id,
  333. [&](auto& builder) {
  334. CARBON_DIAGNOSTIC(IncompleteTypeInAdaptDecl, Context,
  335. "adapted type {0} is an incomplete type",
  336. InstIdAsType);
  337. builder.Context(node_id, IncompleteTypeInAdaptDecl,
  338. adapted_type_inst_id);
  339. },
  340. [&](auto& builder) {
  341. CARBON_DIAGNOSTIC(AbstractTypeInAdaptDecl, Context,
  342. "adapted type {0} is an abstract type",
  343. InstIdAsType);
  344. builder.Context(node_id, AbstractTypeInAdaptDecl,
  345. adapted_type_inst_id);
  346. })) {
  347. adapted_type_id = SemIR::ErrorInst::TypeId;
  348. }
  349. if (adapted_type_id == SemIR::ErrorInst::TypeId) {
  350. adapted_type_inst_id = SemIR::ErrorInst::TypeInstId;
  351. }
  352. // Build a SemIR representation for the declaration.
  353. class_info.adapt_id = AddInst<SemIR::AdaptDecl>(
  354. context, node_id, {.adapted_type_inst_id = adapted_type_inst_id});
  355. // Extend the class scope with the adapted type's scope if requested.
  356. if (introducer.modifier_set.HasAnyOf(KeywordModifierSet::Extend)) {
  357. auto& class_scope = context.name_scopes().Get(class_info.scope_id);
  358. class_scope.AddExtendedScope({adapted_type_inst_id});
  359. }
  360. return true;
  361. }
  362. auto HandleParseNode(Context& context, Parse::BaseIntroducerId /*node_id*/)
  363. -> bool {
  364. context.decl_introducer_state_stack().Push<Lex::TokenKind::Base>();
  365. return true;
  366. }
  367. auto HandleParseNode(Context& /*context*/, Parse::BaseColonId /*node_id*/)
  368. -> bool {
  369. return true;
  370. }
  371. namespace {
  372. // Information gathered about a base type specified in a `base` declaration.
  373. struct BaseInfo {
  374. // A `BaseInfo` representing an erroneous base.
  375. static const BaseInfo Error;
  376. SemIR::TypeId type_id;
  377. SemIR::NameScopeId scope_id;
  378. SemIR::TypeInstId inst_id;
  379. };
  380. constexpr BaseInfo BaseInfo::Error = {.type_id = SemIR::ErrorInst::TypeId,
  381. .scope_id = SemIR::NameScopeId::None,
  382. .inst_id = SemIR::ErrorInst::TypeInstId};
  383. } // namespace
  384. // Diagnoses an attempt to derive from a final type.
  385. static auto DiagnoseBaseIsFinal(Context& context, Parse::NodeId node_id,
  386. SemIR::TypeInstId base_type_inst_id) -> void {
  387. CARBON_DIAGNOSTIC(BaseIsFinal, Error,
  388. "deriving from final type {0}; base type must be an "
  389. "`abstract` or `base` class",
  390. InstIdAsType);
  391. context.emitter().Emit(node_id, BaseIsFinal, base_type_inst_id);
  392. }
  393. // Checks that the specified base type is valid.
  394. static auto CheckBaseType(Context& context, Parse::NodeId node_id,
  395. SemIR::InstId base_expr_id) -> BaseInfo {
  396. auto [base_type_inst_id, base_type_id] =
  397. ExprAsType(context, node_id, base_expr_id);
  398. if (base_type_id == SemIR::ErrorInst::TypeId) {
  399. return BaseInfo::Error;
  400. }
  401. if (!RequireCompleteType(context, base_type_id, node_id, [&](auto& builder) {
  402. CARBON_DIAGNOSTIC(IncompleteTypeInBaseDecl, Context,
  403. "base {0} is an incomplete type", InstIdAsType);
  404. builder.Context(node_id, IncompleteTypeInBaseDecl, base_type_inst_id);
  405. })) {
  406. return BaseInfo::Error;
  407. }
  408. auto class_type = context.types().TryGetAs<SemIR::ClassType>(base_type_id);
  409. // The base must not be a final class.
  410. if (!class_type) {
  411. // For now, we treat all types that aren't introduced by a `class`
  412. // declaration as being final classes.
  413. // TODO: Once we have a better idea of which types are considered to be
  414. // classes, produce a better diagnostic for deriving from a non-class type.
  415. DiagnoseBaseIsFinal(context, node_id, base_type_inst_id);
  416. return BaseInfo::Error;
  417. }
  418. const auto& base_class_info = context.classes().Get(class_type->class_id);
  419. if (base_class_info.inheritance_kind == SemIR::Class::Final) {
  420. DiagnoseBaseIsFinal(context, node_id, base_type_inst_id);
  421. }
  422. CARBON_CHECK(base_class_info.scope_id.has_value(),
  423. "Complete class should have a scope");
  424. return {.type_id = base_type_id,
  425. .scope_id = base_class_info.scope_id,
  426. .inst_id = base_type_inst_id};
  427. }
  428. auto HandleParseNode(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. auto introducer =
  433. context.decl_introducer_state_stack().Pop<Lex::TokenKind::Base>();
  434. LimitModifiersOnDecl(context, introducer, KeywordModifierSet::Extend);
  435. if (!introducer.modifier_set.HasAnyOf(KeywordModifierSet::Extend)) {
  436. CARBON_DIAGNOSTIC(BaseMissingExtend, Error,
  437. "missing `extend` before `base` declaration");
  438. context.emitter().Emit(node_id, BaseMissingExtend);
  439. }
  440. auto parent_class_decl =
  441. GetCurrentScopeAsClassOrDiagnose(context, node_id, Lex::TokenKind::Base);
  442. if (!parent_class_decl) {
  443. return true;
  444. }
  445. auto& class_info = context.classes().Get(parent_class_decl->class_id);
  446. if (class_info.base_id.has_value()) {
  447. DiagnoseClassSpecificDeclRepeated(context, node_id,
  448. SemIR::LocId(class_info.base_id),
  449. Lex::TokenKind::Base);
  450. return true;
  451. }
  452. if (!context.field_decls_stack().PeekArray().empty()) {
  453. // TODO: Add note that includes the first field location as an example.
  454. CARBON_DIAGNOSTIC(
  455. BaseDeclAfterFieldDecl, Error,
  456. "`base` declaration must appear before field declarations");
  457. context.emitter().Emit(node_id, BaseDeclAfterFieldDecl);
  458. return true;
  459. }
  460. auto base_info = CheckBaseType(context, base_type_node_id, base_type_expr_id);
  461. // TODO: Should we diagnose if there are already any fields?
  462. // The `base` value in the class scope has an unbound element type. Instance
  463. // binding will be performed when it's found by name lookup into an instance.
  464. auto field_type_id = GetUnboundElementType(
  465. context, context.types().GetTypeInstId(class_info.self_type_id),
  466. base_info.inst_id);
  467. class_info.base_id =
  468. AddInst<SemIR::BaseDecl>(context, node_id,
  469. {.type_id = field_type_id,
  470. .base_type_inst_id = base_info.inst_id,
  471. .index = SemIR::ElementIndex::None});
  472. if (base_info.type_id != SemIR::ErrorInst::TypeId) {
  473. auto base_class_info = context.classes().Get(
  474. context.types().GetAs<SemIR::ClassType>(base_info.type_id).class_id);
  475. class_info.is_dynamic |= base_class_info.is_dynamic;
  476. }
  477. // Bind the name `base` in the class to the base field.
  478. context.decl_name_stack().AddNameOrDiagnose(
  479. context.decl_name_stack().MakeUnqualifiedName(node_id,
  480. SemIR::NameId::Base),
  481. class_info.base_id, introducer.modifier_set.GetAccessKind());
  482. // Extend the class scope with the base class.
  483. if (introducer.modifier_set.HasAnyOf(KeywordModifierSet::Extend)) {
  484. auto& class_scope = context.name_scopes().Get(class_info.scope_id);
  485. if (base_info.scope_id.has_value()) {
  486. class_scope.AddExtendedScope({base_info.inst_id});
  487. } else {
  488. class_scope.set_has_error();
  489. }
  490. }
  491. return true;
  492. }
  493. auto HandleParseNode(Context& context, Parse::ClassDefinitionId node_id)
  494. -> bool {
  495. auto class_id =
  496. context.node_stack().Pop<Parse::NodeKind::ClassDefinitionStart>();
  497. // The class type is now fully defined. Compute its object representation.
  498. ComputeClassObjectRepr(context, node_id, class_id,
  499. context.field_decls_stack().PeekArray(),
  500. context.vtable_stack().PeekCurrentBlockContents(),
  501. context.inst_block_stack().PeekCurrentBlockContents());
  502. context.inst_block_stack().Pop();
  503. context.field_decls_stack().PopArray();
  504. context.vtable_stack().Pop();
  505. FinishGenericDefinition(context, context.classes().Get(class_id).generic_id);
  506. // The decl_name_stack and scopes are popped by `ProcessNodeIds`.
  507. return true;
  508. }
  509. } // namespace Carbon::Check