handle_class.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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/check/context.h"
  5. #include "toolchain/check/convert.h"
  6. #include "toolchain/check/modifiers.h"
  7. #include "toolchain/sem_ir/typed_insts.h"
  8. namespace Carbon::Check {
  9. auto HandleClassIntroducer(Context& context, Parse::ClassIntroducerId node_id)
  10. -> bool {
  11. // Create an instruction block to hold the instructions created as part of the
  12. // class signature, such as generic parameters.
  13. context.inst_block_stack().Push();
  14. // Push the bracketing node.
  15. context.node_stack().Push(node_id);
  16. // Optional modifiers and the name follow.
  17. context.decl_state_stack().Push(DeclState::Class);
  18. context.decl_name_stack().PushScopeAndStartName();
  19. return true;
  20. }
  21. static auto BuildClassDecl(Context& context, Parse::AnyClassDeclId node_id)
  22. -> std::tuple<SemIR::ClassId, SemIR::InstId> {
  23. if (context.node_stack().PopIf<Parse::NodeKind::TuplePattern>()) {
  24. context.TODO(node_id, "generic class");
  25. }
  26. if (context.node_stack().PopIf<Parse::NodeKind::ImplicitParamList>()) {
  27. context.TODO(node_id, "generic class");
  28. }
  29. auto name_context = context.decl_name_stack().FinishName();
  30. context.node_stack()
  31. .PopAndDiscardSoloNodeId<Parse::NodeKind::ClassIntroducer>();
  32. // Process modifiers.
  33. CheckAccessModifiersOnDecl(context, Lex::TokenKind::Class,
  34. name_context.target_scope_id);
  35. LimitModifiersOnDecl(context,
  36. KeywordModifierSet::Class | KeywordModifierSet::Access,
  37. Lex::TokenKind::Class);
  38. auto modifiers = context.decl_state_stack().innermost().modifier_set;
  39. if (!!(modifiers & KeywordModifierSet::Access)) {
  40. context.TODO(context.decl_state_stack().innermost().modifier_node_id(
  41. ModifierOrder::Access),
  42. "access modifier");
  43. }
  44. auto inheritance_kind =
  45. !!(modifiers & KeywordModifierSet::Abstract) ? SemIR::Class::Abstract
  46. : !!(modifiers & KeywordModifierSet::Base) ? SemIR::Class::Base
  47. : SemIR::Class::Final;
  48. context.decl_state_stack().Pop(DeclState::Class);
  49. auto decl_block_id = context.inst_block_stack().Pop();
  50. // Add the class declaration.
  51. auto class_decl = SemIR::ClassDecl{SemIR::TypeId::TypeType,
  52. SemIR::ClassId::Invalid, decl_block_id};
  53. auto class_decl_id = context.AddPlaceholderInst({node_id, class_decl});
  54. // Check whether this is a redeclaration.
  55. auto existing_id =
  56. context.decl_name_stack().LookupOrAddName(name_context, class_decl_id);
  57. if (existing_id.is_valid()) {
  58. if (auto existing_class_decl =
  59. context.insts().Get(existing_id).TryAs<SemIR::ClassDecl>()) {
  60. // This is a redeclaration of an existing class.
  61. class_decl.class_id = existing_class_decl->class_id;
  62. auto& class_info = context.classes().Get(class_decl.class_id);
  63. // The introducer kind must match the previous declaration.
  64. // TODO: The rule here is not yet decided. See #3384.
  65. if (class_info.inheritance_kind != inheritance_kind) {
  66. CARBON_DIAGNOSTIC(ClassRedeclarationDifferentIntroducer, Error,
  67. "Class redeclared with different inheritance kind.");
  68. CARBON_DIAGNOSTIC(ClassRedeclarationDifferentIntroducerPrevious, Note,
  69. "Previously declared here.");
  70. context.emitter()
  71. .Build(node_id, ClassRedeclarationDifferentIntroducer)
  72. .Note(existing_id, ClassRedeclarationDifferentIntroducerPrevious)
  73. .Emit();
  74. }
  75. // TODO: Check that the generic parameter list agrees with the prior
  76. // declaration.
  77. } else {
  78. // This is a redeclaration of something other than a class.
  79. context.DiagnoseDuplicateName(class_decl_id, existing_id);
  80. }
  81. }
  82. // Create a new class if this isn't a valid redeclaration.
  83. bool is_new_class = !class_decl.class_id.is_valid();
  84. if (is_new_class) {
  85. // TODO: If this is an invalid redeclaration of a non-class entity or there
  86. // was an error in the qualifier, we will have lost track of the class name
  87. // here. We should keep track of it even if the name is invalid.
  88. class_decl.class_id = context.classes().Add(
  89. {.name_id = name_context.name_id_for_new_inst(),
  90. .enclosing_scope_id = name_context.enclosing_scope_id_for_new_inst(),
  91. // `.self_type_id` depends on the ClassType, so is set below.
  92. .self_type_id = SemIR::TypeId::Invalid,
  93. .decl_id = class_decl_id,
  94. .inheritance_kind = inheritance_kind});
  95. }
  96. // Write the class ID into the ClassDecl.
  97. context.ReplaceInstBeforeConstantUse(class_decl_id, {node_id, class_decl});
  98. if (is_new_class) {
  99. // Build the `Self` type using the resulting type constant.
  100. auto& class_info = context.classes().Get(class_decl.class_id);
  101. class_info.self_type_id = context.GetTypeIdForTypeInst(class_decl_id);
  102. }
  103. return {class_decl.class_id, class_decl_id};
  104. }
  105. auto HandleClassDecl(Context& context, Parse::ClassDeclId node_id) -> bool {
  106. BuildClassDecl(context, node_id);
  107. context.decl_name_stack().PopScope();
  108. return true;
  109. }
  110. auto HandleClassDefinitionStart(Context& context,
  111. Parse::ClassDefinitionStartId node_id) -> bool {
  112. auto [class_id, class_decl_id] = BuildClassDecl(context, node_id);
  113. auto& class_info = context.classes().Get(class_id);
  114. // Track that this declaration is the definition.
  115. if (class_info.is_defined()) {
  116. CARBON_DIAGNOSTIC(ClassRedefinition, Error, "Redefinition of class {0}.",
  117. SemIR::NameId);
  118. CARBON_DIAGNOSTIC(ClassPreviousDefinition, Note,
  119. "Previous definition was here.");
  120. context.emitter()
  121. .Build(node_id, ClassRedefinition, class_info.name_id)
  122. .Note(class_info.definition_id, ClassPreviousDefinition)
  123. .Emit();
  124. } else {
  125. class_info.definition_id = class_decl_id;
  126. class_info.scope_id = context.name_scopes().Add(
  127. class_decl_id, SemIR::NameId::Invalid, class_info.enclosing_scope_id);
  128. }
  129. // Enter the class scope.
  130. context.scope_stack().Push(class_decl_id, class_info.scope_id);
  131. // Introduce `Self`.
  132. context.name_scopes()
  133. .Get(class_info.scope_id)
  134. .names.insert({SemIR::NameId::SelfType,
  135. context.types().GetInstId(class_info.self_type_id)});
  136. context.inst_block_stack().Push();
  137. context.node_stack().Push(node_id, class_id);
  138. context.args_type_info_stack().Push();
  139. // TODO: Handle the case where there's control flow in the class body. For
  140. // example:
  141. //
  142. // class C {
  143. // var v: if true then i32 else f64;
  144. // }
  145. //
  146. // We may need to track a list of instruction blocks here, as we do for a
  147. // function.
  148. class_info.body_block_id = context.inst_block_stack().PeekOrAdd();
  149. return true;
  150. }
  151. auto HandleBaseIntroducer(Context& context, Parse::BaseIntroducerId /*node_id*/)
  152. -> bool {
  153. context.decl_state_stack().Push(DeclState::Base);
  154. return true;
  155. }
  156. auto HandleBaseColon(Context& /*context*/, Parse::BaseColonId /*node_id*/)
  157. -> bool {
  158. return true;
  159. }
  160. namespace {
  161. // Information gathered about a base type specified in a `base` declaration.
  162. struct BaseInfo {
  163. // A `BaseInfo` representing an erroneous base.
  164. static const BaseInfo Error;
  165. SemIR::TypeId type_id;
  166. SemIR::NameScopeId scope_id;
  167. };
  168. constexpr BaseInfo BaseInfo::Error = {.type_id = SemIR::TypeId::Error,
  169. .scope_id = SemIR::NameScopeId::Invalid};
  170. } // namespace
  171. // If `type_id` is a class type, get its corresponding `SemIR::Class` object.
  172. // Otherwise returns `nullptr`.
  173. static auto TryGetAsClass(Context& context, SemIR::TypeId type_id)
  174. -> SemIR::Class* {
  175. auto class_type = context.types().TryGetAs<SemIR::ClassType>(type_id);
  176. if (!class_type) {
  177. return nullptr;
  178. }
  179. return &context.classes().Get(class_type->class_id);
  180. }
  181. // Diagnoses an attempt to derive from a final type.
  182. static auto DiagnoseBaseIsFinal(Context& context, Parse::NodeId node_id,
  183. SemIR::TypeId base_type_id) -> void {
  184. CARBON_DIAGNOSTIC(BaseIsFinal, Error,
  185. "Deriving from final type `{0}`. Base type must be an "
  186. "`abstract` or `base` class.",
  187. SemIR::TypeId);
  188. context.emitter().Emit(node_id, BaseIsFinal, base_type_id);
  189. }
  190. // Checks that the specified base type is valid.
  191. static auto CheckBaseType(Context& context, Parse::NodeId node_id,
  192. SemIR::InstId base_expr_id) -> BaseInfo {
  193. auto base_type_id = ExprAsType(context, node_id, base_expr_id);
  194. base_type_id = context.AsCompleteType(base_type_id, [&] {
  195. CARBON_DIAGNOSTIC(IncompleteTypeInBaseDecl, Error,
  196. "Base `{0}` is an incomplete type.", SemIR::TypeId);
  197. return context.emitter().Build(node_id, IncompleteTypeInBaseDecl,
  198. base_type_id);
  199. });
  200. if (base_type_id == SemIR::TypeId::Error) {
  201. return BaseInfo::Error;
  202. }
  203. auto* base_class_info = TryGetAsClass(context, base_type_id);
  204. // The base must not be a final class.
  205. if (!base_class_info) {
  206. // For now, we treat all types that aren't introduced by a `class`
  207. // declaration as being final classes.
  208. // TODO: Once we have a better idea of which types are considered to be
  209. // classes, produce a better diagnostic for deriving from a non-class type.
  210. DiagnoseBaseIsFinal(context, node_id, base_type_id);
  211. return BaseInfo::Error;
  212. }
  213. if (base_class_info->inheritance_kind == SemIR::Class::Final) {
  214. DiagnoseBaseIsFinal(context, node_id, base_type_id);
  215. }
  216. CARBON_CHECK(base_class_info->scope_id.is_valid())
  217. << "Complete class should have a scope";
  218. return {.type_id = base_type_id, .scope_id = base_class_info->scope_id};
  219. }
  220. auto HandleBaseDecl(Context& context, Parse::BaseDeclId node_id) -> bool {
  221. auto [base_type_node_id, base_type_expr_id] =
  222. context.node_stack().PopExprWithNodeId();
  223. // Process modifiers. `extend` is required, none others are allowed.
  224. LimitModifiersOnDecl(context, KeywordModifierSet::Extend,
  225. Lex::TokenKind::Base);
  226. auto modifiers = context.decl_state_stack().innermost().modifier_set;
  227. if (!(modifiers & KeywordModifierSet::Extend)) {
  228. CARBON_DIAGNOSTIC(BaseMissingExtend, Error,
  229. "Missing `extend` before `base` declaration in class.");
  230. context.emitter().Emit(node_id, BaseMissingExtend);
  231. }
  232. context.decl_state_stack().Pop(DeclState::Base);
  233. auto enclosing_class_decl = context.GetCurrentScopeAs<SemIR::ClassDecl>();
  234. if (!enclosing_class_decl) {
  235. CARBON_DIAGNOSTIC(BaseOutsideClass, Error,
  236. "`base` declaration can only be used in a class.");
  237. context.emitter().Emit(node_id, BaseOutsideClass);
  238. return true;
  239. }
  240. auto& class_info = context.classes().Get(enclosing_class_decl->class_id);
  241. if (class_info.base_id.is_valid()) {
  242. CARBON_DIAGNOSTIC(BaseRepeated, Error,
  243. "Multiple `base` declarations in class. Multiple "
  244. "inheritance is not permitted.");
  245. CARBON_DIAGNOSTIC(BasePrevious, Note,
  246. "Previous `base` declaration is here.");
  247. context.emitter()
  248. .Build(node_id, BaseRepeated)
  249. .Note(class_info.base_id, BasePrevious)
  250. .Emit();
  251. return true;
  252. }
  253. auto base_info = CheckBaseType(context, base_type_node_id, base_type_expr_id);
  254. // The `base` value in the class scope has an unbound element type. Instance
  255. // binding will be performed when it's found by name lookup into an instance.
  256. auto field_type_id =
  257. context.GetUnboundElementType(class_info.self_type_id, base_info.type_id);
  258. class_info.base_id = context.AddInst(
  259. {node_id,
  260. SemIR::BaseDecl{field_type_id, base_info.type_id,
  261. SemIR::ElementIndex(context.args_type_info_stack()
  262. .PeekCurrentBlockContents()
  263. .size())}});
  264. // Add a corresponding field to the object representation of the class.
  265. // TODO: Consider whether we want to use `partial T` here.
  266. context.args_type_info_stack().AddInstId(context.AddInstInNoBlock(
  267. {node_id,
  268. SemIR::StructTypeField{SemIR::NameId::Base, base_info.type_id}}));
  269. // Bind the name `base` in the class to the base field.
  270. context.decl_name_stack().AddNameToLookup(
  271. context.decl_name_stack().MakeUnqualifiedName(node_id,
  272. SemIR::NameId::Base),
  273. class_info.base_id);
  274. // Extend the class scope with the base class.
  275. if (!!(modifiers & KeywordModifierSet::Extend)) {
  276. auto& class_scope = context.name_scopes().Get(class_info.scope_id);
  277. if (base_info.scope_id.is_valid()) {
  278. class_scope.extended_scopes.push_back(base_info.scope_id);
  279. } else {
  280. class_scope.has_error = true;
  281. }
  282. }
  283. return true;
  284. }
  285. auto HandleClassDefinition(Context& context,
  286. Parse::ClassDefinitionId /*node_id*/) -> bool {
  287. auto fields_id = context.args_type_info_stack().Pop();
  288. auto class_id =
  289. context.node_stack().Pop<Parse::NodeKind::ClassDefinitionStart>();
  290. context.inst_block_stack().Pop();
  291. context.scope_stack().Pop();
  292. context.decl_name_stack().PopScope();
  293. // The class type is now fully defined.
  294. auto& class_info = context.classes().Get(class_id);
  295. class_info.object_repr_id = context.GetStructType(fields_id);
  296. return true;
  297. }
  298. } // namespace Carbon::Check