handle_impl.cpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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.scope_id.is_valid()) {
  99. // TODO: Should this be valid?
  100. context.TODO(parse_node, "extending interface without definition");
  101. enclosing_scope.has_error = true;
  102. return;
  103. }
  104. enclosing_scope.extended_scopes.push_back(interface.scope_id);
  105. }
  106. // Build an ImplDecl describing the signature of an impl. This handles the
  107. // common logic shared by impl forward declarations and impl definitions.
  108. static auto BuildImplDecl(Context& context, Parse::AnyImplDeclId parse_node)
  109. -> std::pair<SemIR::ImplId, SemIR::InstId> {
  110. auto [constraint_node, constraint_id] =
  111. context.node_stack().PopExprWithParseNode();
  112. auto self_type_id = context.node_stack().Pop<Parse::NodeCategory::ImplAs>();
  113. auto params_id = context.node_stack().PopIf<Parse::NodeKind::ImplForall>();
  114. auto decl_block_id = context.inst_block_stack().Pop();
  115. context.node_stack().PopForSoloParseNode<Parse::NodeKind::ImplIntroducer>();
  116. // Convert the constraint expression to a type.
  117. // TODO: Check that its constant value is a constraint.
  118. auto constraint_type_id = ExprAsType(context, constraint_node, constraint_id);
  119. // Process modifiers.
  120. // TODO: Should we somehow permit access specifiers on `impl`s?
  121. // TODO: Handle `final` modifier.
  122. LimitModifiersOnDecl(context, KeywordModifierSet::ImplDecl,
  123. Lex::TokenKind::Impl);
  124. // Finish processing the name, which should be empty, but might have
  125. // parameters.
  126. auto name_context = context.decl_name_stack().FinishImplName();
  127. CARBON_CHECK(name_context.state == DeclNameStack::NameContext::State::Empty);
  128. // Add the impl declaration.
  129. auto impl_decl = SemIR::ImplDecl{SemIR::ImplId::Invalid, decl_block_id};
  130. auto impl_decl_id = context.AddPlaceholderInst({parse_node, impl_decl});
  131. // TODO: Check whether this is a redeclaration.
  132. static_cast<void>(params_id);
  133. // Create a new impl if this isn't a valid redeclaration.
  134. if (!impl_decl.impl_id.is_valid()) {
  135. impl_decl.impl_id = context.impls().Add(
  136. {.self_id = self_type_id, .constraint_id = constraint_type_id});
  137. }
  138. // Write the impl ID into the ImplDecl.
  139. context.ReplaceInstBeforeConstantUse(impl_decl_id, {parse_node, impl_decl});
  140. // For an `extend impl` declaration, mark the impl as extending this `impl`.
  141. if (!!(context.decl_state_stack().innermost().modifier_set &
  142. KeywordModifierSet::Extend)) {
  143. // TODO: Diagnose combining `extend` with `forall`.
  144. // TODO: Diagnose combining `extend` with an explicit self type.
  145. ExtendImpl(context, parse_node, constraint_type_id);
  146. }
  147. context.decl_state_stack().Pop(DeclState::Impl);
  148. return {impl_decl.impl_id, impl_decl_id};
  149. }
  150. auto HandleImplDecl(Context& context, Parse::ImplDeclId parse_node) -> bool {
  151. BuildImplDecl(context, parse_node);
  152. context.decl_name_stack().PopScope();
  153. return true;
  154. }
  155. auto HandleImplDefinitionStart(Context& context,
  156. Parse::ImplDefinitionStartId parse_node)
  157. -> bool {
  158. auto [impl_id, impl_decl_id] = BuildImplDecl(context, parse_node);
  159. auto& impl_info = context.impls().Get(impl_id);
  160. if (impl_info.definition_id.is_valid()) {
  161. CARBON_DIAGNOSTIC(ImplRedefinition, Error,
  162. "Redefinition of `impl {0} as {1}`.", std::string,
  163. std::string);
  164. CARBON_DIAGNOSTIC(ImplPreviousDefinition, Note,
  165. "Previous definition was here.");
  166. context.emitter()
  167. .Build(parse_node, ImplRedefinition,
  168. context.sem_ir().StringifyType(impl_info.self_id),
  169. context.sem_ir().StringifyType(impl_info.constraint_id))
  170. .Note(impl_info.definition_id, ImplPreviousDefinition)
  171. .Emit();
  172. } else {
  173. impl_info.definition_id = impl_decl_id;
  174. impl_info.scope_id =
  175. context.name_scopes().Add(impl_decl_id, SemIR::NameId::Invalid,
  176. context.decl_name_stack().PeekTargetScope());
  177. }
  178. context.scope_stack().Push(impl_decl_id, impl_info.scope_id);
  179. context.inst_block_stack().Push();
  180. context.node_stack().Push(parse_node, impl_id);
  181. // TODO: Handle the case where there's control flow in the impl body. For
  182. // example:
  183. //
  184. // impl C as I {
  185. // fn F() -> if true then i32 else f64;
  186. // }
  187. //
  188. // We may need to track a list of instruction blocks here, as we do for a
  189. // function.
  190. impl_info.body_block_id = context.inst_block_stack().PeekOrAdd();
  191. return true;
  192. }
  193. auto HandleImplDefinition(Context& context,
  194. Parse::ImplDefinitionId /*parse_node*/) -> bool {
  195. auto impl_id =
  196. context.node_stack().Pop<Parse::NodeKind::ImplDefinitionStart>();
  197. context.inst_block_stack().Pop();
  198. context.decl_name_stack().PopScope();
  199. // The impl is now fully defined.
  200. context.impls().Get(impl_id).defined = true;
  201. return true;
  202. }
  203. } // namespace Carbon::Check