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. 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(
  21. Context& context,
  22. Parse::NodeIdOneOf<Parse::ClassDeclId, Parse::ClassDefinitionStartId>
  23. parse_node) -> std::tuple<SemIR::ClassId, SemIR::InstId> {
  24. auto name_context = context.decl_name_stack().FinishName();
  25. context.node_stack()
  26. .PopAndDiscardSoloParseNode<Parse::NodeKind::ClassIntroducer>();
  27. // Process modifiers.
  28. CheckAccessModifiersOnDecl(context, Lex::TokenKind::Class);
  29. LimitModifiersOnDecl(context,
  30. KeywordModifierSet::Class | KeywordModifierSet::Access,
  31. Lex::TokenKind::Class);
  32. auto modifiers = context.decl_state_stack().innermost().modifier_set;
  33. if (!!(modifiers & KeywordModifierSet::Access)) {
  34. context.TODO(context.decl_state_stack().innermost().saw_access_modifier,
  35. "access modifier");
  36. }
  37. auto inheritance_kind =
  38. !!(modifiers & KeywordModifierSet::Abstract) ? SemIR::Class::Abstract
  39. : !!(modifiers & KeywordModifierSet::Base) ? SemIR::Class::Base
  40. : SemIR::Class::Final;
  41. context.decl_state_stack().Pop(DeclState::Class);
  42. auto decl_block_id = context.inst_block_stack().Pop();
  43. // Add the class declaration.
  44. auto class_decl =
  45. SemIR::ClassDecl{parse_node, SemIR::ClassId::Invalid, decl_block_id};
  46. auto class_decl_id = context.AddInst(class_decl);
  47. // Check whether this is a redeclaration.
  48. auto existing_id =
  49. context.decl_name_stack().LookupOrAddName(name_context, class_decl_id);
  50. if (existing_id.is_valid()) {
  51. if (auto existing_class_decl =
  52. context.insts().Get(existing_id).TryAs<SemIR::ClassDecl>()) {
  53. // This is a redeclaration of an existing class.
  54. class_decl.class_id = existing_class_decl->class_id;
  55. auto& class_info = context.classes().Get(class_decl.class_id);
  56. // The introducer kind must match the previous declaration.
  57. // TODO: The rule here is not yet decided. See #3384.
  58. if (class_info.inheritance_kind != inheritance_kind) {
  59. CARBON_DIAGNOSTIC(ClassRedeclarationDifferentIntroducer, Error,
  60. "Class redeclared with different inheritance kind.");
  61. CARBON_DIAGNOSTIC(ClassRedeclarationDifferentIntroducerPrevious, Note,
  62. "Previously declared here.");
  63. context.emitter()
  64. .Build(parse_node, ClassRedeclarationDifferentIntroducer)
  65. .Note(existing_class_decl->parse_node,
  66. ClassRedeclarationDifferentIntroducerPrevious)
  67. .Emit();
  68. }
  69. // TODO: Check that the generic parameter list agrees with the prior
  70. // declaration.
  71. } else {
  72. // This is a redeclaration of something other than a class.
  73. context.DiagnoseDuplicateName(name_context.parse_node, existing_id);
  74. }
  75. }
  76. // Create a new class if this isn't a valid redeclaration.
  77. if (!class_decl.class_id.is_valid()) {
  78. // TODO: If this is an invalid redeclaration of a non-class entity or there
  79. // was an error in the qualifier, we will have lost track of the class name
  80. // here. We should keep track of it even if the name is invalid.
  81. class_decl.class_id = context.classes().Add(
  82. {.name_id =
  83. name_context.state == DeclNameStack::NameContext::State::Unresolved
  84. ? name_context.unresolved_name_id
  85. : SemIR::NameId::Invalid,
  86. // `.self_type_id` depends on `class_id`, so is set below.
  87. .self_type_id = SemIR::TypeId::Invalid,
  88. .decl_id = class_decl_id,
  89. .inheritance_kind = inheritance_kind});
  90. // Build the `Self` type.
  91. auto& class_info = context.classes().Get(class_decl.class_id);
  92. class_info.self_type_id =
  93. context.CanonicalizeType(context.AddInst(SemIR::ClassType{
  94. parse_node, context.GetBuiltinType(SemIR::BuiltinKind::TypeType),
  95. class_decl.class_id}));
  96. }
  97. // Write the class ID into the ClassDecl.
  98. context.insts().Set(class_decl_id, class_decl);
  99. return {class_decl.class_id, class_decl_id};
  100. }
  101. auto HandleClassDecl(Context& context, Parse::ClassDeclId parse_node) -> bool {
  102. BuildClassDecl(context, parse_node);
  103. context.decl_name_stack().PopScope();
  104. return true;
  105. }
  106. auto HandleClassDefinitionStart(Context& context,
  107. Parse::ClassDefinitionStartId parse_node)
  108. -> bool {
  109. auto [class_id, class_decl_id] = BuildClassDecl(context, parse_node);
  110. auto& class_info = context.classes().Get(class_id);
  111. // Track that this declaration is the definition.
  112. if (class_info.definition_id.is_valid()) {
  113. CARBON_DIAGNOSTIC(ClassRedefinition, Error, "Redefinition of class {0}.",
  114. std::string);
  115. CARBON_DIAGNOSTIC(ClassPreviousDefinition, Note,
  116. "Previous definition was here.");
  117. context.emitter()
  118. .Build(parse_node, ClassRedefinition,
  119. context.names().GetFormatted(class_info.name_id).str())
  120. .Note(context.insts().Get(class_info.definition_id).parse_node(),
  121. ClassPreviousDefinition)
  122. .Emit();
  123. } else {
  124. class_info.definition_id = class_decl_id;
  125. class_info.scope_id = context.name_scopes().Add(class_decl_id);
  126. }
  127. // Enter the class scope.
  128. context.PushScope(class_decl_id, class_info.scope_id);
  129. // Introduce `Self`.
  130. context.AddNameToLookup(parse_node, SemIR::NameId::SelfType,
  131. context.types().GetInstId(class_info.self_type_id));
  132. context.inst_block_stack().Push();
  133. context.node_stack().Push(parse_node, class_id);
  134. context.args_type_info_stack().Push();
  135. // TODO: Handle the case where there's control flow in the class body. For
  136. // example:
  137. //
  138. // class C {
  139. // var v: if true then i32 else f64;
  140. // }
  141. //
  142. // We may need to track a list of instruction blocks here, as we do for a
  143. // function.
  144. class_info.body_block_id = context.inst_block_stack().PeekOrAdd();
  145. return true;
  146. }
  147. auto HandleBaseIntroducer(Context& context,
  148. Parse::BaseIntroducerId /*parse_node*/) -> bool {
  149. context.decl_state_stack().Push(DeclState::Base);
  150. return true;
  151. }
  152. auto HandleBaseColon(Context& /*context*/, Parse::BaseColonId /*parse_node*/)
  153. -> bool {
  154. return true;
  155. }
  156. namespace {
  157. // Information gathered about a base type specified in a `base` declaration.
  158. struct BaseInfo {
  159. // A `BaseInfo` representing an erroneous base.
  160. static const BaseInfo Error;
  161. SemIR::TypeId type_id;
  162. SemIR::NameScopeId scope_id;
  163. };
  164. constexpr BaseInfo BaseInfo::Error = {.type_id = SemIR::TypeId::Error,
  165. .scope_id = SemIR::NameScopeId::Invalid};
  166. } // namespace
  167. // If `type_id` is a class type, get its corresponding `SemIR::Class` object.
  168. // Otherwise returns `nullptr`.
  169. static auto TryGetAsClass(Context& context, SemIR::TypeId type_id)
  170. -> SemIR::Class* {
  171. auto class_type = context.types().TryGetAs<SemIR::ClassType>(type_id);
  172. if (!class_type) {
  173. return nullptr;
  174. }
  175. return &context.classes().Get(class_type->class_id);
  176. }
  177. // Diagnoses an attempt to derive from a final type.
  178. static auto DiagnoseBaseIsFinal(Context& context, Parse::NodeId parse_node,
  179. SemIR::TypeId base_type_id) -> void {
  180. CARBON_DIAGNOSTIC(BaseIsFinal, Error,
  181. "Deriving from final type `{0}`. Base type must be an "
  182. "`abstract` or `base` class.",
  183. std::string);
  184. context.emitter().Emit(parse_node, BaseIsFinal,
  185. context.sem_ir().StringifyType(base_type_id));
  186. }
  187. // Checks that the specified base type is valid.
  188. static auto CheckBaseType(Context& context, Parse::NodeId parse_node,
  189. SemIR::InstId base_expr_id) -> BaseInfo {
  190. auto base_type_id = ExprAsType(context, parse_node, base_expr_id);
  191. base_type_id = context.AsCompleteType(base_type_id, [&] {
  192. CARBON_DIAGNOSTIC(IncompleteTypeInBaseDecl, Error,
  193. "Base `{0}` is an incomplete type.", std::string);
  194. return context.emitter().Build(
  195. parse_node, IncompleteTypeInBaseDecl,
  196. context.sem_ir().StringifyType(base_type_id));
  197. });
  198. if (base_type_id == SemIR::TypeId::Error) {
  199. return BaseInfo::Error;
  200. }
  201. auto* base_class_info = TryGetAsClass(context, base_type_id);
  202. // The base must not be a final class.
  203. if (!base_class_info) {
  204. // For now, we treat all types that aren't introduced by a `class`
  205. // declaration as being final classes.
  206. // TODO: Once we have a better idea of which types are considered to be
  207. // classes, produce a better diagnostic for deriving from a non-class type.
  208. DiagnoseBaseIsFinal(context, parse_node, base_type_id);
  209. return BaseInfo::Error;
  210. }
  211. if (base_class_info->inheritance_kind == SemIR::Class::Final) {
  212. DiagnoseBaseIsFinal(context, parse_node, base_type_id);
  213. }
  214. CARBON_CHECK(base_class_info->scope_id.is_valid())
  215. << "Complete class should have a scope";
  216. return {.type_id = base_type_id, .scope_id = base_class_info->scope_id};
  217. }
  218. auto HandleBaseDecl(Context& context, Parse::BaseDeclId parse_node) -> bool {
  219. auto base_type_expr_id = context.node_stack().PopExpr();
  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(context.insts().Get(class_info.base_id).parse_node(),
  247. BasePrevious)
  248. .Emit();
  249. return true;
  250. }
  251. auto base_info = CheckBaseType(context, parse_node, base_type_expr_id);
  252. // The `base` value in the class scope has an unbound element type. Instance
  253. // binding will be performed when it's found by name lookup into an instance.
  254. auto field_type_inst_id = context.AddInst(SemIR::UnboundElementType{
  255. parse_node, context.GetBuiltinType(SemIR::BuiltinKind::TypeType),
  256. class_info.self_type_id, base_info.type_id});
  257. auto field_type_id = context.CanonicalizeType(field_type_inst_id);
  258. class_info.base_id = context.AddInst(SemIR::BaseDecl{
  259. parse_node, field_type_id, base_info.type_id,
  260. SemIR::ElementIndex(
  261. context.args_type_info_stack().PeekCurrentBlockContents().size())});
  262. // Add a corresponding field to the object representation of the class.
  263. // TODO: Consider whether we want to use `partial T` here.
  264. context.args_type_info_stack().AddInst(SemIR::StructTypeField{
  265. parse_node, 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.PopScope();
  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 =
  293. context.CanonicalizeStructType(parse_node, fields_id);
  294. return true;
  295. }
  296. } // namespace Carbon::Check