This commit is contained in:
Manish Goregaokar 2014-11-19 14:27:34 +05:30
parent 6db0039e90
commit 92f13d8231
3 changed files with 92 additions and 3 deletions

12
examples/boxvec.rs Normal file
View file

@ -0,0 +1,12 @@
#![feature(phase)]
#[phase(plugin)]
extern crate rust_clippy;
pub fn test(foo: Box<Vec<uint>>) {
println!("{}", foo)
}
fn main(){
test(box Vec::new());
}

View file

@ -1,3 +1,21 @@
#[test]
fn it_works() {
}
#![feature(globs, phase, plugin_registrar)]
#[phase(plugin,link)]
extern crate syntax;
#[phase(plugin, link)]
extern crate rustc;
use rustc::plugin::Registry;
use rustc::lint::LintPassObject;
pub mod types;
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
//reg.register_syntax_extension(intern("jstraceable"), base::ItemDecorator(box expand_jstraceable));
//reg.register_macro("factorial", expand)
reg.register_lint_pass(box types::TypePass as LintPassObject);
}

59
src/types.rs Normal file
View file

@ -0,0 +1,59 @@
use syntax::ptr::P;
use syntax::ast;
use syntax::ast::*;
use rustc::lint::{Context, LintPass, LintArray, Lint, Level};
use syntax::codemap::Span;
pub struct TypePass;
declare_lint!(CLIPPY_BOX_VEC, Warn,
"Warn on usage of Box<Vec<T>>")
pub fn match_ty_unwrap<'a>(ty: &'a Ty, segments: &[&str]) -> Option<&'a [P<Ty>]> {
match ty.node {
TyPath(Path {segments: ref seg, ..}, _, _) => {
// So ast::Path isn't the full path, just the tokens that were provided.
// I could muck around with the maps and find the full path
// however the more efficient way is to simply reverse the iterators and zip them
// which will compare them in reverse until one of them runs out of segments
if seg.iter().rev().zip(segments.iter().rev()).all(|(a,b)| a.identifier.as_str() == *b) {
match seg.as_slice().last() {
Some(&PathSegment {parameters: AngleBracketedParameters(ref a), ..}) => {
Some(a.types.as_slice())
}
_ => None
}
} else {
None
}
},
_ => None
}
}
fn span_note_and_lint(cx: &Context, lint: &'static Lint, span: Span, msg: &str, note: &str) {
cx.span_lint(lint, span, msg);
if cx.current_level(lint) != Level::Allow {
cx.sess().span_note(span, note);
}
}
impl LintPass for TypePass {
fn get_lints(&self) -> LintArray {
lint_array!(CLIPPY_BOX_VEC)
}
fn check_ty(&mut self, cx: &Context, ty: &ast::Ty) {
match_ty_unwrap(ty, &["std", "boxed", "Box"]).and_then(|t| t.head())
.map(|t| match_ty_unwrap(&**t, &["std", "vec", "Vec"]))
.map(|_| {
span_note_and_lint(cx, CLIPPY_BOX_VEC, ty.span,
"Detected Box<Vec<T>>. Did you mean to use Vec<T>?",
"Vec<T> is already on the heap, Box<Vec<T>> makes an extra allocation");
});
}
}