handle_class.cpp 23 KB

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