handle_binding_pattern.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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. // Prevent lambda helpers from creating a compile time binding.
  86. needs_compile_time_binding = false;
  87. }
  88. auto binding_id =
  89. is_generic
  90. ? Parse::NodeId::Invalid
  91. : context.parse_tree().As<Parse::BindingPatternId>(node_id);
  92. // A `var` declaration at class scope introduces a field.
  93. auto parent_class_decl = context.GetCurrentScopeAs<SemIR::ClassDecl>();
  94. cast_type_id = context.AsCompleteType(
  95. cast_type_id,
  96. [&] {
  97. CARBON_DIAGNOSTIC(IncompleteTypeInVarDecl, Error,
  98. "{0:field|variable} has incomplete type {1}",
  99. BoolAsSelect, SemIR::TypeId);
  100. return context.emitter().Build(type_node, IncompleteTypeInVarDecl,
  101. parent_class_decl.has_value(),
  102. cast_type_id);
  103. },
  104. [&] {
  105. CARBON_DIAGNOSTIC(AbstractTypeInVarDecl, Error,
  106. "{0:field|variable} has abstract type {1}",
  107. BoolAsSelect, SemIR::TypeId);
  108. return context.emitter().Build(type_node, AbstractTypeInVarDecl,
  109. parent_class_decl.has_value(),
  110. cast_type_id);
  111. });
  112. if (parent_class_decl) {
  113. CARBON_CHECK(context_node_kind == Parse::NodeKind::VariableIntroducer,
  114. "`returned var` at class scope");
  115. auto& class_info = context.classes().Get(parent_class_decl->class_id);
  116. auto field_type_id = context.GetUnboundElementType(
  117. class_info.self_type_id, cast_type_id);
  118. auto field_id = context.AddInst<SemIR::FieldDecl>(
  119. binding_id, {.type_id = field_type_id,
  120. .name_id = name_id,
  121. .index = SemIR::ElementIndex::Invalid});
  122. context.field_decls_stack().AppendToTop(field_id);
  123. context.node_stack().Push(node_id, field_id);
  124. break;
  125. }
  126. SemIR::InstId value_id = SemIR::InstId::Invalid;
  127. if (context_node_kind == Parse::NodeKind::ReturnedModifier) {
  128. // TODO: Should we check this for the `var` as a whole, rather than for
  129. // the name binding?
  130. value_id =
  131. CheckReturnedVar(context, context.node_stack().PeekNodeId(),
  132. name_node, name_id, type_node, cast_type_id);
  133. } else {
  134. value_id = context.AddInst<SemIR::VarStorage>(
  135. name_node, {.type_id = cast_type_id, .name_id = name_id});
  136. }
  137. auto bind_id = context.AddInst(make_bind_name(cast_type_id, value_id));
  138. push_bind_name(bind_id);
  139. if (context_node_kind == Parse::NodeKind::ReturnedModifier) {
  140. RegisterReturnedVar(context, bind_id);
  141. }
  142. break;
  143. }
  144. case Parse::NodeKind::ImplicitParamListStart:
  145. case Parse::NodeKind::TuplePatternStart: {
  146. // Parameters can have incomplete types in a function declaration, but not
  147. // in a function definition. We don't know which kind we have here.
  148. // TODO: A tuple pattern can appear in other places than function
  149. // parameters.
  150. auto param_pattern_id = SemIR::InstId::Invalid;
  151. bool had_error = false;
  152. switch (context.decl_introducer_state_stack().innermost().kind) {
  153. case Lex::TokenKind::Fn: {
  154. if (context_node_kind == Parse::NodeKind::ImplicitParamListStart &&
  155. !(is_generic || name_id == SemIR::NameId::SelfValue)) {
  156. CARBON_DIAGNOSTIC(
  157. ImplictParamMustBeConstant, Error,
  158. "implicit parameters of functions must be constant or `self`");
  159. context.emitter().Emit(node_id, ImplictParamMustBeConstant);
  160. had_error = true;
  161. }
  162. break;
  163. }
  164. case Lex::TokenKind::Class:
  165. case Lex::TokenKind::Impl:
  166. case Lex::TokenKind::Interface: {
  167. if (name_id == SemIR::NameId::SelfValue) {
  168. CARBON_DIAGNOSTIC(SelfParameterNotAllowed, Error,
  169. "`self` parameter only allowed on functions");
  170. context.emitter().Emit(node_id, SelfParameterNotAllowed);
  171. had_error = true;
  172. } else if (!is_generic) {
  173. CARBON_DIAGNOSTIC(GenericParamMustBeConstant, Error,
  174. "parameters of generic types must be constant");
  175. context.emitter().Emit(node_id, GenericParamMustBeConstant);
  176. had_error = true;
  177. }
  178. break;
  179. }
  180. default:
  181. break;
  182. }
  183. if (had_error) {
  184. context.AddNameToLookup(name_id, SemIR::InstId::BuiltinErrorInst);
  185. // Replace the parameter with an invalid instruction so that we don't
  186. // try constructing a generic based on it.
  187. param_pattern_id = SemIR::InstId::BuiltinErrorInst;
  188. } else {
  189. auto bind_id = context.AddInstInNoBlock(
  190. make_bind_name(cast_type_id, SemIR::InstId::Invalid));
  191. if (needs_compile_time_binding) {
  192. context.scope_stack().PushCompileTimeBinding(bind_id);
  193. }
  194. // TODO: Bindings should come into scope immediately in other contexts
  195. // too.
  196. context.AddNameToLookup(name_id, bind_id);
  197. auto entity_name_id =
  198. context.insts().GetAs<SemIR::AnyBindName>(bind_id).entity_name_id;
  199. bool inserted = context.bind_name_cache()
  200. .Insert(entity_name_id, bind_id)
  201. .is_inserted();
  202. CARBON_CHECK(inserted);
  203. auto pattern_inst_id = SemIR::InstId::Invalid;
  204. if (is_generic) {
  205. pattern_inst_id =
  206. context.AddPatternInst<SemIR::SymbolicBindingPattern>(
  207. name_node,
  208. {.type_id = cast_type_id, .entity_name_id = entity_name_id});
  209. } else {
  210. pattern_inst_id = context.AddPatternInst<SemIR::BindingPattern>(
  211. name_node,
  212. {.type_id = cast_type_id, .entity_name_id = entity_name_id});
  213. }
  214. param_pattern_id = context.AddPatternInst<SemIR::ValueParamPattern>(
  215. node_id,
  216. {
  217. .type_id = context.insts().Get(pattern_inst_id).type_id(),
  218. .subpattern_id = pattern_inst_id,
  219. .runtime_index = is_generic ? SemIR::RuntimeParamIndex::Invalid
  220. : SemIR::RuntimeParamIndex::Unknown,
  221. });
  222. }
  223. context.node_stack().Push(node_id, param_pattern_id);
  224. // TODO: Use the pattern insts to generate the pattern-match insts
  225. // at the end of the full pattern, instead of eagerly generating them
  226. // here.
  227. break;
  228. }
  229. case Parse::NodeKind::LetIntroducer: {
  230. cast_type_id = context.AsCompleteType(cast_type_id, [&] {
  231. CARBON_DIAGNOSTIC(IncompleteTypeInLetDecl, Error,
  232. "`let` binding has incomplete type {0}",
  233. InstIdAsType);
  234. return context.emitter().Build(type_node, IncompleteTypeInLetDecl,
  235. cast_type_inst_id);
  236. });
  237. // Create the instruction, but don't add it to a block until after we've
  238. // formed its initializer.
  239. // TODO: For general pattern parsing, we'll need to create a block to hold
  240. // the `let` pattern before we see the initializer.
  241. auto bind_id = context.AddPlaceholderInstInNoBlock(
  242. make_bind_name(cast_type_id, SemIR::InstId::Invalid));
  243. push_bind_name(bind_id);
  244. break;
  245. }
  246. default:
  247. CARBON_FATAL("Found a pattern binding in unexpected context {0}",
  248. context_node_kind);
  249. }
  250. return true;
  251. }
  252. auto HandleParseNode(Context& context, Parse::BindingPatternId node_id)
  253. -> bool {
  254. return HandleAnyBindingPattern(context, node_id, /*is_generic=*/false);
  255. }
  256. auto HandleParseNode(Context& context,
  257. Parse::CompileTimeBindingPatternId node_id) -> bool {
  258. bool is_generic = true;
  259. if (context.decl_introducer_state_stack().innermost().kind ==
  260. Lex::TokenKind::Let) {
  261. // Disallow `let` outside of function and interface definitions.
  262. // TODO: Find a less brittle way of doing this. An invalid scope_inst_id
  263. // can represent a block scope, but is also used for other kinds of scopes
  264. // that aren't necessarily part of an interface or function decl.
  265. auto scope_inst_id = context.scope_stack().PeekInstId();
  266. if (scope_inst_id.is_valid()) {
  267. auto scope_inst = context.insts().Get(scope_inst_id);
  268. if (!scope_inst.Is<SemIR::InterfaceDecl>() &&
  269. !scope_inst.Is<SemIR::FunctionDecl>()) {
  270. context.TODO(
  271. node_id,
  272. "`let` compile time binding outside function or interface");
  273. is_generic = false;
  274. }
  275. }
  276. }
  277. return HandleAnyBindingPattern(context, node_id, is_generic);
  278. }
  279. auto HandleParseNode(Context& context, Parse::AddrId node_id) -> bool {
  280. auto param_pattern_id = context.node_stack().PopPattern();
  281. if (SemIR::Function::GetNameFromPatternId(
  282. context.sem_ir(), param_pattern_id) == SemIR::NameId::SelfValue) {
  283. auto pointer_type = context.types().TryGetAs<SemIR::PointerType>(
  284. context.insts().Get(param_pattern_id).type_id());
  285. if (pointer_type) {
  286. auto addr_pattern_id = context.AddPatternInst<SemIR::AddrPattern>(
  287. node_id,
  288. {.type_id = SemIR::TypeId::AutoType, .inner_id = param_pattern_id});
  289. context.node_stack().Push(node_id, addr_pattern_id);
  290. } else {
  291. CARBON_DIAGNOSTIC(
  292. AddrOnNonPointerType, Error,
  293. "`addr` can only be applied to a binding with a pointer type");
  294. context.emitter().Emit(node_id, AddrOnNonPointerType);
  295. context.node_stack().Push(node_id, param_pattern_id);
  296. }
  297. } else {
  298. CARBON_DIAGNOSTIC(AddrOnNonSelfParam, Error,
  299. "`addr` can only be applied to a `self` parameter");
  300. context.emitter().Emit(TokenOnly(node_id), AddrOnNonSelfParam);
  301. context.node_stack().Push(node_id, param_pattern_id);
  302. }
  303. return true;
  304. }
  305. auto HandleParseNode(Context& context, Parse::TemplateId node_id) -> bool {
  306. return context.TODO(node_id, "HandleTemplate");
  307. }
  308. } // namespace Carbon::Check