handle_class.cpp 20 KB

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