handle_class.cpp 25 KB

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