1 //! Tidy check to ensure error codes are properly documented and tested.
5 //! 1. We create a list of error codes used by the compiler. Error codes are extracted from `compiler/rustc_error_codes/src/error_codes.rs`.
7 //! 2. We check that the error code has a long-form explanation in `compiler/rustc_error_codes/src/error_codes/`.
8 //! - The explanation is expected to contain a `doctest` that fails with the correct error code. (`EXEMPT_FROM_DOCTEST` *currently* bypasses this check)
9 //! - Note that other stylistic conventions for markdown files are checked in the `style.rs` tidy check.
11 //! 3. We check that the error code has a UI test in `tests/ui/error-codes/`.
12 //! - We ensure that there is both a `Exxxx.rs` file and a corresponding `Exxxx.stderr` file.
13 //! - We also ensure that the error code is used in the tests.
14 //! - *Currently*, it is possible to opt-out of this check with the `EXEMPTED_FROM_TEST` constant.
16 //! 4. We check that the error code is actually emitted by the compiler.
17 //! - This is done by searching `compiler/` with a regex.
19 use std::{ffi::OsStr, fs, path::Path};
23 use crate::walk::{filter_dirs, walk, walk_many};
25 const ERROR_CODES_PATH: &str = "compiler/rustc_error_codes/src/error_codes.rs";
26 const ERROR_DOCS_PATH: &str = "compiler/rustc_error_codes/src/error_codes/";
27 const ERROR_TESTS_PATH: &str = "tests/ui/error-codes/";
29 // Error codes that (for some reason) can't have a doctest in their explanation. Error codes are still expected to provide a code example, even if untested.
30 const IGNORE_DOCTEST_CHECK: &[&str] =
31 &["E0208", "E0464", "E0570", "E0601", "E0602", "E0640", "E0717"];
33 // Error codes that don't yet have a UI test. This list will eventually be removed.
34 const IGNORE_UI_TEST_CHECK: &[&str] =
35 &["E0461", "E0465", "E0476", "E0514", "E0523", "E0554", "E0640", "E0717", "E0729", "E0789"];
37 macro_rules! verbose_print {
38 ($verbose:expr, $($fmt:tt)*) => {
40 println!("{}", format_args!($($fmt)*));
45 pub fn check(root_path: &Path, search_paths: &[&Path], verbose: bool, bad: &mut bool) {
46 let mut errors = Vec::new();
48 // Stage 1: create list
49 let error_codes = extract_error_codes(root_path, &mut errors, verbose);
50 println!("Found {} error codes", error_codes.len());
51 println!("Highest error code: `{}`", error_codes.iter().max().unwrap());
53 // Stage 2: check list has docs
54 let no_longer_emitted = check_error_codes_docs(root_path, &error_codes, &mut errors, verbose);
56 // Stage 3: check list has UI tests
57 check_error_codes_tests(root_path, &error_codes, &mut errors, verbose, &no_longer_emitted);
59 // Stage 4: check list is emitted by compiler
60 check_error_codes_used(search_paths, &error_codes, &mut errors, &no_longer_emitted, verbose);
64 tidy_error!(bad, "{}", error);
68 /// Stage 1: Parses a list of error codes from `error_codes.rs`.
69 fn extract_error_codes(root_path: &Path, errors: &mut Vec<String>, verbose: bool) -> Vec<String> {
70 let path = root_path.join(Path::new(ERROR_CODES_PATH));
72 fs::read_to_string(&path).unwrap_or_else(|e| panic!("failed to read `{path:?}`: {e}"));
74 let mut error_codes = Vec::new();
75 let mut reached_undocumented_codes = false;
77 for line in file.lines() {
78 let line = line.trim();
80 if !reached_undocumented_codes && line.starts_with('E') {
81 let split_line = line.split_once(':');
83 // Extract the error code from the line, emitting a fatal error if it is not in a correct format.
84 let err_code = if let Some(err_code) = split_line {
88 "Expected a line with the format `Exxxx: include_str!(\"..\")`, but got \"{}\" \
89 without a `:` delimiter",
95 // If this is a duplicate of another error code, emit a fatal error.
96 if error_codes.contains(&err_code) {
97 errors.push(format!("Found duplicate error code: `{}`", err_code));
101 // Ensure that the line references the correct markdown file.
102 let expected_filename = format!(" include_str!(\"./error_codes/{}.md\"),", err_code);
103 if expected_filename != split_line.unwrap().1 {
105 "Error code `{}` expected to reference docs with `{}` but instead found `{}` in \
106 `compiler/rustc_error_codes/src/error_codes.rs`",
109 split_line.unwrap().1,
114 error_codes.push(err_code);
115 } else if reached_undocumented_codes && line.starts_with('E') {
116 let err_code = match line.split_once(',') {
118 Some((err_code, _)) => err_code,
122 verbose_print!(verbose, "warning: Error code `{}` is undocumented.", err_code);
124 if error_codes.contains(&err_code) {
125 errors.push(format!("Found duplicate error code: `{}`", err_code));
128 error_codes.push(err_code);
129 } else if line == ";" {
130 // Once we reach the undocumented error codes, adapt to different syntax.
131 reached_undocumented_codes = true;
138 /// Stage 2: Checks that long-form error code explanations exist and have doctests.
139 fn check_error_codes_docs(
141 error_codes: &[String],
142 errors: &mut Vec<String>,
145 let docs_path = root_path.join(Path::new(ERROR_DOCS_PATH));
147 let mut no_longer_emitted_codes = Vec::new();
149 walk(&docs_path, &mut |_| false, &mut |entry, contents| {
150 let path = entry.path();
152 // Error if the file isn't markdown.
153 if path.extension() != Some(OsStr::new("md")) {
155 "Found unexpected non-markdown file in error code docs directory: {}",
161 // Make sure that the file is referenced in `error_codes.rs`
162 let filename = path.file_name().unwrap().to_str().unwrap().split_once('.');
163 let err_code = filename.unwrap().0; // `unwrap` is ok because we know the filename is in the correct format.
165 if error_codes.iter().all(|e| e != err_code) {
167 "Found valid file `{}` in error code docs directory without corresponding \
168 entry in `error_code.rs`",
174 let (found_code_example, found_proper_doctest, emit_ignore_warning, no_longer_emitted) =
175 check_explanation_has_doctest(&contents, &err_code);
177 if emit_ignore_warning {
180 "warning: Error code `{err_code}` uses the ignore header. This should not be used, add the error code to the \
181 `IGNORE_DOCTEST_CHECK` constant instead."
185 if no_longer_emitted {
186 no_longer_emitted_codes.push(err_code.to_owned());
189 if !found_code_example {
192 "warning: Error code `{err_code}` doesn't have a code example, all error codes are expected to have one \
198 let test_ignored = IGNORE_DOCTEST_CHECK.contains(&&err_code);
200 // Check that the explanation has a doctest, and if it shouldn't, that it doesn't
201 if !found_proper_doctest && !test_ignored {
203 "`{}` doesn't use its own error code in compile_fail example",
206 } else if found_proper_doctest && test_ignored {
208 "`{}` has a compile_fail doctest with its own error code, it shouldn't \
209 be listed in `IGNORE_DOCTEST_CHECK`",
215 no_longer_emitted_codes
218 /// This function returns a tuple indicating whether the provided explanation:
219 /// a) has a code example, tested or not.
220 /// b) has a valid doctest
221 fn check_explanation_has_doctest(explanation: &str, err_code: &str) -> (bool, bool, bool, bool) {
222 let mut found_code_example = false;
223 let mut found_proper_doctest = false;
225 let mut emit_ignore_warning = false;
226 let mut no_longer_emitted = false;
228 for line in explanation.lines() {
229 let line = line.trim();
231 if line.starts_with("```") {
232 found_code_example = true;
234 // Check for the `rustdoc` doctest headers.
235 if line.contains("compile_fail") && line.contains(err_code) {
236 found_proper_doctest = true;
239 if line.contains("ignore") {
240 emit_ignore_warning = true;
241 found_proper_doctest = true;
244 .starts_with("#### Note: this error code is no longer emitted by the compiler")
246 no_longer_emitted = true;
247 found_code_example = true;
248 found_proper_doctest = true;
252 (found_code_example, found_proper_doctest, emit_ignore_warning, no_longer_emitted)
255 // Stage 3: Checks that each error code has a UI test in the correct directory
256 fn check_error_codes_tests(
258 error_codes: &[String],
259 errors: &mut Vec<String>,
261 no_longer_emitted: &[String],
263 let tests_path = root_path.join(Path::new(ERROR_TESTS_PATH));
265 for code in error_codes {
266 let test_path = tests_path.join(format!("{}.stderr", code));
268 if !test_path.exists() && !IGNORE_UI_TEST_CHECK.contains(&code.as_str()) {
271 "warning: Error code `{code}` needs to have at least one UI test in the `tests/error-codes/` directory`!"
275 if IGNORE_UI_TEST_CHECK.contains(&code.as_str()) {
276 if test_path.exists() {
278 "Error code `{code}` has a UI test in `tests/ui/error-codes/{code}.rs`, it shouldn't be listed in `EXEMPTED_FROM_TEST`!"
284 let file = match fs::read_to_string(&test_path) {
289 "warning: Failed to read UI test file (`{}`) for `{code}` but the file exists. The test is assumed to work:\n{err}",
296 if no_longer_emitted.contains(code) {
297 // UI tests *can't* contain error codes that are no longer emitted.
301 let mut found_code = false;
303 for line in file.lines() {
305 // Assuming the line starts with `error[E`, we can substring the error code out.
306 if s.starts_with("error[E") {
307 if &s[6..11] == code {
317 "warning: Error code {code}`` has a UI test file, but doesn't contain its own error code!"
323 /// Stage 4: Search `compiler/` and ensure that every error code is actually used by the compiler and that no undocumented error codes exist.
324 fn check_error_codes_used(
325 search_paths: &[&Path],
326 error_codes: &[String],
327 errors: &mut Vec<String>,
328 no_longer_emitted: &[String],
331 // We want error codes which match the following cases:
333 // * foo(a, E0111, a)
336 // * #[error = "E0111"]
337 let regex = Regex::new(r#"[(,"\s](E\d{4})[,)"]"#).unwrap();
339 let mut found_codes = Vec::new();
341 walk_many(search_paths, &mut filter_dirs, &mut |entry, contents| {
342 let path = entry.path();
344 // Return early if we aren't looking at a source file.
345 if path.extension() != Some(OsStr::new("rs")) {
349 for line in contents.lines() {
350 // We want to avoid parsing error codes in comments.
351 if line.trim_start().starts_with("//") {
355 for cap in regex.captures_iter(line) {
356 if let Some(error_code) = cap.get(1) {
357 let error_code = error_code.as_str().to_owned();
359 if !error_codes.contains(&error_code) {
360 // This error code isn't properly defined, we must error.
361 errors.push(format!("Error code `{}` is used in the compiler but not defined and documented in `compiler/rustc_error_codes/src/error_codes.rs`.", error_code));
365 // This error code can now be marked as used.
366 found_codes.push(error_code);
372 for code in error_codes {
373 if !found_codes.contains(code) && !no_longer_emitted.contains(code) {
374 errors.push(format!("Error code `{code}` exists, but is not emitted by the compiler!"))
377 if found_codes.contains(code) && no_longer_emitted.contains(code) {
380 "warning: Error code `{code}` is used when it's marked as \"no longer emitted\""