handle_binding_pattern.cpp 8.4 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. #include "toolchain/sem_ir/inst.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 type_node_copy = type_node;
  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().PopNameWithParseNode();
  18. // Create the appropriate kind of binding for this pattern.
  19. auto make_bind_name = [&, name_node = name_node, name_id = name_id](
  20. SemIR::TypeId type_id,
  21. SemIR::InstId value_id) -> SemIR::Inst {
  22. // TODO: Eventually the name will need to support associations with other
  23. // scopes, but right now we don't support qualified names here.
  24. auto bind_name_id = context.bind_names().Add(
  25. {.name_id = name_id, .enclosing_scope_id = context.current_scope_id()});
  26. if (is_generic) {
  27. // TODO: Create a `BindTemplateName` instead inside a `template` pattern.
  28. return SemIR::BindSymbolicName{name_node, type_id, bind_name_id,
  29. value_id};
  30. } else {
  31. return SemIR::BindName{name_node, type_id, bind_name_id, value_id};
  32. }
  33. };
  34. // A `self` binding can only appear in an implicit parameter list.
  35. if (name_id == SemIR::NameId::SelfValue &&
  36. !context.node_stack().PeekIs<Parse::NodeKind::ImplicitParamListStart>()) {
  37. CARBON_DIAGNOSTIC(
  38. SelfOutsideImplicitParamList, Error,
  39. "`self` can only be declared in an implicit parameter list.");
  40. context.emitter().Emit(parse_node, SelfOutsideImplicitParamList);
  41. }
  42. // Allocate an instruction of the appropriate kind, linked to the name for
  43. // error locations.
  44. // TODO: The node stack is a fragile way of getting context information.
  45. // Get this information from somewhere else.
  46. switch (auto context_parse_node_kind =
  47. context.node_stack().PeekParseNodeKind()) {
  48. case Parse::NodeKind::ReturnedModifier:
  49. case Parse::NodeKind::VariableIntroducer: {
  50. if (is_generic) {
  51. CARBON_DIAGNOSTIC(
  52. CompileTimeBindingInVarDecl, Error,
  53. "`var` declaration cannot declare a compile-time binding.");
  54. context.emitter().Emit(type_node, CompileTimeBindingInVarDecl);
  55. }
  56. auto binding_id =
  57. is_generic
  58. ? Parse::NodeId::Invalid
  59. : context.parse_tree().As<Parse::BindingPatternId>(parse_node);
  60. // A `var` declaration at class scope introduces a field.
  61. auto enclosing_class_decl = context.GetCurrentScopeAs<SemIR::ClassDecl>();
  62. cast_type_id = context.AsCompleteType(cast_type_id, [&] {
  63. CARBON_DIAGNOSTIC(IncompleteTypeInVarDecl, Error,
  64. "{0} has incomplete type `{1}`.", llvm::StringLiteral,
  65. std::string);
  66. return context.emitter().Build(
  67. type_node_copy, IncompleteTypeInVarDecl,
  68. enclosing_class_decl ? llvm::StringLiteral("Field")
  69. : llvm::StringLiteral("Variable"),
  70. context.sem_ir().StringifyType(cast_type_id));
  71. });
  72. SemIR::InstId value_id = SemIR::InstId::Invalid;
  73. SemIR::TypeId value_type_id = cast_type_id;
  74. if (context_parse_node_kind == Parse::NodeKind::ReturnedModifier) {
  75. // TODO: Should we check this for the `var` as a whole, rather than for
  76. // the name binding?
  77. CARBON_CHECK(!enclosing_class_decl) << "`returned var` at class scope";
  78. value_id =
  79. CheckReturnedVar(context, context.node_stack().PeekParseNode(),
  80. name_node, name_id, type_node, cast_type_id);
  81. } else if (enclosing_class_decl) {
  82. auto& class_info =
  83. context.classes().Get(enclosing_class_decl->class_id);
  84. auto field_type_inst_id = context.AddInst(SemIR::UnboundElementType{
  85. binding_id, context.GetBuiltinType(SemIR::BuiltinKind::TypeType),
  86. class_info.self_type_id, cast_type_id});
  87. value_type_id = context.CanonicalizeType(field_type_inst_id);
  88. value_id = context.AddInst(
  89. SemIR::FieldDecl{binding_id, value_type_id, name_id,
  90. SemIR::ElementIndex(context.args_type_info_stack()
  91. .PeekCurrentBlockContents()
  92. .size())});
  93. // Add a corresponding field to the object representation of the class.
  94. context.args_type_info_stack().AddInst(
  95. SemIR::StructTypeField{binding_id, name_id, cast_type_id});
  96. } else {
  97. value_id = context.AddInst(
  98. SemIR::VarStorage{name_node, value_type_id, name_id});
  99. }
  100. auto bind_id = context.AddInst(make_bind_name(value_type_id, value_id));
  101. context.node_stack().Push(parse_node, bind_id);
  102. if (context_parse_node_kind == Parse::NodeKind::ReturnedModifier) {
  103. RegisterReturnedVar(context, bind_id);
  104. }
  105. break;
  106. }
  107. case Parse::NodeKind::ImplicitParamListStart:
  108. case Parse::NodeKind::TuplePatternStart: {
  109. // Parameters can have incomplete types in a function declaration, but not
  110. // in a function definition. We don't know which kind we have here.
  111. // TODO: A tuple pattern can appear in other places than function
  112. // parameters.
  113. auto param_id =
  114. context.AddInst(SemIR::Param{name_node, cast_type_id, name_id});
  115. context.AddInstAndPush(parse_node,
  116. make_bind_name(cast_type_id, param_id));
  117. break;
  118. }
  119. case Parse::NodeKind::LetIntroducer:
  120. cast_type_id = context.AsCompleteType(cast_type_id, [&] {
  121. CARBON_DIAGNOSTIC(IncompleteTypeInLetDecl, Error,
  122. "`let` binding has incomplete type `{0}`.",
  123. std::string);
  124. return context.emitter().Build(
  125. type_node_copy, IncompleteTypeInLetDecl,
  126. context.sem_ir().StringifyType(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(parse_node,
  133. context.insts().AddInNoBlock(make_bind_name(
  134. cast_type_id, SemIR::InstId::Invalid)));
  135. break;
  136. default:
  137. CARBON_FATAL() << "Found a pattern binding in unexpected context "
  138. << context_parse_node_kind;
  139. }
  140. return true;
  141. }
  142. auto HandleBindingPattern(Context& context, Parse::BindingPatternId parse_node)
  143. -> bool {
  144. return HandleAnyBindingPattern(context, parse_node, /*is_generic=*/false);
  145. }
  146. auto HandleGenericBindingPattern(Context& context,
  147. Parse::GenericBindingPatternId parse_node)
  148. -> bool {
  149. return HandleAnyBindingPattern(context, parse_node, /*is_generic=*/true);
  150. }
  151. auto HandleAddr(Context& context, Parse::AddrId parse_node) -> 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. parse_node,
  162. SemIR::AddrPattern{parse_node, 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