handle_interface.cpp 11 KB

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