handle_class.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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);
  16. context.decl_name_stack().PushScopeAndStartName();
  17. return true;
  18. }
  19. static auto BuildClassDecl(Context& context, Parse::NodeId parse_node)
  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. // Process modifiers.
  25. CheckAccessModifiersOnDecl(context, Lex::TokenKind::Class);
  26. LimitModifiersOnDecl(context,
  27. KeywordModifierSet::Class | KeywordModifierSet::Access,
  28. Lex::TokenKind::Class);
  29. auto modifiers = context.decl_state_stack().innermost().modifier_set;
  30. if (!!(modifiers & KeywordModifierSet::Access)) {
  31. context.TODO(context.decl_state_stack().innermost().saw_access_modifier,
  32. "access modifier");
  33. }
  34. auto inheritance_kind =
  35. !!(modifiers & KeywordModifierSet::Abstract) ? SemIR::Class::Abstract
  36. : !!(modifiers & KeywordModifierSet::Base) ? SemIR::Class::Base
  37. : SemIR::Class::Final;
  38. context.decl_state_stack().Pop(DeclState::Class);
  39. auto decl_block_id = context.inst_block_stack().Pop();
  40. // Add the class declaration.
  41. auto class_decl =
  42. SemIR::ClassDecl{parse_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(parse_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. parse_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, parse_node);
  100. context.decl_name_stack().PopScope();
  101. return true;
  102. }
  103. auto HandleClassDefinitionStart(Context& context, Parse::NodeId parse_node)
  104. -> bool {
  105. auto [class_id, class_decl_id] = BuildClassDecl(context, parse_node);
  106. auto& class_info = context.classes().Get(class_id);
  107. // Track that this declaration is the definition.
  108. if (class_info.definition_id.is_valid()) {
  109. CARBON_DIAGNOSTIC(ClassRedefinition, Error, "Redefinition of class {0}.",
  110. std::string);
  111. CARBON_DIAGNOSTIC(ClassPreviousDefinition, Note,
  112. "Previous definition was here.");
  113. context.emitter()
  114. .Build(parse_node, ClassRedefinition,
  115. context.names().GetFormatted(class_info.name_id).str())
  116. .Note(context.insts().Get(class_info.definition_id).parse_node(),
  117. ClassPreviousDefinition)
  118. .Emit();
  119. } else {
  120. class_info.definition_id = class_decl_id;
  121. class_info.scope_id = context.name_scopes().Add(class_decl_id);
  122. }
  123. // Enter the class scope.
  124. context.PushScope(class_decl_id, class_info.scope_id);
  125. // Introduce `Self`.
  126. context.AddNameToLookup(parse_node, SemIR::NameId::SelfType,
  127. context.types().GetInstId(class_info.self_type_id));
  128. context.inst_block_stack().Push();
  129. context.node_stack().Push(parse_node, class_id);
  130. context.args_type_info_stack().Push();
  131. // TODO: Handle the case where there's control flow in the class body. For
  132. // example:
  133. //
  134. // class C {
  135. // var v: if true then i32 else f64;
  136. // }
  137. //
  138. // We may need to track a list of instruction blocks here, as we do for a
  139. // function.
  140. class_info.body_block_id = context.inst_block_stack().PeekOrAdd();
  141. return true;
  142. }
  143. auto HandleBaseIntroducer(Context& context, Parse::NodeId /*parse_node*/)
  144. -> bool {
  145. context.decl_state_stack().Push(DeclState::Base);
  146. return true;
  147. }
  148. auto HandleBaseColon(Context& /*context*/, Parse::NodeId /*parse_node*/)
  149. -> bool {
  150. return true;
  151. }
  152. namespace {
  153. // Information gathered about a base type specified in a `base` declaration.
  154. struct BaseInfo {
  155. // A `BaseInfo` representing an erroneous base.
  156. static const BaseInfo Error;
  157. SemIR::TypeId type_id;
  158. SemIR::NameScopeId scope_id;
  159. };
  160. constexpr BaseInfo BaseInfo::Error = {.type_id = SemIR::TypeId::Error,
  161. .scope_id = SemIR::NameScopeId::Invalid};
  162. } // namespace
  163. // If `type_id` is a class type, get its corresponding `SemIR::Class` object.
  164. // Otherwise returns `nullptr`.
  165. static auto TryGetAsClass(Context& context, SemIR::TypeId type_id)
  166. -> SemIR::Class* {
  167. auto class_type = context.types().TryGetAs<SemIR::ClassType>(type_id);
  168. if (!class_type) {
  169. return nullptr;
  170. }
  171. return &context.classes().Get(class_type->class_id);
  172. }
  173. // Diagnoses an attempt to derive from a final type.
  174. static auto DiagnoseBaseIsFinal(Context& context, Parse::NodeId parse_node,
  175. SemIR::TypeId base_type_id) -> void {
  176. CARBON_DIAGNOSTIC(BaseIsFinal, Error,
  177. "Deriving from final type `{0}`. Base type must be an "
  178. "`abstract` or `base` class.",
  179. std::string);
  180. context.emitter().Emit(parse_node, BaseIsFinal,
  181. context.sem_ir().StringifyType(base_type_id));
  182. }
  183. // Checks that the specified base type is valid.
  184. static auto CheckBaseType(Context& context, Parse::NodeId parse_node,
  185. SemIR::InstId base_expr_id) -> BaseInfo {
  186. auto base_type_id = ExprAsType(context, parse_node, base_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. return BaseInfo::Error;
  196. }
  197. auto* base_class_info = TryGetAsClass(context, base_type_id);
  198. // The base must not be a final class.
  199. if (!base_class_info) {
  200. // For now, we treat all types that aren't introduced by a `class`
  201. // declaration as being final classes.
  202. // TODO: Once we have a better idea of which types are considered to be
  203. // classes, produce a better diagnostic for deriving from a non-class type.
  204. DiagnoseBaseIsFinal(context, parse_node, base_type_id);
  205. return BaseInfo::Error;
  206. }
  207. if (base_class_info->inheritance_kind == SemIR::Class::Final) {
  208. DiagnoseBaseIsFinal(context, parse_node, base_type_id);
  209. }
  210. CARBON_CHECK(base_class_info->scope_id.is_valid())
  211. << "Complete class should have a scope";
  212. return {.type_id = base_type_id, .scope_id = base_class_info->scope_id};
  213. }
  214. auto HandleBaseDecl(Context& context, Parse::NodeId parse_node) -> bool {
  215. auto base_type_expr_id = context.node_stack().PopExpr();
  216. // Process modifiers. `extend` is required, none others are allowed.
  217. LimitModifiersOnDecl(context, KeywordModifierSet::Extend,
  218. Lex::TokenKind::Base);
  219. auto modifiers = context.decl_state_stack().innermost().modifier_set;
  220. if (!(modifiers & KeywordModifierSet::Extend)) {
  221. CARBON_DIAGNOSTIC(BaseMissingExtend, Error,
  222. "Missing `extend` before `base` declaration in class.");
  223. context.emitter().Emit(parse_node, BaseMissingExtend);
  224. }
  225. context.decl_state_stack().Pop(DeclState::Base);
  226. auto enclosing_class_decl = context.GetCurrentScopeAs<SemIR::ClassDecl>();
  227. if (!enclosing_class_decl) {
  228. CARBON_DIAGNOSTIC(BaseOutsideClass, Error,
  229. "`base` declaration can only be used in a class.");
  230. context.emitter().Emit(parse_node, BaseOutsideClass);
  231. return true;
  232. }
  233. auto& class_info = context.classes().Get(enclosing_class_decl->class_id);
  234. if (class_info.base_id.is_valid()) {
  235. CARBON_DIAGNOSTIC(BaseRepeated, Error,
  236. "Multiple `base` declarations in class. Multiple "
  237. "inheritance is not permitted.");
  238. CARBON_DIAGNOSTIC(BasePrevious, Note,
  239. "Previous `base` declaration is here.");
  240. context.emitter()
  241. .Build(parse_node, BaseRepeated)
  242. .Note(context.insts().Get(class_info.base_id).parse_node(),
  243. BasePrevious)
  244. .Emit();
  245. return true;
  246. }
  247. auto base_info = CheckBaseType(context, parse_node, base_type_expr_id);
  248. // The `base` value in the class scope has an unbound element type. Instance
  249. // binding will be performed when it's found by name lookup into an instance.
  250. auto field_type_inst_id = context.AddInst(SemIR::UnboundElementType{
  251. parse_node, context.GetBuiltinType(SemIR::BuiltinKind::TypeType),
  252. class_info.self_type_id, base_info.type_id});
  253. auto field_type_id = context.CanonicalizeType(field_type_inst_id);
  254. class_info.base_id = context.AddInst(SemIR::BaseDecl{
  255. parse_node, field_type_id, base_info.type_id,
  256. SemIR::ElementIndex(
  257. context.args_type_info_stack().PeekCurrentBlockContents().size())});
  258. // Add a corresponding field to the object representation of the class.
  259. // TODO: Consider whether we want to use `partial T` here.
  260. context.args_type_info_stack().AddInst(SemIR::StructTypeField{
  261. parse_node, SemIR::NameId::Base, base_info.type_id});
  262. // Bind the name `base` in the class to the base field.
  263. context.decl_name_stack().AddNameToLookup(
  264. context.decl_name_stack().MakeUnqualifiedName(parse_node,
  265. SemIR::NameId::Base),
  266. class_info.base_id);
  267. // Extend the class scope with the base class.
  268. if (!!(modifiers & KeywordModifierSet::Extend)) {
  269. auto& class_scope = context.name_scopes().Get(class_info.scope_id);
  270. if (base_info.scope_id.is_valid()) {
  271. class_scope.extended_scopes.push_back(base_info.scope_id);
  272. } else {
  273. class_scope.has_error = true;
  274. }
  275. }
  276. return true;
  277. }
  278. auto HandleClassDefinition(Context& context, Parse::NodeId parse_node) -> bool {
  279. auto fields_id = context.args_type_info_stack().Pop();
  280. auto class_id =
  281. context.node_stack().Pop<Parse::NodeKind::ClassDefinitionStart>();
  282. context.inst_block_stack().Pop();
  283. context.PopScope();
  284. context.decl_name_stack().PopScope();
  285. // The class type is now fully defined.
  286. auto& class_info = context.classes().Get(class_id);
  287. class_info.object_repr_id =
  288. context.CanonicalizeStructType(parse_node, fields_id);
  289. return true;
  290. }
  291. } // namespace Carbon::Check