handle_class.cpp 23 KB

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