handle_class.cpp 31 KB

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