handle_binding_pattern.cpp 7.4 KB

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