/
main.rs
274 lines (240 loc) · 8.8 KB
/
main.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
#![feature(rustc_private)]
extern crate env_logger;
extern crate syntax;
extern crate serialize as rustc_serialize;
use std::collections::BTreeMap;
use std::env;
use std::error::Error;
use std::fs::{self, read_dir, File};
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use std::cell::RefCell;
use syntax::edition::DEFAULT_EDITION;
use syntax::diagnostics::metadata::{get_metadata_dir, ErrorMetadataMap, ErrorMetadata};
use rustdoc::html::markdown::{Markdown, IdMap, ErrorCodes, Playground};
use rustc_serialize::json;
enum OutputFormat {
HTML(HTMLFormatter),
Markdown(MarkdownFormatter),
Unknown(String),
}
impl OutputFormat {
fn from(format: &str, resource_suffix: &str) -> OutputFormat {
match &*format.to_lowercase() {
"html" => OutputFormat::HTML(HTMLFormatter(RefCell::new(IdMap::new()),
resource_suffix.to_owned())),
"markdown" => OutputFormat::Markdown(MarkdownFormatter),
s => OutputFormat::Unknown(s.to_owned()),
}
}
}
trait Formatter {
fn header(&self, output: &mut dyn Write) -> Result<(), Box<dyn Error>>;
fn title(&self, output: &mut dyn Write) -> Result<(), Box<dyn Error>>;
fn error_code_block(&self, output: &mut dyn Write, info: &ErrorMetadata,
err_code: &str) -> Result<(), Box<dyn Error>>;
fn footer(&self, output: &mut dyn Write) -> Result<(), Box<dyn Error>>;
}
struct HTMLFormatter(RefCell<IdMap>, String);
struct MarkdownFormatter;
impl Formatter for HTMLFormatter {
fn header(&self, output: &mut dyn Write) -> Result<(), Box<dyn Error>> {
write!(output, r##"<!DOCTYPE html>
<html>
<head>
<title>Rust Compiler Error Index</title>
<meta charset="utf-8">
<!-- Include rust.css after light.css so its rules take priority. -->
<link rel="stylesheet" type="text/css" href="light{suffix}.css"/>
<link rel="stylesheet" type="text/css" href="rust.css"/>
<style>
.error-undescribed {{
display: none;
}}
</style>
</head>
<body>
"##, suffix=self.1)?;
Ok(())
}
fn title(&self, output: &mut dyn Write) -> Result<(), Box<dyn Error>> {
write!(output, "<h1>Rust Compiler Error Index</h1>\n")?;
Ok(())
}
fn error_code_block(&self, output: &mut dyn Write, info: &ErrorMetadata,
err_code: &str) -> Result<(), Box<dyn Error>> {
// Enclose each error in a div so they can be shown/hidden en masse.
let desc_desc = match info.description {
Some(_) => "error-described",
None => "error-undescribed",
};
let use_desc = match info.use_site {
Some(_) => "error-used",
None => "error-unused",
};
write!(output, "<div class=\"{} {}\">", desc_desc, use_desc)?;
// Error title (with self-link).
write!(output,
"<h2 id=\"{0}\" class=\"section-header\"><a href=\"#{0}\">{0}</a></h2>\n",
err_code)?;
// Description rendered as markdown.
match info.description {
Some(ref desc) => {
let mut id_map = self.0.borrow_mut();
let playground = Playground {
crate_name: None,
url: String::from("https://play.rust-lang.org/"),
};
write!(output, "{}",
Markdown(desc, &[], &mut id_map,
ErrorCodes::Yes, DEFAULT_EDITION, &Some(playground)).to_string())?
},
None => write!(output, "<p>No description.</p>\n")?,
}
write!(output, "</div>\n")?;
Ok(())
}
fn footer(&self, output: &mut dyn Write) -> Result<(), Box<dyn Error>> {
write!(output, r##"<script>
function onEach(arr, func) {{
if (arr && arr.length > 0 && func) {{
for (var i = 0; i < arr.length; i++) {{
func(arr[i]);
}}
}}
}}
function hasClass(elem, className) {{
if (elem && className && elem.className) {{
var elemClass = elem.className;
var start = elemClass.indexOf(className);
if (start === -1) {{
return false;
}} else if (elemClass.length === className.length) {{
return true;
}} else {{
if (start > 0 && elemClass[start - 1] !== ' ') {{
return false;
}}
var end = start + className.length;
if (end < elemClass.length && elemClass[end] !== ' ') {{
return false;
}}
return true;
}}
if (start > 0 && elemClass[start - 1] !== ' ') {{
return false;
}}
var end = start + className.length;
if (end < elemClass.length && elemClass[end] !== ' ') {{
return false;
}}
return true;
}}
return false;
}}
onEach(document.getElementsByClassName('rust-example-rendered'), function(e) {{
if (hasClass(e, 'compile_fail')) {{
e.addEventListener("mouseover", function(event) {{
e.previousElementSibling.childNodes[0].style.color = '#f00';
}});
e.addEventListener("mouseout", function(event) {{
e.previousElementSibling.childNodes[0].style.color = '';
}});
}} else if (hasClass(e, 'ignore')) {{
e.addEventListener("mouseover", function(event) {{
e.previousElementSibling.childNodes[0].style.color = '#ff9200';
}});
e.addEventListener("mouseout", function(event) {{
e.previousElementSibling.childNodes[0].style.color = '';
}});
}}
}});
</script>
</body>
</html>"##)?;
Ok(())
}
}
impl Formatter for MarkdownFormatter {
#[allow(unused_variables)]
fn header(&self, output: &mut dyn Write) -> Result<(), Box<dyn Error>> {
Ok(())
}
fn title(&self, output: &mut dyn Write) -> Result<(), Box<dyn Error>> {
write!(output, "# Rust Compiler Error Index\n")?;
Ok(())
}
fn error_code_block(&self, output: &mut dyn Write, info: &ErrorMetadata,
err_code: &str) -> Result<(), Box<dyn Error>> {
Ok(match info.description {
Some(ref desc) => write!(output, "## {}\n{}\n", err_code, desc)?,
None => (),
})
}
#[allow(unused_variables)]
fn footer(&self, output: &mut dyn Write) -> Result<(), Box<dyn Error>> {
Ok(())
}
}
/// Loads all the metadata files from `metadata_dir` into an in-memory map.
fn load_all_errors(metadata_dir: &Path) -> Result<ErrorMetadataMap, Box<dyn Error>> {
let mut all_errors = BTreeMap::new();
for entry in read_dir(metadata_dir)? {
let path = entry?.path();
let metadata_str = fs::read_to_string(&path)?;
let some_errors: ErrorMetadataMap = json::decode(&metadata_str)?;
for (err_code, info) in some_errors {
all_errors.insert(err_code, info);
}
}
Ok(all_errors)
}
/// Output an HTML page for the errors in `err_map` to `output_path`.
fn render_error_page<T: Formatter>(err_map: &ErrorMetadataMap, output_path: &Path,
formatter: T) -> Result<(), Box<dyn Error>> {
let mut output_file = File::create(output_path)?;
formatter.header(&mut output_file)?;
formatter.title(&mut output_file)?;
for (err_code, info) in err_map {
formatter.error_code_block(&mut output_file, info, err_code)?;
}
formatter.footer(&mut output_file)
}
fn main_with_result(format: OutputFormat, dst: &Path) -> Result<(), Box<dyn Error>> {
let build_arch = env::var("CFG_BUILD")?;
let metadata_dir = get_metadata_dir(&build_arch);
let err_map = load_all_errors(&metadata_dir)?;
match format {
OutputFormat::Unknown(s) => panic!("Unknown output format: {}", s),
OutputFormat::HTML(h) => render_error_page(&err_map, dst, h)?,
OutputFormat::Markdown(m) => render_error_page(&err_map, dst, m)?,
}
Ok(())
}
fn parse_args() -> (OutputFormat, PathBuf) {
let mut args = env::args().skip(1);
let format = args.next();
let dst = args.next();
let resource_suffix = args.next().unwrap_or_else(String::new);
let format = format.map(|a| OutputFormat::from(&a, &resource_suffix))
.unwrap_or(OutputFormat::from("html", &resource_suffix));
let dst = dst.map(PathBuf::from).unwrap_or_else(|| {
match format {
OutputFormat::HTML(..) => PathBuf::from("doc/error-index.html"),
OutputFormat::Markdown(..) => PathBuf::from("doc/error-index.md"),
OutputFormat::Unknown(..) => PathBuf::from("<nul>"),
}
});
(format, dst)
}
fn main() {
env_logger::init();
let (format, dst) = parse_args();
let result = syntax::with_default_globals(move || {
main_with_result(format, &dst)
});
if let Err(e) = result {
panic!("{}", e.description());
}
}