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