handle_class.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  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/class.h"
  6. #include "toolchain/check/context.h"
  7. #include "toolchain/check/convert.h"
  8. #include "toolchain/check/decl_name_stack.h"
  9. #include "toolchain/check/merge.h"
  10. #include "toolchain/check/modifiers.h"
  11. #include "toolchain/sem_ir/ids.h"
  12. #include "toolchain/sem_ir/typed_insts.h"
  13. namespace Carbon::Check {
  14. // If `type_id` is a class type, get its corresponding `SemIR::Class` object.
  15. // Otherwise returns `nullptr`.
  16. static auto TryGetAsClass(Context& context, SemIR::TypeId type_id)
  17. -> SemIR::Class* {
  18. auto class_type = context.types().TryGetAs<SemIR::ClassType>(type_id);
  19. if (!class_type) {
  20. return nullptr;
  21. }
  22. return &context.classes().Get(class_type->class_id);
  23. }
  24. auto HandleClassIntroducer(Context& context, Parse::ClassIntroducerId node_id)
  25. -> bool {
  26. // Create an instruction block to hold the instructions created as part of the
  27. // class signature, such as generic parameters.
  28. context.inst_block_stack().Push();
  29. // Push the bracketing node.
  30. context.node_stack().Push(node_id);
  31. // Optional modifiers and the name follow.
  32. context.decl_state_stack().Push(DeclState::Class);
  33. context.decl_name_stack().PushScopeAndStartName();
  34. return true;
  35. }
  36. // Adds the name to name lookup. If there's a conflict, tries to merge. May
  37. // update class_decl and class_info when merging.
  38. static auto MergeOrAddName(Context& context, Parse::AnyClassDeclId node_id,
  39. const DeclNameStack::NameContext& name_context,
  40. SemIR::InstId class_decl_id,
  41. SemIR::ClassDecl& class_decl,
  42. SemIR::Class& class_info, bool is_definition,
  43. bool is_extern) -> void {
  44. auto prev_id =
  45. context.decl_name_stack().LookupOrAddName(name_context, class_decl_id);
  46. if (!prev_id.is_valid()) {
  47. return;
  48. }
  49. auto prev_class_id = SemIR::ClassId::Invalid;
  50. auto prev_import_ir_id = SemIR::ImportIRId::Invalid;
  51. CARBON_KIND_SWITCH(context.insts().Get(prev_id)) {
  52. case CARBON_KIND(SemIR::ClassDecl class_decl): {
  53. prev_class_id = class_decl.class_id;
  54. break;
  55. }
  56. case CARBON_KIND(SemIR::ImportRefLoaded import_ref): {
  57. auto import_ir_inst =
  58. context.import_ir_insts().Get(import_ref.import_ir_inst_id);
  59. // Verify the decl so that things like aliases are name conflicts.
  60. const auto* import_ir =
  61. context.import_irs().Get(import_ir_inst.ir_id).sem_ir;
  62. if (!import_ir->insts().Is<SemIR::ClassDecl>(import_ir_inst.inst_id)) {
  63. break;
  64. }
  65. // Use the type to get the ID.
  66. if (auto class_type = context.insts().TryGetAs<SemIR::ClassType>(
  67. context.constant_values().Get(prev_id).inst_id())) {
  68. prev_class_id = class_type->class_id;
  69. prev_import_ir_id = import_ir_inst.ir_id;
  70. }
  71. break;
  72. }
  73. default:
  74. break;
  75. }
  76. if (!prev_class_id.is_valid()) {
  77. // This is a redeclaration of something other than a class.
  78. context.DiagnoseDuplicateName(class_decl_id, prev_id);
  79. return;
  80. }
  81. // TODO: Fix prev_is_extern logic.
  82. if (MergeClassRedecl(context, node_id, class_info,
  83. /*new_is_import=*/false, is_definition, is_extern,
  84. prev_class_id, /*prev_is_extern=*/false,
  85. prev_import_ir_id)) {
  86. // When merging, use the existing entity rather than adding a new one.
  87. class_decl.class_id = prev_class_id;
  88. }
  89. }
  90. static auto BuildClassDecl(Context& context, Parse::AnyClassDeclId node_id,
  91. bool is_definition)
  92. -> std::tuple<SemIR::ClassId, SemIR::InstId> {
  93. auto param_refs_id =
  94. context.node_stack().PopIf<Parse::NodeKind::TuplePattern>().value_or(
  95. SemIR::InstBlockId::Invalid);
  96. auto implicit_param_refs_id =
  97. context.node_stack().PopIf<Parse::NodeKind::ImplicitParamList>().value_or(
  98. SemIR::InstBlockId::Invalid);
  99. auto name_context = context.decl_name_stack().FinishName();
  100. context.node_stack()
  101. .PopAndDiscardSoloNodeId<Parse::NodeKind::ClassIntroducer>();
  102. // Process modifiers.
  103. CheckAccessModifiersOnDecl(context, Lex::TokenKind::Class,
  104. name_context.target_scope_id);
  105. LimitModifiersOnDecl(context,
  106. KeywordModifierSet::Class | KeywordModifierSet::Access |
  107. KeywordModifierSet::Extern,
  108. Lex::TokenKind::Class);
  109. RestrictExternModifierOnDecl(context, Lex::TokenKind::Class,
  110. name_context.target_scope_id, is_definition);
  111. auto modifiers = context.decl_state_stack().innermost().modifier_set;
  112. if (!!(modifiers & KeywordModifierSet::Access)) {
  113. context.TODO(context.decl_state_stack().innermost().modifier_node_id(
  114. ModifierOrder::Access),
  115. "access modifier");
  116. }
  117. bool is_extern = !!(modifiers & KeywordModifierSet::Extern);
  118. auto inheritance_kind =
  119. !!(modifiers & KeywordModifierSet::Abstract) ? SemIR::Class::Abstract
  120. : !!(modifiers & KeywordModifierSet::Base) ? SemIR::Class::Base
  121. : SemIR::Class::Final;
  122. context.decl_state_stack().Pop(DeclState::Class);
  123. auto decl_block_id = context.inst_block_stack().Pop();
  124. // Add the class declaration.
  125. auto class_decl = SemIR::ClassDecl{SemIR::TypeId::TypeType,
  126. SemIR::ClassId::Invalid, decl_block_id};
  127. auto class_decl_id = context.AddPlaceholderInst({node_id, class_decl});
  128. // TODO: Store state regarding is_extern.
  129. SemIR::Class class_info = {
  130. .name_id = name_context.name_id_for_new_inst(),
  131. .enclosing_scope_id = name_context.enclosing_scope_id_for_new_inst(),
  132. .implicit_param_refs_id = implicit_param_refs_id,
  133. .param_refs_id = param_refs_id,
  134. // `.self_type_id` depends on the ClassType, so is set below.
  135. .self_type_id = SemIR::TypeId::Invalid,
  136. .decl_id = class_decl_id,
  137. .inheritance_kind = inheritance_kind};
  138. MergeOrAddName(context, node_id, name_context, class_decl_id, class_decl,
  139. class_info, is_definition, is_extern);
  140. // Create a new class if this isn't a valid redeclaration.
  141. bool is_new_class = !class_decl.class_id.is_valid();
  142. if (is_new_class) {
  143. // TODO: If this is an invalid redeclaration of a non-class entity or there
  144. // was an error in the qualifier, we will have lost track of the class name
  145. // here. We should keep track of it even if the name is invalid.
  146. class_decl.class_id = context.classes().Add(class_info);
  147. }
  148. // Write the class ID into the ClassDecl.
  149. context.ReplaceInstBeforeConstantUse(class_decl_id, class_decl);
  150. if (is_new_class) {
  151. // Build the `Self` type using the resulting type constant.
  152. auto& class_info = context.classes().Get(class_decl.class_id);
  153. class_info.self_type_id = context.GetTypeIdForTypeInst(class_decl_id);
  154. }
  155. return {class_decl.class_id, class_decl_id};
  156. }
  157. auto HandleClassDecl(Context& context, Parse::ClassDeclId node_id) -> bool {
  158. BuildClassDecl(context, node_id, /*is_definition=*/false);
  159. context.decl_name_stack().PopScope();
  160. return true;
  161. }
  162. auto HandleClassDefinitionStart(Context& context,
  163. Parse::ClassDefinitionStartId node_id) -> bool {
  164. auto [class_id, class_decl_id] =
  165. BuildClassDecl(context, node_id, /*is_definition=*/true);
  166. auto& class_info = context.classes().Get(class_id);
  167. // Track that this declaration is the definition.
  168. if (!class_info.is_defined()) {
  169. class_info.definition_id = class_decl_id;
  170. class_info.scope_id = context.name_scopes().Add(
  171. class_decl_id, SemIR::NameId::Invalid, class_info.enclosing_scope_id);
  172. }
  173. // Enter the class scope.
  174. context.scope_stack().Push(class_decl_id, class_info.scope_id);
  175. // Introduce `Self`.
  176. context.name_scopes()
  177. .Get(class_info.scope_id)
  178. .names.insert({SemIR::NameId::SelfType,
  179. context.types().GetInstId(class_info.self_type_id)});
  180. context.inst_block_stack().Push();
  181. context.node_stack().Push(node_id, class_id);
  182. context.args_type_info_stack().Push();
  183. // TODO: Handle the case where there's control flow in the class body. For
  184. // example:
  185. //
  186. // class C {
  187. // var v: if true then i32 else f64;
  188. // }
  189. //
  190. // We may need to track a list of instruction blocks here, as we do for a
  191. // function.
  192. class_info.body_block_id = context.inst_block_stack().PeekOrAdd();
  193. return true;
  194. }
  195. // Diagnoses a class-specific declaration appearing outside a class.
  196. static auto DiagnoseClassSpecificDeclOutsideClass(Context& context,
  197. SemIRLoc loc,
  198. Lex::TokenKind tok) -> void {
  199. CARBON_DIAGNOSTIC(ClassSpecificDeclOutsideClass, Error,
  200. "`{0}` declaration can only be used in a class.",
  201. Lex::TokenKind);
  202. context.emitter().Emit(loc, ClassSpecificDeclOutsideClass, tok);
  203. }
  204. // Returns the declaration of the immediately-enclosing class scope, or
  205. // diagonses if there isn't one.
  206. static auto GetEnclosingClassOrDiagnose(Context& context, SemIRLoc loc,
  207. Lex::TokenKind tok)
  208. -> std::optional<SemIR::ClassDecl> {
  209. auto class_scope = context.GetCurrentScopeAs<SemIR::ClassDecl>();
  210. if (!class_scope) {
  211. DiagnoseClassSpecificDeclOutsideClass(context, loc, tok);
  212. }
  213. return class_scope;
  214. }
  215. // Diagnoses a class-specific declaration that is repeated within a class, but
  216. // is not permitted to be repeated.
  217. static auto DiagnoseClassSpecificDeclRepeated(Context& context,
  218. SemIRLoc new_loc,
  219. SemIRLoc prev_loc,
  220. Lex::TokenKind tok) -> void {
  221. CARBON_DIAGNOSTIC(ClassSpecificDeclRepeated, Error,
  222. "Multiple `{0}` declarations in class.{1}", Lex::TokenKind,
  223. std::string);
  224. const llvm::StringRef extra = tok == Lex::TokenKind::Base
  225. ? " Multiple inheritance is not permitted."
  226. : "";
  227. CARBON_DIAGNOSTIC(ClassSpecificDeclPrevious, Note,
  228. "Previous `{0}` declaration is here.", Lex::TokenKind);
  229. context.emitter()
  230. .Build(new_loc, ClassSpecificDeclRepeated, tok, extra.str())
  231. .Note(prev_loc, ClassSpecificDeclPrevious, tok)
  232. .Emit();
  233. }
  234. auto HandleAdaptIntroducer(Context& context,
  235. Parse::AdaptIntroducerId /*node_id*/) -> bool {
  236. context.decl_state_stack().Push(DeclState::Adapt);
  237. return true;
  238. }
  239. auto HandleAdaptDecl(Context& context, Parse::AdaptDeclId node_id) -> bool {
  240. auto [adapted_type_node, adapted_type_expr_id] =
  241. context.node_stack().PopExprWithNodeId();
  242. // Process modifiers. `extend` is permitted, no others are allowed.
  243. LimitModifiersOnDecl(context, KeywordModifierSet::Extend,
  244. Lex::TokenKind::Adapt);
  245. auto modifiers = context.decl_state_stack().innermost().modifier_set;
  246. context.decl_state_stack().Pop(DeclState::Adapt);
  247. auto enclosing_class_decl =
  248. GetEnclosingClassOrDiagnose(context, node_id, Lex::TokenKind::Adapt);
  249. if (!enclosing_class_decl) {
  250. return true;
  251. }
  252. auto& class_info = context.classes().Get(enclosing_class_decl->class_id);
  253. if (class_info.adapt_id.is_valid()) {
  254. DiagnoseClassSpecificDeclRepeated(context, node_id, class_info.adapt_id,
  255. Lex::TokenKind::Adapt);
  256. return true;
  257. }
  258. auto adapted_type_id = ExprAsType(context, node_id, adapted_type_expr_id);
  259. adapted_type_id = context.AsCompleteType(adapted_type_id, [&] {
  260. CARBON_DIAGNOSTIC(IncompleteTypeInAdaptDecl, Error,
  261. "Adapted type `{0}` is an incomplete type.",
  262. SemIR::TypeId);
  263. return context.emitter().Build(node_id, IncompleteTypeInAdaptDecl,
  264. adapted_type_id);
  265. });
  266. // Build a SemIR representation for the declaration.
  267. class_info.adapt_id =
  268. context.AddInst({node_id, SemIR::AdaptDecl{adapted_type_id}});
  269. // Extend the class scope with the adapted type's scope if requested.
  270. if (!!(modifiers & KeywordModifierSet::Extend)) {
  271. auto extended_scope_id = SemIR::NameScopeId::Invalid;
  272. if (adapted_type_id == SemIR::TypeId::Error) {
  273. // Recover by not extending any scope. We instead set has_error to true
  274. // below.
  275. } else if (auto* adapted_class_info =
  276. TryGetAsClass(context, adapted_type_id)) {
  277. extended_scope_id = adapted_class_info->scope_id;
  278. CARBON_CHECK(adapted_class_info->scope_id.is_valid())
  279. << "Complete class should have a scope";
  280. } else {
  281. // TODO: Accept any type that has a scope.
  282. context.TODO(node_id, "extending non-class type");
  283. }
  284. auto& class_scope = context.name_scopes().Get(class_info.scope_id);
  285. if (extended_scope_id.is_valid()) {
  286. class_scope.extended_scopes.push_back(extended_scope_id);
  287. } else {
  288. class_scope.has_error = true;
  289. }
  290. }
  291. return true;
  292. }
  293. auto HandleBaseIntroducer(Context& context, Parse::BaseIntroducerId /*node_id*/)
  294. -> bool {
  295. context.decl_state_stack().Push(DeclState::Base);
  296. return true;
  297. }
  298. auto HandleBaseColon(Context& /*context*/, Parse::BaseColonId /*node_id*/)
  299. -> bool {
  300. return true;
  301. }
  302. namespace {
  303. // Information gathered about a base type specified in a `base` declaration.
  304. struct BaseInfo {
  305. // A `BaseInfo` representing an erroneous base.
  306. static const BaseInfo Error;
  307. SemIR::TypeId type_id;
  308. SemIR::NameScopeId scope_id;
  309. };
  310. constexpr BaseInfo BaseInfo::Error = {.type_id = SemIR::TypeId::Error,
  311. .scope_id = SemIR::NameScopeId::Invalid};
  312. } // namespace
  313. // Diagnoses an attempt to derive from a final type.
  314. static auto DiagnoseBaseIsFinal(Context& context, Parse::NodeId node_id,
  315. SemIR::TypeId base_type_id) -> void {
  316. CARBON_DIAGNOSTIC(BaseIsFinal, Error,
  317. "Deriving from final type `{0}`. Base type must be an "
  318. "`abstract` or `base` class.",
  319. SemIR::TypeId);
  320. context.emitter().Emit(node_id, BaseIsFinal, base_type_id);
  321. }
  322. // Checks that the specified base type is valid.
  323. static auto CheckBaseType(Context& context, Parse::NodeId node_id,
  324. SemIR::InstId base_expr_id) -> BaseInfo {
  325. auto base_type_id = ExprAsType(context, node_id, base_expr_id);
  326. base_type_id = context.AsCompleteType(base_type_id, [&] {
  327. CARBON_DIAGNOSTIC(IncompleteTypeInBaseDecl, Error,
  328. "Base `{0}` is an incomplete type.", SemIR::TypeId);
  329. return context.emitter().Build(node_id, IncompleteTypeInBaseDecl,
  330. base_type_id);
  331. });
  332. if (base_type_id == SemIR::TypeId::Error) {
  333. return BaseInfo::Error;
  334. }
  335. auto* base_class_info = TryGetAsClass(context, base_type_id);
  336. // The base must not be a final class.
  337. if (!base_class_info) {
  338. // For now, we treat all types that aren't introduced by a `class`
  339. // declaration as being final classes.
  340. // TODO: Once we have a better idea of which types are considered to be
  341. // classes, produce a better diagnostic for deriving from a non-class type.
  342. DiagnoseBaseIsFinal(context, node_id, base_type_id);
  343. return BaseInfo::Error;
  344. }
  345. if (base_class_info->inheritance_kind == SemIR::Class::Final) {
  346. DiagnoseBaseIsFinal(context, node_id, base_type_id);
  347. }
  348. CARBON_CHECK(base_class_info->scope_id.is_valid())
  349. << "Complete class should have a scope";
  350. return {.type_id = base_type_id, .scope_id = base_class_info->scope_id};
  351. }
  352. auto HandleBaseDecl(Context& context, Parse::BaseDeclId node_id) -> bool {
  353. auto [base_type_node_id, base_type_expr_id] =
  354. context.node_stack().PopExprWithNodeId();
  355. // Process modifiers. `extend` is required, no others are allowed.
  356. LimitModifiersOnDecl(context, KeywordModifierSet::Extend,
  357. Lex::TokenKind::Base);
  358. auto modifiers = context.decl_state_stack().innermost().modifier_set;
  359. if (!(modifiers & KeywordModifierSet::Extend)) {
  360. CARBON_DIAGNOSTIC(BaseMissingExtend, Error,
  361. "Missing `extend` before `base` declaration in class.");
  362. context.emitter().Emit(node_id, BaseMissingExtend);
  363. }
  364. context.decl_state_stack().Pop(DeclState::Base);
  365. auto enclosing_class_decl =
  366. GetEnclosingClassOrDiagnose(context, node_id, Lex::TokenKind::Base);
  367. if (!enclosing_class_decl) {
  368. return true;
  369. }
  370. auto& class_info = context.classes().Get(enclosing_class_decl->class_id);
  371. if (class_info.base_id.is_valid()) {
  372. DiagnoseClassSpecificDeclRepeated(context, node_id, class_info.base_id,
  373. Lex::TokenKind::Base);
  374. return true;
  375. }
  376. auto base_info = CheckBaseType(context, base_type_node_id, base_type_expr_id);
  377. // The `base` value in the class scope has an unbound element type. Instance
  378. // binding will be performed when it's found by name lookup into an instance.
  379. auto field_type_id =
  380. context.GetUnboundElementType(class_info.self_type_id, base_info.type_id);
  381. class_info.base_id = context.AddInst(
  382. {node_id,
  383. SemIR::BaseDecl{field_type_id, base_info.type_id,
  384. SemIR::ElementIndex(context.args_type_info_stack()
  385. .PeekCurrentBlockContents()
  386. .size())}});
  387. // Add a corresponding field to the object representation of the class.
  388. // TODO: Consider whether we want to use `partial T` here.
  389. // TODO: Should we diagnose if there are already any fields?
  390. context.args_type_info_stack().AddInstId(context.AddInstInNoBlock(
  391. {node_id,
  392. SemIR::StructTypeField{SemIR::NameId::Base, base_info.type_id}}));
  393. // Bind the name `base` in the class to the base field.
  394. context.decl_name_stack().AddNameOrDiagnoseDuplicate(
  395. context.decl_name_stack().MakeUnqualifiedName(node_id,
  396. SemIR::NameId::Base),
  397. class_info.base_id);
  398. // Extend the class scope with the base class.
  399. if (!!(modifiers & KeywordModifierSet::Extend)) {
  400. auto& class_scope = context.name_scopes().Get(class_info.scope_id);
  401. if (base_info.scope_id.is_valid()) {
  402. class_scope.extended_scopes.push_back(base_info.scope_id);
  403. } else {
  404. class_scope.has_error = true;
  405. }
  406. }
  407. return true;
  408. }
  409. auto HandleClassDefinition(Context& context,
  410. Parse::ClassDefinitionId /*node_id*/) -> bool {
  411. auto fields_id = context.args_type_info_stack().Pop();
  412. auto class_id =
  413. context.node_stack().Pop<Parse::NodeKind::ClassDefinitionStart>();
  414. context.inst_block_stack().Pop();
  415. // The class type is now fully defined. Compute its object representation.
  416. auto& class_info = context.classes().Get(class_id);
  417. if (class_info.adapt_id.is_valid()) {
  418. class_info.object_repr_id = SemIR::TypeId::Error;
  419. if (class_info.base_id.is_valid()) {
  420. CARBON_DIAGNOSTIC(AdaptWithBase, Error,
  421. "Adapter cannot have a base class.");
  422. CARBON_DIAGNOSTIC(AdaptBaseHere, Note, "`base` declaration is here.");
  423. context.emitter()
  424. .Build(class_info.adapt_id, AdaptWithBase)
  425. .Note(class_info.base_id, AdaptBaseHere)
  426. .Emit();
  427. } else if (!context.inst_blocks().Get(fields_id).empty()) {
  428. auto first_field_id = context.inst_blocks().Get(fields_id).front();
  429. CARBON_DIAGNOSTIC(AdaptWithFields, Error, "Adapter cannot have fields.");
  430. CARBON_DIAGNOSTIC(AdaptFieldHere, Note,
  431. "First field declaration is here.");
  432. context.emitter()
  433. .Build(class_info.adapt_id, AdaptWithFields)
  434. .Note(first_field_id, AdaptFieldHere)
  435. .Emit();
  436. } else {
  437. // The object representation of the adapter is the object representation
  438. // of the adapted type.
  439. auto adapted_type_id = context.insts()
  440. .GetAs<SemIR::AdaptDecl>(class_info.adapt_id)
  441. .adapted_type_id;
  442. // If we adapt an adapter, directly track the non-adapter type we're
  443. // adapting so that we have constant-time access to it.
  444. if (auto adapted_class =
  445. context.types().TryGetAs<SemIR::ClassType>(adapted_type_id)) {
  446. auto& adapted_class_info =
  447. context.classes().Get(adapted_class->class_id);
  448. if (adapted_class_info.adapt_id.is_valid()) {
  449. adapted_type_id = adapted_class_info.object_repr_id;
  450. }
  451. }
  452. class_info.object_repr_id = adapted_type_id;
  453. }
  454. } else {
  455. class_info.object_repr_id = context.GetStructType(fields_id);
  456. }
  457. // The decl_name_stack and scopes are popped by `ProcessNodeIds`.
  458. return true;
  459. }
  460. } // namespace Carbon::Check