Skip to content

Commit 5d6e4a6

Browse files
authored
Merge pull request #1068 from AtheMathmo/useless_vec-constant-expr
Check for constant expression in useless_vec lint
2 parents 4e9ca25 + 10b545e commit 5d6e4a6

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

clippy_lints/src/vec.rs

+9-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
use rustc::lint::*;
22
use rustc::ty::TypeVariants;
33
use rustc::hir::*;
4+
use rustc_const_eval::EvalHint::ExprTypeChecked;
5+
use rustc_const_eval::eval_const_expr_partial;
46
use syntax::codemap::Span;
57
use syntax::ptr::P;
68
use utils::{is_expn_of, match_path, paths, recover_for_loop, snippet, span_lint_and_then};
@@ -52,9 +54,15 @@ impl LateLintPass for Pass {
5254

5355
fn check_vec_macro(cx: &LateContext, vec: &Expr, span: Span) {
5456
if let Some(vec_args) = unexpand(cx, vec) {
57+
5558
let snippet = match vec_args {
5659
Args::Repeat(elem, len) => {
57-
format!("&[{}; {}]", snippet(cx, elem.span, "elem"), snippet(cx, len.span, "len")).into()
60+
// Check that the length is a constant expression
61+
if eval_const_expr_partial(cx.tcx, len, ExprTypeChecked, None).is_ok() {
62+
format!("&[{}; {}]", snippet(cx, elem.span, "elem"), snippet(cx, len.span, "len")).into()
63+
} else {
64+
return;
65+
}
5866
}
5967
Args::Vec(args) => {
6068
if let Some(last) = args.iter().last() {

tests/compile-fail/vec.rs

+16
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,16 @@ fn on_slice(_: &[u8]) {}
77
#[allow(ptr_arg)]
88
fn on_vec(_: &Vec<u8>) {}
99

10+
struct Line {
11+
length: usize,
12+
}
13+
14+
impl Line {
15+
fn length(&self) -> usize {
16+
self.length
17+
}
18+
}
19+
1020
fn main() {
1121
on_slice(&vec![]);
1222
//~^ ERROR useless use of `vec!`
@@ -42,6 +52,12 @@ fn main() {
4252
on_vec(&vec![1, 2]);
4353
on_vec(&vec![1; 2]);
4454

55+
// Now with non-constant expressions
56+
let line = Line { length: 2 };
57+
58+
on_slice(&vec![2; line.length]);
59+
on_slice(&vec![2; line.length()]);
60+
4561
for a in vec![1, 2, 3] {
4662
//~^ ERROR useless use of `vec!`
4763
//~| HELP you can use

0 commit comments

Comments
 (0)