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