handle_interface.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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 <tuple>
  5. #include "toolchain/check/context.h"
  6. #include "toolchain/check/eval.h"
  7. #include "toolchain/check/facet_type.h"
  8. #include "toolchain/check/generic.h"
  9. #include "toolchain/check/handle.h"
  10. #include "toolchain/check/inst.h"
  11. #include "toolchain/check/interface.h"
  12. #include "toolchain/check/merge.h"
  13. #include "toolchain/check/modifiers.h"
  14. #include "toolchain/check/name_component.h"
  15. #include "toolchain/check/name_lookup.h"
  16. #include "toolchain/check/type.h"
  17. #include "toolchain/sem_ir/entity_with_params_base.h"
  18. #include "toolchain/sem_ir/ids.h"
  19. #include "toolchain/sem_ir/interface.h"
  20. #include "toolchain/sem_ir/typed_insts.h"
  21. namespace Carbon::Check {
  22. auto HandleParseNode(Context& context, Parse::InterfaceIntroducerId node_id)
  23. -> bool {
  24. // This interface is potentially generic.
  25. StartGenericDecl(context);
  26. // Create an instruction block to hold the instructions created as part of the
  27. // interface signature, such as generic parameters.
  28. context.inst_block_stack().Push();
  29. // Optional modifiers and the name follow.
  30. context.decl_introducer_state_stack().Push<Lex::TokenKind::Interface>();
  31. context.decl_name_stack().PushScopeAndStartName();
  32. // Push the bracketing node.
  33. context.node_stack().Push(node_id);
  34. return true;
  35. }
  36. static auto BuildInterfaceDecl(Context& context,
  37. Parse::AnyInterfaceDeclId node_id,
  38. bool is_definition)
  39. -> std::tuple<SemIR::InterfaceId, SemIR::InstId> {
  40. auto name = PopNameComponent(context);
  41. auto name_context = context.decl_name_stack().FinishName(name);
  42. context.node_stack()
  43. .PopAndDiscardSoloNodeId<Parse::NodeKind::InterfaceIntroducer>();
  44. // Process modifiers.
  45. auto [_, parent_scope_inst] =
  46. context.name_scopes().GetInstIfValid(name_context.parent_scope_id);
  47. auto introducer =
  48. context.decl_introducer_state_stack().Pop<Lex::TokenKind::Interface>();
  49. CheckAccessModifiersOnDecl(context, introducer, parent_scope_inst);
  50. LimitModifiersOnDecl(context, introducer, KeywordModifierSet::Access);
  51. auto decl_block_id = context.inst_block_stack().Pop();
  52. // Add the interface declaration.
  53. auto interface_decl = SemIR::InterfaceDecl{
  54. SemIR::TypeType::TypeId, SemIR::InterfaceId::None, decl_block_id};
  55. auto decl_inst_id = AddPlaceholderInst(context, node_id, interface_decl);
  56. SemIR::Interface interface_info = {name_context.MakeEntityWithParamsBase(
  57. name, decl_inst_id, /*is_extern=*/false, SemIR::LibraryNameId::None)};
  58. DiagnoseIfGenericMissingExplicitParameters(context, interface_info);
  59. // Check whether this is a redeclaration.
  60. SemIR::ScopeLookupResult lookup_result =
  61. context.decl_name_stack().LookupOrAddName(
  62. name_context, decl_inst_id, introducer.modifier_set.GetAccessKind());
  63. if (auto existing_decl = TryGetExistingDecl(context, name, lookup_result,
  64. interface_info, is_definition)) {
  65. auto existing_interface_decl = existing_decl->As<SemIR::InterfaceDecl>();
  66. interface_decl.interface_id = existing_interface_decl.interface_id;
  67. interface_decl.type_id = existing_interface_decl.type_id;
  68. // TODO: If the new declaration is a definition, keep its parameter
  69. // and implicit parameter lists rather than the ones from the
  70. // previous declaration.
  71. auto prev_decl_generic_id =
  72. context.interfaces().Get(interface_decl.interface_id).generic_id;
  73. FinishGenericRedecl(context, prev_decl_generic_id);
  74. } else {
  75. // Create a new interface if this isn't a valid redeclaration.
  76. interface_info.generic_id = BuildGenericDecl(context, decl_inst_id);
  77. if (context.sem_ir().package_id() == PackageNameId::Core) {
  78. auto name = context.names().GetIRBaseName(interface_info.name_id);
  79. interface_info.core_interface =
  80. llvm::StringSwitch<SemIR::CoreInterface>(name)
  81. .Case("Copy", SemIR::CoreInterface::Copy)
  82. .Case("CppUnsafeDeref", SemIR::CoreInterface::CppUnsafeDeref)
  83. .Case("Default", SemIR::CoreInterface::Default)
  84. .Case("Destroy", SemIR::CoreInterface::Destroy)
  85. .Case("IntFitsIn", SemIR::CoreInterface::IntFitsIn)
  86. .Default(SemIR::CoreInterface::Unknown);
  87. }
  88. interface_decl.interface_id = context.interfaces().Add(interface_info);
  89. if (interface_info.has_parameters()) {
  90. interface_decl.type_id =
  91. GetGenericInterfaceType(context, interface_decl.interface_id,
  92. context.scope_stack().PeekSpecificId());
  93. }
  94. }
  95. // Write the interface ID into the InterfaceDecl.
  96. ReplaceInstBeforeConstantUse(context, decl_inst_id, interface_decl);
  97. return {interface_decl.interface_id, decl_inst_id};
  98. }
  99. auto HandleParseNode(Context& context, Parse::InterfaceDeclId node_id) -> bool {
  100. BuildInterfaceDecl(context, node_id, /*is_definition=*/false);
  101. context.decl_name_stack().PopScope();
  102. return true;
  103. }
  104. auto HandleParseNode(Context& context,
  105. Parse::InterfaceDefinitionStartId node_id) -> bool {
  106. auto [interface_id, decl_inst_id] =
  107. BuildInterfaceDecl(context, node_id, /*is_definition=*/true);
  108. auto& interface_info = context.interfaces().Get(interface_id);
  109. // Track that this declaration is the definition.
  110. CARBON_CHECK(!interface_info.has_definition_started(),
  111. "Can't merge with defined interfaces.");
  112. interface_info.definition_id = decl_inst_id;
  113. interface_info.scope_without_self_id = context.name_scopes().Add(
  114. decl_inst_id, SemIR::NameId::None, interface_info.parent_scope_id);
  115. // Start the definition of interface-without-self.
  116. StartGenericDefinition(context, interface_info.generic_id);
  117. context.inst_block_stack().Push();
  118. // Enter the interface-without-self scope, which is used for the Self
  119. // instruction, since it needs to reference the interface (without-self)
  120. // generic. Self can't reference the interface-with-self generic since it's a
  121. // parameter to the generic.
  122. context.scope_stack().PushForEntity(
  123. decl_inst_id, interface_info.scope_without_self_id,
  124. context.generics().GetSelfSpecific(interface_info.generic_id));
  125. // Declare and introduce `Self`. We model `Self` as a symbolic binding whose
  126. // type is the interface, excluding any other interfaces mentioned by
  127. // `require` declarations.
  128. //
  129. // This is an instruction in the interface-without-self so that we can apply a
  130. // SpecificInterface to it, and get the inner `Self` as modified by any
  131. // enclosing specific.
  132. SemIR::TypeId self_type_id = GetInterfaceType(
  133. context, interface_id,
  134. context.generics().GetSelfSpecific(interface_info.generic_id));
  135. interface_info.self_param_id = AddSelfSymbolicBindingToScope(
  136. context, node_id, self_type_id, interface_info.scope_without_self_id,
  137. /*is_template=*/false);
  138. // Start the declaration of interface-with-self.
  139. StartGenericDecl(context);
  140. // Push `Self` as a parameter of the interface-with-self.
  141. context.scope_stack().PushCompileTimeBinding(interface_info.self_param_id);
  142. // Add the interface-with-self declaration and build the generic for it. This
  143. // captures the `interface_info.self_param_id` as a parameter of the generic.
  144. auto interface_with_self_decl =
  145. SemIR::InterfaceWithSelfDecl{.interface_id = interface_id};
  146. auto decl_with_self_inst_id =
  147. AddPlaceholderInst(context, node_id, interface_with_self_decl);
  148. auto generic_with_self_id = BuildGenericDecl(context, decl_with_self_inst_id);
  149. interface_info.generic_with_self_id = generic_with_self_id;
  150. ReplaceInstBeforeConstantUse(context, decl_with_self_inst_id,
  151. interface_with_self_decl);
  152. interface_info.scope_with_self_id =
  153. context.name_scopes().Add(decl_with_self_inst_id, SemIR::NameId::None,
  154. interface_info.scope_without_self_id);
  155. // Set on the name scope that `M` is replaced by `Self.M`.
  156. context.name_scopes()
  157. .Get(interface_info.scope_with_self_id)
  158. .set_is_interface_definition();
  159. // Start the definition of interface-with-self.
  160. StartGenericDefinition(context, interface_info.generic_with_self_id);
  161. // Enter a scope for the interace-with-self.
  162. context.scope_stack().PushForEntity(
  163. decl_with_self_inst_id, interface_info.scope_with_self_id,
  164. context.generics().GetSelfSpecific(interface_info.generic_with_self_id));
  165. interface_info.body_block_without_self_id =
  166. context.inst_block_stack().PeekOrAdd();
  167. context.inst_block_stack().Push();
  168. context.require_impls_stack().Push(interface_id);
  169. // We use the arg stack to build the witness table type.
  170. context.args_type_info_stack().Push();
  171. // TODO: Handle the case where there's control flow in the interface body. For
  172. // example:
  173. //
  174. // interface C {
  175. // let v: if true then i32 else f64;
  176. // }
  177. //
  178. // We may need to track a list of instruction blocks here, as we do for a
  179. // function.
  180. interface_info.body_block_with_self_id =
  181. context.inst_block_stack().PeekOrAdd();
  182. context.node_stack().Push(node_id, interface_id);
  183. return true;
  184. }
  185. auto HandleParseNode(Context& context, Parse::InterfaceDefinitionId /*node_id*/)
  186. -> bool {
  187. auto interface_id =
  188. context.node_stack().Pop<Parse::NodeKind::InterfaceDefinitionStart>();
  189. // Pop the body_block_with_self.
  190. context.inst_block_stack().Pop();
  191. auto associated_entities_id = context.args_type_info_stack().Pop();
  192. auto require_impls_block_id = context.require_impls_blocks().Add(
  193. context.require_impls_stack().PeekTop());
  194. context.require_impls_stack().Pop();
  195. auto& interface_info = context.interfaces().Get(interface_id);
  196. if (!interface_info.associated_entities_id.has_value()) {
  197. interface_info.require_impls_block_id = require_impls_block_id;
  198. // This marks the interface type as fully defined.
  199. interface_info.associated_entities_id = associated_entities_id;
  200. }
  201. // Finish the definition of interface-with-self.
  202. FinishGenericDefinition(context, interface_info.generic_with_self_id);
  203. // Pop the body_block_without_self.
  204. context.inst_block_stack().Pop();
  205. // Finish the definition of interface-without-self.
  206. FinishGenericDefinition(context, interface_info.generic_id);
  207. // The decl_name_stack and scopes are popped by `ProcessNodeIds`.
  208. return true;
  209. }
  210. } // namespace Carbon::Check