handle_binding_pattern.cpp 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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,
  24. .enclosing_scope_id = context.scope_stack().PeekNameScopeId()});
  25. if (is_generic) {
  26. // TODO: Create a `BindTemplateName` instead inside a `template` pattern.
  27. return {name_node,
  28. SemIR::BindSymbolicName{type_id, bind_name_id, value_id}};
  29. } else {
  30. return {name_node, SemIR::BindName{type_id, bind_name_id, value_id}};
  31. }
  32. };
  33. // A `self` binding can only appear in an implicit parameter list.
  34. if (name_id == SemIR::NameId::SelfValue &&
  35. !context.node_stack().PeekIs<Parse::NodeKind::ImplicitParamListStart>()) {
  36. CARBON_DIAGNOSTIC(
  37. SelfOutsideImplicitParamList, Error,
  38. "`self` can only be declared in an implicit parameter list.");
  39. context.emitter().Emit(parse_node, SelfOutsideImplicitParamList);
  40. }
  41. // Allocate an instruction of the appropriate kind, linked to the name for
  42. // error locations.
  43. // TODO: The node stack is a fragile way of getting context information.
  44. // Get this information from somewhere else.
  45. switch (auto context_parse_node_kind =
  46. context.node_stack().PeekParseNodeKind()) {
  47. case Parse::NodeKind::ReturnedModifier:
  48. case Parse::NodeKind::VariableIntroducer: {
  49. if (is_generic) {
  50. CARBON_DIAGNOSTIC(
  51. CompileTimeBindingInVarDecl, Error,
  52. "`var` declaration cannot declare a compile-time binding.");
  53. context.emitter().Emit(type_node, CompileTimeBindingInVarDecl);
  54. }
  55. auto binding_id =
  56. is_generic
  57. ? Parse::NodeId::Invalid
  58. : context.parse_tree().As<Parse::BindingPatternId>(parse_node);
  59. // A `var` declaration at class scope introduces a field.
  60. auto enclosing_class_decl = context.GetCurrentScopeAs<SemIR::ClassDecl>();
  61. cast_type_id = context.AsCompleteType(cast_type_id, [&] {
  62. CARBON_DIAGNOSTIC(IncompleteTypeInVarDecl, Error,
  63. "{0} has incomplete type `{1}`.", llvm::StringLiteral,
  64. std::string);
  65. return context.emitter().Build(
  66. type_node, IncompleteTypeInVarDecl,
  67. enclosing_class_decl ? llvm::StringLiteral("Field")
  68. : llvm::StringLiteral("Variable"),
  69. context.sem_ir().StringifyType(cast_type_id));
  70. });
  71. if (enclosing_class_decl) {
  72. CARBON_CHECK(context_parse_node_kind ==
  73. Parse::NodeKind::VariableIntroducer)
  74. << "`returned var` at class scope";
  75. auto& class_info =
  76. context.classes().Get(enclosing_class_decl->class_id);
  77. auto field_type_id = context.GetUnboundElementType(
  78. class_info.self_type_id, cast_type_id);
  79. auto field_id = context.AddInst(
  80. {binding_id, SemIR::FieldDecl{
  81. field_type_id, name_id,
  82. SemIR::ElementIndex(context.args_type_info_stack()
  83. .PeekCurrentBlockContents()
  84. .size())}});
  85. // Add a corresponding field to the object representation of the class.
  86. context.args_type_info_stack().AddInstId(context.AddInstInNoBlock(
  87. {binding_id, SemIR::StructTypeField{name_id, cast_type_id}}));
  88. context.node_stack().Push(parse_node, field_id);
  89. break;
  90. }
  91. SemIR::InstId value_id = SemIR::InstId::Invalid;
  92. if (context_parse_node_kind == Parse::NodeKind::ReturnedModifier) {
  93. // TODO: Should we check this for the `var` as a whole, rather than for
  94. // the name binding?
  95. value_id =
  96. CheckReturnedVar(context, context.node_stack().PeekParseNode(),
  97. name_node, name_id, type_node, cast_type_id);
  98. } else {
  99. value_id = context.AddInst(
  100. {name_node, SemIR::VarStorage{cast_type_id, name_id}});
  101. }
  102. auto bind_id = context.AddInst(make_bind_name(cast_type_id, value_id));
  103. context.node_stack().Push(parse_node, bind_id);
  104. if (context_parse_node_kind == Parse::NodeKind::ReturnedModifier) {
  105. RegisterReturnedVar(context, bind_id);
  106. }
  107. break;
  108. }
  109. case Parse::NodeKind::ImplicitParamListStart:
  110. case Parse::NodeKind::TuplePatternStart: {
  111. // Parameters can have incomplete types in a function declaration, but not
  112. // in a function definition. We don't know which kind we have here.
  113. // TODO: A tuple pattern can appear in other places than function
  114. // parameters.
  115. auto param_id =
  116. context.AddInst({name_node, SemIR::Param{cast_type_id, name_id}});
  117. auto bind_id = context.AddInst(make_bind_name(cast_type_id, param_id));
  118. // TODO: Bindings should come into scope immediately in other contexts
  119. // too.
  120. context.AddNameToLookup(name_id, bind_id);
  121. context.node_stack().Push(parse_node, bind_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, 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(
  138. parse_node, context.AddPlaceholderInstInNoBlock(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 HandleBindingPattern(Context& context, Parse::BindingPatternId parse_node)
  148. -> bool {
  149. return HandleAnyBindingPattern(context, parse_node, /*is_generic=*/false);
  150. }
  151. auto HandleGenericBindingPattern(Context& context,
  152. Parse::GenericBindingPatternId parse_node)
  153. -> bool {
  154. return HandleAnyBindingPattern(context, parse_node, /*is_generic=*/true);
  155. }
  156. auto HandleAddr(Context& context, Parse::AddrId parse_node) -> bool {
  157. auto self_param_id = context.node_stack().PopPattern();
  158. if (auto self_param =
  159. context.insts().TryGetAs<SemIR::AnyBindName>(self_param_id);
  160. self_param &&
  161. context.bind_names().Get(self_param->bind_name_id).name_id ==
  162. SemIR::NameId::SelfValue) {
  163. // TODO: The type of an `addr_pattern` should probably be the non-pointer
  164. // type, because that's the type that the pattern matches.
  165. context.AddInstAndPush(
  166. {parse_node, SemIR::AddrPattern{self_param->type_id, self_param_id}});
  167. } else {
  168. CARBON_DIAGNOSTIC(AddrOnNonSelfParam, Error,
  169. "`addr` can only be applied to a `self` parameter.");
  170. context.emitter().Emit(TokenOnly(parse_node), AddrOnNonSelfParam);
  171. context.node_stack().Push(parse_node, self_param_id);
  172. }
  173. return true;
  174. }
  175. auto HandleTemplate(Context& context, Parse::TemplateId parse_node) -> bool {
  176. return context.TODO(parse_node, "HandleTemplate");
  177. }
  178. } // namespace Carbon::Check