handle_class.cpp 25 KB

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