Skip to content

Commit edd27cf

Browse files
authored
Rollup merge of #108482 - Ezrashaw:force-error-docs, r=GuillaumeGomez
statically guarantee that current error codes are documented Closes #61137 (that's right!) Pretty simple refactor (often just a change from `Result<Option<&str>>` to `Result<&str>`) r? `@GuillaumeGomez` (could you specially look at 5304415? I believe you wrote that in the first place, just want to make sure you're happy with the change)
2 parents be23b32 + 5304415 commit edd27cf

File tree

10 files changed

+37
-88
lines changed

10 files changed

+37
-88
lines changed

Cargo.lock

+1
Original file line numberDiff line numberDiff line change
@@ -1445,6 +1445,7 @@ name = "error_index_generator"
14451445
version = "0.0.0"
14461446
dependencies = [
14471447
"mdbook",
1448+
"rustc_error_codes",
14481449
]
14491450

14501451
[[package]]

compiler/rustc_driver_impl/src/lib.rs

+1-4
Original file line numberDiff line numberDiff line change
@@ -485,7 +485,7 @@ fn handle_explain(registry: Registry, code: &str, output: ErrorOutputType) {
485485
let normalised =
486486
if upper_cased_code.starts_with('E') { upper_cased_code } else { format!("E{code:0>4}") };
487487
match registry.try_find_description(&normalised) {
488-
Ok(Some(description)) => {
488+
Ok(description) => {
489489
let mut is_in_code_block = false;
490490
let mut text = String::new();
491491
// Slice off the leading newline and print.
@@ -509,9 +509,6 @@ fn handle_explain(registry: Registry, code: &str, output: ErrorOutputType) {
509509
print!("{text}");
510510
}
511511
}
512-
Ok(None) => {
513-
early_error(output, &format!("no extended information for {code}"));
514-
}
515512
Err(InvalidErrorCode) => {
516513
early_error(output, &format!("{code} is not a valid error code"));
517514
}

compiler/rustc_error_codes/src/error_codes.rs

+6-5
Original file line numberDiff line numberDiff line change
@@ -513,7 +513,9 @@ E0790: include_str!("./error_codes/E0790.md"),
513513
E0791: include_str!("./error_codes/E0791.md"),
514514
E0792: include_str!("./error_codes/E0792.md"),
515515
E0793: include_str!("./error_codes/E0793.md"),
516-
;
516+
}
517+
518+
// Undocumented removed error codes. Note that many removed error codes are documented.
517519
// E0006, // merged with E0005
518520
// E0008, // cannot bind by-move into a pattern guard
519521
// E0019, // merged into E0015
@@ -570,7 +572,7 @@ E0793: include_str!("./error_codes/E0793.md"),
570572
// E0246, // invalid recursive type
571573
// E0247,
572574
// E0248, // value used as a type, now reported earlier during resolution
573-
// as E0412
575+
// // as E0412
574576
// E0249,
575577
// E0257,
576578
// E0258,
@@ -631,14 +633,14 @@ E0793: include_str!("./error_codes/E0793.md"),
631633
// E0558, // replaced with a generic attribute input check
632634
// E0563, // cannot determine a type for this `impl Trait` removed in 6383de15
633635
// E0564, // only named lifetimes are allowed in `impl Trait`,
634-
// but `{}` was found in the type `{}`
636+
// // but `{}` was found in the type `{}`
635637
// E0598, // lifetime of {} is too short to guarantee its contents can be...
636638
// E0611, // merged into E0616
637639
// E0612, // merged into E0609
638640
// E0613, // Removed (merged with E0609)
639641
// E0629, // missing 'feature' (rustc_const_unstable)
640642
// E0630, // rustc_const_unstable attribute must be paired with stable/unstable
641-
// attribute
643+
// // attribute
642644
// E0645, // trait aliases not finished
643645
// E0694, // an unknown tool name found in scoped attributes
644646
// E0702, // replaced with a generic attribute input check
@@ -647,4 +649,3 @@ E0793: include_str!("./error_codes/E0793.md"),
647649
// E0721, // `await` keyword
648650
// E0723, // unstable feature in `const` context
649651
// E0738, // Removed; errored on `#[track_caller] fn`s in `extern "Rust" { ... }`.
650-
}

compiler/rustc_error_codes/src/lib.rs

+3-4
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,9 @@
55
//! the goal being to make their maintenance easier.
66
77
macro_rules! register_diagnostics {
8-
($($ecode:ident: $message:expr,)* ; $($code:ident,)*) => (
9-
pub static DIAGNOSTICS: &[(&str, Option<&str>)] = &[
10-
$( (stringify!($ecode), Some($message)), )*
11-
$( (stringify!($code), None), )*
8+
($($ecode:ident: $message:expr,)*) => (
9+
pub static DIAGNOSTICS: &[(&str, &str)] = &[
10+
$( (stringify!($ecode), $message), )*
1211
];
1312
)
1413
}

compiler/rustc_errors/src/json.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -580,7 +580,7 @@ impl DiagnosticCode {
580580
let je_result =
581581
je.registry.as_ref().map(|registry| registry.try_find_description(&s)).unwrap();
582582

583-
DiagnosticCode { code: s, explanation: je_result.unwrap_or(None) }
583+
DiagnosticCode { code: s, explanation: je_result.ok() }
584584
})
585585
}
586586
}

