]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/utils/mod.rs
Merge pull request #2112 from topecongiro/issue-2109
[rust.git] / clippy_lints / src / utils / mod.rs
1 use reexport::*;
2 use rustc::hir;
3 use rustc::hir::*;
4 use rustc::hir::def_id::{DefId, CRATE_DEF_INDEX};
5 use rustc::hir::def::Def;
6 use rustc::hir::intravisit::{NestedVisitorMap, Visitor};
7 use rustc::hir::map::Node;
8 use rustc::lint::{LateContext, Level, Lint, LintContext};
9 use rustc::session::Session;
10 use rustc::traits;
11 use rustc::ty::{self, Ty, TyCtxt};
12 use rustc::mir::transform::MirSource;
13 use rustc_errors;
14 use std::borrow::Cow;
15 use std::env;
16 use std::mem;
17 use std::str::FromStr;
18 use std::rc::Rc;
19 use syntax::ast::{self, LitKind};
20 use syntax::attr;
21 use syntax::codemap::{CompilerDesugaringKind, ExpnFormat, ExpnInfo, Span, DUMMY_SP};
22 use syntax::errors::DiagnosticBuilder;
23 use syntax::ptr::P;
24 use syntax::symbol::keywords;
25
26 pub mod comparisons;
27 pub mod conf;
28 pub mod constants;
29 mod hir_utils;
30 pub mod paths;
31 pub mod sugg;
32 pub mod inspector;
33 pub mod internal_lints;
34 pub mod author;
35 pub use self::hir_utils::{SpanlessEq, SpanlessHash};
36
37 pub type MethodArgs = HirVec<P<Expr>>;
38
39 /// Produce a nested chain of if-lets and ifs from the patterns:
40 ///
41 /// ```rust,ignore
42 /// if_let_chain! {[
43 ///     let Some(y) = x,
44 ///     y.len() == 2,
45 ///     let Some(z) = y,
46 /// ], {
47 ///     block
48 /// }}
49 /// ```
50 ///
51 /// becomes
52 ///
53 /// ```rust,ignore
54 /// if let Some(y) = x {
55 ///     if y.len() == 2 {
56 ///         if let Some(z) = y {
57 ///             block
58 ///         }
59 ///     }
60 /// }
61 /// ```
62 #[macro_export]
63 macro_rules! if_let_chain {
64     ([let $pat:pat = $expr:expr, $($tt:tt)+], $block:block) => {
65         if let $pat = $expr {
66            if_let_chain!{ [$($tt)+], $block }
67         }
68     };
69     ([let $pat:pat = $expr:expr], $block:block) => {
70         if let $pat = $expr {
71            $block
72         }
73     };
74     ([let $pat:pat = $expr:expr,], $block:block) => {
75         if let $pat = $expr {
76            $block
77         }
78     };
79     ([$expr:expr, $($tt:tt)+], $block:block) => {
80         if $expr {
81            if_let_chain!{ [$($tt)+], $block }
82         }
83     };
84     ([$expr:expr], $block:block) => {
85         if $expr {
86            $block
87         }
88     };
89     ([$expr:expr,], $block:block) => {
90         if $expr {
91            $block
92         }
93     };
94 }
95
96 pub mod higher;
97
98 /// Returns true if the two spans come from differing expansions (i.e. one is
99 /// from a macro and one
100 /// isn't).
101 pub fn differing_macro_contexts(lhs: Span, rhs: Span) -> bool {
102     rhs.ctxt() != lhs.ctxt()
103 }
104
105 pub fn in_constant(cx: &LateContext, id: NodeId) -> bool {
106     let parent_id = cx.tcx.hir.get_parent(id);
107     match MirSource::from_node(cx.tcx, parent_id) {
108         MirSource::GeneratorDrop(_) | MirSource::Fn(_) => false,
109         MirSource::Const(_) | MirSource::Static(..) | MirSource::Promoted(..) => true,
110     }
111 }
112
113 /// Returns true if this `expn_info` was expanded by any macro.
114 pub fn in_macro(span: Span) -> bool {
115     span.ctxt().outer().expn_info().map_or(false, |info| {
116         match info.callee.format {
117             // don't treat range expressions desugared to structs as "in_macro"
118             ExpnFormat::CompilerDesugaring(kind) => kind != CompilerDesugaringKind::DotFill,
119             _ => true,
120         }
121     })
122 }
123
124 /// Returns true if the macro that expanded the crate was outside of the
125 /// current crate or was a
126 /// compiler plugin.
127 pub fn in_external_macro<'a, T: LintContext<'a>>(cx: &T, span: Span) -> bool {
128     /// Invokes `in_macro` with the expansion info of the given span slightly
129     /// heavy, try to use
130     /// this after other checks have already happened.
131     fn in_macro_ext<'a, T: LintContext<'a>>(cx: &T, info: &ExpnInfo) -> bool {
132         // no ExpnInfo = no macro
133         if let ExpnFormat::MacroAttribute(..) = info.callee.format {
134             // these are all plugins
135             return true;
136         }
137         // no span for the callee = external macro
138         info.callee.span.map_or(true, |span| {
139             // no snippet = external macro or compiler-builtin expansion
140             cx.sess()
141                 .codemap()
142                 .span_to_snippet(span)
143                 .ok()
144                 .map_or(true, |code| !code.starts_with("macro_rules"))
145         })
146     }
147
148     span.ctxt()
149         .outer()
150         .expn_info()
151         .map_or(false, |info| in_macro_ext(cx, &info))
152 }
153
154 /// Check if a `DefId`'s path matches the given absolute type path usage.
155 ///
156 /// # Examples
157 /// ```rust,ignore
158 /// match_def_path(cx.tcx, id, &["core", "option", "Option"])
159 /// ```
160 ///
161 /// See also the `paths` module.
162 pub fn match_def_path(tcx: TyCtxt, def_id: DefId, path: &[&str]) -> bool {
163     use syntax::symbol;
164
165     struct AbsolutePathBuffer {
166         names: Vec<symbol::InternedString>,
167     }
168
169     impl ty::item_path::ItemPathBuffer for AbsolutePathBuffer {
170         fn root_mode(&self) -> &ty::item_path::RootMode {
171             const ABSOLUTE: &'static ty::item_path::RootMode = &ty::item_path::RootMode::Absolute;
172             ABSOLUTE
173         }
174
175         fn push(&mut self, text: &str) {
176             self.names.push(symbol::Symbol::intern(text).as_str());
177         }
178     }
179
180     let mut apb = AbsolutePathBuffer { names: vec![] };
181
182     tcx.push_item_path(&mut apb, def_id);
183
184     apb.names.len() == path.len() &&
185         apb.names
186             .into_iter()
187             .zip(path.iter())
188             .all(|(a, &b)| *a == *b)
189 }
190
191 /// Check if type is struct, enum or union type with given def path.
192 pub fn match_type(cx: &LateContext, ty: Ty, path: &[&str]) -> bool {
193     match ty.sty {
194         ty::TyAdt(adt, _) => match_def_path(cx.tcx, adt.did, path),
195         _ => false,
196     }
197 }
198
199 /// Check if the method call given in `expr` belongs to given type.
200 pub fn match_impl_method(cx: &LateContext, expr: &Expr, path: &[&str]) -> bool {
201     let method_call = cx.tables.type_dependent_defs()[expr.hir_id];
202     let trt_id = cx.tcx.impl_of_method(method_call.def_id());
203     if let Some(trt_id) = trt_id {
204         match_def_path(cx.tcx, trt_id, path)
205     } else {
206         false
207     }
208 }
209
210 /// Check if the method call given in `expr` belongs to given trait.
211 pub fn match_trait_method(cx: &LateContext, expr: &Expr, path: &[&str]) -> bool {
212     let method_call = cx.tables.type_dependent_defs()[expr.hir_id];
213     let trt_id = cx.tcx.trait_of_item(method_call.def_id());
214     if let Some(trt_id) = trt_id {
215         match_def_path(cx.tcx, trt_id, path)
216     } else {
217         false
218     }
219 }
220
221 /// Check if an expression references a variable of the given name.
222 pub fn match_var(expr: &Expr, var: Name) -> bool {
223     if let ExprPath(QPath::Resolved(None, ref path)) = expr.node {
224         if path.segments.len() == 1 && path.segments[0].name == var {
225             return true;
226         }
227     }
228     false
229 }
230
231
232 pub fn last_path_segment(path: &QPath) -> &PathSegment {
233     match *path {
234         QPath::Resolved(_, ref path) => path.segments
235             .last()
236             .expect("A path must have at least one segment"),
237         QPath::TypeRelative(_, ref seg) => seg,
238     }
239 }
240
241 pub fn single_segment_path(path: &QPath) -> Option<&PathSegment> {
242     match *path {
243         QPath::Resolved(_, ref path) if path.segments.len() == 1 => Some(&path.segments[0]),
244         QPath::Resolved(..) => None,
245         QPath::TypeRelative(_, ref seg) => Some(seg),
246     }
247 }
248
249 /// Match a `Path` against a slice of segment string literals.
250 ///
251 /// # Examples
252 /// ```rust,ignore
253 /// match_qpath(path, &["std", "rt", "begin_unwind"])
254 /// ```
255 pub fn match_qpath(path: &QPath, segments: &[&str]) -> bool {
256     match *path {
257         QPath::Resolved(_, ref path) => match_path(path, segments),
258         QPath::TypeRelative(ref ty, ref segment) => match ty.node {
259             TyPath(ref inner_path) => {
260                 !segments.is_empty() && match_qpath(inner_path, &segments[..(segments.len() - 1)]) &&
261                     segment.name == segments[segments.len() - 1]
262             },
263             _ => false,
264         },
265     }
266 }
267
268 pub fn match_path(path: &Path, segments: &[&str]) -> bool {
269     path.segments
270         .iter()
271         .rev()
272         .zip(segments.iter().rev())
273         .all(|(a, b)| a.name == *b)
274 }
275
276 /// Match a `Path` against a slice of segment string literals, e.g.
277 ///
278 /// # Examples
279 /// ```rust,ignore
280 /// match_qpath(path, &["std", "rt", "begin_unwind"])
281 /// ```
282 pub fn match_path_ast(path: &ast::Path, segments: &[&str]) -> bool {
283     path.segments
284         .iter()
285         .rev()
286         .zip(segments.iter().rev())
287         .all(|(a, b)| a.identifier.name == *b)
288 }
289
290 /// Get the definition associated to a path.
291 pub fn path_to_def(cx: &LateContext, path: &[&str]) -> Option<def::Def> {
292
293     let crates = cx.tcx.crates();
294     let krate = crates
295         .iter()
296         .find(|&&krate| cx.tcx.crate_name(krate) == path[0]);
297     if let Some(krate) = krate {
298         let krate = DefId {
299             krate: *krate,
300             index: CRATE_DEF_INDEX,
301         };
302         let mut items = cx.tcx.item_children(krate);
303         let mut path_it = path.iter().skip(1).peekable();
304
305         loop {
306             let segment = match path_it.next() {
307                 Some(segment) => segment,
308                 None => return None,
309             };
310
311             for item in mem::replace(&mut items, Rc::new(vec![])).iter() {
312                 if item.ident.name == *segment {
313                     if path_it.peek().is_none() {
314                         return Some(item.def);
315                     }
316
317                     items = cx.tcx.item_children(item.def.def_id());
318                     break;
319                 }
320             }
321         }
322     } else {
323         None
324     }
325 }
326
327 pub fn const_to_u64(c: &ty::Const) -> u64 {
328     c.val.to_const_int().expect("eddyb says this works").to_u64().expect("see previous expect")
329 }
330
331 /// Convenience function to get the `DefId` of a trait by path.
332 pub fn get_trait_def_id(cx: &LateContext, path: &[&str]) -> Option<DefId> {
333     let def = match path_to_def(cx, path) {
334         Some(def) => def,
335         None => return None,
336     };
337
338     match def {
339         def::Def::Trait(trait_id) => Some(trait_id),
340         _ => None,
341     }
342 }
343
344 /// Check whether a type implements a trait.
345 /// See also `get_trait_def_id`.
346 pub fn implements_trait<'a, 'tcx>(
347     cx: &LateContext<'a, 'tcx>,
348     ty: Ty<'tcx>,
349     trait_id: DefId,
350     ty_params: &[Ty<'tcx>],
351 ) -> bool {
352     let ty = cx.tcx.erase_regions(&ty);
353     let obligation =
354         cx.tcx
355             .predicate_for_trait_def(cx.param_env, traits::ObligationCause::dummy(), trait_id, 0, ty, ty_params);
356     cx.tcx.infer_ctxt().enter(|infcx| {
357         traits::SelectionContext::new(&infcx).evaluate_obligation_conservatively(&obligation)
358     })
359 }
360
361 /// Check whether this type implements Drop.
362 pub fn has_drop(cx: &LateContext, expr: &Expr) -> bool {
363     let struct_ty = cx.tables.expr_ty(expr);
364     match struct_ty.ty_adt_def() {
365         Some(def) => def.has_dtor(cx.tcx),
366         _ => false,
367     }
368 }
369
370 /// Resolve the definition of a node from its `HirId`.
371 pub fn resolve_node(cx: &LateContext, qpath: &QPath, id: HirId) -> def::Def {
372     cx.tables.qpath_def(qpath, id)
373 }
374
375 /// Match an `Expr` against a chain of methods, and return the matched `Expr`s.
376 ///
377 /// For example, if `expr` represents the `.baz()` in `foo.bar().baz()`,
378 /// `matched_method_chain(expr, &["bar", "baz"])` will return a `Vec`
379 /// containing the `Expr`s for
380 /// `.bar()` and `.baz()`
381 pub fn method_chain_args<'a>(expr: &'a Expr, methods: &[&str]) -> Option<Vec<&'a [Expr]>> {
382     let mut current = expr;
383     let mut matched = Vec::with_capacity(methods.len());
384     for method_name in methods.iter().rev() {
385         // method chains are stored last -> first
386         if let ExprMethodCall(ref path, _, ref args) = current.node {
387             if path.name == *method_name {
388                 if args.iter().any(|e| in_macro(e.span)) {
389                     return None;
390                 }
391                 matched.push(&**args); // build up `matched` backwards
392                 current = &args[0] // go to parent expression
393             } else {
394                 return None;
395             }
396         } else {
397             return None;
398         }
399     }
400     matched.reverse(); // reverse `matched`, so that it is in the same order as `methods`
401     Some(matched)
402 }
403
404
405 /// Get the name of the item the expression is in, if available.
406 pub fn get_item_name(cx: &LateContext, expr: &Expr) -> Option<Name> {
407     let parent_id = cx.tcx.hir.get_parent(expr.id);
408     match cx.tcx.hir.find(parent_id) {
409         Some(Node::NodeItem(&Item { ref name, .. })) |
410         Some(Node::NodeTraitItem(&TraitItem { ref name, .. })) |
411         Some(Node::NodeImplItem(&ImplItem { ref name, .. })) => Some(*name),
412         _ => None,
413     }
414 }
415
416 /// Get the name of a `Pat`, if any
417 pub fn get_pat_name(pat: &Pat) -> Option<Name> {
418     match pat.node {
419         PatKind::Binding(_, _, ref spname, _) => Some(spname.node),
420         PatKind::Path(ref qpath) => single_segment_path(qpath).map(|ps| ps.name),
421         PatKind::Box(ref p) | PatKind::Ref(ref p, _) => get_pat_name(&*p),
422         _ => None,
423     }
424 }
425
426 struct ContainsName {
427     name: Name,
428     result: bool,
429 }
430
431 impl<'tcx> Visitor<'tcx> for ContainsName {
432     fn visit_name(&mut self, _: Span, name: Name) {
433         if self.name == name {
434             self.result = true;
435         }
436     }
437     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
438         NestedVisitorMap::None
439     }
440 }
441
442 /// check if an `Expr` contains a certain name
443 pub fn contains_name(name: Name, expr: &Expr) -> bool {
444     let mut cn = ContainsName {
445         name: name,
446         result: false,
447     };
448     cn.visit_expr(expr);
449     cn.result
450 }
451
452
453 /// Convert a span to a code snippet if available, otherwise use default.
454 ///
455 /// # Example
456 /// ```rust,ignore
457 /// snippet(cx, expr.span, "..")
458 /// ```
459 pub fn snippet<'a, 'b, T: LintContext<'b>>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
460     snippet_opt(cx, span).map_or_else(|| Cow::Borrowed(default), From::from)
461 }
462
463 /// Convert a span to a code snippet. Returns `None` if not available.
464 pub fn snippet_opt<'a, T: LintContext<'a>>(cx: &T, span: Span) -> Option<String> {
465     cx.sess().codemap().span_to_snippet(span).ok()
466 }
467
468 /// Convert a span (from a block) to a code snippet if available, otherwise use
469 /// default.
470 /// This trims the code of indentation, except for the first line. Use it for
471 /// blocks or block-like
472 /// things which need to be printed as such.
473 ///
474 /// # Example
475 /// ```rust,ignore
476 /// snippet(cx, expr.span, "..")
477 /// ```
478 pub fn snippet_block<'a, 'b, T: LintContext<'b>>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
479     let snip = snippet(cx, span, default);
480     trim_multiline(snip, true)
481 }
482
483 /// Like `snippet_block`, but add braces if the expr is not an `ExprBlock`.
484 /// Also takes an `Option<String>` which can be put inside the braces.
485 pub fn expr_block<'a, 'b, T: LintContext<'b>>(
486     cx: &T,
487     expr: &Expr,
488     option: Option<String>,
489     default: &'a str,
490 ) -> Cow<'a, str> {
491     let code = snippet_block(cx, expr.span, default);
492     let string = option.unwrap_or_default();
493     if let ExprBlock(_) = expr.node {
494         Cow::Owned(format!("{}{}", code, string))
495     } else if string.is_empty() {
496         Cow::Owned(format!("{{ {} }}", code))
497     } else {
498         Cow::Owned(format!("{{\n{};\n{}\n}}", code, string))
499     }
500 }
501
502 /// Trim indentation from a multiline string with possibility of ignoring the
503 /// first line.
504 pub fn trim_multiline(s: Cow<str>, ignore_first: bool) -> Cow<str> {
505     let s_space = trim_multiline_inner(s, ignore_first, ' ');
506     let s_tab = trim_multiline_inner(s_space, ignore_first, '\t');
507     trim_multiline_inner(s_tab, ignore_first, ' ')
508 }
509
510 fn trim_multiline_inner(s: Cow<str>, ignore_first: bool, ch: char) -> Cow<str> {
511     let x = s.lines()
512         .skip(ignore_first as usize)
513         .filter_map(|l| {
514             if l.is_empty() {
515                 None
516             } else {
517                 // ignore empty lines
518                 Some(
519                     l.char_indices()
520                         .find(|&(_, x)| x != ch)
521                         .unwrap_or((l.len(), ch))
522                         .0,
523                 )
524             }
525         })
526         .min()
527         .unwrap_or(0);
528     if x > 0 {
529         Cow::Owned(
530             s.lines()
531                 .enumerate()
532                 .map(|(i, l)| if (ignore_first && i == 0) || l.is_empty() {
533                     l
534                 } else {
535                     l.split_at(x).1
536                 })
537                 .collect::<Vec<_>>()
538                 .join("\n"),
539         )
540     } else {
541         s
542     }
543 }
544
545 /// Get a parent expressions if any â€“ this is useful to constrain a lint.
546 pub fn get_parent_expr<'c>(cx: &'c LateContext, e: &Expr) -> Option<&'c Expr> {
547     let map = &cx.tcx.hir;
548     let node_id: NodeId = e.id;
549     let parent_id: NodeId = map.get_parent_node(node_id);
550     if node_id == parent_id {
551         return None;
552     }
553     map.find(parent_id)
554         .and_then(|node| if let Node::NodeExpr(parent) = node {
555             Some(parent)
556         } else {
557             None
558         })
559 }
560
561 pub fn get_enclosing_block<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, node: NodeId) -> Option<&'tcx Block> {
562     let map = &cx.tcx.hir;
563     let enclosing_node = map.get_enclosing_scope(node)
564         .and_then(|enclosing_id| map.find(enclosing_id));
565     if let Some(node) = enclosing_node {
566         match node {
567             Node::NodeBlock(block) => Some(block),
568             Node::NodeItem(&Item {
569                 node: ItemFn(_, _, _, _, _, eid),
570                 ..
571             }) => match cx.tcx.hir.body(eid).value.node {
572                 ExprBlock(ref block) => Some(block),
573                 _ => None,
574             },
575             _ => None,
576         }
577     } else {
578         None
579     }
580 }
581
582 pub struct DiagnosticWrapper<'a>(pub DiagnosticBuilder<'a>);
583
584 impl<'a> Drop for DiagnosticWrapper<'a> {
585     fn drop(&mut self) {
586         self.0.emit();
587     }
588 }
589
590 impl<'a> DiagnosticWrapper<'a> {
591     fn docs_link(&mut self, lint: &'static Lint) {
592         if env::var("CLIPPY_DISABLE_DOCS_LINKS").is_err() {
593             self.0.help(&format!(
594                 "for further information visit https://rust-lang-nursery.github.io/rust-clippy/v{}/index.html#{}",
595                 env!("CARGO_PKG_VERSION"),
596                 lint.name_lower()
597             ));
598         }
599     }
600 }
601
602 pub fn span_lint<'a, T: LintContext<'a>>(cx: &T, lint: &'static Lint, sp: Span, msg: &str) {
603     DiagnosticWrapper(cx.struct_span_lint(lint, sp, msg)).docs_link(lint);
604 }
605
606 pub fn span_help_and_lint<'a, 'tcx: 'a, T: LintContext<'tcx>>(
607     cx: &'a T,
608     lint: &'static Lint,
609     span: Span,
610     msg: &str,
611     help: &str,
612 ) {
613     let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, span, msg));
614     db.0.help(help);
615     db.docs_link(lint);
616 }
617
618 pub fn span_note_and_lint<'a, 'tcx: 'a, T: LintContext<'tcx>>(
619     cx: &'a T,
620     lint: &'static Lint,
621     span: Span,
622     msg: &str,
623     note_span: Span,
624     note: &str,
625 ) {
626     let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, span, msg));
627     if note_span == span {
628         db.0.note(note);
629     } else {
630         db.0.span_note(note_span, note);
631     }
632     db.docs_link(lint);
633 }
634
635 pub fn span_lint_and_then<'a, 'tcx: 'a, T: LintContext<'tcx>, F>(
636     cx: &'a T,
637     lint: &'static Lint,
638     sp: Span,
639     msg: &str,
640     f: F,
641 ) where
642     F: for<'b> FnOnce(&mut DiagnosticBuilder<'b>),
643 {
644     let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, sp, msg));
645     f(&mut db.0);
646     db.docs_link(lint);
647 }
648
649 pub fn span_lint_and_sugg<'a, 'tcx: 'a, T: LintContext<'tcx>>(
650     cx: &'a T,
651     lint: &'static Lint,
652     sp: Span,
653     msg: &str,
654     help: &str,
655     sugg: String,
656 ) {
657     span_lint_and_then(cx, lint, sp, msg, |db| { db.span_suggestion(sp, help, sugg); });
658 }
659
660 /// Create a suggestion made from several `span â†’ replacement`.
661 ///
662 /// Note: in the JSON format (used by `compiletest_rs`), the help message will
663 /// appear once per
664 /// replacement. In human-readable format though, it only appears once before
665 /// the whole suggestion.
666 pub fn multispan_sugg(db: &mut DiagnosticBuilder, help_msg: String, sugg: Vec<(Span, String)>) {
667     let sugg = rustc_errors::CodeSuggestion {
668         substitution_parts: sugg.into_iter()
669             .map(|(span, sub)| {
670                 rustc_errors::Substitution {
671                     span: span,
672                     substitutions: vec![sub],
673                 }
674             })
675             .collect(),
676         msg: help_msg,
677         show_code_when_inline: true,
678     };
679     db.suggestions.push(sugg);
680 }
681
682 /// Return the base type for HIR references and pointers.
683 pub fn walk_ptrs_hir_ty(ty: &hir::Ty) -> &hir::Ty {
684     match ty.node {
685         TyPtr(ref mut_ty) |
686         TyRptr(_, ref mut_ty) => walk_ptrs_hir_ty(&mut_ty.ty),
687         _ => ty
688     }
689 }
690
691 /// Return the base type for references and raw pointers.
692 pub fn walk_ptrs_ty(ty: Ty) -> Ty {
693     match ty.sty {
694         ty::TyRef(_, ref tm) => walk_ptrs_ty(tm.ty),
695         _ => ty,
696     }
697 }
698
699 /// Return the base type for references and raw pointers, and count reference
700 /// depth.
701 pub fn walk_ptrs_ty_depth(ty: Ty) -> (Ty, usize) {
702     fn inner(ty: Ty, depth: usize) -> (Ty, usize) {
703         match ty.sty {
704             ty::TyRef(_, ref tm) => inner(tm.ty, depth + 1),
705             _ => (ty, depth),
706         }
707     }
708     inner(ty, 0)
709 }
710
711 /// Check whether the given expression is a constant literal of the given value.
712 pub fn is_integer_literal(expr: &Expr, value: u128) -> bool {
713     // FIXME: use constant folding
714     if let ExprLit(ref spanned) = expr.node {
715         if let LitKind::Int(v, _) = spanned.node {
716             return v == value;
717         }
718     }
719     false
720 }
721
722 pub fn is_adjusted(cx: &LateContext, e: &Expr) -> bool {
723     cx.tables.adjustments().get(e.hir_id).is_some()
724 }
725
726 pub struct LimitStack {
727     stack: Vec<u64>,
728 }
729
730 impl Drop for LimitStack {
731     fn drop(&mut self) {
732         assert_eq!(self.stack.len(), 1);
733     }
734 }
735
736 impl LimitStack {
737     pub fn new(limit: u64) -> Self {
738         Self { stack: vec![limit] }
739     }
740     pub fn limit(&self) -> u64 {
741         *self.stack
742             .last()
743             .expect("there should always be a value in the stack")
744     }
745     pub fn push_attrs(&mut self, sess: &Session, attrs: &[ast::Attribute], name: &'static str) {
746         let stack = &mut self.stack;
747         parse_attrs(sess, attrs, name, |val| stack.push(val));
748     }
749     pub fn pop_attrs(&mut self, sess: &Session, attrs: &[ast::Attribute], name: &'static str) {
750         let stack = &mut self.stack;
751         parse_attrs(sess, attrs, name, |val| assert_eq!(stack.pop(), Some(val)));
752     }
753 }
754
755 fn parse_attrs<F: FnMut(u64)>(sess: &Session, attrs: &[ast::Attribute], name: &'static str, mut f: F) {
756     for attr in attrs {
757         if attr.is_sugared_doc {
758             continue;
759         }
760         if let Some(ref value) = attr.value_str() {
761             if attr.name().map_or(false, |n| n == name) {
762                 if let Ok(value) = FromStr::from_str(&value.as_str()) {
763                     attr::mark_used(attr);
764                     f(value)
765                 } else {
766                     sess.span_err(attr.span, "not a number");
767                 }
768             }
769         }
770     }
771 }
772
773 /// Return the pre-expansion span if is this comes from an expansion of the
774 /// macro `name`.
775 /// See also `is_direct_expn_of`.
776 pub fn is_expn_of(mut span: Span, name: &str) -> Option<Span> {
777     loop {
778         let span_name_span = span.ctxt()
779             .outer()
780             .expn_info()
781             .map(|ei| (ei.callee.name(), ei.call_site));
782
783         match span_name_span {
784             Some((mac_name, new_span)) if mac_name == name => return Some(new_span),
785             None => return None,
786             Some((_, new_span)) => span = new_span,
787         }
788     }
789 }
790
791 /// Return the pre-expansion span if is this directly comes from an expansion
792 /// of the macro `name`.
793 /// The difference with `is_expn_of` is that in
794 /// ```rust,ignore
795 /// foo!(bar!(42));
796 /// ```
797 /// `42` is considered expanded from `foo!` and `bar!` by `is_expn_of` but only
798 /// `bar!` by
799 /// `is_direct_expn_of`.
800 pub fn is_direct_expn_of(span: Span, name: &str) -> Option<Span> {
801     let span_name_span = span.ctxt()
802         .outer()
803         .expn_info()
804         .map(|ei| (ei.callee.name(), ei.call_site));
805
806     match span_name_span {
807         Some((mac_name, new_span)) if mac_name == name => Some(new_span),
808         _ => None,
809     }
810 }
811
812 /// Return the index of the character after the first camel-case component of
813 /// `s`.
814 pub fn camel_case_until(s: &str) -> usize {
815     let mut iter = s.char_indices();
816     if let Some((_, first)) = iter.next() {
817         if !first.is_uppercase() {
818             return 0;
819         }
820     } else {
821         return 0;
822     }
823     let mut up = true;
824     let mut last_i = 0;
825     for (i, c) in iter {
826         if up {
827             if c.is_lowercase() {
828                 up = false;
829             } else {
830                 return last_i;
831             }
832         } else if c.is_uppercase() {
833             up = true;
834             last_i = i;
835         } else if !c.is_lowercase() {
836             return i;
837         }
838     }
839     if up {
840         last_i
841     } else {
842         s.len()
843     }
844 }
845
846 /// Return index of the last camel-case component of `s`.
847 pub fn camel_case_from(s: &str) -> usize {
848     let mut iter = s.char_indices().rev();
849     if let Some((_, first)) = iter.next() {
850         if !first.is_lowercase() {
851             return s.len();
852         }
853     } else {
854         return s.len();
855     }
856     let mut down = true;
857     let mut last_i = s.len();
858     for (i, c) in iter {
859         if down {
860             if c.is_uppercase() {
861                 down = false;
862                 last_i = i;
863             } else if !c.is_lowercase() {
864                 return last_i;
865             }
866         } else if c.is_lowercase() {
867             down = true;
868         } else {
869             return last_i;
870         }
871     }
872     last_i
873 }
874
875 /// Convenience function to get the return type of a function
876 pub fn return_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, fn_item: NodeId) -> Ty<'tcx> {
877     let fn_def_id = cx.tcx.hir.local_def_id(fn_item);
878     let ret_ty = cx.tcx.fn_sig(fn_def_id).output();
879     cx.tcx.erase_late_bound_regions(&ret_ty)
880 }
881
882 /// Check if two types are the same.
883 // FIXME: this works correctly for lifetimes bounds (`for <'a> Foo<'a>` == `for
884 // <'b> Foo<'b>` but
885 // not for type parameters.
886 pub fn same_tys<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
887     cx.tcx
888         .infer_ctxt()
889         .enter(|infcx| infcx.can_eq(cx.param_env, a, b).is_ok())
890 }
891
892 /// Return whether the given type is an `unsafe` function.
893 pub fn type_is_unsafe_function<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
894     match ty.sty {
895         ty::TyFnDef(..) | ty::TyFnPtr(_) => ty.fn_sig(cx.tcx).unsafety() == Unsafety::Unsafe,
896         _ => false,
897     }
898 }
899
900 pub fn is_copy<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
901     !ty.moves_by_default(cx.tcx.global_tcx(), cx.param_env, DUMMY_SP)
902 }
903
904 /// Return whether a pattern is refutable.
905 pub fn is_refutable(cx: &LateContext, pat: &Pat) -> bool {
906     fn is_enum_variant(cx: &LateContext, qpath: &QPath, id: HirId) -> bool {
907         matches!(
908             cx.tables.qpath_def(qpath, id),
909             def::Def::Variant(..) | def::Def::VariantCtor(..)
910         )
911     }
912
913     fn are_refutable<'a, I: Iterator<Item = &'a Pat>>(cx: &LateContext, mut i: I) -> bool {
914         i.any(|pat| is_refutable(cx, pat))
915     }
916
917     match pat.node {
918         PatKind::Binding(..) | PatKind::Wild => false,
919         PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => is_refutable(cx, pat),
920         PatKind::Lit(..) | PatKind::Range(..) => true,
921         PatKind::Path(ref qpath) => is_enum_variant(cx, qpath, pat.hir_id),
922         PatKind::Tuple(ref pats, _) => are_refutable(cx, pats.iter().map(|pat| &**pat)),
923         PatKind::Struct(ref qpath, ref fields, _) => if is_enum_variant(cx, qpath, pat.hir_id) {
924             true
925         } else {
926             are_refutable(cx, fields.iter().map(|field| &*field.node.pat))
927         },
928         PatKind::TupleStruct(ref qpath, ref pats, _) => if is_enum_variant(cx, qpath, pat.hir_id) {
929             true
930         } else {
931             are_refutable(cx, pats.iter().map(|pat| &**pat))
932         },
933         PatKind::Slice(ref head, ref middle, ref tail) => are_refutable(
934             cx,
935             head.iter()
936                 .chain(middle)
937                 .chain(tail.iter())
938                 .map(|pat| &**pat),
939         ),
940     }
941 }
942
943 /// Checks for the `#[automatically_derived]` attribute all `#[derive]`d
944 /// implementations have.
945 pub fn is_automatically_derived(attrs: &[ast::Attribute]) -> bool {
946     attr::contains_name(attrs, "automatically_derived")
947 }
948
949 /// Remove blocks around an expression.
950 ///
951 /// Ie. `x`, `{ x }` and `{{{{ x }}}}` all give `x`. `{ x; y }` and `{}` return
952 /// themselves.
953 pub fn remove_blocks(expr: &Expr) -> &Expr {
954     if let ExprBlock(ref block) = expr.node {
955         if block.stmts.is_empty() {
956             if let Some(ref expr) = block.expr {
957                 remove_blocks(expr)
958             } else {
959                 expr
960             }
961         } else {
962             expr
963         }
964     } else {
965         expr
966     }
967 }
968
969 pub fn opt_def_id(def: Def) -> Option<DefId> {
970     match def {
971         Def::Fn(id) |
972         Def::Mod(id) |
973         Def::Static(id, _) |
974         Def::Variant(id) |
975         Def::VariantCtor(id, ..) |
976         Def::Enum(id) |
977         Def::TyAlias(id) |
978         Def::AssociatedTy(id) |
979         Def::TyParam(id) |
980         Def::Struct(id) |
981         Def::StructCtor(id, ..) |
982         Def::Union(id) |
983         Def::Trait(id) |
984         Def::Method(id) |
985         Def::Const(id) |
986         Def::AssociatedConst(id) |
987         Def::Macro(id, ..) |
988         Def::GlobalAsm(id) => Some(id),
989
990         Def::Upvar(..) | Def::Local(_) | Def::Label(..) | Def::PrimTy(..) | Def::SelfTy(..) | Def::Err => None,
991     }
992 }
993
994 pub fn is_self(slf: &Arg) -> bool {
995     if let PatKind::Binding(_, _, name, _) = slf.pat.node {
996         name.node == keywords::SelfValue.name()
997     } else {
998         false
999     }
1000 }
1001
1002 pub fn is_self_ty(slf: &hir::Ty) -> bool {
1003     if_let_chain! {[
1004         let TyPath(ref qp) = slf.node,
1005         let QPath::Resolved(None, ref path) = *qp,
1006         let Def::SelfTy(..) = path.def,
1007     ], {
1008         return true
1009     }}
1010     false
1011 }
1012
1013 pub fn iter_input_pats<'tcx>(decl: &FnDecl, body: &'tcx Body) -> impl Iterator<Item = &'tcx Arg> {
1014     (0..decl.inputs.len()).map(move |i| &body.arguments[i])
1015 }
1016
1017 /// Check if a given expression is a match expression
1018 /// expanded from `?` operator or `try` macro.
1019 pub fn is_try(expr: &Expr) -> Option<&Expr> {
1020     fn is_ok(arm: &Arm) -> bool {
1021         if_let_chain! {[
1022             let PatKind::TupleStruct(ref path, ref pat, None) = arm.pats[0].node,
1023             match_qpath(path, &paths::RESULT_OK[1..]),
1024             let PatKind::Binding(_, defid, _, None) = pat[0].node,
1025             let ExprPath(QPath::Resolved(None, ref path)) = arm.body.node,
1026             let Def::Local(lid) = path.def,
1027             lid == defid,
1028         ], {
1029             return true;
1030         }}
1031         false
1032     }
1033
1034     fn is_err(arm: &Arm) -> bool {
1035         if let PatKind::TupleStruct(ref path, _, _) = arm.pats[0].node {
1036             match_qpath(path, &paths::RESULT_ERR[1..])
1037         } else {
1038             false
1039         }
1040     }
1041
1042     if let ExprMatch(_, ref arms, ref source) = expr.node {
1043         // desugared from a `?` operator
1044         if let MatchSource::TryDesugar = *source {
1045             return Some(expr);
1046         }
1047
1048         if_let_chain! {[
1049             arms.len() == 2,
1050             arms[0].pats.len() == 1 && arms[0].guard.is_none(),
1051             arms[1].pats.len() == 1 && arms[1].guard.is_none(),
1052             (is_ok(&arms[0]) && is_err(&arms[1])) ||
1053                 (is_ok(&arms[1]) && is_err(&arms[0])),
1054         ], {
1055             return Some(expr);
1056         }}
1057     }
1058
1059     None
1060 }
1061
1062 pub fn type_size<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> Option<u64> {
1063     ty.layout(cx.tcx, cx.param_env)
1064         .ok()
1065         .map(|layout| layout.size(cx.tcx).bytes())
1066 }
1067
1068 /// Returns true if the lint is allowed in the current context
1069 ///
1070 /// Useful for skipping long running code when it's unnecessary
1071 pub fn is_allowed(cx: &LateContext, lint: &'static Lint, id: NodeId) -> bool {
1072     cx.tcx.lint_level_at_node(lint, id).0 == Level::Allow
1073 }