handle_class.cpp 13 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. namespace Carbon::Check {
  8. auto HandleClassIntroducer(Context& context,
  9. Parse::ClassIntroducerId parse_node) -> bool {
  10. // Create an instruction block to hold the instructions created as part of the
  11. // class signature, such as generic parameters.
  12. context.inst_block_stack().Push();
  13. // Push the bracketing node.
  14. context.node_stack().Push(parse_node);
  15. // Optional modifiers and the name follow.
  16. context.decl_state_stack().Push(DeclState::Class);
  17. context.decl_name_stack().PushScopeAndStartName();
  18. return true;
  19. }
  20. static auto BuildClassDecl(Context& context, Parse::AnyClassDeclId parse_node)
  21. -> std::tuple<SemIR::ClassId, SemIR::InstId> {
  22. if (context.node_stack().PopIf<Parse::NodeKind::TuplePattern>()) {
  23. context.TODO(parse_node, "generic class");
  24. }
  25. auto name_context = context.decl_name_stack().FinishName();
  26. context.node_stack()
  27. .PopAndDiscardSoloParseNode<Parse::NodeKind::ClassIntroducer>();
  28. // Process modifiers.
  29. CheckAccessModifiersOnDecl(context, Lex::TokenKind::Class);
  30. LimitModifiersOnDecl(context,
  31. KeywordModifierSet::Class | KeywordModifierSet::Access,
  32. Lex::TokenKind::Class);
  33. auto modifiers = context.decl_state_stack().innermost().modifier_set;
  34. if (!!(modifiers & KeywordModifierSet::Access)) {
  35. context.TODO(context.decl_state_stack().innermost().saw_access_modifier,
  36. "access modifier");
  37. }
  38. auto inheritance_kind =
  39. !!(modifiers & KeywordModifierSet::Abstract) ? SemIR::Class::Abstract
  40. : !!(modifiers & KeywordModifierSet::Base) ? SemIR::Class::Base
  41. : SemIR::Class::Final;
  42. context.decl_state_stack().Pop(DeclState::Class);
  43. auto decl_block_id = context.inst_block_stack().Pop();
  44. // Add the class declaration.
  45. auto class_decl =
  46. SemIR::ClassDecl{parse_node, SemIR::ClassId::Invalid, decl_block_id};
  47. auto class_decl_id = context.AddInst(class_decl);
  48. // Check whether this is a redeclaration.
  49. auto existing_id =
  50. context.decl_name_stack().LookupOrAddName(name_context, class_decl_id);
  51. if (existing_id.is_valid()) {
  52. if (auto existing_class_decl =
  53. context.insts().Get(existing_id).TryAs<SemIR::ClassDecl>()) {
  54. // This is a redeclaration of an existing class.
  55. class_decl.class_id = existing_class_decl->class_id;
  56. auto& class_info = context.classes().Get(class_decl.class_id);
  57. // The introducer kind must match the previous declaration.
  58. // TODO: The rule here is not yet decided. See #3384.
  59. if (class_info.inheritance_kind != inheritance_kind) {
  60. CARBON_DIAGNOSTIC(ClassRedeclarationDifferentIntroducer, Error,
  61. "Class redeclared with different inheritance kind.");
  62. CARBON_DIAGNOSTIC(ClassRedeclarationDifferentIntroducerPrevious, Note,
  63. "Previously declared here.");
  64. context.emitter()
  65. .Build(parse_node, ClassRedeclarationDifferentIntroducer)
  66. .Note(existing_class_decl->parse_node,
  67. ClassRedeclarationDifferentIntroducerPrevious)
  68. .Emit();
  69. }
  70. // TODO: Check that the generic parameter list agrees with the prior
  71. // declaration.
  72. } else {
  73. // This is a redeclaration of something other than a class.
  74. context.DiagnoseDuplicateName(name_context.parse_node, existing_id);
  75. }
  76. }
  77. // Create a new class if this isn't a valid redeclaration.
  78. if (!class_decl.class_id.is_valid()) {
  79. // TODO: If this is an invalid redeclaration of a non-class entity or there
  80. // was an error in the qualifier, we will have lost track of the class name
  81. // here. We should keep track of it even if the name is invalid.
  82. class_decl.class_id = context.classes().Add(
  83. {.name_id =
  84. name_context.state == DeclNameStack::NameContext::State::Unresolved
  85. ? name_context.unresolved_name_id
  86. : SemIR::NameId::Invalid,
  87. // `.self_type_id` depends on `class_id`, so is set below.
  88. .self_type_id = SemIR::TypeId::Invalid,
  89. .decl_id = class_decl_id,
  90. .inheritance_kind = inheritance_kind});
  91. // Build the `Self` type.
  92. auto& class_info = context.classes().Get(class_decl.class_id);
  93. class_info.self_type_id =
  94. context.CanonicalizeType(context.AddInst(SemIR::ClassType{
  95. parse_node, context.GetBuiltinType(SemIR::BuiltinKind::TypeType),
  96. class_decl.class_id}));
  97. }
  98. // Write the class ID into the ClassDecl.
  99. context.insts().Set(class_decl_id, class_decl);
  100. return {class_decl.class_id, class_decl_id};
  101. }
  102. auto HandleClassDecl(Context& context, Parse::ClassDeclId parse_node) -> bool {
  103. BuildClassDecl(context, parse_node);
  104. context.decl_name_stack().PopScope();
  105. return true;
  106. }
  107. auto HandleClassDefinitionStart(Context& context,
  108. Parse::ClassDefinitionStartId parse_node)
  109. -> bool {
  110. auto [class_id, class_decl_id] = BuildClassDecl(context, parse_node);
  111. auto& class_info = context.classes().Get(class_id);
  112. // Track that this declaration is the definition.
  113. if (class_info.definition_id.is_valid()) {
  114. CARBON_DIAGNOSTIC(ClassRedefinition, Error, "Redefinition of class {0}.",
  115. std::string);
  116. CARBON_DIAGNOSTIC(ClassPreviousDefinition, Note,
  117. "Previous definition was here.");
  118. context.emitter()
  119. .Build(parse_node, ClassRedefinition,
  120. context.names().GetFormatted(class_info.name_id).str())
  121. .Note(context.insts().Get(class_info.definition_id).parse_node(),
  122. ClassPreviousDefinition)
  123. .Emit();
  124. } else {
  125. class_info.definition_id = class_decl_id;
  126. class_info.scope_id = context.name_scopes().Add(class_decl_id);
  127. }
  128. // Enter the class scope.
  129. context.PushScope(class_decl_id, class_info.scope_id);
  130. // Introduce `Self`.
  131. context.AddNameToLookup(parse_node, SemIR::NameId::SelfType,
  132. context.types().GetInstId(class_info.self_type_id));
  133. context.inst_block_stack().Push();
  134. context.node_stack().Push(parse_node, class_id);
  135. context.args_type_info_stack().Push();
  136. // TODO: Handle the case where there's control flow in the class body. For
  137. // example:
  138. //
  139. // class C {
  140. // var v: if true then i32 else f64;
  141. // }
  142. //
  143. // We may need to track a list of instruction blocks here, as we do for a
  144. // function.
  145. class_info.body_block_id = context.inst_block_stack().PeekOrAdd();
  146. return true;
  147. }
  148. auto HandleBaseIntroducer(Context& context,
  149. Parse::BaseIntroducerId /*parse_node*/) -> bool {
  150. context.decl_state_stack().Push(DeclState::Base);
  151. return true;
  152. }
  153. auto HandleBaseColon(Context& /*context*/, Parse::BaseColonId /*parse_node*/)
  154. -> bool {
  155. return true;
  156. }
  157. namespace {
  158. // Information gathered about a base type specified in a `base` declaration.
  159. struct BaseInfo {
  160. // A `BaseInfo` representing an erroneous base.
  161. static const BaseInfo Error;
  162. SemIR::TypeId type_id;
  163. SemIR::NameScopeId scope_id;
  164. };
  165. constexpr BaseInfo BaseInfo::Error = {.type_id = SemIR::TypeId::Error,
  166. .scope_id = SemIR::NameScopeId::Invalid};
  167. } // namespace
  168. // If `type_id` is a class type, get its corresponding `SemIR::Class` object.
  169. // Otherwise returns `nullptr`.
  170. static auto TryGetAsClass(Context& context, SemIR::TypeId type_id)
  171. -> SemIR::Class* {
  172. auto class_type = context.types().TryGetAs<SemIR::ClassType>(type_id);
  173. if (!class_type) {
  174. return nullptr;
  175. }
  176. return &context.classes().Get(class_type->class_id);
  177. }
  178. // Diagnoses an attempt to derive from a final type.
  179. static auto DiagnoseBaseIsFinal(Context& context, Parse::NodeId parse_node,
  180. SemIR::TypeId base_type_id) -> void {
  181. CARBON_DIAGNOSTIC(BaseIsFinal, Error,
  182. "Deriving from final type `{0}`. Base type must be an "
  183. "`abstract` or `base` class.",
  184. std::string);
  185. context.emitter().Emit(parse_node, BaseIsFinal,
  186. context.sem_ir().StringifyType(base_type_id));
  187. }
  188. // Checks that the specified base type is valid.
  189. static auto CheckBaseType(Context& context, Parse::NodeId parse_node,
  190. SemIR::InstId base_expr_id) -> BaseInfo {
  191. auto base_type_id = ExprAsType(context, parse_node, base_expr_id);
  192. base_type_id = context.AsCompleteType(base_type_id, [&] {
  193. CARBON_DIAGNOSTIC(IncompleteTypeInBaseDecl, Error,
  194. "Base `{0}` is an incomplete type.", std::string);
  195. return context.emitter().Build(
  196. parse_node, IncompleteTypeInBaseDecl,
  197. context.sem_ir().StringifyType(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_expr_id = context.node_stack().PopExpr();
  221. // Process modifiers. `extend` is required, none others are allowed.
  222. LimitModifiersOnDecl(context, KeywordModifierSet::Extend,
  223. Lex::TokenKind::Base);
  224. auto modifiers = context.decl_state_stack().innermost().modifier_set;
  225. if (!(modifiers & KeywordModifierSet::Extend)) {
  226. CARBON_DIAGNOSTIC(BaseMissingExtend, Error,
  227. "Missing `extend` before `base` declaration in class.");
  228. context.emitter().Emit(parse_node, BaseMissingExtend);
  229. }
  230. context.decl_state_stack().Pop(DeclState::Base);
  231. auto enclosing_class_decl = context.GetCurrentScopeAs<SemIR::ClassDecl>();
  232. if (!enclosing_class_decl) {
  233. CARBON_DIAGNOSTIC(BaseOutsideClass, Error,
  234. "`base` declaration can only be used in a class.");
  235. context.emitter().Emit(parse_node, BaseOutsideClass);
  236. return true;
  237. }
  238. auto& class_info = context.classes().Get(enclosing_class_decl->class_id);
  239. if (class_info.base_id.is_valid()) {
  240. CARBON_DIAGNOSTIC(BaseRepeated, Error,
  241. "Multiple `base` declarations in class. Multiple "
  242. "inheritance is not permitted.");
  243. CARBON_DIAGNOSTIC(BasePrevious, Note,
  244. "Previous `base` declaration is here.");
  245. context.emitter()
  246. .Build(parse_node, BaseRepeated)
  247. .Note(context.insts().Get(class_info.base_id).parse_node(),
  248. BasePrevious)
  249. .Emit();
  250. return true;
  251. }
  252. auto base_info = CheckBaseType(context, parse_node, 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_inst_id = context.AddInst(SemIR::UnboundElementType{
  256. parse_node, context.GetBuiltinType(SemIR::BuiltinKind::TypeType),
  257. class_info.self_type_id, base_info.type_id});
  258. auto field_type_id = context.CanonicalizeType(field_type_inst_id);
  259. class_info.base_id = context.AddInst(SemIR::BaseDecl{
  260. parse_node, field_type_id, base_info.type_id,
  261. SemIR::ElementIndex(
  262. context.args_type_info_stack().PeekCurrentBlockContents().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().AddInst(SemIR::StructTypeField{
  266. parse_node, SemIR::NameId::Base, base_info.type_id});
  267. // Bind the name `base` in the class to the base field.
  268. context.decl_name_stack().AddNameToLookup(
  269. context.decl_name_stack().MakeUnqualifiedName(parse_node,
  270. SemIR::NameId::Base),
  271. class_info.base_id);
  272. // Extend the class scope with the base class.
  273. if (!!(modifiers & KeywordModifierSet::Extend)) {
  274. auto& class_scope = context.name_scopes().Get(class_info.scope_id);
  275. if (base_info.scope_id.is_valid()) {
  276. class_scope.extended_scopes.push_back(base_info.scope_id);
  277. } else {
  278. class_scope.has_error = true;
  279. }
  280. }
  281. return true;
  282. }
  283. auto HandleClassDefinition(Context& context,
  284. Parse::ClassDefinitionId parse_node) -> bool {
  285. auto fields_id = context.args_type_info_stack().Pop();
  286. auto class_id =
  287. context.node_stack().Pop<Parse::NodeKind::ClassDefinitionStart>();
  288. context.inst_block_stack().Pop();
  289. context.PopScope();
  290. context.decl_name_stack().PopScope();
  291. // The class type is now fully defined.
  292. auto& class_info = context.classes().Get(class_id);
  293. class_info.object_repr_id =
  294. context.CanonicalizeStructType(parse_node, fields_id);
  295. return true;
  296. }
  297. } // namespace Carbon::Check