handle_interface.cpp 9.8 KB

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