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