handle_interface.cpp 9.6 KB

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