handle_binding_pattern.cpp 8.3 KB

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