handle_class.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  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/context.h"
  6. #include "toolchain/check/convert.h"
  7. #include "toolchain/check/decl_name_stack.h"
  8. #include "toolchain/check/eval.h"
  9. #include "toolchain/check/merge.h"
  10. #include "toolchain/check/modifiers.h"
  11. #include "toolchain/check/name_component.h"
  12. #include "toolchain/sem_ir/ids.h"
  13. #include "toolchain/sem_ir/inst.h"
  14. #include "toolchain/sem_ir/typed_insts.h"
  15. namespace Carbon::Check {
  16. // If `type_id` is a class type, get its corresponding `SemIR::Class` object.
  17. // Otherwise returns `nullptr`.
  18. static auto TryGetAsClass(Context& context, SemIR::TypeId type_id)
  19. -> SemIR::Class* {
  20. auto class_type = context.types().TryGetAs<SemIR::ClassType>(type_id);
  21. if (!class_type) {
  22. return nullptr;
  23. }
  24. return &context.classes().Get(class_type->class_id);
  25. }
  26. auto HandleClassIntroducer(Context& context, Parse::ClassIntroducerId node_id)
  27. -> bool {
  28. // Create an instruction block to hold the instructions created as part of the
  29. // class signature, such as generic parameters.
  30. context.inst_block_stack().Push();
  31. // Push the bracketing node.
  32. context.node_stack().Push(node_id);
  33. // Optional modifiers and the name follow.
  34. context.decl_state_stack().Push(DeclState::Class);
  35. context.decl_name_stack().PushScopeAndStartName();
  36. return true;
  37. }
  38. // Tries to merge new_class into prev_class_id. Since new_class won't have a
  39. // definition even if one is upcoming, set is_definition to indicate the planned
  40. // result.
  41. //
  42. // If merging is successful, returns true and may update the previous class.
  43. // Otherwise, returns false. Prints a diagnostic when appropriate.
  44. static auto MergeClassRedecl(Context& context, SemIRLoc new_loc,
  45. SemIR::Class& new_class, bool new_is_import,
  46. bool new_is_definition, bool new_is_extern,
  47. SemIR::ClassId prev_class_id, bool prev_is_extern,
  48. SemIR::ImportIRId prev_import_ir_id) -> bool {
  49. auto& prev_class = context.classes().Get(prev_class_id);
  50. SemIRLoc prev_loc =
  51. prev_class.is_defined() ? prev_class.definition_id : prev_class.decl_id;
  52. // Check the generic parameters match, if they were specified.
  53. if (!CheckRedeclParamsMatch(context, DeclParams(new_class),
  54. DeclParams(prev_class), {})) {
  55. return false;
  56. }
  57. CheckIsAllowedRedecl(context, Lex::TokenKind::Class, prev_class.name_id,
  58. {.loc = new_loc,
  59. .is_definition = new_is_definition,
  60. .is_extern = new_is_extern},
  61. {.loc = prev_loc,
  62. .is_definition = prev_class.is_defined(),
  63. .is_extern = prev_is_extern},
  64. prev_import_ir_id);
  65. if (new_is_definition && prev_class.is_defined()) {
  66. // Don't attempt to merge multiple definitions.
  67. return false;
  68. }
  69. // The introducer kind must match the previous declaration.
  70. // TODO: The rule here is not yet decided. See #3384.
  71. if (prev_class.inheritance_kind != new_class.inheritance_kind) {
  72. CARBON_DIAGNOSTIC(ClassRedeclarationDifferentIntroducer, Error,
  73. "Class redeclared with different inheritance kind.");
  74. CARBON_DIAGNOSTIC(ClassRedeclarationDifferentIntroducerPrevious, Note,
  75. "Previously declared here.");
  76. context.emitter()
  77. .Build(new_loc, ClassRedeclarationDifferentIntroducer)
  78. .Note(prev_loc, ClassRedeclarationDifferentIntroducerPrevious)
  79. .Emit();
  80. }
  81. if (new_is_definition) {
  82. prev_class.implicit_param_refs_id = new_class.implicit_param_refs_id;
  83. prev_class.param_refs_id = new_class.param_refs_id;
  84. prev_class.definition_id = new_class.definition_id;
  85. prev_class.scope_id = new_class.scope_id;
  86. prev_class.body_block_id = new_class.body_block_id;
  87. prev_class.adapt_id = new_class.adapt_id;
  88. prev_class.base_id = new_class.base_id;
  89. prev_class.object_repr_id = new_class.object_repr_id;
  90. }
  91. if ((prev_import_ir_id.is_valid() && !new_is_import) ||
  92. (prev_is_extern && !new_is_extern)) {
  93. prev_class.decl_id = new_class.decl_id;
  94. ReplacePrevInstForMerge(
  95. context, prev_class.enclosing_scope_id, prev_class.name_id,
  96. new_is_import ? new_loc.inst_id : new_class.decl_id);
  97. }
  98. return true;
  99. }
  100. // Adds the name to name lookup. If there's a conflict, tries to merge. May
  101. // update class_decl and class_info when merging.
  102. static auto MergeOrAddName(Context& context, Parse::AnyClassDeclId node_id,
  103. const DeclNameStack::NameContext& name_context,
  104. SemIR::InstId class_decl_id,
  105. SemIR::ClassDecl& class_decl,
  106. SemIR::Class& class_info, bool is_definition,
  107. bool is_extern) -> void {
  108. auto prev_id =
  109. context.decl_name_stack().LookupOrAddName(name_context, class_decl_id);
  110. if (!prev_id.is_valid()) {
  111. return;
  112. }
  113. auto prev_class_id = SemIR::ClassId::Invalid;
  114. auto prev_import_ir_id = SemIR::ImportIRId::Invalid;
  115. CARBON_KIND_SWITCH(context.insts().Get(prev_id)) {
  116. case CARBON_KIND(SemIR::ClassDecl class_decl): {
  117. prev_class_id = class_decl.class_id;
  118. break;
  119. }
  120. case CARBON_KIND(SemIR::ImportRefLoaded import_ref): {
  121. auto import_ir_inst =
  122. context.import_ir_insts().Get(import_ref.import_ir_inst_id);
  123. // Verify the decl so that things like aliases are name conflicts.
  124. const auto* import_ir =
  125. context.import_irs().Get(import_ir_inst.ir_id).sem_ir;
  126. if (!import_ir->insts().Is<SemIR::ClassDecl>(import_ir_inst.inst_id)) {
  127. break;
  128. }
  129. // Use the constant value to get the ID.
  130. auto decl_value =
  131. context.insts().Get(context.constant_values().Get(prev_id).inst_id());
  132. if (auto class_type = decl_value.TryAs<SemIR::ClassType>()) {
  133. prev_class_id = class_type->class_id;
  134. prev_import_ir_id = import_ir_inst.ir_id;
  135. } else if (auto generic_class_type =
  136. context.types().TryGetAs<SemIR::GenericClassType>(
  137. decl_value.type_id())) {
  138. prev_class_id = generic_class_type->class_id;
  139. prev_import_ir_id = import_ir_inst.ir_id;
  140. }
  141. break;
  142. }
  143. default:
  144. break;
  145. }
  146. if (!prev_class_id.is_valid()) {
  147. // This is a redeclaration of something other than a class.
  148. context.DiagnoseDuplicateName(class_decl_id, prev_id);
  149. return;
  150. }
  151. // TODO: Fix prev_is_extern logic.
  152. if (MergeClassRedecl(context, node_id, class_info,
  153. /*new_is_import=*/false, is_definition, is_extern,
  154. prev_class_id, /*prev_is_extern=*/false,
  155. prev_import_ir_id)) {
  156. // When merging, use the existing entity rather than adding a new one.
  157. class_decl.class_id = prev_class_id;
  158. }
  159. }
  160. static auto BuildClassDecl(Context& context, Parse::AnyClassDeclId node_id,
  161. bool is_definition)
  162. -> std::tuple<SemIR::ClassId, SemIR::InstId> {
  163. auto name = PopNameComponent(context);
  164. auto name_context = context.decl_name_stack().FinishName(name);
  165. context.node_stack()
  166. .PopAndDiscardSoloNodeId<Parse::NodeKind::ClassIntroducer>();
  167. // Process modifiers.
  168. auto [_, enclosing_scope_inst] =
  169. context.name_scopes().GetInstIfValid(name_context.enclosing_scope_id);
  170. CheckAccessModifiersOnDecl(context, Lex::TokenKind::Class,
  171. enclosing_scope_inst);
  172. LimitModifiersOnDecl(context,
  173. KeywordModifierSet::Class | KeywordModifierSet::Access |
  174. KeywordModifierSet::Extern,
  175. Lex::TokenKind::Class);
  176. RestrictExternModifierOnDecl(context, Lex::TokenKind::Class,
  177. enclosing_scope_inst, is_definition);
  178. auto modifiers = context.decl_state_stack().innermost().modifier_set;
  179. if (modifiers.HasAnyOf(KeywordModifierSet::Access)) {
  180. context.TODO(context.decl_state_stack().innermost().modifier_node_id(
  181. ModifierOrder::Access),
  182. "access modifier");
  183. }
  184. bool is_extern = modifiers.HasAnyOf(KeywordModifierSet::Extern);
  185. auto inheritance_kind =
  186. modifiers.HasAnyOf(KeywordModifierSet::Abstract) ? SemIR::Class::Abstract
  187. : modifiers.HasAnyOf(KeywordModifierSet::Base) ? SemIR::Class::Base
  188. : SemIR::Class::Final;
  189. context.decl_state_stack().Pop(DeclState::Class);
  190. auto decl_block_id = context.inst_block_stack().Pop();
  191. // Add the class declaration.
  192. auto class_decl = SemIR::ClassDecl{.type_id = SemIR::TypeId::TypeType,
  193. .class_id = SemIR::ClassId::Invalid,
  194. .decl_block_id = decl_block_id};
  195. auto class_decl_id =
  196. context.AddPlaceholderInst(SemIR::LocIdAndInst(node_id, class_decl));
  197. // TODO: Store state regarding is_extern.
  198. SemIR::Class class_info = {
  199. .name_id = name_context.name_id_for_new_inst(),
  200. .enclosing_scope_id = name_context.enclosing_scope_id_for_new_inst(),
  201. .implicit_param_refs_id = name.implicit_params_id,
  202. .param_refs_id = name.params_id,
  203. // `.self_type_id` depends on the ClassType, so is set below.
  204. .self_type_id = SemIR::TypeId::Invalid,
  205. .decl_id = class_decl_id,
  206. .inheritance_kind = inheritance_kind};
  207. MergeOrAddName(context, node_id, name_context, class_decl_id, class_decl,
  208. class_info, is_definition, is_extern);
  209. // Create a new class if this isn't a valid redeclaration.
  210. bool is_new_class = !class_decl.class_id.is_valid();
  211. if (is_new_class) {
  212. // TODO: If this is an invalid redeclaration of a non-class entity or there
  213. // was an error in the qualifier, we will have lost track of the class name
  214. // here. We should keep track of it even if the name is invalid.
  215. class_decl.class_id = context.classes().Add(class_info);
  216. if (class_info.is_generic()) {
  217. class_decl.type_id = context.GetGenericClassType(class_decl.class_id);
  218. }
  219. }
  220. // Write the class ID into the ClassDecl.
  221. context.ReplaceInstBeforeConstantUse(class_decl_id, class_decl);
  222. if (is_new_class) {
  223. // Build the `Self` type using the resulting type constant.
  224. // TODO: Form this as part of building the definition, not as part of the
  225. // declaration.
  226. auto& class_info = context.classes().Get(class_decl.class_id);
  227. if (class_info.is_generic()) {
  228. // TODO: Pass in the generic arguments once we can represent them.
  229. class_info.self_type_id = context.GetTypeIdForTypeConstant(TryEvalInst(
  230. context, SemIR::InstId::Invalid,
  231. SemIR::ClassType{SemIR::TypeId::TypeType, class_decl.class_id}));
  232. } else {
  233. class_info.self_type_id = context.GetTypeIdForTypeInst(class_decl_id);
  234. }
  235. }
  236. return {class_decl.class_id, class_decl_id};
  237. }
  238. auto HandleClassDecl(Context& context, Parse::ClassDeclId node_id) -> bool {
  239. BuildClassDecl(context, node_id, /*is_definition=*/false);
  240. context.decl_name_stack().PopScope();
  241. return true;
  242. }
  243. auto HandleClassDefinitionStart(Context& context,
  244. Parse::ClassDefinitionStartId node_id) -> bool {
  245. auto [class_id, class_decl_id] =
  246. BuildClassDecl(context, node_id, /*is_definition=*/true);
  247. auto& class_info = context.classes().Get(class_id);
  248. // Track that this declaration is the definition.
  249. if (!class_info.is_defined()) {
  250. class_info.definition_id = class_decl_id;
  251. class_info.scope_id = context.name_scopes().Add(
  252. class_decl_id, SemIR::NameId::Invalid, class_info.enclosing_scope_id);
  253. }
  254. // Enter the class scope.
  255. context.scope_stack().Push(class_decl_id, class_info.scope_id);
  256. // Introduce `Self`.
  257. context.name_scopes()
  258. .Get(class_info.scope_id)
  259. .names.insert({SemIR::NameId::SelfType,
  260. context.types().GetInstId(class_info.self_type_id)});
  261. context.inst_block_stack().Push();
  262. context.node_stack().Push(node_id, class_id);
  263. context.args_type_info_stack().Push();
  264. // TODO: Handle the case where there's control flow in the class body. For
  265. // example:
  266. //
  267. // class C {
  268. // var v: if true then i32 else f64;
  269. // }
  270. //
  271. // We may need to track a list of instruction blocks here, as we do for a
  272. // function.
  273. class_info.body_block_id = context.inst_block_stack().PeekOrAdd();
  274. return true;
  275. }
  276. // Diagnoses a class-specific declaration appearing outside a class.
  277. static auto DiagnoseClassSpecificDeclOutsideClass(Context& context,
  278. SemIRLoc loc,
  279. Lex::TokenKind tok) -> void {
  280. CARBON_DIAGNOSTIC(ClassSpecificDeclOutsideClass, Error,
  281. "`{0}` declaration can only be used in a class.",
  282. Lex::TokenKind);
  283. context.emitter().Emit(loc, ClassSpecificDeclOutsideClass, tok);
  284. }
  285. // Returns the declaration of the immediately-enclosing class scope, or
  286. // diagonses if there isn't one.
  287. static auto GetEnclosingClassOrDiagnose(Context& context, SemIRLoc loc,
  288. Lex::TokenKind tok)
  289. -> std::optional<SemIR::ClassDecl> {
  290. auto class_scope = context.GetCurrentScopeAs<SemIR::ClassDecl>();
  291. if (!class_scope) {
  292. DiagnoseClassSpecificDeclOutsideClass(context, loc, tok);
  293. }
  294. return class_scope;
  295. }
  296. // Diagnoses a class-specific declaration that is repeated within a class, but
  297. // is not permitted to be repeated.
  298. static auto DiagnoseClassSpecificDeclRepeated(Context& context,
  299. SemIRLoc new_loc,
  300. SemIRLoc prev_loc,
  301. Lex::TokenKind tok) -> void {
  302. CARBON_DIAGNOSTIC(ClassSpecificDeclRepeated, Error,
  303. "Multiple `{0}` declarations in class.{1}", Lex::TokenKind,
  304. std::string);
  305. const llvm::StringRef extra = tok == Lex::TokenKind::Base
  306. ? " Multiple inheritance is not permitted."
  307. : "";
  308. CARBON_DIAGNOSTIC(ClassSpecificDeclPrevious, Note,
  309. "Previous `{0}` declaration is here.", Lex::TokenKind);
  310. context.emitter()
  311. .Build(new_loc, ClassSpecificDeclRepeated, tok, extra.str())
  312. .Note(prev_loc, ClassSpecificDeclPrevious, tok)
  313. .Emit();
  314. }
  315. auto HandleAdaptIntroducer(Context& context,
  316. Parse::AdaptIntroducerId /*node_id*/) -> bool {
  317. context.decl_state_stack().Push(DeclState::Adapt);
  318. return true;
  319. }
  320. auto HandleAdaptDecl(Context& context, Parse::AdaptDeclId node_id) -> bool {
  321. auto [adapted_type_node, adapted_type_expr_id] =
  322. context.node_stack().PopExprWithNodeId();
  323. // Process modifiers. `extend` is permitted, no others are allowed.
  324. LimitModifiersOnDecl(context, KeywordModifierSet::Extend,
  325. Lex::TokenKind::Adapt);
  326. auto modifiers = context.decl_state_stack().innermost().modifier_set;
  327. context.decl_state_stack().Pop(DeclState::Adapt);
  328. auto enclosing_class_decl =
  329. GetEnclosingClassOrDiagnose(context, node_id, Lex::TokenKind::Adapt);
  330. if (!enclosing_class_decl) {
  331. return true;
  332. }
  333. auto& class_info = context.classes().Get(enclosing_class_decl->class_id);
  334. if (class_info.adapt_id.is_valid()) {
  335. DiagnoseClassSpecificDeclRepeated(context, node_id, class_info.adapt_id,
  336. Lex::TokenKind::Adapt);
  337. return true;
  338. }
  339. auto adapted_type_id = ExprAsType(context, node_id, adapted_type_expr_id);
  340. adapted_type_id = context.AsCompleteType(adapted_type_id, [&] {
  341. CARBON_DIAGNOSTIC(IncompleteTypeInAdaptDecl, Error,
  342. "Adapted type `{0}` is an incomplete type.",
  343. SemIR::TypeId);
  344. return context.emitter().Build(node_id, IncompleteTypeInAdaptDecl,
  345. adapted_type_id);
  346. });
  347. // Build a SemIR representation for the declaration.
  348. class_info.adapt_id = context.AddInst<SemIR::AdaptDecl>(
  349. node_id, {.adapted_type_id = adapted_type_id});
  350. // Extend the class scope with the adapted type's scope if requested.
  351. if (modifiers.HasAnyOf(KeywordModifierSet::Extend)) {
  352. auto extended_scope_id = SemIR::NameScopeId::Invalid;
  353. if (adapted_type_id == SemIR::TypeId::Error) {
  354. // Recover by not extending any scope. We instead set has_error to true
  355. // below.
  356. } else if (auto* adapted_class_info =
  357. TryGetAsClass(context, adapted_type_id)) {
  358. extended_scope_id = adapted_class_info->scope_id;
  359. CARBON_CHECK(adapted_class_info->scope_id.is_valid())
  360. << "Complete class should have a scope";
  361. } else {
  362. // TODO: Accept any type that has a scope.
  363. context.TODO(node_id, "extending non-class type");
  364. }
  365. auto& class_scope = context.name_scopes().Get(class_info.scope_id);
  366. if (extended_scope_id.is_valid()) {
  367. class_scope.extended_scopes.push_back(extended_scope_id);
  368. } else {
  369. class_scope.has_error = true;
  370. }
  371. }
  372. return true;
  373. }
  374. auto HandleBaseIntroducer(Context& context, Parse::BaseIntroducerId /*node_id*/)
  375. -> bool {
  376. context.decl_state_stack().Push(DeclState::Base);
  377. return true;
  378. }
  379. auto HandleBaseColon(Context& /*context*/, Parse::BaseColonId /*node_id*/)
  380. -> bool {
  381. return true;
  382. }
  383. namespace {
  384. // Information gathered about a base type specified in a `base` declaration.
  385. struct BaseInfo {
  386. // A `BaseInfo` representing an erroneous base.
  387. static const BaseInfo Error;
  388. SemIR::TypeId type_id;
  389. SemIR::NameScopeId scope_id;
  390. };
  391. constexpr BaseInfo BaseInfo::Error = {.type_id = SemIR::TypeId::Error,
  392. .scope_id = SemIR::NameScopeId::Invalid};
  393. } // namespace
  394. // Diagnoses an attempt to derive from a final type.
  395. static auto DiagnoseBaseIsFinal(Context& context, Parse::NodeId node_id,
  396. SemIR::TypeId base_type_id) -> void {
  397. CARBON_DIAGNOSTIC(BaseIsFinal, Error,
  398. "Deriving from final type `{0}`. Base type must be an "
  399. "`abstract` or `base` class.",
  400. SemIR::TypeId);
  401. context.emitter().Emit(node_id, BaseIsFinal, base_type_id);
  402. }
  403. // Checks that the specified base type is valid.
  404. static auto CheckBaseType(Context& context, Parse::NodeId node_id,
  405. SemIR::InstId base_expr_id) -> BaseInfo {
  406. auto base_type_id = ExprAsType(context, node_id, base_expr_id);
  407. base_type_id = context.AsCompleteType(base_type_id, [&] {
  408. CARBON_DIAGNOSTIC(IncompleteTypeInBaseDecl, Error,
  409. "Base `{0}` is an incomplete type.", SemIR::TypeId);
  410. return context.emitter().Build(node_id, IncompleteTypeInBaseDecl,
  411. base_type_id);
  412. });
  413. if (base_type_id == SemIR::TypeId::Error) {
  414. return BaseInfo::Error;
  415. }
  416. auto* base_class_info = TryGetAsClass(context, base_type_id);
  417. // The base must not be a final class.
  418. if (!base_class_info) {
  419. // For now, we treat all types that aren't introduced by a `class`
  420. // declaration as being final classes.
  421. // TODO: Once we have a better idea of which types are considered to be
  422. // classes, produce a better diagnostic for deriving from a non-class type.
  423. DiagnoseBaseIsFinal(context, node_id, base_type_id);
  424. return BaseInfo::Error;
  425. }
  426. if (base_class_info->inheritance_kind == SemIR::Class::Final) {
  427. DiagnoseBaseIsFinal(context, node_id, base_type_id);
  428. }
  429. CARBON_CHECK(base_class_info->scope_id.is_valid())
  430. << "Complete class should have a scope";
  431. return {.type_id = base_type_id, .scope_id = base_class_info->scope_id};
  432. }
  433. auto HandleBaseDecl(Context& context, Parse::BaseDeclId node_id) -> bool {
  434. auto [base_type_node_id, base_type_expr_id] =
  435. context.node_stack().PopExprWithNodeId();
  436. // Process modifiers. `extend` is required, no others are allowed.
  437. LimitModifiersOnDecl(context, KeywordModifierSet::Extend,
  438. Lex::TokenKind::Base);
  439. auto modifiers = context.decl_state_stack().innermost().modifier_set;
  440. if (!modifiers.HasAnyOf(KeywordModifierSet::Extend)) {
  441. CARBON_DIAGNOSTIC(BaseMissingExtend, Error,
  442. "Missing `extend` before `base` declaration in class.");
  443. context.emitter().Emit(node_id, BaseMissingExtend);
  444. }
  445. context.decl_state_stack().Pop(DeclState::Base);
  446. auto enclosing_class_decl =
  447. GetEnclosingClassOrDiagnose(context, node_id, Lex::TokenKind::Base);
  448. if (!enclosing_class_decl) {
  449. return true;
  450. }
  451. auto& class_info = context.classes().Get(enclosing_class_decl->class_id);
  452. if (class_info.base_id.is_valid()) {
  453. DiagnoseClassSpecificDeclRepeated(context, node_id, class_info.base_id,
  454. Lex::TokenKind::Base);
  455. return true;
  456. }
  457. auto base_info = CheckBaseType(context, base_type_node_id, base_type_expr_id);
  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 =
  461. context.GetUnboundElementType(class_info.self_type_id, base_info.type_id);
  462. class_info.base_id = context.AddInst<SemIR::BaseDecl>(
  463. node_id,
  464. {.type_id = field_type_id,
  465. .base_type_id = base_info.type_id,
  466. .index = SemIR::ElementIndex(
  467. context.args_type_info_stack().PeekCurrentBlockContents().size())});
  468. // Add a corresponding field to the object representation of the class.
  469. // TODO: Consider whether we want to use `partial T` here.
  470. // TODO: Should we diagnose if there are already any fields?
  471. context.args_type_info_stack().AddInstId(
  472. context.AddInstInNoBlock<SemIR::StructTypeField>(
  473. node_id, {.name_id = SemIR::NameId::Base,
  474. .field_type_id = base_info.type_id}));
  475. // Bind the name `base` in the class to the base field.
  476. context.decl_name_stack().AddNameOrDiagnoseDuplicate(
  477. context.decl_name_stack().MakeUnqualifiedName(node_id,
  478. SemIR::NameId::Base),
  479. class_info.base_id);
  480. // Extend the class scope with the base class.
  481. if (modifiers.HasAnyOf(KeywordModifierSet::Extend)) {
  482. auto& class_scope = context.name_scopes().Get(class_info.scope_id);
  483. if (base_info.scope_id.is_valid()) {
  484. class_scope.extended_scopes.push_back(base_info.scope_id);
  485. } else {
  486. class_scope.has_error = true;
  487. }
  488. }
  489. return true;
  490. }
  491. auto HandleClassDefinition(Context& context,
  492. Parse::ClassDefinitionId /*node_id*/) -> bool {
  493. auto fields_id = context.args_type_info_stack().Pop();
  494. auto class_id =
  495. context.node_stack().Pop<Parse::NodeKind::ClassDefinitionStart>();
  496. context.inst_block_stack().Pop();
  497. // The class type is now fully defined. Compute its object representation.
  498. auto& class_info = context.classes().Get(class_id);
  499. if (class_info.adapt_id.is_valid()) {
  500. class_info.object_repr_id = SemIR::TypeId::Error;
  501. if (class_info.base_id.is_valid()) {
  502. CARBON_DIAGNOSTIC(AdaptWithBase, Error,
  503. "Adapter cannot have a base class.");
  504. CARBON_DIAGNOSTIC(AdaptBaseHere, Note, "`base` declaration is here.");
  505. context.emitter()
  506. .Build(class_info.adapt_id, AdaptWithBase)
  507. .Note(class_info.base_id, AdaptBaseHere)
  508. .Emit();
  509. } else if (!context.inst_blocks().Get(fields_id).empty()) {
  510. auto first_field_id = context.inst_blocks().Get(fields_id).front();
  511. CARBON_DIAGNOSTIC(AdaptWithFields, Error, "Adapter cannot have fields.");
  512. CARBON_DIAGNOSTIC(AdaptFieldHere, Note,
  513. "First field declaration is here.");
  514. context.emitter()
  515. .Build(class_info.adapt_id, AdaptWithFields)
  516. .Note(first_field_id, AdaptFieldHere)
  517. .Emit();
  518. } else {
  519. // The object representation of the adapter is the object representation
  520. // of the adapted type.
  521. auto adapted_type_id = context.insts()
  522. .GetAs<SemIR::AdaptDecl>(class_info.adapt_id)
  523. .adapted_type_id;
  524. // If we adapt an adapter, directly track the non-adapter type we're
  525. // adapting so that we have constant-time access to it.
  526. if (auto adapted_class =
  527. context.types().TryGetAs<SemIR::ClassType>(adapted_type_id)) {
  528. auto& adapted_class_info =
  529. context.classes().Get(adapted_class->class_id);
  530. if (adapted_class_info.adapt_id.is_valid()) {
  531. adapted_type_id = adapted_class_info.object_repr_id;
  532. }
  533. }
  534. class_info.object_repr_id = adapted_type_id;
  535. }
  536. } else {
  537. class_info.object_repr_id = context.GetStructType(fields_id);
  538. }
  539. // The decl_name_stack and scopes are popped by `ProcessNodeIds`.
  540. return true;
  541. }
  542. } // namespace Carbon::Check