handle_binding_pattern.cpp 16 KB

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