handle_class.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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. // If `type_id` is a class type, get its corresponding `SemIR::Class` object.
  10. // Otherwise returns `nullptr`.
  11. static auto TryGetAsClass(Context& context, SemIR::TypeId type_id)
  12. -> SemIR::Class* {
  13. auto class_type = context.types().TryGetAs<SemIR::ClassType>(type_id);
  14. if (!class_type) {
  15. return nullptr;
  16. }
  17. return &context.classes().Get(class_type->class_id);
  18. }
  19. auto HandleClassIntroducer(Context& context, Parse::ClassIntroducerId node_id)
  20. -> bool {
  21. // Create an instruction block to hold the instructions created as part of the
  22. // class signature, such as generic parameters.
  23. context.inst_block_stack().Push();
  24. // Push the bracketing node.
  25. context.node_stack().Push(node_id);
  26. // Optional modifiers and the name follow.
  27. context.decl_state_stack().Push(DeclState::Class);
  28. context.decl_name_stack().PushScopeAndStartName();
  29. return true;
  30. }
  31. static auto BuildClassDecl(Context& context, Parse::AnyClassDeclId node_id)
  32. -> std::tuple<SemIR::ClassId, SemIR::InstId> {
  33. if (context.node_stack().PopIf<Parse::NodeKind::TuplePattern>()) {
  34. context.TODO(node_id, "generic class");
  35. }
  36. if (context.node_stack().PopIf<Parse::NodeKind::ImplicitParamList>()) {
  37. context.TODO(node_id, "generic class");
  38. }
  39. auto name_context = context.decl_name_stack().FinishName();
  40. context.node_stack()
  41. .PopAndDiscardSoloNodeId<Parse::NodeKind::ClassIntroducer>();
  42. // Process modifiers.
  43. CheckAccessModifiersOnDecl(context, Lex::TokenKind::Class,
  44. name_context.target_scope_id);
  45. LimitModifiersOnDecl(context,
  46. KeywordModifierSet::Class | KeywordModifierSet::Access,
  47. Lex::TokenKind::Class);
  48. auto modifiers = context.decl_state_stack().innermost().modifier_set;
  49. if (!!(modifiers & KeywordModifierSet::Access)) {
  50. context.TODO(context.decl_state_stack().innermost().modifier_node_id(
  51. ModifierOrder::Access),
  52. "access modifier");
  53. }
  54. auto inheritance_kind =
  55. !!(modifiers & KeywordModifierSet::Abstract) ? SemIR::Class::Abstract
  56. : !!(modifiers & KeywordModifierSet::Base) ? SemIR::Class::Base
  57. : SemIR::Class::Final;
  58. context.decl_state_stack().Pop(DeclState::Class);
  59. auto decl_block_id = context.inst_block_stack().Pop();
  60. // Add the class declaration.
  61. auto class_decl = SemIR::ClassDecl{SemIR::TypeId::TypeType,
  62. SemIR::ClassId::Invalid, decl_block_id};
  63. auto class_decl_id = context.AddPlaceholderInst({node_id, class_decl});
  64. // Check whether this is a redeclaration.
  65. auto existing_id =
  66. context.decl_name_stack().LookupOrAddName(name_context, class_decl_id);
  67. if (existing_id.is_valid()) {
  68. if (auto existing_class_decl =
  69. context.insts().Get(existing_id).TryAs<SemIR::ClassDecl>()) {
  70. // This is a redeclaration of an existing class.
  71. class_decl.class_id = existing_class_decl->class_id;
  72. auto& class_info = context.classes().Get(class_decl.class_id);
  73. // The introducer kind must match the previous declaration.
  74. // TODO: The rule here is not yet decided. See #3384.
  75. if (class_info.inheritance_kind != inheritance_kind) {
  76. CARBON_DIAGNOSTIC(ClassRedeclarationDifferentIntroducer, Error,
  77. "Class redeclared with different inheritance kind.");
  78. CARBON_DIAGNOSTIC(ClassRedeclarationDifferentIntroducerPrevious, Note,
  79. "Previously declared here.");
  80. context.emitter()
  81. .Build(node_id, ClassRedeclarationDifferentIntroducer)
  82. .Note(existing_id, ClassRedeclarationDifferentIntroducerPrevious)
  83. .Emit();
  84. }
  85. // TODO: Check that the generic parameter list agrees with the prior
  86. // declaration.
  87. } else {
  88. // This is a redeclaration of something other than a class.
  89. context.DiagnoseDuplicateName(class_decl_id, existing_id);
  90. }
  91. }
  92. // Create a new class if this isn't a valid redeclaration.
  93. bool is_new_class = !class_decl.class_id.is_valid();
  94. if (is_new_class) {
  95. // TODO: If this is an invalid redeclaration of a non-class entity or there
  96. // was an error in the qualifier, we will have lost track of the class name
  97. // here. We should keep track of it even if the name is invalid.
  98. class_decl.class_id = context.classes().Add(
  99. {.name_id = name_context.name_id_for_new_inst(),
  100. .enclosing_scope_id = name_context.enclosing_scope_id_for_new_inst(),
  101. // `.self_type_id` depends on the ClassType, so is set below.
  102. .self_type_id = SemIR::TypeId::Invalid,
  103. .decl_id = class_decl_id,
  104. .inheritance_kind = inheritance_kind});
  105. }
  106. // Write the class ID into the ClassDecl.
  107. context.ReplaceInstBeforeConstantUse(class_decl_id, class_decl);
  108. if (is_new_class) {
  109. // Build the `Self` type using the resulting type constant.
  110. auto& class_info = context.classes().Get(class_decl.class_id);
  111. class_info.self_type_id = context.GetTypeIdForTypeInst(class_decl_id);
  112. }
  113. return {class_decl.class_id, class_decl_id};
  114. }
  115. auto HandleClassDecl(Context& context, Parse::ClassDeclId node_id) -> bool {
  116. BuildClassDecl(context, node_id);
  117. context.decl_name_stack().PopScope();
  118. return true;
  119. }
  120. auto HandleClassDefinitionStart(Context& context,
  121. Parse::ClassDefinitionStartId node_id) -> bool {
  122. auto [class_id, class_decl_id] = BuildClassDecl(context, node_id);
  123. auto& class_info = context.classes().Get(class_id);
  124. // Track that this declaration is the definition.
  125. if (class_info.is_defined()) {
  126. CARBON_DIAGNOSTIC(ClassRedefinition, Error, "Redefinition of class {0}.",
  127. SemIR::NameId);
  128. CARBON_DIAGNOSTIC(ClassPreviousDefinition, Note,
  129. "Previous definition was here.");
  130. context.emitter()
  131. .Build(node_id, ClassRedefinition, class_info.name_id)
  132. .Note(class_info.definition_id, ClassPreviousDefinition)
  133. .Emit();
  134. } else {
  135. class_info.definition_id = class_decl_id;
  136. class_info.scope_id = context.name_scopes().Add(
  137. class_decl_id, SemIR::NameId::Invalid, class_info.enclosing_scope_id);
  138. }
  139. // Enter the class scope.
  140. context.scope_stack().Push(class_decl_id, class_info.scope_id);
  141. // Introduce `Self`.
  142. context.name_scopes()
  143. .Get(class_info.scope_id)
  144. .names.insert({SemIR::NameId::SelfType,
  145. context.types().GetInstId(class_info.self_type_id)});
  146. context.inst_block_stack().Push();
  147. context.node_stack().Push(node_id, class_id);
  148. context.args_type_info_stack().Push();
  149. // TODO: Handle the case where there's control flow in the class body. For
  150. // example:
  151. //
  152. // class C {
  153. // var v: if true then i32 else f64;
  154. // }
  155. //
  156. // We may need to track a list of instruction blocks here, as we do for a
  157. // function.
  158. class_info.body_block_id = context.inst_block_stack().PeekOrAdd();
  159. return true;
  160. }
  161. // Diagnoses a class-specific declaration appearing outside a class.
  162. static auto DiagnoseClassSpecificDeclOutsideClass(Context& context,
  163. SemIRLoc loc,
  164. Lex::TokenKind tok) -> void {
  165. CARBON_DIAGNOSTIC(ClassSpecificDeclOutsideClass, Error,
  166. "`{0}` declaration can only be used in a class.",
  167. Lex::TokenKind);
  168. context.emitter().Emit(loc, ClassSpecificDeclOutsideClass, tok);
  169. }
  170. // Returns the declaration of the immediately-enclosing class scope, or
  171. // diagonses if there isn't one.
  172. static auto GetEnclosingClassOrDiagnose(Context& context, SemIRLoc loc,
  173. Lex::TokenKind tok)
  174. -> std::optional<SemIR::ClassDecl> {
  175. auto class_scope = context.GetCurrentScopeAs<SemIR::ClassDecl>();
  176. if (!class_scope) {
  177. DiagnoseClassSpecificDeclOutsideClass(context, loc, tok);
  178. }
  179. return class_scope;
  180. }
  181. // Diagnoses a class-specific declaration that is repeated within a class, but
  182. // is not permitted to be repeated.
  183. static auto DiagnoseClassSpecificDeclRepeated(Context& context,
  184. SemIRLoc new_loc,
  185. SemIRLoc prev_loc,
  186. Lex::TokenKind tok) -> void {
  187. CARBON_DIAGNOSTIC(ClassSpecificDeclRepeated, Error,
  188. "Multiple `{0}` declarations in class.{1}", Lex::TokenKind,
  189. std::string);
  190. const llvm::StringRef extra = tok == Lex::TokenKind::Base
  191. ? " Multiple inheritance is not permitted."
  192. : "";
  193. CARBON_DIAGNOSTIC(ClassSpecificDeclPrevious, Note,
  194. "Previous `{0}` declaration is here.", Lex::TokenKind);
  195. context.emitter()
  196. .Build(new_loc, ClassSpecificDeclRepeated, tok, extra.str())
  197. .Note(prev_loc, ClassSpecificDeclPrevious, tok)
  198. .Emit();
  199. }
  200. auto HandleAdaptIntroducer(Context& context,
  201. Parse::AdaptIntroducerId /*node_id*/) -> bool {
  202. context.decl_state_stack().Push(DeclState::Adapt);
  203. return true;
  204. }
  205. auto HandleAdaptDecl(Context& context, Parse::AdaptDeclId node_id) -> bool {
  206. auto [adapted_type_node, adapted_type_expr_id] =
  207. context.node_stack().PopExprWithNodeId();
  208. // Process modifiers. `extend` is permitted, no others are allowed.
  209. LimitModifiersOnDecl(context, KeywordModifierSet::Extend,
  210. Lex::TokenKind::Adapt);
  211. auto modifiers = context.decl_state_stack().innermost().modifier_set;
  212. context.decl_state_stack().Pop(DeclState::Adapt);
  213. auto enclosing_class_decl =
  214. GetEnclosingClassOrDiagnose(context, node_id, Lex::TokenKind::Adapt);
  215. if (!enclosing_class_decl) {
  216. return true;
  217. }
  218. auto& class_info = context.classes().Get(enclosing_class_decl->class_id);
  219. if (class_info.adapt_id.is_valid()) {
  220. DiagnoseClassSpecificDeclRepeated(context, node_id, class_info.adapt_id,
  221. Lex::TokenKind::Adapt);
  222. return true;
  223. }
  224. auto adapted_type_id = ExprAsType(context, node_id, adapted_type_expr_id);
  225. adapted_type_id = context.AsCompleteType(adapted_type_id, [&] {
  226. CARBON_DIAGNOSTIC(IncompleteTypeInAdaptDecl, Error,
  227. "Adapted type `{0}` is an incomplete type.",
  228. SemIR::TypeId);
  229. return context.emitter().Build(node_id, IncompleteTypeInAdaptDecl,
  230. adapted_type_id);
  231. });
  232. // Build a SemIR representation for the declaration.
  233. class_info.adapt_id =
  234. context.AddInst({node_id, SemIR::AdaptDecl{adapted_type_id}});
  235. // Extend the class scope with the adapted type's scope if requested.
  236. if (!!(modifiers & KeywordModifierSet::Extend)) {
  237. auto extended_scope_id = SemIR::NameScopeId::Invalid;
  238. if (adapted_type_id == SemIR::TypeId::Error) {
  239. // Recover by not extending any scope. We instead set has_error to true
  240. // below.
  241. } else if (auto* adapted_class_info =
  242. TryGetAsClass(context, adapted_type_id)) {
  243. extended_scope_id = adapted_class_info->scope_id;
  244. CARBON_CHECK(adapted_class_info->scope_id.is_valid())
  245. << "Complete class should have a scope";
  246. } else {
  247. // TODO: Accept any type that has a scope.
  248. context.TODO(node_id, "extending non-class type");
  249. }
  250. auto& class_scope = context.name_scopes().Get(class_info.scope_id);
  251. if (extended_scope_id.is_valid()) {
  252. class_scope.extended_scopes.push_back(extended_scope_id);
  253. } else {
  254. class_scope.has_error = true;
  255. }
  256. }
  257. return true;
  258. }
  259. auto HandleBaseIntroducer(Context& context, Parse::BaseIntroducerId /*node_id*/)
  260. -> bool {
  261. context.decl_state_stack().Push(DeclState::Base);
  262. return true;
  263. }
  264. auto HandleBaseColon(Context& /*context*/, Parse::BaseColonId /*node_id*/)
  265. -> bool {
  266. return true;
  267. }
  268. namespace {
  269. // Information gathered about a base type specified in a `base` declaration.
  270. struct BaseInfo {
  271. // A `BaseInfo` representing an erroneous base.
  272. static const BaseInfo Error;
  273. SemIR::TypeId type_id;
  274. SemIR::NameScopeId scope_id;
  275. };
  276. constexpr BaseInfo BaseInfo::Error = {.type_id = SemIR::TypeId::Error,
  277. .scope_id = SemIR::NameScopeId::Invalid};
  278. } // namespace
  279. // Diagnoses an attempt to derive from a final type.
  280. static auto DiagnoseBaseIsFinal(Context& context, Parse::NodeId node_id,
  281. SemIR::TypeId base_type_id) -> void {
  282. CARBON_DIAGNOSTIC(BaseIsFinal, Error,
  283. "Deriving from final type `{0}`. Base type must be an "
  284. "`abstract` or `base` class.",
  285. SemIR::TypeId);
  286. context.emitter().Emit(node_id, BaseIsFinal, base_type_id);
  287. }
  288. // Checks that the specified base type is valid.
  289. static auto CheckBaseType(Context& context, Parse::NodeId node_id,
  290. SemIR::InstId base_expr_id) -> BaseInfo {
  291. auto base_type_id = ExprAsType(context, node_id, base_expr_id);
  292. base_type_id = context.AsCompleteType(base_type_id, [&] {
  293. CARBON_DIAGNOSTIC(IncompleteTypeInBaseDecl, Error,
  294. "Base `{0}` is an incomplete type.", SemIR::TypeId);
  295. return context.emitter().Build(node_id, IncompleteTypeInBaseDecl,
  296. base_type_id);
  297. });
  298. if (base_type_id == SemIR::TypeId::Error) {
  299. return BaseInfo::Error;
  300. }
  301. auto* base_class_info = TryGetAsClass(context, base_type_id);
  302. // The base must not be a final class.
  303. if (!base_class_info) {
  304. // For now, we treat all types that aren't introduced by a `class`
  305. // declaration as being final classes.
  306. // TODO: Once we have a better idea of which types are considered to be
  307. // classes, produce a better diagnostic for deriving from a non-class type.
  308. DiagnoseBaseIsFinal(context, node_id, base_type_id);
  309. return BaseInfo::Error;
  310. }
  311. if (base_class_info->inheritance_kind == SemIR::Class::Final) {
  312. DiagnoseBaseIsFinal(context, node_id, base_type_id);
  313. }
  314. CARBON_CHECK(base_class_info->scope_id.is_valid())
  315. << "Complete class should have a scope";
  316. return {.type_id = base_type_id, .scope_id = base_class_info->scope_id};
  317. }
  318. auto HandleBaseDecl(Context& context, Parse::BaseDeclId node_id) -> bool {
  319. auto [base_type_node_id, base_type_expr_id] =
  320. context.node_stack().PopExprWithNodeId();
  321. // Process modifiers. `extend` is required, no others are allowed.
  322. LimitModifiersOnDecl(context, KeywordModifierSet::Extend,
  323. Lex::TokenKind::Base);
  324. auto modifiers = context.decl_state_stack().innermost().modifier_set;
  325. if (!(modifiers & KeywordModifierSet::Extend)) {
  326. CARBON_DIAGNOSTIC(BaseMissingExtend, Error,
  327. "Missing `extend` before `base` declaration in class.");
  328. context.emitter().Emit(node_id, BaseMissingExtend);
  329. }
  330. context.decl_state_stack().Pop(DeclState::Base);
  331. auto enclosing_class_decl =
  332. GetEnclosingClassOrDiagnose(context, node_id, Lex::TokenKind::Base);
  333. if (!enclosing_class_decl) {
  334. return true;
  335. }
  336. auto& class_info = context.classes().Get(enclosing_class_decl->class_id);
  337. if (class_info.base_id.is_valid()) {
  338. DiagnoseClassSpecificDeclRepeated(context, node_id, class_info.base_id,
  339. Lex::TokenKind::Base);
  340. return true;
  341. }
  342. auto base_info = CheckBaseType(context, base_type_node_id, base_type_expr_id);
  343. // The `base` value in the class scope has an unbound element type. Instance
  344. // binding will be performed when it's found by name lookup into an instance.
  345. auto field_type_id =
  346. context.GetUnboundElementType(class_info.self_type_id, base_info.type_id);
  347. class_info.base_id = context.AddInst(
  348. {node_id,
  349. SemIR::BaseDecl{field_type_id, base_info.type_id,
  350. SemIR::ElementIndex(context.args_type_info_stack()
  351. .PeekCurrentBlockContents()
  352. .size())}});
  353. // Add a corresponding field to the object representation of the class.
  354. // TODO: Consider whether we want to use `partial T` here.
  355. // TODO: Should we diagnose if there are already any fields?
  356. context.args_type_info_stack().AddInstId(context.AddInstInNoBlock(
  357. {node_id,
  358. SemIR::StructTypeField{SemIR::NameId::Base, base_info.type_id}}));
  359. // Bind the name `base` in the class to the base field.
  360. context.decl_name_stack().AddNameToLookup(
  361. context.decl_name_stack().MakeUnqualifiedName(node_id,
  362. SemIR::NameId::Base),
  363. class_info.base_id);
  364. // Extend the class scope with the base class.
  365. if (!!(modifiers & KeywordModifierSet::Extend)) {
  366. auto& class_scope = context.name_scopes().Get(class_info.scope_id);
  367. if (base_info.scope_id.is_valid()) {
  368. class_scope.extended_scopes.push_back(base_info.scope_id);
  369. } else {
  370. class_scope.has_error = true;
  371. }
  372. }
  373. return true;
  374. }
  375. auto HandleClassDefinition(Context& context,
  376. Parse::ClassDefinitionId /*node_id*/) -> bool {
  377. auto fields_id = context.args_type_info_stack().Pop();
  378. auto class_id =
  379. context.node_stack().Pop<Parse::NodeKind::ClassDefinitionStart>();
  380. context.inst_block_stack().Pop();
  381. // The class type is now fully defined. Compute its object representation.
  382. auto& class_info = context.classes().Get(class_id);
  383. if (class_info.adapt_id.is_valid()) {
  384. class_info.object_repr_id = SemIR::TypeId::Error;
  385. if (class_info.base_id.is_valid()) {
  386. CARBON_DIAGNOSTIC(AdaptWithBase, Error,
  387. "Adapter cannot have a base class.");
  388. CARBON_DIAGNOSTIC(AdaptBaseHere, Note, "`base` declaration is here.");
  389. context.emitter()
  390. .Build(class_info.adapt_id, AdaptWithBase)
  391. .Note(class_info.base_id, AdaptBaseHere)
  392. .Emit();
  393. } else if (!context.inst_blocks().Get(fields_id).empty()) {
  394. auto first_field_id = context.inst_blocks().Get(fields_id).front();
  395. CARBON_DIAGNOSTIC(AdaptWithFields, Error, "Adapter cannot have fields.");
  396. CARBON_DIAGNOSTIC(AdaptFieldHere, Note,
  397. "First field declaration is here.");
  398. context.emitter()
  399. .Build(class_info.adapt_id, AdaptWithFields)
  400. .Note(first_field_id, AdaptFieldHere)
  401. .Emit();
  402. } else {
  403. // The object representation of the adapter is the adapted type.
  404. // TODO: If the adapted type is a class, should we use its object
  405. // representation type instead?
  406. class_info.object_repr_id =
  407. context.insts()
  408. .GetAs<SemIR::AdaptDecl>(class_info.adapt_id)
  409. .adapted_type_id;
  410. }
  411. } else {
  412. class_info.object_repr_id = context.GetStructType(fields_id);
  413. }
  414. // The decl_name_stack and scopes are popped by `ProcessNodeIds`.
  415. return true;
  416. }
  417. } // namespace Carbon::Check