handle_impl.cpp 11 KB

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