Match min and max functions using DefId

Closes #446.
This commit is contained in:
Andrew Paseltiner 2015-11-11 11:08:33 -05:00
parent c8509a0799
commit 91763d7725
2 changed files with 13 additions and 7 deletions

View file

@ -5,7 +5,7 @@ use std::cmp::PartialOrd;
use std::cmp::Ordering::*;
use consts::{Constant, constant_simple};
use utils::{match_path, span_lint};
use utils::{match_def_path, span_lint};
use self::MinMax::{Min, Max};
declare_lint!(pub MIN_MAX, Warn,
@ -23,8 +23,8 @@ impl LintPass for MinMaxPass {
impl LateLintPass for MinMaxPass {
fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
if let Some((outer_max, outer_c, oe)) = min_max(expr) {
if let Some((inner_max, inner_c, _)) = min_max(oe) {
if let Some((outer_max, outer_c, oe)) = min_max(cx, expr) {
if let Some((inner_max, inner_c, _)) = min_max(cx, oe) {
if outer_max == inner_max { return; }
match (outer_max, outer_c.partial_cmp(&inner_c)) {
(_, None) | (Max, Some(Less)) | (Min, Some(Greater)) => (),
@ -44,13 +44,15 @@ enum MinMax {
Max,
}
fn min_max(expr: &Expr) -> Option<(MinMax, Constant, &Expr)> {
fn min_max<'a>(cx: &LateContext, expr: &'a Expr) -> Option<(MinMax, Constant, &'a Expr)> {
if let ExprCall(ref path, ref args) = expr.node {
if let ExprPath(None, ref path) = path.node {
if match_path(path, &["std", "cmp", "min"]) {
if let ExprPath(None, _) = path.node {
let def_id = cx.tcx.def_map.borrow()[&path.id].def_id();
if match_def_path(cx, def_id, &["core", "cmp", "min"]) {
fetch_const(args, Min)
} else {
if match_path(path, &["std", "cmp", "max"]) {
if match_def_path(cx, def_id, &["core", "cmp", "max"]) {
fetch_const(args, Max)
} else {
None

View file

@ -4,6 +4,8 @@
#![deny(clippy)]
use std::cmp::{min, max};
use std::cmp::min as my_min;
use std::cmp::max as my_max;
const LARGE : usize = 3;
@ -15,6 +17,8 @@ fn main() {
max(min(x, 1), 3); //~ERROR this min/max combination leads to constant result
max(3, min(x, 1)); //~ERROR this min/max combination leads to constant result
my_max(3, my_min(x, 1)); //~ERROR this min/max combination leads to constant result
min(3, max(1, x)); // ok, could be 1, 2 or 3 depending on x
min(1, max(LARGE, x)); // no error, we don't lookup consts here