handle_impl.cpp 10 KB

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