Skip to content

Commit 5c729c0

Browse files
committed
Check for comparisons to NaN in patterns
For every pattern that refers to a static value, evaluate it and emit a warning if it is a NaN. Fixes #6804
1 parent 766eb95 commit 5c729c0

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

src/librustc/middle/check_match.rs

+17-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111

1212
use middle::const_eval::{compare_const_vals, lookup_const_by_id};
13-
use middle::const_eval::{eval_const_expr, const_val, const_bool};
13+
use middle::const_eval::{eval_const_expr, const_val, const_bool, const_float};
1414
use middle::pat_util::*;
1515
use middle::ty::*;
1616
use middle::ty;
@@ -102,6 +102,22 @@ pub fn check_arms(cx: &MatchCheckCtxt, arms: &[arm]) {
102102
let mut seen = ~[];
103103
for arms.iter().advance |arm| {
104104
for arm.pats.iter().advance |pat| {
105+
106+
// Check that we do not match against a static NaN (#6804)
107+
match cx.tcx.def_map.find(&pat.id) {
108+
Some(&def_static(did, false)) => {
109+
let const_expr = lookup_const_by_id(cx.tcx, did).get();
110+
match eval_const_expr(cx.tcx, const_expr) {
111+
const_float(f) if f.is_NaN() => {
112+
let msg = "unmatchable NaN in pattern, use is_NaN() in a guard instead";
113+
cx.tcx.sess.span_warn(pat.span, msg);
114+
}
115+
_ => {}
116+
}
117+
}
118+
_ => {}
119+
}
120+
105121
let v = ~[*pat];
106122
match is_useful(cx, &seen, v) {
107123
not_useful => {

src/test/compile-fail/issue-6804.rs

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
// Matching against NaN should result in a warning
2+
3+
use std::float::NaN;
4+
5+
fn main() {
6+
let x = NaN;
7+
match x {
8+
NaN => {},
9+
_ => {},
10+
};
11+
//~^^^ WARNING unmatchable NaN in pattern, use is_NaN() in a guard instead
12+
}
13+
14+
// At least one error is needed so that compilation fails
15+
#[static_assert]
16+
static b: bool = false; //~ ERROR static assertion failed

0 commit comments

Comments
 (0)