handle_binding_pattern.cpp 17 KB

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