|
| 1 | +use std::ops::ControlFlow; |
| 2 | + |
| 3 | +use clippy_utils::diagnostics::span_lint_and_then; |
| 4 | +use clippy_utils::visitors::for_each_expr_with_closures; |
| 5 | +use clippy_utils::{def_path_def_ids, fn_def_id, is_lint_allowed}; |
| 6 | +use rustc_data_structures::fx::FxHashMap; |
| 7 | +use rustc_errors::Applicability; |
| 8 | +use rustc_hir::def_id::DefId; |
| 9 | +use rustc_hir::hir_id::CRATE_HIR_ID; |
| 10 | +use rustc_hir::{Body, ExprKind, GeneratorKind, HirIdSet}; |
| 11 | +use rustc_lint::{LateContext, LateLintPass}; |
| 12 | +use rustc_session::{declare_tool_lint, impl_lint_pass}; |
| 13 | + |
| 14 | +declare_clippy_lint! { |
| 15 | + /// ### What it does |
| 16 | + /// Checks for async function or async closure with blocking operations that |
| 17 | + /// could be replaced with their async counterpart. |
| 18 | + /// |
| 19 | + /// ### Why is this bad? |
| 20 | + /// Blocking a thread prevents tasks being swapped, causing other tasks to stop running |
| 21 | + /// until the thread is no longer blocked, which might not be as expected in an async context. |
| 22 | + /// |
| 23 | + /// ### Known problems |
| 24 | + /// Not all blocking operations can be detected, as for now, this lint only detects a small |
| 25 | + /// set of functions in standard library by default. And some of the suggestions might need |
| 26 | + /// additional features to work properly. |
| 27 | + /// |
| 28 | + /// ### Example |
| 29 | + /// ```rust |
| 30 | + /// use std::time::Duration; |
| 31 | + /// pub async fn foo() { |
| 32 | + /// std::thread::sleep(Duration::from_secs(5)); |
| 33 | + /// } |
| 34 | + /// ``` |
| 35 | + /// Use instead: |
| 36 | + /// ```rust |
| 37 | + /// use std::time::Duration; |
| 38 | + /// pub async fn foo() { |
| 39 | + /// tokio::time::sleep(Duration::from_secs(5)); |
| 40 | + /// } |
| 41 | + /// ``` |
| 42 | + #[clippy::version = "1.74.0"] |
| 43 | + pub UNNECESSARY_BLOCKING_OPS, |
| 44 | + nursery, |
| 45 | + "blocking operations in an async context" |
| 46 | +} |
| 47 | + |
| 48 | +pub(crate) struct UnnecessaryBlockingOps { |
| 49 | + blocking_ops: Vec<String>, |
| 50 | + blocking_ops_with_suggs: Vec<[String; 2]>, |
| 51 | + /// Map of resolved funtion def_id with suggestion string after checking crate |
| 52 | + id_with_suggs: FxHashMap<DefId, String>, |
| 53 | + /// Keep track of visited block ids to skip checking the same bodies in `check_body` calls |
| 54 | + visited_block: HirIdSet, |
| 55 | +} |
| 56 | + |
| 57 | +impl UnnecessaryBlockingOps { |
| 58 | + pub(crate) fn new(blocking_ops: Vec<String>, blocking_ops_with_suggs: Vec<[String; 2]>) -> Self { |
| 59 | + Self { |
| 60 | + blocking_ops, |
| 61 | + blocking_ops_with_suggs, |
| 62 | + id_with_suggs: FxHashMap::default(), |
| 63 | + visited_block: HirIdSet::default(), |
| 64 | + } |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +impl_lint_pass!(UnnecessaryBlockingOps => [UNNECESSARY_BLOCKING_OPS]); |
| 69 | + |
| 70 | +// TODO: Should we throw away all suggestions and and give full control to user configurations? |
| 71 | +// this feels like a free ad for tokio :P |
| 72 | +static HARD_CODED_BLOCKING_OPS_WITH_SUGG: [[&str; 2]; 26] = [ |
| 73 | + // Sleep |
| 74 | + ["std::thread::sleep", "tokio::time::sleep"], |
| 75 | + // IO functions |
| 76 | + ["std::io::copy", "tokio::io::copy"], |
| 77 | + ["std::io::empty", "tokio::io::empty"], |
| 78 | + ["std::io::repeat", "tokio::io::repeat"], |
| 79 | + ["std::io::sink", "tokio::io::sink"], |
| 80 | + ["std::io::stderr", "tokio::io::stderr"], |
| 81 | + ["std::io::stdin", "tokio::io::stdin"], |
| 82 | + ["std::io::stdout", "tokio::io::stdout"], |
| 83 | + // Filesystem functions |
| 84 | + ["std::fs::try_exists", "tokio::fs::try_exists"], |
| 85 | + ["std::fs::canonicalize", "tokio::fs::canonicalize"], |
| 86 | + ["std::fs::copy", "tokio::fs::copy"], |
| 87 | + ["std::fs::create_dir", "tokio::fs::create_dir"], |
| 88 | + ["std::fs::create_dir_all", "tokio::fs::create_dir_all"], |
| 89 | + ["std::fs::hard_link", "tokio::fs::hard_link"], |
| 90 | + ["std::fs::metadata", "tokio::fs::metadata"], |
| 91 | + ["std::fs::read", "tokio::fs::read"], |
| 92 | + ["std::fs::read_dir", "tokio::fs::read_dir"], |
| 93 | + ["std::fs::read_to_string", "tokio::fs::read_to_string"], |
| 94 | + ["std::fs::remove_dir", "tokio::fs::remove_dir"], |
| 95 | + ["std::fs::remove_dir_all", "tokio::fs::remove_dir_all"], |
| 96 | + ["std::fs::remove_file", "tokio::fs::remove_file"], |
| 97 | + ["std::fs::rename", "tokio::fs::rename"], |
| 98 | + ["std::fs::set_permissions", "tokio::fs::set_permissions"], |
| 99 | + ["std::fs::soft_link", "tokio::fs::soft_link"], |
| 100 | + ["std::fs::symlink_metadata", "tokio::fs::symlink_metadata"], |
| 101 | + ["std::fs::write", "tokio::fs::write"], |
| 102 | +]; |
| 103 | + |
| 104 | +impl<'tcx> LateLintPass<'tcx> for UnnecessaryBlockingOps { |
| 105 | + fn check_crate(&mut self, cx: &LateContext<'tcx>) { |
| 106 | + // Avoids processing and storing a long list of paths if this lint was allowed entirely |
| 107 | + if is_lint_allowed(cx, UNNECESSARY_BLOCKING_OPS, CRATE_HIR_ID) { |
| 108 | + return; |
| 109 | + } |
| 110 | + |
| 111 | + let full_fn_list = HARD_CODED_BLOCKING_OPS_WITH_SUGG |
| 112 | + .into_iter() |
| 113 | + // Chain configured functions without suggestions |
| 114 | + .chain(self.blocking_ops.iter().map(|p| [p, ""])) |
| 115 | + // Chain configured functions with suggestions |
| 116 | + .chain( |
| 117 | + self.blocking_ops_with_suggs |
| 118 | + .iter() |
| 119 | + .map(|[p, s]| [p.as_str(), s.as_str()]), |
| 120 | + ); |
| 121 | + |
| 122 | + for [path_str, sugg_path_str] in full_fn_list { |
| 123 | + let path = path_str.split("::").collect::<Vec<_>>(); |
| 124 | + for did in def_path_def_ids(cx, &path) { |
| 125 | + self.id_with_suggs.insert(did, sugg_path_str.to_string()); |
| 126 | + } |
| 127 | + } |
| 128 | + } |
| 129 | + |
| 130 | + fn check_body(&mut self, cx: &LateContext<'tcx>, body: &'tcx Body<'tcx>) { |
| 131 | + if self.visited_block.contains(&body.value.hir_id) { |
| 132 | + return; |
| 133 | + } |
| 134 | + if let Some(GeneratorKind::Async(_)) = body.generator_kind() { |
| 135 | + for_each_expr_with_closures(cx, body, |ex| { |
| 136 | + if let ExprKind::Block(block, _) = ex.kind { |
| 137 | + self.visited_block.insert(block.hir_id); |
| 138 | + } else if let Some(call_did) = fn_def_id(cx, ex) && |
| 139 | + let Some(replace_sugg) = self.id_with_suggs.get(&call_did) |
| 140 | + { |
| 141 | + span_lint_and_then( |
| 142 | + cx, |
| 143 | + UNNECESSARY_BLOCKING_OPS, |
| 144 | + ex.span, |
| 145 | + "blocking function call detected in an async body", |
| 146 | + |diag| { |
| 147 | + if !replace_sugg.is_empty() { |
| 148 | + diag.span_suggestion( |
| 149 | + ex.span, |
| 150 | + "try using an async counterpart such as", |
| 151 | + replace_sugg, |
| 152 | + Applicability::Unspecified, |
| 153 | + ); |
| 154 | + } |
| 155 | + } |
| 156 | + ); |
| 157 | + } |
| 158 | + ControlFlow::<()>::Continue(()) |
| 159 | + }); |
| 160 | + } |
| 161 | + } |
| 162 | +} |
0 commit comments