handle_class.cpp 11 KB

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