handle_binding_pattern.cpp 24 KB

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