handle_interface.cpp 9.2 KB

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