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