handle_binding_pattern.cpp 14 KB

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