handle_binding_pattern.cpp 14 KB

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