handle_class.cpp 32 KB

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