]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/utils/mod.rs
Rollup merge of #81333 - RalfJung:const-err-simplify, r=oli-obk
[rust.git] / src / tools / clippy / clippy_lints / src / utils / mod.rs
1 #[macro_use]
2 pub mod sym_helper;
3
4 #[allow(clippy::module_name_repetitions)]
5 pub mod ast_utils;
6 pub mod attrs;
7 pub mod author;
8 pub mod camel_case;
9 pub mod comparisons;
10 pub mod conf;
11 pub mod constants;
12 mod diagnostics;
13 pub mod eager_or_lazy;
14 pub mod higher;
15 mod hir_utils;
16 pub mod inspector;
17 #[cfg(feature = "internal-lints")]
18 pub mod internal_lints;
19 pub mod numeric_literal;
20 pub mod paths;
21 pub mod ptr;
22 pub mod qualify_min_const_fn;
23 pub mod sugg;
24 pub mod usage;
25 pub mod visitors;
26
27 pub use self::attrs::*;
28 pub use self::diagnostics::*;
29 pub use self::hir_utils::{both, eq_expr_value, over, SpanlessEq, SpanlessHash};
30
31 use std::borrow::Cow;
32 use std::collections::hash_map::Entry;
33 use std::hash::BuildHasherDefault;
34 use std::mem;
35
36 use if_chain::if_chain;
37 use rustc_ast::ast::{self, Attribute, LitKind};
38 use rustc_data_structures::fx::FxHashMap;
39 use rustc_errors::Applicability;
40 use rustc_hir as hir;
41 use rustc_hir::def::{DefKind, Res};
42 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
43 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
44 use rustc_hir::Node;
45 use rustc_hir::{
46     def, Arm, Block, Body, Constness, Crate, Expr, ExprKind, FnDecl, HirId, ImplItem, ImplItemKind, Item, ItemKind,
47     MatchSource, Param, Pat, PatKind, Path, PathSegment, QPath, TraitItem, TraitItemKind, TraitRef, TyKind, Unsafety,
48 };
49 use rustc_infer::infer::TyCtxtInferExt;
50 use rustc_lint::{LateContext, Level, Lint, LintContext};
51 use rustc_middle::hir::map::Map;
52 use rustc_middle::ty::subst::{GenericArg, GenericArgKind};
53 use rustc_middle::ty::{self, layout::IntegerExt, Ty, TyCtxt, TypeFoldable};
54 use rustc_semver::RustcVersion;
55 use rustc_session::Session;
56 use rustc_span::hygiene::{ExpnKind, MacroKind};
57 use rustc_span::source_map::original_sp;
58 use rustc_span::sym;
59 use rustc_span::symbol::{kw, Symbol};
60 use rustc_span::{BytePos, Pos, Span, DUMMY_SP};
61 use rustc_target::abi::Integer;
62 use rustc_trait_selection::traits::query::normalize::AtExt;
63 use smallvec::SmallVec;
64
65 use crate::consts::{constant, Constant};
66
67 pub fn parse_msrv(msrv: &str, sess: Option<&Session>, span: Option<Span>) -> Option<RustcVersion> {
68     if let Ok(version) = RustcVersion::parse(msrv) {
69         return Some(version);
70     } else if let Some(sess) = sess {
71         if let Some(span) = span {
72             sess.span_err(span, &format!("`{}` is not a valid Rust version", msrv));
73         }
74     }
75     None
76 }
77
78 pub fn meets_msrv(msrv: Option<&RustcVersion>, lint_msrv: &RustcVersion) -> bool {
79     msrv.map_or(true, |msrv| msrv.meets(*lint_msrv))
80 }
81
82 macro_rules! extract_msrv_attr {
83     (LateContext) => {
84         extract_msrv_attr!(@LateContext, ());
85     };
86     (EarlyContext) => {
87         extract_msrv_attr!(@EarlyContext);
88     };
89     (@$context:ident$(, $call:tt)?) => {
90         fn enter_lint_attrs(&mut self, cx: &rustc_lint::$context<'tcx>, attrs: &'tcx [rustc_ast::ast::Attribute]) {
91             use $crate::utils::get_unique_inner_attr;
92             match get_unique_inner_attr(cx.sess$($call)?, attrs, "msrv") {
93                 Some(msrv_attr) => {
94                     if let Some(msrv) = msrv_attr.value_str() {
95                         self.msrv = $crate::utils::parse_msrv(
96                             &msrv.to_string(),
97                             Some(cx.sess$($call)?),
98                             Some(msrv_attr.span),
99                         );
100                     } else {
101                         cx.sess$($call)?.span_err(msrv_attr.span, "bad clippy attribute");
102                     }
103                 },
104                 _ => (),
105             }
106         }
107     };
108 }
109
110 /// Returns `true` if the two spans come from differing expansions (i.e., one is
111 /// from a macro and one isn't).
112 #[must_use]
113 pub fn differing_macro_contexts(lhs: Span, rhs: Span) -> bool {
114     rhs.ctxt() != lhs.ctxt()
115 }
116
117 /// Returns `true` if the given `NodeId` is inside a constant context
118 ///
119 /// # Example
120 ///
121 /// ```rust,ignore
122 /// if in_constant(cx, expr.hir_id) {
123 ///     // Do something
124 /// }
125 /// ```
126 pub fn in_constant(cx: &LateContext<'_>, id: HirId) -> bool {
127     let parent_id = cx.tcx.hir().get_parent_item(id);
128     match cx.tcx.hir().get(parent_id) {
129         Node::Item(&Item {
130             kind: ItemKind::Const(..) | ItemKind::Static(..),
131             ..
132         })
133         | Node::TraitItem(&TraitItem {
134             kind: TraitItemKind::Const(..),
135             ..
136         })
137         | Node::ImplItem(&ImplItem {
138             kind: ImplItemKind::Const(..),
139             ..
140         })
141         | Node::AnonConst(_) => true,
142         Node::Item(&Item {
143             kind: ItemKind::Fn(ref sig, ..),
144             ..
145         })
146         | Node::ImplItem(&ImplItem {
147             kind: ImplItemKind::Fn(ref sig, _),
148             ..
149         }) => sig.header.constness == Constness::Const,
150         _ => false,
151     }
152 }
153
154 /// Returns `true` if this `span` was expanded by any macro.
155 #[must_use]
156 pub fn in_macro(span: Span) -> bool {
157     if span.from_expansion() {
158         !matches!(span.ctxt().outer_expn_data().kind, ExpnKind::Desugaring(..))
159     } else {
160         false
161     }
162 }
163
164 // If the snippet is empty, it's an attribute that was inserted during macro
165 // expansion and we want to ignore those, because they could come from external
166 // sources that the user has no control over.
167 // For some reason these attributes don't have any expansion info on them, so
168 // we have to check it this way until there is a better way.
169 pub fn is_present_in_source<T: LintContext>(cx: &T, span: Span) -> bool {
170     if let Some(snippet) = snippet_opt(cx, span) {
171         if snippet.is_empty() {
172             return false;
173         }
174     }
175     true
176 }
177
178 /// Checks if given pattern is a wildcard (`_`)
179 pub fn is_wild<'tcx>(pat: &impl std::ops::Deref<Target = Pat<'tcx>>) -> bool {
180     matches!(pat.kind, PatKind::Wild)
181 }
182
183 /// Checks if type is struct, enum or union type with the given def path.
184 ///
185 /// If the type is a diagnostic item, use `is_type_diagnostic_item` instead.
186 /// If you change the signature, remember to update the internal lint `MatchTypeOnDiagItem`
187 pub fn match_type(cx: &LateContext<'_>, ty: Ty<'_>, path: &[&str]) -> bool {
188     match ty.kind() {
189         ty::Adt(adt, _) => match_def_path(cx, adt.did, path),
190         _ => false,
191     }
192 }
193
194 /// Checks if the type is equal to a diagnostic item
195 ///
196 /// If you change the signature, remember to update the internal lint `MatchTypeOnDiagItem`
197 pub fn is_type_diagnostic_item(cx: &LateContext<'_>, ty: Ty<'_>, diag_item: Symbol) -> bool {
198     match ty.kind() {
199         ty::Adt(adt, _) => cx.tcx.is_diagnostic_item(diag_item, adt.did),
200         _ => false,
201     }
202 }
203
204 /// Checks if the type is equal to a lang item
205 pub fn is_type_lang_item(cx: &LateContext<'_>, ty: Ty<'_>, lang_item: hir::LangItem) -> bool {
206     match ty.kind() {
207         ty::Adt(adt, _) => cx.tcx.lang_items().require(lang_item).unwrap() == adt.did,
208         _ => false,
209     }
210 }
211
212 /// Checks if the method call given in `expr` belongs to the given trait.
213 pub fn match_trait_method(cx: &LateContext<'_>, expr: &Expr<'_>, path: &[&str]) -> bool {
214     let def_id = cx.typeck_results().type_dependent_def_id(expr.hir_id).unwrap();
215     let trt_id = cx.tcx.trait_of_item(def_id);
216     trt_id.map_or(false, |trt_id| match_def_path(cx, trt_id, path))
217 }
218
219 /// Checks if an expression references a variable of the given name.
220 pub fn match_var(expr: &Expr<'_>, var: Symbol) -> bool {
221     if let ExprKind::Path(QPath::Resolved(None, ref path)) = expr.kind {
222         if let [p] = path.segments {
223             return p.ident.name == var;
224         }
225     }
226     false
227 }
228
229 pub fn last_path_segment<'tcx>(path: &QPath<'tcx>) -> &'tcx PathSegment<'tcx> {
230     match *path {
231         QPath::Resolved(_, ref path) => path.segments.last().expect("A path must have at least one segment"),
232         QPath::TypeRelative(_, ref seg) => seg,
233         QPath::LangItem(..) => panic!("last_path_segment: lang item has no path segments"),
234     }
235 }
236
237 pub fn single_segment_path<'tcx>(path: &QPath<'tcx>) -> Option<&'tcx PathSegment<'tcx>> {
238     match *path {
239         QPath::Resolved(_, ref path) => path.segments.get(0),
240         QPath::TypeRelative(_, ref seg) => Some(seg),
241         QPath::LangItem(..) => None,
242     }
243 }
244
245 /// Matches a `QPath` against a slice of segment string literals.
246 ///
247 /// There is also `match_path` if you are dealing with a `rustc_hir::Path` instead of a
248 /// `rustc_hir::QPath`.
249 ///
250 /// # Examples
251 /// ```rust,ignore
252 /// match_qpath(path, &["std", "rt", "begin_unwind"])
253 /// ```
254 pub fn match_qpath(path: &QPath<'_>, segments: &[&str]) -> bool {
255     match *path {
256         QPath::Resolved(_, ref path) => match_path(path, segments),
257         QPath::TypeRelative(ref ty, ref segment) => match ty.kind {
258             TyKind::Path(ref inner_path) => {
259                 if let [prefix @ .., end] = segments {
260                     if match_qpath(inner_path, prefix) {
261                         return segment.ident.name.as_str() == *end;
262                     }
263                 }
264                 false
265             },
266             _ => false,
267         },
268         QPath::LangItem(..) => false,
269     }
270 }
271
272 /// Matches a `Path` against a slice of segment string literals.
273 ///
274 /// There is also `match_qpath` if you are dealing with a `rustc_hir::QPath` instead of a
275 /// `rustc_hir::Path`.
276 ///
277 /// # Examples
278 ///
279 /// ```rust,ignore
280 /// if match_path(&trait_ref.path, &paths::HASH) {
281 ///     // This is the `std::hash::Hash` trait.
282 /// }
283 ///
284 /// if match_path(ty_path, &["rustc", "lint", "Lint"]) {
285 ///     // This is a `rustc_middle::lint::Lint`.
286 /// }
287 /// ```
288 pub fn match_path(path: &Path<'_>, segments: &[&str]) -> bool {
289     path.segments
290         .iter()
291         .rev()
292         .zip(segments.iter().rev())
293         .all(|(a, b)| a.ident.name.as_str() == *b)
294 }
295
296 /// Matches a `Path` against a slice of segment string literals, e.g.
297 ///
298 /// # Examples
299 /// ```rust,ignore
300 /// match_path_ast(path, &["std", "rt", "begin_unwind"])
301 /// ```
302 pub fn match_path_ast(path: &ast::Path, segments: &[&str]) -> bool {
303     path.segments
304         .iter()
305         .rev()
306         .zip(segments.iter().rev())
307         .all(|(a, b)| a.ident.name.as_str() == *b)
308 }
309
310 /// Gets the definition associated to a path.
311 pub fn path_to_res(cx: &LateContext<'_>, path: &[&str]) -> Option<def::Res> {
312     let crates = cx.tcx.crates();
313     let krate = crates
314         .iter()
315         .find(|&&krate| cx.tcx.crate_name(krate).as_str() == path[0]);
316     if let Some(krate) = krate {
317         let krate = DefId {
318             krate: *krate,
319             index: CRATE_DEF_INDEX,
320         };
321         let mut current_item = None;
322         let mut items = cx.tcx.item_children(krate);
323         let mut path_it = path.iter().skip(1).peekable();
324
325         loop {
326             let segment = match path_it.next() {
327                 Some(segment) => segment,
328                 None => return None,
329             };
330
331             // `get_def_path` seems to generate these empty segments for extern blocks.
332             // We can just ignore them.
333             if segment.is_empty() {
334                 continue;
335             }
336
337             let result = SmallVec::<[_; 8]>::new();
338             for item in mem::replace(&mut items, cx.tcx.arena.alloc_slice(&result)).iter() {
339                 if item.ident.name.as_str() == *segment {
340                     if path_it.peek().is_none() {
341                         return Some(item.res);
342                     }
343
344                     current_item = Some(item);
345                     items = cx.tcx.item_children(item.res.def_id());
346                     break;
347                 }
348             }
349
350             // The segment isn't a child_item.
351             // Try to find it under an inherent impl.
352             if_chain! {
353                 if path_it.peek().is_none();
354                 if let Some(current_item) = current_item;
355                 let item_def_id = current_item.res.def_id();
356                 if cx.tcx.def_kind(item_def_id) == DefKind::Struct;
357                 then {
358                     // Bad `find_map` suggestion. See #4193.
359                     #[allow(clippy::find_map)]
360                     return cx.tcx.inherent_impls(item_def_id).iter()
361                         .flat_map(|&impl_def_id| cx.tcx.item_children(impl_def_id))
362                         .find(|item| item.ident.name.as_str() == *segment)
363                         .map(|item| item.res);
364                 }
365             }
366         }
367     } else {
368         None
369     }
370 }
371
372 /// Convenience function to get the `DefId` of a trait by path.
373 /// It could be a trait or trait alias.
374 pub fn get_trait_def_id(cx: &LateContext<'_>, path: &[&str]) -> Option<DefId> {
375     let res = match path_to_res(cx, path) {
376         Some(res) => res,
377         None => return None,
378     };
379
380     match res {
381         Res::Def(DefKind::Trait | DefKind::TraitAlias, trait_id) => Some(trait_id),
382         Res::Err => unreachable!("this trait resolution is impossible: {:?}", &path),
383         _ => None,
384     }
385 }
386
387 /// Checks whether a type implements a trait.
388 /// See also `get_trait_def_id`.
389 pub fn implements_trait<'tcx>(
390     cx: &LateContext<'tcx>,
391     ty: Ty<'tcx>,
392     trait_id: DefId,
393     ty_params: &[GenericArg<'tcx>],
394 ) -> bool {
395     // Do not check on infer_types to avoid panic in evaluate_obligation.
396     if ty.has_infer_types() {
397         return false;
398     }
399     let ty = cx.tcx.erase_regions(ty);
400     if ty.has_escaping_bound_vars() {
401         return false;
402     }
403     let ty_params = cx.tcx.mk_substs(ty_params.iter());
404     cx.tcx.type_implements_trait((trait_id, ty, ty_params, cx.param_env))
405 }
406
407 /// Gets the `hir::TraitRef` of the trait the given method is implemented for.
408 ///
409 /// Use this if you want to find the `TraitRef` of the `Add` trait in this example:
410 ///
411 /// ```rust
412 /// struct Point(isize, isize);
413 ///
414 /// impl std::ops::Add for Point {
415 ///     type Output = Self;
416 ///
417 ///     fn add(self, other: Self) -> Self {
418 ///         Point(0, 0)
419 ///     }
420 /// }
421 /// ```
422 pub fn trait_ref_of_method<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Option<&'tcx TraitRef<'tcx>> {
423     // Get the implemented trait for the current function
424     let parent_impl = cx.tcx.hir().get_parent_item(hir_id);
425     if_chain! {
426         if parent_impl != hir::CRATE_HIR_ID;
427         if let hir::Node::Item(item) = cx.tcx.hir().get(parent_impl);
428         if let hir::ItemKind::Impl(impl_) = &item.kind;
429         then { return impl_.of_trait.as_ref(); }
430     }
431     None
432 }
433
434 /// Checks whether this type implements `Drop`.
435 pub fn has_drop<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
436     match ty.ty_adt_def() {
437         Some(def) => def.has_dtor(cx.tcx),
438         None => false,
439     }
440 }
441
442 /// Returns the method names and argument list of nested method call expressions that make up
443 /// `expr`. method/span lists are sorted with the most recent call first.
444 pub fn method_calls<'tcx>(
445     expr: &'tcx Expr<'tcx>,
446     max_depth: usize,
447 ) -> (Vec<Symbol>, Vec<&'tcx [Expr<'tcx>]>, Vec<Span>) {
448     let mut method_names = Vec::with_capacity(max_depth);
449     let mut arg_lists = Vec::with_capacity(max_depth);
450     let mut spans = Vec::with_capacity(max_depth);
451
452     let mut current = expr;
453     for _ in 0..max_depth {
454         if let ExprKind::MethodCall(path, span, args, _) = &current.kind {
455             if args.iter().any(|e| e.span.from_expansion()) {
456                 break;
457             }
458             method_names.push(path.ident.name);
459             arg_lists.push(&**args);
460             spans.push(*span);
461             current = &args[0];
462         } else {
463             break;
464         }
465     }
466
467     (method_names, arg_lists, spans)
468 }
469
470 /// Matches an `Expr` against a chain of methods, and return the matched `Expr`s.
471 ///
472 /// For example, if `expr` represents the `.baz()` in `foo.bar().baz()`,
473 /// `method_chain_args(expr, &["bar", "baz"])` will return a `Vec`
474 /// containing the `Expr`s for
475 /// `.bar()` and `.baz()`
476 pub fn method_chain_args<'a>(expr: &'a Expr<'_>, methods: &[&str]) -> Option<Vec<&'a [Expr<'a>]>> {
477     let mut current = expr;
478     let mut matched = Vec::with_capacity(methods.len());
479     for method_name in methods.iter().rev() {
480         // method chains are stored last -> first
481         if let ExprKind::MethodCall(ref path, _, ref args, _) = current.kind {
482             if path.ident.name.as_str() == *method_name {
483                 if args.iter().any(|e| e.span.from_expansion()) {
484                     return None;
485                 }
486                 matched.push(&**args); // build up `matched` backwards
487                 current = &args[0] // go to parent expression
488             } else {
489                 return None;
490             }
491         } else {
492             return None;
493         }
494     }
495     // Reverse `matched` so that it is in the same order as `methods`.
496     matched.reverse();
497     Some(matched)
498 }
499
500 /// Returns `true` if the provided `def_id` is an entrypoint to a program.
501 pub fn is_entrypoint_fn(cx: &LateContext<'_>, def_id: DefId) -> bool {
502     cx.tcx
503         .entry_fn(LOCAL_CRATE)
504         .map_or(false, |(entry_fn_def_id, _)| def_id == entry_fn_def_id.to_def_id())
505 }
506
507 /// Returns `true` if the expression is in the program's `#[panic_handler]`.
508 pub fn is_in_panic_handler(cx: &LateContext<'_>, e: &Expr<'_>) -> bool {
509     let parent = cx.tcx.hir().get_parent_item(e.hir_id);
510     let def_id = cx.tcx.hir().local_def_id(parent).to_def_id();
511     Some(def_id) == cx.tcx.lang_items().panic_impl()
512 }
513
514 /// Gets the name of the item the expression is in, if available.
515 pub fn get_item_name(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<Symbol> {
516     let parent_id = cx.tcx.hir().get_parent_item(expr.hir_id);
517     match cx.tcx.hir().find(parent_id) {
518         Some(
519             Node::Item(Item { ident, .. })
520             | Node::TraitItem(TraitItem { ident, .. })
521             | Node::ImplItem(ImplItem { ident, .. }),
522         ) => Some(ident.name),
523         _ => None,
524     }
525 }
526
527 /// Gets the name of a `Pat`, if any.
528 pub fn get_pat_name(pat: &Pat<'_>) -> Option<Symbol> {
529     match pat.kind {
530         PatKind::Binding(.., ref spname, _) => Some(spname.name),
531         PatKind::Path(ref qpath) => single_segment_path(qpath).map(|ps| ps.ident.name),
532         PatKind::Box(ref p) | PatKind::Ref(ref p, _) => get_pat_name(&*p),
533         _ => None,
534     }
535 }
536
537 struct ContainsName {
538     name: Symbol,
539     result: bool,
540 }
541
542 impl<'tcx> Visitor<'tcx> for ContainsName {
543     type Map = Map<'tcx>;
544
545     fn visit_name(&mut self, _: Span, name: Symbol) {
546         if self.name == name {
547             self.result = true;
548         }
549     }
550     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
551         NestedVisitorMap::None
552     }
553 }
554
555 /// Checks if an `Expr` contains a certain name.
556 pub fn contains_name(name: Symbol, expr: &Expr<'_>) -> bool {
557     let mut cn = ContainsName { name, result: false };
558     cn.visit_expr(expr);
559     cn.result
560 }
561
562 /// Returns `true` if `expr` contains a return expression
563 pub fn contains_return(expr: &hir::Expr<'_>) -> bool {
564     struct RetCallFinder {
565         found: bool,
566     }
567
568     impl<'tcx> hir::intravisit::Visitor<'tcx> for RetCallFinder {
569         type Map = Map<'tcx>;
570
571         fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) {
572             if self.found {
573                 return;
574             }
575             if let hir::ExprKind::Ret(..) = &expr.kind {
576                 self.found = true;
577             } else {
578                 hir::intravisit::walk_expr(self, expr);
579             }
580         }
581
582         fn nested_visit_map(&mut self) -> hir::intravisit::NestedVisitorMap<Self::Map> {
583             hir::intravisit::NestedVisitorMap::None
584         }
585     }
586
587     let mut visitor = RetCallFinder { found: false };
588     visitor.visit_expr(expr);
589     visitor.found
590 }
591
592 struct FindMacroCalls<'a, 'b> {
593     names: &'a [&'b str],
594     result: Vec<Span>,
595 }
596
597 impl<'a, 'b, 'tcx> Visitor<'tcx> for FindMacroCalls<'a, 'b> {
598     type Map = Map<'tcx>;
599
600     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
601         if self.names.iter().any(|fun| is_expn_of(expr.span, fun).is_some()) {
602             self.result.push(expr.span);
603         }
604         // and check sub-expressions
605         intravisit::walk_expr(self, expr);
606     }
607
608     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
609         NestedVisitorMap::None
610     }
611 }
612
613 /// Finds calls of the specified macros in a function body.
614 pub fn find_macro_calls(names: &[&str], body: &Body<'_>) -> Vec<Span> {
615     let mut fmc = FindMacroCalls {
616         names,
617         result: Vec::new(),
618     };
619     fmc.visit_expr(&body.value);
620     fmc.result
621 }
622
623 /// Converts a span to a code snippet if available, otherwise use default.
624 ///
625 /// This is useful if you want to provide suggestions for your lint or more generally, if you want
626 /// to convert a given `Span` to a `str`.
627 ///
628 /// # Example
629 /// ```rust,ignore
630 /// snippet(cx, expr.span, "..")
631 /// ```
632 pub fn snippet<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
633     snippet_opt(cx, span).map_or_else(|| Cow::Borrowed(default), From::from)
634 }
635
636 /// Same as `snippet`, but it adapts the applicability level by following rules:
637 ///
638 /// - Applicability level `Unspecified` will never be changed.
639 /// - If the span is inside a macro, change the applicability level to `MaybeIncorrect`.
640 /// - If the default value is used and the applicability level is `MachineApplicable`, change it to
641 /// `HasPlaceholders`
642 pub fn snippet_with_applicability<'a, T: LintContext>(
643     cx: &T,
644     span: Span,
645     default: &'a str,
646     applicability: &mut Applicability,
647 ) -> Cow<'a, str> {
648     if *applicability != Applicability::Unspecified && span.from_expansion() {
649         *applicability = Applicability::MaybeIncorrect;
650     }
651     snippet_opt(cx, span).map_or_else(
652         || {
653             if *applicability == Applicability::MachineApplicable {
654                 *applicability = Applicability::HasPlaceholders;
655             }
656             Cow::Borrowed(default)
657         },
658         From::from,
659     )
660 }
661
662 /// Same as `snippet`, but should only be used when it's clear that the input span is
663 /// not a macro argument.
664 pub fn snippet_with_macro_callsite<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
665     snippet(cx, span.source_callsite(), default)
666 }
667
668 /// Converts a span to a code snippet. Returns `None` if not available.
669 pub fn snippet_opt<T: LintContext>(cx: &T, span: Span) -> Option<String> {
670     cx.sess().source_map().span_to_snippet(span).ok()
671 }
672
673 /// Converts a span (from a block) to a code snippet if available, otherwise use default.
674 ///
675 /// This trims the code of indentation, except for the first line. Use it for blocks or block-like
676 /// things which need to be printed as such.
677 ///
678 /// The `indent_relative_to` arg can be used, to provide a span, where the indentation of the
679 /// resulting snippet of the given span.
680 ///
681 /// # Example
682 ///
683 /// ```rust,ignore
684 /// snippet_block(cx, block.span, "..", None)
685 /// // where, `block` is the block of the if expr
686 ///     if x {
687 ///         y;
688 ///     }
689 /// // will return the snippet
690 /// {
691 ///     y;
692 /// }
693 /// ```
694 ///
695 /// ```rust,ignore
696 /// snippet_block(cx, block.span, "..", Some(if_expr.span))
697 /// // where, `block` is the block of the if expr
698 ///     if x {
699 ///         y;
700 ///     }
701 /// // will return the snippet
702 /// {
703 ///         y;
704 ///     } // aligned with `if`
705 /// ```
706 /// Note that the first line of the snippet always has 0 indentation.
707 pub fn snippet_block<'a, T: LintContext>(
708     cx: &T,
709     span: Span,
710     default: &'a str,
711     indent_relative_to: Option<Span>,
712 ) -> Cow<'a, str> {
713     let snip = snippet(cx, span, default);
714     let indent = indent_relative_to.and_then(|s| indent_of(cx, s));
715     reindent_multiline(snip, true, indent)
716 }
717
718 /// Same as `snippet_block`, but adapts the applicability level by the rules of
719 /// `snippet_with_applicability`.
720 pub fn snippet_block_with_applicability<'a, T: LintContext>(
721     cx: &T,
722     span: Span,
723     default: &'a str,
724     indent_relative_to: Option<Span>,
725     applicability: &mut Applicability,
726 ) -> Cow<'a, str> {
727     let snip = snippet_with_applicability(cx, span, default, applicability);
728     let indent = indent_relative_to.and_then(|s| indent_of(cx, s));
729     reindent_multiline(snip, true, indent)
730 }
731
732 /// Returns a new Span that extends the original Span to the first non-whitespace char of the first
733 /// line.
734 ///
735 /// ```rust,ignore
736 ///     let x = ();
737 /// //          ^^
738 /// // will be converted to
739 ///     let x = ();
740 /// //  ^^^^^^^^^^
741 /// ```
742 pub fn first_line_of_span<T: LintContext>(cx: &T, span: Span) -> Span {
743     first_char_in_first_line(cx, span).map_or(span, |first_char_pos| span.with_lo(first_char_pos))
744 }
745
746 fn first_char_in_first_line<T: LintContext>(cx: &T, span: Span) -> Option<BytePos> {
747     let line_span = line_span(cx, span);
748     snippet_opt(cx, line_span).and_then(|snip| {
749         snip.find(|c: char| !c.is_whitespace())
750             .map(|pos| line_span.lo() + BytePos::from_usize(pos))
751     })
752 }
753
754 /// Returns the indentation of the line of a span
755 ///
756 /// ```rust,ignore
757 /// let x = ();
758 /// //      ^^ -- will return 0
759 ///     let x = ();
760 /// //          ^^ -- will return 4
761 /// ```
762 pub fn indent_of<T: LintContext>(cx: &T, span: Span) -> Option<usize> {
763     snippet_opt(cx, line_span(cx, span)).and_then(|snip| snip.find(|c: char| !c.is_whitespace()))
764 }
765
766 /// Returns the positon just before rarrow
767 ///
768 /// ```rust,ignore
769 /// fn into(self) -> () {}
770 ///              ^
771 /// // in case of unformatted code
772 /// fn into2(self)-> () {}
773 ///               ^
774 /// fn into3(self)   -> () {}
775 ///               ^
776 /// ```
777 pub fn position_before_rarrow(s: &str) -> Option<usize> {
778     s.rfind("->").map(|rpos| {
779         let mut rpos = rpos;
780         let chars: Vec<char> = s.chars().collect();
781         while rpos > 1 {
782             if let Some(c) = chars.get(rpos - 1) {
783                 if c.is_whitespace() {
784                     rpos -= 1;
785                     continue;
786                 }
787             }
788             break;
789         }
790         rpos
791     })
792 }
793
794 /// Extends the span to the beginning of the spans line, incl. whitespaces.
795 ///
796 /// ```rust,ignore
797 ///        let x = ();
798 /// //             ^^
799 /// // will be converted to
800 ///        let x = ();
801 /// // ^^^^^^^^^^^^^^
802 /// ```
803 fn line_span<T: LintContext>(cx: &T, span: Span) -> Span {
804     let span = original_sp(span, DUMMY_SP);
805     let source_map_and_line = cx.sess().source_map().lookup_line(span.lo()).unwrap();
806     let line_no = source_map_and_line.line;
807     let line_start = source_map_and_line.sf.lines[line_no];
808     Span::new(line_start, span.hi(), span.ctxt())
809 }
810
811 /// Like `snippet_block`, but add braces if the expr is not an `ExprKind::Block`.
812 /// Also takes an `Option<String>` which can be put inside the braces.
813 pub fn expr_block<'a, T: LintContext>(
814     cx: &T,
815     expr: &Expr<'_>,
816     option: Option<String>,
817     default: &'a str,
818     indent_relative_to: Option<Span>,
819 ) -> Cow<'a, str> {
820     let code = snippet_block(cx, expr.span, default, indent_relative_to);
821     let string = option.unwrap_or_default();
822     if expr.span.from_expansion() {
823         Cow::Owned(format!("{{ {} }}", snippet_with_macro_callsite(cx, expr.span, default)))
824     } else if let ExprKind::Block(_, _) = expr.kind {
825         Cow::Owned(format!("{}{}", code, string))
826     } else if string.is_empty() {
827         Cow::Owned(format!("{{ {} }}", code))
828     } else {
829         Cow::Owned(format!("{{\n{};\n{}\n}}", code, string))
830     }
831 }
832
833 /// Reindent a multiline string with possibility of ignoring the first line.
834 #[allow(clippy::needless_pass_by_value)]
835 pub fn reindent_multiline(s: Cow<'_, str>, ignore_first: bool, indent: Option<usize>) -> Cow<'_, str> {
836     let s_space = reindent_multiline_inner(&s, ignore_first, indent, ' ');
837     let s_tab = reindent_multiline_inner(&s_space, ignore_first, indent, '\t');
838     reindent_multiline_inner(&s_tab, ignore_first, indent, ' ').into()
839 }
840
841 fn reindent_multiline_inner(s: &str, ignore_first: bool, indent: Option<usize>, ch: char) -> String {
842     let x = s
843         .lines()
844         .skip(ignore_first as usize)
845         .filter_map(|l| {
846             if l.is_empty() {
847                 None
848             } else {
849                 // ignore empty lines
850                 Some(l.char_indices().find(|&(_, x)| x != ch).unwrap_or((l.len(), ch)).0)
851             }
852         })
853         .min()
854         .unwrap_or(0);
855     let indent = indent.unwrap_or(0);
856     s.lines()
857         .enumerate()
858         .map(|(i, l)| {
859             if (ignore_first && i == 0) || l.is_empty() {
860                 l.to_owned()
861             } else if x > indent {
862                 l.split_at(x - indent).1.to_owned()
863             } else {
864                 " ".repeat(indent - x) + l
865             }
866         })
867         .collect::<Vec<String>>()
868         .join("\n")
869 }
870
871 /// Gets the parent expression, if any â€“- this is useful to constrain a lint.
872 pub fn get_parent_expr<'tcx>(cx: &LateContext<'tcx>, e: &Expr<'_>) -> Option<&'tcx Expr<'tcx>> {
873     let map = &cx.tcx.hir();
874     let hir_id = e.hir_id;
875     let parent_id = map.get_parent_node(hir_id);
876     if hir_id == parent_id {
877         return None;
878     }
879     map.find(parent_id).and_then(|node| {
880         if let Node::Expr(parent) = node {
881             Some(parent)
882         } else {
883             None
884         }
885     })
886 }
887
888 pub fn get_enclosing_block<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Option<&'tcx Block<'tcx>> {
889     let map = &cx.tcx.hir();
890     let enclosing_node = map
891         .get_enclosing_scope(hir_id)
892         .and_then(|enclosing_id| map.find(enclosing_id));
893     enclosing_node.and_then(|node| match node {
894         Node::Block(block) => Some(block),
895         Node::Item(&Item {
896             kind: ItemKind::Fn(_, _, eid),
897             ..
898         })
899         | Node::ImplItem(&ImplItem {
900             kind: ImplItemKind::Fn(_, eid),
901             ..
902         }) => match cx.tcx.hir().body(eid).value.kind {
903             ExprKind::Block(ref block, _) => Some(block),
904             _ => None,
905         },
906         _ => None,
907     })
908 }
909
910 /// Returns the base type for HIR references and pointers.
911 pub fn walk_ptrs_hir_ty<'tcx>(ty: &'tcx hir::Ty<'tcx>) -> &'tcx hir::Ty<'tcx> {
912     match ty.kind {
913         TyKind::Ptr(ref mut_ty) | TyKind::Rptr(_, ref mut_ty) => walk_ptrs_hir_ty(&mut_ty.ty),
914         _ => ty,
915     }
916 }
917
918 /// Returns the base type for references and raw pointers, and count reference
919 /// depth.
920 pub fn walk_ptrs_ty_depth(ty: Ty<'_>) -> (Ty<'_>, usize) {
921     fn inner(ty: Ty<'_>, depth: usize) -> (Ty<'_>, usize) {
922         match ty.kind() {
923             ty::Ref(_, ty, _) => inner(ty, depth + 1),
924             _ => (ty, depth),
925         }
926     }
927     inner(ty, 0)
928 }
929
930 /// Checks whether the given expression is a constant integer of the given value.
931 /// unlike `is_integer_literal`, this version does const folding
932 pub fn is_integer_const(cx: &LateContext<'_>, e: &Expr<'_>, value: u128) -> bool {
933     if is_integer_literal(e, value) {
934         return true;
935     }
936     let map = cx.tcx.hir();
937     let parent_item = map.get_parent_item(e.hir_id);
938     if let Some((Constant::Int(v), _)) = map
939         .maybe_body_owned_by(parent_item)
940         .and_then(|body_id| constant(cx, cx.tcx.typeck_body(body_id), e))
941     {
942         value == v
943     } else {
944         false
945     }
946 }
947
948 /// Checks whether the given expression is a constant literal of the given value.
949 pub fn is_integer_literal(expr: &Expr<'_>, value: u128) -> bool {
950     // FIXME: use constant folding
951     if let ExprKind::Lit(ref spanned) = expr.kind {
952         if let LitKind::Int(v, _) = spanned.node {
953             return v == value;
954         }
955     }
956     false
957 }
958
959 /// Returns `true` if the given `Expr` has been coerced before.
960 ///
961 /// Examples of coercions can be found in the Nomicon at
962 /// <https://doc.rust-lang.org/nomicon/coercions.html>.
963 ///
964 /// See `rustc_middle::ty::adjustment::Adjustment` and `rustc_typeck::check::coercion` for more
965 /// information on adjustments and coercions.
966 pub fn is_adjusted(cx: &LateContext<'_>, e: &Expr<'_>) -> bool {
967     cx.typeck_results().adjustments().get(e.hir_id).is_some()
968 }
969
970 /// Returns the pre-expansion span if is this comes from an expansion of the
971 /// macro `name`.
972 /// See also `is_direct_expn_of`.
973 #[must_use]
974 pub fn is_expn_of(mut span: Span, name: &str) -> Option<Span> {
975     loop {
976         if span.from_expansion() {
977             let data = span.ctxt().outer_expn_data();
978             let new_span = data.call_site;
979
980             if let ExpnKind::Macro(MacroKind::Bang, mac_name) = data.kind {
981                 if mac_name.as_str() == name {
982                     return Some(new_span);
983                 }
984             }
985
986             span = new_span;
987         } else {
988             return None;
989         }
990     }
991 }
992
993 /// Returns the pre-expansion span if the span directly comes from an expansion
994 /// of the macro `name`.
995 /// The difference with `is_expn_of` is that in
996 /// ```rust,ignore
997 /// foo!(bar!(42));
998 /// ```
999 /// `42` is considered expanded from `foo!` and `bar!` by `is_expn_of` but only
1000 /// `bar!` by
1001 /// `is_direct_expn_of`.
1002 #[must_use]
1003 pub fn is_direct_expn_of(span: Span, name: &str) -> Option<Span> {
1004     if span.from_expansion() {
1005         let data = span.ctxt().outer_expn_data();
1006         let new_span = data.call_site;
1007
1008         if let ExpnKind::Macro(MacroKind::Bang, mac_name) = data.kind {
1009             if mac_name.as_str() == name {
1010                 return Some(new_span);
1011             }
1012         }
1013     }
1014
1015     None
1016 }
1017
1018 /// Convenience function to get the return type of a function.
1019 pub fn return_ty<'tcx>(cx: &LateContext<'tcx>, fn_item: hir::HirId) -> Ty<'tcx> {
1020     let fn_def_id = cx.tcx.hir().local_def_id(fn_item);
1021     let ret_ty = cx.tcx.fn_sig(fn_def_id).output();
1022     cx.tcx.erase_late_bound_regions(ret_ty)
1023 }
1024
1025 /// Walks into `ty` and returns `true` if any inner type is the same as `other_ty`
1026 pub fn contains_ty(ty: Ty<'_>, other_ty: Ty<'_>) -> bool {
1027     ty.walk().any(|inner| match inner.unpack() {
1028         GenericArgKind::Type(inner_ty) => ty::TyS::same_type(other_ty, inner_ty),
1029         GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => false,
1030     })
1031 }
1032
1033 /// Returns `true` if the given type is an `unsafe` function.
1034 pub fn type_is_unsafe_function<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
1035     match ty.kind() {
1036         ty::FnDef(..) | ty::FnPtr(_) => ty.fn_sig(cx.tcx).unsafety() == Unsafety::Unsafe,
1037         _ => false,
1038     }
1039 }
1040
1041 pub fn is_copy<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
1042     ty.is_copy_modulo_regions(cx.tcx.at(DUMMY_SP), cx.param_env)
1043 }
1044
1045 /// Checks if an expression is constructing a tuple-like enum variant or struct
1046 pub fn is_ctor_or_promotable_const_function(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
1047     if let ExprKind::Call(ref fun, _) = expr.kind {
1048         if let ExprKind::Path(ref qp) = fun.kind {
1049             let res = cx.qpath_res(qp, fun.hir_id);
1050             return match res {
1051                 def::Res::Def(DefKind::Variant | DefKind::Ctor(..), ..) => true,
1052                 def::Res::Def(_, def_id) => cx.tcx.is_promotable_const_fn(def_id),
1053                 _ => false,
1054             };
1055         }
1056     }
1057     false
1058 }
1059
1060 /// Returns `true` if a pattern is refutable.
1061 // TODO: should be implemented using rustc/mir_build/thir machinery
1062 pub fn is_refutable(cx: &LateContext<'_>, pat: &Pat<'_>) -> bool {
1063     fn is_enum_variant(cx: &LateContext<'_>, qpath: &QPath<'_>, id: HirId) -> bool {
1064         matches!(
1065             cx.qpath_res(qpath, id),
1066             def::Res::Def(DefKind::Variant, ..) | Res::Def(DefKind::Ctor(def::CtorOf::Variant, _), _)
1067         )
1068     }
1069
1070     fn are_refutable<'a, I: Iterator<Item = &'a Pat<'a>>>(cx: &LateContext<'_>, mut i: I) -> bool {
1071         i.any(|pat| is_refutable(cx, pat))
1072     }
1073
1074     match pat.kind {
1075         PatKind::Wild => false,
1076         PatKind::Binding(_, _, _, pat) => pat.map_or(false, |pat| is_refutable(cx, pat)),
1077         PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => is_refutable(cx, pat),
1078         PatKind::Lit(..) | PatKind::Range(..) => true,
1079         PatKind::Path(ref qpath) => is_enum_variant(cx, qpath, pat.hir_id),
1080         PatKind::Or(ref pats) => {
1081             // TODO: should be the honest check, that pats is exhaustive set
1082             are_refutable(cx, pats.iter().map(|pat| &**pat))
1083         },
1084         PatKind::Tuple(ref pats, _) => are_refutable(cx, pats.iter().map(|pat| &**pat)),
1085         PatKind::Struct(ref qpath, ref fields, _) => {
1086             is_enum_variant(cx, qpath, pat.hir_id) || are_refutable(cx, fields.iter().map(|field| &*field.pat))
1087         },
1088         PatKind::TupleStruct(ref qpath, ref pats, _) => {
1089             is_enum_variant(cx, qpath, pat.hir_id) || are_refutable(cx, pats.iter().map(|pat| &**pat))
1090         },
1091         PatKind::Slice(ref head, ref middle, ref tail) => {
1092             match &cx.typeck_results().node_type(pat.hir_id).kind() {
1093                 ty::Slice(..) => {
1094                     // [..] is the only irrefutable slice pattern.
1095                     !head.is_empty() || middle.is_none() || !tail.is_empty()
1096                 },
1097                 ty::Array(..) => are_refutable(cx, head.iter().chain(middle).chain(tail.iter()).map(|pat| &**pat)),
1098                 _ => {
1099                     // unreachable!()
1100                     true
1101                 },
1102             }
1103         },
1104     }
1105 }
1106
1107 /// Checks for the `#[automatically_derived]` attribute all `#[derive]`d
1108 /// implementations have.
1109 pub fn is_automatically_derived(attrs: &[ast::Attribute]) -> bool {
1110     attrs.iter().any(|attr| attr.has_name(sym::automatically_derived))
1111 }
1112
1113 /// Remove blocks around an expression.
1114 ///
1115 /// Ie. `x`, `{ x }` and `{{{{ x }}}}` all give `x`. `{ x; y }` and `{}` return
1116 /// themselves.
1117 pub fn remove_blocks<'tcx>(mut expr: &'tcx Expr<'tcx>) -> &'tcx Expr<'tcx> {
1118     while let ExprKind::Block(ref block, ..) = expr.kind {
1119         match (block.stmts.is_empty(), block.expr.as_ref()) {
1120             (true, Some(e)) => expr = e,
1121             _ => break,
1122         }
1123     }
1124     expr
1125 }
1126
1127 pub fn is_self(slf: &Param<'_>) -> bool {
1128     if let PatKind::Binding(.., name, _) = slf.pat.kind {
1129         name.name == kw::SelfLower
1130     } else {
1131         false
1132     }
1133 }
1134
1135 pub fn is_self_ty(slf: &hir::Ty<'_>) -> bool {
1136     if_chain! {
1137         if let TyKind::Path(ref qp) = slf.kind;
1138         if let QPath::Resolved(None, ref path) = *qp;
1139         if let Res::SelfTy(..) = path.res;
1140         then {
1141             return true
1142         }
1143     }
1144     false
1145 }
1146
1147 pub fn iter_input_pats<'tcx>(decl: &FnDecl<'_>, body: &'tcx Body<'_>) -> impl Iterator<Item = &'tcx Param<'tcx>> {
1148     (0..decl.inputs.len()).map(move |i| &body.params[i])
1149 }
1150
1151 /// Checks if a given expression is a match expression expanded from the `?`
1152 /// operator or the `try` macro.
1153 pub fn is_try<'tcx>(expr: &'tcx Expr<'tcx>) -> Option<&'tcx Expr<'tcx>> {
1154     fn is_ok(arm: &Arm<'_>) -> bool {
1155         if_chain! {
1156             if let PatKind::TupleStruct(ref path, ref pat, None) = arm.pat.kind;
1157             if match_qpath(path, &paths::RESULT_OK[1..]);
1158             if let PatKind::Binding(_, hir_id, _, None) = pat[0].kind;
1159             if let ExprKind::Path(QPath::Resolved(None, ref path)) = arm.body.kind;
1160             if let Res::Local(lid) = path.res;
1161             if lid == hir_id;
1162             then {
1163                 return true;
1164             }
1165         }
1166         false
1167     }
1168
1169     fn is_err(arm: &Arm<'_>) -> bool {
1170         if let PatKind::TupleStruct(ref path, _, _) = arm.pat.kind {
1171             match_qpath(path, &paths::RESULT_ERR[1..])
1172         } else {
1173             false
1174         }
1175     }
1176
1177     if let ExprKind::Match(_, ref arms, ref source) = expr.kind {
1178         // desugared from a `?` operator
1179         if let MatchSource::TryDesugar = *source {
1180             return Some(expr);
1181         }
1182
1183         if_chain! {
1184             if arms.len() == 2;
1185             if arms[0].guard.is_none();
1186             if arms[1].guard.is_none();
1187             if (is_ok(&arms[0]) && is_err(&arms[1])) ||
1188                 (is_ok(&arms[1]) && is_err(&arms[0]));
1189             then {
1190                 return Some(expr);
1191             }
1192         }
1193     }
1194
1195     None
1196 }
1197
1198 /// Returns `true` if the lint is allowed in the current context
1199 ///
1200 /// Useful for skipping long running code when it's unnecessary
1201 pub fn is_allowed(cx: &LateContext<'_>, lint: &'static Lint, id: HirId) -> bool {
1202     cx.tcx.lint_level_at_node(lint, id).0 == Level::Allow
1203 }
1204
1205 pub fn get_arg_name(pat: &Pat<'_>) -> Option<Symbol> {
1206     match pat.kind {
1207         PatKind::Binding(.., ident, None) => Some(ident.name),
1208         PatKind::Ref(ref subpat, _) => get_arg_name(subpat),
1209         _ => None,
1210     }
1211 }
1212
1213 pub fn int_bits(tcx: TyCtxt<'_>, ity: ty::IntTy) -> u64 {
1214     Integer::from_int_ty(&tcx, ity).size().bits()
1215 }
1216
1217 #[allow(clippy::cast_possible_wrap)]
1218 /// Turn a constant int byte representation into an i128
1219 pub fn sext(tcx: TyCtxt<'_>, u: u128, ity: ty::IntTy) -> i128 {
1220     let amt = 128 - int_bits(tcx, ity);
1221     ((u as i128) << amt) >> amt
1222 }
1223
1224 #[allow(clippy::cast_sign_loss)]
1225 /// clip unused bytes
1226 pub fn unsext(tcx: TyCtxt<'_>, u: i128, ity: ty::IntTy) -> u128 {
1227     let amt = 128 - int_bits(tcx, ity);
1228     ((u as u128) << amt) >> amt
1229 }
1230
1231 /// clip unused bytes
1232 pub fn clip(tcx: TyCtxt<'_>, u: u128, ity: ty::UintTy) -> u128 {
1233     let bits = Integer::from_uint_ty(&tcx, ity).size().bits();
1234     let amt = 128 - bits;
1235     (u << amt) >> amt
1236 }
1237
1238 /// Removes block comments from the given `Vec` of lines.
1239 ///
1240 /// # Examples
1241 ///
1242 /// ```rust,ignore
1243 /// without_block_comments(vec!["/*", "foo", "*/"]);
1244 /// // => vec![]
1245 ///
1246 /// without_block_comments(vec!["bar", "/*", "foo", "*/"]);
1247 /// // => vec!["bar"]
1248 /// ```
1249 pub fn without_block_comments(lines: Vec<&str>) -> Vec<&str> {
1250     let mut without = vec![];
1251
1252     let mut nest_level = 0;
1253
1254     for line in lines {
1255         if line.contains("/*") {
1256             nest_level += 1;
1257             continue;
1258         } else if line.contains("*/") {
1259             nest_level -= 1;
1260             continue;
1261         }
1262
1263         if nest_level == 0 {
1264             without.push(line);
1265         }
1266     }
1267
1268     without
1269 }
1270
1271 pub fn any_parent_is_automatically_derived(tcx: TyCtxt<'_>, node: HirId) -> bool {
1272     let map = &tcx.hir();
1273     let mut prev_enclosing_node = None;
1274     let mut enclosing_node = node;
1275     while Some(enclosing_node) != prev_enclosing_node {
1276         if is_automatically_derived(map.attrs(enclosing_node)) {
1277             return true;
1278         }
1279         prev_enclosing_node = Some(enclosing_node);
1280         enclosing_node = map.get_parent_item(enclosing_node);
1281     }
1282     false
1283 }
1284
1285 /// Returns true if ty has `iter` or `iter_mut` methods
1286 pub fn has_iter_method(cx: &LateContext<'_>, probably_ref_ty: Ty<'_>) -> Option<&'static str> {
1287     // FIXME: instead of this hard-coded list, we should check if `<adt>::iter`
1288     // exists and has the desired signature. Unfortunately FnCtxt is not exported
1289     // so we can't use its `lookup_method` method.
1290     let into_iter_collections: [&[&str]; 13] = [
1291         &paths::VEC,
1292         &paths::OPTION,
1293         &paths::RESULT,
1294         &paths::BTREESET,
1295         &paths::BTREEMAP,
1296         &paths::VEC_DEQUE,
1297         &paths::LINKED_LIST,
1298         &paths::BINARY_HEAP,
1299         &paths::HASHSET,
1300         &paths::HASHMAP,
1301         &paths::PATH_BUF,
1302         &paths::PATH,
1303         &paths::RECEIVER,
1304     ];
1305
1306     let ty_to_check = match probably_ref_ty.kind() {
1307         ty::Ref(_, ty_to_check, _) => ty_to_check,
1308         _ => probably_ref_ty,
1309     };
1310
1311     let def_id = match ty_to_check.kind() {
1312         ty::Array(..) => return Some("array"),
1313         ty::Slice(..) => return Some("slice"),
1314         ty::Adt(adt, _) => adt.did,
1315         _ => return None,
1316     };
1317
1318     for path in &into_iter_collections {
1319         if match_def_path(cx, def_id, path) {
1320             return Some(*path.last().unwrap());
1321         }
1322     }
1323     None
1324 }
1325
1326 /// Matches a function call with the given path and returns the arguments.
1327 ///
1328 /// Usage:
1329 ///
1330 /// ```rust,ignore
1331 /// if let Some(args) = match_function_call(cx, cmp_max_call, &paths::CMP_MAX);
1332 /// ```
1333 pub fn match_function_call<'tcx>(
1334     cx: &LateContext<'tcx>,
1335     expr: &'tcx Expr<'_>,
1336     path: &[&str],
1337 ) -> Option<&'tcx [Expr<'tcx>]> {
1338     if_chain! {
1339         if let ExprKind::Call(ref fun, ref args) = expr.kind;
1340         if let ExprKind::Path(ref qpath) = fun.kind;
1341         if let Some(fun_def_id) = cx.qpath_res(qpath, fun.hir_id).opt_def_id();
1342         if match_def_path(cx, fun_def_id, path);
1343         then {
1344             return Some(&args)
1345         }
1346     };
1347     None
1348 }
1349
1350 /// Checks if `Ty` is normalizable. This function is useful
1351 /// to avoid crashes on `layout_of`.
1352 pub fn is_normalizable<'tcx>(cx: &LateContext<'tcx>, param_env: ty::ParamEnv<'tcx>, ty: Ty<'tcx>) -> bool {
1353     cx.tcx.infer_ctxt().enter(|infcx| {
1354         let cause = rustc_middle::traits::ObligationCause::dummy();
1355         infcx.at(&cause, param_env).normalize(ty).is_ok()
1356     })
1357 }
1358
1359 pub fn match_def_path<'tcx>(cx: &LateContext<'tcx>, did: DefId, syms: &[&str]) -> bool {
1360     // We have to convert `syms` to `&[Symbol]` here because rustc's `match_def_path`
1361     // accepts only that. We should probably move to Symbols in Clippy as well.
1362     let syms = syms.iter().map(|p| Symbol::intern(p)).collect::<Vec<Symbol>>();
1363     cx.match_def_path(did, &syms)
1364 }
1365
1366 pub fn match_panic_call<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<&'tcx [Expr<'tcx>]> {
1367     match_function_call(cx, expr, &paths::BEGIN_PANIC)
1368         .or_else(|| match_function_call(cx, expr, &paths::BEGIN_PANIC_FMT))
1369         .or_else(|| match_function_call(cx, expr, &paths::PANIC_ANY))
1370         .or_else(|| match_function_call(cx, expr, &paths::PANICKING_PANIC))
1371         .or_else(|| match_function_call(cx, expr, &paths::PANICKING_PANIC_FMT))
1372         .or_else(|| match_function_call(cx, expr, &paths::PANICKING_PANIC_STR))
1373 }
1374
1375 pub fn match_panic_def_id(cx: &LateContext<'_>, did: DefId) -> bool {
1376     match_def_path(cx, did, &paths::BEGIN_PANIC)
1377         || match_def_path(cx, did, &paths::BEGIN_PANIC_FMT)
1378         || match_def_path(cx, did, &paths::PANIC_ANY)
1379         || match_def_path(cx, did, &paths::PANICKING_PANIC)
1380         || match_def_path(cx, did, &paths::PANICKING_PANIC_FMT)
1381         || match_def_path(cx, did, &paths::PANICKING_PANIC_STR)
1382 }
1383
1384 /// Returns the list of condition expressions and the list of blocks in a
1385 /// sequence of `if/else`.
1386 /// E.g., this returns `([a, b], [c, d, e])` for the expression
1387 /// `if a { c } else if b { d } else { e }`.
1388 pub fn if_sequence<'tcx>(
1389     mut expr: &'tcx Expr<'tcx>,
1390 ) -> (SmallVec<[&'tcx Expr<'tcx>; 1]>, SmallVec<[&'tcx Block<'tcx>; 1]>) {
1391     let mut conds = SmallVec::new();
1392     let mut blocks: SmallVec<[&Block<'_>; 1]> = SmallVec::new();
1393
1394     while let ExprKind::If(ref cond, ref then_expr, ref else_expr) = expr.kind {
1395         conds.push(&**cond);
1396         if let ExprKind::Block(ref block, _) = then_expr.kind {
1397             blocks.push(block);
1398         } else {
1399             panic!("ExprKind::If node is not an ExprKind::Block");
1400         }
1401
1402         if let Some(ref else_expr) = *else_expr {
1403             expr = else_expr;
1404         } else {
1405             break;
1406         }
1407     }
1408
1409     // final `else {..}`
1410     if !blocks.is_empty() {
1411         if let ExprKind::Block(ref block, _) = expr.kind {
1412             blocks.push(&**block);
1413         }
1414     }
1415
1416     (conds, blocks)
1417 }
1418
1419 pub fn parent_node_is_if_expr(expr: &Expr<'_>, cx: &LateContext<'_>) -> bool {
1420     let map = cx.tcx.hir();
1421     let parent_id = map.get_parent_node(expr.hir_id);
1422     let parent_node = map.get(parent_id);
1423     matches!(
1424         parent_node,
1425         Node::Expr(Expr {
1426             kind: ExprKind::If(_, _, _),
1427             ..
1428         })
1429     )
1430 }
1431
1432 // Finds the attribute with the given name, if any
1433 pub fn attr_by_name<'a>(attrs: &'a [Attribute], name: &'_ str) -> Option<&'a Attribute> {
1434     attrs
1435         .iter()
1436         .find(|attr| attr.ident().map_or(false, |ident| ident.as_str() == name))
1437 }
1438
1439 // Finds the `#[must_use]` attribute, if any
1440 pub fn must_use_attr(attrs: &[Attribute]) -> Option<&Attribute> {
1441     attr_by_name(attrs, "must_use")
1442 }
1443
1444 // Returns whether the type has #[must_use] attribute
1445 pub fn is_must_use_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
1446     match ty.kind() {
1447         ty::Adt(ref adt, _) => must_use_attr(&cx.tcx.get_attrs(adt.did)).is_some(),
1448         ty::Foreign(ref did) => must_use_attr(&cx.tcx.get_attrs(*did)).is_some(),
1449         ty::Slice(ref ty)
1450         | ty::Array(ref ty, _)
1451         | ty::RawPtr(ty::TypeAndMut { ref ty, .. })
1452         | ty::Ref(_, ref ty, _) => {
1453             // for the Array case we don't need to care for the len == 0 case
1454             // because we don't want to lint functions returning empty arrays
1455             is_must_use_ty(cx, *ty)
1456         },
1457         ty::Tuple(ref substs) => substs.types().any(|ty| is_must_use_ty(cx, ty)),
1458         ty::Opaque(ref def_id, _) => {
1459             for (predicate, _) in cx.tcx.explicit_item_bounds(*def_id) {
1460                 if let ty::PredicateKind::Trait(trait_predicate, _) = predicate.kind().skip_binder() {
1461                     if must_use_attr(&cx.tcx.get_attrs(trait_predicate.trait_ref.def_id)).is_some() {
1462                         return true;
1463                     }
1464                 }
1465             }
1466             false
1467         },
1468         ty::Dynamic(binder, _) => {
1469             for predicate in binder.iter() {
1470                 if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate.skip_binder() {
1471                     if must_use_attr(&cx.tcx.get_attrs(trait_ref.def_id)).is_some() {
1472                         return true;
1473                     }
1474                 }
1475             }
1476             false
1477         },
1478         _ => false,
1479     }
1480 }
1481
1482 // check if expr is calling method or function with #[must_use] attribute
1483 pub fn is_must_use_func_call(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
1484     let did = match expr.kind {
1485         ExprKind::Call(ref path, _) => if_chain! {
1486             if let ExprKind::Path(ref qpath) = path.kind;
1487             if let def::Res::Def(_, did) = cx.qpath_res(qpath, path.hir_id);
1488             then {
1489                 Some(did)
1490             } else {
1491                 None
1492             }
1493         },
1494         ExprKind::MethodCall(_, _, _, _) => cx.typeck_results().type_dependent_def_id(expr.hir_id),
1495         _ => None,
1496     };
1497
1498     did.map_or(false, |did| must_use_attr(&cx.tcx.get_attrs(did)).is_some())
1499 }
1500
1501 pub fn is_no_std_crate(krate: &Crate<'_>) -> bool {
1502     krate.item.attrs.iter().any(|attr| {
1503         if let ast::AttrKind::Normal(ref attr, _) = attr.kind {
1504             attr.path == sym::no_std
1505         } else {
1506             false
1507         }
1508     })
1509 }
1510
1511 /// Check if parent of a hir node is a trait implementation block.
1512 /// For example, `f` in
1513 /// ```rust,ignore
1514 /// impl Trait for S {
1515 ///     fn f() {}
1516 /// }
1517 /// ```
1518 pub fn is_trait_impl_item(cx: &LateContext<'_>, hir_id: HirId) -> bool {
1519     if let Some(Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_node(hir_id)) {
1520         matches!(item.kind, ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }))
1521     } else {
1522         false
1523     }
1524 }
1525
1526 /// Check if it's even possible to satisfy the `where` clause for the item.
1527 ///
1528 /// `trivial_bounds` feature allows functions with unsatisfiable bounds, for example:
1529 ///
1530 /// ```ignore
1531 /// fn foo() where i32: Iterator {
1532 ///     for _ in 2i32 {}
1533 /// }
1534 /// ```
1535 pub fn fn_has_unsatisfiable_preds(cx: &LateContext<'_>, did: DefId) -> bool {
1536     use rustc_trait_selection::traits;
1537     let predicates =
1538         cx.tcx
1539             .predicates_of(did)
1540             .predicates
1541             .iter()
1542             .filter_map(|(p, _)| if p.is_global() { Some(*p) } else { None });
1543     traits::impossible_predicates(
1544         cx.tcx,
1545         traits::elaborate_predicates(cx.tcx, predicates)
1546             .map(|o| o.predicate)
1547             .collect::<Vec<_>>(),
1548     )
1549 }
1550
1551 /// Returns the `DefId` of the callee if the given expression is a function or method call.
1552 pub fn fn_def_id(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<DefId> {
1553     match &expr.kind {
1554         ExprKind::MethodCall(..) => cx.typeck_results().type_dependent_def_id(expr.hir_id),
1555         ExprKind::Call(
1556             Expr {
1557                 kind: ExprKind::Path(qpath),
1558                 ..
1559             },
1560             ..,
1561         ) => cx.typeck_results().qpath_res(qpath, expr.hir_id).opt_def_id(),
1562         _ => None,
1563     }
1564 }
1565
1566 pub fn run_lints(cx: &LateContext<'_>, lints: &[&'static Lint], id: HirId) -> bool {
1567     lints.iter().any(|lint| {
1568         matches!(
1569             cx.tcx.lint_level_at_node(lint, id),
1570             (Level::Forbid | Level::Deny | Level::Warn, _)
1571         )
1572     })
1573 }
1574
1575 /// Returns true iff the given type is a primitive (a bool or char, any integer or floating-point
1576 /// number type, a str, or an array, slice, or tuple of those types).
1577 pub fn is_recursively_primitive_type(ty: Ty<'_>) -> bool {
1578     match ty.kind() {
1579         ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str => true,
1580         ty::Ref(_, inner, _) if *inner.kind() == ty::Str => true,
1581         ty::Array(inner_type, _) | ty::Slice(inner_type) => is_recursively_primitive_type(inner_type),
1582         ty::Tuple(inner_types) => inner_types.types().all(is_recursively_primitive_type),
1583         _ => false,
1584     }
1585 }
1586
1587 /// Returns Option<String> where String is a textual representation of the type encapsulated in the
1588 /// slice iff the given expression is a slice of primitives (as defined in the
1589 /// `is_recursively_primitive_type` function) and None otherwise.
1590 pub fn is_slice_of_primitives(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<String> {
1591     let expr_type = cx.typeck_results().expr_ty_adjusted(expr);
1592     let expr_kind = expr_type.kind();
1593     let is_primitive = match expr_kind {
1594         ty::Slice(element_type) => is_recursively_primitive_type(element_type),
1595         ty::Ref(_, inner_ty, _) if matches!(inner_ty.kind(), &ty::Slice(_)) => {
1596             if let ty::Slice(element_type) = inner_ty.kind() {
1597                 is_recursively_primitive_type(element_type)
1598             } else {
1599                 unreachable!()
1600             }
1601         },
1602         _ => false,
1603     };
1604
1605     if is_primitive {
1606         // if we have wrappers like Array, Slice or Tuple, print these
1607         // and get the type enclosed in the slice ref
1608         match expr_type.peel_refs().walk().nth(1).unwrap().expect_ty().kind() {
1609             ty::Slice(..) => return Some("slice".into()),
1610             ty::Array(..) => return Some("array".into()),
1611             ty::Tuple(..) => return Some("tuple".into()),
1612             _ => {
1613                 // is_recursively_primitive_type() should have taken care
1614                 // of the rest and we can rely on the type that is found
1615                 let refs_peeled = expr_type.peel_refs();
1616                 return Some(refs_peeled.walk().last().unwrap().to_string());
1617             },
1618         }
1619     }
1620     None
1621 }
1622
1623 /// returns list of all pairs (a, b) from `exprs` such that `eq(a, b)`
1624 /// `hash` must be comformed with `eq`
1625 pub fn search_same<T, Hash, Eq>(exprs: &[T], hash: Hash, eq: Eq) -> Vec<(&T, &T)>
1626 where
1627     Hash: Fn(&T) -> u64,
1628     Eq: Fn(&T, &T) -> bool,
1629 {
1630     if exprs.len() == 2 && eq(&exprs[0], &exprs[1]) {
1631         return vec![(&exprs[0], &exprs[1])];
1632     }
1633
1634     let mut match_expr_list: Vec<(&T, &T)> = Vec::new();
1635
1636     let mut map: FxHashMap<_, Vec<&_>> =
1637         FxHashMap::with_capacity_and_hasher(exprs.len(), BuildHasherDefault::default());
1638
1639     for expr in exprs {
1640         match map.entry(hash(expr)) {
1641             Entry::Occupied(mut o) => {
1642                 for o in o.get() {
1643                     if eq(o, expr) {
1644                         match_expr_list.push((o, expr));
1645                     }
1646                 }
1647                 o.get_mut().push(expr);
1648             },
1649             Entry::Vacant(v) => {
1650                 v.insert(vec![expr]);
1651             },
1652         }
1653     }
1654
1655     match_expr_list
1656 }
1657
1658 #[macro_export]
1659 macro_rules! unwrap_cargo_metadata {
1660     ($cx: ident, $lint: ident, $deps: expr) => {{
1661         let mut command = cargo_metadata::MetadataCommand::new();
1662         if !$deps {
1663             command.no_deps();
1664         }
1665
1666         match command.exec() {
1667             Ok(metadata) => metadata,
1668             Err(err) => {
1669                 span_lint($cx, $lint, DUMMY_SP, &format!("could not read cargo metadata: {}", err));
1670                 return;
1671             },
1672         }
1673     }};
1674 }
1675
1676 pub fn is_hir_ty_cfg_dependant(cx: &LateContext<'_>, ty: &hir::Ty<'_>) -> bool {
1677     if_chain! {
1678         if let TyKind::Path(QPath::Resolved(_, path)) = ty.kind;
1679         if let Res::Def(_, def_id) = path.res;
1680         then {
1681             cx.tcx.has_attr(def_id, sym::cfg) || cx.tcx.has_attr(def_id, sym::cfg_attr)
1682         } else {
1683             false
1684         }
1685     }
1686 }
1687
1688 #[cfg(test)]
1689 mod test {
1690     use super::{reindent_multiline, without_block_comments};
1691
1692     #[test]
1693     fn test_reindent_multiline_single_line() {
1694         assert_eq!("", reindent_multiline("".into(), false, None));
1695         assert_eq!("...", reindent_multiline("...".into(), false, None));
1696         assert_eq!("...", reindent_multiline("    ...".into(), false, None));
1697         assert_eq!("...", reindent_multiline("\t...".into(), false, None));
1698         assert_eq!("...", reindent_multiline("\t\t...".into(), false, None));
1699     }
1700
1701     #[test]
1702     #[rustfmt::skip]
1703     fn test_reindent_multiline_block() {
1704         assert_eq!("\
1705     if x {
1706         y
1707     } else {
1708         z
1709     }", reindent_multiline("    if x {
1710             y
1711         } else {
1712             z
1713         }".into(), false, None));
1714         assert_eq!("\
1715     if x {
1716     \ty
1717     } else {
1718     \tz
1719     }", reindent_multiline("    if x {
1720         \ty
1721         } else {
1722         \tz
1723         }".into(), false, None));
1724     }
1725
1726     #[test]
1727     #[rustfmt::skip]
1728     fn test_reindent_multiline_empty_line() {
1729         assert_eq!("\
1730     if x {
1731         y
1732
1733     } else {
1734         z
1735     }", reindent_multiline("    if x {
1736             y
1737
1738         } else {
1739             z
1740         }".into(), false, None));
1741     }
1742
1743     #[test]
1744     #[rustfmt::skip]
1745     fn test_reindent_multiline_lines_deeper() {
1746         assert_eq!("\
1747         if x {
1748             y
1749         } else {
1750             z
1751         }", reindent_multiline("\
1752     if x {
1753         y
1754     } else {
1755         z
1756     }".into(), true, Some(8)));
1757     }
1758
1759     #[test]
1760     fn test_without_block_comments_lines_without_block_comments() {
1761         let result = without_block_comments(vec!["/*", "", "*/"]);
1762         println!("result: {:?}", result);
1763         assert!(result.is_empty());
1764
1765         let result = without_block_comments(vec!["", "/*", "", "*/", "#[crate_type = \"lib\"]", "/*", "", "*/", ""]);
1766         assert_eq!(result, vec!["", "#[crate_type = \"lib\"]", ""]);
1767
1768         let result = without_block_comments(vec!["/* rust", "", "*/"]);
1769         assert!(result.is_empty());
1770
1771         let result = without_block_comments(vec!["/* one-line comment */"]);
1772         assert!(result.is_empty());
1773
1774         let result = without_block_comments(vec!["/* nested", "/* multi-line", "comment", "*/", "test", "*/"]);
1775         assert!(result.is_empty());
1776
1777         let result = without_block_comments(vec!["/* nested /* inline /* comment */ test */ */"]);
1778         assert!(result.is_empty());
1779
1780         let result = without_block_comments(vec!["foo", "bar", "baz"]);
1781         assert_eq!(result, vec!["foo", "bar", "baz"]);
1782     }
1783 }