handle_class.cpp 25 KB

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