handle_impl.cpp 17 KB

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