handle_binding_pattern.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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/inst.h"
  8. #include "toolchain/check/interface.h"
  9. #include "toolchain/check/name_lookup.h"
  10. #include "toolchain/check/return.h"
  11. #include "toolchain/check/subpattern.h"
  12. #include "toolchain/check/type.h"
  13. #include "toolchain/check/type_completion.h"
  14. #include "toolchain/diagnostics/format_providers.h"
  15. #include "toolchain/sem_ir/ids.h"
  16. #include "toolchain/sem_ir/inst.h"
  17. #include "toolchain/sem_ir/pattern.h"
  18. namespace Carbon::Check {
  19. static auto HandleAnyBindingPattern(Context& context, Parse::NodeId node_id,
  20. Parse::NodeKind node_kind) -> bool {
  21. // TODO: split this into smaller, more focused functions.
  22. auto [type_node, parsed_type_id] = context.node_stack().PopExprWithNodeId();
  23. auto [cast_type_inst_id, cast_type_id] =
  24. ExprAsType(context, type_node, parsed_type_id);
  25. // TODO: Handle `_` bindings.
  26. SemIR::ExprRegionId type_expr_region_id =
  27. EndSubpatternAsExpr(context, cast_type_inst_id);
  28. // The name in a template binding may be wrapped in `template`.
  29. bool is_generic = node_kind == Parse::NodeKind::CompileTimeBindingPattern;
  30. auto is_template =
  31. context.node_stack()
  32. .PopAndDiscardSoloNodeIdIf<Parse::NodeKind::TemplateBindingName>();
  33. // A non-generic template binding is diagnosed by the parser.
  34. is_template &= is_generic;
  35. // Every other kind of pattern binding has a name.
  36. auto [name_node, name_id] = context.node_stack().PopNameWithNodeId();
  37. const DeclIntroducerState& introducer =
  38. context.decl_introducer_state_stack().innermost();
  39. auto make_binding_pattern = [&]() -> SemIR::InstId {
  40. auto bind_id = SemIR::InstId::None;
  41. auto binding_pattern_id = SemIR::InstId::None;
  42. // TODO: Eventually the name will need to support associations with other
  43. // scopes, but right now we don't support qualified names here.
  44. auto entity_name_id = context.entity_names().AddSymbolicBindingName(
  45. name_id, context.scope_stack().PeekNameScopeId(),
  46. is_generic ? context.scope_stack().AddCompileTimeBinding()
  47. : SemIR::CompileTimeBindIndex::None,
  48. is_template);
  49. if (is_generic) {
  50. bind_id = AddInstInNoBlock(
  51. context,
  52. SemIR::LocIdAndInst(name_node, SemIR::BindSymbolicName{
  53. .type_id = cast_type_id,
  54. .entity_name_id = entity_name_id,
  55. .value_id = SemIR::InstId::None}));
  56. binding_pattern_id = AddPatternInst<SemIR::SymbolicBindingPattern>(
  57. context, name_node,
  58. {.type_id = cast_type_id, .entity_name_id = entity_name_id});
  59. } else {
  60. bind_id = AddInstInNoBlock(
  61. context,
  62. SemIR::LocIdAndInst(
  63. name_node, SemIR::BindName{.type_id = cast_type_id,
  64. .entity_name_id = entity_name_id,
  65. .value_id = SemIR::InstId::None}));
  66. binding_pattern_id = AddPatternInst<SemIR::BindingPattern>(
  67. context, 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 (is_generic) {
  73. context.scope_stack().PushCompileTimeBinding(bind_id);
  74. }
  75. auto name_context =
  76. context.decl_name_stack().MakeUnqualifiedName(name_node, 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. // A `var` binding in a class scope declares a field, not a true binding,
  97. // so we handle it separately.
  98. if (auto parent_class_decl =
  99. context.scope_stack().GetCurrentScopeAs<SemIR::ClassDecl>();
  100. parent_class_decl.has_value() && !is_generic &&
  101. node_kind == Parse::NodeKind::VarBindingPattern) {
  102. cast_type_id = AsConcreteType(
  103. context, cast_type_id, type_node,
  104. [&] {
  105. CARBON_DIAGNOSTIC(IncompleteTypeInFieldDecl, Error,
  106. "field has incomplete type {0}", SemIR::TypeId);
  107. return context.emitter().Build(type_node, IncompleteTypeInFieldDecl,
  108. cast_type_id);
  109. },
  110. [&] {
  111. CARBON_DIAGNOSTIC(AbstractTypeInFieldDecl, Error,
  112. "field has abstract type {0}", SemIR::TypeId);
  113. return context.emitter().Build(type_node, AbstractTypeInFieldDecl,
  114. cast_type_id);
  115. });
  116. auto binding_id =
  117. context.parse_tree().As<Parse::VarBindingPatternId>(node_id);
  118. auto& class_info = context.classes().Get(parent_class_decl->class_id);
  119. auto field_type_id =
  120. GetUnboundElementType(context, class_info.self_type_id, cast_type_id);
  121. auto field_id =
  122. AddInst<SemIR::FieldDecl>(context, binding_id,
  123. {.type_id = field_type_id,
  124. .name_id = name_id,
  125. .index = SemIR::ElementIndex::None});
  126. context.field_decls_stack().AppendToTop(field_id);
  127. context.node_stack().Push(node_id, field_id);
  128. auto name_context =
  129. context.decl_name_stack().MakeUnqualifiedName(node_id, name_id);
  130. context.decl_name_stack().AddNameOrDiagnose(
  131. name_context, field_id, introducer.modifier_set.GetAccessKind());
  132. return true;
  133. }
  134. // A binding in an interface scope declares an associated constant, not a
  135. // true binding, so we handle it separately.
  136. if (auto parent_interface_decl =
  137. context.scope_stack().GetCurrentScopeAs<SemIR::InterfaceDecl>();
  138. parent_interface_decl.has_value() && is_generic) {
  139. cast_type_id = AsCompleteType(context, cast_type_id, type_node, [&] {
  140. CARBON_DIAGNOSTIC(IncompleteTypeInAssociatedConstantDecl, Error,
  141. "associated constant has incomplete type {0}",
  142. SemIR::TypeId);
  143. return context.emitter().Build(
  144. type_node, IncompleteTypeInAssociatedConstantDecl, cast_type_id);
  145. });
  146. if (is_template) {
  147. CARBON_DIAGNOSTIC(TemplateBindingInAssociatedConstantDecl, Error,
  148. "associated constant has `template` binding");
  149. context.emitter().Emit(type_node,
  150. TemplateBindingInAssociatedConstantDecl);
  151. }
  152. SemIR::AssociatedConstantDecl assoc_const_decl = {
  153. .type_id = cast_type_id,
  154. .assoc_const_id = SemIR::AssociatedConstantId::None,
  155. .decl_block_id = SemIR::InstBlockId::None};
  156. auto decl_id = AddPlaceholderInstInNoBlock(
  157. context,
  158. SemIR::LocIdAndInst(
  159. context.parse_tree().As<Parse::CompileTimeBindingPatternId>(
  160. node_id),
  161. assoc_const_decl));
  162. assoc_const_decl.assoc_const_id = context.associated_constants().Add(
  163. {.name_id = name_id,
  164. .parent_scope_id = context.scope_stack().PeekNameScopeId(),
  165. .decl_id = decl_id,
  166. .generic_id = SemIR::GenericId::None,
  167. .default_value_id = SemIR::InstId::None});
  168. ReplaceInstBeforeConstantUse(context, decl_id, assoc_const_decl);
  169. context.node_stack().Push(node_id, decl_id);
  170. return true;
  171. }
  172. // Allocate an instruction of the appropriate kind, linked to the name for
  173. // error locations.
  174. switch (context.full_pattern_stack().CurrentKind()) {
  175. case FullPatternStack::Kind::ImplicitParamList:
  176. case FullPatternStack::Kind::ExplicitParamList: {
  177. // Parameters can have incomplete types in a function declaration, but not
  178. // in a function definition. We don't know which kind we have here.
  179. bool had_error = false;
  180. switch (introducer.kind) {
  181. case Lex::TokenKind::Fn: {
  182. if (context.full_pattern_stack().CurrentKind() ==
  183. FullPatternStack::Kind::ImplicitParamList &&
  184. !(is_generic || name_id == SemIR::NameId::SelfValue)) {
  185. CARBON_DIAGNOSTIC(
  186. ImplictParamMustBeConstant, Error,
  187. "implicit parameters of functions must be constant or `self`");
  188. context.emitter().Emit(node_id, ImplictParamMustBeConstant);
  189. had_error = true;
  190. }
  191. break;
  192. }
  193. case Lex::TokenKind::Choice:
  194. if (context.scope_stack().PeekInstId().has_value()) {
  195. // We are building a pattern for a choice alternative, not the
  196. // choice type itself.
  197. // Implicit param lists are prevented during parse.
  198. CARBON_CHECK(context.full_pattern_stack().CurrentKind() !=
  199. FullPatternStack::Kind::ImplicitParamList,
  200. "choice alternative with implicit parameters");
  201. // Don't fall through to the `Class` logic for choice alternatives.
  202. break;
  203. }
  204. [[fallthrough]];
  205. case Lex::TokenKind::Class:
  206. case Lex::TokenKind::Impl:
  207. case Lex::TokenKind::Interface: {
  208. if (name_id == SemIR::NameId::SelfValue) {
  209. CARBON_DIAGNOSTIC(SelfParameterNotAllowed, Error,
  210. "`self` parameter only allowed on functions");
  211. context.emitter().Emit(node_id, SelfParameterNotAllowed);
  212. had_error = true;
  213. } else if (!is_generic) {
  214. CARBON_DIAGNOSTIC(GenericParamMustBeConstant, Error,
  215. "parameters of generic types must be constant");
  216. context.emitter().Emit(node_id, GenericParamMustBeConstant);
  217. had_error = true;
  218. }
  219. break;
  220. }
  221. default:
  222. break;
  223. }
  224. auto result_inst_id = SemIR::InstId::None;
  225. if (had_error) {
  226. AddNameToLookup(context, name_id, SemIR::ErrorInst::SingletonInstId);
  227. // Replace the parameter with `ErrorInst` so that we don't try
  228. // constructing a generic based on it.
  229. result_inst_id = SemIR::ErrorInst::SingletonInstId;
  230. } else {
  231. result_inst_id = make_binding_pattern();
  232. if (node_kind == Parse::NodeKind::LetBindingPattern) {
  233. // A value binding pattern in a function signature is a `Call`
  234. // parameter, but a variable binding pattern is not (instead the
  235. // enclosing `var` pattern is), and a symbolic binding pattern is not
  236. // (because it's not passed to the `Call` inst).
  237. result_inst_id = AddPatternInst<SemIR::ValueParamPattern>(
  238. context, node_id,
  239. {.type_id = context.insts().Get(result_inst_id).type_id(),
  240. .subpattern_id = result_inst_id,
  241. .index = SemIR::CallParamIndex::None});
  242. }
  243. }
  244. context.node_stack().Push(node_id, result_inst_id);
  245. break;
  246. }
  247. case FullPatternStack::Kind::NameBindingDecl: {
  248. auto incomplete_diagnoser = [&] {
  249. CARBON_DIAGNOSTIC(IncompleteTypeInBindingDecl, Error,
  250. "binding pattern has incomplete type {0} in name "
  251. "binding declaration",
  252. InstIdAsType);
  253. return context.emitter().Build(type_node, IncompleteTypeInBindingDecl,
  254. cast_type_inst_id);
  255. };
  256. if (node_kind == Parse::NodeKind::VarBindingPattern) {
  257. cast_type_id = AsConcreteType(
  258. context, cast_type_id, type_node, incomplete_diagnoser, [&] {
  259. CARBON_DIAGNOSTIC(
  260. AbstractTypeInVarPattern, Error,
  261. "binding pattern has abstract type {0} in `var` "
  262. "pattern",
  263. SemIR::TypeId);
  264. return context.emitter().Build(
  265. type_node, AbstractTypeInVarPattern, cast_type_id);
  266. });
  267. } else {
  268. cast_type_id = AsCompleteType(context, cast_type_id, type_node,
  269. incomplete_diagnoser);
  270. }
  271. auto binding_pattern_id = make_binding_pattern();
  272. if (node_kind == Parse::NodeKind::VarBindingPattern) {
  273. CARBON_CHECK(!is_generic);
  274. if (introducer.modifier_set.HasAnyOf(KeywordModifierSet::Returned)) {
  275. // TODO: Should we check this for the `var` as a whole, rather than
  276. // for the name binding?
  277. auto bind_id = context.bind_name_map()
  278. .Lookup(binding_pattern_id)
  279. .value()
  280. .bind_name_id;
  281. RegisterReturnedVar(context,
  282. introducer.modifier_node_id(ModifierOrder::Decl),
  283. type_node, cast_type_id, bind_id);
  284. }
  285. }
  286. context.node_stack().Push(node_id, binding_pattern_id);
  287. break;
  288. }
  289. }
  290. return true;
  291. }
  292. auto HandleParseNode(Context& context, Parse::LetBindingPatternId node_id)
  293. -> bool {
  294. return HandleAnyBindingPattern(context, node_id,
  295. Parse::NodeKind::LetBindingPattern);
  296. }
  297. auto HandleParseNode(Context& context, Parse::VarBindingPatternId node_id)
  298. -> bool {
  299. return HandleAnyBindingPattern(context, node_id,
  300. Parse::NodeKind::VarBindingPattern);
  301. }
  302. auto HandleParseNode(Context& context,
  303. Parse::CompileTimeBindingPatternId node_id) -> bool {
  304. auto node_kind = Parse::NodeKind::CompileTimeBindingPattern;
  305. if (context.decl_introducer_state_stack().innermost().kind ==
  306. Lex::TokenKind::Let) {
  307. // Disallow `let` outside of function and interface definitions.
  308. // TODO: Find a less brittle way of doing this. A `scope_inst_id` of `None`
  309. // can represent a block scope, but is also used for other kinds of scopes
  310. // that aren't necessarily part of an interface or function decl.
  311. auto scope_inst_id = context.scope_stack().PeekInstId();
  312. if (scope_inst_id.has_value()) {
  313. auto scope_inst = context.insts().Get(scope_inst_id);
  314. if (!scope_inst.Is<SemIR::InterfaceDecl>() &&
  315. !scope_inst.Is<SemIR::FunctionDecl>()) {
  316. context.TODO(
  317. node_id,
  318. "`let` compile time binding outside function or interface");
  319. node_kind = Parse::NodeKind::LetBindingPattern;
  320. }
  321. }
  322. }
  323. return HandleAnyBindingPattern(context, node_id, node_kind);
  324. }
  325. auto HandleParseNode(Context& context, Parse::AddrId node_id) -> bool {
  326. auto param_pattern_id = context.node_stack().PopPattern();
  327. if (SemIR::IsSelfPattern(context.sem_ir(), param_pattern_id)) {
  328. auto pointer_type = context.types().TryGetAs<SemIR::PointerType>(
  329. context.insts().Get(param_pattern_id).type_id());
  330. if (pointer_type) {
  331. auto addr_pattern_id = AddPatternInst<SemIR::AddrPattern>(
  332. context, node_id,
  333. {.type_id = SemIR::AutoType::SingletonTypeId,
  334. .inner_id = param_pattern_id});
  335. context.node_stack().Push(node_id, addr_pattern_id);
  336. } else {
  337. CARBON_DIAGNOSTIC(
  338. AddrOnNonPointerType, Error,
  339. "`addr` can only be applied to a binding with a pointer type");
  340. context.emitter().Emit(node_id, AddrOnNonPointerType);
  341. context.node_stack().Push(node_id, param_pattern_id);
  342. }
  343. } else {
  344. CARBON_DIAGNOSTIC(AddrOnNonSelfParam, Error,
  345. "`addr` can only be applied to a `self` parameter");
  346. context.emitter().Emit(TokenOnly(node_id), AddrOnNonSelfParam);
  347. context.node_stack().Push(node_id, param_pattern_id);
  348. }
  349. return true;
  350. }
  351. auto HandleParseNode(Context& context, Parse::TemplateBindingNameId node_id)
  352. -> bool {
  353. context.node_stack().Push(node_id);
  354. return true;
  355. }
  356. } // namespace Carbon::Check