handle_impl.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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/node_ids.h"
  20. #include "toolchain/parse/typed_nodes.h"
  21. #include "toolchain/sem_ir/generic.h"
  22. #include "toolchain/sem_ir/ids.h"
  23. #include "toolchain/sem_ir/specific_interface.h"
  24. #include "toolchain/sem_ir/typed_insts.h"
  25. namespace Carbon::Check {
  26. // Returns the implicit `Self` type for an `impl` when it's in a `class`
  27. // declaration.
  28. //
  29. // TODO: Mixin scopes also have a default `Self` type.
  30. static auto GetImplDefaultSelfType(Context& context,
  31. const ClassScope& class_scope)
  32. -> SemIR::TypeId {
  33. return context.classes().Get(class_scope.class_decl.class_id).self_type_id;
  34. }
  35. auto HandleParseNode(Context& context, Parse::ImplIntroducerId node_id)
  36. -> bool {
  37. // This might be a generic impl.
  38. StartGenericDecl(context);
  39. // Create an instruction block to hold the instructions created for the type
  40. // and interface.
  41. context.inst_block_stack().Push();
  42. // Push the bracketing node.
  43. context.node_stack().Push(node_id);
  44. // Optional modifiers follow.
  45. context.decl_introducer_state_stack().Push<Lex::TokenKind::Impl>();
  46. // An impl doesn't have a name per se, but it makes the processing more
  47. // consistent to imagine that it does. This also gives us a scope for implicit
  48. // parameters.
  49. context.decl_name_stack().PushScopeAndStartName();
  50. return true;
  51. }
  52. auto HandleParseNode(Context& context, Parse::ForallId /*node_id*/) -> bool {
  53. // Push a pattern block for the signature of the `forall`.
  54. context.pattern_block_stack().Push();
  55. context.full_pattern_stack().PushFullPattern(
  56. FullPatternStack::Kind::ImplicitParamList);
  57. return true;
  58. }
  59. auto HandleParseNode(Context& context, Parse::ImplTypeAsId node_id) -> bool {
  60. auto [self_node, self_id] = context.node_stack().PopExprWithNodeId();
  61. auto self_type = ExprAsType(context, self_node, self_id);
  62. const auto& introducer = context.decl_introducer_state_stack().innermost();
  63. if (introducer.modifier_set.HasAnyOf(KeywordModifierSet::Extend)) {
  64. // TODO: Also handle the parent scope being a mixin.
  65. if (auto class_scope = TryAsClassScope(
  66. context, context.decl_name_stack().PeekParentScopeId())) {
  67. // If we're not inside a class at all, that will be diagnosed against the
  68. // `extend` elsewhere.
  69. auto extend_node = introducer.modifier_node_id(ModifierOrder::Extend);
  70. CARBON_DIAGNOSTIC(ExtendImplSelfAs, Error,
  71. "cannot `extend` an `impl` with an explicit self type");
  72. auto diag = context.emitter().Build(extend_node, ExtendImplSelfAs);
  73. if (self_type.type_id == GetImplDefaultSelfType(context, *class_scope)) {
  74. // If the explicit self type is the default, suggest removing it with a
  75. // diagnostic, but continue as if no error occurred since the self-type
  76. // is semantically valid.
  77. CARBON_DIAGNOSTIC(ExtendImplSelfAsDefault, Note,
  78. "remove the explicit `Self` type here");
  79. diag.Note(self_node, ExtendImplSelfAsDefault);
  80. if (self_type.type_id != SemIR::ErrorInst::TypeId) {
  81. diag.Emit();
  82. }
  83. } else if (self_type.type_id != SemIR::ErrorInst::TypeId) {
  84. // Otherwise, the self-type is an error.
  85. diag.Emit();
  86. self_type.inst_id = SemIR::ErrorInst::TypeInstId;
  87. }
  88. }
  89. }
  90. // Introduce `Self`. Note that we add this name lexically rather than adding
  91. // to the `NameScopeId` of the `impl`, because this happens before we enter
  92. // the `impl` scope or even identify which `impl` we're declaring.
  93. // TODO: Revisit this once #3714 is resolved.
  94. AddNameToLookup(context, SemIR::NameId::SelfType, self_type.inst_id);
  95. context.node_stack().Push(node_id, self_type.inst_id);
  96. return true;
  97. }
  98. auto HandleParseNode(Context& context, Parse::ImplDefaultSelfAsId node_id)
  99. -> bool {
  100. auto self_inst_id = SemIR::TypeInstId::None;
  101. if (auto class_scope = TryAsClassScope(
  102. context, context.decl_name_stack().PeekParentScopeId())) {
  103. auto self_type_id = GetImplDefaultSelfType(context, *class_scope);
  104. // Build the implicit access to the enclosing `Self`.
  105. // TODO: Consider calling `HandleNameAsExpr` to build this implicit `Self`
  106. // expression. We've already done the work to check that the enclosing
  107. // context is a class and found its `Self`, so additionally performing an
  108. // unqualified name lookup would be redundant work, but would avoid
  109. // duplicating the handling of the `Self` expression.
  110. self_inst_id = AddTypeInst(
  111. context, node_id,
  112. SemIR::NameRef{.type_id = SemIR::TypeType::TypeId,
  113. .name_id = SemIR::NameId::SelfType,
  114. .value_id = context.types().GetInstId(self_type_id)});
  115. } else {
  116. CARBON_DIAGNOSTIC(ImplAsOutsideClass, Error,
  117. "`impl as` can only be used in a class");
  118. context.emitter().Emit(node_id, ImplAsOutsideClass);
  119. self_inst_id = SemIR::ErrorInst::TypeInstId;
  120. }
  121. // There's no need to push `Self` into scope here, because we can find it in
  122. // the parent class scope.
  123. context.node_stack().Push(node_id, self_inst_id);
  124. return true;
  125. }
  126. // Pops the parameters of an `impl`, forming a `NameComponent` with no
  127. // associated name that describes them.
  128. static auto PopImplIntroducerAndParamsAsNameComponent(
  129. Context& context, Parse::AnyImplDeclId end_of_decl_node_id)
  130. -> NameComponent {
  131. auto [implicit_params_loc_id, implicit_param_patterns_id] =
  132. context.node_stack()
  133. .PopWithNodeIdIf<Parse::NodeKind::ImplicitParamList>();
  134. if (implicit_param_patterns_id) {
  135. context.node_stack()
  136. .PopAndDiscardSoloNodeId<Parse::NodeKind::ImplicitParamListStart>();
  137. // Emit the `forall` match. This shouldn't produce any valid `Call` params,
  138. // because `impl`s are never actually called at runtime.
  139. auto call_params_id =
  140. CalleePatternMatch(context, *implicit_param_patterns_id,
  141. SemIR::InstBlockId::None, SemIR::InstBlockId::None);
  142. CARBON_CHECK(call_params_id == SemIR::InstBlockId::Empty ||
  143. llvm::all_of(context.inst_blocks().Get(call_params_id),
  144. [](SemIR::InstId inst_id) {
  145. return inst_id == SemIR::ErrorInst::InstId;
  146. }));
  147. }
  148. Parse::NodeId first_param_node_id =
  149. context.node_stack().PopForSoloNodeId<Parse::NodeKind::ImplIntroducer>();
  150. // Subtracting 1 since we don't want to include the final `{` or `;` of the
  151. // declaration when performing syntactic match.
  152. Parse::Tree::PostorderIterator last_param_iter(end_of_decl_node_id);
  153. --last_param_iter;
  154. auto pattern_block_id = SemIR::InstBlockId::None;
  155. if (implicit_param_patterns_id) {
  156. pattern_block_id = context.pattern_block_stack().Pop();
  157. context.full_pattern_stack().PopFullPattern();
  158. }
  159. return {.name_loc_id = Parse::NodeId::None,
  160. .name_id = SemIR::NameId::None,
  161. .first_param_node_id = first_param_node_id,
  162. .last_param_node_id = *last_param_iter,
  163. .implicit_params_loc_id = implicit_params_loc_id,
  164. .implicit_param_patterns_id =
  165. implicit_param_patterns_id.value_or(SemIR::InstBlockId::None),
  166. .params_loc_id = Parse::NodeId::None,
  167. .param_patterns_id = SemIR::InstBlockId::None,
  168. .call_params_id = SemIR::InstBlockId::None,
  169. .pattern_block_id = pattern_block_id};
  170. }
  171. // Build an ImplDecl describing the signature of an impl. This handles the
  172. // common logic shared by impl forward declarations and impl definitions.
  173. static auto BuildImplDecl(Context& context, Parse::AnyImplDeclId node_id)
  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, 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. auto [impl_id, impl_decl_id] = BuildImplDecl(context, node_id);
  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] = BuildImplDecl(context, node_id);
  242. auto& impl = context.impls().Get(impl_id);
  243. CARBON_CHECK(!impl.has_definition_started());
  244. impl.definition_id = impl_decl_id;
  245. impl.scope_id =
  246. context.name_scopes().Add(impl_decl_id, SemIR::NameId::None,
  247. context.decl_name_stack().PeekParentScopeId());
  248. context.scope_stack().PushForEntity(
  249. impl_decl_id, impl.scope_id,
  250. context.generics().GetSelfSpecific(impl.generic_id));
  251. StartGenericDefinition(context, impl.generic_id);
  252. ImplWitnessStartDefinition(context, impl);
  253. context.inst_block_stack().Push();
  254. context.node_stack().Push(node_id, impl_id);
  255. // TODO: Handle the case where there's control flow in the impl body. For
  256. // example:
  257. //
  258. // impl C as I {
  259. // fn F() -> if true then i32 else f64;
  260. // }
  261. //
  262. // We may need to track a list of instruction blocks here, as we do for a
  263. // function.
  264. impl.body_block_id = context.inst_block_stack().PeekOrAdd();
  265. return true;
  266. }
  267. auto HandleParseNode(Context& context, Parse::ImplDefinitionId /*node_id*/)
  268. -> bool {
  269. auto impl_id =
  270. context.node_stack().Pop<Parse::NodeKind::ImplDefinitionStart>();
  271. FinishImplWitness(context, impl_id);
  272. auto& impl = context.impls().Get(impl_id);
  273. impl.defined = true;
  274. FinishGenericDefinition(context, impl.generic_id);
  275. context.inst_block_stack().Pop();
  276. // The decl_name_stack and scopes are popped by `ProcessNodeIds`.
  277. return true;
  278. }
  279. } // namespace Carbon::Check