Skip to content

Commit f44794f

Browse files
committed
Only allow negation on literals in patterns if it's on integers or floats
1 parent 24d94b2 commit f44794f

File tree

3 files changed

+38
-4
lines changed

3 files changed

+38
-4
lines changed

compiler/rustc_hir_typeck/src/pat.rs

+10-2
Original file line numberDiff line numberDiff line change
@@ -570,8 +570,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
570570

571571
fn check_pat_expr_unadjusted(&self, lt: &'tcx hir::PatExpr<'tcx>) -> Ty<'tcx> {
572572
let ty = match &lt.kind {
573-
rustc_hir::PatExprKind::Lit { lit, .. } => {
574-
self.check_expr_lit(lit, Expectation::NoExpectation)
573+
rustc_hir::PatExprKind::Lit { lit, negated } => {
574+
let ty = self.check_expr_lit(lit, Expectation::NoExpectation);
575+
if *negated {
576+
self.register_bound(
577+
ty,
578+
self.tcx.require_lang_item(LangItem::Neg, Some(lt.span)),
579+
ObligationCause::dummy_with_span(lt.span),
580+
);
581+
}
582+
ty
575583
}
576584
rustc_hir::PatExprKind::ConstBlock(c) => {
577585
self.check_expr_const_block(c, Expectation::NoExpectation)

tests/ui/type/pattern_types/signed_ranges.rs

+2
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,13 @@ type SignedChar = pattern_type!(char is -'A'..);
1212
fn main() {
1313
match 42_u8 {
1414
-10..253 => {}
15+
//~^ ERROR `u8: Neg` is not satisfied
1516
_ => {}
1617
}
1718

1819
match 'A' {
1920
-'\0'..'a' => {}
21+
//~^ ERROR `char: Neg` is not satisfied
2022
_ => {}
2123
}
2224
}

tests/ui/type/pattern_types/signed_ranges.stderr

+26-2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,26 @@
1+
error[E0277]: the trait bound `u8: Neg` is not satisfied
2+
--> $DIR/signed_ranges.rs:14:9
3+
|
4+
LL | -10..253 => {}
5+
| ^^^ the trait `Neg` is not implemented for `u8`
6+
|
7+
= help: the following other types implement trait `Neg`:
8+
&f128
9+
&f16
10+
&f32
11+
&f64
12+
&i128
13+
&i16
14+
&i32
15+
&i64
16+
and 12 others
17+
18+
error[E0277]: the trait bound `char: Neg` is not satisfied
19+
--> $DIR/signed_ranges.rs:20:9
20+
|
21+
LL | -'\0'..'a' => {}
22+
| ^^^^^ the trait `Neg` is not implemented for `char`
23+
124
error[E0600]: cannot apply unary operator `-` to type `u32`
225
--> $DIR/signed_ranges.rs:6:34
326
|
@@ -12,6 +35,7 @@ error[E0600]: cannot apply unary operator `-` to type `char`
1235
LL | type SignedChar = pattern_type!(char is -'A'..);
1336
| ^^^^ cannot apply unary operator `-`
1437

15-
error: aborting due to 2 previous errors
38+
error: aborting due to 4 previous errors
1639

17-
For more information about this error, try `rustc --explain E0600`.
40+
Some errors have detailed explanations: E0277, E0600.
41+
For more information about an error, try `rustc --explain E0277`.

0 commit comments

Comments
 (0)