handle_impl.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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 <optional>
  5. #include <utility>
  6. #include "toolchain/check/context.h"
  7. #include "toolchain/check/convert.h"
  8. #include "toolchain/check/decl_name_stack.h"
  9. #include "toolchain/check/generic.h"
  10. #include "toolchain/check/handle.h"
  11. #include "toolchain/check/impl.h"
  12. #include "toolchain/check/inst.h"
  13. #include "toolchain/check/modifiers.h"
  14. #include "toolchain/check/name_lookup.h"
  15. #include "toolchain/check/pattern_match.h"
  16. #include "toolchain/check/type.h"
  17. #include "toolchain/check/type_completion.h"
  18. #include "toolchain/parse/typed_nodes.h"
  19. #include "toolchain/sem_ir/generic.h"
  20. #include "toolchain/sem_ir/ids.h"
  21. #include "toolchain/sem_ir/typed_insts.h"
  22. namespace Carbon::Check {
  23. auto HandleParseNode(Context& context, Parse::ImplIntroducerId node_id)
  24. -> bool {
  25. // This might be a generic impl.
  26. StartGenericDecl(context);
  27. // Create an instruction block to hold the instructions created for the type
  28. // and interface.
  29. context.inst_block_stack().Push();
  30. // Push the bracketing node.
  31. context.node_stack().Push(node_id);
  32. // Optional modifiers follow.
  33. context.decl_introducer_state_stack().Push<Lex::TokenKind::Impl>();
  34. // An impl doesn't have a name per se, but it makes the processing more
  35. // consistent to imagine that it does. This also gives us a scope for implicit
  36. // parameters.
  37. context.decl_name_stack().PushScopeAndStartName();
  38. return true;
  39. }
  40. auto HandleParseNode(Context& context, Parse::ForallId /*node_id*/) -> bool {
  41. // Push a pattern block for the signature of the `forall`.
  42. context.pattern_block_stack().Push();
  43. context.full_pattern_stack().PushFullPattern(
  44. FullPatternStack::Kind::ImplicitParamList);
  45. return true;
  46. }
  47. auto HandleParseNode(Context& context, Parse::ImplTypeAsId node_id) -> bool {
  48. auto [self_node, self_id] = context.node_stack().PopExprWithNodeId();
  49. auto self_type_inst_id = ExprAsType(context, self_node, self_id).inst_id;
  50. context.node_stack().Push(node_id, self_type_inst_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. AddNameToLookup(context, SemIR::NameId::SelfType, self_type_inst_id);
  56. return true;
  57. }
  58. auto HandleParseNode(Context& context, Parse::ImplDefaultSelfAsId node_id)
  59. -> bool {
  60. auto self_inst_id = SemIR::TypeInstId::None;
  61. if (auto self_type_id = GetImplDefaultSelfType(context);
  62. self_type_id.has_value()) {
  63. // Build the implicit access to the enclosing `Self`.
  64. // TODO: Consider calling `HandleNameAsExpr` to build this implicit `Self`
  65. // expression. We've already done the work to check that the enclosing
  66. // context is a class and found its `Self`, so additionally performing an
  67. // unqualified name lookup would be redundant work, but would avoid
  68. // duplicating the handling of the `Self` expression.
  69. self_inst_id = AddTypeInst(
  70. context, node_id,
  71. SemIR::NameRef{.type_id = SemIR::TypeType::TypeId,
  72. .name_id = SemIR::NameId::SelfType,
  73. .value_id = context.types().GetInstId(self_type_id)});
  74. } else {
  75. CARBON_DIAGNOSTIC(ImplAsOutsideClass, Error,
  76. "`impl as` can only be used in a class");
  77. context.emitter().Emit(node_id, ImplAsOutsideClass);
  78. self_inst_id = SemIR::ErrorInst::TypeInstId;
  79. }
  80. // There's no need to push `Self` into scope here, because we can find it in
  81. // the parent class scope.
  82. context.node_stack().Push(node_id, self_inst_id);
  83. return true;
  84. }
  85. // Pops the parameters of an `impl`, forming a `NameComponent` with no
  86. // associated name that describes them.
  87. static auto PopImplIntroducerAndParamsAsNameComponent(
  88. Context& context, Parse::AnyImplDeclId end_of_decl_node_id)
  89. -> NameComponent {
  90. auto [implicit_params_loc_id, implicit_param_patterns_id] =
  91. context.node_stack()
  92. .PopWithNodeIdIf<Parse::NodeKind::ImplicitParamList>();
  93. if (implicit_param_patterns_id) {
  94. context.node_stack()
  95. .PopAndDiscardSoloNodeId<Parse::NodeKind::ImplicitParamListStart>();
  96. // Emit the `forall` match. This shouldn't produce any valid `Call` params,
  97. // because `impl`s are never actually called at runtime.
  98. auto call_params_id =
  99. CalleePatternMatch(context, *implicit_param_patterns_id,
  100. SemIR::InstBlockId::None, SemIR::InstId::None);
  101. CARBON_CHECK(call_params_id == SemIR::InstBlockId::Empty ||
  102. llvm::all_of(context.inst_blocks().Get(call_params_id),
  103. [](SemIR::InstId inst_id) {
  104. return inst_id == SemIR::ErrorInst::InstId;
  105. }));
  106. }
  107. Parse::NodeId first_param_node_id =
  108. context.node_stack().PopForSoloNodeId<Parse::NodeKind::ImplIntroducer>();
  109. // Subtracting 1 since we don't want to include the final `{` or `;` of the
  110. // declaration when performing syntactic match.
  111. Parse::Tree::PostorderIterator last_param_iter(end_of_decl_node_id);
  112. --last_param_iter;
  113. auto pattern_block_id = SemIR::InstBlockId::None;
  114. if (implicit_param_patterns_id) {
  115. pattern_block_id = context.pattern_block_stack().Pop();
  116. context.full_pattern_stack().PopFullPattern();
  117. }
  118. return {.name_loc_id = Parse::NodeId::None,
  119. .name_id = SemIR::NameId::None,
  120. .first_param_node_id = first_param_node_id,
  121. .last_param_node_id = *last_param_iter,
  122. .implicit_params_loc_id = implicit_params_loc_id,
  123. .implicit_param_patterns_id =
  124. implicit_param_patterns_id.value_or(SemIR::InstBlockId::None),
  125. .params_loc_id = Parse::NodeId::None,
  126. .param_patterns_id = SemIR::InstBlockId::None,
  127. .call_params_id = SemIR::InstBlockId::None,
  128. .return_slot_pattern_id = SemIR::InstId::None,
  129. .pattern_block_id = pattern_block_id};
  130. }
  131. // Build an ImplDecl describing the signature of an impl. This handles the
  132. // common logic shared by impl forward declarations and impl definitions.
  133. static auto BuildImplDecl(Context& context, Parse::AnyImplDeclId node_id,
  134. bool is_definition)
  135. -> std::pair<SemIR::ImplId, SemIR::InstId> {
  136. auto [constraint_node, constraint_id] =
  137. context.node_stack().PopExprWithNodeId();
  138. auto [self_type_node, self_type_inst_id] =
  139. context.node_stack().PopWithNodeId<Parse::NodeCategory::ImplAs>();
  140. // Pop the `impl` introducer and any `forall` parameters as a "name".
  141. auto name = PopImplIntroducerAndParamsAsNameComponent(context, node_id);
  142. auto decl_block_id = context.inst_block_stack().Pop();
  143. // Convert the constraint expression to a type.
  144. auto [constraint_type_inst_id, constraint_type_id] =
  145. ExprAsType(context, constraint_node, constraint_id);
  146. // Process modifiers.
  147. // TODO: Should we somehow permit access specifiers on `impl`s?
  148. auto introducer =
  149. context.decl_introducer_state_stack().Pop<Lex::TokenKind::Impl>();
  150. LimitModifiersOnDecl(context, introducer, KeywordModifierSet::ImplDecl);
  151. bool is_final = introducer.modifier_set.HasAnyOf(KeywordModifierSet::Final);
  152. // Finish processing the name, which should be empty, but might have
  153. // parameters.
  154. auto name_context = context.decl_name_stack().FinishImplName();
  155. CARBON_CHECK(name_context.state == DeclNameStack::NameContext::State::Empty);
  156. // TODO: Check for an orphan `impl`.
  157. // Add the impl declaration.
  158. auto impl_decl_id =
  159. AddPlaceholderInst(context, node_id,
  160. SemIR::ImplDecl{.impl_id = SemIR::ImplId::None,
  161. .decl_block_id = decl_block_id});
  162. SemIR::Impl impl_info = {name_context.MakeEntityWithParamsBase(
  163. name, impl_decl_id,
  164. /*is_extern=*/false, SemIR::LibraryNameId::None),
  165. {.self_id = self_type_inst_id,
  166. .constraint_id = constraint_type_inst_id,
  167. // This requires that the facet type is identified.
  168. .interface = CheckConstraintIsInterface(
  169. context, impl_decl_id, constraint_type_inst_id),
  170. .is_final = is_final}};
  171. std::optional<ExtendImplDecl> extend_impl;
  172. if (introducer.modifier_set.HasAnyOf(KeywordModifierSet::Extend)) {
  173. extend_impl = ExtendImplDecl{
  174. .self_type_node_id = self_type_node,
  175. .constraint_type_id = constraint_type_id,
  176. .extend_node_id = introducer.modifier_node_id(ModifierOrder::Extend),
  177. };
  178. }
  179. return StartImplDecl(context, SemIR::LocId(node_id),
  180. name.implicit_params_loc_id, impl_info, is_definition,
  181. extend_impl);
  182. }
  183. auto HandleParseNode(Context& context, Parse::ImplDeclId node_id) -> bool {
  184. BuildImplDecl(context, node_id, /*is_definition=*/false);
  185. context.decl_name_stack().PopScope();
  186. return true;
  187. }
  188. auto HandleParseNode(Context& context, Parse::ImplDefinitionStartId node_id)
  189. -> bool {
  190. auto [impl_id, impl_decl_id] =
  191. BuildImplDecl(context, node_id, /*is_definition=*/true);
  192. auto& impl_info = context.impls().Get(impl_id);
  193. CARBON_CHECK(!impl_info.has_definition_started());
  194. impl_info.definition_id = impl_decl_id;
  195. impl_info.scope_id =
  196. context.name_scopes().Add(impl_decl_id, SemIR::NameId::None,
  197. context.decl_name_stack().PeekParentScopeId());
  198. context.scope_stack().PushForEntity(
  199. impl_decl_id, impl_info.scope_id,
  200. context.generics().GetSelfSpecific(impl_info.generic_id));
  201. StartGenericDefinition(context, impl_info.generic_id);
  202. // This requires that the facet type is complete.
  203. ImplWitnessStartDefinition(context, impl_info);
  204. context.inst_block_stack().Push();
  205. context.node_stack().Push(node_id, impl_id);
  206. // TODO: Handle the case where there's control flow in the impl body. For
  207. // example:
  208. //
  209. // impl C as I {
  210. // fn F() -> if true then i32 else f64;
  211. // }
  212. //
  213. // We may need to track a list of instruction blocks here, as we do for a
  214. // function.
  215. impl_info.body_block_id = context.inst_block_stack().PeekOrAdd();
  216. return true;
  217. }
  218. auto HandleParseNode(Context& context, Parse::ImplDefinitionId /*node_id*/)
  219. -> bool {
  220. auto impl_id =
  221. context.node_stack().Pop<Parse::NodeKind::ImplDefinitionStart>();
  222. FinishImplWitness(context, impl_id);
  223. auto& impl_info = context.impls().Get(impl_id);
  224. impl_info.defined = true;
  225. FinishGenericDefinition(context, impl_info.generic_id);
  226. context.inst_block_stack().Pop();
  227. // The decl_name_stack and scopes are popped by `ProcessNodeIds`.
  228. return true;
  229. }
  230. } // namespace Carbon::Check