handle_binding_pattern.cpp 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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/ids.h"
  8. #include "toolchain/sem_ir/inst.h"
  9. namespace Carbon::Check {
  10. auto HandleAnyBindingPattern(Context& context, Parse::NodeId node_id,
  11. bool is_generic) -> bool {
  12. auto [type_node, parsed_type_id] = context.node_stack().PopExprWithNodeId();
  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().PopNameWithNodeId();
  17. // Determine whether we're handling an associated constant. These share the
  18. // syntax for a compile-time binding, but don't behave like other compile-time
  19. // bindings.
  20. // TODO: Consider using a different parse node kind to make this easier.
  21. bool is_associated_constant = false;
  22. if (is_generic) {
  23. auto inst_id = context.scope_stack().PeekInstId();
  24. is_associated_constant =
  25. inst_id.is_valid() && context.insts().Is<SemIR::InterfaceDecl>(inst_id);
  26. }
  27. // Create the appropriate kind of binding for this pattern.
  28. auto make_bind_name = [&](SemIR::TypeId type_id,
  29. SemIR::InstId value_id) -> SemIR::LocIdAndInst {
  30. // TODO: Eventually the name will need to support associations with other
  31. // scopes, but right now we don't support qualified names here.
  32. auto bind_name_id = context.bind_names().Add(
  33. {.name_id = name_id,
  34. .enclosing_scope_id = context.scope_stack().PeekNameScopeId(),
  35. // TODO: Don't allocate a compile-time binding index for an associated
  36. // constant declaration.
  37. .bind_index = is_generic && !is_associated_constant
  38. ? context.scope_stack().AddCompileTimeBinding()
  39. : SemIR::CompileTimeBindIndex::Invalid});
  40. if (is_generic) {
  41. // TODO: Create a `BindTemplateName` instead inside a `template` pattern.
  42. return SemIR::LocIdAndInst(
  43. name_node, SemIR::BindSymbolicName{.type_id = type_id,
  44. .bind_name_id = bind_name_id,
  45. .value_id = value_id});
  46. } else {
  47. return SemIR::LocIdAndInst(name_node,
  48. SemIR::BindName{.type_id = type_id,
  49. .bind_name_id = bind_name_id,
  50. .value_id = value_id});
  51. }
  52. };
  53. // A `self` binding can only appear in an implicit parameter list.
  54. if (name_id == SemIR::NameId::SelfValue &&
  55. !context.node_stack().PeekIs<Parse::NodeKind::ImplicitParamListStart>()) {
  56. CARBON_DIAGNOSTIC(
  57. SelfOutsideImplicitParamList, Error,
  58. "`self` can only be declared in an implicit parameter list.");
  59. context.emitter().Emit(node_id, SelfOutsideImplicitParamList);
  60. }
  61. // Allocate an instruction of the appropriate kind, linked to the name for
  62. // error locations.
  63. // TODO: The node stack is a fragile way of getting context information.
  64. // Get this information from somewhere else.
  65. switch (auto context_node_kind = context.node_stack().PeekNodeKind()) {
  66. case Parse::NodeKind::ReturnedModifier:
  67. case Parse::NodeKind::VariableIntroducer: {
  68. if (is_generic) {
  69. CARBON_DIAGNOSTIC(
  70. CompileTimeBindingInVarDecl, Error,
  71. "`var` declaration cannot declare a compile-time binding.");
  72. context.emitter().Emit(type_node, CompileTimeBindingInVarDecl);
  73. }
  74. auto binding_id =
  75. is_generic
  76. ? Parse::NodeId::Invalid
  77. : context.parse_tree().As<Parse::BindingPatternId>(node_id);
  78. // A `var` declaration at class scope introduces a field.
  79. auto enclosing_class_decl = context.GetCurrentScopeAs<SemIR::ClassDecl>();
  80. cast_type_id = context.AsCompleteType(cast_type_id, [&] {
  81. CARBON_DIAGNOSTIC(IncompleteTypeInVarDecl, Error,
  82. "{0} has incomplete type `{1}`.", llvm::StringLiteral,
  83. SemIR::TypeId);
  84. return context.emitter().Build(type_node, IncompleteTypeInVarDecl,
  85. enclosing_class_decl
  86. ? llvm::StringLiteral("Field")
  87. : llvm::StringLiteral("Variable"),
  88. cast_type_id);
  89. });
  90. if (enclosing_class_decl) {
  91. CARBON_CHECK(context_node_kind == Parse::NodeKind::VariableIntroducer)
  92. << "`returned var` at class scope";
  93. auto& class_info =
  94. context.classes().Get(enclosing_class_decl->class_id);
  95. auto field_type_id = context.GetUnboundElementType(
  96. class_info.self_type_id, cast_type_id);
  97. auto field_id = context.AddInst<SemIR::FieldDecl>(
  98. binding_id,
  99. {.type_id = field_type_id,
  100. .name_id = name_id,
  101. .index = 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().AddInstId(
  106. context.AddInstInNoBlock<SemIR::StructTypeField>(
  107. binding_id,
  108. {.name_id = name_id, .field_type_id = cast_type_id}));
  109. context.node_stack().Push(node_id, field_id);
  110. break;
  111. }
  112. SemIR::InstId value_id = SemIR::InstId::Invalid;
  113. if (context_node_kind == Parse::NodeKind::ReturnedModifier) {
  114. // TODO: Should we check this for the `var` as a whole, rather than for
  115. // the name binding?
  116. value_id =
  117. CheckReturnedVar(context, context.node_stack().PeekNodeId(),
  118. name_node, name_id, type_node, cast_type_id);
  119. } else {
  120. value_id = context.AddInst<SemIR::VarStorage>(
  121. name_node, {.type_id = cast_type_id, .name_id = name_id});
  122. }
  123. auto bind_id = context.AddInst(make_bind_name(cast_type_id, value_id));
  124. context.node_stack().Push(node_id, bind_id);
  125. if (context_node_kind == Parse::NodeKind::ReturnedModifier) {
  126. RegisterReturnedVar(context, bind_id);
  127. }
  128. break;
  129. }
  130. case Parse::NodeKind::ImplicitParamListStart:
  131. case Parse::NodeKind::TuplePatternStart: {
  132. // Parameters can have incomplete types in a function declaration, but not
  133. // in a function definition. We don't know which kind we have here.
  134. // TODO: A tuple pattern can appear in other places than function
  135. // parameters.
  136. auto param_id = context.AddInst<SemIR::Param>(
  137. name_node, {.type_id = cast_type_id, .name_id = name_id});
  138. auto bind_id = context.AddInst(make_bind_name(cast_type_id, param_id));
  139. // TODO: Bindings should come into scope immediately in other contexts
  140. // too.
  141. context.AddNameToLookup(name_id, bind_id);
  142. context.node_stack().Push(node_id, bind_id);
  143. break;
  144. }
  145. case Parse::NodeKind::LetIntroducer:
  146. cast_type_id = context.AsCompleteType(cast_type_id, [&] {
  147. CARBON_DIAGNOSTIC(IncompleteTypeInLetDecl, Error,
  148. "`let` binding has incomplete type `{0}`.",
  149. SemIR::TypeId);
  150. return context.emitter().Build(type_node, IncompleteTypeInLetDecl,
  151. cast_type_id);
  152. });
  153. // Create the instruction, but don't add it to a block until after we've
  154. // formed its initializer.
  155. // TODO: For general pattern parsing, we'll need to create a block to hold
  156. // the `let` pattern before we see the initializer.
  157. context.node_stack().Push(
  158. node_id, context.AddPlaceholderInstInNoBlock(
  159. make_bind_name(cast_type_id, SemIR::InstId::Invalid)));
  160. break;
  161. default:
  162. CARBON_FATAL() << "Found a pattern binding in unexpected context "
  163. << context_node_kind;
  164. }
  165. return true;
  166. }
  167. auto HandleBindingPattern(Context& context, Parse::BindingPatternId node_id)
  168. -> bool {
  169. return HandleAnyBindingPattern(context, node_id, /*is_generic=*/false);
  170. }
  171. auto HandleCompileTimeBindingPattern(Context& context,
  172. Parse::CompileTimeBindingPatternId node_id)
  173. -> bool {
  174. return HandleAnyBindingPattern(context, node_id, /*is_generic=*/true);
  175. }
  176. auto HandleAddr(Context& context, Parse::AddrId node_id) -> bool {
  177. auto self_param_id = context.node_stack().PopPattern();
  178. if (auto self_param =
  179. context.insts().TryGetAs<SemIR::AnyBindName>(self_param_id);
  180. self_param &&
  181. context.bind_names().Get(self_param->bind_name_id).name_id ==
  182. SemIR::NameId::SelfValue) {
  183. // TODO: The type of an `addr_pattern` should probably be the non-pointer
  184. // type, because that's the type that the pattern matches.
  185. context.AddInstAndPush<SemIR::AddrPattern>(
  186. node_id, {.type_id = self_param->type_id, .inner_id = self_param_id});
  187. } else {
  188. CARBON_DIAGNOSTIC(AddrOnNonSelfParam, Error,
  189. "`addr` can only be applied to a `self` parameter.");
  190. context.emitter().Emit(TokenOnly(node_id), AddrOnNonSelfParam);
  191. context.node_stack().Push(node_id, self_param_id);
  192. }
  193. return true;
  194. }
  195. auto HandleTemplate(Context& context, Parse::TemplateId node_id) -> bool {
  196. return context.TODO(node_id, "HandleTemplate");
  197. }
  198. } // namespace Carbon::Check