handle_class.cpp 20 KB

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