handle_impl.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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/name_scope.h"
  16. #include "toolchain/check/pattern_match.h"
  17. #include "toolchain/check/type.h"
  18. #include "toolchain/check/type_completion.h"
  19. #include "toolchain/parse/typed_nodes.h"
  20. #include "toolchain/sem_ir/generic.h"
  21. #include "toolchain/sem_ir/ids.h"
  22. #include "toolchain/sem_ir/typed_insts.h"
  23. namespace Carbon::Check {
  24. // Returns the implicit `Self` type for an `impl` when it's in a `class`
  25. // declaration.
  26. //
  27. // TODO: Mixin scopes also have a default `Self` type.
  28. static auto GetImplDefaultSelfType(Context& context,
  29. const ClassScope& class_scope)
  30. -> SemIR::TypeId {
  31. return context.classes().Get(class_scope.class_decl.class_id).self_type_id;
  32. }
  33. auto HandleParseNode(Context& context, Parse::ImplIntroducerId node_id)
  34. -> bool {
  35. // This might be a generic impl.
  36. StartGenericDecl(context);
  37. // Create an instruction block to hold the instructions created for the type
  38. // and interface.
  39. context.inst_block_stack().Push();
  40. // Push the bracketing node.
  41. context.node_stack().Push(node_id);
  42. // Optional modifiers follow.
  43. context.decl_introducer_state_stack().Push<Lex::TokenKind::Impl>();
  44. // An impl doesn't have a name per se, but it makes the processing more
  45. // consistent to imagine that it does. This also gives us a scope for implicit
  46. // parameters.
  47. context.decl_name_stack().PushScopeAndStartName();
  48. return true;
  49. }
  50. auto HandleParseNode(Context& context, Parse::ForallId /*node_id*/) -> bool {
  51. // Push a pattern block for the signature of the `forall`.
  52. context.pattern_block_stack().Push();
  53. context.full_pattern_stack().PushFullPattern(
  54. FullPatternStack::Kind::ImplicitParamList);
  55. return true;
  56. }
  57. auto HandleParseNode(Context& context, Parse::ImplTypeAsId node_id) -> bool {
  58. auto [self_node, self_id] = context.node_stack().PopExprWithNodeId();
  59. auto self_type = ExprAsType(context, self_node, self_id);
  60. const auto& introducer = context.decl_introducer_state_stack().innermost();
  61. if (introducer.modifier_set.HasAnyOf(KeywordModifierSet::Extend)) {
  62. // TODO: Also handle the parent scope being a mixin.
  63. if (auto class_scope = TryAsClassScope(
  64. context, context.decl_name_stack().PeekParentScopeId())) {
  65. // If we're not inside a class at all, that will be diagnosed against the
  66. // `extend` elsewhere.
  67. auto extend_node = introducer.modifier_node_id(ModifierOrder::Extend);
  68. CARBON_DIAGNOSTIC(ExtendImplSelfAs, Error,
  69. "cannot `extend` an `impl` with an explicit self type");
  70. auto diag = context.emitter().Build(extend_node, ExtendImplSelfAs);
  71. if (self_type.type_id == GetImplDefaultSelfType(context, *class_scope)) {
  72. // If the explicit self type is the default, suggest removing it with a
  73. // diagnostic, but continue as if no error occurred since the self-type
  74. // is semantically valid.
  75. CARBON_DIAGNOSTIC(ExtendImplSelfAsDefault, Note,
  76. "remove the explicit `Self` type here");
  77. diag.Note(self_node, ExtendImplSelfAsDefault);
  78. if (self_type.type_id != SemIR::ErrorInst::TypeId) {
  79. diag.Emit();
  80. }
  81. } else if (self_type.type_id != SemIR::ErrorInst::TypeId) {
  82. // Otherwise, the self-type is an error.
  83. diag.Emit();
  84. class_scope->name_scope->set_has_error();
  85. self_type.inst_id = SemIR::ErrorInst::TypeInstId;
  86. }
  87. }
  88. }
  89. // Introduce `Self`. Note that we add this name lexically rather than adding
  90. // to the `NameScopeId` of the `impl`, because this happens before we enter
  91. // the `impl` scope or even identify which `impl` we're declaring.
  92. // TODO: Revisit this once #3714 is resolved.
  93. AddNameToLookup(context, SemIR::NameId::SelfType, self_type.inst_id);
  94. context.node_stack().Push(node_id, self_type.inst_id);
  95. return true;
  96. }
  97. auto HandleParseNode(Context& context, Parse::ImplDefaultSelfAsId node_id)
  98. -> bool {
  99. auto self_inst_id = SemIR::TypeInstId::None;
  100. if (auto class_scope = TryAsClassScope(
  101. context, context.decl_name_stack().PeekParentScopeId())) {
  102. auto self_type_id = GetImplDefaultSelfType(context, *class_scope);
  103. // Build the implicit access to the enclosing `Self`.
  104. // TODO: Consider calling `HandleNameAsExpr` to build this implicit `Self`
  105. // expression. We've already done the work to check that the enclosing
  106. // context is a class and found its `Self`, so additionally performing an
  107. // unqualified name lookup would be redundant work, but would avoid
  108. // duplicating the handling of the `Self` expression.
  109. self_inst_id = AddTypeInst(
  110. context, node_id,
  111. SemIR::NameRef{.type_id = SemIR::TypeType::TypeId,
  112. .name_id = SemIR::NameId::SelfType,
  113. .value_id = context.types().GetInstId(self_type_id)});
  114. } else {
  115. CARBON_DIAGNOSTIC(ImplAsOutsideClass, Error,
  116. "`impl as` can only be used in a class");
  117. context.emitter().Emit(node_id, ImplAsOutsideClass);
  118. self_inst_id = SemIR::ErrorInst::TypeInstId;
  119. }
  120. // There's no need to push `Self` into scope here, because we can find it in
  121. // the parent class scope.
  122. context.node_stack().Push(node_id, self_inst_id);
  123. return true;
  124. }
  125. // Pops the parameters of an `impl`, forming a `NameComponent` with no
  126. // associated name that describes them.
  127. static auto PopImplIntroducerAndParamsAsNameComponent(
  128. Context& context, Parse::AnyImplDeclId end_of_decl_node_id)
  129. -> NameComponent {
  130. auto [implicit_params_loc_id, implicit_param_patterns_id] =
  131. context.node_stack()
  132. .PopWithNodeIdIf<Parse::NodeKind::ImplicitParamList>();
  133. if (implicit_param_patterns_id) {
  134. context.node_stack()
  135. .PopAndDiscardSoloNodeId<Parse::NodeKind::ImplicitParamListStart>();
  136. // Emit the `forall` match. This shouldn't produce any valid `Call` params,
  137. // because `impl`s are never actually called at runtime.
  138. auto call_params_id =
  139. CalleePatternMatch(context, *implicit_param_patterns_id,
  140. SemIR::InstBlockId::None, SemIR::InstBlockId::None);
  141. CARBON_CHECK(call_params_id == SemIR::InstBlockId::Empty ||
  142. llvm::all_of(context.inst_blocks().Get(call_params_id),
  143. [](SemIR::InstId inst_id) {
  144. return inst_id == SemIR::ErrorInst::InstId;
  145. }));
  146. }
  147. Parse::NodeId first_param_node_id =
  148. context.node_stack().PopForSoloNodeId<Parse::NodeKind::ImplIntroducer>();
  149. // Subtracting 1 since we don't want to include the final `{` or `;` of the
  150. // declaration when performing syntactic match.
  151. Parse::Tree::PostorderIterator last_param_iter(end_of_decl_node_id);
  152. --last_param_iter;
  153. auto pattern_block_id = SemIR::InstBlockId::None;
  154. if (implicit_param_patterns_id) {
  155. pattern_block_id = context.pattern_block_stack().Pop();
  156. context.full_pattern_stack().PopFullPattern();
  157. }
  158. return {.name_loc_id = Parse::NodeId::None,
  159. .name_id = SemIR::NameId::None,
  160. .first_param_node_id = first_param_node_id,
  161. .last_param_node_id = *last_param_iter,
  162. .implicit_params_loc_id = implicit_params_loc_id,
  163. .implicit_param_patterns_id =
  164. implicit_param_patterns_id.value_or(SemIR::InstBlockId::None),
  165. .params_loc_id = Parse::NodeId::None,
  166. .param_patterns_id = SemIR::InstBlockId::None,
  167. .call_params_id = SemIR::InstBlockId::None,
  168. .pattern_block_id = pattern_block_id};
  169. }
  170. // Build an ImplDecl describing the signature of an impl. This handles the
  171. // common logic shared by impl forward declarations and impl definitions.
  172. static auto BuildImplDecl(Context& context, Parse::AnyImplDeclId node_id,
  173. bool is_definition)
  174. -> std::pair<SemIR::ImplId, SemIR::InstId> {
  175. auto [constraint_node, constraint_id] =
  176. context.node_stack().PopExprWithNodeId();
  177. auto [self_type_node, self_type_inst_id] =
  178. context.node_stack().PopWithNodeId<Parse::NodeCategory::ImplAs>();
  179. // Pop the `impl` introducer and any `forall` parameters as a "name".
  180. auto name = PopImplIntroducerAndParamsAsNameComponent(context, node_id);
  181. auto decl_block_id = context.inst_block_stack().Pop();
  182. // Convert the constraint expression to a type.
  183. auto [constraint_type_inst_id, constraint_type_id] =
  184. ExprAsType(context, constraint_node, constraint_id);
  185. // Process modifiers.
  186. // TODO: Should we somehow permit access specifiers on `impl`s?
  187. auto introducer =
  188. context.decl_introducer_state_stack().Pop<Lex::TokenKind::Impl>();
  189. LimitModifiersOnDecl(context, introducer, KeywordModifierSet::ImplDecl);
  190. bool is_final = introducer.modifier_set.HasAnyOf(KeywordModifierSet::Final);
  191. // Finish processing the name, which should be empty, but might have
  192. // parameters.
  193. auto name_context = context.decl_name_stack().FinishImplName();
  194. CARBON_CHECK(name_context.state == DeclNameStack::NameContext::State::Empty);
  195. // TODO: Check for an orphan `impl`.
  196. // Add the impl declaration.
  197. auto impl_decl_id =
  198. AddPlaceholderInst(context, node_id,
  199. SemIR::ImplDecl{.impl_id = SemIR::ImplId::None,
  200. .decl_block_id = decl_block_id});
  201. // This requires that the facet type is identified. It returns None if an
  202. // error was diagnosed.
  203. auto specific_interface = CheckConstraintIsInterface(context, impl_decl_id,
  204. constraint_type_inst_id);
  205. auto impl_id = SemIR::ImplId::None;
  206. {
  207. SemIR::Impl impl_info = {
  208. name_context.MakeEntityWithParamsBase(name, impl_decl_id,
  209. /*is_extern=*/false,
  210. SemIR::LibraryNameId::None),
  211. {.self_id = self_type_inst_id,
  212. .constraint_id = constraint_type_inst_id,
  213. .interface = specific_interface,
  214. .is_final = is_final}};
  215. auto extend_node = introducer.modifier_node_id(ModifierOrder::Extend);
  216. impl_id = GetOrAddImpl(context, node_id, name.implicit_params_loc_id,
  217. impl_info, is_definition, extend_node);
  218. }
  219. // `GetOrAddImpl` either filled in the `impl_info` and returned a fresh
  220. // ImplId, or if we're redeclaring a previous impl, returned an existing
  221. // ImplId. Write that ImplId into the ImplDecl instruction and finish it.
  222. auto impl_decl = context.insts().GetAs<SemIR::ImplDecl>(impl_decl_id);
  223. impl_decl.impl_id = impl_id;
  224. ReplaceInstBeforeConstantUse(context, impl_decl_id, impl_decl);
  225. return {impl_id, impl_decl_id};
  226. }
  227. auto HandleParseNode(Context& context, Parse::ImplDeclId node_id) -> bool {
  228. BuildImplDecl(context, node_id, /*is_definition=*/false);
  229. context.decl_name_stack().PopScope();
  230. return true;
  231. }
  232. auto HandleParseNode(Context& context, Parse::ImplDefinitionStartId node_id)
  233. -> bool {
  234. auto [impl_id, impl_decl_id] =
  235. BuildImplDecl(context, node_id, /*is_definition=*/true);
  236. auto& impl_info = context.impls().Get(impl_id);
  237. CARBON_CHECK(!impl_info.has_definition_started());
  238. impl_info.definition_id = impl_decl_id;
  239. impl_info.scope_id =
  240. context.name_scopes().Add(impl_decl_id, SemIR::NameId::None,
  241. context.decl_name_stack().PeekParentScopeId());
  242. context.scope_stack().PushForEntity(
  243. impl_decl_id, impl_info.scope_id,
  244. context.generics().GetSelfSpecific(impl_info.generic_id));
  245. StartGenericDefinition(context, impl_info.generic_id);
  246. // This requires that the facet type is complete.
  247. ImplWitnessStartDefinition(context, impl_info);
  248. context.inst_block_stack().Push();
  249. context.node_stack().Push(node_id, impl_id);
  250. // TODO: Handle the case where there's control flow in the impl body. For
  251. // example:
  252. //
  253. // impl C as I {
  254. // fn F() -> if true then i32 else f64;
  255. // }
  256. //
  257. // We may need to track a list of instruction blocks here, as we do for a
  258. // function.
  259. impl_info.body_block_id = context.inst_block_stack().PeekOrAdd();
  260. return true;
  261. }
  262. auto HandleParseNode(Context& context, Parse::ImplDefinitionId /*node_id*/)
  263. -> bool {
  264. auto impl_id =
  265. context.node_stack().Pop<Parse::NodeKind::ImplDefinitionStart>();
  266. FinishImplWitness(context, impl_id);
  267. auto& impl_info = context.impls().Get(impl_id);
  268. impl_info.defined = true;
  269. FinishGenericDefinition(context, impl_info.generic_id);
  270. context.inst_block_stack().Pop();
  271. // The decl_name_stack and scopes are popped by `ProcessNodeIds`.
  272. return true;
  273. }
  274. } // namespace Carbon::Check