handle_class.cpp 31 KB

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