2 use crate::docfs::PathError;
3 use crate::error::Error;
4 use crate::html::format::Buffer;
5 use crate::html::highlight;
6 use crate::html::layout;
7 use crate::html::render::{Context, BASIC_KEYWORDS};
8 use crate::visit::DocVisitor;
10 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
11 use rustc_hir::def_id::LOCAL_CRATE;
12 use rustc_middle::ty::TyCtxt;
13 use rustc_session::Session;
14 use rustc_span::source_map::FileName;
18 use std::path::{Component, Path, PathBuf};
21 pub(crate) fn render(cx: &mut Context<'_>, krate: &clean::Crate) -> Result<(), Error> {
22 info!("emitting source files");
24 let dst = cx.dst.join("src").join(krate.name(cx.tcx()).as_str());
25 cx.shared.ensure_dir(&dst)?;
27 let mut collector = SourceCollector { dst, cx, emitted_local_sources: FxHashSet::default() };
28 collector.visit_crate(krate);
32 pub(crate) fn collect_local_sources<'tcx>(
36 ) -> FxHashMap<PathBuf, String> {
37 let mut lsc = LocalSourcesCollector { tcx, local_sources: FxHashMap::default(), src_root };
38 lsc.visit_crate(krate);
42 struct LocalSourcesCollector<'a, 'tcx> {
44 local_sources: FxHashMap<PathBuf, String>,
48 fn is_real_and_local(span: clean::Span, sess: &Session) -> bool {
49 span.cnum(sess) == LOCAL_CRATE && span.filename(sess).is_real()
52 impl LocalSourcesCollector<'_, '_> {
53 fn add_local_source(&mut self, item: &clean::Item) {
54 let sess = self.tcx.sess;
55 let span = item.span(self.tcx);
56 let Some(span) = span else { return };
57 // skip all synthetic "files"
58 if !is_real_and_local(span, sess) {
61 let filename = span.filename(sess);
62 let p = if let FileName::Real(file) = filename {
63 match file.into_local_path() {
70 if self.local_sources.contains_key(&*p) {
71 // We've already emitted this source
75 let mut href = String::new();
76 clean_path(self.src_root, &p, false, |component| {
77 href.push_str(&component.to_string_lossy());
81 let mut src_fname = p.file_name().expect("source has no filename").to_os_string();
82 src_fname.push(".html");
83 href.push_str(&src_fname.to_string_lossy());
84 self.local_sources.insert(p, href);
88 impl DocVisitor for LocalSourcesCollector<'_, '_> {
89 fn visit_item(&mut self, item: &clean::Item) {
90 self.add_local_source(item);
92 self.visit_item_recur(item)
96 /// Helper struct to render all source code to HTML pages
97 struct SourceCollector<'a, 'tcx> {
98 cx: &'a mut Context<'tcx>,
100 /// Root destination to place all HTML output into
102 emitted_local_sources: FxHashSet<PathBuf>,
105 impl DocVisitor for SourceCollector<'_, '_> {
106 fn visit_item(&mut self, item: &clean::Item) {
107 if !self.cx.include_sources {
111 let tcx = self.cx.tcx();
112 let span = item.span(tcx);
113 let Some(span) = span else { return };
116 // If we're not rendering sources, there's nothing to do.
117 // If we're including source files, and we haven't seen this file yet,
118 // then we need to render it out to the filesystem.
119 if is_real_and_local(span, sess) {
120 let filename = span.filename(sess);
121 let span = span.inner();
122 let pos = sess.source_map().lookup_source_file(span.lo());
123 let file_span = span.with_lo(pos.start_pos).with_hi(pos.end_pos);
124 // If it turns out that we couldn't read this file, then we probably
125 // can't read any of the files (generating html output from json or
126 // something like that), so just don't include sources for the
127 // entire crate. The other option is maintaining this mapping on a
128 // per-file basis, but that's probably not worth it...
129 self.cx.include_sources = match self.emit_source(&filename, file_span) {
132 self.cx.shared.tcx.sess.span_err(
135 "failed to render source code for `{}`: {}",
136 filename.prefer_local(),
145 self.visit_item_recur(item)
149 impl SourceCollector<'_, '_> {
150 /// Renders the given filename into its corresponding HTML source file.
154 file_span: rustc_span::Span,
155 ) -> Result<(), Error> {
156 let p = match *filename {
157 FileName::Real(ref file) => {
158 if let Some(local_path) = file.local_path() {
159 local_path.to_path_buf()
161 unreachable!("only the current crate should have sources emitted");
166 if self.emitted_local_sources.contains(&*p) {
167 // We've already emitted this source
171 let contents = match fs::read_to_string(&p) {
172 Ok(contents) => contents,
174 return Err(Error::new(e, &p));
178 // Remove the utf-8 BOM if any
179 let contents = contents.strip_prefix('\u{feff}').unwrap_or(&contents);
181 let shared = Rc::clone(&self.cx.shared);
182 // Create the intermediate directories
183 let mut cur = self.dst.clone();
184 let mut root_path = String::from("../../");
185 clean_path(&shared.src_root, &p, false, |component| {
187 root_path.push_str("../");
190 shared.ensure_dir(&cur)?;
192 let src_fname = p.file_name().expect("source has no filename").to_os_string();
193 let mut fname = src_fname.clone();
197 let title = format!("{} - source", src_fname.to_string_lossy());
198 let desc = format!("Source of the Rust file `{}`.", filename.prefer_remapped());
199 let page = layout::Page {
202 root_path: &root_path,
203 static_root_path: shared.static_root_path.as_deref(),
205 keywords: BASIC_KEYWORDS,
206 resource_suffix: &shared.resource_suffix,
208 let v = layout::render(
213 let cx = &mut self.cx;
220 highlight::DecorationInfo::default(),
221 SourceContext::Standalone,
226 shared.fs.write(cur, v)?;
227 self.emitted_local_sources.insert(p);
232 /// Takes a path to a source file and cleans the path to it. This canonicalizes
233 /// things like ".." to components which preserve the "top down" hierarchy of a
234 /// static HTML tree. Each component in the cleaned path will be passed as an
235 /// argument to `f`. The very last component of the path (ie the file name) will
236 /// be passed to `f` if `keep_filename` is true, and ignored otherwise.
237 pub(crate) fn clean_path<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F)
241 // make it relative, if possible
242 let p = p.strip_prefix(src_root).unwrap_or(p);
244 let mut iter = p.components().peekable();
246 while let Some(c) = iter.next() {
247 if !keep_filename && iter.peek().is_none() {
252 Component::ParentDir => f("up".as_ref()),
253 Component::Normal(c) => f(c),
259 pub(crate) enum SourceContext {
261 Embedded { offset: usize, needs_expansion: bool },
264 /// Wrapper struct to render the source code of a file. This will do things like
265 /// adding line numbers to the left-hand side.
266 pub(crate) fn print_src(
269 file_span: rustc_span::Span,
270 context: &Context<'_>,
272 decoration_info: highlight::DecorationInfo,
273 source_context: SourceContext,
275 let lines = s.lines().count();
276 let mut line_numbers = Buffer::empty_from(buf);
278 line_numbers.write_str("<pre class=\"src-line-numbers\">");
279 let current_href = &context
280 .href_from_span(clean::Span::new(file_span), false)
281 .expect("only local crates should have sources emitted");
282 match source_context {
283 SourceContext::Standalone => {
285 for line in 1..=lines {
286 writeln!(line_numbers, "<a href=\"#{line}\" id=\"{line}\">{line}</a>")
289 SourceContext::Embedded { offset, needs_expansion } => {
290 extra = if needs_expansion {
291 Some(r#"<button class="expand">↕</button>"#)
295 for line_number in 1..=lines {
296 let line = line_number + offset;
297 writeln!(line_numbers, "<span>{line}</span>")
301 line_numbers.write_str("</pre>");
302 highlight::render_source_with_highlighting(
306 highlight::HrefContext { context, file_span, root_path, current_href },