handle_impl.cpp 10 KB

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