handle_class.cpp 23 KB

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