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