handle_impl.cpp 19 KB

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