]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/undocumented_unsafe_blocks.rs
Rollup merge of #91861 - juniorbassani:use-from-array-in-collections-examples, r...
[rust.git] / src / tools / clippy / clippy_lints / src / undocumented_unsafe_blocks.rs
1 use clippy_utils::diagnostics::{span_lint_and_help, span_lint_and_sugg};
2 use clippy_utils::is_lint_allowed;
3 use clippy_utils::source::{indent_of, reindent_multiline, snippet};
4 use rustc_errors::Applicability;
5 use rustc_hir::intravisit::{walk_expr, Visitor};
6 use rustc_hir::{Block, BlockCheckMode, Expr, ExprKind, HirId, Local, UnsafeSource};
7 use rustc_lexer::TokenKind;
8 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_middle::lint::in_external_macro;
10 use rustc_middle::ty::TyCtxt;
11 use rustc_session::{declare_tool_lint, impl_lint_pass};
12 use rustc_span::{BytePos, Span};
13 use std::borrow::Cow;
14
15 declare_clippy_lint! {
16     /// ### What it does
17     /// Checks for `unsafe` blocks without a `// SAFETY: ` comment
18     /// explaining why the unsafe operations performed inside
19     /// the block are safe.
20     ///
21     /// ### Why is this bad?
22     /// Undocumented unsafe blocks can make it difficult to
23     /// read and maintain code, as well as uncover unsoundness
24     /// and bugs.
25     ///
26     /// ### Example
27     /// ```rust
28     /// use std::ptr::NonNull;
29     /// let a = &mut 42;
30     ///
31     /// let ptr = unsafe { NonNull::new_unchecked(a) };
32     /// ```
33     /// Use instead:
34     /// ```rust
35     /// use std::ptr::NonNull;
36     /// let a = &mut 42;
37     ///
38     /// // SAFETY: references are guaranteed to be non-null.
39     /// let ptr = unsafe { NonNull::new_unchecked(a) };
40     /// ```
41     #[clippy::version = "1.58.0"]
42     pub UNDOCUMENTED_UNSAFE_BLOCKS,
43     restriction,
44     "creating an unsafe block without explaining why it is safe"
45 }
46
47 impl_lint_pass!(UndocumentedUnsafeBlocks => [UNDOCUMENTED_UNSAFE_BLOCKS]);
48
49 #[derive(Default)]
50 pub struct UndocumentedUnsafeBlocks {
51     pub local_level: u32,
52     pub local_span: Option<Span>,
53     // The local was already checked for an overall safety comment
54     // There is no need to continue checking the blocks in the local
55     pub local_checked: bool,
56     // Since we can only check the blocks from expanded macros
57     // We have to omit the suggestion due to the actual definition
58     // Not being available to us
59     pub macro_expansion: bool,
60 }
61
62 impl LateLintPass<'_> for UndocumentedUnsafeBlocks {
63     fn check_block(&mut self, cx: &LateContext<'_>, block: &'_ Block<'_>) {
64         if_chain! {
65             if !self.local_checked;
66             if !is_lint_allowed(cx, UNDOCUMENTED_UNSAFE_BLOCKS, block.hir_id);
67             if !in_external_macro(cx.tcx.sess, block.span);
68             if let BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided) = block.rules;
69             if let Some(enclosing_scope_hir_id) = cx.tcx.hir().get_enclosing_scope(block.hir_id);
70             if self.block_has_safety_comment(cx.tcx, enclosing_scope_hir_id, block.span) == Some(false);
71             then {
72                 let mut span = block.span;
73
74                 if let Some(local_span) = self.local_span {
75                     span = local_span;
76
77                     let result = self.block_has_safety_comment(cx.tcx, enclosing_scope_hir_id, span);
78
79                     if result.unwrap_or(true) {
80                         self.local_checked = true;
81                         return;
82                     }
83                 }
84
85                 self.lint(cx, span);
86             }
87         }
88     }
89
90     fn check_local(&mut self, cx: &LateContext<'_>, local: &'_ Local<'_>) {
91         if_chain! {
92             if !is_lint_allowed(cx, UNDOCUMENTED_UNSAFE_BLOCKS, local.hir_id);
93             if !in_external_macro(cx.tcx.sess, local.span);
94             if let Some(init) = local.init;
95             then {
96                 self.visit_expr(init);
97
98                 if self.local_level > 0 {
99                     self.local_span = Some(local.span);
100                 }
101             }
102         }
103     }
104
105     fn check_block_post(&mut self, _: &LateContext<'_>, _: &'_ Block<'_>) {
106         self.local_level = self.local_level.saturating_sub(1);
107
108         if self.local_level == 0 {
109             self.local_checked = false;
110             self.local_span = None;
111         }
112     }
113 }
114
115 impl<'v> Visitor<'v> for UndocumentedUnsafeBlocks {
116     fn visit_expr(&mut self, ex: &'v Expr<'v>) {
117         match ex.kind {
118             ExprKind::Block(_, _) => self.local_level = self.local_level.saturating_add(1),
119             _ => walk_expr(self, ex),
120         }
121     }
122 }
123
124 impl UndocumentedUnsafeBlocks {
125     fn block_has_safety_comment(&mut self, tcx: TyCtxt<'_>, enclosing_hir_id: HirId, block_span: Span) -> Option<bool> {
126         let map = tcx.hir();
127         let source_map = tcx.sess.source_map();
128
129         let enclosing_scope_span = map.opt_span(enclosing_hir_id)?;
130
131         let between_span = if block_span.from_expansion() {
132             self.macro_expansion = true;
133             enclosing_scope_span.with_hi(block_span.hi()).source_callsite()
134         } else {
135             self.macro_expansion = false;
136             enclosing_scope_span.to(block_span).source_callsite()
137         };
138
139         let file_name = source_map.span_to_filename(between_span);
140         let source_file = source_map.get_source_file(&file_name)?;
141
142         let lex_start = (between_span.lo().0 - source_file.start_pos.0 + 1) as usize;
143         let lex_end = (between_span.hi().0 - source_file.start_pos.0) as usize;
144         let src_str = source_file.src.as_ref()?[lex_start..lex_end].to_string();
145
146         let source_start_pos = source_file.start_pos.0 as usize + lex_start;
147
148         let mut pos = 0;
149         let mut comment = false;
150
151         for token in rustc_lexer::tokenize(&src_str) {
152             match token.kind {
153                 TokenKind::LineComment { doc_style: None }
154                 | TokenKind::BlockComment {
155                     doc_style: None,
156                     terminated: true,
157                 } => {
158                     let comment_str = src_str[pos + 2..pos + token.len].to_ascii_uppercase();
159
160                     if comment_str.contains("SAFETY:") {
161                         comment = true;
162                     }
163                 },
164                 // We need to add all whitespace to `pos` before checking the comment's line number
165                 TokenKind::Whitespace => {},
166                 _ => {
167                     if comment {
168                         // Get the line number of the "comment" (really wherever the trailing whitespace ended)
169                         let comment_line_num = source_file
170                             .lookup_file_pos(BytePos((source_start_pos + pos).try_into().unwrap()))
171                             .0;
172                         // Find the block/local's line number
173                         let block_line_num = tcx.sess.source_map().lookup_char_pos(block_span.lo()).line;
174
175                         // Check the comment is immediately followed by the block/local
176                         if block_line_num == comment_line_num + 1 || block_line_num == comment_line_num {
177                             return Some(true);
178                         }
179
180                         comment = false;
181                     }
182                 },
183             }
184
185             pos += token.len;
186         }
187
188         Some(false)
189     }
190
191     fn lint(&self, cx: &LateContext<'_>, mut span: Span) {
192         let source_map = cx.tcx.sess.source_map();
193
194         if source_map.is_multiline(span) {
195             span = source_map.span_until_char(span, '\n');
196         }
197
198         if self.macro_expansion {
199             span_lint_and_help(
200                 cx,
201                 UNDOCUMENTED_UNSAFE_BLOCKS,
202                 span,
203                 "unsafe block in macro expansion missing a safety comment",
204                 None,
205                 "consider adding a safety comment in the macro definition",
206             );
207         } else {
208             let block_indent = indent_of(cx, span);
209             let suggestion = format!("// SAFETY: ...\n{}", snippet(cx, span, ".."));
210
211             span_lint_and_sugg(
212                 cx,
213                 UNDOCUMENTED_UNSAFE_BLOCKS,
214                 span,
215                 "unsafe block missing a safety comment",
216                 "consider adding a safety comment",
217                 reindent_multiline(Cow::Borrowed(&suggestion), true, block_indent).to_string(),
218                 Applicability::HasPlaceholders,
219             );
220         }
221     }
222 }