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