handle_class.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780
  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/import.h"
  13. #include "toolchain/check/import_ref.h"
  14. #include "toolchain/check/merge.h"
  15. #include "toolchain/check/modifiers.h"
  16. #include "toolchain/check/name_component.h"
  17. #include "toolchain/check/type_completion.h"
  18. #include "toolchain/parse/node_ids.h"
  19. #include "toolchain/sem_ir/function.h"
  20. #include "toolchain/sem_ir/ids.h"
  21. #include "toolchain/sem_ir/inst.h"
  22. #include "toolchain/sem_ir/typed_insts.h"
  23. namespace Carbon::Check {
  24. // If `type_id` is a class type, get its corresponding `SemIR::Class` object.
  25. // Otherwise returns `nullptr`.
  26. static auto TryGetAsClass(Context& context, SemIR::TypeId type_id)
  27. -> SemIR::Class* {
  28. auto class_type = context.types().TryGetAs<SemIR::ClassType>(type_id);
  29. if (!class_type) {
  30. return nullptr;
  31. }
  32. return &context.classes().Get(class_type->class_id);
  33. }
  34. auto HandleParseNode(Context& context, Parse::ClassIntroducerId node_id)
  35. -> bool {
  36. // Create an instruction block to hold the instructions created as part of the
  37. // class signature, such as generic parameters.
  38. context.inst_block_stack().Push();
  39. // Push the bracketing node.
  40. context.node_stack().Push(node_id);
  41. // Optional modifiers and the name follow.
  42. context.decl_introducer_state_stack().Push<Lex::TokenKind::Class>();
  43. context.decl_name_stack().PushScopeAndStartName();
  44. // This class is potentially generic.
  45. StartGenericDecl(context);
  46. return true;
  47. }
  48. // Tries to merge new_class into prev_class_id. Since new_class won't have a
  49. // definition even if one is upcoming, set is_definition to indicate the planned
  50. // result.
  51. //
  52. // If merging is successful, returns true and may update the previous class.
  53. // Otherwise, returns false. Prints a diagnostic when appropriate.
  54. static auto MergeClassRedecl(Context& context, Parse::AnyClassDeclId node_id,
  55. SemIR::Class& new_class, 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. DiagnoseIfInvalidRedecl(
  66. context, Lex::TokenKind::Class, prev_class.name_id,
  67. RedeclInfo(new_class, node_id, new_is_definition),
  68. RedeclInfo(prev_class, prev_loc, prev_class.has_definition_started()),
  69. prev_import_ir_id);
  70. if (new_is_definition && prev_class.has_definition_started()) {
  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.has_value() ||
  83. (prev_class.is_extern && !new_class.is_extern)) {
  84. prev_class.first_owning_decl_id = new_class.first_owning_decl_id;
  85. ReplacePrevInstForMerge(context, new_class.parent_scope_id,
  86. prev_class.name_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. SemIR::ScopeLookupResult lookup_result =
  99. context.decl_name_stack().LookupOrAddName(name_context, class_decl_id,
  100. access_kind);
  101. if (lookup_result.is_poisoned()) {
  102. // This is a declaration of a poisoned name.
  103. context.DiagnosePoisonedName(lookup_result.poisoning_loc_id(),
  104. name_context.loc_id);
  105. return;
  106. }
  107. if (!lookup_result.is_found()) {
  108. return;
  109. }
  110. SemIR::InstId prev_id = lookup_result.target_inst_id();
  111. auto prev_class_id = SemIR::ClassId::None;
  112. auto prev_import_ir_id = SemIR::ImportIRId::None;
  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.has_value()) {
  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, is_definition,
  153. prev_class_id, prev_import_ir_id)) {
  154. // When merging, use the existing entity rather than adding a new one.
  155. class_decl.class_id = prev_class_id;
  156. class_decl.type_id = prev.type_id();
  157. // TODO: Validate that the redeclaration doesn't set an access modifier.
  158. }
  159. }
  160. static auto BuildClassDecl(Context& context, Parse::AnyClassDeclId node_id,
  161. bool is_definition)
  162. -> std::tuple<SemIR::ClassId, SemIR::InstId> {
  163. auto name = PopNameComponent(context);
  164. auto name_context = context.decl_name_stack().FinishName(name);
  165. context.node_stack()
  166. .PopAndDiscardSoloNodeId<Parse::NodeKind::ClassIntroducer>();
  167. // Process modifiers.
  168. auto [_, parent_scope_inst] =
  169. context.name_scopes().GetInstIfValid(name_context.parent_scope_id);
  170. auto introducer =
  171. context.decl_introducer_state_stack().Pop<Lex::TokenKind::Class>();
  172. CheckAccessModifiersOnDecl(context, introducer, parent_scope_inst);
  173. auto always_acceptable_modifiers =
  174. KeywordModifierSet::Access | KeywordModifierSet::Extern;
  175. LimitModifiersOnDecl(context, introducer,
  176. always_acceptable_modifiers | KeywordModifierSet::Class);
  177. if (!is_definition) {
  178. LimitModifiersOnNotDefinition(context, introducer,
  179. always_acceptable_modifiers);
  180. }
  181. RestrictExternModifierOnDecl(context, introducer, parent_scope_inst,
  182. is_definition);
  183. bool is_extern = introducer.modifier_set.HasAnyOf(KeywordModifierSet::Extern);
  184. if (introducer.extern_library.has_value()) {
  185. context.TODO(node_id, "extern library");
  186. }
  187. auto inheritance_kind =
  188. introducer.modifier_set.ToEnum<SemIR::Class::InheritanceKind>()
  189. .Case(KeywordModifierSet::Abstract, SemIR::Class::Abstract)
  190. .Case(KeywordModifierSet::Base, SemIR::Class::Base)
  191. .Default(SemIR::Class::Final);
  192. auto decl_block_id = context.inst_block_stack().Pop();
  193. // Add the class declaration.
  194. auto class_decl =
  195. SemIR::ClassDecl{.type_id = SemIR::TypeType::SingletonTypeId,
  196. .class_id = SemIR::ClassId::None,
  197. .decl_block_id = decl_block_id};
  198. auto class_decl_id =
  199. context.AddPlaceholderInst(SemIR::LocIdAndInst(node_id, class_decl));
  200. // TODO: Store state regarding is_extern.
  201. SemIR::Class class_info = {
  202. name_context.MakeEntityWithParamsBase(name, class_decl_id, is_extern,
  203. SemIR::LibraryNameId::None),
  204. {// `.self_type_id` depends on the ClassType, so is set below.
  205. .self_type_id = SemIR::TypeId::None,
  206. .inheritance_kind = inheritance_kind}};
  207. MergeOrAddName(context, node_id, name_context, class_decl_id, class_decl,
  208. class_info, is_definition,
  209. introducer.modifier_set.GetAccessKind());
  210. // Create a new class if this isn't a valid redeclaration.
  211. bool is_new_class = !class_decl.class_id.has_value();
  212. if (is_new_class) {
  213. // TODO: If this is an invalid redeclaration of a non-class entity or there
  214. // was an error in the qualifier, we will have lost track of the class name
  215. // here. We should keep track of it even if the name is invalid.
  216. class_info.generic_id = BuildGenericDecl(context, class_decl_id);
  217. class_decl.class_id = context.classes().Add(class_info);
  218. if (class_info.has_parameters()) {
  219. class_decl.type_id = context.GetGenericClassType(
  220. class_decl.class_id, context.scope_stack().PeekSpecificId());
  221. }
  222. } else {
  223. FinishGenericRedecl(context, class_decl_id, class_info.generic_id);
  224. }
  225. // Write the class ID into the ClassDecl.
  226. context.ReplaceInstBeforeConstantUse(class_decl_id, class_decl);
  227. if (is_new_class) {
  228. // Build the `Self` type using the resulting type constant.
  229. // TODO: Form this as part of building the definition, not as part of the
  230. // declaration.
  231. auto& class_info = context.classes().Get(class_decl.class_id);
  232. auto specific_id =
  233. context.generics().GetSelfSpecific(class_info.generic_id);
  234. class_info.self_type_id = context.GetTypeIdForTypeConstant(TryEvalInst(
  235. context, SemIR::InstId::None,
  236. SemIR::ClassType{.type_id = SemIR::TypeType::SingletonTypeId,
  237. .class_id = class_decl.class_id,
  238. .specific_id = specific_id}));
  239. }
  240. if (!is_definition && context.sem_ir().is_impl() && !is_extern) {
  241. context.definitions_required().push_back(class_decl_id);
  242. }
  243. return {class_decl.class_id, class_decl_id};
  244. }
  245. auto HandleParseNode(Context& context, Parse::ClassDeclId node_id) -> bool {
  246. BuildClassDecl(context, node_id, /*is_definition=*/false);
  247. context.decl_name_stack().PopScope();
  248. return true;
  249. }
  250. auto HandleParseNode(Context& context, Parse::ClassDefinitionStartId node_id)
  251. -> bool {
  252. auto [class_id, class_decl_id] =
  253. BuildClassDecl(context, node_id, /*is_definition=*/true);
  254. auto& class_info = context.classes().Get(class_id);
  255. // Track that this declaration is the definition.
  256. CARBON_CHECK(!class_info.has_definition_started());
  257. class_info.definition_id = class_decl_id;
  258. class_info.scope_id = context.name_scopes().Add(
  259. class_decl_id, SemIR::NameId::None, class_info.parent_scope_id);
  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.field_decls_stack().PushArray();
  272. context.vtable_stack().Push();
  273. // TODO: Handle the case where there's control flow in the class body. For
  274. // example:
  275. //
  276. // class C {
  277. // var v: if true then i32 else f64;
  278. // }
  279. //
  280. // We may need to track a list of instruction blocks here, as we do for a
  281. // function.
  282. class_info.body_block_id = context.inst_block_stack().PeekOrAdd();
  283. return true;
  284. }
  285. // Diagnoses a class-specific declaration appearing outside a class.
  286. static auto DiagnoseClassSpecificDeclOutsideClass(Context& context,
  287. SemIRLoc loc,
  288. Lex::TokenKind tok) -> void {
  289. CARBON_DIAGNOSTIC(ClassSpecificDeclOutsideClass, Error,
  290. "`{0}` declaration outside class", 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 =
  299. context.scope_stack().GetCurrentScopeAs<SemIR::ClassDecl>();
  300. if (!class_scope) {
  301. DiagnoseClassSpecificDeclOutsideClass(context, loc, tok);
  302. }
  303. return class_scope;
  304. }
  305. // Diagnoses a class-specific declaration that is repeated within a class, but
  306. // is not permitted to be repeated.
  307. static auto DiagnoseClassSpecificDeclRepeated(Context& context,
  308. SemIRLoc new_loc,
  309. SemIRLoc prev_loc,
  310. Lex::TokenKind tok) -> void {
  311. CARBON_DIAGNOSTIC(AdaptDeclRepeated, Error,
  312. "multiple `adapt` declarations in class");
  313. CARBON_DIAGNOSTIC(BaseDeclRepeated, Error,
  314. "multiple `base` declarations in class; multiple "
  315. "inheritance is not permitted");
  316. CARBON_DIAGNOSTIC(ClassSpecificDeclPrevious, Note,
  317. "previous `{0}` declaration is here", Lex::TokenKind);
  318. CARBON_CHECK(tok == Lex::TokenKind::Adapt || tok == Lex::TokenKind::Base);
  319. context.emitter()
  320. .Build(new_loc, tok == Lex::TokenKind::Adapt ? AdaptDeclRepeated
  321. : BaseDeclRepeated)
  322. .Note(prev_loc, ClassSpecificDeclPrevious, tok)
  323. .Emit();
  324. }
  325. auto HandleParseNode(Context& context, Parse::AdaptIntroducerId /*node_id*/)
  326. -> bool {
  327. context.decl_introducer_state_stack().Push<Lex::TokenKind::Adapt>();
  328. return true;
  329. }
  330. auto HandleParseNode(Context& context, Parse::AdaptDeclId node_id) -> bool {
  331. auto [adapted_type_node, adapted_type_expr_id] =
  332. context.node_stack().PopExprWithNodeId();
  333. // Process modifiers. `extend` is permitted, no others are allowed.
  334. auto introducer =
  335. context.decl_introducer_state_stack().Pop<Lex::TokenKind::Adapt>();
  336. LimitModifiersOnDecl(context, introducer, KeywordModifierSet::Extend);
  337. auto parent_class_decl =
  338. GetCurrentScopeAsClassOrDiagnose(context, node_id, Lex::TokenKind::Adapt);
  339. if (!parent_class_decl) {
  340. return true;
  341. }
  342. auto& class_info = context.classes().Get(parent_class_decl->class_id);
  343. if (class_info.adapt_id.has_value()) {
  344. DiagnoseClassSpecificDeclRepeated(context, node_id, class_info.adapt_id,
  345. Lex::TokenKind::Adapt);
  346. return true;
  347. }
  348. auto [adapted_inst_id, adapted_type_id] =
  349. ExprAsType(context, node_id, adapted_type_expr_id);
  350. adapted_type_id = AsConcreteType(
  351. context, adapted_type_id, node_id,
  352. [&] {
  353. CARBON_DIAGNOSTIC(IncompleteTypeInAdaptDecl, Error,
  354. "adapted type {0} is an incomplete type",
  355. InstIdAsType);
  356. return context.emitter().Build(node_id, IncompleteTypeInAdaptDecl,
  357. adapted_inst_id);
  358. },
  359. [&] {
  360. CARBON_DIAGNOSTIC(AbstractTypeInAdaptDecl, Error,
  361. "adapted type {0} is an abstract type", InstIdAsType);
  362. return context.emitter().Build(node_id, AbstractTypeInAdaptDecl,
  363. adapted_inst_id);
  364. });
  365. if (adapted_type_id == SemIR::ErrorInst::SingletonTypeId) {
  366. adapted_inst_id = SemIR::ErrorInst::SingletonInstId;
  367. }
  368. // Build a SemIR representation for the declaration.
  369. class_info.adapt_id = context.AddInst<SemIR::AdaptDecl>(
  370. node_id, {.adapted_type_inst_id = adapted_inst_id});
  371. // Extend the class scope with the adapted type's scope if requested.
  372. if (introducer.modifier_set.HasAnyOf(KeywordModifierSet::Extend)) {
  373. auto& class_scope = context.name_scopes().Get(class_info.scope_id);
  374. class_scope.AddExtendedScope(adapted_inst_id);
  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. SemIR::InstId inst_id;
  395. };
  396. constexpr BaseInfo BaseInfo::Error = {
  397. .type_id = SemIR::ErrorInst::SingletonTypeId,
  398. .scope_id = SemIR::NameScopeId::None,
  399. .inst_id = SemIR::ErrorInst::SingletonInstId};
  400. } // namespace
  401. // Diagnoses an attempt to derive from a final type.
  402. static auto DiagnoseBaseIsFinal(Context& context, Parse::NodeId node_id,
  403. SemIR::InstId base_type_inst_id) -> void {
  404. CARBON_DIAGNOSTIC(BaseIsFinal, Error,
  405. "deriving from final type {0}; base type must be an "
  406. "`abstract` or `base` class",
  407. InstIdAsType);
  408. context.emitter().Emit(node_id, BaseIsFinal, base_type_inst_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_inst_id, base_type_id] =
  414. ExprAsType(context, node_id, base_expr_id);
  415. base_type_id = AsCompleteType(context, base_type_id, node_id, [&] {
  416. CARBON_DIAGNOSTIC(IncompleteTypeInBaseDecl, Error,
  417. "base {0} is an incomplete type", InstIdAsType);
  418. return context.emitter().Build(node_id, IncompleteTypeInBaseDecl,
  419. base_type_inst_id);
  420. });
  421. if (base_type_id == SemIR::ErrorInst::SingletonTypeId) {
  422. return BaseInfo::Error;
  423. }
  424. auto* base_class_info = TryGetAsClass(context, base_type_id);
  425. // The base must not be a final class.
  426. if (!base_class_info) {
  427. // For now, we treat all types that aren't introduced by a `class`
  428. // declaration as being final classes.
  429. // TODO: Once we have a better idea of which types are considered to be
  430. // classes, produce a better diagnostic for deriving from a non-class type.
  431. DiagnoseBaseIsFinal(context, node_id, base_type_inst_id);
  432. return BaseInfo::Error;
  433. }
  434. if (base_class_info->inheritance_kind == SemIR::Class::Final) {
  435. DiagnoseBaseIsFinal(context, node_id, base_type_inst_id);
  436. }
  437. CARBON_CHECK(base_class_info->scope_id.has_value(),
  438. "Complete class should have a scope");
  439. return {.type_id = base_type_id,
  440. .scope_id = base_class_info->scope_id,
  441. .inst_id = base_type_inst_id};
  442. }
  443. auto HandleParseNode(Context& context, Parse::BaseDeclId node_id) -> bool {
  444. auto [base_type_node_id, base_type_expr_id] =
  445. context.node_stack().PopExprWithNodeId();
  446. // Process modifiers. `extend` is required, no others are allowed.
  447. auto introducer =
  448. context.decl_introducer_state_stack().Pop<Lex::TokenKind::Base>();
  449. LimitModifiersOnDecl(context, introducer, KeywordModifierSet::Extend);
  450. if (!introducer.modifier_set.HasAnyOf(KeywordModifierSet::Extend)) {
  451. CARBON_DIAGNOSTIC(BaseMissingExtend, Error,
  452. "missing `extend` before `base` declaration");
  453. context.emitter().Emit(node_id, BaseMissingExtend);
  454. }
  455. auto parent_class_decl =
  456. GetCurrentScopeAsClassOrDiagnose(context, node_id, Lex::TokenKind::Base);
  457. if (!parent_class_decl) {
  458. return true;
  459. }
  460. auto& class_info = context.classes().Get(parent_class_decl->class_id);
  461. if (class_info.base_id.has_value()) {
  462. DiagnoseClassSpecificDeclRepeated(context, node_id, class_info.base_id,
  463. Lex::TokenKind::Base);
  464. return true;
  465. }
  466. if (!context.field_decls_stack().PeekArray().empty()) {
  467. // TODO: Add note that includes the first field location as an example.
  468. CARBON_DIAGNOSTIC(
  469. BaseDeclAfterFieldDecl, Error,
  470. "`base` declaration must appear before field declarations");
  471. context.emitter().Emit(node_id, BaseDeclAfterFieldDecl);
  472. return true;
  473. }
  474. auto base_info = CheckBaseType(context, base_type_node_id, base_type_expr_id);
  475. // TODO: Should we diagnose if there are already any fields?
  476. // The `base` value in the class scope has an unbound element type. Instance
  477. // binding will be performed when it's found by name lookup into an instance.
  478. auto field_type_id =
  479. context.GetUnboundElementType(class_info.self_type_id, base_info.type_id);
  480. class_info.base_id = context.AddInst<SemIR::BaseDecl>(
  481. node_id, {.type_id = field_type_id,
  482. .base_type_inst_id = base_info.inst_id,
  483. .index = SemIR::ElementIndex::None});
  484. if (base_info.type_id != SemIR::ErrorInst::SingletonTypeId) {
  485. auto base_class_info = context.classes().Get(
  486. context.types().GetAs<SemIR::ClassType>(base_info.type_id).class_id);
  487. class_info.is_dynamic |= base_class_info.is_dynamic;
  488. }
  489. // Bind the name `base` in the class to the base field.
  490. context.decl_name_stack().AddNameOrDiagnose(
  491. context.decl_name_stack().MakeUnqualifiedName(node_id,
  492. SemIR::NameId::Base),
  493. class_info.base_id, introducer.modifier_set.GetAccessKind());
  494. // Extend the class scope with the base class.
  495. if (introducer.modifier_set.HasAnyOf(KeywordModifierSet::Extend)) {
  496. auto& class_scope = context.name_scopes().Get(class_info.scope_id);
  497. if (base_info.scope_id.has_value()) {
  498. class_scope.AddExtendedScope(base_info.inst_id);
  499. } else {
  500. class_scope.set_has_error();
  501. }
  502. }
  503. return true;
  504. }
  505. // Checks that the specified finished adapter definition is valid and builds and
  506. // returns a corresponding complete type witness instruction.
  507. static auto CheckCompleteAdapterClassType(Context& context,
  508. Parse::NodeId node_id,
  509. SemIR::ClassId class_id)
  510. -> SemIR::InstId {
  511. const auto& class_info = context.classes().Get(class_id);
  512. if (class_info.base_id.has_value()) {
  513. CARBON_DIAGNOSTIC(AdaptWithBase, Error, "adapter with base class");
  514. CARBON_DIAGNOSTIC(AdaptWithBaseHere, Note, "`base` declaration is here");
  515. context.emitter()
  516. .Build(class_info.adapt_id, AdaptWithBase)
  517. .Note(class_info.base_id, AdaptWithBaseHere)
  518. .Emit();
  519. return SemIR::ErrorInst::SingletonInstId;
  520. }
  521. auto field_decls = context.field_decls_stack().PeekArray();
  522. if (!field_decls.empty()) {
  523. CARBON_DIAGNOSTIC(AdaptWithFields, Error, "adapter with fields");
  524. CARBON_DIAGNOSTIC(AdaptWithFieldHere, Note,
  525. "first field declaration is here");
  526. context.emitter()
  527. .Build(class_info.adapt_id, AdaptWithFields)
  528. .Note(field_decls.front(), AdaptWithFieldHere)
  529. .Emit();
  530. return SemIR::ErrorInst::SingletonInstId;
  531. }
  532. for (auto inst_id : context.inst_block_stack().PeekCurrentBlockContents()) {
  533. if (auto function_decl =
  534. context.insts().TryGetAs<SemIR::FunctionDecl>(inst_id)) {
  535. auto& function = context.functions().Get(function_decl->function_id);
  536. if (function.virtual_modifier ==
  537. SemIR::Function::VirtualModifier::Virtual) {
  538. CARBON_DIAGNOSTIC(AdaptWithVirtual, Error,
  539. "adapter with virtual function");
  540. CARBON_DIAGNOSTIC(AdaptWithVirtualHere, Note,
  541. "first virtual function declaration is here");
  542. context.emitter()
  543. .Build(class_info.adapt_id, AdaptWithVirtual)
  544. .Note(inst_id, AdaptWithVirtualHere)
  545. .Emit();
  546. return SemIR::ErrorInst::SingletonInstId;
  547. }
  548. }
  549. }
  550. // The object representation of the adapter is the object representation
  551. // of the adapted type.
  552. auto adapted_type_id =
  553. class_info.GetAdaptedType(context.sem_ir(), SemIR::SpecificId::None);
  554. auto object_repr_id = context.types().GetObjectRepr(adapted_type_id);
  555. return context.AddInst<SemIR::CompleteTypeWitness>(
  556. node_id,
  557. {.type_id = context.GetSingletonType(SemIR::WitnessType::SingletonInstId),
  558. .object_repr_id = object_repr_id});
  559. }
  560. static auto AddStructTypeFields(
  561. Context& context,
  562. llvm::SmallVector<SemIR::StructTypeField>& struct_type_fields)
  563. -> SemIR::StructTypeFieldsId {
  564. for (auto field_decl_id : context.field_decls_stack().PeekArray()) {
  565. auto field_decl = context.insts().GetAs<SemIR::FieldDecl>(field_decl_id);
  566. field_decl.index =
  567. SemIR::ElementIndex{static_cast<int>(struct_type_fields.size())};
  568. context.ReplaceInstPreservingConstantValue(field_decl_id, field_decl);
  569. if (field_decl.type_id == SemIR::ErrorInst::SingletonTypeId) {
  570. struct_type_fields.push_back(
  571. {.name_id = field_decl.name_id,
  572. .type_id = SemIR::ErrorInst::SingletonTypeId});
  573. continue;
  574. }
  575. auto unbound_element_type =
  576. context.sem_ir().types().GetAs<SemIR::UnboundElementType>(
  577. field_decl.type_id);
  578. struct_type_fields.push_back(
  579. {.name_id = field_decl.name_id,
  580. .type_id = unbound_element_type.element_type_id});
  581. }
  582. auto fields_id =
  583. context.struct_type_fields().AddCanonical(struct_type_fields);
  584. return fields_id;
  585. }
  586. // Checks that the specified finished class definition is valid and builds and
  587. // returns a corresponding complete type witness instruction.
  588. static auto CheckCompleteClassType(Context& context, Parse::NodeId node_id,
  589. SemIR::ClassId class_id) -> SemIR::InstId {
  590. auto& class_info = context.classes().Get(class_id);
  591. if (class_info.adapt_id.has_value()) {
  592. return CheckCompleteAdapterClassType(context, node_id, class_id);
  593. }
  594. bool defining_vptr = class_info.is_dynamic;
  595. auto base_type_id =
  596. class_info.GetBaseType(context.sem_ir(), SemIR::SpecificId::None);
  597. SemIR::Class* base_class_info = nullptr;
  598. if (base_type_id.has_value()) {
  599. // TODO: If the base class is template dependent, we will need to decide
  600. // whether to add a vptr as part of instantiation.
  601. base_class_info = TryGetAsClass(context, base_type_id);
  602. if (base_class_info && base_class_info->is_dynamic) {
  603. defining_vptr = false;
  604. }
  605. }
  606. auto field_decls = context.field_decls_stack().PeekArray();
  607. llvm::SmallVector<SemIR::StructTypeField> struct_type_fields;
  608. struct_type_fields.reserve(defining_vptr + class_info.base_id.has_value() +
  609. field_decls.size());
  610. if (defining_vptr) {
  611. struct_type_fields.push_back(
  612. {.name_id = SemIR::NameId::Vptr,
  613. .type_id = context.GetPointerType(
  614. context.GetSingletonType(SemIR::VtableType::SingletonInstId))});
  615. }
  616. if (base_type_id.has_value()) {
  617. auto base_decl = context.insts().GetAs<SemIR::BaseDecl>(class_info.base_id);
  618. base_decl.index =
  619. SemIR::ElementIndex{static_cast<int>(struct_type_fields.size())};
  620. context.ReplaceInstPreservingConstantValue(class_info.base_id, base_decl);
  621. struct_type_fields.push_back(
  622. {.name_id = SemIR::NameId::Base, .type_id = base_type_id});
  623. }
  624. if (class_info.is_dynamic) {
  625. llvm::SmallVector<SemIR::InstId> vtable;
  626. if (!defining_vptr) {
  627. LoadImportRef(context, base_class_info->vtable_id);
  628. auto base_vtable_id = context.constant_values().GetConstantInstId(
  629. base_class_info->vtable_id);
  630. auto base_vtable_inst_block =
  631. context.inst_blocks().Get(context.insts()
  632. .GetAs<SemIR::Vtable>(base_vtable_id)
  633. .virtual_functions_id);
  634. // TODO: Avoid quadratic search. Perhaps build a map from `NameId` to the
  635. // elements of the top of `vtable_stack`.
  636. for (auto fn_decl_id : base_vtable_inst_block) {
  637. auto fn_decl = GetCalleeFunction(context.sem_ir(), fn_decl_id);
  638. const auto& fn = context.functions().Get(fn_decl.function_id);
  639. for (auto override_fn_decl_id :
  640. context.vtable_stack().PeekCurrentBlockContents()) {
  641. auto override_fn_decl =
  642. context.insts().GetAs<SemIR::FunctionDecl>(override_fn_decl_id);
  643. const auto& override_fn =
  644. context.functions().Get(override_fn_decl.function_id);
  645. if (override_fn.virtual_modifier ==
  646. SemIR::FunctionFields::VirtualModifier::Impl &&
  647. override_fn.name_id == fn.name_id) {
  648. // TODO: Support generic base classes, rather than passing
  649. // `SpecificId::None`.
  650. CheckFunctionTypeMatches(context, override_fn, fn,
  651. SemIR::SpecificId::None,
  652. /*check_syntax=*/false);
  653. fn_decl_id = override_fn_decl_id;
  654. }
  655. }
  656. vtable.push_back(fn_decl_id);
  657. }
  658. }
  659. for (auto inst_id : context.vtable_stack().PeekCurrentBlockContents()) {
  660. auto fn_decl = context.insts().GetAs<SemIR::FunctionDecl>(inst_id);
  661. const auto& fn = context.functions().Get(fn_decl.function_id);
  662. if (fn.virtual_modifier != SemIR::FunctionFields::VirtualModifier::Impl) {
  663. vtable.push_back(inst_id);
  664. }
  665. }
  666. class_info.vtable_id = context.AddInst<SemIR::Vtable>(
  667. node_id, {.type_id = context.GetSingletonType(
  668. SemIR::VtableType::SingletonInstId),
  669. .virtual_functions_id = context.inst_blocks().Add(vtable)});
  670. }
  671. return context.AddInst<SemIR::CompleteTypeWitness>(
  672. node_id,
  673. {.type_id = context.GetSingletonType(SemIR::WitnessType::SingletonInstId),
  674. .object_repr_id = context.GetStructType(
  675. AddStructTypeFields(context, struct_type_fields))});
  676. }
  677. auto HandleParseNode(Context& context, Parse::ClassDefinitionId node_id)
  678. -> bool {
  679. auto class_id =
  680. context.node_stack().Pop<Parse::NodeKind::ClassDefinitionStart>();
  681. // The class type is now fully defined. Compute its object representation.
  682. auto complete_type_witness_id =
  683. CheckCompleteClassType(context, node_id, class_id);
  684. auto& class_info = context.classes().Get(class_id);
  685. class_info.complete_type_witness_id = complete_type_witness_id;
  686. context.inst_block_stack().Pop();
  687. context.field_decls_stack().PopArray();
  688. context.vtable_stack().Pop();
  689. FinishGenericDefinition(context, class_info.generic_id);
  690. // The decl_name_stack and scopes are popped by `ProcessNodeIds`.
  691. return true;
  692. }
  693. } // namespace Carbon::Check