handle_binding_pattern.cpp 9.9 KB

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