1use std::ffi::OsStr;
21use std::path::Path;
22use std::sync::LazyLock;
23
24use regex::RegexSetBuilder;
25use rustc_hash::FxHashMap;
26
27use crate::walk::{filter_dirs, walk};
28
29#[cfg(test)]
30mod tests;
31
32const ERROR_CODE_COLS: usize = 80;
35const COLS: usize = 100;
36const GOML_COLS: usize = 120;
37
38const LINES: usize = 3000;
39
40const UNEXPLAINED_IGNORE_DOCTEST_INFO: &str = r#"unexplained "```ignore" doctest; try one:
41
42* make the test actually pass, by adding necessary imports and declarations, or
43* use "```text", if the code is not Rust code, or
44* use "```compile_fail,Ennnn", if the code is expected to fail at compile time, or
45* use "```should_panic", if the code is expected to fail at run time, or
46* use "```no_run", if the code should type-check but not necessary linkable/runnable, or
47* explain it like "```ignore (cannot-test-this-because-xxxx)", if the annotation cannot be avoided.
48
49"#;
50
51const LLVM_UNREACHABLE_INFO: &str = r"\
52C++ code used llvm_unreachable, which triggers undefined behavior
53when executed when assertions are disabled.
54Use llvm::report_fatal_error for increased robustness.";
55
56const DOUBLE_SPACE_AFTER_DOT: &str = r"\
57Use a single space after dots in comments.";
58
59const ANNOTATIONS_TO_IGNORE: &[&str] = &[
60 "// @!has",
61 "// @has",
62 "// @matches",
63 "// CHECK",
64 "// EMIT_MIR",
65 "// compile-flags",
66 "//@ compile-flags",
67 "// error-pattern",
68 "//@ error-pattern",
69 "// gdb",
70 "// lldb",
71 "// cdb",
72 "//@ normalize-stderr",
73];
74
75const LINELENGTH_CHECK: &str = "linelength";
76
77const CONFIGURABLE_CHECKS: [&str; 11] = [
79 "cr",
80 "undocumented-unsafe",
81 "tab",
82 LINELENGTH_CHECK,
83 "filelength",
84 "end-whitespace",
85 "trailing-newlines",
86 "leading-newlines",
87 "copyright",
88 "dbg",
89 "odd-backticks",
90];
91
92fn generate_problems<'a>(
93 consts: &'a [u32],
94 letter_digit: &'a FxHashMap<char, char>,
95) -> impl Iterator<Item = u32> + 'a {
96 consts.iter().flat_map(move |const_value| {
97 let problem =
98 letter_digit.iter().fold(format!("{:X}", const_value), |acc, (key, value)| {
99 acc.replace(&value.to_string(), &key.to_string())
100 });
101 let indexes: Vec<usize> = problem
102 .chars()
103 .enumerate()
104 .filter_map(|(index, c)| if letter_digit.contains_key(&c) { Some(index) } else { None })
105 .collect();
106 (0..1 << indexes.len()).map(move |i| {
107 u32::from_str_radix(
108 &problem
109 .chars()
110 .enumerate()
111 .map(|(index, c)| {
112 if let Some(pos) = indexes.iter().position(|&x| x == index) {
113 if (i >> pos) & 1 == 1 { letter_digit[&c] } else { c }
114 } else {
115 c
116 }
117 })
118 .collect::<String>(),
119 0x10,
120 )
121 .unwrap()
122 })
123 })
124}
125
126const ROOT_PROBLEMATIC_CONSTS: &[u32] = &[
128 184594741, 2880289470, 2881141438, 2965027518, 2976579765, 3203381950, 3405691582, 3405697037,
129 3735927486, 3735932941, 4027431614, 4276992702, 195934910, 252707358, 762133, 179681982,
130 173390526, 721077,
131];
132
133const LETTER_DIGIT: &[(char, char)] = &[('A', '4'), ('B', '8'), ('E', '3')];
134
135fn generate_problematic_strings(
137 consts: &[u32],
138 letter_digit: &FxHashMap<char, char>,
139) -> Vec<String> {
140 generate_problems(consts, letter_digit)
141 .flat_map(|v| vec![v.to_string(), format!("{:X}", v)])
142 .collect()
143}
144
145static PROBLEMATIC_CONSTS_STRINGS: LazyLock<Vec<String>> = LazyLock::new(|| {
146 generate_problematic_strings(ROOT_PROBLEMATIC_CONSTS, &LETTER_DIGIT.iter().cloned().collect())
147});
148
149fn contains_problematic_const(trimmed: &str) -> bool {
150 PROBLEMATIC_CONSTS_STRINGS.iter().any(|s| trimmed.to_uppercase().contains(s))
151}
152
153const INTERNAL_COMPILER_DOCS_LINE: &str = "#### This error code is internal to the compiler and will not be emitted with normal Rust code.";
154
155#[derive(Clone, Copy, PartialEq)]
157#[allow(non_camel_case_types)]
158enum LIUState {
159 EXP_COMMENT_START,
160 EXP_LINK_LABEL_OR_URL,
161 EXP_URL,
162 EXP_END,
163}
164
165fn line_is_url(is_error_code: bool, columns: usize, line: &str) -> bool {
172 if is_error_code {
174 return line.starts_with('[') && line.contains("]:") && line.contains("http");
175 }
176
177 use self::LIUState::*;
178 let mut state: LIUState = EXP_COMMENT_START;
179 let is_url = |w: &str| w.starts_with("http://") || w.starts_with("https://");
180
181 for tok in line.split_whitespace() {
182 match (state, tok) {
183 (EXP_COMMENT_START, "//") | (EXP_COMMENT_START, "///") | (EXP_COMMENT_START, "//!") => {
184 state = EXP_LINK_LABEL_OR_URL
185 }
186
187 (EXP_LINK_LABEL_OR_URL, w)
188 if w.len() >= 4 && w.starts_with('[') && w.ends_with("]:") =>
189 {
190 state = EXP_URL
191 }
192
193 (EXP_LINK_LABEL_OR_URL, w) if is_url(w) => state = EXP_END,
194
195 (EXP_URL, w) if is_url(w) || w.starts_with("../") => state = EXP_END,
196
197 (_, w) if w.len() > columns && is_url(w) => state = EXP_END,
198
199 (_, _) => {}
200 }
201 }
202
203 state == EXP_END
204}
205
206fn should_ignore(line: &str) -> bool {
209 static_regex!("\\s*//(\\[.*\\])?~.*").is_match(line)
213 || ANNOTATIONS_TO_IGNORE.iter().any(|a| line.contains(a))
214
215 || static_regex!("\\s*//@(\\[.*\\]) (compile-flags|normalize-stderr|error-pattern).*")
219 .is_match(line)
220 || static_regex!(
223 "\\s*//@ \\!?(count|files|has|has-dir|hasraw|matches|matchesraw|snapshot)\\s.*"
224 ).is_match(line)
225}
226
227fn long_line_is_ok(extension: &str, is_error_code: bool, max_columns: usize, line: &str) -> bool {
229 match extension {
230 "ftl" => true,
232 "md" if !is_error_code => true,
234 "md" if line == INTERNAL_COMPILER_DOCS_LINE => true,
236 _ => line_is_url(is_error_code, max_columns, line) || should_ignore(line),
237 }
238}
239
240#[derive(Clone, Copy)]
241enum Directive {
242 Deny,
244
245 Ignore(bool),
250}
251
252fn contains_ignore_directives<const N: usize>(
255 path_str: &str,
256 can_contain: bool,
257 contents: &str,
258 checks: [&str; N],
259) -> [Directive; N] {
260 let always_ignore_linelength = path_str.contains("rustdoc-json");
263
264 if !can_contain && !always_ignore_linelength {
265 return [Directive::Deny; N];
266 }
267
268 checks.map(|check| {
269 if check == LINELENGTH_CHECK && always_ignore_linelength {
270 return Directive::Ignore(false);
271 }
272
273 if contents.contains(&format!("// ignore-tidy-{check}"))
275 || contents.contains(&format!("# ignore-tidy-{check}"))
276 || contents.contains(&format!("/* ignore-tidy-{check} */"))
277 || contents.contains(&format!("<!-- ignore-tidy-{check} -->"))
278 {
279 Directive::Ignore(false)
280 } else {
281 Directive::Deny
282 }
283 })
284}
285
286macro_rules! suppressible_tidy_err {
287 ($err:ident, $skip:ident, $msg:literal) => {
288 if let Directive::Deny = $skip {
289 $err(&format!($msg));
290 } else {
291 $skip = Directive::Ignore(true);
292 }
293 };
294}
295
296pub fn is_in(full_path: &Path, parent_folder_to_find: &str, folder_to_find: &str) -> bool {
297 if let Some(parent) = full_path.parent() {
298 if parent.file_name().map_or_else(
299 || false,
300 |f| {
301 f == folder_to_find
302 && parent
303 .parent()
304 .and_then(|f| f.file_name())
305 .map_or_else(|| false, |f| f == parent_folder_to_find)
306 },
307 ) {
308 true
309 } else {
310 is_in(parent, parent_folder_to_find, folder_to_find)
311 }
312 } else {
313 false
314 }
315}
316
317fn skip_markdown_path(path: &Path) -> bool {
318 const SKIP_MD: &[&str] = &[
320 "src/doc/edition-guide",
321 "src/doc/embedded-book",
322 "src/doc/nomicon",
323 "src/doc/reference",
324 "src/doc/rust-by-example",
325 "src/doc/rustc-dev-guide",
326 ];
327 SKIP_MD.iter().any(|p| path.ends_with(p))
328}
329
330fn is_unexplained_ignore(extension: &str, line: &str) -> bool {
331 if !line.ends_with("```ignore") && !line.ends_with("```rust,ignore") {
332 return false;
333 }
334 if extension == "md" && line.trim().starts_with("//") {
335 return false;
338 }
339 true
340}
341
342pub fn check(path: &Path, bad: &mut bool) {
343 fn skip(path: &Path, is_dir: bool) -> bool {
344 if path.file_name().map_or(false, |name| name.to_string_lossy().starts_with(".#")) {
345 return true;
347 }
348
349 if filter_dirs(path) || skip_markdown_path(path) {
350 return true;
351 }
352
353 if is_dir {
355 return false;
356 }
357
358 let extensions = ["rs", "py", "js", "sh", "c", "cpp", "h", "md", "css", "ftl", "goml"];
359
360 if path.extension().map_or(true, |ext| !extensions.iter().any(|e| ext == OsStr::new(e))) {
362 return true;
363 }
364
365 path.extension().map_or(false, |e| e == "css") && !is_in(path, "src", "librustdoc")
367 }
368
369 let problematic_regex = RegexSetBuilder::new(PROBLEMATIC_CONSTS_STRINGS.as_slice())
372 .case_insensitive(true)
373 .build()
374 .unwrap();
375
376 let this_file = Path::new(file!());
379
380 walk(path, skip, &mut |entry, contents| {
381 let file = entry.path();
382 let path_str = file.to_string_lossy();
383 let filename = file.file_name().unwrap().to_string_lossy();
384
385 let is_css_file = filename.ends_with(".css");
386 let under_rustfmt = filename.ends_with(".rs") &&
387 !file.ancestors().any(|a| {
390 (a.ends_with("tests") && a.join("COMPILER_TESTS.md").exists()) ||
391 a.ends_with("src/doc/book")
392 });
393
394 if contents.is_empty() {
395 tidy_error!(bad, "{}: empty file", file.display());
396 }
397
398 let extension = file.extension().unwrap().to_string_lossy();
399 let is_error_code = extension == "md" && is_in(file, "src", "error_codes");
400 let is_goml_code = extension == "goml";
401
402 let max_columns = if is_error_code {
403 ERROR_CODE_COLS
404 } else if is_goml_code {
405 GOML_COLS
406 } else {
407 COLS
408 };
409
410 let can_contain = contents.contains("// ignore-tidy-")
412 || contents.contains("# ignore-tidy-")
413 || contents.contains("/* ignore-tidy-")
414 || contents.contains("<!-- ignore-tidy-");
415 if filename.contains("ignore-tidy") {
418 return;
419 }
420 if let Some(p) = file.parent() {
422 if p.ends_with(Path::new("src/etc/completions")) {
423 return;
424 }
425 }
426 let [
427 mut skip_cr,
428 mut skip_undocumented_unsafe,
429 mut skip_tab,
430 mut skip_line_length,
431 mut skip_file_length,
432 mut skip_end_whitespace,
433 mut skip_trailing_newlines,
434 mut skip_leading_newlines,
435 mut skip_copyright,
436 mut skip_dbg,
437 mut skip_odd_backticks,
438 ] = contains_ignore_directives(&path_str, can_contain, &contents, CONFIGURABLE_CHECKS);
439 let mut leading_new_lines = false;
440 let mut trailing_new_lines = 0;
441 let mut lines = 0;
442 let mut last_safety_comment = false;
443 let mut comment_block: Option<(usize, usize)> = None;
444 let is_test = file.components().any(|c| c.as_os_str() == "tests")
445 || file.file_stem().unwrap() == "tests";
446 let is_this_file = file.ends_with(this_file) || this_file.ends_with(file);
447 let is_test_for_this_file =
448 is_test && file.parent().unwrap().ends_with(this_file.with_extension(""));
449 let any_problematic_line =
452 !is_this_file && !is_test_for_this_file && problematic_regex.is_match(contents);
453 for (i, line) in contents.split('\n').enumerate() {
454 if line.is_empty() {
455 if i == 0 {
456 leading_new_lines = true;
457 }
458 trailing_new_lines += 1;
459 continue;
460 } else {
461 trailing_new_lines = 0;
462 }
463
464 let trimmed = line.trim();
465
466 if !trimmed.starts_with("//") {
467 lines += 1;
468 }
469
470 let mut err = |msg: &str| {
471 tidy_error!(bad, "{}:{}: {}", file.display(), i + 1, msg);
472 };
473
474 if trimmed.contains("dbg!")
475 && !trimmed.starts_with("//")
476 && !file.ancestors().any(|a| {
477 (a.ends_with("tests") && a.join("COMPILER_TESTS.md").exists())
478 || a.ends_with("library/alloctests")
479 })
480 && filename != "tests.rs"
481 {
482 suppressible_tidy_err!(
483 err,
484 skip_dbg,
485 "`dbg!` macro is intended as a debugging tool. It should not be in version control."
486 )
487 }
488
489 if !under_rustfmt
490 && line.chars().count() > max_columns
491 && !long_line_is_ok(&extension, is_error_code, max_columns, line)
492 {
493 suppressible_tidy_err!(
494 err,
495 skip_line_length,
496 "line longer than {max_columns} chars"
497 );
498 }
499 if !is_css_file && line.contains('\t') {
500 suppressible_tidy_err!(err, skip_tab, "tab character");
501 }
502 if line.ends_with(' ') || line.ends_with('\t') {
503 suppressible_tidy_err!(err, skip_end_whitespace, "trailing whitespace");
504 }
505 if is_css_file && line.starts_with(' ') {
506 err("CSS files use tabs for indent");
507 }
508 if line.contains('\r') {
509 suppressible_tidy_err!(err, skip_cr, "CR character");
510 }
511 if !is_this_file {
512 let directive_line_starts = ["// ", "# ", "/* ", "<!-- "];
513 let possible_line_start =
514 directive_line_starts.into_iter().any(|s| line.starts_with(s));
515 let contains_potential_directive =
516 possible_line_start && (line.contains("-tidy") || line.contains("tidy-"));
517 let has_recognized_ignore_directive =
518 contains_ignore_directives(&path_str, can_contain, line, CONFIGURABLE_CHECKS)
519 .into_iter()
520 .any(|directive| matches!(directive, Directive::Ignore(_)));
521 let has_alphabetical_directive = line.contains("tidy-alphabetical-start")
522 || line.contains("tidy-alphabetical-end");
523 let has_recognized_directive =
524 has_recognized_ignore_directive || has_alphabetical_directive;
525 if contains_potential_directive && (!has_recognized_directive) {
526 err("Unrecognized tidy directive")
527 }
528 if trimmed.contains("TODO") && !trimmed.contains("ignore-tidy-todo") {
531 err(
532 "TODO is used for tasks that should be done before merging a PR; If you want to leave a message in the codebase use FIXME",
533 )
534 }
535 if trimmed.contains("//") && trimmed.contains(" XXX") {
536 err("Instead of XXX use FIXME")
537 }
538 if any_problematic_line && contains_problematic_const(trimmed) {
539 err("Don't use magic numbers that spell things (consider 0x12345678)");
540 }
541 }
542 if trimmed.contains("unsafe {")
544 && !trimmed.starts_with("//")
545 && !last_safety_comment
546 && file.components().any(|c| c.as_os_str() == "core")
547 && !is_test
548 {
549 suppressible_tidy_err!(err, skip_undocumented_unsafe, "undocumented unsafe");
550 }
551 if trimmed.contains("// SAFETY:") {
552 last_safety_comment = true;
553 } else if trimmed.starts_with("//") || trimmed.is_empty() {
554 } else {
556 last_safety_comment = false;
557 }
558 if (line.starts_with("// Copyright")
559 || line.starts_with("# Copyright")
560 || line.starts_with("Copyright"))
561 && (trimmed.contains("Rust Developers")
562 || trimmed.contains("Rust Project Developers"))
563 {
564 suppressible_tidy_err!(
565 err,
566 skip_copyright,
567 "copyright notices attributed to the Rust Project Developers are deprecated"
568 );
569 }
570 if !file.components().any(|c| c.as_os_str() == "rustc_baked_icu_data")
571 && is_unexplained_ignore(&extension, line)
572 {
573 err(UNEXPLAINED_IGNORE_DOCTEST_INFO);
574 }
575
576 if filename.ends_with(".cpp") && line.contains("llvm_unreachable") {
577 err(LLVM_UNREACHABLE_INFO);
578 }
579
580 let is_compiler = || file.components().any(|c| c.as_os_str() == "compiler");
582
583 if is_compiler() {
584 if line.contains("//")
585 && line
586 .chars()
587 .collect::<Vec<_>>()
588 .windows(4)
589 .any(|cs| matches!(cs, ['.', ' ', ' ', last] if last.is_alphabetic()))
590 {
591 err(DOUBLE_SPACE_AFTER_DOT)
592 }
593
594 if filename.ends_with(".ftl") {
595 let line_backticks = trimmed.chars().filter(|ch| *ch == '`').count();
596 if line_backticks % 2 == 1 {
597 suppressible_tidy_err!(err, skip_odd_backticks, "odd number of backticks");
598 }
599 } else if trimmed.contains("//") {
600 let (start_line, mut backtick_count) = comment_block.unwrap_or((i + 1, 0));
601 let line_backticks = trimmed.chars().filter(|ch| *ch == '`').count();
602 let comment_text = trimmed.split("//").nth(1).unwrap();
603 if line_backticks % 2 == 1 {
605 backtick_count += comment_text.chars().filter(|ch| *ch == '`').count();
606 }
607 comment_block = Some((start_line, backtick_count));
608 } else if let Some((start_line, backtick_count)) = comment_block.take() {
609 if backtick_count % 2 == 1 {
610 let mut err = |msg: &str| {
611 tidy_error!(bad, "{}:{start_line}: {msg}", file.display());
612 };
613 let block_len = (i + 1) - start_line;
614 if block_len == 1 {
615 suppressible_tidy_err!(
616 err,
617 skip_odd_backticks,
618 "comment with odd number of backticks"
619 );
620 } else {
621 suppressible_tidy_err!(
622 err,
623 skip_odd_backticks,
624 "{block_len}-line comment block with odd number of backticks"
625 );
626 }
627 }
628 }
629 }
630 }
631 if leading_new_lines {
632 let mut err = |_| {
633 tidy_error!(bad, "{}: leading newline", file.display());
634 };
635 suppressible_tidy_err!(err, skip_leading_newlines, "missing leading newline");
636 }
637 let mut err = |msg: &str| {
638 tidy_error!(bad, "{}: {}", file.display(), msg);
639 };
640 match trailing_new_lines {
641 0 => suppressible_tidy_err!(err, skip_trailing_newlines, "missing trailing newline"),
642 1 => {}
643 n => suppressible_tidy_err!(
644 err,
645 skip_trailing_newlines,
646 "too many trailing newlines ({n})"
647 ),
648 };
649 if lines > LINES {
650 let mut err = |_| {
651 tidy_error!(
652 bad,
653 "{}: too many lines ({}) (add `// \
654 ignore-tidy-filelength` to the file to suppress this error)",
655 file.display(),
656 lines
657 );
658 };
659 suppressible_tidy_err!(err, skip_file_length, "");
660 }
661
662 if let Directive::Ignore(false) = skip_cr {
663 tidy_error!(bad, "{}: ignoring CR characters unnecessarily", file.display());
664 }
665 if let Directive::Ignore(false) = skip_tab {
666 tidy_error!(bad, "{}: ignoring tab characters unnecessarily", file.display());
667 }
668 if let Directive::Ignore(false) = skip_end_whitespace {
669 tidy_error!(bad, "{}: ignoring trailing whitespace unnecessarily", file.display());
670 }
671 if let Directive::Ignore(false) = skip_trailing_newlines {
672 tidy_error!(bad, "{}: ignoring trailing newlines unnecessarily", file.display());
673 }
674 if let Directive::Ignore(false) = skip_leading_newlines {
675 tidy_error!(bad, "{}: ignoring leading newlines unnecessarily", file.display());
676 }
677 if let Directive::Ignore(false) = skip_copyright {
678 tidy_error!(bad, "{}: ignoring copyright unnecessarily", file.display());
679 }
680 let _unused = skip_line_length;
683 let _unused = skip_file_length;
684 })
685}