handle_class.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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. namespace Carbon::Check {
  8. auto HandleClassIntroducer(Context& context, Parse::NodeId parse_node) -> bool {
  9. // Create an instruction block to hold the instructions created as part of the
  10. // class signature, such as generic parameters.
  11. context.inst_block_stack().Push();
  12. // Push the bracketing node.
  13. context.node_stack().Push(parse_node);
  14. // Optional modifiers and the name follow.
  15. context.decl_state_stack().Push(DeclState::Class, parse_node);
  16. context.decl_name_stack().PushScopeAndStartName();
  17. return true;
  18. }
  19. static auto BuildClassDecl(Context& context)
  20. -> std::tuple<SemIR::ClassId, SemIR::InstId> {
  21. auto name_context = context.decl_name_stack().FinishName();
  22. context.node_stack()
  23. .PopAndDiscardSoloParseNode<Parse::NodeKind::ClassIntroducer>();
  24. auto first_node = context.decl_state_stack().innermost().first_node;
  25. // Process modifiers.
  26. CheckAccessModifiersOnDecl(context, Lex::TokenKind::Class);
  27. LimitModifiersOnDecl(context,
  28. KeywordModifierSet::Class | KeywordModifierSet::Access,
  29. Lex::TokenKind::Class);
  30. auto modifiers = context.decl_state_stack().innermost().modifier_set;
  31. if (!!(modifiers & KeywordModifierSet::Access)) {
  32. context.TODO(context.decl_state_stack().innermost().saw_access_modifier,
  33. "access modifier");
  34. }
  35. auto inheritance_kind =
  36. !!(modifiers & KeywordModifierSet::Abstract) ? SemIR::Class::Abstract
  37. : !!(modifiers & KeywordModifierSet::Base) ? SemIR::Class::Base
  38. : SemIR::Class::Final;
  39. auto decl_block_id = context.inst_block_stack().Pop();
  40. // Add the class declaration.
  41. auto class_decl =
  42. SemIR::ClassDecl{first_node, SemIR::ClassId::Invalid, decl_block_id};
  43. auto class_decl_id = context.AddInst(class_decl);
  44. // Check whether this is a redeclaration.
  45. auto existing_id =
  46. context.decl_name_stack().LookupOrAddName(name_context, class_decl_id);
  47. if (existing_id.is_valid()) {
  48. if (auto existing_class_decl =
  49. context.insts().Get(existing_id).TryAs<SemIR::ClassDecl>()) {
  50. // This is a redeclaration of an existing class.
  51. class_decl.class_id = existing_class_decl->class_id;
  52. auto& class_info = context.classes().Get(class_decl.class_id);
  53. // The introducer kind must match the previous declaration.
  54. // TODO: The rule here is not yet decided. See #3384.
  55. if (class_info.inheritance_kind != inheritance_kind) {
  56. CARBON_DIAGNOSTIC(ClassRedeclarationDifferentIntroducer, Error,
  57. "Class redeclared with different inheritance kind.");
  58. CARBON_DIAGNOSTIC(ClassRedeclarationDifferentIntroducerPrevious, Note,
  59. "Previously declared here.");
  60. context.emitter()
  61. .Build(first_node, ClassRedeclarationDifferentIntroducer)
  62. .Note(existing_class_decl->parse_node,
  63. ClassRedeclarationDifferentIntroducerPrevious)
  64. .Emit();
  65. }
  66. // TODO: Check that the generic parameter list agrees with the prior
  67. // declaration.
  68. } else {
  69. // This is a redeclaration of something other than a class.
  70. context.DiagnoseDuplicateName(name_context.parse_node, existing_id);
  71. }
  72. }
  73. // Create a new class if this isn't a valid redeclaration.
  74. if (!class_decl.class_id.is_valid()) {
  75. // TODO: If this is an invalid redeclaration of a non-class entity or there
  76. // was an error in the qualifier, we will have lost track of the class name
  77. // here. We should keep track of it even if the name is invalid.
  78. class_decl.class_id = context.classes().Add(
  79. {.name_id =
  80. name_context.state == DeclNameStack::NameContext::State::Unresolved
  81. ? name_context.unresolved_name_id
  82. : SemIR::NameId::Invalid,
  83. // `.self_type_id` depends on `class_id`, so is set below.
  84. .self_type_id = SemIR::TypeId::Invalid,
  85. .decl_id = class_decl_id,
  86. .inheritance_kind = inheritance_kind});
  87. // Build the `Self` type.
  88. auto& class_info = context.classes().Get(class_decl.class_id);
  89. class_info.self_type_id =
  90. context.CanonicalizeType(context.AddInst(SemIR::ClassType{
  91. first_node, context.GetBuiltinType(SemIR::BuiltinKind::TypeType),
  92. class_decl.class_id}));
  93. }
  94. // Write the class ID into the ClassDecl.
  95. context.insts().Set(class_decl_id, class_decl);
  96. return {class_decl.class_id, class_decl_id};
  97. }
  98. auto HandleClassDecl(Context& context, Parse::NodeId /*parse_node*/) -> bool {
  99. BuildClassDecl(context);
  100. context.decl_name_stack().PopScope();
  101. context.decl_state_stack().Pop(DeclState::Class);
  102. return true;
  103. }
  104. auto HandleClassDefinitionStart(Context& context, Parse::NodeId parse_node)
  105. -> bool {
  106. auto [class_id, class_decl_id] = BuildClassDecl(context);
  107. auto& class_info = context.classes().Get(class_id);
  108. // Track that this declaration is the definition.
  109. if (class_info.definition_id.is_valid()) {
  110. CARBON_DIAGNOSTIC(ClassRedefinition, Error, "Redefinition of class {0}.",
  111. std::string);
  112. CARBON_DIAGNOSTIC(ClassPreviousDefinition, Note,
  113. "Previous definition was here.");
  114. context.emitter()
  115. .Build(parse_node, ClassRedefinition,
  116. context.names().GetFormatted(class_info.name_id).str())
  117. .Note(context.insts().Get(class_info.definition_id).parse_node(),
  118. ClassPreviousDefinition)
  119. .Emit();
  120. } else {
  121. class_info.definition_id = class_decl_id;
  122. class_info.scope_id = context.name_scopes().Add();
  123. }
  124. // Enter the class scope.
  125. context.PushScope(class_decl_id, class_info.scope_id);
  126. // Introduce `Self`.
  127. context.AddNameToLookup(
  128. parse_node, SemIR::NameId::SelfType,
  129. context.sem_ir().GetTypeAllowBuiltinTypes(class_info.self_type_id));
  130. context.inst_block_stack().Push();
  131. context.node_stack().Push(parse_node, class_id);
  132. context.args_type_info_stack().Push();
  133. // TODO: Handle the case where there's control flow in the class body. For
  134. // example:
  135. //
  136. // class C {
  137. // var v: if true then i32 else f64;
  138. // }
  139. //
  140. // We may need to track a list of instruction blocks here, as we do for a
  141. // function.
  142. class_info.body_block_id = context.inst_block_stack().PeekOrAdd();
  143. return true;
  144. }
  145. auto HandleBaseIntroducer(Context& /*context*/, Parse::NodeId /*parse_node*/)
  146. -> bool {
  147. return true;
  148. }
  149. auto HandleBaseColon(Context& /*context*/, Parse::NodeId /*parse_node*/)
  150. -> bool {
  151. return true;
  152. }
  153. auto HandleBaseDecl(Context& context, Parse::NodeId parse_node) -> bool {
  154. auto base_type_expr_id = context.node_stack().PopExpr();
  155. auto enclosing_class_decl = context.GetCurrentScopeAs<SemIR::ClassDecl>();
  156. if (!enclosing_class_decl) {
  157. CARBON_DIAGNOSTIC(BaseOutsideClass, Error,
  158. "`base` declaration can only be used in a class.");
  159. context.emitter().Emit(parse_node, BaseOutsideClass);
  160. return true;
  161. }
  162. auto& class_info = context.classes().Get(enclosing_class_decl->class_id);
  163. if (class_info.base_id.is_valid()) {
  164. CARBON_DIAGNOSTIC(BaseRepeated, Error,
  165. "Multiple `base` declarations in class. Multiple "
  166. "inheritance is not permitted.");
  167. CARBON_DIAGNOSTIC(BasePrevious, Note,
  168. "Previous `base` declaration is here.");
  169. context.emitter()
  170. .Build(parse_node, BaseRepeated)
  171. .Note(context.insts().Get(class_info.base_id).parse_node(),
  172. BasePrevious)
  173. .Emit();
  174. return true;
  175. }
  176. auto base_type_id = ExprAsType(context, parse_node, base_type_expr_id);
  177. if (!context.TryToCompleteType(base_type_id, [&] {
  178. CARBON_DIAGNOSTIC(IncompleteTypeInBaseDecl, Error,
  179. "Base `{0}` is an incomplete type.", std::string);
  180. return context.emitter().Build(
  181. parse_node, IncompleteTypeInBaseDecl,
  182. context.sem_ir().StringifyType(base_type_id));
  183. })) {
  184. base_type_id = SemIR::TypeId::Error;
  185. }
  186. if (base_type_id != SemIR::TypeId::Error) {
  187. // For now, we treat all types that aren't introduced by a `class`
  188. // declaration as being final classes.
  189. // TODO: Once we have a better idea of which types are considered to be
  190. // classes, produce a better diagnostic for deriving from a non-class type.
  191. auto base_class =
  192. context.insts()
  193. .Get(context.sem_ir().GetTypeAllowBuiltinTypes(base_type_id))
  194. .TryAs<SemIR::ClassType>();
  195. if (!base_class ||
  196. context.classes().Get(base_class->class_id).inheritance_kind ==
  197. SemIR::Class::Final) {
  198. CARBON_DIAGNOSTIC(BaseIsFinal, Error,
  199. "Deriving from final type `{0}`. Base type must be an "
  200. "`abstract` or `base` class.",
  201. std::string);
  202. context.emitter().Emit(parse_node, BaseIsFinal,
  203. context.sem_ir().StringifyType(base_type_id));
  204. }
  205. }
  206. // The `base` value in the class scope has an unbound element type. Instance
  207. // binding will be performed when it's found by name lookup into an instance.
  208. auto field_type_inst_id = context.AddInst(SemIR::UnboundElementType{
  209. parse_node, context.GetBuiltinType(SemIR::BuiltinKind::TypeType),
  210. class_info.self_type_id, base_type_id});
  211. auto field_type_id = context.CanonicalizeType(field_type_inst_id);
  212. class_info.base_id = context.AddInst(SemIR::BaseDecl{
  213. parse_node, field_type_id, base_type_id,
  214. SemIR::ElementIndex(
  215. context.args_type_info_stack().PeekCurrentBlockContents().size())});
  216. // Add a corresponding field to the object representation of the class.
  217. // TODO: Consider whether we want to use `partial T` here.
  218. context.args_type_info_stack().AddInst(
  219. SemIR::StructTypeField{parse_node, SemIR::NameId::Base, base_type_id});
  220. // Bind the name `base` in the class to the base field.
  221. context.decl_name_stack().AddNameToLookup(
  222. context.decl_name_stack().MakeUnqualifiedName(parse_node,
  223. SemIR::NameId::Base),
  224. class_info.base_id);
  225. return true;
  226. }
  227. auto HandleClassDefinition(Context& context, Parse::NodeId parse_node) -> bool {
  228. auto fields_id = context.args_type_info_stack().Pop();
  229. auto class_id =
  230. context.node_stack().Pop<Parse::NodeKind::ClassDefinitionStart>();
  231. context.inst_block_stack().Pop();
  232. context.PopScope();
  233. context.decl_name_stack().PopScope();
  234. context.decl_state_stack().Pop(DeclState::Class);
  235. // The class type is now fully defined.
  236. auto& class_info = context.classes().Get(class_id);
  237. class_info.object_representation_id =
  238. context.CanonicalizeStructType(parse_node, fields_id);
  239. return true;
  240. }
  241. } // namespace Carbon::Check