handle_impl.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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/impl.h"
  8. #include "toolchain/check/modifiers.h"
  9. #include "toolchain/parse/typed_nodes.h"
  10. #include "toolchain/sem_ir/ids.h"
  11. #include "toolchain/sem_ir/typed_insts.h"
  12. namespace Carbon::Check {
  13. auto HandleImplIntroducer(Context& context, Parse::ImplIntroducerId node_id)
  14. -> bool {
  15. // Create an instruction block to hold the instructions created for the type
  16. // and interface.
  17. context.inst_block_stack().Push();
  18. // Push the bracketing node.
  19. context.node_stack().Push(node_id);
  20. // Optional modifiers follow.
  21. context.decl_state_stack().Push(DeclState::Impl);
  22. // An impl doesn't have a name per se, but it makes the processing more
  23. // consistent to imagine that it does. This also gives us a scope for implicit
  24. // parameters.
  25. context.decl_name_stack().PushScopeAndStartName();
  26. return true;
  27. }
  28. auto HandleImplForall(Context& context, Parse::ImplForallId node_id) -> bool {
  29. auto params_id =
  30. context.node_stack().Pop<Parse::NodeKind::ImplicitParamList>();
  31. context.node_stack().Push(node_id, params_id);
  32. return true;
  33. }
  34. auto HandleTypeImplAs(Context& context, Parse::TypeImplAsId node_id) -> bool {
  35. auto [self_node, self_id] = context.node_stack().PopExprWithNodeId();
  36. auto self_type_id = ExprAsType(context, self_node, self_id);
  37. context.node_stack().Push(node_id, self_type_id);
  38. // Introduce `Self`. Note that we add this name lexically rather than adding
  39. // to the `NameScopeId` of the `impl`, because this happens before we enter
  40. // the `impl` scope or even identify which `impl` we're declaring.
  41. // TODO: Revisit this once #3714 is resolved.
  42. context.AddNameToLookup(SemIR::NameId::SelfType,
  43. context.types().GetInstId(self_type_id));
  44. return true;
  45. }
  46. // If the specified name scope corresponds to a class, returns the corresponding
  47. // class declaration.
  48. // TODO: Should this be somewhere more central?
  49. static auto TryAsClassScope(Context& context, SemIR::NameScopeId scope_id)
  50. -> std::optional<SemIR::ClassDecl> {
  51. if (!scope_id.is_valid()) {
  52. return std::nullopt;
  53. }
  54. auto& scope = context.name_scopes().Get(scope_id);
  55. if (!scope.inst_id.is_valid()) {
  56. return std::nullopt;
  57. }
  58. return context.insts().TryGetAs<SemIR::ClassDecl>(scope.inst_id);
  59. }
  60. static auto GetDefaultSelfType(Context& context) -> SemIR::TypeId {
  61. auto enclosing_scope_id = context.decl_name_stack().PeekTargetScope();
  62. if (auto class_decl = TryAsClassScope(context, enclosing_scope_id)) {
  63. return context.classes().Get(class_decl->class_id).self_type_id;
  64. }
  65. // TODO: This is also valid in a mixin.
  66. return SemIR::TypeId::Invalid;
  67. }
  68. auto HandleDefaultSelfImplAs(Context& context,
  69. Parse::DefaultSelfImplAsId node_id) -> bool {
  70. auto self_type_id = GetDefaultSelfType(context);
  71. if (!self_type_id.is_valid()) {
  72. CARBON_DIAGNOSTIC(ImplAsOutsideClass, Error,
  73. "`impl as` can only be used in a class.");
  74. context.emitter().Emit(node_id, ImplAsOutsideClass);
  75. self_type_id = SemIR::TypeId::Error;
  76. }
  77. // There's no need to push `Self` into scope here, because we can find it in
  78. // the enclosing class scope.
  79. context.node_stack().Push(node_id, self_type_id);
  80. return true;
  81. }
  82. // Process an `extend impl` declaration by extending the impl scope with the
  83. // `impl`'s scope.
  84. static auto ExtendImpl(Context& context, Parse::NodeId extend_node,
  85. Parse::AnyImplDeclId node_id,
  86. Parse::NodeId self_type_node, SemIR::TypeId self_type_id,
  87. Parse::NodeId params_node, SemIR::TypeId constraint_id)
  88. -> void {
  89. auto enclosing_scope_id = context.decl_name_stack().PeekTargetScope();
  90. auto& enclosing_scope = context.name_scopes().Get(enclosing_scope_id);
  91. // TODO: This is also valid in a mixin.
  92. if (!TryAsClassScope(context, enclosing_scope_id)) {
  93. CARBON_DIAGNOSTIC(ExtendImplOutsideClass, Error,
  94. "`extend impl` can only be used in a class.");
  95. context.emitter().Emit(node_id, ExtendImplOutsideClass);
  96. return;
  97. }
  98. if (params_node.is_valid()) {
  99. CARBON_DIAGNOSTIC(ExtendImplForall, Error,
  100. "Cannot `extend` a parameterized `impl`.");
  101. context.emitter().Emit(extend_node, ExtendImplForall);
  102. enclosing_scope.has_error = true;
  103. return;
  104. }
  105. if (context.parse_tree().node_kind(self_type_node) ==
  106. Parse::NodeKind::TypeImplAs) {
  107. CARBON_DIAGNOSTIC(ExtendImplSelfAs, Error,
  108. "Cannot `extend` an `impl` with an explicit self type.");
  109. auto diag = context.emitter().Build(extend_node, ExtendImplSelfAs);
  110. // If the explicit self type is not the default, just bail out.
  111. if (self_type_id != GetDefaultSelfType(context)) {
  112. diag.Emit();
  113. enclosing_scope.has_error = true;
  114. return;
  115. }
  116. // The explicit self type is the same as the default self type, so suggest
  117. // removing it and recover as if it were not present.
  118. if (auto self_as =
  119. context.parse_tree().ExtractAs<Parse::TypeImplAs>(self_type_node)) {
  120. CARBON_DIAGNOSTIC(ExtendImplSelfAsDefault, Note,
  121. "Remove the explicit `Self` type here.");
  122. diag.Note(self_as->type_expr, ExtendImplSelfAsDefault);
  123. }
  124. diag.Emit();
  125. }
  126. auto interface_type =
  127. context.types().TryGetAs<SemIR::InterfaceType>(constraint_id);
  128. if (!interface_type) {
  129. context.TODO(node_id, "extending non-interface constraint");
  130. enclosing_scope.has_error = true;
  131. return;
  132. }
  133. auto& interface = context.interfaces().Get(interface_type->interface_id);
  134. if (!interface.is_defined()) {
  135. CARBON_DIAGNOSTIC(
  136. ExtendUndefinedInterface, Error,
  137. "`extend impl` requires a definition for interface `{0}`.",
  138. SemIR::TypeId);
  139. auto diag = context.emitter().Build(node_id, ExtendUndefinedInterface,
  140. constraint_id);
  141. context.NoteUndefinedInterface(interface_type->interface_id, diag);
  142. diag.Emit();
  143. enclosing_scope.has_error = true;
  144. return;
  145. }
  146. enclosing_scope.extended_scopes.push_back(interface.scope_id);
  147. }
  148. // Build an ImplDecl describing the signature of an impl. This handles the
  149. // common logic shared by impl forward declarations and impl definitions.
  150. static auto BuildImplDecl(Context& context, Parse::AnyImplDeclId node_id)
  151. -> std::pair<SemIR::ImplId, SemIR::InstId> {
  152. auto [constraint_node, constraint_id] =
  153. context.node_stack().PopExprWithNodeId();
  154. auto [self_type_node, self_type_id] =
  155. context.node_stack().PopWithNodeId<Parse::NodeCategory::ImplAs>();
  156. auto [params_node, params_id] =
  157. context.node_stack().PopWithNodeIdIf<Parse::NodeKind::ImplForall>();
  158. auto decl_block_id = context.inst_block_stack().Pop();
  159. context.node_stack().PopForSoloNodeId<Parse::NodeKind::ImplIntroducer>();
  160. // Convert the constraint expression to a type.
  161. // TODO: Check that its constant value is a constraint.
  162. auto constraint_type_id = ExprAsType(context, constraint_node, constraint_id);
  163. // Process modifiers.
  164. // TODO: Should we somehow permit access specifiers on `impl`s?
  165. // TODO: Handle `final` modifier.
  166. LimitModifiersOnDecl(context, KeywordModifierSet::ImplDecl,
  167. Lex::TokenKind::Impl);
  168. // Finish processing the name, which should be empty, but might have
  169. // parameters.
  170. auto name_context = context.decl_name_stack().FinishImplName();
  171. CARBON_CHECK(name_context.state == DeclNameStack::NameContext::State::Empty);
  172. // TODO: Check for an orphan `impl`.
  173. // TODO: Check parameters. Store them on the `Impl` in some form.
  174. static_cast<void>(params_id);
  175. // Add the impl declaration.
  176. // TODO: Does lookup in an impl file need to look for a prior impl declaration
  177. // in the api file?
  178. auto impl_id = context.impls().LookupOrAdd(self_type_id, constraint_type_id);
  179. auto impl_decl = SemIR::ImplDecl{impl_id, decl_block_id};
  180. auto impl_decl_id = context.AddInst({node_id, impl_decl});
  181. // For an `extend impl` declaration, mark the impl as extending this `impl`.
  182. if (!!(context.decl_state_stack().innermost().modifier_set &
  183. KeywordModifierSet::Extend)) {
  184. auto extend_node = context.decl_state_stack().innermost().modifier_node_id(
  185. ModifierOrder::Decl);
  186. ExtendImpl(context, extend_node, node_id, self_type_node, self_type_id,
  187. params_node, constraint_type_id);
  188. }
  189. context.decl_state_stack().Pop(DeclState::Impl);
  190. return {impl_decl.impl_id, impl_decl_id};
  191. }
  192. auto HandleImplDecl(Context& context, Parse::ImplDeclId node_id) -> bool {
  193. BuildImplDecl(context, node_id);
  194. context.decl_name_stack().PopScope();
  195. return true;
  196. }
  197. auto HandleImplDefinitionStart(Context& context,
  198. Parse::ImplDefinitionStartId node_id) -> bool {
  199. auto [impl_id, impl_decl_id] = BuildImplDecl(context, node_id);
  200. auto& impl_info = context.impls().Get(impl_id);
  201. if (impl_info.is_defined()) {
  202. CARBON_DIAGNOSTIC(ImplRedefinition, Error,
  203. "Redefinition of `impl {0} as {1}`.", SemIR::TypeId,
  204. SemIR::TypeId);
  205. CARBON_DIAGNOSTIC(ImplPreviousDefinition, Note,
  206. "Previous definition was here.");
  207. context.emitter()
  208. .Build(node_id, ImplRedefinition, impl_info.self_id,
  209. impl_info.constraint_id)
  210. .Note(impl_info.definition_id, ImplPreviousDefinition)
  211. .Emit();
  212. } else {
  213. impl_info.definition_id = impl_decl_id;
  214. impl_info.scope_id =
  215. context.name_scopes().Add(impl_decl_id, SemIR::NameId::Invalid,
  216. context.decl_name_stack().PeekTargetScope());
  217. }
  218. context.scope_stack().Push(impl_decl_id, impl_info.scope_id);
  219. context.inst_block_stack().Push();
  220. context.node_stack().Push(node_id, impl_id);
  221. // TODO: Handle the case where there's control flow in the impl body. For
  222. // example:
  223. //
  224. // impl C as I {
  225. // fn F() -> if true then i32 else f64;
  226. // }
  227. //
  228. // We may need to track a list of instruction blocks here, as we do for a
  229. // function.
  230. impl_info.body_block_id = context.inst_block_stack().PeekOrAdd();
  231. return true;
  232. }
  233. auto HandleImplDefinition(Context& context, Parse::ImplDefinitionId /*node_id*/)
  234. -> bool {
  235. auto impl_id =
  236. context.node_stack().Pop<Parse::NodeKind::ImplDefinitionStart>();
  237. if (!context.impls().Get(impl_id).is_defined()) {
  238. context.impls().Get(impl_id).witness_id =
  239. BuildImplWitness(context, impl_id);
  240. }
  241. context.inst_block_stack().Pop();
  242. context.decl_name_stack().PopScope();
  243. return true;
  244. }
  245. } // namespace Carbon::Check