Skip to content

Commit

Permalink
Add check for missing fields in enum variant pattern
Browse files Browse the repository at this point in the history
  • Loading branch information
estebank committed Jan 8, 2025
1 parent 5f04f98 commit d44f021
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 4 deletions.
2 changes: 1 addition & 1 deletion compiler/rustc_resolve/src/late/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1130,7 +1130,7 @@ impl<'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
let None = following_seg else { return };
for rib in self.ribs[ValueNS].iter().rev() {
for (def_id, spans) in &rib.patterns_with_skipped_bindings {
if let DefKind::Struct = self.r.tcx.def_kind(*def_id)
if let DefKind::Struct | DefKind::Variant = self.r.tcx.def_kind(*def_id)
&& let Some(fields) = self.r.field_idents(*def_id)
{
for field in fields {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ struct Website {
title: Option<String>,
}

enum Foo {
Bar { a: i32 },
}

fn main() {
let website = Website {
url: "http://www.example.com".into(),
Expand All @@ -18,4 +22,9 @@ fn main() {
println!("[{}]({})", title, url); //~ ERROR cannot find value `title` in this scope
//~^ NOTE not found in this scope
}

let x = Foo::Bar { a: 1 };
if let Foo::Bar { .. } = x { //~ NOTE this pattern
println!("{a}"); //~ ERROR cannot find value `a` in this scope
}
}
Original file line number Diff line number Diff line change
@@ -1,19 +1,27 @@
error: expected `,`
--> $DIR/struct-pattern-with-missing-fields-resolve-error.rs:12:31
--> $DIR/struct-pattern-with-missing-fields-resolve-error.rs:16:31
|
LL | if let Website { url, Some(title) } = website {
| ------- ^
| |
| while parsing the fields for this pattern

error[E0425]: cannot find value `title` in this scope
--> $DIR/struct-pattern-with-missing-fields-resolve-error.rs:18:30
--> $DIR/struct-pattern-with-missing-fields-resolve-error.rs:22:30
|
LL | if let Website { url, .. } = website {
| ------------------- this pattern doesn't include `title`, which is available in `Website`
LL | println!("[{}]({})", title, url);
| ^^^^^ not found in this scope

error: aborting due to 2 previous errors
error[E0425]: cannot find value `a` in this scope
--> $DIR/struct-pattern-with-missing-fields-resolve-error.rs:28:20
|
LL | if let Foo::Bar { .. } = x {
| --------------- this pattern doesn't include `a`, which is available in `Bar`
LL | println!("{a}");
| ^ help: a local variable with a similar name exists: `x`

error: aborting due to 3 previous errors

For more information about this error, try `rustc --explain E0425`.

0 comments on commit d44f021

Please sign in to comment.