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. static auto GetDefaultSelfType(Context& context, Parse::NodeId parse_node)
  57. -> 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. CARBON_DIAGNOSTIC(ImplAsOutsideClass, Error,
  64. "`impl as` can only be used in a class.");
  65. context.emitter().Emit(parse_node, ImplAsOutsideClass);
  66. return SemIR::TypeId::Error;
  67. }
  68. auto HandleDefaultSelfImplAs(Context& context,
  69. Parse::DefaultSelfImplAsId parse_node) -> bool {
  70. auto self_type_id = GetDefaultSelfType(context, parse_node);
  71. context.node_stack().Push(parse_node, self_type_id);
  72. return true;
  73. }
  74. // Process an `extend impl` declaration by extending the impl scope with the
  75. // `impl`'s scope.
  76. static auto ExtendImpl(Context& context, Parse::AnyImplDeclId parse_node,
  77. SemIR::TypeId constraint_id) -> void {
  78. auto enclosing_scope_id = context.decl_name_stack().PeekTargetScope();
  79. // TODO: This is also valid in a mixin.
  80. if (!TryAsClassScope(context, enclosing_scope_id)) {
  81. CARBON_DIAGNOSTIC(ExtendImplOutsideClass, Error,
  82. "`extend impl` can only be used in a class.");
  83. context.emitter().Emit(parse_node, ExtendImplOutsideClass);
  84. return;
  85. }
  86. auto& enclosing_scope = context.name_scopes().Get(enclosing_scope_id);
  87. auto interface_type =
  88. context.types().TryGetAs<SemIR::InterfaceType>(constraint_id);
  89. if (!interface_type) {
  90. context.TODO(parse_node, "extending non-interface constraint");
  91. enclosing_scope.has_error = true;
  92. return;
  93. }
  94. auto& interface = context.interfaces().Get(interface_type->interface_id);
  95. if (!interface.is_defined()) {
  96. CARBON_DIAGNOSTIC(
  97. ExtendUndefinedInterface, Error,
  98. "`extend impl` requires a definition for interface `{0}`.",
  99. SemIR::TypeId);
  100. auto diag = context.emitter().Build(parse_node, ExtendUndefinedInterface,
  101. constraint_id);
  102. context.NoteUndefinedInterface(interface_type->interface_id, diag);
  103. diag.Emit();
  104. enclosing_scope.has_error = true;
  105. return;
  106. }
  107. enclosing_scope.extended_scopes.push_back(interface.scope_id);
  108. }
  109. // Build an ImplDecl describing the signature of an impl. This handles the
  110. // common logic shared by impl forward declarations and impl definitions.
  111. static auto BuildImplDecl(Context& context, Parse::AnyImplDeclId parse_node)
  112. -> std::pair<SemIR::ImplId, SemIR::InstId> {
  113. auto [constraint_node, constraint_id] =
  114. context.node_stack().PopExprWithParseNode();
  115. auto self_type_id = context.node_stack().Pop<Parse::NodeCategory::ImplAs>();
  116. auto params_id = context.node_stack().PopIf<Parse::NodeKind::ImplForall>();
  117. auto decl_block_id = context.inst_block_stack().Pop();
  118. context.node_stack().PopForSoloParseNode<Parse::NodeKind::ImplIntroducer>();
  119. // Convert the constraint expression to a type.
  120. // TODO: Check that its constant value is a constraint.
  121. auto constraint_type_id = ExprAsType(context, constraint_node, constraint_id);
  122. // Process modifiers.
  123. // TODO: Should we somehow permit access specifiers on `impl`s?
  124. // TODO: Handle `final` modifier.
  125. LimitModifiersOnDecl(context, KeywordModifierSet::ImplDecl,
  126. Lex::TokenKind::Impl);
  127. // Finish processing the name, which should be empty, but might have
  128. // parameters.
  129. auto name_context = context.decl_name_stack().FinishImplName();
  130. CARBON_CHECK(name_context.state == DeclNameStack::NameContext::State::Empty);
  131. // TODO: Check for an orphan `impl`.
  132. // TODO: Check parameters. Store them on the `Impl` in some form.
  133. static_cast<void>(params_id);
  134. // Add the impl declaration.
  135. // TODO: Does lookup in an impl file need to look for a prior impl declaration
  136. // in the api file?
  137. auto impl_id = context.impls().LookupOrAdd(self_type_id, constraint_type_id);
  138. auto impl_decl = SemIR::ImplDecl{impl_id, decl_block_id};
  139. auto impl_decl_id = context.AddInst({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}`.", SemIR::TypeId,
  163. SemIR::TypeId);
  164. CARBON_DIAGNOSTIC(ImplPreviousDefinition, Note,
  165. "Previous definition was here.");
  166. context.emitter()
  167. .Build(parse_node, ImplRedefinition, impl_info.self_id,
  168. impl_info.constraint_id)
  169. .Note(impl_info.definition_id, ImplPreviousDefinition)
  170. .Emit();
  171. } else {
  172. impl_info.definition_id = impl_decl_id;
  173. impl_info.scope_id =
  174. context.name_scopes().Add(impl_decl_id, SemIR::NameId::Invalid,
  175. context.decl_name_stack().PeekTargetScope());
  176. }
  177. context.scope_stack().Push(impl_decl_id, impl_info.scope_id);
  178. context.inst_block_stack().Push();
  179. context.node_stack().Push(parse_node, impl_id);
  180. // TODO: Handle the case where there's control flow in the impl body. For
  181. // example:
  182. //
  183. // impl C as I {
  184. // fn F() -> if true then i32 else f64;
  185. // }
  186. //
  187. // We may need to track a list of instruction blocks here, as we do for a
  188. // function.
  189. impl_info.body_block_id = context.inst_block_stack().PeekOrAdd();
  190. return true;
  191. }
  192. auto HandleImplDefinition(Context& context,
  193. Parse::ImplDefinitionId /*parse_node*/) -> bool {
  194. auto impl_id =
  195. context.node_stack().Pop<Parse::NodeKind::ImplDefinitionStart>();
  196. context.inst_block_stack().Pop();
  197. context.decl_name_stack().PopScope();
  198. // The impl is now fully defined.
  199. context.impls().Get(impl_id).defined = true;
  200. return true;
  201. }
  202. } // namespace Carbon::Check