handle_interface.cpp 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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. // Push a pattern block for the signature (if any) of the first NameComponent.
  26. // TODO: Instead use a separate parse node kind for an identifier that's
  27. // followed by a pattern, and push a pattern block when handling it.
  28. context.pattern_block_stack().Push();
  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 = SemIR::InterfaceDecl{
  49. SemIR::TypeId::TypeType, SemIR::InterfaceId::Invalid, decl_block_id};
  50. auto interface_decl_id =
  51. context.AddPlaceholderInst(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::Invalid)};
  55. // Check whether this is a redeclaration.
  56. auto existing_id = context.decl_name_stack().LookupOrAddName(
  57. name_context, interface_decl_id, introducer.modifier_set.GetAccessKind());
  58. if (existing_id.is_valid()) {
  59. if (auto existing_interface_decl =
  60. context.insts().Get(existing_id).TryAs<SemIR::InterfaceDecl>()) {
  61. auto existing_interface =
  62. context.interfaces().Get(existing_interface_decl->interface_id);
  63. if (CheckRedeclParamsMatch(
  64. context,
  65. DeclParams(interface_decl_id, name.first_param_node_id,
  66. name.last_param_node_id,
  67. name.implicit_param_patterns_id,
  68. name.param_patterns_id),
  69. DeclParams(existing_interface))) {
  70. // TODO: This should be refactored a little, particularly for
  71. // prev_import_ir_id. See similar logic for classes and functions, which
  72. // might also be refactored to merge.
  73. CheckIsAllowedRedecl(
  74. context, Lex::TokenKind::Interface, existing_interface.name_id,
  75. RedeclInfo(interface_info, node_id, is_definition),
  76. RedeclInfo(existing_interface, existing_interface.latest_decl_id(),
  77. existing_interface.is_defined()),
  78. /*prev_import_ir_id=*/SemIR::ImportIRId::Invalid);
  79. // Can't merge interface definitions due to the generic requirements.
  80. // TODO: Should this also be mirrored to classes/functions for generics?
  81. if (!is_definition || !existing_interface.is_defined()) {
  82. // This is a redeclaration of an existing interface.
  83. interface_decl.interface_id = existing_interface_decl->interface_id;
  84. interface_decl.type_id = existing_interface_decl->type_id;
  85. // TODO: If the new declaration is a definition, keep its parameter
  86. // and implicit parameter lists rather than the ones from the
  87. // previous declaration.
  88. }
  89. }
  90. } else {
  91. // This is a redeclaration of something other than a interface.
  92. context.DiagnoseDuplicateName(interface_decl_id, existing_id);
  93. }
  94. }
  95. // Create a new interface if this isn't a valid redeclaration.
  96. if (!interface_decl.interface_id.is_valid()) {
  97. // TODO: If this is an invalid redeclaration of a non-interface entity or
  98. // there was an error in the qualifier, we will have lost track of the
  99. // interface name here. We should keep track of it even if the name is
  100. // invalid.
  101. interface_info.generic_id = FinishGenericDecl(context, interface_decl_id);
  102. interface_decl.interface_id = context.interfaces().Add(interface_info);
  103. if (interface_info.has_parameters()) {
  104. interface_decl.type_id = context.GetGenericInterfaceType(
  105. interface_decl.interface_id, context.scope_stack().PeekSpecificId());
  106. }
  107. } else {
  108. FinishGenericRedecl(
  109. context, interface_decl_id,
  110. context.interfaces().Get(interface_decl.interface_id).generic_id);
  111. }
  112. // Write the interface ID into the InterfaceDecl.
  113. context.ReplaceInstBeforeConstantUse(interface_decl_id, interface_decl);
  114. return {interface_decl.interface_id, interface_decl_id};
  115. }
  116. auto HandleParseNode(Context& context, Parse::InterfaceDeclId node_id) -> bool {
  117. BuildInterfaceDecl(context, node_id, /*is_definition=*/false);
  118. context.decl_name_stack().PopScope();
  119. return true;
  120. }
  121. auto HandleParseNode(Context& context,
  122. Parse::InterfaceDefinitionStartId node_id) -> bool {
  123. auto [interface_id, interface_decl_id] =
  124. BuildInterfaceDecl(context, node_id, /*is_definition=*/true);
  125. auto& interface_info = context.interfaces().Get(interface_id);
  126. // Track that this declaration is the definition.
  127. CARBON_CHECK(!interface_info.is_defined(),
  128. "Can't merge with defined interfaces.");
  129. interface_info.definition_id = interface_decl_id;
  130. interface_info.scope_id =
  131. context.name_scopes().Add(interface_decl_id, SemIR::NameId::Invalid,
  132. interface_info.parent_scope_id);
  133. auto self_specific_id =
  134. context.generics().GetSelfSpecific(interface_info.generic_id);
  135. StartGenericDefinition(context);
  136. context.inst_block_stack().Push();
  137. context.node_stack().Push(node_id, interface_id);
  138. // We use the arg stack to build the witness table type.
  139. context.args_type_info_stack().Push();
  140. // Declare and introduce `Self`.
  141. if (!interface_info.is_defined()) {
  142. auto interface_type =
  143. SemIR::InterfaceType{.type_id = SemIR::TypeId::TypeType,
  144. .interface_id = interface_id,
  145. .specific_id = self_specific_id};
  146. SemIR::TypeId self_type_id = context.GetTypeIdForTypeConstant(
  147. TryEvalInst(context, SemIR::InstId::Invalid, interface_type));
  148. // We model `Self` as a symbolic binding whose type is the interface.
  149. // Because there is no equivalent non-symbolic value, we use `Invalid` as
  150. // the `value_id` on the `BindSymbolicName`.
  151. auto entity_name_id = context.entity_names().Add(
  152. {.name_id = SemIR::NameId::SelfType,
  153. .parent_scope_id = interface_info.scope_id,
  154. .bind_index = context.scope_stack().AddCompileTimeBinding()});
  155. interface_info.self_param_id =
  156. context.AddInst(SemIR::LocIdAndInst::NoLoc<SemIR::BindSymbolicName>(
  157. {.type_id = self_type_id,
  158. .entity_name_id = entity_name_id,
  159. .value_id = SemIR::InstId::Invalid}));
  160. context.scope_stack().PushCompileTimeBinding(interface_info.self_param_id);
  161. context.name_scopes().AddRequiredName(interface_info.scope_id,
  162. SemIR::NameId::SelfType,
  163. interface_info.self_param_id);
  164. }
  165. // Enter the interface scope.
  166. context.scope_stack().Push(interface_decl_id, interface_info.scope_id,
  167. self_specific_id);
  168. // TODO: Handle the case where there's control flow in the interface body. For
  169. // example:
  170. //
  171. // interface C {
  172. // let v: if true then i32 else f64;
  173. // }
  174. //
  175. // We may need to track a list of instruction blocks here, as we do for a
  176. // function.
  177. interface_info.body_block_id = context.inst_block_stack().PeekOrAdd();
  178. return true;
  179. }
  180. auto HandleParseNode(Context& context, Parse::InterfaceDefinitionId /*node_id*/)
  181. -> bool {
  182. auto interface_id =
  183. context.node_stack().Pop<Parse::NodeKind::InterfaceDefinitionStart>();
  184. context.inst_block_stack().Pop();
  185. auto associated_entities_id = context.args_type_info_stack().Pop();
  186. // The interface type is now fully defined.
  187. auto& interface_info = context.interfaces().Get(interface_id);
  188. if (!interface_info.associated_entities_id.is_valid()) {
  189. interface_info.associated_entities_id = associated_entities_id;
  190. }
  191. FinishGenericDefinition(context, interface_info.generic_id);
  192. // The decl_name_stack and scopes are popped by `ProcessNodeIds`.
  193. return true;
  194. }
  195. } // namespace Carbon::Check