handle_class.cpp 13 KB

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