handle_binding_pattern.cpp 7.6 KB

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