handle_impl.cpp 11 KB

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