Skip to main content

tidy/
style.rs

1//! Tidy check to enforce various stylistic guidelines on the Rust codebase.
2//!
3//! Example checks are:
4//!
5//! * No lines over 100 characters (in non-Rust files).
6//! * No files with over 3000 lines (in non-Rust files).
7//! * No tabs.
8//! * No trailing whitespace.
9//! * No CR characters.
10//! * No `TODO` or `XXX` directives.
11//! * No unexplained ` ```ignore ` or ` ```rust,ignore ` doc tests.
12//!
13//! Note that some of these rules are excluded from Rust files because we enforce rustfmt. It is
14//! preferable to be formatted rather than tidy-clean.
15//!
16//! A number of these checks can be opted-out of with various directives of the form:
17//! `// ignore-tidy-CHECK-NAME`.
18
19use std::ffi::OsStr;
20use std::mem;
21use std::path::Path;
22use std::sync::LazyLock;
23
24use regex::RegexSetBuilder;
25use rustc_hash::FxHashMap;
26
27use crate::diagnostics::{CheckId, RunningCheck, TidyCtx};
28use crate::style::directive::{Directives, LineNumber, NamedDirective, match_ignore};
29use crate::walk::{filter_dirs, walk};
30
31mod directive;
32
33#[cfg(test)]
34mod tests;
35
36/// Error code markdown is restricted to 80 columns because they can be
37/// displayed on the console with --example.
38const ERROR_CODE_COLS: usize = 80;
39const COLS: usize = 100;
40const GOML_COLS: usize = 120;
41
42const LINES: usize = 3000;
43
44const UNEXPLAINED_IGNORE_DOCTEST_INFO: &str = r#"unexplained "```ignore" doctest; try one:
45
46* make the test actually pass, by adding necessary imports and declarations, or
47* use "```text", if the code is not Rust code, or
48* use "```compile_fail,Ennnn", if the code is expected to fail at compile time, or
49* use "```should_panic", if the code is expected to fail at run time, or
50* use "```no_run", if the code should type-check but not necessary linkable/runnable, or
51* explain it like "```ignore (cannot-test-this-because-xxxx)", if the annotation cannot be avoided.
52
53"#;
54
55const LLVM_UNREACHABLE_INFO: &str = r"\
56C++ code used llvm_unreachable, which triggers undefined behavior
57when executed when assertions are disabled.
58Use llvm::report_fatal_error for increased robustness.";
59
60const DOUBLE_SPACE_AFTER_DOT: &str = r"\
61Use a single space after dots in comments.";
62
63const ANNOTATIONS_TO_IGNORE: &[&str] = &[
64    "// @!has",
65    "// @has",
66    "// @matches",
67    "// CHECK",
68    "// EMIT_MIR",
69    "// compile-flags",
70    "//@ compile-flags",
71    "// error-pattern",
72    "//@ error-pattern",
73    "//@ gdb",
74    "//@ lldb",
75    "//@ cdb",
76    "//@ normalize-stderr",
77];
78
79fn generate_problems<'a>(
80    consts: &'a [u32],
81    letter_digit: &'a FxHashMap<char, char>,
82) -> impl Iterator<Item = u32> + 'a {
83    consts.iter().flat_map(move |const_value| {
84        let problem = letter_digit.iter().fold(format!("{const_value:X}"), |acc, (key, value)| {
85            acc.replace(&value.to_string(), &key.to_string())
86        });
87        let indexes: Vec<usize> = problem
88            .chars()
89            .enumerate()
90            .filter_map(|(index, c)| if letter_digit.contains_key(&c) { Some(index) } else { None })
91            .collect();
92        (0..1 << indexes.len()).map(move |i| {
93            u32::from_str_radix(
94                &problem
95                    .chars()
96                    .enumerate()
97                    .map(|(index, c)| {
98                        if let Some(pos) = indexes.iter().position(|&x| x == index) {
99                            if (i >> pos) & 1 == 1 { letter_digit[&c] } else { c }
100                        } else {
101                            c
102                        }
103                    })
104                    .collect::<String>(),
105                0x10,
106            )
107            .unwrap()
108        })
109    })
110}
111
112// Intentionally written in decimal rather than hex
113const ROOT_PROBLEMATIC_CONSTS: &[u32] = &[
114    184594741, 2880289470, 2881141438, 2965027518, 2976579765, 3203381950, 3405691582, 3405697037,
115    3735927486, 3735932941, 4027431614, 4276992702, 195934910, 252707358, 762133, 179681982,
116    173390526, 721077,
117];
118
119const LETTER_DIGIT: &[(char, char)] = &[('A', '4'), ('B', '8'), ('E', '3')];
120
121// Returns all permutations of problematic consts, over 2000 elements.
122fn generate_problematic_strings(
123    consts: &[u32],
124    letter_digit: &FxHashMap<char, char>,
125) -> Vec<String> {
126    generate_problems(consts, letter_digit)
127        .flat_map(|v| vec![v.to_string(), format!("{:X}", v)])
128        .collect()
129}
130
131static PROBLEMATIC_CONSTS_STRINGS: LazyLock<Vec<String>> = LazyLock::new(|| {
132    generate_problematic_strings(ROOT_PROBLEMATIC_CONSTS, &LETTER_DIGIT.iter().cloned().collect())
133});
134
135fn contains_problematic_const(trimmed: &str) -> bool {
136    PROBLEMATIC_CONSTS_STRINGS.iter().any(|s| trimmed.to_uppercase().contains(s))
137}
138
139const INTERNAL_COMPILER_DOCS_LINE: &str = "#### This error code is internal to the compiler and will not be emitted with normal Rust code.";
140
141/// Parser states for `line_is_url`.
142#[derive(Clone, Copy, PartialEq)]
143#[allow(non_camel_case_types)]
144enum LIUState {
145    EXP_COMMENT_START,
146    EXP_LINK_LABEL_OR_URL,
147    EXP_URL,
148    EXP_END,
149}
150
151/// Returns `true` if `line` appears to be a line comment containing a URL,
152/// possibly with a Markdown link label in front, and nothing else.
153/// The Markdown link label, if present, may not contain whitespace.
154/// Lines of this form are allowed to be overlength, because Markdown
155/// offers no way to split a line in the middle of a URL, and the lengths
156/// of URLs to external references are beyond our control.
157fn line_is_url(is_error_code: bool, columns: usize, line: &str) -> bool {
158    // more basic check for markdown, to avoid complexity in implementing two state machines
159    if is_error_code {
160        return line.starts_with('[') && line.contains("]:") && line.contains("http");
161    }
162
163    use self::LIUState::*;
164    let mut state: LIUState = EXP_COMMENT_START;
165    let is_url = |w: &str| w.starts_with("http://") || w.starts_with("https://");
166
167    for tok in line.split_whitespace() {
168        match (state, tok) {
169            (EXP_COMMENT_START, "//") | (EXP_COMMENT_START, "///") | (EXP_COMMENT_START, "//!") => {
170                state = EXP_LINK_LABEL_OR_URL
171            }
172
173            (EXP_LINK_LABEL_OR_URL, w)
174                if w.len() >= 4 && w.starts_with('[') && w.ends_with("]:") =>
175            {
176                state = EXP_URL
177            }
178
179            (EXP_LINK_LABEL_OR_URL, w) if is_url(w) => state = EXP_END,
180
181            (EXP_URL, w) if is_url(w) || w.starts_with("../") => state = EXP_END,
182
183            (_, w) if w.len() > columns && is_url(w) => state = EXP_END,
184
185            (_, _) => {}
186        }
187    }
188
189    state == EXP_END
190}
191
192/// Returns `true` if `line` can be ignored. This is the case when it contains
193/// an annotation that is explicitly ignored.
194fn should_ignore(line: &str) -> bool {
195    // Matches test annotations like `//~ ERROR text`.
196    // This mirrors the regex in src/tools/compiletest/src/runtest.rs, please
197    // update both if either are changed.
198    static_regex!("\\s*//(\\[.*\\])?~.*").is_match(line)
199        || ANNOTATIONS_TO_IGNORE.iter().any(|a| line.contains(a))
200
201    // For `ui_test`-style UI test directives, also ignore
202    // - `//@[rev] compile-flags`
203    // - `//@[rev] normalize-stderr`
204        || static_regex!("\\s*//@(\\[.*\\]) (compile-flags|normalize-stderr|error-pattern).*")
205            .is_match(line)
206        // Matching for rustdoc tests commands.
207        // It allows to prevent them emitting warnings like `line longer than 100 chars`.
208        || static_regex!(
209            "\\s*//@ \\!?(count|files|has|has-dir|hasraw|matches|matchesraw|snapshot)\\s.*"
210        ).is_match(line)
211        // Matching for FileCheck checks
212        || static_regex!(
213            "\\s*// [a-zA-Z0-9-_]*:\\s.*"
214        ).is_match(line)
215}
216
217/// Returns `true` if `line` is allowed to be longer than the normal limit.
218fn long_line_is_ok(extension: &str, is_error_code: bool, max_columns: usize, line: &str) -> bool {
219    match extension {
220        // non-error code markdown is allowed to be any length
221        "md" if !is_error_code => true,
222        // HACK(Ezrashaw): there is no way to split a markdown header over multiple lines
223        "md" if line == INTERNAL_COMPILER_DOCS_LINE => true,
224        _ => line_is_url(is_error_code, max_columns, line) || should_ignore(line),
225    }
226}
227
228macro_rules! suppressible_tidy_err {
229    ($err:ident, $skip:expr, $msg:literal $($args: tt)*) => {
230        if let Err(()) = $skip.check() {
231            $err(&format!($msg $($args)*));
232        }
233    };
234}
235
236pub fn is_in(full_path: &Path, parent_folder_to_find: &str, folder_to_find: &str) -> bool {
237    if let Some(parent) = full_path.parent() {
238        if parent.file_name().map_or_else(
239            || false,
240            |f| {
241                f == folder_to_find
242                    && parent
243                        .parent()
244                        .and_then(|f| f.file_name())
245                        .map_or_else(|| false, |f| f == parent_folder_to_find)
246            },
247        ) {
248            true
249        } else {
250            is_in(parent, parent_folder_to_find, folder_to_find)
251        }
252    } else {
253        false
254    }
255}
256
257fn skip_markdown_path(path: &Path) -> bool {
258    // These aren't ready for tidy.
259    const SKIP_MD: &[&str] = &[
260        "src/doc/edition-guide",
261        "src/doc/embedded-book",
262        "src/doc/nomicon",
263        "src/doc/reference",
264        "src/doc/rust-by-example",
265        "src/doc/rustc-dev-guide",
266    ];
267    SKIP_MD.iter().any(|p| path.ends_with(p))
268}
269
270fn is_unexplained_ignore(extension: &str, line: &str) -> bool {
271    if !line.ends_with("```ignore") && !line.ends_with("```rust,ignore") {
272        return false;
273    }
274    if extension == "md" && line.trim().starts_with("//") {
275        // Markdown examples may include doc comments with ignore inside a
276        // code block.
277        return false;
278    }
279    true
280}
281
282pub fn check(path: &Path, tidy_ctx: TidyCtx) {
283    let mut check = tidy_ctx.start_check(CheckId::new("style").path(path));
284
285    fn skip(path: &Path, is_dir: bool) -> bool {
286        if path.file_name().is_some_and(|name| name.to_string_lossy().starts_with(".#")) {
287            // vim or emacs temporary file
288            return true;
289        }
290
291        if filter_dirs(path) || skip_markdown_path(path) {
292            return true;
293        }
294
295        // Don't check extensions for directories
296        if is_dir {
297            return false;
298        }
299
300        let extensions = ["rs", "py", "js", "sh", "c", "cpp", "h", "md", "css", "goml"];
301
302        // NB: don't skip paths without extensions (or else we'll skip all directories and will only check top level files)
303        if path.extension().is_none_or(|ext| !extensions.iter().any(|e| ext == OsStr::new(e))) {
304            return true;
305        }
306
307        // We only check CSS files in rustdoc.
308        path.extension().is_some_and(|e| e == "css") && !is_in(path, "src", "librustdoc")
309    }
310
311    walk(path, skip, &mut |entry, contents| {
312        let file = entry.path();
313        check_file_style(path, &mut check, file, contents);
314    });
315}
316
317// This creates a RegexSet as regex contains performance optimizations to be able to deal with these over
318// 2000 needles efficiently. This runs over the entire source code, so performance matters.
319static PROBLEMATIC_REGEX: LazyLock<regex::RegexSet> = LazyLock::new(|| {
320    RegexSetBuilder::new(PROBLEMATIC_CONSTS_STRINGS.as_slice())
321        .case_insensitive(true)
322        .build()
323        .unwrap()
324});
325
326fn check_file_style(base_path: &Path, check: &mut RunningCheck, file: &Path, contents: &str) {
327    // In some cases, a style check would be triggered by its own implementation
328    // or comments. A simple workaround is to just allowlist this file.
329    let this_file = Path::new(file!());
330    let codegen_file = Path::new("src/tools/tidy/src/codegen.rs");
331
332    let path_str = file.to_string_lossy();
333    let filename = file.file_name().unwrap().to_string_lossy();
334
335    let is_css_file = filename.ends_with(".css");
336    let under_rustfmt = filename.ends_with(".rs") &&
337            // This list should ideally be sourced from rustfmt.toml but we don't want to add a toml
338            // parser to tidy.
339            !file.ancestors().any(|a| {
340                (a.ends_with("tests") && a.join("COMPILER_TESTS.md").exists()) ||
341                    a.ends_with("src/doc/book")
342            });
343
344    if contents.is_empty() {
345        // __init__.py files are expected to be empty in many cases. Early returning prevents
346        // extraneous errors (e.g. leading/trailing newline).
347        if file.file_name().is_some_and(|x| x == "__init__.py") {
348            return;
349        }
350        check.error(format!("{}: empty file", file.display()));
351    }
352
353    let extension = file.extension().unwrap().to_string_lossy();
354    let is_error_code = extension == "md" && is_in(file, "src", "error_codes");
355    let is_goml_code = extension == "goml";
356
357    let max_columns = if is_error_code {
358        ERROR_CODE_COLS
359    } else if is_goml_code {
360        GOML_COLS
361    } else {
362        COLS
363    };
364
365    // When you change this, also change the `directive_line_starts` variable below
366    let can_contain = match_ignore(contents, false, None) || match_ignore(contents, true, None);
367
368    // Enable testing ICE's that require specific (untidy)
369    // file formats easily eg. `issue-1234-ignore-tidy.rs`
370    if filename.contains("ignore-tidy") {
371        return;
372    }
373    // Shell completions are automatically generated
374    if let Some(p) = file.parent()
375        && p.ends_with(Path::new("src/etc/completions"))
376    {
377        return;
378    }
379
380    let file_ignore = Directives::from_str(&path_str, LineNumber::WholeFile, can_contain, contents);
381    // the ignores set in this line, meant for the next line
382    let mut next_line_ignore = Default::default();
383
384    // return immediately if we should ignore this entire file
385    if file_ignore.all.is_ignore_and_defuse() {
386        file_ignore.iter().for_each(|i| i.force_discard_unsused_ignore());
387        return;
388    }
389
390    let mut leading_new_lines = false;
391    let mut trailing_new_lines = 0;
392    let mut lines = 0;
393    let mut last_safety_comment = false;
394    let mut comment_block: Option<(usize, usize, NamedDirective)> = None;
395    let is_test =
396        file.components().any(|c| c.as_os_str() == "tests") || file.file_stem().unwrap() == "tests";
397    let is_codegen_test = is_test && file.components().any(|c| c.as_os_str() == "codegen-llvm");
398    let is_this_file = file.ends_with(this_file) || this_file.ends_with(file);
399    let is_test_for_this_file =
400        is_test && file.parent().unwrap().ends_with(this_file.with_extension(""));
401    let is_codegen_tidy_file = file.ends_with(codegen_file);
402    // scanning the whole file for multiple needles at once is more efficient than
403    // executing lines times needles separate searches.
404    let any_problematic_line =
405        !is_this_file && !is_test_for_this_file && PROBLEMATIC_REGEX.is_match(contents);
406    for (i, line) in contents.split('\n').enumerate() {
407        if line.is_empty() {
408            if i == 0 {
409                leading_new_lines = true;
410            }
411            trailing_new_lines += 1;
412            continue;
413        } else {
414            trailing_new_lines = 0;
415        }
416
417        let line_number = i + 1;
418
419        let mut ignore = file_ignore.create_child(
420            mem::replace(
421                &mut next_line_ignore,
422                Directives::from_str(&path_str, LineNumber::Line(line_number), can_contain, line),
423            ),
424            check,
425            file,
426        );
427
428        let trimmed = line.trim();
429
430        if !trimmed.starts_with("//") {
431            lines += 1;
432        }
433
434        let mut err = |msg: &str| {
435            check.error(format!("{}:{}: {msg}", file.display(), line_number));
436        };
437
438        if !is_this_file
439            && trimmed.contains("dbg!")
440            && !trimmed.starts_with("//")
441            && !file.ancestors().any(|a| {
442                (a.ends_with("tests") && a.join("COMPILER_TESTS.md").exists())
443                    || a.ends_with("library/alloctests")
444            })
445            && filename != "tests.rs"
446        {
447            suppressible_tidy_err!(
448                err,
449                ignore.dbg,
450                "`dbg!` macro is intended as a debugging tool. It should not be in version control."
451            )
452        }
453
454        if !is_this_file
455            && trimmed.contains("todo!")
456            && !trimmed.starts_with("//")
457            && !file.ancestors().any(|a| {
458                (a.ends_with("tests") && a.join("COMPILER_TESTS.md").exists())
459                    || a.ends_with("library/alloctests")
460            })
461            && filename != "tests.rs"
462        {
463            let without_macro_call =
464                trimmed.split_once("todo!").expect("todo in line because of previous check").1;
465            let without_start =
466                without_macro_call.split_once("(").map_or(without_macro_call, |(_, s)| s);
467            let without_end =
468                without_start.rsplit_once(")").map_or(without_start, |(s, _)| s).trim();
469            let message = if without_end.is_empty() {
470                format_args!("")
471            } else {
472                format_args!("\n >> TODO: {}", without_end)
473            };
474
475            suppressible_tidy_err!(
476                err,
477                ignore.todo,
478                "the `todo!` macro is used for tasks that should be done before merging a PR.\nIf you want to panic here, use `panic!`, `unimplemented!`, `unreachable!`, `rustc_middle::bug!` or an assertion{message}"
479            )
480        }
481
482        if is_codegen_test && trimmed.contains("CHECK") && trimmed.ends_with(": br") {
483            err("`CHECK: br` and `CHECK-NOT: br` in codegen tests are fragile to false \
484                    positives in mangled symbols. Try using `br {{.*}}` instead.")
485        }
486
487        if !under_rustfmt
488            && line.chars().count() > max_columns
489            && !long_line_is_ok(&extension, is_error_code, max_columns, line)
490        {
491            suppressible_tidy_err!(err, ignore.linelength, "line longer than {max_columns} chars");
492        }
493        if !is_css_file && line.contains('\t') {
494            suppressible_tidy_err!(err, ignore.tab, "tab character");
495        }
496        if line.ends_with(' ') || line.ends_with('\t') {
497            suppressible_tidy_err!(err, ignore.end_whitespace, "trailing whitespace");
498        }
499        if is_css_file && line.starts_with(' ') {
500            err("CSS files use tabs for indent");
501        }
502        if line.contains('\r') {
503            suppressible_tidy_err!(err, ignore.cr, "CR character");
504        }
505        if !is_this_file && !is_codegen_tidy_file {
506            let directive_line_starts = ["// ", "# ", "/* ", "<!-- "];
507            let possible_line_start =
508                directive_line_starts.into_iter().any(|s| line.starts_with(s));
509            let contains_potential_directive =
510                possible_line_start && (line.contains("-tidy") || line.contains("tidy-"));
511            let has_recognized_ignore_directive = can_contain
512                && (Directives::parse(LineNumber::Line(line_number), line)
513                    .iter()
514                    .any(|directive| directive.is_ignore_and_defuse())
515                    || Directives::parse(LineNumber::WholeFile, line)
516                        .iter()
517                        .any(|directive| directive.is_ignore_and_defuse()));
518            let has_alphabetical_directive =
519                line.contains("tidy-alphabetical-start") || line.contains("tidy-alphabetical-end");
520            let has_other_tidy_ignore_directive =
521                line.contains("ignore-tidy-target-specific-tests");
522            let has_recognized_directive = has_recognized_ignore_directive
523                || has_alphabetical_directive
524                || has_other_tidy_ignore_directive;
525            if contains_potential_directive && (!has_recognized_directive) {
526                err("Unrecognized tidy directive")
527            }
528            if trimmed.contains("TODO") {
529                let without_todo =
530                    trimmed.split_once("TODO").expect("TODO in line because of previous check").1;
531                let without_colon = without_todo.trim().trim_start_matches(":").trim();
532
533                let message = if without_colon.is_empty() {
534                    format_args!("")
535                } else {
536                    format_args!("\n >> TODO: {}", without_colon)
537                };
538                suppressible_tidy_err!(
539                    err,
540                    ignore.todo,
541                    "TODO is used for tasks that should be done before merging a PR;\nIf you want to leave a message in the codebase use FIXME{message}",
542                )
543            }
544            if trimmed.contains("//") && trimmed.contains(" XXX") {
545                err("Instead of XXX use FIXME")
546            }
547            if any_problematic_line && contains_problematic_const(trimmed) {
548                err("Don't use magic numbers that spell things (consider 0x12345678)");
549            }
550        }
551        // Only check core & alloc for now; to be expanded to (parts of)
552        // std in the future as well.
553        if trimmed.contains("unsafe {")
554            && !trimmed.starts_with("//")
555            && !last_safety_comment
556            && !is_test
557            && base_path.ends_with("library")
558            && file
559                .strip_prefix(base_path)
560                .is_ok_and(|rel| rel.starts_with("core") || rel.starts_with("alloc"))
561        {
562            suppressible_tidy_err!(err, ignore.undocumented_unsafe, "undocumented unsafe");
563        }
564        if trimmed.contains("// SAFETY:") {
565            last_safety_comment = true;
566        } else if trimmed.starts_with("//") || trimmed.is_empty() {
567            // keep previous value
568        } else {
569            last_safety_comment = false;
570        }
571        if (line.starts_with("// Copyright")
572            || line.starts_with("# Copyright")
573            || line.starts_with("Copyright"))
574            && (trimmed.contains("Rust Developers") || trimmed.contains("Rust Project Developers"))
575        {
576            suppressible_tidy_err!(
577                err,
578                ignore.copyright,
579                "copyright notices attributed to the Rust Project Developers are deprecated"
580            );
581        }
582        if !file.components().any(|c| c.as_os_str() == "rustc_baked_icu_data")
583            && is_unexplained_ignore(&extension, line)
584        {
585            err(UNEXPLAINED_IGNORE_DOCTEST_INFO);
586        }
587
588        if filename.ends_with(".cpp") && line.contains("llvm_unreachable") {
589            err(LLVM_UNREACHABLE_INFO);
590        }
591
592        // For now only enforce in compiler
593        let is_compiler = || file.components().any(|c| c.as_os_str() == "compiler");
594
595        if is_compiler() {
596            if line.contains("//")
597                && line
598                    .chars()
599                    .collect::<Vec<_>>()
600                    .windows(4)
601                    .any(|cs| matches!(cs, ['.', ' ', ' ', last] if last.is_alphabetic()))
602            {
603                err(DOUBLE_SPACE_AFTER_DOT)
604            }
605
606            // Heuristics for matching unbalanced backticks by trying to find comments and
607            // comment blocks. Technically, this can have false negatives (or false positives),
608            // but as a heuristic this is fine.
609            let likely_comment = |trimmed: &str| {
610                if trimmed.contains("ignore-tidy") {
611                    return false;
612                }
613
614                // Line comments, doc comments
615                trimmed.contains("//")
616                        // Also account for `#[cfg_attr(bootstrap, doc = "")]` cases.
617                        || (trimmed.contains("cfg_attr") && trimmed.contains("doc"))
618            };
619
620            if likely_comment(trimmed) {
621                let (start_line, mut backtick_count, directive) =
622                    comment_block.take().unwrap_or((line_number, 0, ignore.odd_backticks.take()));
623                let line_backticks = trimmed.chars().filter(|ch| *ch == '`').count();
624
625                // Try to split `//`-like comments or `#[cfg_attr(bootstrap), doc = ""]`-like
626                // doc attributes. Fuzzy, but probably good enough.
627                let comment_text = match trimmed.split("//").nth(1) {
628                    Some(text) => text,
629                    None => {
630                        // Fallback to try look for RHS of doc attr bits.
631                        let (_doc, rest) =
632                            trimmed.split_once("doc").expect("failed to find `doc` attribute");
633                        rest
634                    }
635                };
636
637                // If backticks on a given comment line is not balanced, add to backtick count.
638                // This is to account for wrapped backticks and code blocks.
639                if line_backticks % 2 == 1 {
640                    backtick_count += comment_text.chars().filter(|ch| *ch == '`').count();
641                }
642                comment_block = Some((start_line, backtick_count, directive));
643            } else if let Some((start_line, backtick_count, directive)) = comment_block.take()
644                && backtick_count % 2 == 1
645            {
646                let mut err = |msg: &str| {
647                    check.error(format!("{}:{start_line}: {msg}", file.display()));
648                };
649                let block_len = line_number - start_line;
650                if block_len == 1 {
651                    suppressible_tidy_err!(
652                        err,
653                        // use the directives from when the block started
654                        directive,
655                        "comment with odd number of backticks"
656                    );
657                } else {
658                    suppressible_tidy_err!(
659                        err,
660                        // use the directives from when the block started
661                        directive,
662                        "{block_len}-line comment block with odd number of backticks"
663                    );
664                }
665
666                directive.check_usage(check, file);
667            }
668        }
669
670        ignore.check_usage(check, file);
671    }
672    if leading_new_lines {
673        let mut err = |_| {
674            check.error(format!("{}: leading newline", file.display()));
675        };
676        suppressible_tidy_err!(err, file_ignore.leading_newlines, "missing leading newline");
677    }
678    let mut err = |msg: &str| {
679        check.error(format!("{}: {}", file.display(), msg));
680    };
681    match trailing_new_lines {
682        0 => suppressible_tidy_err!(err, file_ignore.trailing_newlines, "missing trailing newline"),
683        1 => {}
684        n => suppressible_tidy_err!(
685            err,
686            file_ignore.trailing_newlines,
687            "too many trailing newlines ({n})"
688        ),
689    };
690    if lines > LINES {
691        let mut err = |_| {
692            check.error(format!(
693                "{}: too many lines ({lines}) (add `// \
694                     ignore-tidy-file-filelength` to the file to suppress this error)",
695                file.display(),
696            ));
697        };
698        suppressible_tidy_err!(err, file_ignore.filelength, "");
699    }
700
701    if let Some((_, _, directive)) = comment_block.take() {
702        directive.check_usage(check, file);
703    }
704    drop(comment_block);
705    next_line_ignore.check_usage(check, file);
706    file_ignore.check_usage(check, file);
707}