handle_binding_pattern.cpp 8.3 KB

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