"Fossies" - the Fresh Open Source Software Archive

Member "rustc-1.72.1-src/src/librustdoc/markdown.rs" (13 Sep 2023, 4970 Bytes) of package /linux/misc/rustc-1.72.1-src.tar.xz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Rust source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. See also the last Fossies "Diffs" side-by-side code changes report for "markdown.rs": 1.68.2_vs_1.69.0.

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