handle_binding_pattern.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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_diagnoser = [&] {
  148. CARBON_DIAGNOSTIC(AbstractTypeInVarPattern, Error,
  149. "binding pattern has abstract type {0} in `var` "
  150. "pattern",
  151. SemIR::TypeId);
  152. return context.emitter().Build(type_node, AbstractTypeInVarPattern,
  153. cast_type_id);
  154. };
  155. // A `self` binding can only appear in an implicit parameter list.
  156. if (name_id == SemIR::NameId::SelfValue &&
  157. !context.node_stack().PeekIs(Parse::NodeKind::ImplicitParamListStart)) {
  158. CARBON_DIAGNOSTIC(
  159. SelfOutsideImplicitParamList, Error,
  160. "`self` can only be declared in an implicit parameter list");
  161. context.emitter().Emit(node_id, SelfOutsideImplicitParamList);
  162. }
  163. if (node_kind == Parse::NodeKind::CompileTimeBindingPattern &&
  164. introducer.kind == Lex::TokenKind::Let) {
  165. // TODO: We should re-evaluate the contents of the eval block in a
  166. // synthesized specific to form these values, in order to propagate the
  167. // values.
  168. return context.TODO(node_id,
  169. "local `let :!` bindings are currently unsupported");
  170. }
  171. // Allocate an instruction of the appropriate kind, linked to the name for
  172. // error locations.
  173. switch (context.full_pattern_stack().CurrentKind()) {
  174. case FullPatternStack::Kind::ImplicitParamList:
  175. case FullPatternStack::Kind::ExplicitParamList: {
  176. if (!IsValidParamForIntroducer(context, node_id, name_id, introducer.kind,
  177. is_generic)) {
  178. if (name_id != SemIR::NameId::Underscore) {
  179. AddNameToLookup(context, name_id, SemIR::ErrorInst::InstId);
  180. }
  181. // Replace the parameter with `ErrorInst` so that we don't try
  182. // constructing a generic based on it.
  183. context.node_stack().Push(node_id, SemIR::ErrorInst::InstId);
  184. break;
  185. }
  186. // Using `AsConcreteType` here causes `fn F[var self: Self]();`
  187. // to fail since `Self` is an incomplete type.
  188. if (node_kind == Parse::NodeKind::VarBindingPattern) {
  189. auto [unqualified_type_id, qualifiers] =
  190. context.types().GetUnqualifiedTypeAndQualifiers(cast_type_id);
  191. if ((qualifiers & SemIR::TypeQualifiers::Partial) !=
  192. SemIR::TypeQualifiers::Partial &&
  193. context.types().Is<SemIR::ClassType>(unqualified_type_id)) {
  194. auto class_type =
  195. context.types().GetAs<SemIR::ClassType>(unqualified_type_id);
  196. auto& class_info = context.classes().Get(class_type.class_id);
  197. if (class_info.inheritance_kind ==
  198. SemIR::Class::InheritanceKind::Abstract) {
  199. auto builder = abstract_diagnoser();
  200. auto direct_use = true;
  201. NoteAbstractClass(context, class_type.class_id, direct_use,
  202. builder);
  203. builder.Emit();
  204. cast_type_id = SemIR::ErrorInst::TypeId;
  205. }
  206. }
  207. }
  208. auto result_inst_id = make_binding_pattern();
  209. // A binding pattern in a function signature is a `Call` parameter
  210. // unless it's nested inside a `var` pattern (because then the
  211. // enclosing `var` pattern is), or it's a compile-time binding pattern
  212. // (because then it's not passed to the `Call` inst).
  213. if (node_kind == Parse::NodeKind::LetBindingPattern) {
  214. auto type_id = context.insts().GetAttachedType(result_inst_id);
  215. if (is_ref) {
  216. result_inst_id = AddPatternInst<SemIR::RefParamPattern>(
  217. context, node_id,
  218. {.type_id = type_id,
  219. .subpattern_id = result_inst_id,
  220. .index = context.full_pattern_stack().NextCallParamIndex()});
  221. } else {
  222. result_inst_id = AddPatternInst<SemIR::ValueParamPattern>(
  223. context, node_id,
  224. {.type_id = type_id,
  225. .subpattern_id = result_inst_id,
  226. .index = context.full_pattern_stack().NextCallParamIndex()});
  227. }
  228. }
  229. context.node_stack().Push(node_id, result_inst_id);
  230. break;
  231. }
  232. case FullPatternStack::Kind::NameBindingDecl: {
  233. auto incomplete_diagnoser = [&] {
  234. CARBON_DIAGNOSTIC(IncompleteTypeInBindingDecl, Error,
  235. "binding pattern has incomplete type {0} in name "
  236. "binding declaration",
  237. InstIdAsType);
  238. return context.emitter().Build(type_node, IncompleteTypeInBindingDecl,
  239. cast_type_inst_id);
  240. };
  241. if (node_kind == Parse::NodeKind::VarBindingPattern) {
  242. cast_type_id = AsConcreteType(context, cast_type_id, type_node,
  243. incomplete_diagnoser, abstract_diagnoser);
  244. } else {
  245. cast_type_id = AsCompleteType(context, cast_type_id, type_node,
  246. incomplete_diagnoser);
  247. }
  248. auto binding_pattern_id = make_binding_pattern();
  249. if (node_kind == Parse::NodeKind::VarBindingPattern) {
  250. CARBON_CHECK(!is_generic);
  251. if (introducer.modifier_set.HasAnyOf(KeywordModifierSet::Returned)) {
  252. // TODO: Should we check this for the `var` as a whole, rather than
  253. // for the name binding?
  254. auto bind_id = context.bind_name_map()
  255. .Lookup(binding_pattern_id)
  256. .value()
  257. .bind_name_id;
  258. RegisterReturnedVar(context,
  259. introducer.modifier_node_id(ModifierOrder::Decl),
  260. type_node, cast_type_id, bind_id, name_id);
  261. }
  262. }
  263. context.node_stack().Push(node_id, binding_pattern_id);
  264. break;
  265. }
  266. }
  267. return true;
  268. }
  269. auto HandleParseNode(Context& context, Parse::LetBindingPatternId node_id)
  270. -> bool {
  271. return HandleAnyBindingPattern(context, node_id,
  272. Parse::NodeKind::LetBindingPattern);
  273. }
  274. auto HandleParseNode(Context& context, Parse::VarBindingPatternId node_id)
  275. -> bool {
  276. return HandleAnyBindingPattern(context, node_id,
  277. Parse::NodeKind::VarBindingPattern);
  278. }
  279. auto HandleParseNode(Context& context, Parse::FormBindingPatternId node_id)
  280. -> bool {
  281. return context.TODO(node_id, "Implement :? support");
  282. }
  283. auto HandleParseNode(Context& context,
  284. Parse::CompileTimeBindingPatternStartId /*node_id*/)
  285. -> bool {
  286. // Make a scope to contain the `.Self` facet value for use in the type of the
  287. // compile time binding. This is popped when handling the
  288. // CompileTimeBindingPatternId.
  289. context.scope_stack().PushForSameRegion();
  290. // The `.Self` must have a type of `FacetType`, so that it gets wrapped in
  291. // `FacetAccessType` when used in a type position, such as in `U:! I(.Self)`.
  292. // This allows substitution with other facet values without requiring an
  293. // additional `FacetAccessType` to be inserted.
  294. auto type_id = GetEmptyFacetType(context);
  295. MakePeriodSelfFacetValue(context, type_id);
  296. return true;
  297. }
  298. auto HandleParseNode(Context& context,
  299. Parse::CompileTimeBindingPatternId node_id) -> bool {
  300. // Pop the `.Self` facet value name introduced by the
  301. // CompileTimeBindingPatternStart.
  302. context.scope_stack().Pop(/*check_unused=*/true);
  303. auto node_kind = Parse::NodeKind::CompileTimeBindingPattern;
  304. const DeclIntroducerState& introducer =
  305. context.decl_introducer_state_stack().innermost();
  306. if (introducer.kind == 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 a function decl.
  311. // We don't need to check if the scope is an interface here as this is
  312. // already caught in the parse phase by the separated associated constant
  313. // logic.
  314. auto scope_inst_id = context.scope_stack().PeekInstId();
  315. if (scope_inst_id.has_value()) {
  316. auto scope_inst = context.insts().Get(scope_inst_id);
  317. if (!scope_inst.Is<SemIR::FunctionDecl>()) {
  318. context.TODO(
  319. node_id,
  320. "`let` compile time binding outside function or interface");
  321. node_kind = Parse::NodeKind::LetBindingPattern;
  322. }
  323. }
  324. }
  325. return HandleAnyBindingPattern(context, node_id, node_kind);
  326. }
  327. auto HandleParseNode(Context& context,
  328. Parse::AssociatedConstantNameAndTypeId node_id) -> bool {
  329. auto [type_node, parsed_type_id] = context.node_stack().PopExprWithNodeId();
  330. auto [cast_type_inst_id, cast_type_id] =
  331. ExprAsType(context, type_node, parsed_type_id);
  332. EndSubpatternAsExpr(context, cast_type_inst_id);
  333. auto [name_node, name_id] = context.node_stack().PopNameWithNodeId();
  334. if (name_id == SemIR::NameId::Underscore) {
  335. // The action item here may be to document this as not allowed, and
  336. // add a proper diagnostic.
  337. context.TODO(node_id, "_ used as associated constant name");
  338. }
  339. SemIR::AssociatedConstantDecl assoc_const_decl = {
  340. .type_id = cast_type_id,
  341. .assoc_const_id = SemIR::AssociatedConstantId::None,
  342. .decl_block_id = SemIR::InstBlockId::None};
  343. auto decl_id =
  344. AddPlaceholderInstInNoBlock(context, node_id, assoc_const_decl);
  345. assoc_const_decl.assoc_const_id = context.associated_constants().Add(
  346. {.name_id = name_id,
  347. .parent_scope_id = context.scope_stack().PeekNameScopeId(),
  348. .decl_id = decl_id,
  349. .default_value_id = SemIR::InstId::None});
  350. ReplaceInstBeforeConstantUse(context, decl_id, assoc_const_decl);
  351. context.node_stack().Push(node_id, decl_id);
  352. return true;
  353. }
  354. auto HandleParseNode(Context& context, Parse::FieldNameAndTypeId node_id)
  355. -> bool {
  356. auto [type_node, parsed_type_id] = context.node_stack().PopExprWithNodeId();
  357. auto [cast_type_inst_id, cast_type_id] =
  358. ExprAsType(context, type_node, parsed_type_id);
  359. auto [name_node, name_id] = context.node_stack().PopNameWithNodeId();
  360. auto parent_class_decl =
  361. context.scope_stack().TryGetCurrentScopeAs<SemIR::ClassDecl>();
  362. CARBON_CHECK(parent_class_decl);
  363. cast_type_id = AsConcreteType(
  364. context, cast_type_id, type_node,
  365. [&] {
  366. CARBON_DIAGNOSTIC(IncompleteTypeInFieldDecl, Error,
  367. "field has incomplete type {0}", SemIR::TypeId);
  368. return context.emitter().Build(type_node, IncompleteTypeInFieldDecl,
  369. cast_type_id);
  370. },
  371. [&] {
  372. CARBON_DIAGNOSTIC(AbstractTypeInFieldDecl, Error,
  373. "field has abstract type {0}", SemIR::TypeId);
  374. return context.emitter().Build(type_node, AbstractTypeInFieldDecl,
  375. cast_type_id);
  376. });
  377. if (cast_type_id == SemIR::ErrorInst::TypeId) {
  378. cast_type_inst_id = SemIR::ErrorInst::TypeInstId;
  379. }
  380. auto& class_info = context.classes().Get(parent_class_decl->class_id);
  381. auto field_type_id = GetUnboundElementType(
  382. context, context.types().GetTypeInstId(class_info.self_type_id),
  383. cast_type_inst_id);
  384. auto field_id =
  385. AddInst<SemIR::FieldDecl>(context, node_id,
  386. {.type_id = field_type_id,
  387. .name_id = name_id,
  388. .index = SemIR::ElementIndex::None});
  389. context.field_decls_stack().AppendToTop(field_id);
  390. auto name_context =
  391. context.decl_name_stack().MakeUnqualifiedName(node_id, name_id);
  392. context.decl_name_stack().AddNameOrDiagnose(
  393. name_context, field_id,
  394. context.decl_introducer_state_stack()
  395. .innermost()
  396. .modifier_set.GetAccessKind());
  397. return true;
  398. }
  399. auto HandleParseNode(Context& context, Parse::RefBindingNameId node_id)
  400. -> bool {
  401. context.node_stack().Push(node_id);
  402. return true;
  403. }
  404. auto HandleParseNode(Context& context, Parse::TemplateBindingNameId node_id)
  405. -> bool {
  406. context.node_stack().Push(node_id);
  407. return true;
  408. }
  409. // Within a pattern with an unused modifier, sets the is_unused on all
  410. // entity names and also returns whether any names were found. The result
  411. // is needed to emit a diagnostic when the unused modifier is
  412. // unnecessary.
  413. static auto MarkPatternUnused(Context& context, SemIR::InstId inst_id) -> bool {
  414. bool found_name = false;
  415. llvm::SmallVector<SemIR::InstId> worklist;
  416. worklist.push_back(inst_id);
  417. while (!worklist.empty()) {
  418. auto current_inst_id = worklist.pop_back_val();
  419. auto inst = context.insts().Get(current_inst_id);
  420. CARBON_KIND_SWITCH(inst) {
  421. case SemIR::OutParamPattern::Kind:
  422. case SemIR::RefParamPattern::Kind:
  423. case SemIR::ValueParamPattern::Kind:
  424. case SemIR::VarParamPattern::Kind: {
  425. auto param = inst.As<SemIR::AnyParamPattern>();
  426. worklist.push_back(param.subpattern_id);
  427. break;
  428. }
  429. case SemIR::RefBindingPattern::Kind:
  430. case SemIR::SymbolicBindingPattern::Kind:
  431. case SemIR::ValueBindingPattern::Kind: {
  432. auto bind = inst.As<SemIR::AnyBindingPattern>();
  433. auto& name = context.entity_names().Get(bind.entity_name_id);
  434. name.is_unused = true;
  435. // We treat `_` as not marking the pattern as unused for the purpose of
  436. // deciding whether to issue a warning for `unused` on a pattern that
  437. // doesn't contain any bindings. `_` is implicitly unused, so marking it
  438. // `unused` is redundant but harmless.
  439. if (name.name_id != SemIR::NameId::Underscore) {
  440. found_name = true;
  441. }
  442. break;
  443. }
  444. case CARBON_KIND(SemIR::TuplePattern tuple): {
  445. for (auto elem_id : context.inst_blocks().Get(tuple.elements_id)) {
  446. worklist.push_back(elem_id);
  447. }
  448. break;
  449. }
  450. case CARBON_KIND(SemIR::VarPattern var): {
  451. worklist.push_back(var.subpattern_id);
  452. break;
  453. }
  454. default:
  455. break;
  456. }
  457. }
  458. return found_name;
  459. }
  460. auto HandleParseNode(Context& context, Parse::UnusedPatternId node_id) -> bool {
  461. auto [child_node, child_inst_id] =
  462. context.node_stack().PopPatternWithNodeId();
  463. if (!MarkPatternUnused(context, child_inst_id)) {
  464. CARBON_DIAGNOSTIC(UnusedPatternNoBindings, Warning,
  465. "`unused` modifier on pattern without bindings");
  466. context.emitter().Emit(node_id, UnusedPatternNoBindings);
  467. }
  468. context.node_stack().Push(node_id, child_inst_id);
  469. return true;
  470. }
  471. } // namespace Carbon::Check