handle_class.cpp 23 KB

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