]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/markdown.rs
Rollup merge of #69599 - Centril:typeck-tweak-wording, r=davidtwco
[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
9 use crate::config::{Options, RenderOptions};
10 use crate::externalfiles::{load_string, LoadStringError};
11 use crate::html::escape::Escape;
12 use crate::html::markdown;
13 use crate::html::markdown::{find_testable_code, ErrorCodes, IdMap, Markdown, MarkdownWithToc};
14 use crate::test::{Collector, TestOptions};
15
16 /// Separate any lines at the start of the file that begin with `# ` or `%`.
17 fn extract_leading_metadata(s: &str) -> (Vec<&str>, &str) {
18     let mut metadata = Vec::new();
19     let mut count = 0;
20
21     for line in s.lines() {
22         if line.starts_with("# ") || line.starts_with('%') {
23             // trim the whitespace after the symbol
24             metadata.push(line[1..].trim_start());
25             count += line.len() + 1;
26         } else {
27             return (metadata, &s[count..]);
28         }
29     }
30
31     // if we're here, then all lines were metadata `# ` or `%` lines.
32     (metadata, "")
33 }
34
35 /// Render `input` (e.g., "foo.md") into an HTML file in `output`
36 /// (e.g., output = "bar" => "bar/foo.html").
37 pub fn render(
38     input: PathBuf,
39     options: RenderOptions,
40     diag: &rustc_errors::Handler,
41     edition: Edition,
42 ) -> i32 {
43     let mut output = options.output;
44     output.push(input.file_name().unwrap());
45     output.set_extension("html");
46
47     let mut css = String::new();
48     for name in &options.markdown_css {
49         let s = format!("<link rel=\"stylesheet\" type=\"text/css\" href=\"{}\">\n", name);
50         css.push_str(&s)
51     }
52
53     let input_str = match load_string(&input, diag) {
54         Ok(s) => s,
55         Err(LoadStringError::ReadFail) => return 1,
56         Err(LoadStringError::BadUtf8) => return 2,
57     };
58     let playground_url = options.markdown_playground_url.or(options.playground_url);
59     let playground = playground_url.map(|url| markdown::Playground { crate_name: None, url });
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, &mut ids, error_codes, edition, &playground).to_string()
80     } else {
81         Markdown(text, &[], &mut ids, error_codes, edition, &playground).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: &rustc_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(
140         options.input.display().to_string(),
141         options.clone(),
142         true,
143         opts,
144         None,
145         Some(options.input),
146         options.enable_per_target_ignores,
147     );
148     collector.set_position(DUMMY_SP);
149     let codes = ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build());
150
151     find_testable_code(&input_str, &mut collector, codes, options.enable_per_target_ignores);
152
153     options.test_args.insert(0, "rustdoctest".to_string());
154     testing::test_main(
155         &options.test_args,
156         collector.tests,
157         Some(testing::Options::new().display_output(options.display_warnings)),
158     );
159     0
160 }