handle_class.cpp 25 KB

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