handle_class.cpp 20 KB

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