handle_impl.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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/decl_name_stack.h"
  7. #include "toolchain/check/generic.h"
  8. #include "toolchain/check/handle.h"
  9. #include "toolchain/check/impl.h"
  10. #include "toolchain/check/merge.h"
  11. #include "toolchain/check/modifiers.h"
  12. #include "toolchain/check/pattern_match.h"
  13. #include "toolchain/parse/typed_nodes.h"
  14. #include "toolchain/sem_ir/ids.h"
  15. #include "toolchain/sem_ir/typed_insts.h"
  16. namespace Carbon::Check {
  17. auto HandleParseNode(Context& context, Parse::ImplIntroducerId node_id)
  18. -> bool {
  19. // Create an instruction block to hold the instructions created for the type
  20. // and interface.
  21. context.inst_block_stack().Push();
  22. // Push the bracketing node.
  23. context.node_stack().Push(node_id);
  24. // Optional modifiers follow.
  25. context.decl_introducer_state_stack().Push<Lex::TokenKind::Impl>();
  26. // An impl doesn't have a name per se, but it makes the processing more
  27. // consistent to imagine that it does. This also gives us a scope for implicit
  28. // parameters.
  29. context.decl_name_stack().PushScopeAndStartName();
  30. // This might be a generic impl.
  31. StartGenericDecl(context);
  32. // Push a pattern block for the signature of the `forall` (if any).
  33. // TODO: Instead use a separate parse node kinds for `impl` and `impl forall`,
  34. // and only push a pattern block in `forall` case.
  35. context.pattern_block_stack().Push();
  36. return true;
  37. }
  38. auto HandleParseNode(Context& context, Parse::ImplForallId node_id) -> bool {
  39. auto params_id =
  40. context.node_stack().Pop<Parse::NodeKind::ImplicitParamList>();
  41. context.node_stack()
  42. .PopAndDiscardSoloNodeId<Parse::NodeKind::ImplicitParamListStart>();
  43. context.node_stack().Push(node_id, params_id);
  44. return true;
  45. }
  46. auto HandleParseNode(Context& context, Parse::TypeImplAsId node_id) -> bool {
  47. auto [self_node, self_id] = context.node_stack().PopExprWithNodeId();
  48. self_id = ExprAsType(context, self_node, self_id).inst_id;
  49. context.node_stack().Push(node_id, self_id);
  50. // Introduce `Self`. Note that we add this name lexically rather than adding
  51. // to the `NameScopeId` of the `impl`, because this happens before we enter
  52. // the `impl` scope or even identify which `impl` we're declaring.
  53. // TODO: Revisit this once #3714 is resolved.
  54. context.AddNameToLookup(SemIR::NameId::SelfType, self_id);
  55. return true;
  56. }
  57. // If the specified name scope corresponds to a class, returns the corresponding
  58. // class declaration.
  59. // TODO: Should this be somewhere more central?
  60. static auto TryAsClassScope(Context& context, SemIR::NameScopeId scope_id)
  61. -> std::optional<SemIR::ClassDecl> {
  62. if (!scope_id.is_valid()) {
  63. return std::nullopt;
  64. }
  65. auto& scope = context.name_scopes().Get(scope_id);
  66. if (!scope.inst_id.is_valid()) {
  67. return std::nullopt;
  68. }
  69. return context.insts().TryGetAs<SemIR::ClassDecl>(scope.inst_id);
  70. }
  71. static auto GetDefaultSelfType(Context& context) -> SemIR::TypeId {
  72. auto parent_scope_id = context.decl_name_stack().PeekParentScopeId();
  73. if (auto class_decl = TryAsClassScope(context, parent_scope_id)) {
  74. return context.classes().Get(class_decl->class_id).self_type_id;
  75. }
  76. // TODO: This is also valid in a mixin.
  77. return SemIR::TypeId::Invalid;
  78. }
  79. auto HandleParseNode(Context& context, Parse::DefaultSelfImplAsId node_id)
  80. -> bool {
  81. auto self_type_id = GetDefaultSelfType(context);
  82. if (!self_type_id.is_valid()) {
  83. CARBON_DIAGNOSTIC(ImplAsOutsideClass, Error,
  84. "`impl as` can only be used in a class");
  85. context.emitter().Emit(node_id, ImplAsOutsideClass);
  86. self_type_id = SemIR::TypeId::Error;
  87. }
  88. // Build the implicit access to the enclosing `Self`.
  89. // TODO: Consider calling `HandleNameAsExpr` to build this implicit `Self`
  90. // expression. We've already done the work to check that the enclosing context
  91. // is a class and found its `Self`, so additionally performing an unqualified
  92. // name lookup would be redundant work, but would avoid duplicating the
  93. // handling of the `Self` expression.
  94. auto self_inst_id = context.AddInst(
  95. node_id,
  96. SemIR::NameRef{.type_id = SemIR::TypeId::TypeType,
  97. .name_id = SemIR::NameId::SelfType,
  98. .value_id = context.types().GetInstId(self_type_id)});
  99. // There's no need to push `Self` into scope here, because we can find it in
  100. // the parent class scope.
  101. context.node_stack().Push(node_id, self_inst_id);
  102. return true;
  103. }
  104. // Process an `extend impl` declaration by extending the impl scope with the
  105. // `impl`'s scope.
  106. static auto ExtendImpl(Context& context, Parse::NodeId extend_node,
  107. Parse::AnyImplDeclId node_id,
  108. Parse::NodeId self_type_node, SemIR::TypeId self_type_id,
  109. Parse::NodeId params_node,
  110. SemIR::InstId constraint_inst_id,
  111. SemIR::TypeId constraint_id) -> void {
  112. auto parent_scope_id = context.decl_name_stack().PeekParentScopeId();
  113. auto& parent_scope = context.name_scopes().Get(parent_scope_id);
  114. // TODO: This is also valid in a mixin.
  115. if (!TryAsClassScope(context, parent_scope_id)) {
  116. CARBON_DIAGNOSTIC(ExtendImplOutsideClass, Error,
  117. "`extend impl` can only be used in a class");
  118. context.emitter().Emit(node_id, ExtendImplOutsideClass);
  119. return;
  120. }
  121. if (params_node.is_valid()) {
  122. CARBON_DIAGNOSTIC(ExtendImplForall, Error,
  123. "cannot `extend` a parameterized `impl`");
  124. context.emitter().Emit(extend_node, ExtendImplForall);
  125. parent_scope.has_error = true;
  126. return;
  127. }
  128. if (context.parse_tree().node_kind(self_type_node) ==
  129. Parse::NodeKind::TypeImplAs) {
  130. CARBON_DIAGNOSTIC(ExtendImplSelfAs, Error,
  131. "cannot `extend` an `impl` with an explicit self type");
  132. auto diag = context.emitter().Build(extend_node, ExtendImplSelfAs);
  133. // If the explicit self type is not the default, just bail out.
  134. if (self_type_id != GetDefaultSelfType(context)) {
  135. diag.Emit();
  136. parent_scope.has_error = true;
  137. return;
  138. }
  139. // The explicit self type is the same as the default self type, so suggest
  140. // removing it and recover as if it were not present.
  141. if (auto self_as =
  142. context.parse_tree_and_subtrees().ExtractAs<Parse::TypeImplAs>(
  143. self_type_node)) {
  144. CARBON_DIAGNOSTIC(ExtendImplSelfAsDefault, Note,
  145. "remove the explicit `Self` type here");
  146. diag.Note(self_as->type_expr, ExtendImplSelfAsDefault);
  147. }
  148. diag.Emit();
  149. }
  150. auto interface_type =
  151. context.types().TryGetAs<SemIR::InterfaceType>(constraint_id);
  152. if (!interface_type) {
  153. context.TODO(node_id, "extending non-interface constraint");
  154. parent_scope.has_error = true;
  155. return;
  156. }
  157. auto& interface = context.interfaces().Get(interface_type->interface_id);
  158. if (!interface.is_defined()) {
  159. CARBON_DIAGNOSTIC(ExtendUndefinedInterface, Error,
  160. "`extend impl` requires a definition for interface {0}",
  161. InstIdAsType);
  162. auto diag = context.emitter().Build(node_id, ExtendUndefinedInterface,
  163. constraint_inst_id);
  164. context.NoteUndefinedInterface(interface_type->interface_id, diag);
  165. diag.Emit();
  166. parent_scope.has_error = true;
  167. return;
  168. }
  169. parent_scope.extended_scopes.push_back(interface.scope_id);
  170. }
  171. // Pops the parameters of an `impl`, forming a `NameComponent` with no
  172. // associated name that describes them.
  173. static auto PopImplIntroducerAndParamsAsNameComponent(
  174. Context& context, Parse::AnyImplDeclId end_of_decl_node_id)
  175. -> NameComponent {
  176. auto [implicit_params_loc_id, implicit_param_patterns_id] =
  177. context.node_stack().PopWithNodeIdIf<Parse::NodeKind::ImplForall>();
  178. ParameterBlocks parameter_blocks{
  179. .implicit_params_id = SemIR::InstBlockId::Invalid,
  180. .params_id = SemIR::InstBlockId::Invalid,
  181. .return_slot_id = SemIR::InstId::Invalid};
  182. if (implicit_param_patterns_id) {
  183. parameter_blocks =
  184. CalleePatternMatch(context, *implicit_param_patterns_id,
  185. SemIR::InstBlockId::Invalid, SemIR::InstId::Invalid);
  186. }
  187. Parse::NodeId first_param_node_id =
  188. context.node_stack().PopForSoloNodeId<Parse::NodeKind::ImplIntroducer>();
  189. Parse::NodeId last_param_node_id = end_of_decl_node_id;
  190. return {
  191. .name_loc_id = Parse::NodeId::Invalid,
  192. .name_id = SemIR::NameId::Invalid,
  193. .first_param_node_id = first_param_node_id,
  194. .last_param_node_id = last_param_node_id,
  195. .implicit_params_loc_id = implicit_params_loc_id,
  196. .implicit_params_id = parameter_blocks.implicit_params_id,
  197. .implicit_param_patterns_id =
  198. implicit_param_patterns_id.value_or(SemIR::InstBlockId::Invalid),
  199. .params_loc_id = Parse::NodeId::Invalid,
  200. .params_id = SemIR::InstBlockId::Invalid,
  201. .param_patterns_id = SemIR::InstBlockId::Invalid,
  202. .return_slot_pattern_id = SemIR::InstId::Invalid,
  203. .return_slot_id = SemIR::InstId::Invalid,
  204. .pattern_block_id = context.pattern_block_stack().Pop(),
  205. };
  206. }
  207. static auto MergeImplRedecl(Context& context, SemIR::Impl& new_impl,
  208. SemIR::ImplId prev_impl_id) -> bool {
  209. auto& prev_impl = context.impls().Get(prev_impl_id);
  210. // TODO: Following #3763, disallow redeclarations in different scopes.
  211. // If the parameters aren't the same, then this is not a redeclaration of this
  212. // `impl`. Keep looking for a prior declaration without issuing a diagnostic.
  213. if (!CheckRedeclParamsMatch(context, DeclParams(new_impl),
  214. DeclParams(prev_impl), SemIR::SpecificId::Invalid,
  215. /*check_syntax=*/true, /*diagnose=*/false)) {
  216. // NOLINTNEXTLINE(readability-simplify-boolean-expr)
  217. return false;
  218. }
  219. // TODO: CheckIsAllowedRedecl. We don't have a suitable NameId; decide if we
  220. // need to treat the `T as I` as a kind of name.
  221. // TODO: Merge information from the new declaration into the old one as
  222. // needed.
  223. return true;
  224. }
  225. // Build an ImplDecl describing the signature of an impl. This handles the
  226. // common logic shared by impl forward declarations and impl definitions.
  227. static auto BuildImplDecl(Context& context, Parse::AnyImplDeclId node_id,
  228. bool is_definition)
  229. -> std::pair<SemIR::ImplId, SemIR::InstId> {
  230. auto [constraint_node, constraint_id] =
  231. context.node_stack().PopExprWithNodeId();
  232. auto [self_type_node, self_inst_id] =
  233. context.node_stack().PopWithNodeId<Parse::NodeCategory::ImplAs>();
  234. auto self_type_id = context.GetTypeIdForTypeInst(self_inst_id);
  235. // Pop the `impl` introducer and any `forall` parameters as a "name".
  236. auto name = PopImplIntroducerAndParamsAsNameComponent(context, node_id);
  237. auto decl_block_id = context.inst_block_stack().Pop();
  238. // Convert the constraint expression to a type.
  239. // TODO: Check that its constant value is a constraint.
  240. auto [constraint_inst_id, constraint_type_id] =
  241. ExprAsType(context, constraint_node, constraint_id);
  242. // Process modifiers.
  243. // TODO: Should we somehow permit access specifiers on `impl`s?
  244. // TODO: Handle `final` modifier.
  245. auto introducer =
  246. context.decl_introducer_state_stack().Pop<Lex::TokenKind::Impl>();
  247. LimitModifiersOnDecl(context, introducer, KeywordModifierSet::ImplDecl);
  248. // Finish processing the name, which should be empty, but might have
  249. // parameters.
  250. auto name_context = context.decl_name_stack().FinishImplName();
  251. CARBON_CHECK(name_context.state == DeclNameStack::NameContext::State::Empty);
  252. // TODO: Check for an orphan `impl`.
  253. // Add the impl declaration.
  254. SemIR::ImplDecl impl_decl = {.impl_id = SemIR::ImplId::Invalid,
  255. .decl_block_id = decl_block_id};
  256. auto impl_decl_id =
  257. context.AddPlaceholderInst(SemIR::LocIdAndInst(node_id, impl_decl));
  258. SemIR::Impl impl_info = {
  259. name_context.MakeEntityWithParamsBase(name, impl_decl_id,
  260. /*is_extern=*/false,
  261. SemIR::LibraryNameId::Invalid),
  262. {.self_id = self_inst_id, .constraint_id = constraint_inst_id}};
  263. // Add the impl declaration.
  264. auto lookup_bucket_ref = context.impls().GetOrAddLookupBucket(impl_info);
  265. for (auto prev_impl_id : lookup_bucket_ref) {
  266. if (MergeImplRedecl(context, impl_info, prev_impl_id)) {
  267. impl_decl.impl_id = prev_impl_id;
  268. break;
  269. }
  270. }
  271. // Create a new impl if this isn't a valid redeclaration.
  272. if (!impl_decl.impl_id.is_valid()) {
  273. impl_info.generic_id = FinishGenericDecl(context, impl_decl_id);
  274. impl_decl.impl_id = context.impls().Add(impl_info);
  275. lookup_bucket_ref.push_back(impl_decl.impl_id);
  276. } else {
  277. FinishGenericRedecl(context, impl_decl_id,
  278. context.impls().Get(impl_decl.impl_id).generic_id);
  279. }
  280. // Write the impl ID into the ImplDecl.
  281. context.ReplaceInstBeforeConstantUse(impl_decl_id, impl_decl);
  282. // For an `extend impl` declaration, mark the impl as extending this `impl`.
  283. if (introducer.modifier_set.HasAnyOf(KeywordModifierSet::Extend)) {
  284. auto extend_node = introducer.modifier_node_id(ModifierOrder::Decl);
  285. ExtendImpl(context, extend_node, node_id, self_type_node, self_type_id,
  286. name.implicit_params_loc_id, constraint_inst_id,
  287. constraint_type_id);
  288. }
  289. if (!is_definition && context.IsImplFile()) {
  290. context.definitions_required().push_back(impl_decl_id);
  291. }
  292. return {impl_decl.impl_id, impl_decl_id};
  293. }
  294. auto HandleParseNode(Context& context, Parse::ImplDeclId node_id) -> bool {
  295. BuildImplDecl(context, node_id, /*is_definition=*/false);
  296. context.decl_name_stack().PopScope();
  297. return true;
  298. }
  299. auto HandleParseNode(Context& context, Parse::ImplDefinitionStartId node_id)
  300. -> bool {
  301. auto [impl_id, impl_decl_id] =
  302. BuildImplDecl(context, node_id, /*is_definition=*/true);
  303. auto& impl_info = context.impls().Get(impl_id);
  304. if (impl_info.is_defined()) {
  305. CARBON_DIAGNOSTIC(ImplRedefinition, Error,
  306. "redefinition of `impl {0} as {1}`", InstIdAsRawType,
  307. InstIdAsRawType);
  308. CARBON_DIAGNOSTIC(ImplPreviousDefinition, Note,
  309. "previous definition was here");
  310. context.emitter()
  311. .Build(node_id, ImplRedefinition, impl_info.self_id,
  312. impl_info.constraint_id)
  313. .Note(impl_info.definition_id, ImplPreviousDefinition)
  314. .Emit();
  315. } else {
  316. impl_info.definition_id = impl_decl_id;
  317. impl_info.scope_id = context.name_scopes().Add(
  318. impl_decl_id, SemIR::NameId::Invalid,
  319. context.decl_name_stack().PeekParentScopeId());
  320. }
  321. context.scope_stack().Push(
  322. impl_decl_id, impl_info.scope_id,
  323. context.generics().GetSelfSpecific(impl_info.generic_id));
  324. StartGenericDefinition(context);
  325. context.inst_block_stack().Push();
  326. context.node_stack().Push(node_id, impl_id);
  327. // TODO: Handle the case where there's control flow in the impl body. For
  328. // example:
  329. //
  330. // impl C as I {
  331. // fn F() -> if true then i32 else f64;
  332. // }
  333. //
  334. // We may need to track a list of instruction blocks here, as we do for a
  335. // function.
  336. impl_info.body_block_id = context.inst_block_stack().PeekOrAdd();
  337. return true;
  338. }
  339. auto HandleParseNode(Context& context, Parse::ImplDefinitionId /*node_id*/)
  340. -> bool {
  341. auto impl_id =
  342. context.node_stack().Pop<Parse::NodeKind::ImplDefinitionStart>();
  343. auto& impl_info = context.impls().Get(impl_id);
  344. if (!impl_info.is_defined()) {
  345. impl_info.witness_id = BuildImplWitness(context, impl_id);
  346. }
  347. FinishGenericDefinition(context, impl_info.generic_id);
  348. context.inst_block_stack().Pop();
  349. // The decl_name_stack and scopes are popped by `ProcessNodeIds`.
  350. return true;
  351. }
  352. } // namespace Carbon::Check