]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/utils/mod.rs
cargo fmt
[rust.git] / clippy_lints / src / utils / mod.rs
1 use crate::reexport::*;
2 use if_chain::if_chain;
3 use matches::matches;
4 use rustc::hir;
5 use rustc::hir::def::Def;
6 use rustc::hir::def_id::{DefId, CRATE_DEF_INDEX};
7 use rustc::hir::intravisit::{NestedVisitorMap, Visitor};
8 use rustc::hir::Node;
9 use rustc::hir::*;
10 use rustc::lint::{LateContext, Level, Lint, LintContext};
11 use rustc::session::Session;
12 use rustc::traits;
13 use rustc::ty::{
14     self,
15     layout::{self, IntegerExt},
16     subst::Kind,
17     Binder, Ty, TyCtxt,
18 };
19 use rustc_data_structures::sync::Lrc;
20 use rustc_errors::{Applicability, CodeSuggestion, Substitution, SubstitutionPart};
21 use std::borrow::Cow;
22 use std::env;
23 use std::mem;
24 use std::str::FromStr;
25 use syntax::ast::{self, LitKind};
26 use syntax::attr;
27 use syntax::errors::DiagnosticBuilder;
28 use syntax::source_map::{Span, DUMMY_SP};
29 use syntax::symbol;
30 use syntax::symbol::{keywords, Symbol};
31
32 pub mod camel_case;
33
34 pub mod author;
35 pub mod comparisons;
36 pub mod conf;
37 pub mod constants;
38 mod hir_utils;
39 pub mod inspector;
40 pub mod internal_lints;
41 pub mod paths;
42 pub mod ptr;
43 pub mod sugg;
44 pub mod usage;
45 pub use self::hir_utils::{SpanlessEq, SpanlessHash};
46
47 pub mod higher;
48
49 /// Returns true if the two spans come from differing expansions (i.e. one is
50 /// from a macro and one
51 /// isn't).
52 pub fn differing_macro_contexts(lhs: Span, rhs: Span) -> bool {
53     rhs.ctxt() != lhs.ctxt()
54 }
55
56 /// Returns `true` if the given `NodeId` is inside a constant context
57 ///
58 /// # Example
59 ///
60 /// ```rust,ignore
61 /// if in_constant(cx, expr.id) {
62 ///     // Do something
63 /// }
64 /// ```
65 pub fn in_constant(cx: &LateContext<'_, '_>, id: NodeId) -> bool {
66     let parent_id = cx.tcx.hir().get_parent(id);
67     match cx.tcx.hir().get(parent_id) {
68         Node::Item(&Item {
69             node: ItemKind::Const(..),
70             ..
71         })
72         | Node::TraitItem(&TraitItem {
73             node: TraitItemKind::Const(..),
74             ..
75         })
76         | Node::ImplItem(&ImplItem {
77             node: ImplItemKind::Const(..),
78             ..
79         })
80         | Node::AnonConst(_)
81         | Node::Item(&Item {
82             node: ItemKind::Static(..),
83             ..
84         }) => true,
85         Node::Item(&Item {
86             node: ItemKind::Fn(_, header, ..),
87             ..
88         }) => header.constness == Constness::Const,
89         _ => false,
90     }
91 }
92
93 /// Returns true if this `expn_info` was expanded by any macro.
94 pub fn in_macro(span: Span) -> bool {
95     span.ctxt().outer().expn_info().is_some()
96 }
97
98 /// Used to store the absolute path to a type.
99 ///
100 /// See `match_def_path` for usage.
101 #[derive(Debug)]
102 pub struct AbsolutePathBuffer {
103     pub names: Vec<symbol::LocalInternedString>,
104 }
105
106 impl ty::item_path::ItemPathBuffer for AbsolutePathBuffer {
107     fn root_mode(&self) -> &ty::item_path::RootMode {
108         const ABSOLUTE: &ty::item_path::RootMode = &ty::item_path::RootMode::Absolute;
109         ABSOLUTE
110     }
111
112     fn push(&mut self, text: &str) {
113         self.names.push(symbol::Symbol::intern(text).as_str());
114     }
115 }
116
117 /// Check if a `DefId`'s path matches the given absolute type path usage.
118 ///
119 /// # Examples
120 /// ```rust,ignore
121 /// match_def_path(cx.tcx, id, &["core", "option", "Option"])
122 /// ```
123 ///
124 /// See also the `paths` module.
125 pub fn match_def_path(tcx: TyCtxt<'_, '_, '_>, def_id: DefId, path: &[&str]) -> bool {
126     let mut apb = AbsolutePathBuffer { names: vec![] };
127
128     tcx.push_item_path(&mut apb, def_id, false);
129
130     apb.names.len() == path.len() && apb.names.into_iter().zip(path.iter()).all(|(a, &b)| *a == *b)
131 }
132
133 /// Check if type is struct, enum or union type with given def path.
134 pub fn match_type(cx: &LateContext<'_, '_>, ty: Ty<'_>, path: &[&str]) -> bool {
135     match ty.sty {
136         ty::Adt(adt, _) => match_def_path(cx.tcx, adt.did, path),
137         _ => false,
138     }
139 }
140
141 /// Check if the method call given in `expr` belongs to given trait.
142 pub fn match_trait_method(cx: &LateContext<'_, '_>, expr: &Expr, path: &[&str]) -> bool {
143     let method_call = cx.tables.type_dependent_defs()[expr.hir_id];
144     let trt_id = cx.tcx.trait_of_item(method_call.def_id());
145     if let Some(trt_id) = trt_id {
146         match_def_path(cx.tcx, trt_id, path)
147     } else {
148         false
149     }
150 }
151
152 /// Check if an expression references a variable of the given name.
153 pub fn match_var(expr: &Expr, var: Name) -> bool {
154     if let ExprKind::Path(QPath::Resolved(None, ref path)) = expr.node {
155         if path.segments.len() == 1 && path.segments[0].ident.name == var {
156             return true;
157         }
158     }
159     false
160 }
161
162 pub fn last_path_segment(path: &QPath) -> &PathSegment {
163     match *path {
164         QPath::Resolved(_, ref path) => path.segments.last().expect("A path must have at least one segment"),
165         QPath::TypeRelative(_, ref seg) => seg,
166     }
167 }
168
169 pub fn single_segment_path(path: &QPath) -> Option<&PathSegment> {
170     match *path {
171         QPath::Resolved(_, ref path) if path.segments.len() == 1 => Some(&path.segments[0]),
172         QPath::Resolved(..) => None,
173         QPath::TypeRelative(_, ref seg) => Some(seg),
174     }
175 }
176
177 /// Match a `Path` against a slice of segment string literals.
178 ///
179 /// # Examples
180 /// ```rust,ignore
181 /// match_qpath(path, &["std", "rt", "begin_unwind"])
182 /// ```
183 pub fn match_qpath(path: &QPath, segments: &[&str]) -> bool {
184     match *path {
185         QPath::Resolved(_, ref path) => match_path(path, segments),
186         QPath::TypeRelative(ref ty, ref segment) => match ty.node {
187             TyKind::Path(ref inner_path) => {
188                 !segments.is_empty()
189                     && match_qpath(inner_path, &segments[..(segments.len() - 1)])
190                     && segment.ident.name == segments[segments.len() - 1]
191             },
192             _ => false,
193         },
194     }
195 }
196
197 pub fn match_path(path: &Path, segments: &[&str]) -> bool {
198     path.segments
199         .iter()
200         .rev()
201         .zip(segments.iter().rev())
202         .all(|(a, b)| a.ident.name == *b)
203 }
204
205 /// Match a `Path` against a slice of segment string literals, e.g.
206 ///
207 /// # Examples
208 /// ```rust,ignore
209 /// match_qpath(path, &["std", "rt", "begin_unwind"])
210 /// ```
211 pub fn match_path_ast(path: &ast::Path, segments: &[&str]) -> bool {
212     path.segments
213         .iter()
214         .rev()
215         .zip(segments.iter().rev())
216         .all(|(a, b)| a.ident.name == *b)
217 }
218
219 /// Get the definition associated to a path.
220 pub fn path_to_def(cx: &LateContext<'_, '_>, path: &[&str]) -> Option<def::Def> {
221     let crates = cx.tcx.crates();
222     let krate = crates.iter().find(|&&krate| cx.tcx.crate_name(krate) == path[0]);
223     if let Some(krate) = krate {
224         let krate = DefId {
225             krate: *krate,
226             index: CRATE_DEF_INDEX,
227         };
228         let mut items = cx.tcx.item_children(krate);
229         let mut path_it = path.iter().skip(1).peekable();
230
231         loop {
232             let segment = match path_it.next() {
233                 Some(segment) => segment,
234                 None => return None,
235             };
236
237             for item in mem::replace(&mut items, Lrc::new(vec![])).iter() {
238                 if item.ident.name == *segment {
239                     if path_it.peek().is_none() {
240                         return Some(item.def);
241                     }
242
243                     items = cx.tcx.item_children(item.def.def_id());
244                     break;
245                 }
246             }
247         }
248     } else {
249         None
250     }
251 }
252
253 /// Convenience function to get the `DefId` of a trait by path.
254 pub fn get_trait_def_id(cx: &LateContext<'_, '_>, path: &[&str]) -> Option<DefId> {
255     let def = match path_to_def(cx, path) {
256         Some(def) => def,
257         None => return None,
258     };
259
260     match def {
261         def::Def::Trait(trait_id) => Some(trait_id),
262         _ => None,
263     }
264 }
265
266 /// Check whether a type implements a trait.
267 /// See also `get_trait_def_id`.
268 pub fn implements_trait<'a, 'tcx>(
269     cx: &LateContext<'a, 'tcx>,
270     ty: Ty<'tcx>,
271     trait_id: DefId,
272     ty_params: &[Kind<'tcx>],
273 ) -> bool {
274     let ty = cx.tcx.erase_regions(&ty);
275     let obligation = cx.tcx.predicate_for_trait_def(
276         cx.param_env,
277         traits::ObligationCause::dummy(),
278         trait_id,
279         0,
280         ty,
281         ty_params,
282     );
283     cx.tcx
284         .infer_ctxt()
285         .enter(|infcx| infcx.predicate_must_hold_modulo_regions(&obligation))
286 }
287
288 /// Check whether this type implements Drop.
289 pub fn has_drop<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
290     match ty.ty_adt_def() {
291         Some(def) => def.has_dtor(cx.tcx),
292         _ => false,
293     }
294 }
295
296 /// Resolve the definition of a node from its `HirId`.
297 pub fn resolve_node(cx: &LateContext<'_, '_>, qpath: &QPath, id: HirId) -> def::Def {
298     cx.tables.qpath_def(qpath, id)
299 }
300
301 /// Return the method names and argument list of nested method call expressions that make up
302 /// `expr`.
303 pub fn method_calls<'a>(expr: &'a Expr, max_depth: usize) -> (Vec<Symbol>, Vec<&'a [Expr]>) {
304     let mut method_names = Vec::with_capacity(max_depth);
305     let mut arg_lists = Vec::with_capacity(max_depth);
306
307     let mut current = expr;
308     for _ in 0..max_depth {
309         if let ExprKind::MethodCall(path, _, args) = &current.node {
310             if args.iter().any(|e| in_macro(e.span)) {
311                 break;
312             }
313             method_names.push(path.ident.name);
314             arg_lists.push(&**args);
315             current = &args[0];
316         } else {
317             break;
318         }
319     }
320
321     (method_names, arg_lists)
322 }
323
324 /// Match an `Expr` against a chain of methods, and return the matched `Expr`s.
325 ///
326 /// For example, if `expr` represents the `.baz()` in `foo.bar().baz()`,
327 /// `matched_method_chain(expr, &["bar", "baz"])` will return a `Vec`
328 /// containing the `Expr`s for
329 /// `.bar()` and `.baz()`
330 pub fn method_chain_args<'a>(expr: &'a Expr, methods: &[&str]) -> Option<Vec<&'a [Expr]>> {
331     let mut current = expr;
332     let mut matched = Vec::with_capacity(methods.len());
333     for method_name in methods.iter().rev() {
334         // method chains are stored last -> first
335         if let ExprKind::MethodCall(ref path, _, ref args) = current.node {
336             if path.ident.name == *method_name {
337                 if args.iter().any(|e| in_macro(e.span)) {
338                     return None;
339                 }
340                 matched.push(&**args); // build up `matched` backwards
341                 current = &args[0] // go to parent expression
342             } else {
343                 return None;
344             }
345         } else {
346             return None;
347         }
348     }
349     matched.reverse(); // reverse `matched`, so that it is in the same order as `methods`
350     Some(matched)
351 }
352
353 /// Returns true if the function is an entrypoint to a program
354 ///
355 /// This is either the usual `main` function or a custom function with the `#[start]` attribute.
356 pub fn is_entrypoint_fn(fn_name: &str, attrs: &[ast::Attribute]) -> bool {
357     let is_custom_entrypoint = attrs
358         .iter()
359         .any(|attr| attr.path.segments.len() == 1 && attr.path.segments[0].ident.to_string() == "start");
360
361     is_custom_entrypoint || fn_name == "main"
362 }
363
364 /// Get the name of the item the expression is in, if available.
365 pub fn get_item_name(cx: &LateContext<'_, '_>, expr: &Expr) -> Option<Name> {
366     let parent_id = cx.tcx.hir().get_parent(expr.id);
367     match cx.tcx.hir().find(parent_id) {
368         Some(Node::Item(&Item { ref ident, .. })) => Some(ident.name),
369         Some(Node::TraitItem(&TraitItem { ident, .. })) | Some(Node::ImplItem(&ImplItem { ident, .. })) => {
370             Some(ident.name)
371         },
372         _ => None,
373     }
374 }
375
376 /// Get the name of a `Pat`, if any
377 pub fn get_pat_name(pat: &Pat) -> Option<Name> {
378     match pat.node {
379         PatKind::Binding(_, _, ref spname, _) => Some(spname.name),
380         PatKind::Path(ref qpath) => single_segment_path(qpath).map(|ps| ps.ident.name),
381         PatKind::Box(ref p) | PatKind::Ref(ref p, _) => get_pat_name(&*p),
382         _ => None,
383     }
384 }
385
386 struct ContainsName {
387     name: Name,
388     result: bool,
389 }
390
391 impl<'tcx> Visitor<'tcx> for ContainsName {
392     fn visit_name(&mut self, _: Span, name: Name) {
393         if self.name == name {
394             self.result = true;
395         }
396     }
397     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
398         NestedVisitorMap::None
399     }
400 }
401
402 /// check if an `Expr` contains a certain name
403 pub fn contains_name(name: Name, expr: &Expr) -> bool {
404     let mut cn = ContainsName { name, result: false };
405     cn.visit_expr(expr);
406     cn.result
407 }
408
409 /// Convert a span to a code snippet if available, otherwise use default.
410 ///
411 /// This is useful if you want to provide suggestions for your lint or more generally, if you want
412 /// to convert a given `Span` to a `str`.
413 ///
414 /// # Example
415 /// ```rust,ignore
416 /// snippet(cx, expr.span, "..")
417 /// ```
418 pub fn snippet<'a, 'b, T: LintContext<'b>>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
419     snippet_opt(cx, span).map_or_else(|| Cow::Borrowed(default), From::from)
420 }
421
422 /// Same as `snippet`, but it adapts the applicability level by following rules:
423 ///
424 /// - Applicability level `Unspecified` will never be changed.
425 /// - If the span is inside a macro, change the applicability level to `MaybeIncorrect`.
426 /// - If the default value is used and the applicability level is `MachineApplicable`, change it to
427 /// `HasPlaceholders`
428 pub fn snippet_with_applicability<'a, 'b, T: LintContext<'b>>(
429     cx: &T,
430     span: Span,
431     default: &'a str,
432     applicability: &mut Applicability,
433 ) -> Cow<'a, str> {
434     if *applicability != Applicability::Unspecified && in_macro(span) {
435         *applicability = Applicability::MaybeIncorrect;
436     }
437     snippet_opt(cx, span).map_or_else(
438         || {
439             if *applicability == Applicability::MachineApplicable {
440                 *applicability = Applicability::HasPlaceholders;
441             }
442             Cow::Borrowed(default)
443         },
444         From::from,
445     )
446 }
447
448 /// Same as `snippet`, but should only be used when it's clear that the input span is
449 /// not a macro argument.
450 pub fn snippet_with_macro_callsite<'a, 'b, T: LintContext<'b>>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
451     snippet(cx, span.source_callsite(), default)
452 }
453
454 /// Convert a span to a code snippet. Returns `None` if not available.
455 pub fn snippet_opt<'a, T: LintContext<'a>>(cx: &T, span: Span) -> Option<String> {
456     cx.sess().source_map().span_to_snippet(span).ok()
457 }
458
459 /// Convert a span (from a block) to a code snippet if available, otherwise use
460 /// default.
461 /// This trims the code of indentation, except for the first line. Use it for
462 /// blocks or block-like
463 /// things which need to be printed as such.
464 ///
465 /// # Example
466 /// ```rust,ignore
467 /// snippet_block(cx, expr.span, "..")
468 /// ```
469 pub fn snippet_block<'a, 'b, T: LintContext<'b>>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
470     let snip = snippet(cx, span, default);
471     trim_multiline(snip, true)
472 }
473
474 /// Same as `snippet_block`, but adapts the applicability level by the rules of
475 /// `snippet_with_applicabiliy`.
476 pub fn snippet_block_with_applicability<'a, 'b, T: LintContext<'b>>(
477     cx: &T,
478     span: Span,
479     default: &'a str,
480     applicability: &mut Applicability,
481 ) -> Cow<'a, str> {
482     let snip = snippet_with_applicability(cx, span, default, applicability);
483     trim_multiline(snip, true)
484 }
485
486 /// Returns a new Span that covers the full last line of the given Span
487 pub fn last_line_of_span<'a, T: LintContext<'a>>(cx: &T, span: Span) -> Span {
488     let source_map_and_line = cx.sess().source_map().lookup_line(span.lo()).unwrap();
489     let line_no = source_map_and_line.line;
490     let line_start = &source_map_and_line.sf.lines[line_no];
491     Span::new(*line_start, span.hi(), span.ctxt())
492 }
493
494 /// Like `snippet_block`, but add braces if the expr is not an `ExprKind::Block`.
495 /// Also takes an `Option<String>` which can be put inside the braces.
496 pub fn expr_block<'a, 'b, T: LintContext<'b>>(
497     cx: &T,
498     expr: &Expr,
499     option: Option<String>,
500     default: &'a str,
501 ) -> Cow<'a, str> {
502     let code = snippet_block(cx, expr.span, default);
503     let string = option.unwrap_or_default();
504     if in_macro(expr.span) {
505         Cow::Owned(format!("{{ {} }}", snippet_with_macro_callsite(cx, expr.span, default)))
506     } else if let ExprKind::Block(_, _) = expr.node {
507         Cow::Owned(format!("{}{}", code, string))
508     } else if string.is_empty() {
509         Cow::Owned(format!("{{ {} }}", code))
510     } else {
511         Cow::Owned(format!("{{\n{};\n{}\n}}", code, string))
512     }
513 }
514
515 /// Trim indentation from a multiline string with possibility of ignoring the
516 /// first line.
517 pub fn trim_multiline(s: Cow<'_, str>, ignore_first: bool) -> Cow<'_, str> {
518     let s_space = trim_multiline_inner(s, ignore_first, ' ');
519     let s_tab = trim_multiline_inner(s_space, ignore_first, '\t');
520     trim_multiline_inner(s_tab, ignore_first, ' ')
521 }
522
523 fn trim_multiline_inner(s: Cow<'_, str>, ignore_first: bool, ch: char) -> Cow<'_, str> {
524     let x = s
525         .lines()
526         .skip(ignore_first as usize)
527         .filter_map(|l| {
528             if l.is_empty() {
529                 None
530             } else {
531                 // ignore empty lines
532                 Some(l.char_indices().find(|&(_, x)| x != ch).unwrap_or((l.len(), ch)).0)
533             }
534         })
535         .min()
536         .unwrap_or(0);
537     if x > 0 {
538         Cow::Owned(
539             s.lines()
540                 .enumerate()
541                 .map(|(i, l)| {
542                     if (ignore_first && i == 0) || l.is_empty() {
543                         l
544                     } else {
545                         l.split_at(x).1
546                     }
547                 })
548                 .collect::<Vec<_>>()
549                 .join("\n"),
550         )
551     } else {
552         s
553     }
554 }
555
556 /// Get a parent expressions if any â€“ this is useful to constrain a lint.
557 pub fn get_parent_expr<'c>(cx: &'c LateContext<'_, '_>, e: &Expr) -> Option<&'c Expr> {
558     let map = &cx.tcx.hir();
559     let node_id: NodeId = e.id;
560     let parent_id: NodeId = map.get_parent_node(node_id);
561     if node_id == parent_id {
562         return None;
563     }
564     map.find(parent_id).and_then(|node| {
565         if let Node::Expr(parent) = node {
566             Some(parent)
567         } else {
568             None
569         }
570     })
571 }
572
573 pub fn get_enclosing_block<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, node: NodeId) -> Option<&'tcx Block> {
574     let map = &cx.tcx.hir();
575     let enclosing_node = map
576         .get_enclosing_scope(node)
577         .and_then(|enclosing_id| map.find(enclosing_id));
578     if let Some(node) = enclosing_node {
579         match node {
580             Node::Block(block) => Some(block),
581             Node::Item(&Item {
582                 node: ItemKind::Fn(_, _, _, eid),
583                 ..
584             })
585             | Node::ImplItem(&ImplItem {
586                 node: ImplItemKind::Method(_, eid),
587                 ..
588             }) => match cx.tcx.hir().body(eid).value.node {
589                 ExprKind::Block(ref block, _) => Some(block),
590                 _ => None,
591             },
592             _ => None,
593         }
594     } else {
595         None
596     }
597 }
598
599 pub struct DiagnosticWrapper<'a>(pub DiagnosticBuilder<'a>);
600
601 impl<'a> Drop for DiagnosticWrapper<'a> {
602     fn drop(&mut self) {
603         self.0.emit();
604     }
605 }
606
607 impl<'a> DiagnosticWrapper<'a> {
608     fn docs_link(&mut self, lint: &'static Lint) {
609         if env::var("CLIPPY_DISABLE_DOCS_LINKS").is_err() {
610             self.0.help(&format!(
611                 "for further information visit https://rust-lang.github.io/rust-clippy/{}/index.html#{}",
612                 &option_env!("RUST_RELEASE_NUM").map_or("master".to_string(), |n| {
613                     // extract just major + minor version and ignore patch versions
614                     format!("rust-{}", n.rsplitn(2, '.').nth(1).unwrap())
615                 }),
616                 lint.name_lower().replacen("clippy::", "", 1)
617             ));
618         }
619     }
620 }
621
622 pub fn span_lint<'a, T: LintContext<'a>>(cx: &T, lint: &'static Lint, sp: Span, msg: &str) {
623     DiagnosticWrapper(cx.struct_span_lint(lint, sp, msg)).docs_link(lint);
624 }
625
626 pub fn span_help_and_lint<'a, 'tcx: 'a, T: LintContext<'tcx>>(
627     cx: &'a T,
628     lint: &'static Lint,
629     span: Span,
630     msg: &str,
631     help: &str,
632 ) {
633     let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, span, msg));
634     db.0.help(help);
635     db.docs_link(lint);
636 }
637
638 pub fn span_note_and_lint<'a, 'tcx: 'a, T: LintContext<'tcx>>(
639     cx: &'a T,
640     lint: &'static Lint,
641     span: Span,
642     msg: &str,
643     note_span: Span,
644     note: &str,
645 ) {
646     let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, span, msg));
647     if note_span == span {
648         db.0.note(note);
649     } else {
650         db.0.span_note(note_span, note);
651     }
652     db.docs_link(lint);
653 }
654
655 pub fn span_lint_and_then<'a, 'tcx: 'a, T: LintContext<'tcx>, F>(
656     cx: &'a T,
657     lint: &'static Lint,
658     sp: Span,
659     msg: &str,
660     f: F,
661 ) where
662     F: for<'b> FnOnce(&mut DiagnosticBuilder<'b>),
663 {
664     let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, sp, msg));
665     f(&mut db.0);
666     db.docs_link(lint);
667 }
668
669 pub fn span_lint_node(cx: &LateContext<'_, '_>, lint: &'static Lint, node: NodeId, sp: Span, msg: &str) {
670     DiagnosticWrapper(cx.tcx.struct_span_lint_node(lint, node, sp, msg)).docs_link(lint);
671 }
672
673 pub fn span_lint_node_and_then(
674     cx: &LateContext<'_, '_>,
675     lint: &'static Lint,
676     node: NodeId,
677     sp: Span,
678     msg: &str,
679     f: impl FnOnce(&mut DiagnosticBuilder<'_>),
680 ) {
681     let mut db = DiagnosticWrapper(cx.tcx.struct_span_lint_node(lint, node, sp, msg));
682     f(&mut db.0);
683     db.docs_link(lint);
684 }
685
686 /// Add a span lint with a suggestion on how to fix it.
687 ///
688 /// These suggestions can be parsed by rustfix to allow it to automatically fix your code.
689 /// In the example below, `help` is `"try"` and `sugg` is the suggested replacement `".any(|x| x >
690 /// 2)"`.
691 ///
692 /// ```ignore
693 /// error: This `.fold` can be more succinctly expressed as `.any`
694 /// --> $DIR/methods.rs:390:13
695 ///     |
696 /// 390 |     let _ = (0..3).fold(false, |acc, x| acc || x > 2);
697 ///     |                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `.any(|x| x > 2)`
698 ///     |
699 ///     = note: `-D fold-any` implied by `-D warnings`
700 /// ```
701 pub fn span_lint_and_sugg<'a, 'tcx: 'a, T: LintContext<'tcx>>(
702     cx: &'a T,
703     lint: &'static Lint,
704     sp: Span,
705     msg: &str,
706     help: &str,
707     sugg: String,
708     applicability: Applicability,
709 ) {
710     span_lint_and_then(cx, lint, sp, msg, |db| {
711         db.span_suggestion(sp, help, sugg, applicability);
712     });
713 }
714
715 /// Create a suggestion made from several `span â†’ replacement`.
716 ///
717 /// Note: in the JSON format (used by `compiletest_rs`), the help message will
718 /// appear once per
719 /// replacement. In human-readable format though, it only appears once before
720 /// the whole suggestion.
721 pub fn multispan_sugg<I>(db: &mut DiagnosticBuilder<'_>, help_msg: String, sugg: I)
722 where
723     I: IntoIterator<Item = (Span, String)>,
724 {
725     let sugg = CodeSuggestion {
726         substitutions: vec![Substitution {
727             parts: sugg
728                 .into_iter()
729                 .map(|(span, snippet)| SubstitutionPart { snippet, span })
730                 .collect(),
731         }],
732         msg: help_msg,
733         show_code_when_inline: true,
734         applicability: Applicability::Unspecified,
735     };
736     db.suggestions.push(sugg);
737 }
738
739 /// Return the base type for HIR references and pointers.
740 pub fn walk_ptrs_hir_ty(ty: &hir::Ty) -> &hir::Ty {
741     match ty.node {
742         TyKind::Ptr(ref mut_ty) | TyKind::Rptr(_, ref mut_ty) => walk_ptrs_hir_ty(&mut_ty.ty),
743         _ => ty,
744     }
745 }
746
747 /// Return the base type for references and raw pointers.
748 pub fn walk_ptrs_ty(ty: Ty<'_>) -> Ty<'_> {
749     match ty.sty {
750         ty::Ref(_, ty, _) => walk_ptrs_ty(ty),
751         _ => ty,
752     }
753 }
754
755 /// Return the base type for references and raw pointers, and count reference
756 /// depth.
757 pub fn walk_ptrs_ty_depth(ty: Ty<'_>) -> (Ty<'_>, usize) {
758     fn inner(ty: Ty<'_>, depth: usize) -> (Ty<'_>, usize) {
759         match ty.sty {
760             ty::Ref(_, ty, _) => inner(ty, depth + 1),
761             _ => (ty, depth),
762         }
763     }
764     inner(ty, 0)
765 }
766
767 /// Check whether the given expression is a constant literal of the given value.
768 pub fn is_integer_literal(expr: &Expr, value: u128) -> bool {
769     // FIXME: use constant folding
770     if let ExprKind::Lit(ref spanned) = expr.node {
771         if let LitKind::Int(v, _) = spanned.node {
772             return v == value;
773         }
774     }
775     false
776 }
777
778 /// Returns `true` if the given `Expr` has been coerced before.
779 ///
780 /// Examples of coercions can be found in the Nomicon at
781 /// <https://doc.rust-lang.org/nomicon/coercions.html>.
782 ///
783 /// See `rustc::ty::adjustment::Adjustment` and `rustc_typeck::check::coercion` for more
784 /// information on adjustments and coercions.
785 pub fn is_adjusted(cx: &LateContext<'_, '_>, e: &Expr) -> bool {
786     cx.tables.adjustments().get(e.hir_id).is_some()
787 }
788
789 pub struct LimitStack {
790     stack: Vec<u64>,
791 }
792
793 impl Drop for LimitStack {
794     fn drop(&mut self) {
795         assert_eq!(self.stack.len(), 1);
796     }
797 }
798
799 impl LimitStack {
800     pub fn new(limit: u64) -> Self {
801         Self { stack: vec![limit] }
802     }
803     pub fn limit(&self) -> u64 {
804         *self.stack.last().expect("there should always be a value in the stack")
805     }
806     pub fn push_attrs(&mut self, sess: &Session, attrs: &[ast::Attribute], name: &'static str) {
807         let stack = &mut self.stack;
808         parse_attrs(sess, attrs, name, |val| stack.push(val));
809     }
810     pub fn pop_attrs(&mut self, sess: &Session, attrs: &[ast::Attribute], name: &'static str) {
811         let stack = &mut self.stack;
812         parse_attrs(sess, attrs, name, |val| assert_eq!(stack.pop(), Some(val)));
813     }
814 }
815
816 pub fn get_attr<'a>(attrs: &'a [ast::Attribute], name: &'static str) -> impl Iterator<Item = &'a ast::Attribute> {
817     attrs.iter().filter(move |attr| {
818         attr.path.segments.len() == 2
819             && attr.path.segments[0].ident.to_string() == "clippy"
820             && attr.path.segments[1].ident.to_string() == name
821     })
822 }
823
824 fn parse_attrs<F: FnMut(u64)>(sess: &Session, attrs: &[ast::Attribute], name: &'static str, mut f: F) {
825     for attr in get_attr(attrs, name) {
826         if let Some(ref value) = attr.value_str() {
827             if let Ok(value) = FromStr::from_str(&value.as_str()) {
828                 f(value)
829             } else {
830                 sess.span_err(attr.span, "not a number");
831             }
832         } else {
833             sess.span_err(attr.span, "bad clippy attribute");
834         }
835     }
836 }
837
838 /// Return the pre-expansion span if is this comes from an expansion of the
839 /// macro `name`.
840 /// See also `is_direct_expn_of`.
841 pub fn is_expn_of(mut span: Span, name: &str) -> Option<Span> {
842     loop {
843         let span_name_span = span
844             .ctxt()
845             .outer()
846             .expn_info()
847             .map(|ei| (ei.format.name(), ei.call_site));
848
849         match span_name_span {
850             Some((mac_name, new_span)) if mac_name == name => return Some(new_span),
851             None => return None,
852             Some((_, new_span)) => span = new_span,
853         }
854     }
855 }
856
857 /// Return the pre-expansion span if is this directly comes from an expansion
858 /// of the macro `name`.
859 /// The difference with `is_expn_of` is that in
860 /// ```rust,ignore
861 /// foo!(bar!(42));
862 /// ```
863 /// `42` is considered expanded from `foo!` and `bar!` by `is_expn_of` but only
864 /// `bar!` by
865 /// `is_direct_expn_of`.
866 pub fn is_direct_expn_of(span: Span, name: &str) -> Option<Span> {
867     let span_name_span = span
868         .ctxt()
869         .outer()
870         .expn_info()
871         .map(|ei| (ei.format.name(), ei.call_site));
872
873     match span_name_span {
874         Some((mac_name, new_span)) if mac_name == name => Some(new_span),
875         _ => None,
876     }
877 }
878
879 /// Convenience function to get the return type of a function
880 pub fn return_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, fn_item: NodeId) -> Ty<'tcx> {
881     let fn_def_id = cx.tcx.hir().local_def_id(fn_item);
882     let ret_ty = cx.tcx.fn_sig(fn_def_id).output();
883     cx.tcx.erase_late_bound_regions(&ret_ty)
884 }
885
886 /// Check if two types are the same.
887 ///
888 /// This discards any lifetime annotations, too.
889 // FIXME: this works correctly for lifetimes bounds (`for <'a> Foo<'a>` == `for
890 // <'b> Foo<'b>` but
891 // not for type parameters.
892 pub fn same_tys<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
893     let a = cx.tcx.erase_late_bound_regions(&Binder::bind(a));
894     let b = cx.tcx.erase_late_bound_regions(&Binder::bind(b));
895     cx.tcx
896         .infer_ctxt()
897         .enter(|infcx| infcx.can_eq(cx.param_env, a, b).is_ok())
898 }
899
900 /// Return whether the given type is an `unsafe` function.
901 pub fn type_is_unsafe_function<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
902     match ty.sty {
903         ty::FnDef(..) | ty::FnPtr(_) => ty.fn_sig(cx.tcx).unsafety() == Unsafety::Unsafe,
904         _ => false,
905     }
906 }
907
908 pub fn is_copy<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
909     ty.is_copy_modulo_regions(cx.tcx.global_tcx(), cx.param_env, DUMMY_SP)
910 }
911
912 /// Return whether a pattern is refutable.
913 pub fn is_refutable(cx: &LateContext<'_, '_>, pat: &Pat) -> bool {
914     fn is_enum_variant(cx: &LateContext<'_, '_>, qpath: &QPath, id: HirId) -> bool {
915         matches!(
916             cx.tables.qpath_def(qpath, id),
917             def::Def::Variant(..) | def::Def::VariantCtor(..)
918         )
919     }
920
921     fn are_refutable<'a, I: Iterator<Item = &'a Pat>>(cx: &LateContext<'_, '_>, mut i: I) -> bool {
922         i.any(|pat| is_refutable(cx, pat))
923     }
924
925     match pat.node {
926         PatKind::Binding(..) | PatKind::Wild => false,
927         PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => is_refutable(cx, pat),
928         PatKind::Lit(..) | PatKind::Range(..) => true,
929         PatKind::Path(ref qpath) => is_enum_variant(cx, qpath, pat.hir_id),
930         PatKind::Tuple(ref pats, _) => are_refutable(cx, pats.iter().map(|pat| &**pat)),
931         PatKind::Struct(ref qpath, ref fields, _) => {
932             if is_enum_variant(cx, qpath, pat.hir_id) {
933                 true
934             } else {
935                 are_refutable(cx, fields.iter().map(|field| &*field.node.pat))
936             }
937         },
938         PatKind::TupleStruct(ref qpath, ref pats, _) => {
939             if is_enum_variant(cx, qpath, pat.hir_id) {
940                 true
941             } else {
942                 are_refutable(cx, pats.iter().map(|pat| &**pat))
943             }
944         },
945         PatKind::Slice(ref head, ref middle, ref tail) => {
946             are_refutable(cx, head.iter().chain(middle).chain(tail.iter()).map(|pat| &**pat))
947         },
948     }
949 }
950
951 /// Checks for the `#[automatically_derived]` attribute all `#[derive]`d
952 /// implementations have.
953 pub fn is_automatically_derived(attrs: &[ast::Attribute]) -> bool {
954     attr::contains_name(attrs, "automatically_derived")
955 }
956
957 /// Remove blocks around an expression.
958 ///
959 /// Ie. `x`, `{ x }` and `{{{{ x }}}}` all give `x`. `{ x; y }` and `{}` return
960 /// themselves.
961 pub fn remove_blocks(expr: &Expr) -> &Expr {
962     if let ExprKind::Block(ref block, _) = expr.node {
963         if block.stmts.is_empty() {
964             if let Some(ref expr) = block.expr {
965                 remove_blocks(expr)
966             } else {
967                 expr
968             }
969         } else {
970             expr
971         }
972     } else {
973         expr
974     }
975 }
976
977 pub fn opt_def_id(def: Def) -> Option<DefId> {
978     match def {
979         Def::Fn(id)
980         | Def::Mod(id)
981         | Def::Static(id, _)
982         | Def::Variant(id)
983         | Def::VariantCtor(id, ..)
984         | Def::Enum(id)
985         | Def::TyAlias(id)
986         | Def::AssociatedTy(id)
987         | Def::TyParam(id)
988         | Def::ForeignTy(id)
989         | Def::Struct(id)
990         | Def::StructCtor(id, ..)
991         | Def::Union(id)
992         | Def::Trait(id)
993         | Def::TraitAlias(id)
994         | Def::Method(id)
995         | Def::Const(id)
996         | Def::AssociatedConst(id)
997         | Def::Macro(id, ..)
998         | Def::Existential(id)
999         | Def::AssociatedExistential(id)
1000         | Def::SelfCtor(id) => Some(id),
1001
1002         Def::Upvar(..)
1003         | Def::Local(_)
1004         | Def::Label(..)
1005         | Def::PrimTy(..)
1006         | Def::SelfTy(..)
1007         | Def::ToolMod
1008         | Def::NonMacroAttr { .. }
1009         | Def::Err => None,
1010     }
1011 }
1012
1013 pub fn is_self(slf: &Arg) -> bool {
1014     if let PatKind::Binding(_, _, name, _) = slf.pat.node {
1015         name.name == keywords::SelfLower.name()
1016     } else {
1017         false
1018     }
1019 }
1020
1021 pub fn is_self_ty(slf: &hir::Ty) -> bool {
1022     if_chain! {
1023         if let TyKind::Path(ref qp) = slf.node;
1024         if let QPath::Resolved(None, ref path) = *qp;
1025         if let Def::SelfTy(..) = path.def;
1026         then {
1027             return true
1028         }
1029     }
1030     false
1031 }
1032
1033 pub fn iter_input_pats<'tcx>(decl: &FnDecl, body: &'tcx Body) -> impl Iterator<Item = &'tcx Arg> {
1034     (0..decl.inputs.len()).map(move |i| &body.arguments[i])
1035 }
1036
1037 /// Check if a given expression is a match expression
1038 /// expanded from `?` operator or `try` macro.
1039 pub fn is_try(expr: &Expr) -> Option<&Expr> {
1040     fn is_ok(arm: &Arm) -> bool {
1041         if_chain! {
1042             if let PatKind::TupleStruct(ref path, ref pat, None) = arm.pats[0].node;
1043             if match_qpath(path, &paths::RESULT_OK[1..]);
1044             if let PatKind::Binding(_, defid, _, None) = pat[0].node;
1045             if let ExprKind::Path(QPath::Resolved(None, ref path)) = arm.body.node;
1046             if let Def::Local(lid) = path.def;
1047             if lid == defid;
1048             then {
1049                 return true;
1050             }
1051         }
1052         false
1053     }
1054
1055     fn is_err(arm: &Arm) -> bool {
1056         if let PatKind::TupleStruct(ref path, _, _) = arm.pats[0].node {
1057             match_qpath(path, &paths::RESULT_ERR[1..])
1058         } else {
1059             false
1060         }
1061     }
1062
1063     if let ExprKind::Match(_, ref arms, ref source) = expr.node {
1064         // desugared from a `?` operator
1065         if let MatchSource::TryDesugar = *source {
1066             return Some(expr);
1067         }
1068
1069         if_chain! {
1070             if arms.len() == 2;
1071             if arms[0].pats.len() == 1 && arms[0].guard.is_none();
1072             if arms[1].pats.len() == 1 && arms[1].guard.is_none();
1073             if (is_ok(&arms[0]) && is_err(&arms[1])) ||
1074                 (is_ok(&arms[1]) && is_err(&arms[0]));
1075             then {
1076                 return Some(expr);
1077             }
1078         }
1079     }
1080
1081     None
1082 }
1083
1084 /// Returns true if the lint is allowed in the current context
1085 ///
1086 /// Useful for skipping long running code when it's unnecessary
1087 pub fn is_allowed(cx: &LateContext<'_, '_>, lint: &'static Lint, id: NodeId) -> bool {
1088     cx.tcx.lint_level_at_node(lint, id).0 == Level::Allow
1089 }
1090
1091 pub fn get_arg_name(pat: &Pat) -> Option<ast::Name> {
1092     match pat.node {
1093         PatKind::Binding(_, _, ident, None) => Some(ident.name),
1094         PatKind::Ref(ref subpat, _) => get_arg_name(subpat),
1095         _ => None,
1096     }
1097 }
1098
1099 pub fn int_bits(tcx: TyCtxt<'_, '_, '_>, ity: ast::IntTy) -> u64 {
1100     layout::Integer::from_attr(&tcx, attr::IntType::SignedInt(ity))
1101         .size()
1102         .bits()
1103 }
1104
1105 #[allow(clippy::cast_possible_wrap)]
1106 /// Turn a constant int byte representation into an i128
1107 pub fn sext(tcx: TyCtxt<'_, '_, '_>, u: u128, ity: ast::IntTy) -> i128 {
1108     let amt = 128 - int_bits(tcx, ity);
1109     ((u as i128) << amt) >> amt
1110 }
1111
1112 #[allow(clippy::cast_sign_loss)]
1113 /// clip unused bytes
1114 pub fn unsext(tcx: TyCtxt<'_, '_, '_>, u: i128, ity: ast::IntTy) -> u128 {
1115     let amt = 128 - int_bits(tcx, ity);
1116     ((u as u128) << amt) >> amt
1117 }
1118
1119 /// clip unused bytes
1120 pub fn clip(tcx: TyCtxt<'_, '_, '_>, u: u128, ity: ast::UintTy) -> u128 {
1121     let bits = layout::Integer::from_attr(&tcx, attr::IntType::UnsignedInt(ity))
1122         .size()
1123         .bits();
1124     let amt = 128 - bits;
1125     (u << amt) >> amt
1126 }
1127
1128 /// Remove block comments from the given Vec of lines
1129 ///
1130 /// # Examples
1131 ///
1132 /// ```rust,ignore
1133 /// without_block_comments(vec!["/*", "foo", "*/"]);
1134 /// // => vec![]
1135 ///
1136 /// without_block_comments(vec!["bar", "/*", "foo", "*/"]);
1137 /// // => vec!["bar"]
1138 /// ```
1139 pub fn without_block_comments(lines: Vec<&str>) -> Vec<&str> {
1140     let mut without = vec![];
1141
1142     let mut nest_level = 0;
1143
1144     for line in lines {
1145         if line.contains("/*") {
1146             nest_level += 1;
1147             continue;
1148         } else if line.contains("*/") {
1149             nest_level -= 1;
1150             continue;
1151         }
1152
1153         if nest_level == 0 {
1154             without.push(line);
1155         }
1156     }
1157
1158     without
1159 }
1160
1161 pub fn any_parent_is_automatically_derived(tcx: TyCtxt<'_, '_, '_>, node: NodeId) -> bool {
1162     let map = &tcx.hir();
1163     let mut prev_enclosing_node = None;
1164     let mut enclosing_node = node;
1165     while Some(enclosing_node) != prev_enclosing_node {
1166         if is_automatically_derived(map.attrs(enclosing_node)) {
1167             return true;
1168         }
1169         prev_enclosing_node = Some(enclosing_node);
1170         enclosing_node = map.get_parent(enclosing_node);
1171     }
1172     false
1173 }
1174
1175 #[cfg(test)]
1176 mod test {
1177     use super::{trim_multiline, without_block_comments};
1178
1179     #[test]
1180     fn test_trim_multiline_single_line() {
1181         assert_eq!("", trim_multiline("".into(), false));
1182         assert_eq!("...", trim_multiline("...".into(), false));
1183         assert_eq!("...", trim_multiline("    ...".into(), false));
1184         assert_eq!("...", trim_multiline("\t...".into(), false));
1185         assert_eq!("...", trim_multiline("\t\t...".into(), false));
1186     }
1187
1188     #[test]
1189     #[rustfmt::skip]
1190     fn test_trim_multiline_block() {
1191         assert_eq!("\
1192     if x {
1193         y
1194     } else {
1195         z
1196     }", trim_multiline("    if x {
1197             y
1198         } else {
1199             z
1200         }".into(), false));
1201         assert_eq!("\
1202     if x {
1203     \ty
1204     } else {
1205     \tz
1206     }", trim_multiline("    if x {
1207         \ty
1208         } else {
1209         \tz
1210         }".into(), false));
1211     }
1212
1213     #[test]
1214     #[rustfmt::skip]
1215     fn test_trim_multiline_empty_line() {
1216         assert_eq!("\
1217     if x {
1218         y
1219
1220     } else {
1221         z
1222     }", trim_multiline("    if x {
1223             y
1224
1225         } else {
1226             z
1227         }".into(), false));
1228     }
1229
1230     #[test]
1231     fn test_without_block_comments_lines_without_block_comments() {
1232         let result = without_block_comments(vec!["/*", "", "*/"]);
1233         println!("result: {:?}", result);
1234         assert!(result.is_empty());
1235
1236         let result = without_block_comments(vec!["", "/*", "", "*/", "#[crate_type = \"lib\"]", "/*", "", "*/", ""]);
1237         assert_eq!(result, vec!["", "#[crate_type = \"lib\"]", ""]);
1238
1239         let result = without_block_comments(vec!["/* rust", "", "*/"]);
1240         assert!(result.is_empty());
1241
1242         let result = without_block_comments(vec!["/* one-line comment */"]);
1243         assert!(result.is_empty());
1244
1245         let result = without_block_comments(vec!["/* nested", "/* multi-line", "comment", "*/", "test", "*/"]);
1246         assert!(result.is_empty());
1247
1248         let result = without_block_comments(vec!["/* nested /* inline /* comment */ test */ */"]);
1249         assert!(result.is_empty());
1250
1251         let result = without_block_comments(vec!["foo", "bar", "baz"]);
1252         assert_eq!(result, vec!["foo", "bar", "baz"]);
1253     }
1254 }