2 use rustc_front::hir::*;
4 use syntax::codemap::{ExpnInfo, Span, ExpnFormat};
5 use rustc::front::map::Node::*;
6 use rustc::middle::def_id::DefId;
9 use syntax::ast::Lit_::*;
13 use rustc::session::Session;
14 use std::str::FromStr;
16 pub type MethodArgs = HirVec<P<Expr>>;
18 // module DefPaths for certain structs/enums we check for
19 pub const OPTION_PATH: [&'static str; 3] = ["core", "option", "Option"];
20 pub const RESULT_PATH: [&'static str; 3] = ["core", "result", "Result"];
21 pub const STRING_PATH: [&'static str; 3] = ["collections", "string", "String"];
22 pub const VEC_PATH: [&'static str; 3] = ["collections", "vec", "Vec"];
23 pub const LL_PATH: [&'static str; 3] = ["collections", "linked_list", "LinkedList"];
24 pub const OPEN_OPTIONS_PATH: [&'static str; 3] = ["std", "fs", "OpenOptions"];
25 pub const MUTEX_PATH: [&'static str; 4] = ["std", "sync", "mutex", "Mutex"];
26 pub const CLONE_PATH: [&'static str; 2] = ["Clone", "clone"];
27 pub const BEGIN_UNWIND:[&'static str; 3] = ["std", "rt", "begin_unwind"];
29 /// Produce a nested chain of if-lets and ifs from the patterns:
44 /// if let Some(y) = x {
46 /// if let Some(z) = y {
52 macro_rules! if_let_chain {
53 ([let $pat:pat = $expr:expr, $($tt:tt)+], $block:block) => {
55 if_let_chain!{ [$($tt)+], $block }
58 ([let $pat:pat = $expr:expr], $block:block) => {
63 ([$expr:expr, $($tt:tt)+], $block:block) => {
65 if_let_chain!{ [$($tt)+], $block }
68 ([$expr:expr], $block:block) => {
75 /// returns true if this expn_info was expanded by any macro
76 pub fn in_macro<T: LintContext>(cx: &T, span: Span) -> bool {
77 cx.sess().codemap().with_expn_info(span.expn_id,
78 |info| info.is_some())
81 /// returns true if the macro that expanded the crate was outside of
82 /// the current crate or was a compiler plugin
83 pub fn in_external_macro<T: LintContext>(cx: &T, span: Span) -> bool {
84 /// invokes in_macro with the expansion info of the given span
85 /// slightly heavy, try to use this after other checks have already happened
86 fn in_macro_ext<T: LintContext>(cx: &T, opt_info: Option<&ExpnInfo>) -> bool {
87 // no ExpnInfo = no macro
88 opt_info.map_or(false, |info| {
89 if let ExpnFormat::MacroAttribute(..) = info.callee.format {
90 // these are all plugins
93 // no span for the callee = external macro
94 info.callee.span.map_or(true, |span| {
95 // no snippet = external macro or compiler-builtin expansion
96 cx.sess().codemap().span_to_snippet(span).ok().map_or(true, |code|
97 // macro doesn't start with "macro_rules"
99 !code.starts_with("macro_rules")
105 cx.sess().codemap().with_expn_info(span.expn_id,
106 |info| in_macro_ext(cx, info))
109 /// check if a DefId's path matches the given absolute type path
111 /// `match_def_path(cx, id, &["core", "option", "Option"])`
112 pub fn match_def_path(cx: &LateContext, def_id: DefId, path: &[&str]) -> bool {
113 cx.tcx.with_path(def_id, |iter| iter.zip(path)
114 .all(|(nm, p)| nm.name().as_str() == *p))
117 /// check if type is struct or enum type with given def path
118 pub fn match_type(cx: &LateContext, ty: ty::Ty, path: &[&str]) -> bool {
120 ty::TyEnum(ref adt, _) | ty::TyStruct(ref adt, _) => {
121 match_def_path(cx, adt.did, path)
129 /// check if method call given in "expr" belongs to given trait
130 pub fn match_impl_method(cx: &LateContext, expr: &Expr, path: &[&str]) -> bool {
131 let method_call = ty::MethodCall::expr(expr.id);
133 let trt_id = cx.tcx.tables
134 .borrow().method_map.get(&method_call)
135 .and_then(|callee| cx.tcx.impl_of_method(callee.def_id));
136 if let Some(trt_id) = trt_id {
137 match_def_path(cx, trt_id, path)
143 /// check if method call given in "expr" belongs to given trait
144 pub fn match_trait_method(cx: &LateContext, expr: &Expr, path: &[&str]) -> bool {
145 let method_call = ty::MethodCall::expr(expr.id);
146 let trt_id = cx.tcx.tables
147 .borrow().method_map.get(&method_call)
148 .and_then(|callee| cx.tcx.trait_of_item(callee.def_id));
149 if let Some(trt_id) = trt_id {
150 match_def_path(cx, trt_id, path)
156 /// match a Path against a slice of segment string literals, e.g.
157 /// `match_path(path, &["std", "rt", "begin_unwind"])`
158 pub fn match_path(path: &Path, segments: &[&str]) -> bool {
159 path.segments.iter().rev().zip(segments.iter().rev()).all(
160 |(a, b)| a.identifier.name.as_str() == *b)
163 /// match a Path against a slice of segment string literals, e.g.
164 /// `match_path(path, &["std", "rt", "begin_unwind"])`
165 pub fn match_path_ast(path: &ast::Path, segments: &[&str]) -> bool {
166 path.segments.iter().rev().zip(segments.iter().rev()).all(
167 |(a, b)| a.identifier.name.as_str() == *b)
170 /// match an Expr against a chain of methods, and return the matched Exprs. For example, if `expr`
171 /// represents the `.baz()` in `foo.bar().baz()`, `matched_method_chain(expr, &["bar", "baz"])`
172 /// will return a Vec containing the Exprs for `.bar()` and `.baz()`
173 pub fn method_chain_args<'a>(expr: &'a Expr, methods: &[&str]) -> Option<Vec<&'a MethodArgs>> {
174 let mut current = expr;
175 let mut matched = Vec::with_capacity(methods.len());
176 for method_name in methods.iter().rev() { // method chains are stored last -> first
177 if let ExprMethodCall(ref name, _, ref args) = current.node {
178 if name.node.as_str() == *method_name {
179 matched.push(args); // build up `matched` backwards
180 current = &args[0] // go to parent expression
190 matched.reverse(); // reverse `matched`, so that it is in the same order as `methods`
195 /// get the name of the item the expression is in, if available
196 pub fn get_item_name(cx: &LateContext, expr: &Expr) -> Option<Name> {
197 let parent_id = cx.tcx.map.get_parent(expr.id);
198 match cx.tcx.map.find(parent_id) {
199 Some(NodeItem(&Item{ ref name, .. })) |
200 Some(NodeTraitItem(&TraitItem{ ref name, .. })) |
201 Some(NodeImplItem(&ImplItem{ ref name, .. })) => {
208 /// checks if a `let` decl is from a for loop desugaring
209 pub fn is_from_for_desugar(decl: &Decl) -> bool {
212 let DeclLocal(ref loc) = decl.node,
213 let Some(ref expr) = loc.init,
214 let ExprMatch(_, _, MatchSource::ForLoopDesugar) = expr.node
222 /// convert a span to a code snippet if available, otherwise use default, e.g.
223 /// `snippet(cx, expr.span, "..")`
224 pub fn snippet<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
225 cx.sess().codemap().span_to_snippet(span).map(From::from).unwrap_or(Cow::Borrowed(default))
228 /// Converts a span to a code snippet. Returns None if not available.
229 pub fn snippet_opt<T: LintContext>(cx: &T, span: Span) -> Option<String> {
230 cx.sess().codemap().span_to_snippet(span).ok()
233 /// convert a span (from a block) to a code snippet if available, otherwise use default, e.g.
234 /// `snippet(cx, expr.span, "..")`
235 /// This trims the code of indentation, except for the first line
236 /// Use it for blocks or block-like things which need to be printed as such
237 pub fn snippet_block<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
238 let snip = snippet(cx, span, default);
239 trim_multiline(snip, true)
242 /// Like snippet_block, but add braces if the expr is not an ExprBlock
243 /// Also takes an Option<String> which can be put inside the braces
244 pub fn expr_block<'a, T: LintContext>(cx: &T, expr: &Expr,
245 option: Option<String>,
246 default: &'a str) -> Cow<'a, str> {
247 let code = snippet_block(cx, expr.span, default);
248 let string = option.map_or("".to_owned(), |s| s);
249 if let ExprBlock(_) = expr.node {
250 Cow::Owned(format!("{}{}", code, string))
251 } else if string.is_empty() {
252 Cow::Owned(format!("{{ {} }}", code))
254 Cow::Owned(format!("{{\n{};\n{}\n}}", code, string))
258 /// Trim indentation from a multiline string
259 /// with possibility of ignoring the first line
260 pub fn trim_multiline(s: Cow<str>, ignore_first: bool) -> Cow<str> {
261 let s_space = trim_multiline_inner(s, ignore_first, ' ');
262 let s_tab = trim_multiline_inner(s_space, ignore_first, '\t');
263 trim_multiline_inner(s_tab, ignore_first, ' ')
266 fn trim_multiline_inner(s: Cow<str>, ignore_first: bool, ch: char) -> Cow<str> {
267 let x = s.lines().skip(ignore_first as usize)
268 .filter_map(|l| { if l.len() > 0 { // ignore empty lines
269 Some(l.char_indices()
270 .find(|&(_,x)| x != ch)
271 .unwrap_or((l.len(), ch)).0)
275 Cow::Owned(s.lines().enumerate().map(|(i,l)| if (ignore_first && i == 0) ||
280 }).collect::<Vec<_>>()
287 /// get a parent expr if any – this is useful to constrain a lint
288 pub fn get_parent_expr<'c>(cx: &'c LateContext, e: &Expr) -> Option<&'c Expr> {
289 let map = &cx.tcx.map;
290 let node_id : NodeId = e.id;
291 let parent_id : NodeId = map.get_parent_node(node_id);
292 if node_id == parent_id { return None; }
293 map.find(parent_id).and_then(|node|
294 if let NodeExpr(parent) = node { Some(parent) } else { None } )
297 pub fn get_enclosing_block<'c>(cx: &'c LateContext, node: NodeId) -> Option<&'c Block> {
298 let map = &cx.tcx.map;
299 let enclosing_node = map.get_enclosing_scope(node)
300 .and_then(|enclosing_id| map.find(enclosing_id));
301 if let Some(node) = enclosing_node {
303 NodeBlock(ref block) => Some(block),
304 NodeItem(&Item{ node: ItemFn(_, _, _, _, _, ref block), .. }) => Some(block),
310 #[cfg(not(feature="structured_logging"))]
311 pub fn span_lint<T: LintContext>(cx: &T, lint: &'static Lint, sp: Span, msg: &str) {
312 cx.span_lint(lint, sp, msg);
313 if cx.current_level(lint) != Level::Allow {
314 cx.sess().fileline_help(sp, &format!("for further information visit \
315 https://github.com/Manishearth/rust-clippy/wiki#{}",
320 #[cfg(feature="structured_logging")]
321 pub fn span_lint<T: LintContext>(cx: &T, lint: &'static Lint, sp: Span, msg: &str) {
322 // lint.name / lint.desc is can give details of the lint
323 // cx.sess().codemap() has all these nice functions for line/column/snippet details
324 // http://doc.rust-lang.org/syntax/codemap/struct.CodeMap.html#method.span_to_string
325 cx.span_lint(lint, sp, msg);
326 if cx.current_level(lint) != Level::Allow {
327 cx.sess().fileline_help(sp, &format!("for further information visit \
328 https://github.com/Manishearth/rust-clippy/wiki#{}",
333 pub fn span_help_and_lint<T: LintContext>(cx: &T, lint: &'static Lint, span: Span,
334 msg: &str, help: &str) {
335 cx.span_lint(lint, span, msg);
336 if cx.current_level(lint) != Level::Allow {
337 cx.sess().fileline_help(span, &format!("{}\nfor further information \
338 visit https://github.com/Manishearth/rust-clippy/wiki#{}",
339 help, lint.name_lower()))
343 pub fn span_note_and_lint<T: LintContext>(cx: &T, lint: &'static Lint, span: Span,
344 msg: &str, note_span: Span, note: &str) {
345 cx.span_lint(lint, span, msg);
346 if cx.current_level(lint) != Level::Allow {
347 if note_span == span {
348 cx.sess().fileline_note(note_span, note)
350 cx.sess().span_note(note_span, note)
352 cx.sess().fileline_help(span, &format!("for further information visit \
353 https://github.com/Manishearth/rust-clippy/wiki#{}",
358 pub fn span_lint_and_then<T: LintContext, F>(cx: &T, lint: &'static Lint, sp: Span,
359 msg: &str, f: F) where F: Fn() {
360 cx.span_lint(lint, sp, msg);
361 if cx.current_level(lint) != Level::Allow {
363 cx.sess().fileline_help(sp, &format!("for further information visit \
364 https://github.com/Manishearth/rust-clippy/wiki#{}",
369 /// return the base type for references and raw pointers
370 pub fn walk_ptrs_ty(ty: ty::Ty) -> ty::Ty {
372 ty::TyRef(_, ref tm) | ty::TyRawPtr(ref tm) => walk_ptrs_ty(tm.ty),
377 /// return the base type for references and raw pointers, and count reference depth
378 pub fn walk_ptrs_ty_depth(ty: ty::Ty) -> (ty::Ty, usize) {
379 fn inner(ty: ty::Ty, depth: usize) -> (ty::Ty, usize) {
381 ty::TyRef(_, ref tm) | ty::TyRawPtr(ref tm) => inner(tm.ty, depth + 1),
388 pub fn is_integer_literal(expr: &Expr, value: u64) -> bool
390 // FIXME: use constant folding
391 if let ExprLit(ref spanned) = expr.node {
392 if let LitInt(v, _) = spanned.node {
399 pub fn is_adjusted(cx: &LateContext, e: &Expr) -> bool {
400 cx.tcx.tables.borrow().adjustments.get(&e.id).is_some()
403 pub struct LimitStack {
407 impl Drop for LimitStack {
409 assert_eq!(self.stack.len(), 1);
414 pub fn new(limit: u64) -> LimitStack {
419 pub fn limit(&self) -> u64 {
420 *self.stack.last().expect("there should always be a value in the stack")
422 pub fn push_attrs(&mut self, sess: &Session, attrs: &[ast::Attribute], name: &'static str) {
423 let stack = &mut self.stack;
428 |val| stack.push(val),
431 pub fn pop_attrs(&mut self, sess: &Session, attrs: &[ast::Attribute], name: &'static str) {
432 let stack = &mut self.stack;
437 |val| assert_eq!(stack.pop(), Some(val)),
442 fn parse_attrs<F: FnMut(u64)>(sess: &Session, attrs: &[ast::Attribute], name: &'static str, mut f: F) {
444 let attr = &attr.node;
445 if attr.is_sugared_doc { continue; }
446 if let ast::MetaNameValue(ref key, ref value) = attr.value.node {
448 if let LitStr(ref s, _) = value.node {
449 if let Ok(value) = FromStr::from_str(s) {
452 sess.span_err(value.span, "not a number");