handle_binding_pattern.cpp 14 KB

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