handle_class.cpp 14 KB

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