]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/markdown.rs
clean up error codes explanation
[rust.git] / src / librustdoc / markdown.rs
1 use std::fs::File;
2 use std::io::prelude::*;
3 use std::path::PathBuf;
4
5 use rustc_feature::UnstableFeatures;
6 use rustc_span::edition::Edition;
7 use rustc_span::source_map::DUMMY_SP;
8 use testing;
9
10 use crate::config::{Options, RenderOptions};
11 use crate::externalfiles::{load_string, LoadStringError};
12 use crate::html::escape::Escape;
13 use crate::html::markdown;
14 use crate::html::markdown::{find_testable_code, ErrorCodes, IdMap, Markdown, MarkdownWithToc};
15 use crate::test::{Collector, TestOptions};
16
17 /// Separate any lines at the start of the file that begin with `# ` or `%`.
18 fn extract_leading_metadata(s: &str) -> (Vec<&str>, &str) {
19     let mut metadata = Vec::new();
20     let mut count = 0;
21
22     for line in s.lines() {
23         if line.starts_with("# ") || line.starts_with("%") {
24             // trim the whitespace after the symbol
25             metadata.push(line[1..].trim_start());
26             count += line.len() + 1;
27         } else {
28             return (metadata, &s[count..]);
29         }
30     }
31
32     // if we're here, then all lines were metadata `# ` or `%` lines.
33     (metadata, "")
34 }
35
36 /// Render `input` (e.g., "foo.md") into an HTML file in `output`
37 /// (e.g., output = "bar" => "bar/foo.html").
38 pub fn render(
39     input: PathBuf,
40     options: RenderOptions,
41     diag: &rustc_errors::Handler,
42     edition: Edition,
43 ) -> i32 {
44     let mut output = options.output;
45     output.push(input.file_name().unwrap());
46     output.set_extension("html");
47
48     let mut css = String::new();
49     for name in &options.markdown_css {
50         let s = format!("<link rel=\"stylesheet\" type=\"text/css\" href=\"{}\">\n", name);
51         css.push_str(&s)
52     }
53
54     let input_str = match load_string(&input, diag) {
55         Ok(s) => s,
56         Err(LoadStringError::ReadFail) => return 1,
57         Err(LoadStringError::BadUtf8) => return 2,
58     };
59     let playground_url = options.markdown_playground_url.or(options.playground_url);
60     let playground = playground_url.map(|url| markdown::Playground { crate_name: None, url });
61
62     let mut out = match File::create(&output) {
63         Err(e) => {
64             diag.struct_err(&format!("{}: {}", output.display(), e)).emit();
65             return 4;
66         }
67         Ok(f) => f,
68     };
69
70     let (metadata, text) = extract_leading_metadata(&input_str);
71     if metadata.is_empty() {
72         diag.struct_err("invalid markdown file: no initial lines starting with `# ` or `%`").emit();
73         return 5;
74     }
75     let title = metadata[0];
76
77     let mut ids = IdMap::new();
78     let error_codes = ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build());
79     let text = if !options.markdown_no_toc {
80         MarkdownWithToc(text, &mut ids, error_codes, edition, &playground).to_string()
81     } else {
82         Markdown(text, &[], &mut ids, error_codes, edition, &playground).to_string()
83     };
84
85     let err = write!(
86         &mut out,
87         r#"<!DOCTYPE html>
88 <html lang="en">
89 <head>
90     <meta charset="utf-8">
91     <meta name="viewport" content="width=device-width, initial-scale=1.0">
92     <meta name="generator" content="rustdoc">
93     <title>{title}</title>
94
95     {css}
96     {in_header}
97 </head>
98 <body class="rustdoc">
99     <!--[if lte IE 8]>
100     <div class="warning">
101         This old browser is unsupported and will most likely display funky
102         things.
103     </div>
104     <![endif]-->
105
106     {before_content}
107     <h1 class="title">{title}</h1>
108     {text}
109     {after_content}
110 </body>
111 </html>"#,
112         title = Escape(title),
113         css = css,
114         in_header = options.external_html.in_header,
115         before_content = options.external_html.before_content,
116         text = text,
117         after_content = options.external_html.after_content,
118     );
119
120     match err {
121         Err(e) => {
122             diag.struct_err(&format!("cannot write to `{}`: {}", output.display(), e)).emit();
123             6
124         }
125         Ok(_) => 0,
126     }
127 }
128
129 /// Runs any tests/code examples in the markdown file `input`.
130 pub fn test(mut options: Options, diag: &rustc_errors::Handler) -> i32 {
131     let input_str = match load_string(&options.input, diag) {
132         Ok(s) => s,
133         Err(LoadStringError::ReadFail) => return 1,
134         Err(LoadStringError::BadUtf8) => return 2,
135     };
136
137     let mut opts = TestOptions::default();
138     opts.no_crate_inject = true;
139     opts.display_warnings = options.display_warnings;
140     let mut collector = Collector::new(
141         options.input.display().to_string(),
142         options.clone(),
143         true,
144         opts,
145         None,
146         Some(options.input),
147         options.enable_per_target_ignores,
148     );
149     collector.set_position(DUMMY_SP);
150     let codes = ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build());
151
152     find_testable_code(&input_str, &mut collector, codes, options.enable_per_target_ignores);
153
154     options.test_args.insert(0, "rustdoctest".to_string());
155     testing::test_main(
156         &options.test_args,
157         collector.tests,
158         Some(testing::Options::new().display_output(options.display_warnings)),
159     );
160     0
161 }