handle_class.cpp 31 KB

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