handle_binding_pattern.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  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 <utility>
  5. #include "toolchain/base/kind_switch.h"
  6. #include "toolchain/check/context.h"
  7. #include "toolchain/check/convert.h"
  8. #include "toolchain/check/facet_type.h"
  9. #include "toolchain/check/handle.h"
  10. #include "toolchain/check/inst.h"
  11. #include "toolchain/check/interface.h"
  12. #include "toolchain/check/name_lookup.h"
  13. #include "toolchain/check/pattern.h"
  14. #include "toolchain/check/return.h"
  15. #include "toolchain/check/type.h"
  16. #include "toolchain/check/type_completion.h"
  17. #include "toolchain/check/unused.h"
  18. #include "toolchain/diagnostics/format_providers.h"
  19. #include "toolchain/parse/node_ids.h"
  20. #include "toolchain/sem_ir/ids.h"
  21. #include "toolchain/sem_ir/inst.h"
  22. #include "toolchain/sem_ir/pattern.h"
  23. #include "toolchain/sem_ir/typed_insts.h"
  24. namespace Carbon::Check {
  25. auto HandleParseNode(Context& context, Parse::UnderscoreNameId node_id)
  26. -> bool {
  27. context.node_stack().Push(node_id, SemIR::NameId::Underscore);
  28. return true;
  29. }
  30. // Returns the `InstKind` corresponding to the pattern's `NodeKind`.
  31. static auto GetPatternInstKind(Parse::NodeKind node_kind, bool is_ref)
  32. -> SemIR::InstKind {
  33. switch (node_kind) {
  34. case Parse::NodeKind::CompileTimeBindingPattern:
  35. return SemIR::InstKind::SymbolicBindingPattern;
  36. case Parse::NodeKind::LetBindingPattern:
  37. return is_ref ? SemIR::InstKind::RefBindingPattern
  38. : SemIR::InstKind::ValueBindingPattern;
  39. case Parse::NodeKind::VarBindingPattern:
  40. return SemIR::InstKind::RefBindingPattern;
  41. default:
  42. CARBON_FATAL("Unexpected node kind: {0}", node_kind);
  43. }
  44. }
  45. // Returns true if a parameter is valid in the given `introducer_kind`.
  46. static auto IsValidParamForIntroducer(Context& context, Parse::NodeId node_id,
  47. SemIR::NameId name_id,
  48. Lex::TokenKind introducer_kind,
  49. bool is_generic) -> bool {
  50. switch (introducer_kind) {
  51. case Lex::TokenKind::Fn: {
  52. if (context.full_pattern_stack().CurrentKind() ==
  53. FullPatternStack::Kind::ImplicitParamList &&
  54. !(is_generic || name_id == SemIR::NameId::SelfValue)) {
  55. CARBON_DIAGNOSTIC(
  56. ImplictParamMustBeConstant, Error,
  57. "implicit parameters of functions must be constant or `self`");
  58. context.emitter().Emit(node_id, ImplictParamMustBeConstant);
  59. return false;
  60. }
  61. // Parameters can have incomplete types in a function declaration, but not
  62. // in a function definition. We don't know which kind we have here, so
  63. // don't validate it.
  64. return true;
  65. }
  66. case Lex::TokenKind::Choice:
  67. if (context.scope_stack().PeekInstId().has_value()) {
  68. // We are building a pattern for a choice alternative, not the
  69. // choice type itself.
  70. // Implicit param lists are prevented during parse.
  71. CARBON_CHECK(context.full_pattern_stack().CurrentKind() !=
  72. FullPatternStack::Kind::ImplicitParamList,
  73. "choice alternative with implicit parameters");
  74. // Don't fall through to the `Class` logic for choice alternatives.
  75. return true;
  76. }
  77. [[fallthrough]];
  78. case Lex::TokenKind::Class:
  79. case Lex::TokenKind::Impl:
  80. case Lex::TokenKind::Interface: {
  81. if (name_id == SemIR::NameId::SelfValue) {
  82. CARBON_DIAGNOSTIC(SelfParameterNotAllowed, Error,
  83. "`self` parameter only allowed on functions");
  84. context.emitter().Emit(node_id, SelfParameterNotAllowed);
  85. return false;
  86. }
  87. if (!is_generic) {
  88. CARBON_DIAGNOSTIC(GenericParamMustBeConstant, Error,
  89. "parameters of generic types must be constant");
  90. context.emitter().Emit(node_id, GenericParamMustBeConstant);
  91. return false;
  92. }
  93. return true;
  94. }
  95. default:
  96. return true;
  97. }
  98. }
  99. // TODO: make this function shorter by factoring pieces out.
  100. static auto HandleAnyBindingPattern(Context& context, Parse::NodeId node_id,
  101. Parse::NodeKind node_kind,
  102. bool is_unused = false) -> bool {
  103. // TODO: split this into smaller, more focused functions.
  104. auto [type_node, parsed_type_id] = context.node_stack().PopExprWithNodeId();
  105. auto [cast_type_inst_id, cast_type_id] =
  106. ExprAsType(context, type_node, parsed_type_id);
  107. SemIR::ExprRegionId type_expr_region_id =
  108. EndSubpatternAsExpr(context, cast_type_inst_id);
  109. // The name in a generic binding may be wrapped in `template`.
  110. bool is_generic = node_kind == Parse::NodeKind::CompileTimeBindingPattern;
  111. bool is_template =
  112. context.node_stack()
  113. .PopAndDiscardSoloNodeIdIf<Parse::NodeKind::TemplateBindingName>();
  114. // A non-generic template binding is diagnosed by the parser.
  115. is_template &= is_generic;
  116. // The name in a runtime binding may be wrapped in `ref`.
  117. bool is_ref =
  118. context.node_stack()
  119. .PopAndDiscardSoloNodeIdIf<Parse::NodeKind::RefBindingName>();
  120. SemIR::InstKind pattern_inst_kind = GetPatternInstKind(node_kind, is_ref);
  121. auto [name_node, name_id] = context.node_stack().PopNameWithNodeId();
  122. const DeclIntroducerState& introducer =
  123. context.decl_introducer_state_stack().innermost();
  124. auto make_binding_pattern = [&]() -> SemIR::InstId {
  125. // TODO: Eventually the name will need to support associations with other
  126. // scopes, but right now we don't support qualified names here.
  127. auto binding = AddBindingPattern(context, name_node, name_id, cast_type_id,
  128. type_expr_region_id, pattern_inst_kind,
  129. is_template, is_unused);
  130. // TODO: If `is_generic`, then `binding.bind_id is a SymbolicBinding. Subst
  131. // the `.Self` of type `type` in the `cast_type_id` type (a `FacetType`)
  132. // with the `binding.bind_id` itself, and build a new pattern with that.
  133. // This is kind of cyclical. So we need to reuse the EntityNameId, which
  134. // will also reuse the CompileTimeBinding for the new SymbolicBinding.
  135. if (name_id != SemIR::NameId::Underscore) {
  136. // Add name to lookup immediately, so it can be used in the rest of the
  137. // enclosing pattern.
  138. auto name_context =
  139. context.decl_name_stack().MakeUnqualifiedName(name_node, name_id);
  140. context.decl_name_stack().AddNameOrDiagnose(
  141. name_context, binding.bind_id,
  142. introducer.modifier_set.GetAccessKind());
  143. context.full_pattern_stack().AddBindName(name_id);
  144. }
  145. return binding.pattern_id;
  146. };
  147. auto abstract_diagnostic_context = [&](auto& builder) {
  148. CARBON_DIAGNOSTIC(AbstractTypeInVarPattern, Context,
  149. "binding pattern has abstract type {0} in `var` "
  150. "pattern",
  151. SemIR::TypeId);
  152. builder.Context(type_node, AbstractTypeInVarPattern, cast_type_id);
  153. };
  154. // A `self` binding can only appear in an implicit parameter list.
  155. if (name_id == SemIR::NameId::SelfValue &&
  156. !context.node_stack().PeekIs(Parse::NodeKind::ImplicitParamListStart)) {
  157. CARBON_DIAGNOSTIC(
  158. SelfOutsideImplicitParamList, Error,
  159. "`self` can only be declared in an implicit parameter list");
  160. context.emitter().Emit(node_id, SelfOutsideImplicitParamList);
  161. }
  162. if (node_kind == Parse::NodeKind::CompileTimeBindingPattern &&
  163. introducer.kind == Lex::TokenKind::Let) {
  164. // TODO: We should re-evaluate the contents of the eval block in a
  165. // synthesized specific to form these values, in order to propagate the
  166. // values.
  167. return context.TODO(node_id,
  168. "local `let :!` bindings are currently unsupported");
  169. }
  170. // Allocate an instruction of the appropriate kind, linked to the name for
  171. // error locations.
  172. switch (context.full_pattern_stack().CurrentKind()) {
  173. case FullPatternStack::Kind::ImplicitParamList:
  174. case FullPatternStack::Kind::ExplicitParamList: {
  175. if (!IsValidParamForIntroducer(context, node_id, name_id, introducer.kind,
  176. is_generic)) {
  177. if (name_id != SemIR::NameId::Underscore) {
  178. AddNameToLookup(context, name_id, SemIR::ErrorInst::InstId);
  179. }
  180. // Replace the parameter with `ErrorInst` so that we don't try
  181. // constructing a generic based on it.
  182. context.node_stack().Push(node_id, SemIR::ErrorInst::InstId);
  183. break;
  184. }
  185. // Using `AsConcreteType` here causes `fn F[var self: Self]();`
  186. // to fail since `Self` is an incomplete type.
  187. if (node_kind == Parse::NodeKind::VarBindingPattern) {
  188. auto [unqualified_type_id, qualifiers] =
  189. context.types().GetUnqualifiedTypeAndQualifiers(cast_type_id);
  190. if ((qualifiers & SemIR::TypeQualifiers::Partial) !=
  191. SemIR::TypeQualifiers::Partial &&
  192. context.types().Is<SemIR::ClassType>(unqualified_type_id)) {
  193. auto class_type =
  194. context.types().GetAs<SemIR::ClassType>(unqualified_type_id);
  195. auto& class_info = context.classes().Get(class_type.class_id);
  196. if (class_info.inheritance_kind ==
  197. SemIR::Class::InheritanceKind::Abstract) {
  198. Diagnostics::ContextScope scope(&context.emitter(),
  199. abstract_diagnostic_context);
  200. DiagnoseAbstractClass(context, class_type.class_id,
  201. /*direct_use=*/true);
  202. cast_type_id = SemIR::ErrorInst::TypeId;
  203. }
  204. }
  205. }
  206. auto result_inst_id = make_binding_pattern();
  207. // A binding pattern in a function signature is a `Call` parameter
  208. // unless it's nested inside a `var` pattern (because then the
  209. // enclosing `var` pattern is), or it's a compile-time binding pattern
  210. // (because then it's not passed to the `Call` inst).
  211. if (node_kind == Parse::NodeKind::LetBindingPattern) {
  212. auto type_id = context.insts().GetAttachedType(result_inst_id);
  213. if (is_ref) {
  214. result_inst_id = AddPatternInst<SemIR::RefParamPattern>(
  215. context, node_id,
  216. {.type_id = type_id,
  217. .subpattern_id = result_inst_id,
  218. .index = context.full_pattern_stack().NextCallParamIndex()});
  219. } else {
  220. result_inst_id = AddPatternInst<SemIR::ValueParamPattern>(
  221. context, node_id,
  222. {.type_id = type_id,
  223. .subpattern_id = result_inst_id,
  224. .index = context.full_pattern_stack().NextCallParamIndex()});
  225. }
  226. }
  227. context.node_stack().Push(node_id, result_inst_id);
  228. break;
  229. }
  230. case FullPatternStack::Kind::NameBindingDecl: {
  231. auto incomplete_diagnostic_context = [&](auto& builder) {
  232. CARBON_DIAGNOSTIC(IncompleteTypeInBindingDecl, Context,
  233. "binding pattern has incomplete type {0} in name "
  234. "binding declaration",
  235. InstIdAsType);
  236. builder.Context(type_node, IncompleteTypeInBindingDecl,
  237. cast_type_inst_id);
  238. };
  239. if (node_kind == Parse::NodeKind::VarBindingPattern) {
  240. if (!RequireConcreteType(context, cast_type_id, type_node,
  241. incomplete_diagnostic_context,
  242. abstract_diagnostic_context)) {
  243. cast_type_id = SemIR::ErrorInst::TypeId;
  244. }
  245. } else {
  246. if (!RequireCompleteType(context, cast_type_id, type_node,
  247. incomplete_diagnostic_context)) {
  248. cast_type_id = SemIR::ErrorInst::TypeId;
  249. }
  250. }
  251. auto binding_pattern_id = make_binding_pattern();
  252. if (node_kind == Parse::NodeKind::VarBindingPattern) {
  253. CARBON_CHECK(!is_generic);
  254. if (introducer.modifier_set.HasAnyOf(KeywordModifierSet::Returned)) {
  255. // TODO: Should we check this for the `var` as a whole, rather than
  256. // for the name binding?
  257. auto bind_id = context.bind_name_map()
  258. .Lookup(binding_pattern_id)
  259. .value()
  260. .bind_name_id;
  261. RegisterReturnedVar(context,
  262. introducer.modifier_node_id(ModifierOrder::Decl),
  263. type_node, cast_type_id, bind_id, name_id);
  264. }
  265. }
  266. context.node_stack().Push(node_id, binding_pattern_id);
  267. break;
  268. }
  269. }
  270. return true;
  271. }
  272. auto HandleParseNode(Context& context, Parse::LetBindingPatternId node_id)
  273. -> bool {
  274. return HandleAnyBindingPattern(context, node_id,
  275. Parse::NodeKind::LetBindingPattern);
  276. }
  277. auto HandleParseNode(Context& context, Parse::VarBindingPatternId node_id)
  278. -> bool {
  279. return HandleAnyBindingPattern(context, node_id,
  280. Parse::NodeKind::VarBindingPattern);
  281. }
  282. auto HandleParseNode(Context& context, Parse::FormBindingPatternId node_id)
  283. -> bool {
  284. return context.TODO(node_id, "Implement :? support");
  285. }
  286. auto HandleParseNode(Context& context,
  287. Parse::CompileTimeBindingPatternStartId /*node_id*/)
  288. -> bool {
  289. // Make a scope to contain the `.Self` facet value for use in the type of the
  290. // compile time binding. This is popped when handling the
  291. // CompileTimeBindingPatternId.
  292. context.scope_stack().PushForSameRegion();
  293. // The `.Self` must have a type of `FacetType`, so that it gets wrapped in
  294. // `FacetAccessType` when used in a type position, such as in `U:! I(.Self)`.
  295. // This allows substitution with other facet values without requiring an
  296. // additional `FacetAccessType` to be inserted.
  297. auto type_id = GetEmptyFacetType(context);
  298. MakePeriodSelfFacetValue(context, type_id);
  299. return true;
  300. }
  301. auto HandleParseNode(Context& context,
  302. Parse::CompileTimeBindingPatternId node_id) -> bool {
  303. // Pop the `.Self` facet value name introduced by the
  304. // CompileTimeBindingPatternStart.
  305. context.scope_stack().Pop(/*check_unused=*/true);
  306. auto node_kind = Parse::NodeKind::CompileTimeBindingPattern;
  307. const DeclIntroducerState& introducer =
  308. context.decl_introducer_state_stack().innermost();
  309. if (introducer.kind == Lex::TokenKind::Let) {
  310. // Disallow `let` outside of function and interface definitions.
  311. // TODO: Find a less brittle way of doing this. A `scope_inst_id` of `None`
  312. // can represent a block scope, but is also used for other kinds of scopes
  313. // that aren't necessarily part of a function decl.
  314. // We don't need to check if the scope is an interface here as this is
  315. // already caught in the parse phase by the separated associated constant
  316. // logic.
  317. auto scope_inst_id = context.scope_stack().PeekInstId();
  318. if (scope_inst_id.has_value()) {
  319. auto scope_inst = context.insts().Get(scope_inst_id);
  320. if (!scope_inst.Is<SemIR::FunctionDecl>()) {
  321. context.TODO(
  322. node_id,
  323. "`let` compile time binding outside function or interface");
  324. node_kind = Parse::NodeKind::LetBindingPattern;
  325. }
  326. }
  327. }
  328. return HandleAnyBindingPattern(context, node_id, node_kind);
  329. }
  330. auto HandleParseNode(Context& context,
  331. Parse::AssociatedConstantNameAndTypeId node_id) -> bool {
  332. auto [type_node, parsed_type_id] = context.node_stack().PopExprWithNodeId();
  333. auto [cast_type_inst_id, cast_type_id] =
  334. ExprAsType(context, type_node, parsed_type_id);
  335. EndSubpatternAsExpr(context, cast_type_inst_id);
  336. auto [name_node, name_id] = context.node_stack().PopNameWithNodeId();
  337. if (name_id == SemIR::NameId::Underscore) {
  338. // The action item here may be to document this as not allowed, and
  339. // add a proper diagnostic.
  340. context.TODO(node_id, "_ used as associated constant name");
  341. }
  342. SemIR::AssociatedConstantDecl assoc_const_decl = {
  343. .type_id = cast_type_id,
  344. .assoc_const_id = SemIR::AssociatedConstantId::None,
  345. .decl_block_id = SemIR::InstBlockId::None};
  346. auto decl_id =
  347. AddPlaceholderInstInNoBlock(context, node_id, assoc_const_decl);
  348. assoc_const_decl.assoc_const_id = context.associated_constants().Add(
  349. {.name_id = name_id,
  350. .parent_scope_id = context.scope_stack().PeekNameScopeId(),
  351. .decl_id = decl_id,
  352. .default_value_id = SemIR::InstId::None});
  353. ReplaceInstBeforeConstantUse(context, decl_id, assoc_const_decl);
  354. context.node_stack().Push(node_id, decl_id);
  355. return true;
  356. }
  357. auto HandleParseNode(Context& context, Parse::FieldNameAndTypeId node_id)
  358. -> bool {
  359. auto [type_node, parsed_type_id] = context.node_stack().PopExprWithNodeId();
  360. auto [cast_type_inst_id, cast_type_id] =
  361. ExprAsType(context, type_node, parsed_type_id);
  362. auto [name_node, name_id] = context.node_stack().PopNameWithNodeId();
  363. auto parent_class_decl =
  364. context.scope_stack().TryGetCurrentScopeAs<SemIR::ClassDecl>();
  365. CARBON_CHECK(parent_class_decl);
  366. if (!RequireConcreteType(
  367. context, cast_type_id, type_node,
  368. [&](auto& builder) {
  369. CARBON_DIAGNOSTIC(IncompleteTypeInFieldDecl, Context,
  370. "field has incomplete type {0}", SemIR::TypeId);
  371. builder.Context(type_node, IncompleteTypeInFieldDecl, cast_type_id);
  372. },
  373. [&](auto& builder) {
  374. CARBON_DIAGNOSTIC(AbstractTypeInFieldDecl, Context,
  375. "field has abstract type {0}", SemIR::TypeId);
  376. builder.Context(type_node, AbstractTypeInFieldDecl, cast_type_id);
  377. })) {
  378. cast_type_id = SemIR::ErrorInst::TypeId;
  379. }
  380. if (cast_type_id == SemIR::ErrorInst::TypeId) {
  381. cast_type_inst_id = SemIR::ErrorInst::TypeInstId;
  382. }
  383. auto& class_info = context.classes().Get(parent_class_decl->class_id);
  384. auto field_type_id = GetUnboundElementType(
  385. context, context.types().GetTypeInstId(class_info.self_type_id),
  386. cast_type_inst_id);
  387. auto field_id =
  388. AddInst<SemIR::FieldDecl>(context, node_id,
  389. {.type_id = field_type_id,
  390. .name_id = name_id,
  391. .index = SemIR::ElementIndex::None});
  392. context.field_decls_stack().AppendToTop(field_id);
  393. auto name_context =
  394. context.decl_name_stack().MakeUnqualifiedName(node_id, name_id);
  395. context.decl_name_stack().AddNameOrDiagnose(
  396. name_context, field_id,
  397. context.decl_introducer_state_stack()
  398. .innermost()
  399. .modifier_set.GetAccessKind());
  400. return true;
  401. }
  402. auto HandleParseNode(Context& context, Parse::RefBindingNameId node_id)
  403. -> bool {
  404. context.node_stack().Push(node_id);
  405. return true;
  406. }
  407. auto HandleParseNode(Context& context, Parse::TemplateBindingNameId node_id)
  408. -> bool {
  409. context.node_stack().Push(node_id);
  410. return true;
  411. }
  412. // Within a pattern with an unused modifier, sets the is_unused on all
  413. // entity names and also returns whether any names were found. The result
  414. // is needed to emit a diagnostic when the unused modifier is
  415. // unnecessary.
  416. static auto MarkPatternUnused(Context& context, SemIR::InstId inst_id) -> bool {
  417. bool found_name = false;
  418. llvm::SmallVector<SemIR::InstId> worklist;
  419. worklist.push_back(inst_id);
  420. while (!worklist.empty()) {
  421. auto current_inst_id = worklist.pop_back_val();
  422. auto inst = context.insts().Get(current_inst_id);
  423. CARBON_KIND_SWITCH(inst) {
  424. case SemIR::OutParamPattern::Kind:
  425. case SemIR::RefParamPattern::Kind:
  426. case SemIR::ValueParamPattern::Kind:
  427. case SemIR::VarParamPattern::Kind: {
  428. auto param = inst.As<SemIR::AnyParamPattern>();
  429. worklist.push_back(param.subpattern_id);
  430. break;
  431. }
  432. case SemIR::RefBindingPattern::Kind:
  433. case SemIR::SymbolicBindingPattern::Kind:
  434. case SemIR::ValueBindingPattern::Kind: {
  435. auto bind = inst.As<SemIR::AnyBindingPattern>();
  436. auto& name = context.entity_names().Get(bind.entity_name_id);
  437. name.is_unused = true;
  438. // We treat `_` as not marking the pattern as unused for the purpose of
  439. // deciding whether to issue a warning for `unused` on a pattern that
  440. // doesn't contain any bindings. `_` is implicitly unused, so marking it
  441. // `unused` is redundant but harmless.
  442. if (name.name_id != SemIR::NameId::Underscore) {
  443. found_name = true;
  444. }
  445. break;
  446. }
  447. case CARBON_KIND(SemIR::TuplePattern tuple): {
  448. for (auto elem_id : context.inst_blocks().Get(tuple.elements_id)) {
  449. worklist.push_back(elem_id);
  450. }
  451. break;
  452. }
  453. case CARBON_KIND(SemIR::VarPattern var): {
  454. worklist.push_back(var.subpattern_id);
  455. break;
  456. }
  457. default:
  458. break;
  459. }
  460. }
  461. return found_name;
  462. }
  463. auto HandleParseNode(Context& context, Parse::UnusedPatternId node_id) -> bool {
  464. auto [child_node, child_inst_id] =
  465. context.node_stack().PopPatternWithNodeId();
  466. if (!MarkPatternUnused(context, child_inst_id)) {
  467. CARBON_DIAGNOSTIC(UnusedPatternNoBindings, Warning,
  468. "`unused` modifier on pattern without bindings");
  469. context.emitter().Emit(node_id, UnusedPatternNoBindings);
  470. }
  471. context.node_stack().Push(node_id, child_inst_id);
  472. return true;
  473. }
  474. } // namespace Carbon::Check