]> git.lizzy.rs Git - rust.git/blob - src/utils.rs
Remove * dep
[rust.git] / src / utils.rs
1 use rustc::lint::*;
2 use rustc_front::hir::*;
3 use reexport::*;
4 use syntax::codemap::{ExpnInfo, Span, ExpnFormat};
5 use rustc::front::map::Node::*;
6 use rustc::middle::def_id::DefId;
7 use rustc::middle::ty;
8 use std::borrow::Cow;
9 use syntax::ast::Lit_::*;
10 use syntax::ast;
11 use syntax::ptr::P;
12
13 use rustc::session::Session;
14 use std::str::FromStr;
15
16 pub type MethodArgs = HirVec<P<Expr>>;
17
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"];
28
29 /// Produce a nested chain of if-lets and ifs from the patterns:
30 ///
31 ///     if_let_chain! {
32 ///         [
33 ///             let Some(y) = x,
34 ///             y.len() == 2,
35 ///             let Some(z) = y,
36 ///         ],
37 ///         {
38 ///             block
39 ///         }
40 ///     }
41 ///
42 /// becomes
43 ///
44 ///     if let Some(y) = x {
45 ///         if y.len() == 2 {
46 ///             if let Some(z) = y {
47 ///                 block
48 ///             }
49 ///         }
50 ///     }
51 #[macro_export]
52 macro_rules! if_let_chain {
53     ([let $pat:pat = $expr:expr, $($tt:tt)+], $block:block) => {
54         if let $pat = $expr {
55            if_let_chain!{ [$($tt)+], $block }
56         }
57     };
58     ([let $pat:pat = $expr:expr], $block:block) => {
59         if let $pat = $expr {
60            $block
61         }
62     };
63     ([$expr:expr, $($tt:tt)+], $block:block) => {
64         if $expr {
65            if_let_chain!{ [$($tt)+], $block }
66         }
67     };
68     ([$expr:expr], $block:block) => {
69         if $expr {
70            $block
71         }
72     };
73 }
74
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())
79 }
80
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
91                     return true;
92             }
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"
98                     // = compiler plugin
99                     !code.starts_with("macro_rules")
100                 )
101             })
102         })
103     }
104
105     cx.sess().codemap().with_expn_info(span.expn_id,
106             |info| in_macro_ext(cx, info))
107 }
108
109 /// check if a DefId's path matches the given absolute type path
110 /// usage e.g. with
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))
115 }
116
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 {
119     match ty.sty {
120         ty::TyEnum(ref adt, _) | ty::TyStruct(ref adt, _) => {
121             match_def_path(cx, adt.did, path)
122         }
123         _ => {
124             false
125         }
126     }
127 }
128
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);
132
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)
138     } else {
139         false
140     }
141 }
142
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)
151     } else {
152         false
153     }
154 }
155
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)
161 }
162
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)
168 }
169
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
181             }
182             else {
183                 return None;
184             }
185         }
186         else {
187             return None;
188         }
189     }
190     matched.reverse(); // reverse `matched`, so that it is in the same order as `methods`
191     Some(matched)
192 }
193
194
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, .. })) => {
202             Some(*name)
203         }
204         _ => None,
205     }
206 }
207
208 /// checks if a `let` decl is from a for loop desugaring
209 pub fn is_from_for_desugar(decl: &Decl) -> bool {
210     if_let_chain! {
211         [
212             let DeclLocal(ref loc) = decl.node,
213             let Some(ref expr) = loc.init,
214             let ExprMatch(_, _, MatchSource::ForLoopDesugar) = expr.node
215         ],
216         { return true; }
217     };
218     false
219 }
220
221
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))
226 }
227
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()
231 }
232
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)
240 }
241
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))
253     } else {
254         Cow::Owned(format!("{{\n{};\n{}\n}}", code, string))
255     }
256 }
257
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, ' ')
264 }
265
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)
272                                } else {None}})
273              .min().unwrap_or(0);
274     if x > 0 {
275         Cow::Owned(s.lines().enumerate().map(|(i,l)| if (ignore_first && i == 0) ||
276                                                          l.len() == 0 {
277                                                         l
278                                                      } else {
279                                                         l.split_at(x).1
280                                                      }).collect::<Vec<_>>()
281                                        .join("\n"))
282     } else {
283         s
284     }
285 }
286
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 } )
295 }
296
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 {
302         match node {
303             NodeBlock(ref block) => Some(block),
304             NodeItem(&Item{ node: ItemFn(_, _, _, _, _, ref block), .. }) => Some(block),
305             _ => None
306         }
307     } else { None }
308 }
309
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#{}",
316             lint.name_lower()))
317     }
318 }
319
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#{}",
329             lint.name_lower()))
330     }
331 }
332
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()))
340     }
341 }
342
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)
349         } else {
350             cx.sess().span_note(note_span, note)
351         }
352         cx.sess().fileline_help(span, &format!("for further information visit \
353             https://github.com/Manishearth/rust-clippy/wiki#{}",
354             lint.name_lower()))
355     }
356 }
357
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 {
362         f();
363         cx.sess().fileline_help(sp, &format!("for further information visit \
364             https://github.com/Manishearth/rust-clippy/wiki#{}",
365             lint.name_lower()))
366     }
367 }
368
369 /// return the base type for references and raw pointers
370 pub fn walk_ptrs_ty(ty: ty::Ty) -> ty::Ty {
371     match ty.sty {
372         ty::TyRef(_, ref tm) | ty::TyRawPtr(ref tm) => walk_ptrs_ty(tm.ty),
373         _ => ty
374     }
375 }
376
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) {
380         match ty.sty {
381             ty::TyRef(_, ref tm) | ty::TyRawPtr(ref tm) => inner(tm.ty, depth + 1),
382             _ => (ty, depth)
383         }
384     }
385     inner(ty, 0)
386 }
387
388 pub fn is_integer_literal(expr: &Expr, value: u64) -> bool
389 {
390     // FIXME: use constant folding
391     if let ExprLit(ref spanned) = expr.node {
392         if let LitInt(v, _) = spanned.node {
393             return v == value;
394         }
395     }
396     false
397 }
398
399 pub fn is_adjusted(cx: &LateContext, e: &Expr) -> bool {
400     cx.tcx.tables.borrow().adjustments.get(&e.id).is_some()
401 }
402
403 pub struct LimitStack {
404     stack: Vec<u64>,
405 }
406
407 impl Drop for LimitStack {
408     fn drop(&mut self) {
409         assert_eq!(self.stack.len(), 1);
410     }
411 }
412
413 impl LimitStack {
414     pub fn new(limit: u64) -> LimitStack {
415         LimitStack {
416             stack: vec![limit],
417         }
418     }
419     pub fn limit(&self) -> u64 {
420         *self.stack.last().expect("there should always be a value in the stack")
421     }
422     pub fn push_attrs(&mut self, sess: &Session, attrs: &[ast::Attribute], name: &'static str) {
423         let stack = &mut self.stack;
424         parse_attrs(
425             sess,
426             attrs,
427             name,
428             |val| stack.push(val),
429         );
430     }
431     pub fn pop_attrs(&mut self, sess: &Session, attrs: &[ast::Attribute], name: &'static str) {
432         let stack = &mut self.stack;
433         parse_attrs(
434             sess,
435             attrs,
436             name,
437             |val| assert_eq!(stack.pop(), Some(val)),
438         );
439     }
440 }
441
442 fn parse_attrs<F: FnMut(u64)>(sess: &Session, attrs: &[ast::Attribute], name: &'static str, mut f: F) {
443     for attr in attrs {
444         let attr = &attr.node;
445         if attr.is_sugared_doc { continue; }
446         if let ast::MetaNameValue(ref key, ref value) = attr.value.node {
447             if *key == name {
448                 if let LitStr(ref s, _) = value.node {
449                     if let Ok(value) = FromStr::from_str(s) {
450                         f(value)
451                     } else {
452                         sess.span_err(value.span, "not a number");
453                     }
454                 } else {
455                     unreachable!()
456                 }
457             }
458         }
459     }
460 }