]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/markdown.rs
Auto merge of #102992 - nnethercote:rm-RunCompiler-emitter, r=bjorn3
[rust.git] / src / librustdoc / markdown.rs
1 use std::fmt::Write as _;
2 use std::fs::{create_dir_all, read_to_string, File};
3 use std::io::prelude::*;
4 use std::path::Path;
5
6 use rustc_span::edition::Edition;
7 use rustc_span::source_map::DUMMY_SP;
8 use rustc_span::Symbol;
9
10 use crate::config::{Options, RenderOptions};
11 use crate::doctest::{Collector, GlobalTestOptions};
12 use crate::html::escape::Escape;
13 use crate::html::markdown;
14 use crate::html::markdown::{
15     find_testable_code, ErrorCodes, HeadingOffset, IdMap, Markdown, MarkdownWithToc,
16 };
17
18 /// Separate any lines at the start of the file that begin with `# ` or `%`.
19 fn extract_leading_metadata(s: &str) -> (Vec<&str>, &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(crate) fn render<P: AsRef<Path>>(
40     input: P,
41     options: RenderOptions,
42     edition: Edition,
43 ) -> Result<(), String> {
44     if let Err(e) = create_dir_all(&options.output) {
45         return Err(format!("{}: {}", options.output.display(), e));
46     }
47
48     let input = input.as_ref();
49     let mut output = options.output;
50     output.push(input.file_name().unwrap());
51     output.set_extension("html");
52
53     let mut css = String::new();
54     for name in &options.markdown_css {
55         write!(css, r#"<link rel="stylesheet" type="text/css" href="{name}">"#)
56             .expect("Writing to a String can't fail");
57     }
58
59     let input_str = read_to_string(input).map_err(|err| format!("{}: {}", input.display(), err))?;
60     let playground_url = options.markdown_playground_url.or(options.playground_url);
61     let playground = playground_url.map(|url| markdown::Playground { crate_name: None, url });
62
63     let mut out = File::create(&output).map_err(|e| format!("{}: {}", output.display(), e))?;
64
65     let (metadata, text) = extract_leading_metadata(&input_str);
66     if metadata.is_empty() {
67         return Err("invalid markdown file: no initial lines starting with `# ` or `%`".to_owned());
68     }
69     let title = metadata[0];
70
71     let mut ids = IdMap::new();
72     let error_codes = ErrorCodes::from(options.unstable_features.is_nightly_build());
73     let text = if !options.markdown_no_toc {
74         MarkdownWithToc(text, &mut ids, error_codes, edition, &playground).into_string()
75     } else {
76         Markdown {
77             content: text,
78             links: &[],
79             ids: &mut ids,
80             error_codes,
81             edition,
82             playground: &playground,
83             heading_offset: HeadingOffset::H1,
84         }
85         .into_string()
86     };
87
88     let err = write!(
89         &mut out,
90         r#"<!DOCTYPE html>
91 <html lang="en">
92 <head>
93     <meta charset="utf-8">
94     <meta name="viewport" content="width=device-width, initial-scale=1.0">
95     <meta name="generator" content="rustdoc">
96     <title>{title}</title>
97
98     {css}
99     {in_header}
100 </head>
101 <body class="rustdoc">
102     <!--[if lte IE 8]>
103     <div class="warning">
104         This old browser is unsupported and will most likely display funky
105         things.
106     </div>
107     <![endif]-->
108
109     {before_content}
110     <h1 class="title">{title}</h1>
111     {text}
112     {after_content}
113 </body>
114 </html>"#,
115         title = Escape(title),
116         css = css,
117         in_header = options.external_html.in_header,
118         before_content = options.external_html.before_content,
119         text = text,
120         after_content = options.external_html.after_content,
121     );
122
123     match err {
124         Err(e) => Err(format!("cannot write to `{}`: {}", output.display(), e)),
125         Ok(_) => Ok(()),
126     }
127 }
128
129 /// Runs any tests/code examples in the markdown file `input`.
130 pub(crate) fn test(options: Options) -> Result<(), String> {
131     let input_str = read_to_string(&options.input)
132         .map_err(|err| format!("{}: {}", options.input.display(), err))?;
133     let mut opts = GlobalTestOptions::default();
134     opts.no_crate_inject = true;
135     let mut collector = Collector::new(
136         Symbol::intern(&options.input.display().to_string()),
137         options.clone(),
138         true,
139         opts,
140         None,
141         Some(options.input),
142         options.enable_per_target_ignores,
143     );
144     collector.set_position(DUMMY_SP);
145     let codes = ErrorCodes::from(options.render_options.unstable_features.is_nightly_build());
146
147     find_testable_code(&input_str, &mut collector, codes, options.enable_per_target_ignores, None);
148
149     crate::doctest::run_tests(options.test_args, options.nocapture, collector.tests);
150     Ok(())
151 }