handle_class.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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) -> bool {
  146. context.decl_state_stack().Push(DeclState::Base, parse_node);
  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. // Process modifiers. `extend` is required, none others are allowed.
  156. LimitModifiersOnDecl(context, KeywordModifierSet::Extend,
  157. Lex::TokenKind::Base);
  158. auto modifiers = context.decl_state_stack().innermost().modifier_set;
  159. if (!(modifiers & KeywordModifierSet::Extend)) {
  160. CARBON_DIAGNOSTIC(BaseMissingExtend, Error,
  161. "Missing `extend` before `base` declaration in class.");
  162. context.emitter().Emit(context.decl_state_stack().innermost().first_node,
  163. BaseMissingExtend);
  164. }
  165. context.decl_state_stack().Pop(DeclState::Base);
  166. auto enclosing_class_decl = context.GetCurrentScopeAs<SemIR::ClassDecl>();
  167. if (!enclosing_class_decl) {
  168. CARBON_DIAGNOSTIC(BaseOutsideClass, Error,
  169. "`base` declaration can only be used in a class.");
  170. context.emitter().Emit(parse_node, BaseOutsideClass);
  171. return true;
  172. }
  173. auto& class_info = context.classes().Get(enclosing_class_decl->class_id);
  174. if (class_info.base_id.is_valid()) {
  175. CARBON_DIAGNOSTIC(BaseRepeated, Error,
  176. "Multiple `base` declarations in class. Multiple "
  177. "inheritance is not permitted.");
  178. CARBON_DIAGNOSTIC(BasePrevious, Note,
  179. "Previous `base` declaration is here.");
  180. context.emitter()
  181. .Build(parse_node, BaseRepeated)
  182. .Note(context.insts().Get(class_info.base_id).parse_node(),
  183. BasePrevious)
  184. .Emit();
  185. return true;
  186. }
  187. auto base_type_id = ExprAsType(context, parse_node, base_type_expr_id);
  188. if (!context.TryToCompleteType(base_type_id, [&] {
  189. CARBON_DIAGNOSTIC(IncompleteTypeInBaseDecl, Error,
  190. "Base `{0}` is an incomplete type.", std::string);
  191. return context.emitter().Build(
  192. parse_node, IncompleteTypeInBaseDecl,
  193. context.sem_ir().StringifyType(base_type_id));
  194. })) {
  195. base_type_id = SemIR::TypeId::Error;
  196. }
  197. if (base_type_id != SemIR::TypeId::Error) {
  198. // For now, we treat all types that aren't introduced by a `class`
  199. // declaration as being final classes.
  200. // TODO: Once we have a better idea of which types are considered to be
  201. // classes, produce a better diagnostic for deriving from a non-class type.
  202. auto base_class =
  203. context.insts()
  204. .Get(context.sem_ir().GetTypeAllowBuiltinTypes(base_type_id))
  205. .TryAs<SemIR::ClassType>();
  206. if (!base_class ||
  207. context.classes().Get(base_class->class_id).inheritance_kind ==
  208. SemIR::Class::Final) {
  209. CARBON_DIAGNOSTIC(BaseIsFinal, Error,
  210. "Deriving from final type `{0}`. Base type must be an "
  211. "`abstract` or `base` class.",
  212. std::string);
  213. context.emitter().Emit(parse_node, BaseIsFinal,
  214. context.sem_ir().StringifyType(base_type_id));
  215. }
  216. }
  217. // The `base` value in the class scope has an unbound element type. Instance
  218. // binding will be performed when it's found by name lookup into an instance.
  219. auto field_type_inst_id = context.AddInst(SemIR::UnboundElementType{
  220. parse_node, context.GetBuiltinType(SemIR::BuiltinKind::TypeType),
  221. class_info.self_type_id, base_type_id});
  222. auto field_type_id = context.CanonicalizeType(field_type_inst_id);
  223. class_info.base_id = context.AddInst(SemIR::BaseDecl{
  224. parse_node, field_type_id, base_type_id,
  225. SemIR::ElementIndex(
  226. context.args_type_info_stack().PeekCurrentBlockContents().size())});
  227. // Add a corresponding field to the object representation of the class.
  228. // TODO: Consider whether we want to use `partial T` here.
  229. context.args_type_info_stack().AddInst(
  230. SemIR::StructTypeField{parse_node, SemIR::NameId::Base, base_type_id});
  231. // Bind the name `base` in the class to the base field.
  232. context.decl_name_stack().AddNameToLookup(
  233. context.decl_name_stack().MakeUnqualifiedName(parse_node,
  234. SemIR::NameId::Base),
  235. class_info.base_id);
  236. return true;
  237. }
  238. auto HandleClassDefinition(Context& context, Parse::NodeId parse_node) -> bool {
  239. auto fields_id = context.args_type_info_stack().Pop();
  240. auto class_id =
  241. context.node_stack().Pop<Parse::NodeKind::ClassDefinitionStart>();
  242. context.inst_block_stack().Pop();
  243. context.PopScope();
  244. context.decl_name_stack().PopScope();
  245. context.decl_state_stack().Pop(DeclState::Class);
  246. // The class type is now fully defined.
  247. auto& class_info = context.classes().Get(class_id);
  248. class_info.object_repr_id =
  249. context.CanonicalizeStructType(parse_node, fields_id);
  250. return true;
  251. }
  252. } // namespace Carbon::Check