handle_binding_pattern.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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/convert.h"
  6. #include "toolchain/check/handle.h"
  7. #include "toolchain/check/return.h"
  8. #include "toolchain/sem_ir/ids.h"
  9. #include "toolchain/sem_ir/inst.h"
  10. namespace Carbon::Check {
  11. static auto HandleAnyBindingPattern(Context& context, Parse::NodeId node_id,
  12. bool is_generic) -> bool {
  13. auto [type_node, parsed_type_id] = context.node_stack().PopExprWithNodeId();
  14. auto cast_type_id = ExprAsType(context, type_node, parsed_type_id);
  15. // TODO: Handle `_` bindings.
  16. // Every other kind of pattern binding has a name.
  17. auto [name_node, name_id] = context.node_stack().PopNameWithNodeId();
  18. // Determine whether we're handling an associated constant. These share the
  19. // syntax for a compile-time binding, but don't behave like other compile-time
  20. // bindings.
  21. // TODO: Consider using a different parse node kind to make this easier.
  22. bool is_associated_constant = false;
  23. if (is_generic) {
  24. auto inst_id = context.scope_stack().PeekInstId();
  25. is_associated_constant =
  26. inst_id.is_valid() && context.insts().Is<SemIR::InterfaceDecl>(inst_id);
  27. }
  28. bool needs_compile_time_binding = is_generic && !is_associated_constant;
  29. // Create the appropriate kind of binding for this pattern.
  30. auto make_bind_name = [&](SemIR::TypeId type_id,
  31. SemIR::InstId value_id) -> SemIR::LocIdAndInst {
  32. // TODO: Eventually the name will need to support associations with other
  33. // scopes, but right now we don't support qualified names here.
  34. auto entity_name_id = context.entity_names().Add(
  35. {.name_id = name_id,
  36. .parent_scope_id = context.scope_stack().PeekNameScopeId(),
  37. // TODO: Don't allocate a compile-time binding index for an associated
  38. // constant declaration.
  39. .bind_index = needs_compile_time_binding
  40. ? context.scope_stack().AddCompileTimeBinding()
  41. : SemIR::CompileTimeBindIndex::Invalid});
  42. if (is_generic) {
  43. // TODO: Create a `BindTemplateName` instead inside a `template` pattern.
  44. return SemIR::LocIdAndInst(
  45. name_node, SemIR::BindSymbolicName{.type_id = type_id,
  46. .entity_name_id = entity_name_id,
  47. .value_id = value_id});
  48. } else {
  49. return SemIR::LocIdAndInst(
  50. name_node, SemIR::BindName{.type_id = type_id,
  51. .entity_name_id = entity_name_id,
  52. .value_id = value_id});
  53. }
  54. };
  55. // Push the binding onto the node stack and, if necessary, onto the scope
  56. // stack.
  57. auto push_bind_name = [&](SemIR::InstId bind_id) {
  58. context.node_stack().Push(node_id, bind_id);
  59. if (needs_compile_time_binding) {
  60. context.scope_stack().PushCompileTimeBinding(bind_id);
  61. }
  62. };
  63. // A `self` binding can only appear in an implicit parameter list.
  64. if (name_id == SemIR::NameId::SelfValue &&
  65. !context.node_stack().PeekIs<Parse::NodeKind::ImplicitParamListStart>()) {
  66. CARBON_DIAGNOSTIC(
  67. SelfOutsideImplicitParamList, Error,
  68. "`self` can only be declared in an implicit parameter list");
  69. context.emitter().Emit(node_id, SelfOutsideImplicitParamList);
  70. }
  71. // Allocate an instruction of the appropriate kind, linked to the name for
  72. // error locations.
  73. // TODO: The node stack is a fragile way of getting context information.
  74. // Get this information from somewhere else.
  75. switch (auto context_node_kind = context.node_stack().PeekNodeKind()) {
  76. case Parse::NodeKind::ReturnedModifier:
  77. case Parse::NodeKind::VariableIntroducer: {
  78. if (is_generic) {
  79. CARBON_DIAGNOSTIC(
  80. CompileTimeBindingInVarDecl, Error,
  81. "`var` declaration cannot declare a compile-time binding");
  82. context.emitter().Emit(type_node, CompileTimeBindingInVarDecl);
  83. }
  84. auto binding_id =
  85. is_generic
  86. ? Parse::NodeId::Invalid
  87. : context.parse_tree().As<Parse::BindingPatternId>(node_id);
  88. // A `var` declaration at class scope introduces a field.
  89. auto parent_class_decl = context.GetCurrentScopeAs<SemIR::ClassDecl>();
  90. cast_type_id = context.AsCompleteType(cast_type_id, [&] {
  91. CARBON_DIAGNOSTIC(IncompleteTypeInVarDecl, Error,
  92. "{0} has incomplete type `{1}`", llvm::StringLiteral,
  93. SemIR::TypeId);
  94. return context.emitter().Build(type_node, IncompleteTypeInVarDecl,
  95. parent_class_decl
  96. ? llvm::StringLiteral("Field")
  97. : llvm::StringLiteral("Variable"),
  98. cast_type_id);
  99. });
  100. if (parent_class_decl) {
  101. CARBON_CHECK(context_node_kind == Parse::NodeKind::VariableIntroducer,
  102. "`returned var` at class scope");
  103. auto& class_info = context.classes().Get(parent_class_decl->class_id);
  104. auto field_type_id = context.GetUnboundElementType(
  105. class_info.self_type_id, cast_type_id);
  106. auto field_id = context.AddInst<SemIR::FieldDecl>(
  107. binding_id,
  108. {.type_id = field_type_id,
  109. .name_id = name_id,
  110. .index = SemIR::ElementIndex(context.args_type_info_stack()
  111. .PeekCurrentBlockContents()
  112. .size())});
  113. // Add a corresponding field to the object representation of the class.
  114. context.args_type_info_stack().AddInstId(
  115. context.AddInstInNoBlock<SemIR::StructTypeField>(
  116. binding_id,
  117. {.name_id = name_id, .field_type_id = cast_type_id}));
  118. context.node_stack().Push(node_id, field_id);
  119. break;
  120. }
  121. SemIR::InstId value_id = SemIR::InstId::Invalid;
  122. if (context_node_kind == Parse::NodeKind::ReturnedModifier) {
  123. // TODO: Should we check this for the `var` as a whole, rather than for
  124. // the name binding?
  125. value_id =
  126. CheckReturnedVar(context, context.node_stack().PeekNodeId(),
  127. name_node, name_id, type_node, cast_type_id);
  128. } else {
  129. value_id = context.AddInst<SemIR::VarStorage>(
  130. name_node, {.type_id = cast_type_id, .name_id = name_id});
  131. }
  132. auto bind_id = context.AddInst(make_bind_name(cast_type_id, value_id));
  133. push_bind_name(bind_id);
  134. if (context_node_kind == Parse::NodeKind::ReturnedModifier) {
  135. RegisterReturnedVar(context, bind_id);
  136. }
  137. break;
  138. }
  139. case Parse::NodeKind::ImplicitParamListStart:
  140. case Parse::NodeKind::TuplePatternStart: {
  141. // Parameters can have incomplete types in a function declaration, but not
  142. // in a function definition. We don't know which kind we have here.
  143. // TODO: A tuple pattern can appear in other places than function
  144. // parameters.
  145. auto param_id = context.AddInst<SemIR::Param>(
  146. name_node, {.type_id = cast_type_id,
  147. .name_id = name_id,
  148. .runtime_index = SemIR::RuntimeParamIndex::Invalid});
  149. auto bind_id = context.AddInst(make_bind_name(cast_type_id, param_id));
  150. push_bind_name(bind_id);
  151. // TODO: Bindings should come into scope immediately in other contexts
  152. // too.
  153. context.AddNameToLookup(name_id, bind_id);
  154. auto entity_name_id =
  155. context.insts().GetAs<SemIR::AnyBindName>(bind_id).entity_name_id;
  156. if (is_generic) {
  157. context.AddPatternInst<SemIR::SymbolicBindingPattern>(
  158. name_node,
  159. {.type_id = cast_type_id, .entity_name_id = entity_name_id});
  160. } else {
  161. context.AddPatternInst<SemIR::BindingPattern>(
  162. name_node,
  163. {.type_id = cast_type_id, .entity_name_id = entity_name_id});
  164. }
  165. // TODO: use the pattern insts to generate the pattern-match insts
  166. // at the end of the full pattern, instead of eagerly generating them
  167. // here.
  168. break;
  169. }
  170. case Parse::NodeKind::LetIntroducer: {
  171. cast_type_id = context.AsCompleteType(cast_type_id, [&] {
  172. CARBON_DIAGNOSTIC(IncompleteTypeInLetDecl, Error,
  173. "`let` binding has incomplete type `{0}`",
  174. SemIR::TypeId);
  175. return context.emitter().Build(type_node, IncompleteTypeInLetDecl,
  176. cast_type_id);
  177. });
  178. // Create the instruction, but don't add it to a block until after we've
  179. // formed its initializer.
  180. // TODO: For general pattern parsing, we'll need to create a block to hold
  181. // the `let` pattern before we see the initializer.
  182. auto bind_id = context.AddPlaceholderInstInNoBlock(
  183. make_bind_name(cast_type_id, SemIR::InstId::Invalid));
  184. push_bind_name(bind_id);
  185. break;
  186. }
  187. default:
  188. CARBON_FATAL("Found a pattern binding in unexpected context {0}",
  189. context_node_kind);
  190. }
  191. return true;
  192. }
  193. auto HandleParseNode(Context& context, Parse::BindingPatternId node_id)
  194. -> bool {
  195. return HandleAnyBindingPattern(context, node_id, /*is_generic=*/false);
  196. }
  197. auto HandleParseNode(Context& context,
  198. Parse::CompileTimeBindingPatternId node_id) -> bool {
  199. bool is_generic = true;
  200. if (context.decl_introducer_state_stack().innermost().kind ==
  201. Lex::TokenKind::Let) {
  202. auto scope_inst = context.insts().Get(context.scope_stack().PeekInstId());
  203. if (!scope_inst.Is<SemIR::InterfaceDecl>() &&
  204. !scope_inst.Is<SemIR::FunctionDecl>()) {
  205. context.TODO(node_id,
  206. "`let` compile time binding outside function or interface");
  207. is_generic = false;
  208. }
  209. }
  210. return HandleAnyBindingPattern(context, node_id, is_generic);
  211. }
  212. auto HandleParseNode(Context& context, Parse::AddrId node_id) -> bool {
  213. auto self_param_id = context.node_stack().PopPattern();
  214. if (auto self_param =
  215. context.insts().TryGetAs<SemIR::AnyBindName>(self_param_id);
  216. self_param &&
  217. context.entity_names().Get(self_param->entity_name_id).name_id ==
  218. SemIR::NameId::SelfValue) {
  219. // TODO: The type of an `addr_pattern` should probably be the non-pointer
  220. // type, because that's the type that the pattern matches.
  221. context.AddInstAndPush<SemIR::AddrPattern>(
  222. node_id, {.type_id = self_param->type_id, .inner_id = self_param_id});
  223. } else {
  224. CARBON_DIAGNOSTIC(AddrOnNonSelfParam, Error,
  225. "`addr` can only be applied to a `self` parameter");
  226. context.emitter().Emit(TokenOnly(node_id), AddrOnNonSelfParam);
  227. context.node_stack().Push(node_id, self_param_id);
  228. }
  229. return true;
  230. }
  231. auto HandleParseNode(Context& context, Parse::TemplateId node_id) -> bool {
  232. return context.TODO(node_id, "HandleTemplate");
  233. }
  234. } // namespace Carbon::Check