handle_binding_pattern.cpp 12 KB

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