|
| 1 | +use memchr::memchr; |
| 2 | + |
| 3 | +use ruff_diagnostics::{Diagnostic, Violation}; |
| 4 | +use ruff_macros::{derive_message_formats, ViolationMetadata}; |
| 5 | +use ruff_source_file::Line; |
| 6 | +use ruff_text_size::{TextRange, TextSize}; |
| 7 | + |
| 8 | +/// ## What it does |
| 9 | +/// Checks for form feed characters preceded by either a space or a tab. |
| 10 | +/// |
| 11 | +/// ## Why is this bad? |
| 12 | +/// [The language reference][lexical-analysis-indentation] states: |
| 13 | +/// |
| 14 | +/// > A formfeed character may be present at the start of the line; |
| 15 | +/// > it will be ignored for the indentation calculations above. |
| 16 | +/// > Formfeed characters occurring elsewhere in the leading whitespace |
| 17 | +/// > have an undefined effect (for instance, they may reset the space count to zero). |
| 18 | +/// |
| 19 | +/// ## Example |
| 20 | +/// |
| 21 | +/// ```python |
| 22 | +/// if foo():\n \fbar() |
| 23 | +/// ``` |
| 24 | +/// |
| 25 | +/// Use instead: |
| 26 | +/// |
| 27 | +/// ```python |
| 28 | +/// if foo():\n bar() |
| 29 | +/// ``` |
| 30 | +/// |
| 31 | +/// [lexical-analysis-indentation]: https://docs.python.org/3/reference/lexical_analysis.html#indentation |
| 32 | +#[derive(ViolationMetadata)] |
| 33 | +pub(crate) struct IndentedFormFeed; |
| 34 | + |
| 35 | +impl Violation for IndentedFormFeed { |
| 36 | + #[derive_message_formats] |
| 37 | + fn message(&self) -> String { |
| 38 | + "Indented form feed".to_string() |
| 39 | + } |
| 40 | + |
| 41 | + fn fix_title(&self) -> Option<String> { |
| 42 | + Some("Remove form feed".to_string()) |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +const FORM_FEED: u8 = b'\x0c'; |
| 47 | +const SPACE: u8 = b' '; |
| 48 | +const TAB: u8 = b'\t'; |
| 49 | + |
| 50 | +/// RUF054 |
| 51 | +pub(crate) fn indented_form_feed(line: &Line) -> Option<Diagnostic> { |
| 52 | + let index_relative_to_line = memchr(FORM_FEED, line.as_bytes())?; |
| 53 | + |
| 54 | + if index_relative_to_line == 0 { |
| 55 | + return None; |
| 56 | + } |
| 57 | + |
| 58 | + if line[..index_relative_to_line] |
| 59 | + .as_bytes() |
| 60 | + .iter() |
| 61 | + .any(|byte| *byte != SPACE && *byte != TAB) |
| 62 | + { |
| 63 | + return None; |
| 64 | + } |
| 65 | + |
| 66 | + let relative_index = u32::try_from(index_relative_to_line).ok()?; |
| 67 | + let absolute_index = line.start() + TextSize::new(relative_index); |
| 68 | + let range = TextRange::at(absolute_index, 1.into()); |
| 69 | + |
| 70 | + Some(Diagnostic::new(IndentedFormFeed, range)) |
| 71 | +} |
0 commit comments