handle_class.cpp 25 KB

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