handle_interface.cpp 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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/merge.h"
  12. #include "toolchain/check/modifiers.h"
  13. #include "toolchain/check/name_component.h"
  14. #include "toolchain/check/name_lookup.h"
  15. #include "toolchain/check/type.h"
  16. #include "toolchain/sem_ir/typed_insts.h"
  17. namespace Carbon::Check {
  18. auto HandleParseNode(Context& context, Parse::InterfaceIntroducerId node_id)
  19. -> bool {
  20. // Create an instruction block to hold the instructions created as part of the
  21. // interface signature, such as generic parameters.
  22. context.inst_block_stack().Push();
  23. // Push the bracketing node.
  24. context.node_stack().Push(node_id);
  25. // Optional modifiers and the name follow.
  26. context.decl_introducer_state_stack().Push<Lex::TokenKind::Interface>();
  27. context.decl_name_stack().PushScopeAndStartName();
  28. // This interface is potentially generic.
  29. StartGenericDecl(context);
  30. return true;
  31. }
  32. static auto BuildInterfaceDecl(Context& context,
  33. Parse::AnyInterfaceDeclId node_id,
  34. bool is_definition)
  35. -> std::tuple<SemIR::InterfaceId, SemIR::InstId> {
  36. auto name = PopNameComponent(context);
  37. auto name_context = context.decl_name_stack().FinishName(name);
  38. context.node_stack()
  39. .PopAndDiscardSoloNodeId<Parse::NodeKind::InterfaceIntroducer>();
  40. // Process modifiers.
  41. auto [_, parent_scope_inst] =
  42. context.name_scopes().GetInstIfValid(name_context.parent_scope_id);
  43. auto introducer =
  44. context.decl_introducer_state_stack().Pop<Lex::TokenKind::Interface>();
  45. CheckAccessModifiersOnDecl(context, introducer, parent_scope_inst);
  46. LimitModifiersOnDecl(context, introducer, KeywordModifierSet::Access);
  47. auto decl_block_id = context.inst_block_stack().Pop();
  48. // Add the interface declaration.
  49. auto interface_decl = SemIR::InterfaceDecl{
  50. SemIR::TypeType::TypeId, SemIR::InterfaceId::None, decl_block_id};
  51. auto interface_decl_id = AddPlaceholderInst(context, node_id, interface_decl);
  52. SemIR::Interface interface_info = {name_context.MakeEntityWithParamsBase(
  53. name, interface_decl_id, /*is_extern=*/false,
  54. SemIR::LibraryNameId::None)};
  55. DiagnoseIfGenericMissingExplicitParameters(context, interface_info);
  56. // Check whether this is a redeclaration.
  57. SemIR::ScopeLookupResult lookup_result =
  58. context.decl_name_stack().LookupOrAddName(
  59. name_context, interface_decl_id,
  60. introducer.modifier_set.GetAccessKind());
  61. if (lookup_result.is_poisoned()) {
  62. // This is a declaration of a poisoned name.
  63. DiagnosePoisonedName(context, name_context.name_id_for_new_inst(),
  64. lookup_result.poisoning_loc_id(), name_context.loc_id);
  65. } else if (lookup_result.is_found()) {
  66. SemIR::InstId existing_id = lookup_result.target_inst_id();
  67. if (auto existing_interface_decl =
  68. context.insts().Get(existing_id).TryAs<SemIR::InterfaceDecl>()) {
  69. auto existing_interface =
  70. context.interfaces().Get(existing_interface_decl->interface_id);
  71. if (CheckRedeclParamsMatch(
  72. context,
  73. DeclParams(interface_decl_id, name.first_param_node_id,
  74. name.last_param_node_id,
  75. name.implicit_param_patterns_id,
  76. name.param_patterns_id),
  77. DeclParams(existing_interface))) {
  78. // TODO: This should be refactored a little, particularly for
  79. // prev_import_ir_id. See similar logic for classes and functions, which
  80. // might also be refactored to merge.
  81. DiagnoseIfInvalidRedecl(
  82. context, Lex::TokenKind::Interface, existing_interface.name_id,
  83. RedeclInfo(interface_info, node_id, is_definition),
  84. RedeclInfo(existing_interface, existing_interface.latest_decl_id(),
  85. existing_interface.has_definition_started()),
  86. /*prev_import_ir_id=*/SemIR::ImportIRId::None);
  87. // Can't merge interface definitions due to the generic requirements.
  88. if (!is_definition || !existing_interface.has_definition_started()) {
  89. // This is a redeclaration of an existing interface.
  90. interface_decl.interface_id = existing_interface_decl->interface_id;
  91. interface_decl.type_id = existing_interface_decl->type_id;
  92. // TODO: If the new declaration is a definition, keep its parameter
  93. // and implicit parameter lists rather than the ones from the
  94. // previous declaration.
  95. }
  96. }
  97. } else {
  98. // This is a redeclaration of something other than a interface.
  99. DiagnoseDuplicateName(context, name_context.name_id, name_context.loc_id,
  100. existing_id);
  101. }
  102. }
  103. // Create a new interface if this isn't a valid redeclaration.
  104. if (!interface_decl.interface_id.has_value()) {
  105. // TODO: If this is an invalid redeclaration of a non-interface entity or
  106. // there was an error in the qualifier, we will have lost track of the
  107. // interface name here. We should keep track of it even if the name is
  108. // invalid.
  109. interface_info.generic_id = BuildGenericDecl(context, interface_decl_id);
  110. interface_decl.interface_id = context.interfaces().Add(interface_info);
  111. if (interface_info.has_parameters()) {
  112. interface_decl.type_id =
  113. GetGenericInterfaceType(context, interface_decl.interface_id,
  114. context.scope_stack().PeekSpecificId());
  115. }
  116. } else {
  117. auto prev_decl_generic_id =
  118. context.interfaces().Get(interface_decl.interface_id).generic_id;
  119. FinishGenericRedecl(context, prev_decl_generic_id);
  120. }
  121. // Write the interface ID into the InterfaceDecl.
  122. ReplaceInstBeforeConstantUse(context, interface_decl_id, interface_decl);
  123. return {interface_decl.interface_id, interface_decl_id};
  124. }
  125. auto HandleParseNode(Context& context, Parse::InterfaceDeclId node_id) -> bool {
  126. BuildInterfaceDecl(context, node_id, /*is_definition=*/false);
  127. context.decl_name_stack().PopScope();
  128. return true;
  129. }
  130. auto HandleParseNode(Context& context,
  131. Parse::InterfaceDefinitionStartId node_id) -> bool {
  132. auto [interface_id, interface_decl_id] =
  133. BuildInterfaceDecl(context, node_id, /*is_definition=*/true);
  134. auto& interface_info = context.interfaces().Get(interface_id);
  135. // Track that this declaration is the definition.
  136. CARBON_CHECK(!interface_info.has_definition_started(),
  137. "Can't merge with defined interfaces.");
  138. interface_info.definition_id = interface_decl_id;
  139. interface_info.scope_id = context.name_scopes().Add(
  140. interface_decl_id, SemIR::NameId::None, interface_info.parent_scope_id);
  141. context.name_scopes()
  142. .Get(interface_info.scope_id)
  143. .set_is_interface_definition();
  144. auto self_specific_id =
  145. context.generics().GetSelfSpecific(interface_info.generic_id);
  146. StartGenericDefinition(context);
  147. context.inst_block_stack().Push();
  148. context.node_stack().Push(node_id, interface_id);
  149. // We use the arg stack to build the witness table type.
  150. context.args_type_info_stack().Push();
  151. // Declare and introduce `Self`.
  152. SemIR::TypeId self_type_id =
  153. GetInterfaceType(context, interface_id, self_specific_id);
  154. // We model `Self` as a symbolic binding whose type is the interface.
  155. // Because there is no equivalent non-symbolic value, we use `None` as
  156. // the `value_id` on the `BindSymbolicName`.
  157. auto entity_name_id = context.entity_names().AddSymbolicBindingName(
  158. SemIR::NameId::SelfType, interface_info.scope_id,
  159. context.scope_stack().AddCompileTimeBinding(),
  160. /*is_template=*/false);
  161. interface_info.self_param_id =
  162. AddInst(context, SemIR::LocIdAndInst::NoLoc<SemIR::BindSymbolicName>(
  163. {.type_id = self_type_id,
  164. .entity_name_id = entity_name_id,
  165. .value_id = SemIR::InstId::None}));
  166. context.scope_stack().PushCompileTimeBinding(interface_info.self_param_id);
  167. context.name_scopes().AddRequiredName(interface_info.scope_id,
  168. SemIR::NameId::SelfType,
  169. interface_info.self_param_id);
  170. // Enter the interface scope.
  171. context.scope_stack().Push(interface_decl_id, interface_info.scope_id,
  172. self_specific_id);
  173. // TODO: Handle the case where there's control flow in the interface body. For
  174. // example:
  175. //
  176. // interface C {
  177. // let v: if true then i32 else f64;
  178. // }
  179. //
  180. // We may need to track a list of instruction blocks here, as we do for a
  181. // function.
  182. interface_info.body_block_id = context.inst_block_stack().PeekOrAdd();
  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. context.inst_block_stack().Pop();
  190. auto associated_entities_id = context.args_type_info_stack().Pop();
  191. // The interface type is now fully defined.
  192. auto& interface_info = context.interfaces().Get(interface_id);
  193. if (!interface_info.associated_entities_id.has_value()) {
  194. interface_info.associated_entities_id = associated_entities_id;
  195. }
  196. FinishGenericDefinition(context, interface_info.generic_id);
  197. // The decl_name_stack and scopes are popped by `ProcessNodeIds`.
  198. return true;
  199. }
  200. } // namespace Carbon::Check