handle_impl.cpp 20 KB

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