handle_interface.cpp 9.4 KB

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