handle_class.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  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. // Push a pattern block for the signature (if any) of the first NameComponent.
  41. // TODO: Instead use a separate parse node kind for an identifier that's
  42. // followed by a pattern, and push a pattern block when handling it.
  43. context.pattern_block_stack().Push();
  44. return true;
  45. }
  46. // Tries to merge new_class into prev_class_id. Since new_class won't have a
  47. // definition even if one is upcoming, set is_definition to indicate the planned
  48. // result.
  49. //
  50. // If merging is successful, returns true and may update the previous class.
  51. // Otherwise, returns false. Prints a diagnostic when appropriate.
  52. static auto MergeClassRedecl(Context& context, SemIRLoc new_loc,
  53. SemIR::Class& new_class, bool new_is_import,
  54. bool new_is_definition,
  55. SemIR::ClassId prev_class_id,
  56. SemIR::ImportIRId prev_import_ir_id) -> bool {
  57. auto& prev_class = context.classes().Get(prev_class_id);
  58. SemIRLoc prev_loc = prev_class.latest_decl_id();
  59. // Check the generic parameters match, if they were specified.
  60. if (!CheckRedeclParamsMatch(context, DeclParams(new_class),
  61. DeclParams(prev_class))) {
  62. return false;
  63. }
  64. CheckIsAllowedRedecl(
  65. context, Lex::TokenKind::Class, prev_class.name_id,
  66. RedeclInfo(new_class, new_loc, new_is_definition),
  67. RedeclInfo(prev_class, prev_loc, prev_class.is_defined()),
  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. if (new_is_definition) {
  74. prev_class.MergeDefinition(new_class);
  75. prev_class.scope_id = new_class.scope_id;
  76. prev_class.body_block_id = new_class.body_block_id;
  77. prev_class.adapt_id = new_class.adapt_id;
  78. prev_class.base_id = new_class.base_id;
  79. prev_class.complete_type_witness_id = new_class.complete_type_witness_id;
  80. }
  81. if ((prev_import_ir_id.is_valid() && !new_is_import) ||
  82. (prev_class.is_extern && !new_class.is_extern)) {
  83. prev_class.first_owning_decl_id = new_class.first_owning_decl_id;
  84. ReplacePrevInstForMerge(
  85. context, new_class.parent_scope_id, prev_class.name_id,
  86. new_is_import ? new_loc.inst_id : new_class.first_owning_decl_id);
  87. }
  88. return true;
  89. }
  90. // Adds the name to name lookup. If there's a conflict, tries to merge. May
  91. // update class_decl and class_info when merging.
  92. static auto MergeOrAddName(Context& context, Parse::AnyClassDeclId node_id,
  93. const DeclNameStack::NameContext& name_context,
  94. SemIR::InstId class_decl_id,
  95. SemIR::ClassDecl& class_decl,
  96. SemIR::Class& class_info, bool is_definition,
  97. SemIR::AccessKind access_kind) -> void {
  98. auto prev_id = context.decl_name_stack().LookupOrAddName(
  99. name_context, class_decl_id, access_kind);
  100. if (!prev_id.is_valid()) {
  101. return;
  102. }
  103. auto prev_class_id = SemIR::ClassId::Invalid;
  104. auto prev_import_ir_id = SemIR::ImportIRId::Invalid;
  105. auto prev = context.insts().Get(prev_id);
  106. CARBON_KIND_SWITCH(prev) {
  107. case CARBON_KIND(SemIR::ClassDecl class_decl): {
  108. prev_class_id = class_decl.class_id;
  109. break;
  110. }
  111. case CARBON_KIND(SemIR::ImportRefLoaded import_ref): {
  112. auto import_ir_inst =
  113. context.import_ir_insts().Get(import_ref.import_ir_inst_id);
  114. // Verify the decl so that things like aliases are name conflicts.
  115. const auto* import_ir =
  116. context.import_irs().Get(import_ir_inst.ir_id).sem_ir;
  117. if (!import_ir->insts().Is<SemIR::ClassDecl>(import_ir_inst.inst_id)) {
  118. break;
  119. }
  120. // Use the constant value to get the ID.
  121. auto decl_value = context.insts().Get(
  122. context.constant_values().GetConstantInstId(prev_id));
  123. if (auto class_type = decl_value.TryAs<SemIR::ClassType>()) {
  124. prev_class_id = class_type->class_id;
  125. prev_import_ir_id = import_ir_inst.ir_id;
  126. } else if (auto generic_class_type =
  127. context.types().TryGetAs<SemIR::GenericClassType>(
  128. decl_value.type_id())) {
  129. prev_class_id = generic_class_type->class_id;
  130. prev_import_ir_id = import_ir_inst.ir_id;
  131. }
  132. break;
  133. }
  134. default:
  135. break;
  136. }
  137. if (!prev_class_id.is_valid()) {
  138. // This is a redeclaration of something other than a class.
  139. context.DiagnoseDuplicateName(class_decl_id, prev_id);
  140. return;
  141. }
  142. // TODO: Fix `extern` logic. It doesn't work correctly, but doesn't seem worth
  143. // ripping out because existing code may incrementally help.
  144. if (MergeClassRedecl(context, node_id, class_info,
  145. /*new_is_import=*/false, is_definition, prev_class_id,
  146. prev_import_ir_id)) {
  147. // When merging, use the existing entity rather than adding a new one.
  148. class_decl.class_id = prev_class_id;
  149. class_decl.type_id = prev.type_id();
  150. // TODO: Validate that the redeclaration doesn't set an access modifier.
  151. }
  152. }
  153. static auto BuildClassDecl(Context& context, Parse::AnyClassDeclId node_id,
  154. bool is_definition)
  155. -> std::tuple<SemIR::ClassId, SemIR::InstId> {
  156. auto name = PopNameComponent(context);
  157. auto name_context = context.decl_name_stack().FinishName(name);
  158. context.node_stack()
  159. .PopAndDiscardSoloNodeId<Parse::NodeKind::ClassIntroducer>();
  160. // Process modifiers.
  161. auto [_, parent_scope_inst] =
  162. context.name_scopes().GetInstIfValid(name_context.parent_scope_id);
  163. auto introducer =
  164. context.decl_introducer_state_stack().Pop<Lex::TokenKind::Class>();
  165. CheckAccessModifiersOnDecl(context, introducer, parent_scope_inst);
  166. auto always_acceptable_modifiers =
  167. KeywordModifierSet::Access | KeywordModifierSet::Extern;
  168. LimitModifiersOnDecl(context, introducer,
  169. always_acceptable_modifiers | KeywordModifierSet::Class);
  170. if (!is_definition) {
  171. LimitModifiersOnNotDefinition(context, introducer,
  172. always_acceptable_modifiers);
  173. }
  174. RestrictExternModifierOnDecl(context, introducer, parent_scope_inst,
  175. is_definition);
  176. bool is_extern = introducer.modifier_set.HasAnyOf(KeywordModifierSet::Extern);
  177. if (introducer.extern_library.is_valid()) {
  178. context.TODO(node_id, "extern library");
  179. }
  180. auto inheritance_kind =
  181. introducer.modifier_set.ToEnum<SemIR::Class::InheritanceKind>()
  182. .Case(KeywordModifierSet::Abstract, SemIR::Class::Abstract)
  183. .Case(KeywordModifierSet::Base, SemIR::Class::Base)
  184. .Default(SemIR::Class::Final);
  185. auto decl_block_id = context.inst_block_stack().Pop();
  186. // Add the class declaration.
  187. auto class_decl = SemIR::ClassDecl{.type_id = SemIR::TypeId::TypeType,
  188. .class_id = SemIR::ClassId::Invalid,
  189. .decl_block_id = decl_block_id};
  190. auto class_decl_id =
  191. context.AddPlaceholderInst(SemIR::LocIdAndInst(node_id, class_decl));
  192. // TODO: Store state regarding is_extern.
  193. SemIR::Class class_info = {
  194. name_context.MakeEntityWithParamsBase(name, class_decl_id, is_extern,
  195. SemIR::LibraryNameId::Invalid),
  196. {// `.self_type_id` depends on the ClassType, so is set below.
  197. .self_type_id = SemIR::TypeId::Invalid,
  198. .inheritance_kind = inheritance_kind}};
  199. MergeOrAddName(context, node_id, name_context, class_decl_id, class_decl,
  200. class_info, is_definition,
  201. introducer.modifier_set.GetAccessKind());
  202. // Create a new class if this isn't a valid redeclaration.
  203. bool is_new_class = !class_decl.class_id.is_valid();
  204. if (is_new_class) {
  205. // TODO: If this is an invalid redeclaration of a non-class entity or there
  206. // was an error in the qualifier, we will have lost track of the class name
  207. // here. We should keep track of it even if the name is invalid.
  208. class_info.generic_id = FinishGenericDecl(context, class_decl_id);
  209. class_decl.class_id = context.classes().Add(class_info);
  210. if (class_info.has_parameters()) {
  211. class_decl.type_id = context.GetGenericClassType(
  212. class_decl.class_id, context.scope_stack().PeekSpecificId());
  213. }
  214. } else {
  215. FinishGenericRedecl(context, class_decl_id, class_info.generic_id);
  216. }
  217. // Write the class ID into the ClassDecl.
  218. context.ReplaceInstBeforeConstantUse(class_decl_id, class_decl);
  219. if (is_new_class) {
  220. // Build the `Self` type using the resulting type constant.
  221. // TODO: Form this as part of building the definition, not as part of the
  222. // declaration.
  223. auto& class_info = context.classes().Get(class_decl.class_id);
  224. auto specific_id =
  225. context.generics().GetSelfSpecific(class_info.generic_id);
  226. class_info.self_type_id = context.GetTypeIdForTypeConstant(
  227. TryEvalInst(context, SemIR::InstId::Invalid,
  228. SemIR::ClassType{.type_id = SemIR::TypeId::TypeType,
  229. .class_id = class_decl.class_id,
  230. .specific_id = specific_id}));
  231. }
  232. if (!is_definition && context.IsImplFile() && !is_extern) {
  233. context.definitions_required().push_back(class_decl_id);
  234. }
  235. return {class_decl.class_id, class_decl_id};
  236. }
  237. auto HandleParseNode(Context& context, Parse::ClassDeclId node_id) -> bool {
  238. BuildClassDecl(context, node_id, /*is_definition=*/false);
  239. context.decl_name_stack().PopScope();
  240. return true;
  241. }
  242. auto HandleParseNode(Context& context, Parse::ClassDefinitionStartId node_id)
  243. -> bool {
  244. auto [class_id, class_decl_id] =
  245. BuildClassDecl(context, node_id, /*is_definition=*/true);
  246. auto& class_info = context.classes().Get(class_id);
  247. // Track that this declaration is the definition.
  248. if (!class_info.is_defined()) {
  249. class_info.definition_id = class_decl_id;
  250. class_info.scope_id = context.name_scopes().Add(
  251. class_decl_id, SemIR::NameId::Invalid, class_info.parent_scope_id);
  252. }
  253. // Enter the class scope.
  254. context.scope_stack().Push(
  255. class_decl_id, class_info.scope_id,
  256. context.generics().GetSelfSpecific(class_info.generic_id));
  257. StartGenericDefinition(context);
  258. // Introduce `Self`.
  259. context.name_scopes().AddRequiredName(
  260. class_info.scope_id, SemIR::NameId::SelfType,
  261. context.types().GetInstId(class_info.self_type_id));
  262. context.inst_block_stack().Push();
  263. context.node_stack().Push(node_id, class_id);
  264. context.args_type_info_stack().Push();
  265. // TODO: Handle the case where there's control flow in the class body. For
  266. // example:
  267. //
  268. // class C {
  269. // var v: if true then i32 else f64;
  270. // }
  271. //
  272. // We may need to track a list of instruction blocks here, as we do for a
  273. // function.
  274. class_info.body_block_id = context.inst_block_stack().PeekOrAdd();
  275. return true;
  276. }
  277. // Diagnoses a class-specific declaration appearing outside a class.
  278. static auto DiagnoseClassSpecificDeclOutsideClass(Context& context,
  279. SemIRLoc loc,
  280. Lex::TokenKind tok) -> void {
  281. CARBON_DIAGNOSTIC(ClassSpecificDeclOutsideClass, Error,
  282. "`{0}` declaration outside class", Lex::TokenKind);
  283. context.emitter().Emit(loc, ClassSpecificDeclOutsideClass, tok);
  284. }
  285. // Returns the current scope's class declaration, or diagnoses if it isn't a
  286. // class.
  287. static auto GetCurrentScopeAsClassOrDiagnose(Context& context, SemIRLoc loc,
  288. Lex::TokenKind tok)
  289. -> std::optional<SemIR::ClassDecl> {
  290. auto class_scope = context.GetCurrentScopeAs<SemIR::ClassDecl>();
  291. if (!class_scope) {
  292. DiagnoseClassSpecificDeclOutsideClass(context, loc, tok);
  293. }
  294. return class_scope;
  295. }
  296. // Diagnoses a class-specific declaration that is repeated within a class, but
  297. // is not permitted to be repeated.
  298. static auto DiagnoseClassSpecificDeclRepeated(Context& context,
  299. SemIRLoc new_loc,
  300. SemIRLoc prev_loc,
  301. Lex::TokenKind tok) -> void {
  302. CARBON_DIAGNOSTIC(AdaptDeclRepeated, Error,
  303. "multiple `adapt` declarations in class");
  304. CARBON_DIAGNOSTIC(BaseDeclRepeated, Error,
  305. "multiple `base` declarations in class; multiple "
  306. "inheritance is not permitted");
  307. CARBON_DIAGNOSTIC(ClassSpecificDeclPrevious, Note,
  308. "previous `{0}` declaration is here", Lex::TokenKind);
  309. CARBON_CHECK(tok == Lex::TokenKind::Adapt || tok == Lex::TokenKind::Base);
  310. context.emitter()
  311. .Build(new_loc, tok == Lex::TokenKind::Adapt ? AdaptDeclRepeated
  312. : BaseDeclRepeated)
  313. .Note(prev_loc, ClassSpecificDeclPrevious, tok)
  314. .Emit();
  315. }
  316. auto HandleParseNode(Context& context, Parse::AdaptIntroducerId /*node_id*/)
  317. -> bool {
  318. context.decl_introducer_state_stack().Push<Lex::TokenKind::Adapt>();
  319. return true;
  320. }
  321. auto HandleParseNode(Context& context, Parse::AdaptDeclId node_id) -> bool {
  322. auto [adapted_type_node, adapted_type_expr_id] =
  323. context.node_stack().PopExprWithNodeId();
  324. // Process modifiers. `extend` is permitted, no others are allowed.
  325. auto introducer =
  326. context.decl_introducer_state_stack().Pop<Lex::TokenKind::Adapt>();
  327. LimitModifiersOnDecl(context, introducer, KeywordModifierSet::Extend);
  328. auto parent_class_decl =
  329. GetCurrentScopeAsClassOrDiagnose(context, node_id, Lex::TokenKind::Adapt);
  330. if (!parent_class_decl) {
  331. return true;
  332. }
  333. auto& class_info = context.classes().Get(parent_class_decl->class_id);
  334. if (class_info.adapt_id.is_valid()) {
  335. DiagnoseClassSpecificDeclRepeated(context, node_id, class_info.adapt_id,
  336. Lex::TokenKind::Adapt);
  337. return true;
  338. }
  339. auto adapted_type_id =
  340. ExprAsType(context, node_id, adapted_type_expr_id).type_id;
  341. adapted_type_id = context.AsCompleteType(
  342. adapted_type_id,
  343. [&] {
  344. CARBON_DIAGNOSTIC(IncompleteTypeInAdaptDecl, Error,
  345. "adapted type {0} is an incomplete type",
  346. SemIR::TypeId);
  347. return context.emitter().Build(node_id, IncompleteTypeInAdaptDecl,
  348. adapted_type_id);
  349. },
  350. [&] {
  351. CARBON_DIAGNOSTIC(AbstractTypeInAdaptDecl, Error,
  352. "adapted type {0} is an abstract type",
  353. SemIR::TypeId);
  354. return context.emitter().Build(node_id, AbstractTypeInAdaptDecl,
  355. adapted_type_id);
  356. });
  357. // Build a SemIR representation for the declaration.
  358. class_info.adapt_id = context.AddInst<SemIR::AdaptDecl>(
  359. node_id, {.adapted_type_id = adapted_type_id});
  360. // Extend the class scope with the adapted type's scope if requested.
  361. if (introducer.modifier_set.HasAnyOf(KeywordModifierSet::Extend)) {
  362. auto extended_scope_id = SemIR::NameScopeId::Invalid;
  363. if (adapted_type_id == SemIR::TypeId::Error) {
  364. // Recover by not extending any scope. We instead set has_error to true
  365. // below.
  366. } else if (auto* adapted_class_info =
  367. TryGetAsClass(context, adapted_type_id)) {
  368. extended_scope_id = adapted_class_info->scope_id;
  369. CARBON_CHECK(adapted_class_info->scope_id.is_valid(),
  370. "Complete class should have a scope");
  371. } else {
  372. // TODO: Accept any type that has a scope.
  373. context.TODO(node_id, "extending non-class type");
  374. }
  375. auto& class_scope = context.name_scopes().Get(class_info.scope_id);
  376. if (extended_scope_id.is_valid()) {
  377. class_scope.extended_scopes.push_back(extended_scope_id);
  378. } else {
  379. class_scope.has_error = true;
  380. }
  381. }
  382. return true;
  383. }
  384. auto HandleParseNode(Context& context, Parse::BaseIntroducerId /*node_id*/)
  385. -> bool {
  386. context.decl_introducer_state_stack().Push<Lex::TokenKind::Base>();
  387. return true;
  388. }
  389. auto HandleParseNode(Context& /*context*/, Parse::BaseColonId /*node_id*/)
  390. -> bool {
  391. return true;
  392. }
  393. namespace {
  394. // Information gathered about a base type specified in a `base` declaration.
  395. struct BaseInfo {
  396. // A `BaseInfo` representing an erroneous base.
  397. static const BaseInfo Error;
  398. SemIR::TypeId type_id;
  399. SemIR::NameScopeId scope_id;
  400. };
  401. constexpr BaseInfo BaseInfo::Error = {.type_id = SemIR::TypeId::Error,
  402. .scope_id = SemIR::NameScopeId::Invalid};
  403. } // namespace
  404. // Diagnoses an attempt to derive from a final type.
  405. static auto DiagnoseBaseIsFinal(Context& context, Parse::NodeId node_id,
  406. SemIR::InstId base_type_inst_id) -> void {
  407. CARBON_DIAGNOSTIC(BaseIsFinal, Error,
  408. "deriving from final type {0}; base type must be an "
  409. "`abstract` or `base` class",
  410. InstIdAsType);
  411. context.emitter().Emit(node_id, BaseIsFinal, base_type_inst_id);
  412. }
  413. // Checks that the specified base type is valid.
  414. static auto CheckBaseType(Context& context, Parse::NodeId node_id,
  415. SemIR::InstId base_expr_id) -> BaseInfo {
  416. auto [base_type_inst_id, base_type_id] =
  417. ExprAsType(context, node_id, base_expr_id);
  418. base_type_id = context.AsCompleteType(base_type_id, [&] {
  419. CARBON_DIAGNOSTIC(IncompleteTypeInBaseDecl, Error,
  420. "base {0} is an incomplete type", InstIdAsType);
  421. return context.emitter().Build(node_id, IncompleteTypeInBaseDecl,
  422. base_type_inst_id);
  423. });
  424. if (base_type_id == SemIR::TypeId::Error) {
  425. return BaseInfo::Error;
  426. }
  427. auto* base_class_info = TryGetAsClass(context, base_type_id);
  428. // The base must not be a final class.
  429. if (!base_class_info) {
  430. // For now, we treat all types that aren't introduced by a `class`
  431. // declaration as being final classes.
  432. // TODO: Once we have a better idea of which types are considered to be
  433. // classes, produce a better diagnostic for deriving from a non-class type.
  434. DiagnoseBaseIsFinal(context, node_id, base_type_inst_id);
  435. return BaseInfo::Error;
  436. }
  437. if (base_class_info->inheritance_kind == SemIR::Class::Final) {
  438. DiagnoseBaseIsFinal(context, node_id, base_type_inst_id);
  439. }
  440. CARBON_CHECK(base_class_info->scope_id.is_valid(),
  441. "Complete class should have a scope");
  442. return {.type_id = base_type_id, .scope_id = base_class_info->scope_id};
  443. }
  444. auto HandleParseNode(Context& context, Parse::BaseDeclId node_id) -> bool {
  445. auto [base_type_node_id, base_type_expr_id] =
  446. context.node_stack().PopExprWithNodeId();
  447. // Process modifiers. `extend` is required, no others are allowed.
  448. auto introducer =
  449. context.decl_introducer_state_stack().Pop<Lex::TokenKind::Base>();
  450. LimitModifiersOnDecl(context, introducer, KeywordModifierSet::Extend);
  451. if (!introducer.modifier_set.HasAnyOf(KeywordModifierSet::Extend)) {
  452. CARBON_DIAGNOSTIC(BaseMissingExtend, Error,
  453. "missing `extend` before `base` declaration");
  454. context.emitter().Emit(node_id, BaseMissingExtend);
  455. }
  456. auto parent_class_decl =
  457. GetCurrentScopeAsClassOrDiagnose(context, node_id, Lex::TokenKind::Base);
  458. if (!parent_class_decl) {
  459. return true;
  460. }
  461. auto& class_info = context.classes().Get(parent_class_decl->class_id);
  462. if (class_info.base_id.is_valid()) {
  463. DiagnoseClassSpecificDeclRepeated(context, node_id, class_info.base_id,
  464. Lex::TokenKind::Base);
  465. return true;
  466. }
  467. auto base_info = CheckBaseType(context, base_type_node_id, base_type_expr_id);
  468. // The `base` value in the class scope has an unbound element type. Instance
  469. // binding will be performed when it's found by name lookup into an instance.
  470. auto field_type_id =
  471. context.GetUnboundElementType(class_info.self_type_id, base_info.type_id);
  472. class_info.base_id = context.AddInst<SemIR::BaseDecl>(
  473. node_id,
  474. {.type_id = field_type_id,
  475. .base_type_id = base_info.type_id,
  476. .index = SemIR::ElementIndex(
  477. context.args_type_info_stack().PeekCurrentBlockContents().size())});
  478. if (base_info.type_id != SemIR::TypeId::Error) {
  479. auto base_class_info = context.classes().Get(
  480. context.types().GetAs<SemIR::ClassType>(base_info.type_id).class_id);
  481. class_info.is_dynamic |= base_class_info.is_dynamic;
  482. }
  483. // Add a corresponding field to the object representation of the class.
  484. // TODO: Consider whether we want to use `partial T` here.
  485. // TODO: Should we diagnose if there are already any fields?
  486. context.args_type_info_stack().AddInstId(
  487. context.AddInstInNoBlock<SemIR::StructTypeField>(
  488. node_id, {.name_id = SemIR::NameId::Base,
  489. .field_type_id = base_info.type_id}));
  490. // Bind the name `base` in the class to the base field.
  491. context.decl_name_stack().AddNameOrDiagnoseDuplicate(
  492. context.decl_name_stack().MakeUnqualifiedName(node_id,
  493. SemIR::NameId::Base),
  494. class_info.base_id, introducer.modifier_set.GetAccessKind());
  495. // Extend the class scope with the base class.
  496. if (introducer.modifier_set.HasAnyOf(KeywordModifierSet::Extend)) {
  497. auto& class_scope = context.name_scopes().Get(class_info.scope_id);
  498. if (base_info.scope_id.is_valid()) {
  499. class_scope.extended_scopes.push_back(base_info.scope_id);
  500. } else {
  501. class_scope.has_error = true;
  502. }
  503. }
  504. return true;
  505. }
  506. // Checks that the specified finished adapter definition is valid and builds and
  507. // returns a corresponding complete type witness instruction.
  508. static auto CheckCompleteAdapterClassType(Context& context,
  509. Parse::NodeId node_id,
  510. SemIR::ClassId class_id,
  511. SemIR::InstBlockId fields_id)
  512. -> SemIR::InstId {
  513. const auto& class_info = context.classes().Get(class_id);
  514. if (class_info.base_id.is_valid()) {
  515. CARBON_DIAGNOSTIC(AdaptWithBase, Error, "adapter with base class");
  516. CARBON_DIAGNOSTIC(AdaptWithBaseHere, Note, "`base` declaration is here");
  517. context.emitter()
  518. .Build(class_info.adapt_id, AdaptWithBase)
  519. .Note(class_info.base_id, AdaptWithBaseHere)
  520. .Emit();
  521. return SemIR::InstId::BuiltinError;
  522. }
  523. 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 with fields");
  526. CARBON_DIAGNOSTIC(AdaptWithFieldHere, Note,
  527. "first field declaration is here");
  528. context.emitter()
  529. .Build(class_info.adapt_id, AdaptWithFields)
  530. .Note(first_field_id, AdaptWithFieldHere)
  531. .Emit();
  532. return SemIR::InstId::BuiltinError;
  533. }
  534. for (auto inst_id : context.inst_block_stack().PeekCurrentBlockContents()) {
  535. if (auto function_decl =
  536. context.insts().TryGetAs<SemIR::FunctionDecl>(inst_id)) {
  537. auto& function = context.functions().Get(function_decl->function_id);
  538. if (function.virtual_modifier ==
  539. SemIR::Function::VirtualModifier::Virtual) {
  540. CARBON_DIAGNOSTIC(AdaptWithVirtual, Error,
  541. "adapter with virtual function");
  542. CARBON_DIAGNOSTIC(AdaptWithVirtualHere, Note,
  543. "first virtual function declaration is here");
  544. context.emitter()
  545. .Build(class_info.adapt_id, AdaptWithVirtual)
  546. .Note(inst_id, AdaptWithVirtualHere)
  547. .Emit();
  548. return SemIR::InstId::BuiltinError;
  549. }
  550. }
  551. }
  552. // The object representation of the adapter is the object representation
  553. // of the adapted type. This is the adapted type itself unless it's a class
  554. // type.
  555. //
  556. // TODO: The object representation of `const T` should also be the object
  557. // representation of `T`.
  558. auto adapted_type_id = context.insts()
  559. .GetAs<SemIR::AdaptDecl>(class_info.adapt_id)
  560. .adapted_type_id;
  561. if (auto adapted_class =
  562. context.types().TryGetAs<SemIR::ClassType>(adapted_type_id)) {
  563. auto& adapted_class_info = context.classes().Get(adapted_class->class_id);
  564. if (adapted_class_info.adapt_id.is_valid()) {
  565. return adapted_class_info.complete_type_witness_id;
  566. }
  567. }
  568. return context.AddInst<SemIR::CompleteTypeWitness>(
  569. node_id,
  570. {.type_id = context.GetBuiltinType(SemIR::BuiltinInstKind::WitnessType),
  571. .object_repr_id = adapted_type_id});
  572. }
  573. // Checks that the specified finished class definition is valid and builds and
  574. // returns a corresponding complete type witness instruction.
  575. static auto CheckCompleteClassType(Context& context, Parse::NodeId node_id,
  576. SemIR::ClassId class_id) -> SemIR::InstId {
  577. auto& class_info = context.classes().Get(class_id);
  578. if (class_info.adapt_id.is_valid()) {
  579. auto fields_id = context.args_type_info_stack().Pop();
  580. return CheckCompleteAdapterClassType(context, node_id, class_id, fields_id);
  581. }
  582. bool defining_vtable_ptr = class_info.is_dynamic;
  583. if (class_info.base_id.is_valid()) {
  584. auto base_info = context.insts().GetAs<SemIR::BaseDecl>(class_info.base_id);
  585. // TODO: If the base class is template dependent, we will need to decide
  586. // whether to add a vptr as part of instantiation.
  587. if (auto* base_class_info = TryGetAsClass(context, base_info.base_type_id);
  588. base_class_info && base_class_info->is_dynamic) {
  589. defining_vtable_ptr = false;
  590. }
  591. }
  592. if (defining_vtable_ptr) {
  593. context.args_type_info_stack().AddFrontInstId(
  594. context.AddInstInNoBlock<SemIR::StructTypeField>(
  595. Parse::NodeId::Invalid,
  596. {.name_id = SemIR::NameId::Vptr,
  597. .field_type_id = context.GetPointerType(
  598. context.GetBuiltinType(SemIR::BuiltinInstKind::VtableType))}));
  599. }
  600. auto fields_id = context.args_type_info_stack().Pop();
  601. return context.AddInst<SemIR::CompleteTypeWitness>(
  602. node_id,
  603. {.type_id = context.GetBuiltinType(SemIR::BuiltinInstKind::WitnessType),
  604. .object_repr_id = context.GetStructType(fields_id)});
  605. }
  606. auto HandleParseNode(Context& context, Parse::ClassDefinitionId node_id)
  607. -> bool {
  608. auto class_id =
  609. context.node_stack().Pop<Parse::NodeKind::ClassDefinitionStart>();
  610. // The class type is now fully defined. Compute its object representation.
  611. auto complete_type_witness_id =
  612. CheckCompleteClassType(context, node_id, class_id);
  613. auto& class_info = context.classes().Get(class_id);
  614. class_info.complete_type_witness_id = complete_type_witness_id;
  615. context.inst_block_stack().Pop();
  616. FinishGenericDefinition(context, class_info.generic_id);
  617. // The decl_name_stack and scopes are popped by `ProcessNodeIds`.
  618. return true;
  619. }
  620. } // namespace Carbon::Check