handle_class.cpp 29 KB

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