compiler/rustc_errors/src/lib.rs

+1-3
Original file line numberDiff line numberDiff line change
@@ -1477,9 +1477,7 @@ impl HandlerInner {
14771477
.emitted_diagnostic_codes
14781478
.iter()
14791479
.filter_map(|x| match &x {
1480-
DiagnosticId::Error(s)
1481-
if registry.try_find_description(s).map_or(false, |o| o.is_some()) =>
1482-
{
1480+
DiagnosticId::Error(s) if registry.try_find_description(s).is_ok() => {
14831481
Some(s.clone())
14841482
}
14851483
_ => None,

compiler/rustc_errors/src/registry.rs

+4-8
Original file line numberDiff line numberDiff line change
@@ -5,21 +5,17 @@ pub struct InvalidErrorCode;
55

66
#[derive(Clone)]
77
pub struct Registry {
8-
long_descriptions: FxHashMap<&'static str, Option<&'static str>>,
8+
long_descriptions: FxHashMap<&'static str, &'static str>,
99
}
1010

1111
impl Registry {
12-
pub fn new(long_descriptions: &[(&'static str, Option<&'static str>)]) -> Registry {
12+
pub fn new(long_descriptions: &[(&'static str, &'static str)]) -> Registry {
1313
Registry { long_descriptions: long_descriptions.iter().copied().collect() }
1414
}
1515

1616
/// Returns `InvalidErrorCode` if the code requested does not exist in the
17-
/// registry. Otherwise, returns an `Option` where `None` means the error
18-
/// code is valid but has no extended information.
19-
pub fn try_find_description(
20-
&self,
21-
code: &str,
22-
) -> Result<Option<&'static str>, InvalidErrorCode> {
17+
/// registry.
18+
pub fn try_find_description(&self, code: &str) -> Result<&'static str, InvalidErrorCode> {
2319
self.long_descriptions.get(code).copied().ok_or(InvalidErrorCode)
2420
}
2521
}

src/tools/error_index_generator/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ edition = "2021"
55

66
[dependencies]
77
mdbook = { version = "0.4", default-features = false, features = ["search"] }
8+
rustc_error_codes = { version = "0.0.0", path = "../../../compiler/rustc_error_codes" }
89

910
[[bin]]
1011
name = "error_index_generator"

src/tools/error_index_generator/main.rs

+16-42
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,6 @@
22

33
extern crate rustc_driver;
44

5-
// We use the function we generate from `register_diagnostics!`.
6-
use crate::error_codes::error_codes;
7-
85
use std::env;
96
use std::error::Error;
107
use std::fs::{self, File};
@@ -17,22 +14,6 @@ use std::str::FromStr;
1714
use mdbook::book::{parse_summary, BookItem, Chapter};
1815
use mdbook::{Config, MDBook};
1916

20-
macro_rules! register_diagnostics {
21-
($($error_code:ident: $message:expr,)+ ; $($undocumented:ident,)* ) => {
22-
pub fn error_codes() -> Vec<(&'static str, Option<&'static str>)> {
23-
let mut errors: Vec<(&str, Option<&str>)> = vec![
24-
$((stringify!($error_code), Some($message)),)+
25-
$((stringify!($undocumented), None),)*
26-
];
27-
errors.sort();
28-
errors
29-
}
30-
}
31-
}
32-
33-
#[path = "../../../compiler/rustc_error_codes/src/error_codes.rs"]
34-
mod error_codes;
35-
3617
enum OutputFormat {
3718
HTML,
3819
Markdown,
@@ -55,11 +36,8 @@ fn render_markdown(output_path: &Path) -> Result<(), Box<dyn Error>> {
5536

5637
write!(output_file, "# Rust Compiler Error Index\n")?;
5738

58-
for (err_code, description) in error_codes().iter() {
59-
match description {
60-
Some(ref desc) => write!(output_file, "## {}\n{}\n", err_code, desc)?,
61-
None => {}
62-
}
39+
for (err_code, description) in rustc_error_codes::DIAGNOSTICS.iter() {
40+
write!(output_file, "## {}\n{}\n", err_code, description)?
6341
}
6442

6543
Ok(())
@@ -105,27 +83,23 @@ This page lists all the error codes emitted by the Rust compiler.
10583
"
10684
);
10785

108-
let err_codes = error_codes();
86+
let err_codes = rustc_error_codes::DIAGNOSTICS;
10987
let mut chapters = Vec::with_capacity(err_codes.len());
11088

11189
for (err_code, explanation) in err_codes.iter() {
112-
if let Some(explanation) = explanation {
113-
introduction.push_str(&format!(" * [{0}](./{0}.html)\n", err_code));
114-
115-
let content = add_rust_attribute_on_codeblock(explanation);
116-
chapters.push(BookItem::Chapter(Chapter {
117-
name: err_code.to_string(),
118-
content: format!("# Error code {}\n\n{}\n", err_code, content),
119-
number: None,
120-
sub_items: Vec::new(),
121-
// We generate it into the `error_codes` folder.
122-
path: Some(PathBuf::from(&format!("{}.html", err_code))),
123-
source_path: None,
124-
parent_names: Vec::new(),
125-
}));
126-
} else {
127-
introduction.push_str(&format!(" * {}\n", err_code));
128-
}
90+
introduction.push_str(&format!(" * [{0}](./{0}.html)\n", err_code));
91+
92+
let content = add_rust_attribute_on_codeblock(explanation);
93+
chapters.push(BookItem::Chapter(Chapter {
94+
name: err_code.to_string(),
95+
content: format!("# Error code {}\n\n{}\n", err_code, content),
96+
number: None,
97+
sub_items: Vec::new(),
98+
// We generate it into the `error_codes` folder.
99+
path: Some(PathBuf::from(&format!("{}.html", err_code))),
100+
source_path: None,
101+
parent_names: Vec::new(),
102+
}));
129103
}
130104

131105
let mut config = Config::from_str(include_str!("book_config.toml"))?;

src/tools/tidy/src/error_codes.rs

+3-21
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ pub fn check(root_path: &Path, search_paths: &[&Path], verbose: bool, bad: &mut
4545
let mut errors = Vec::new();
4646

4747
// Stage 1: create list
48-
let error_codes = extract_error_codes(root_path, &mut errors, verbose);
48+
let error_codes = extract_error_codes(root_path, &mut errors);
4949
println!("Found {} error codes", error_codes.len());
5050
println!("Highest error code: `{}`", error_codes.iter().max().unwrap());
5151

@@ -65,18 +65,17 @@ pub fn check(root_path: &Path, search_paths: &[&Path], verbose: bool, bad: &mut
6565
}
6666

6767
/// Stage 1: Parses a list of error codes from `error_codes.rs`.
68-
fn extract_error_codes(root_path: &Path, errors: &mut Vec<String>, verbose: bool) -> Vec<String> {
68+
fn extract_error_codes(root_path: &Path, errors: &mut Vec<String>) -> Vec<String> {
6969
let path = root_path.join(Path::new(ERROR_CODES_PATH));
7070
let file =
7171
fs::read_to_string(&path).unwrap_or_else(|e| panic!("failed to read `{path:?}`: {e}"));
7272

7373
let mut error_codes = Vec::new();
74-
let mut reached_undocumented_codes = false;
7574

7675
for line in file.lines() {
7776
let line = line.trim();
7877

79-
if !reached_undocumented_codes && line.starts_with('E') {
78+
if line.starts_with('E') {
8079
let split_line = line.split_once(':');
8180

8281
// Extract the error code from the line, emitting a fatal error if it is not in a correct format.
@@ -111,23 +110,6 @@ fn extract_error_codes(root_path: &Path, errors: &mut Vec<String>, verbose: bool
111110
}
112111

113112
error_codes.push(err_code);
114-
} else if reached_undocumented_codes && line.starts_with('E') {
115-
let err_code = match line.split_once(',') {
116-
None => line,
117-
Some((err_code, _)) => err_code,
118-
}
119-
.to_string();
120-
121-
verbose_print!(verbose, "warning: Error code `{}` is undocumented.", err_code);
122-
123-
if error_codes.contains(&err_code) {
124-
errors.push(format!("Found duplicate error code: `{}`", err_code));
125-
}
126-
127-
error_codes.push(err_code);
128-
} else if line == ";" {
129-
// Once we reach the undocumented error codes, adapt to different syntax.
130-
reached_undocumented_codes = true;
131113
}
132114
}
133115

0 commit comments

Comments
 (0)