handle_class.cpp 31 KB

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