|
| 1 | +use clippy_config::Conf; |
| 2 | +use clippy_utils::diagnostics::span_lint; |
| 3 | +use clippy_utils::paths::{PathNS, lookup_path_str}; |
| 4 | +use clippy_utils::{get_unique_attr, sym}; |
| 5 | +use rustc_data_structures::fx::FxHashSet; |
| 6 | +use rustc_hir as hir; |
| 7 | +use rustc_hir::def_id::DefId; |
| 8 | +use rustc_lint::{LateContext, LateLintPass, LintContext}; |
| 9 | +use rustc_middle::ty::TyCtxt; |
| 10 | +use rustc_session::impl_lint_pass; |
| 11 | +use rustc_span::Pos; |
| 12 | + |
| 13 | +declare_clippy_lint! { |
| 14 | + /// ### What it does |
| 15 | + /// Checks for calls to functions marked with `#[clippy::may_panic]` or configured in |
| 16 | + /// `may-panic-functions` that don't have a `// Panic:` comment on the line above. |
| 17 | + /// |
| 18 | + /// ### Why is this bad? |
| 19 | + /// Functions that may panic should be documented at their call sites to explain why the |
| 20 | + /// panic is acceptable or impossible in that context. |
| 21 | + /// |
| 22 | + /// ### Example |
| 23 | + /// ```rust,ignore |
| 24 | + /// #[clippy::may_panic] |
| 25 | + /// fn my_panicable_func(n: u32) { |
| 26 | + /// if n % 2 == 0 { |
| 27 | + /// panic!("even number not allowed") |
| 28 | + /// } |
| 29 | + /// } |
| 30 | + /// |
| 31 | + /// fn main() { |
| 32 | + /// // Missing documentation - will lint |
| 33 | + /// my_panicable_func(1); |
| 34 | + /// } |
| 35 | + /// ``` |
| 36 | + /// Use instead: |
| 37 | + /// ```rust,ignore |
| 38 | + /// #[clippy::may_panic] |
| 39 | + /// fn my_panicable_func(n: u32) { |
| 40 | + /// if n % 2 == 0 { |
| 41 | + /// panic!("even number not allowed") |
| 42 | + /// } |
| 43 | + /// } |
| 44 | + /// |
| 45 | + /// fn main() { |
| 46 | + /// // Panic: This is safe, it's an odd number |
| 47 | + /// my_panicable_func(1); |
| 48 | + /// } |
| 49 | + /// ``` |
| 50 | + /// |
| 51 | + /// ### Configuration |
| 52 | + /// This lint can be configured to check calls to external functions that may panic: |
| 53 | + /// ```toml |
| 54 | + /// # clippy.toml |
| 55 | + /// may-panic-functions = [ |
| 56 | + /// "alloc::vec::Vec::push", # Can panic on allocation failure |
| 57 | + /// "std::fs::File::open", # Can panic in some configurations |
| 58 | + /// ] |
| 59 | + /// ``` |
| 60 | + #[clippy::version = "1.92.0"] |
| 61 | + pub UNDOCUMENTED_MAY_PANIC_CALL, |
| 62 | + pedantic, |
| 63 | + "missing `// Panic:` documentation on calls to functions that may panic" |
| 64 | +} |
| 65 | + |
| 66 | +pub struct UndocumentedMayPanicCall { |
| 67 | + may_panic_def_ids: FxHashSet<DefId>, |
| 68 | +} |
| 69 | + |
| 70 | +impl_lint_pass!(UndocumentedMayPanicCall => [UNDOCUMENTED_MAY_PANIC_CALL]); |
| 71 | + |
| 72 | +impl UndocumentedMayPanicCall { |
| 73 | + pub fn new(tcx: TyCtxt<'_>, conf: &'static Conf) -> Self { |
| 74 | + let may_panic_def_ids = conf |
| 75 | + .may_panic_functions |
| 76 | + .iter() |
| 77 | + .flat_map(|path| lookup_path_str(tcx, PathNS::Value, path)) |
| 78 | + .collect(); |
| 79 | + |
| 80 | + Self { may_panic_def_ids } |
| 81 | + } |
| 82 | + |
| 83 | + // A function is a may_panic_function if it has the may_panic attribute |
| 84 | + // or is in the may-panic-functions configuration |
| 85 | + fn is_may_panic_function(&self, cx: &LateContext<'_>, def_id: DefId) -> bool { |
| 86 | + if get_unique_attr(cx.sess(), cx.tcx.get_all_attrs(def_id), sym::may_panic).is_some() { |
| 87 | + return true; |
| 88 | + } |
| 89 | + |
| 90 | + self.may_panic_def_ids.contains(&def_id) |
| 91 | + } |
| 92 | +} |
| 93 | + |
| 94 | +impl LateLintPass<'_> for UndocumentedMayPanicCall { |
| 95 | + fn check_expr(&mut self, cx: &LateContext<'_>, expr: &'_ rustc_hir::Expr<'_>) { |
| 96 | + let def_id = match &expr.kind { |
| 97 | + hir::ExprKind::Call(func, _args) => { |
| 98 | + if let hir::ExprKind::Path(qpath) = &func.kind { |
| 99 | + cx.qpath_res(qpath, func.hir_id).opt_def_id() |
| 100 | + } else { |
| 101 | + None |
| 102 | + } |
| 103 | + }, |
| 104 | + hir::ExprKind::MethodCall(_path, _receiver, _args, _span) => { |
| 105 | + cx.typeck_results().type_dependent_def_id(expr.hir_id) |
| 106 | + }, |
| 107 | + _ => None, |
| 108 | + }; |
| 109 | + |
| 110 | + if let Some(def_id) = def_id |
| 111 | + && self.is_may_panic_function(cx, def_id) |
| 112 | + && !has_panic_comment_above(cx, expr.span) |
| 113 | + { |
| 114 | + span_lint( |
| 115 | + cx, |
| 116 | + UNDOCUMENTED_MAY_PANIC_CALL, |
| 117 | + expr.span, |
| 118 | + "call to a function that may panic is not documented with a `// Panic:` comment", |
| 119 | + ); |
| 120 | + } |
| 121 | + } |
| 122 | +} |
| 123 | + |
| 124 | +/// Checks if the lines immediately preceding the call contain a "Panic:" comment. |
| 125 | +fn has_panic_comment_above(cx: &LateContext<'_>, call_span: rustc_span::Span) -> bool { |
| 126 | + let source_map = cx.sess().source_map(); |
| 127 | + |
| 128 | + if let Ok(call_line) = source_map.lookup_line(call_span.lo()) |
| 129 | + && call_line.line > 0 |
| 130 | + && let Some(src) = call_line.sf.src.as_deref() |
| 131 | + { |
| 132 | + let lines = call_line.sf.lines(); |
| 133 | + let line_starts = &lines[..=call_line.line]; |
| 134 | + |
| 135 | + has_panic_comment_in_text(src, line_starts) |
| 136 | + } else { |
| 137 | + false |
| 138 | + } |
| 139 | +} |
| 140 | + |
| 141 | +fn has_panic_comment_in_text(src: &str, line_starts: &[rustc_span::RelativeBytePos]) -> bool { |
| 142 | + let mut lines = line_starts |
| 143 | + .array_windows::<2>() |
| 144 | + .rev() |
| 145 | + .map_while(|[start, end]| { |
| 146 | + let start = start.to_usize(); |
| 147 | + let end = end.to_usize(); |
| 148 | + let text = src.get(start..end)?; |
| 149 | + let trimmed = text.trim_start(); |
| 150 | + Some((trimmed, text.len() - trimmed.len())) |
| 151 | + }) |
| 152 | + .filter(|(text, _)| !text.is_empty()); |
| 153 | + |
| 154 | + let Some((line, _)) = lines.next() else { |
| 155 | + return false; |
| 156 | + }; |
| 157 | + |
| 158 | + if line.starts_with("//") { |
| 159 | + let mut current_line = line; |
| 160 | + loop { |
| 161 | + if current_line.to_ascii_uppercase().contains("PANIC:") { |
| 162 | + return true; |
| 163 | + } |
| 164 | + match lines.next() { |
| 165 | + Some((text, _)) if text.starts_with("//") => current_line = text, |
| 166 | + _ => return false, |
| 167 | + } |
| 168 | + } |
| 169 | + } |
| 170 | + |
| 171 | + false |
| 172 | +} |
0 commit comments