handle_class.cpp 25 KB

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