handle_class.cpp 13 KB

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