handle_binding_pattern.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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/handle.h"
  7. #include "toolchain/check/return.h"
  8. #include "toolchain/diagnostics/format_providers.h"
  9. #include "toolchain/sem_ir/ids.h"
  10. #include "toolchain/sem_ir/inst.h"
  11. namespace Carbon::Check {
  12. static auto HandleAnyBindingPattern(Context& context, Parse::NodeId node_id,
  13. bool is_generic) -> bool {
  14. auto [type_node, parsed_type_id] = context.node_stack().PopExprWithNodeId();
  15. auto [cast_type_inst_id, cast_type_id] =
  16. ExprAsType(context, type_node, parsed_type_id);
  17. // TODO: Handle `_` bindings.
  18. // Every other kind of pattern binding has a name.
  19. auto [name_node, name_id] = context.node_stack().PopNameWithNodeId();
  20. // Determine whether we're handling an associated constant. These share the
  21. // syntax for a compile-time binding, but don't behave like other compile-time
  22. // bindings.
  23. // TODO: Consider using a different parse node kind to make this easier.
  24. bool is_associated_constant = false;
  25. if (is_generic) {
  26. auto inst_id = context.scope_stack().PeekInstId();
  27. is_associated_constant =
  28. inst_id.is_valid() && context.insts().Is<SemIR::InterfaceDecl>(inst_id);
  29. }
  30. bool needs_compile_time_binding = is_generic && !is_associated_constant;
  31. // Create the appropriate kind of binding for this pattern.
  32. auto make_bind_name = [&](SemIR::TypeId type_id,
  33. SemIR::InstId value_id) -> SemIR::LocIdAndInst {
  34. // TODO: Eventually the name will need to support associations with other
  35. // scopes, but right now we don't support qualified names here.
  36. auto entity_name_id = context.entity_names().Add(
  37. {.name_id = name_id,
  38. .parent_scope_id = context.scope_stack().PeekNameScopeId(),
  39. // TODO: Don't allocate a compile-time binding index for an associated
  40. // constant declaration.
  41. .bind_index = needs_compile_time_binding
  42. ? context.scope_stack().AddCompileTimeBinding()
  43. : SemIR::CompileTimeBindIndex::Invalid});
  44. if (is_generic) {
  45. // TODO: Create a `BindTemplateName` instead inside a `template` pattern.
  46. return SemIR::LocIdAndInst(
  47. name_node, SemIR::BindSymbolicName{.type_id = type_id,
  48. .entity_name_id = entity_name_id,
  49. .value_id = value_id});
  50. } else {
  51. return SemIR::LocIdAndInst(
  52. name_node, SemIR::BindName{.type_id = type_id,
  53. .entity_name_id = entity_name_id,
  54. .value_id = value_id});
  55. }
  56. };
  57. // Push the binding onto the node stack and, if necessary, onto the scope
  58. // stack.
  59. auto push_bind_name = [&](SemIR::InstId bind_id) {
  60. context.node_stack().Push(node_id, bind_id);
  61. if (needs_compile_time_binding) {
  62. context.scope_stack().PushCompileTimeBinding(bind_id);
  63. }
  64. };
  65. // A `self` binding can only appear in an implicit parameter list.
  66. if (name_id == SemIR::NameId::SelfValue &&
  67. !context.node_stack().PeekIs<Parse::NodeKind::ImplicitParamListStart>()) {
  68. CARBON_DIAGNOSTIC(
  69. SelfOutsideImplicitParamList, Error,
  70. "`self` can only be declared in an implicit parameter list");
  71. context.emitter().Emit(node_id, SelfOutsideImplicitParamList);
  72. }
  73. // Allocate an instruction of the appropriate kind, linked to the name for
  74. // error locations.
  75. // TODO: The node stack is a fragile way of getting context information.
  76. // Get this information from somewhere else.
  77. switch (auto context_node_kind = context.node_stack().PeekNodeKind()) {
  78. case Parse::NodeKind::ReturnedModifier:
  79. case Parse::NodeKind::VariableIntroducer: {
  80. if (is_generic) {
  81. CARBON_DIAGNOSTIC(
  82. CompileTimeBindingInVarDecl, Error,
  83. "`var` declaration cannot declare a compile-time binding");
  84. context.emitter().Emit(type_node, CompileTimeBindingInVarDecl);
  85. }
  86. auto binding_id =
  87. is_generic
  88. ? Parse::NodeId::Invalid
  89. : context.parse_tree().As<Parse::BindingPatternId>(node_id);
  90. // A `var` declaration at class scope introduces a field.
  91. auto parent_class_decl = context.GetCurrentScopeAs<SemIR::ClassDecl>();
  92. cast_type_id = context.AsCompleteType(
  93. cast_type_id,
  94. [&] {
  95. CARBON_DIAGNOSTIC(IncompleteTypeInVarDecl, Error,
  96. "{0:field|variable} has incomplete type {1}",
  97. BoolAsSelect, SemIR::TypeId);
  98. return context.emitter().Build(type_node, IncompleteTypeInVarDecl,
  99. parent_class_decl.has_value(),
  100. cast_type_id);
  101. },
  102. [&] {
  103. CARBON_DIAGNOSTIC(AbstractTypeInVarDecl, Error,
  104. "{0:field|variable} has abstract type {1}",
  105. BoolAsSelect, SemIR::TypeId);
  106. return context.emitter().Build(type_node, AbstractTypeInVarDecl,
  107. parent_class_decl.has_value(),
  108. cast_type_id);
  109. });
  110. if (parent_class_decl) {
  111. CARBON_CHECK(context_node_kind == Parse::NodeKind::VariableIntroducer,
  112. "`returned var` at class scope");
  113. auto& class_info = context.classes().Get(parent_class_decl->class_id);
  114. auto field_type_id = context.GetUnboundElementType(
  115. class_info.self_type_id, cast_type_id);
  116. auto field_id = context.AddInst<SemIR::FieldDecl>(
  117. binding_id,
  118. {.type_id = field_type_id,
  119. .name_id = name_id,
  120. .index = SemIR::ElementIndex(context.args_type_info_stack()
  121. .PeekCurrentBlockContents()
  122. .size())});
  123. // Add a corresponding field to the object representation of the class.
  124. context.args_type_info_stack().AddInstId(
  125. context.AddInstInNoBlock<SemIR::StructTypeField>(
  126. binding_id,
  127. {.name_id = name_id, .field_type_id = cast_type_id}));
  128. context.node_stack().Push(node_id, field_id);
  129. break;
  130. }
  131. SemIR::InstId value_id = SemIR::InstId::Invalid;
  132. if (context_node_kind == Parse::NodeKind::ReturnedModifier) {
  133. // TODO: Should we check this for the `var` as a whole, rather than for
  134. // the name binding?
  135. value_id =
  136. CheckReturnedVar(context, context.node_stack().PeekNodeId(),
  137. name_node, name_id, type_node, cast_type_id);
  138. } else {
  139. value_id = context.AddInst<SemIR::VarStorage>(
  140. name_node, {.type_id = cast_type_id, .name_id = name_id});
  141. }
  142. auto bind_id = context.AddInst(make_bind_name(cast_type_id, value_id));
  143. push_bind_name(bind_id);
  144. if (context_node_kind == Parse::NodeKind::ReturnedModifier) {
  145. RegisterReturnedVar(context, bind_id);
  146. }
  147. break;
  148. }
  149. case Parse::NodeKind::ImplicitParamListStart:
  150. case Parse::NodeKind::TuplePatternStart: {
  151. // Parameters can have incomplete types in a function declaration, but not
  152. // in a function definition. We don't know which kind we have here.
  153. // TODO: A tuple pattern can appear in other places than function
  154. // parameters.
  155. auto param_id = context.AddInstInNoBlock<SemIR::Param>(
  156. name_node, {.type_id = cast_type_id,
  157. .runtime_index = SemIR::RuntimeParamIndex::Invalid});
  158. auto bind_id =
  159. context.AddInstInNoBlock(make_bind_name(cast_type_id, param_id));
  160. if (needs_compile_time_binding) {
  161. context.scope_stack().PushCompileTimeBinding(bind_id);
  162. }
  163. // TODO: Bindings should come into scope immediately in other contexts
  164. // too.
  165. context.AddNameToLookup(name_id, bind_id);
  166. auto entity_name_id =
  167. context.insts().GetAs<SemIR::AnyBindName>(bind_id).entity_name_id;
  168. auto pattern_inst_id = SemIR::InstId::Invalid;
  169. if (is_generic) {
  170. pattern_inst_id = context.AddPatternInst<SemIR::SymbolicBindingPattern>(
  171. name_node, {.type_id = cast_type_id,
  172. .entity_name_id = entity_name_id,
  173. .bind_name_id = bind_id});
  174. } else {
  175. pattern_inst_id = context.AddPatternInst<SemIR::BindingPattern>(
  176. name_node, {.type_id = cast_type_id,
  177. .entity_name_id = entity_name_id,
  178. .bind_name_id = bind_id});
  179. }
  180. auto param_pattern_id = context.AddPatternInst<SemIR::ParamPattern>(
  181. node_id,
  182. {
  183. .type_id = context.insts().Get(pattern_inst_id).type_id(),
  184. .subpattern_id = pattern_inst_id,
  185. .runtime_index = SemIR::RuntimeParamIndex::Invalid,
  186. });
  187. context.node_stack().Push(node_id, param_pattern_id);
  188. // TODO: use the pattern insts to generate the pattern-match insts
  189. // at the end of the full pattern, instead of eagerly generating them
  190. // here.
  191. break;
  192. }
  193. case Parse::NodeKind::LetIntroducer: {
  194. cast_type_id = context.AsCompleteType(cast_type_id, [&] {
  195. CARBON_DIAGNOSTIC(IncompleteTypeInLetDecl, Error,
  196. "`let` binding has incomplete type {0}",
  197. InstIdAsType);
  198. return context.emitter().Build(type_node, IncompleteTypeInLetDecl,
  199. cast_type_inst_id);
  200. });
  201. // Create the instruction, but don't add it to a block until after we've
  202. // formed its initializer.
  203. // TODO: For general pattern parsing, we'll need to create a block to hold
  204. // the `let` pattern before we see the initializer.
  205. auto bind_id = context.AddPlaceholderInstInNoBlock(
  206. make_bind_name(cast_type_id, SemIR::InstId::Invalid));
  207. push_bind_name(bind_id);
  208. break;
  209. }
  210. default:
  211. CARBON_FATAL("Found a pattern binding in unexpected context {0}",
  212. context_node_kind);
  213. }
  214. return true;
  215. }
  216. auto HandleParseNode(Context& context, Parse::BindingPatternId node_id)
  217. -> bool {
  218. return HandleAnyBindingPattern(context, node_id, /*is_generic=*/false);
  219. }
  220. auto HandleParseNode(Context& context,
  221. Parse::CompileTimeBindingPatternId node_id) -> bool {
  222. bool is_generic = true;
  223. if (context.decl_introducer_state_stack().innermost().kind ==
  224. Lex::TokenKind::Let) {
  225. // Disallow `let` outside of function and interface definitions.
  226. // TODO: find a less brittle way of doing this. An invalid scope_inst_id
  227. // can represent a block scope, but is also used for other kinds of scopes
  228. // that aren't necessarily part of an interface or function decl.
  229. auto scope_inst_id = context.scope_stack().PeekInstId();
  230. if (scope_inst_id.is_valid()) {
  231. auto scope_inst = context.insts().Get(scope_inst_id);
  232. if (!scope_inst.Is<SemIR::InterfaceDecl>() &&
  233. !scope_inst.Is<SemIR::FunctionDecl>()) {
  234. context.TODO(
  235. node_id,
  236. "`let` compile time binding outside function or interface");
  237. is_generic = false;
  238. }
  239. }
  240. }
  241. return HandleAnyBindingPattern(context, node_id, is_generic);
  242. }
  243. auto HandleParseNode(Context& context, Parse::AddrId node_id) -> bool {
  244. auto param_pattern_id = context.node_stack().PopPattern();
  245. if (SemIR::Function::GetParamPatternInfoFromPatternId(context.sem_ir(),
  246. param_pattern_id)
  247. .GetNameId(context.sem_ir()) == SemIR::NameId::SelfValue) {
  248. auto pointer_type = context.types().TryGetAs<SemIR::PointerType>(
  249. context.insts().Get(param_pattern_id).type_id());
  250. if (pointer_type) {
  251. auto addr_pattern_id = context.AddPatternInst<SemIR::AddrPattern>(
  252. node_id,
  253. {.type_id = SemIR::TypeId::AutoType, .inner_id = param_pattern_id});
  254. context.node_stack().Push(node_id, addr_pattern_id);
  255. } else {
  256. CARBON_DIAGNOSTIC(
  257. AddrOnNonPointerType, Error,
  258. "`addr` can only be applied to a binding with a pointer type");
  259. context.emitter().Emit(node_id, AddrOnNonPointerType);
  260. context.node_stack().Push(node_id, param_pattern_id);
  261. }
  262. } else {
  263. CARBON_DIAGNOSTIC(AddrOnNonSelfParam, Error,
  264. "`addr` can only be applied to a `self` parameter");
  265. context.emitter().Emit(TokenOnly(node_id), AddrOnNonSelfParam);
  266. context.node_stack().Push(node_id, param_pattern_id);
  267. }
  268. return true;
  269. }
  270. auto HandleParseNode(Context& context, Parse::TemplateId node_id) -> bool {
  271. return context.TODO(node_id, "HandleTemplate");
  272. }
  273. } // namespace Carbon::Check