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