handle_interface.cpp 9.3 KB

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