handle_binding_pattern.cpp 25 KB

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