handle_class.cpp 29 KB

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