handle_binding_pattern.cpp 9.1 KB

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