handle_impl.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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. self_type.inst_id = SemIR::ErrorInst::TypeInstId;
  85. }
  86. }
  87. }
  88. // Introduce `Self`. Note that we add this name lexically rather than adding
  89. // to the `NameScopeId` of the `impl`, because this happens before we enter
  90. // the `impl` scope or even identify which `impl` we're declaring.
  91. // TODO: Revisit this once #3714 is resolved.
  92. AddNameToLookup(context, SemIR::NameId::SelfType, self_type.inst_id);
  93. context.node_stack().Push(node_id, self_type.inst_id);
  94. return true;
  95. }
  96. auto HandleParseNode(Context& context, Parse::ImplDefaultSelfAsId node_id)
  97. -> bool {
  98. auto self_inst_id = SemIR::TypeInstId::None;
  99. if (auto class_scope = TryAsClassScope(
  100. context, context.decl_name_stack().PeekParentScopeId())) {
  101. auto self_type_id = GetImplDefaultSelfType(context, *class_scope);
  102. // Build the implicit access to the enclosing `Self`.
  103. // TODO: Consider calling `HandleNameAsExpr` to build this implicit `Self`
  104. // expression. We've already done the work to check that the enclosing
  105. // context is a class and found its `Self`, so additionally performing an
  106. // unqualified name lookup would be redundant work, but would avoid
  107. // duplicating the handling of the `Self` expression.
  108. self_inst_id = AddTypeInst(
  109. context, node_id,
  110. SemIR::NameRef{.type_id = SemIR::TypeType::TypeId,
  111. .name_id = SemIR::NameId::SelfType,
  112. .value_id = context.types().GetInstId(self_type_id)});
  113. } else {
  114. CARBON_DIAGNOSTIC(ImplAsOutsideClass, Error,
  115. "`impl as` can only be used in a class");
  116. context.emitter().Emit(node_id, ImplAsOutsideClass);
  117. self_inst_id = SemIR::ErrorInst::TypeInstId;
  118. }
  119. // There's no need to push `Self` into scope here, because we can find it in
  120. // the parent class scope.
  121. context.node_stack().Push(node_id, self_inst_id);
  122. return true;
  123. }
  124. // Pops the parameters of an `impl`, forming a `NameComponent` with no
  125. // associated name that describes them.
  126. static auto PopImplIntroducerAndParamsAsNameComponent(
  127. Context& context, Parse::AnyImplDeclId end_of_decl_node_id)
  128. -> NameComponent {
  129. auto [implicit_params_loc_id, implicit_param_patterns_id] =
  130. context.node_stack()
  131. .PopWithNodeIdIf<Parse::NodeKind::ImplicitParamList>();
  132. if (implicit_param_patterns_id) {
  133. context.node_stack()
  134. .PopAndDiscardSoloNodeId<Parse::NodeKind::ImplicitParamListStart>();
  135. // Emit the `forall` match. This shouldn't produce any valid `Call` params,
  136. // because `impl`s are never actually called at runtime.
  137. auto call_params_id =
  138. CalleePatternMatch(context, *implicit_param_patterns_id,
  139. SemIR::InstBlockId::None, SemIR::InstBlockId::None);
  140. CARBON_CHECK(call_params_id == SemIR::InstBlockId::Empty ||
  141. llvm::all_of(context.inst_blocks().Get(call_params_id),
  142. [](SemIR::InstId inst_id) {
  143. return inst_id == SemIR::ErrorInst::InstId;
  144. }));
  145. }
  146. Parse::NodeId first_param_node_id =
  147. context.node_stack().PopForSoloNodeId<Parse::NodeKind::ImplIntroducer>();
  148. // Subtracting 1 since we don't want to include the final `{` or `;` of the
  149. // declaration when performing syntactic match.
  150. Parse::Tree::PostorderIterator last_param_iter(end_of_decl_node_id);
  151. --last_param_iter;
  152. auto pattern_block_id = SemIR::InstBlockId::None;
  153. if (implicit_param_patterns_id) {
  154. pattern_block_id = context.pattern_block_stack().Pop();
  155. context.full_pattern_stack().PopFullPattern();
  156. }
  157. return {.name_loc_id = Parse::NodeId::None,
  158. .name_id = SemIR::NameId::None,
  159. .first_param_node_id = first_param_node_id,
  160. .last_param_node_id = *last_param_iter,
  161. .implicit_params_loc_id = implicit_params_loc_id,
  162. .implicit_param_patterns_id =
  163. implicit_param_patterns_id.value_or(SemIR::InstBlockId::None),
  164. .params_loc_id = Parse::NodeId::None,
  165. .param_patterns_id = SemIR::InstBlockId::None,
  166. .call_params_id = SemIR::InstBlockId::None,
  167. .pattern_block_id = pattern_block_id};
  168. }
  169. // Build an ImplDecl describing the signature of an impl. This handles the
  170. // common logic shared by impl forward declarations and impl definitions.
  171. static auto BuildImplDecl(Context& context, Parse::AnyImplDeclId node_id,
  172. bool is_definition)
  173. -> std::pair<SemIR::ImplId, SemIR::InstId> {
  174. auto [constraint_node, constraint_id] =
  175. context.node_stack().PopExprWithNodeId();
  176. auto [self_type_node, self_type_inst_id] =
  177. context.node_stack().PopWithNodeId<Parse::NodeCategory::ImplAs>();
  178. // Pop the `impl` introducer and any `forall` parameters as a "name".
  179. auto name = PopImplIntroducerAndParamsAsNameComponent(context, node_id);
  180. auto decl_block_id = context.inst_block_stack().Pop();
  181. // Convert the constraint expression to a type.
  182. auto [constraint_type_inst_id, constraint_type_id] =
  183. ExprAsType(context, constraint_node, constraint_id);
  184. // Process modifiers.
  185. // TODO: Should we somehow permit access specifiers on `impl`s?
  186. auto introducer =
  187. context.decl_introducer_state_stack().Pop<Lex::TokenKind::Impl>();
  188. LimitModifiersOnDecl(context, introducer, KeywordModifierSet::ImplDecl);
  189. bool is_final = introducer.modifier_set.HasAnyOf(KeywordModifierSet::Final);
  190. // Finish processing the name, which should be empty, but might have
  191. // parameters.
  192. auto name_context = context.decl_name_stack().FinishImplName();
  193. CARBON_CHECK(name_context.state == DeclNameStack::NameContext::State::Empty);
  194. // TODO: Check for an orphan `impl`.
  195. // Add the impl declaration.
  196. auto impl_decl_id =
  197. AddPlaceholderInst(context, node_id,
  198. SemIR::ImplDecl{.impl_id = SemIR::ImplId::None,
  199. .decl_block_id = decl_block_id});
  200. // This requires that the facet type is identified. It returns None if an
  201. // error was diagnosed.
  202. auto specific_interface = CheckConstraintIsInterface(context, impl_decl_id,
  203. constraint_type_inst_id);
  204. auto impl_id = SemIR::ImplId::None;
  205. {
  206. SemIR::Impl impl_info = {
  207. name_context.MakeEntityWithParamsBase(name, impl_decl_id,
  208. /*is_extern=*/false,
  209. SemIR::LibraryNameId::None),
  210. {.self_id = self_type_inst_id,
  211. .constraint_id = constraint_type_inst_id,
  212. .interface = specific_interface,
  213. .is_final = is_final}};
  214. auto extend_node = introducer.modifier_node_id(ModifierOrder::Extend);
  215. impl_id = GetOrAddImpl(context, node_id, name.implicit_params_loc_id,
  216. impl_info, is_definition, extend_node);
  217. }
  218. // `GetOrAddImpl` either filled in the `impl_info` and returned a fresh
  219. // ImplId, or if we're redeclaring a previous impl, returned an existing
  220. // ImplId. Write that ImplId into the ImplDecl instruction and finish it.
  221. auto impl_decl = context.insts().GetAs<SemIR::ImplDecl>(impl_decl_id);
  222. impl_decl.impl_id = impl_id;
  223. ReplaceInstBeforeConstantUse(context, impl_decl_id, impl_decl);
  224. return {impl_id, impl_decl_id};
  225. }
  226. auto HandleParseNode(Context& context, Parse::ImplDeclId node_id) -> bool {
  227. auto [impl_id, impl_decl_id] =
  228. BuildImplDecl(context, node_id, /*is_definition=*/false);
  229. auto& impl = context.impls().Get(impl_id);
  230. context.decl_name_stack().PopScope();
  231. // Impl definitions are required in the same file as the declaration. We skip
  232. // this requirement if we've already issued an invalid redeclaration error, or
  233. // there is an error that would prevent the impl from being legal to define.
  234. if (impl.witness_id != SemIR::ErrorInst::InstId) {
  235. context.definitions_required_by_decl().push_back(impl_decl_id);
  236. }
  237. return true;
  238. }
  239. auto HandleParseNode(Context& context, Parse::ImplDefinitionStartId node_id)
  240. -> bool {
  241. auto [impl_id, impl_decl_id] =
  242. BuildImplDecl(context, node_id, /*is_definition=*/true);
  243. auto& impl = context.impls().Get(impl_id);
  244. CARBON_CHECK(!impl.has_definition_started());
  245. impl.definition_id = impl_decl_id;
  246. impl.scope_id =
  247. context.name_scopes().Add(impl_decl_id, SemIR::NameId::None,
  248. context.decl_name_stack().PeekParentScopeId());
  249. context.scope_stack().PushForEntity(
  250. impl_decl_id, impl.scope_id,
  251. context.generics().GetSelfSpecific(impl.generic_id));
  252. StartGenericDefinition(context, impl.generic_id);
  253. // This requires that the facet type is complete.
  254. ImplWitnessStartDefinition(context, impl);
  255. context.inst_block_stack().Push();
  256. context.node_stack().Push(node_id, impl_id);
  257. // TODO: Handle the case where there's control flow in the impl body. For
  258. // example:
  259. //
  260. // impl C as I {
  261. // fn F() -> if true then i32 else f64;
  262. // }
  263. //
  264. // We may need to track a list of instruction blocks here, as we do for a
  265. // function.
  266. impl.body_block_id = context.inst_block_stack().PeekOrAdd();
  267. return true;
  268. }
  269. auto HandleParseNode(Context& context, Parse::ImplDefinitionId /*node_id*/)
  270. -> bool {
  271. auto impl_id =
  272. context.node_stack().Pop<Parse::NodeKind::ImplDefinitionStart>();
  273. FinishImplWitness(context, impl_id);
  274. auto& impl = context.impls().Get(impl_id);
  275. impl.defined = true;
  276. FinishGenericDefinition(context, impl.generic_id);
  277. context.inst_block_stack().Pop();
  278. // The decl_name_stack and scopes are popped by `ProcessNodeIds`.
  279. return true;
  280. }
  281. } // namespace Carbon::Check