handle_impl.cpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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/sem_ir/ids.h"
  9. #include "toolchain/sem_ir/typed_insts.h"
  10. namespace Carbon::Check {
  11. auto HandleImplIntroducer(Context& context, Parse::ImplIntroducerId parse_node)
  12. -> bool {
  13. // Create an instruction block to hold the instructions created for the type
  14. // and interface.
  15. context.inst_block_stack().Push();
  16. // Push the bracketing node.
  17. context.node_stack().Push(parse_node);
  18. // Optional modifiers follow.
  19. context.decl_state_stack().Push(DeclState::Impl);
  20. // An impl doesn't have a name per se, but it makes the processing more
  21. // consistent to imagine that it does. This also gives us a scope for implicit
  22. // parameters.
  23. context.decl_name_stack().PushScopeAndStartName();
  24. return true;
  25. }
  26. auto HandleImplForall(Context& context, Parse::ImplForallId parse_node)
  27. -> bool {
  28. auto params_id =
  29. context.node_stack().Pop<Parse::NodeKind::ImplicitParamList>();
  30. context.node_stack().Push(parse_node, params_id);
  31. return true;
  32. }
  33. auto HandleTypeImplAs(Context& context, Parse::TypeImplAsId parse_node)
  34. -> bool {
  35. auto [self_node, self_id] = context.node_stack().PopExprWithParseNode();
  36. auto self_type_id = ExprAsType(context, self_node, self_id);
  37. context.node_stack().Push(parse_node, 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. auto HandleDefaultSelfImplAs(Context& context,
  57. Parse::DefaultSelfImplAsId parse_node) -> bool {
  58. // Find the enclosing scope for the `impl`.
  59. // TODO: Do this without modifying the node stack.
  60. auto implicit_param_list =
  61. context.node_stack().PopWithParseNodeIf<Parse::NodeKind::ImplForall>();
  62. auto enclosing_scope_id = context.decl_name_stack().PeekTargetScope();
  63. if (implicit_param_list) {
  64. context.node_stack().Push(implicit_param_list->first,
  65. implicit_param_list->second);
  66. }
  67. // TODO: This is also valid in a mixin.
  68. auto class_decl = TryAsClassScope(context, enclosing_scope_id);
  69. if (!class_decl) {
  70. return context.TODO(parse_node,
  71. "recover from `impl as` in non-class scope");
  72. }
  73. context.node_stack().Push(
  74. parse_node, context.classes().Get(class_decl->class_id).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::AnyImplDeclId parse_node,
  80. SemIR::TypeId constraint_id) -> void {
  81. auto enclosing_scope_id = context.decl_name_stack().PeekTargetScope();
  82. // TODO: This is also valid in a mixin.
  83. if (!TryAsClassScope(context, enclosing_scope_id)) {
  84. CARBON_DIAGNOSTIC(ExtendImplOutsideClass, Error,
  85. "`extend impl` can only be used in a class.");
  86. context.emitter().Emit(parse_node, ExtendImplOutsideClass);
  87. return;
  88. }
  89. auto& enclosing_scope = context.name_scopes().Get(enclosing_scope_id);
  90. auto interface_type =
  91. context.types().TryGetAs<SemIR::InterfaceType>(constraint_id);
  92. if (!interface_type) {
  93. context.TODO(parse_node, "extending non-interface constraint");
  94. enclosing_scope.has_error = true;
  95. return;
  96. }
  97. auto& interface = context.interfaces().Get(interface_type->interface_id);
  98. if (!interface.is_defined()) {
  99. CARBON_DIAGNOSTIC(
  100. ExtendUndefinedInterface, Error,
  101. "`extend impl` requires a definition for interface `{0}`.",
  102. SemIR::TypeId);
  103. auto diag = context.emitter().Build(parse_node, ExtendUndefinedInterface,
  104. constraint_id);
  105. context.NoteUndefinedInterface(interface_type->interface_id, diag);
  106. diag.Emit();
  107. enclosing_scope.has_error = true;
  108. return;
  109. }
  110. enclosing_scope.extended_scopes.push_back(interface.scope_id);
  111. }
  112. // Build an ImplDecl describing the signature of an impl. This handles the
  113. // common logic shared by impl forward declarations and impl definitions.
  114. static auto BuildImplDecl(Context& context, Parse::AnyImplDeclId parse_node)
  115. -> std::pair<SemIR::ImplId, SemIR::InstId> {
  116. auto [constraint_node, constraint_id] =
  117. context.node_stack().PopExprWithParseNode();
  118. auto self_type_id = context.node_stack().Pop<Parse::NodeCategory::ImplAs>();
  119. auto params_id = context.node_stack().PopIf<Parse::NodeKind::ImplForall>();
  120. auto decl_block_id = context.inst_block_stack().Pop();
  121. context.node_stack().PopForSoloParseNode<Parse::NodeKind::ImplIntroducer>();
  122. // Convert the constraint expression to a type.
  123. // TODO: Check that its constant value is a constraint.
  124. auto constraint_type_id = ExprAsType(context, constraint_node, constraint_id);
  125. // Process modifiers.
  126. // TODO: Should we somehow permit access specifiers on `impl`s?
  127. // TODO: Handle `final` modifier.
  128. LimitModifiersOnDecl(context, KeywordModifierSet::ImplDecl,
  129. Lex::TokenKind::Impl);
  130. // Finish processing the name, which should be empty, but might have
  131. // parameters.
  132. auto name_context = context.decl_name_stack().FinishImplName();
  133. CARBON_CHECK(name_context.state == DeclNameStack::NameContext::State::Empty);
  134. // Add the impl declaration.
  135. auto impl_decl = SemIR::ImplDecl{SemIR::ImplId::Invalid, decl_block_id};
  136. auto impl_decl_id = context.AddPlaceholderInst({parse_node, impl_decl});
  137. // TODO: Check whether this is a redeclaration.
  138. static_cast<void>(params_id);
  139. // Create a new impl if this isn't a valid redeclaration.
  140. if (!impl_decl.impl_id.is_valid()) {
  141. impl_decl.impl_id = context.impls().Add(
  142. {.self_id = self_type_id, .constraint_id = constraint_type_id});
  143. }
  144. // Write the impl ID into the ImplDecl.
  145. context.ReplaceInstBeforeConstantUse(impl_decl_id, {parse_node, impl_decl});
  146. // For an `extend impl` declaration, mark the impl as extending this `impl`.
  147. if (!!(context.decl_state_stack().innermost().modifier_set &
  148. KeywordModifierSet::Extend)) {
  149. // TODO: Diagnose combining `extend` with `forall`.
  150. // TODO: Diagnose combining `extend` with an explicit self type.
  151. ExtendImpl(context, parse_node, constraint_type_id);
  152. }
  153. context.decl_state_stack().Pop(DeclState::Impl);
  154. return {impl_decl.impl_id, impl_decl_id};
  155. }
  156. auto HandleImplDecl(Context& context, Parse::ImplDeclId parse_node) -> bool {
  157. BuildImplDecl(context, parse_node);
  158. context.decl_name_stack().PopScope();
  159. return true;
  160. }
  161. auto HandleImplDefinitionStart(Context& context,
  162. Parse::ImplDefinitionStartId parse_node)
  163. -> bool {
  164. auto [impl_id, impl_decl_id] = BuildImplDecl(context, parse_node);
  165. auto& impl_info = context.impls().Get(impl_id);
  166. if (impl_info.definition_id.is_valid()) {
  167. CARBON_DIAGNOSTIC(ImplRedefinition, Error,
  168. "Redefinition of `impl {0} as {1}`.", SemIR::TypeId,
  169. SemIR::TypeId);
  170. CARBON_DIAGNOSTIC(ImplPreviousDefinition, Note,
  171. "Previous definition was here.");
  172. context.emitter()
  173. .Build(parse_node, ImplRedefinition, impl_info.self_id,
  174. impl_info.constraint_id)
  175. .Note(impl_info.definition_id, ImplPreviousDefinition)
  176. .Emit();
  177. } else {
  178. impl_info.definition_id = impl_decl_id;
  179. impl_info.scope_id =
  180. context.name_scopes().Add(impl_decl_id, SemIR::NameId::Invalid,
  181. context.decl_name_stack().PeekTargetScope());
  182. }
  183. context.scope_stack().Push(impl_decl_id, impl_info.scope_id);
  184. context.inst_block_stack().Push();
  185. context.node_stack().Push(parse_node, impl_id);
  186. // TODO: Handle the case where there's control flow in the impl body. For
  187. // example:
  188. //
  189. // impl C as I {
  190. // fn F() -> if true then i32 else f64;
  191. // }
  192. //
  193. // We may need to track a list of instruction blocks here, as we do for a
  194. // function.
  195. impl_info.body_block_id = context.inst_block_stack().PeekOrAdd();
  196. return true;
  197. }
  198. auto HandleImplDefinition(Context& context,
  199. Parse::ImplDefinitionId /*parse_node*/) -> bool {
  200. auto impl_id =
  201. context.node_stack().Pop<Parse::NodeKind::ImplDefinitionStart>();
  202. context.inst_block_stack().Pop();
  203. context.decl_name_stack().PopScope();
  204. // The impl is now fully defined.
  205. context.impls().Get(impl_id).defined = true;
  206. return true;
  207. }
  208. } // namespace Carbon::Check