1use std::cell::{Cell, RefCell};
2use std::ffi::OsStr;
3use std::path::{Component, Path, PathBuf};
4use std::{fmt, fs};
5
6use askama::Template;
7use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
8use rustc_hir::def_id::LOCAL_CRATE;
9use rustc_middle::ty::TyCtxt;
10use rustc_session::Session;
11use rustc_span::{FileName, RealFileName, RemapPathScopeComponents};
12use tracing::info;
13
14use super::render::Context;
15use super::{highlight, layout};
16use crate::clean;
17use crate::clean::utils::has_doc_flag;
18use crate::docfs::PathError;
19use crate::error::Error;
20use crate::visit::DocVisitor;
21
22pub(crate) fn render(cx: &mut Context<'_>, krate: &clean::Crate) -> Result<(), Error> {
23 info!("emitting source files");
24
25 let dst = cx.dst.join("src").join(krate.name(cx.tcx()).as_str());
26 cx.shared.ensure_dir(&dst)?;
27 let crate_name = krate.name(cx.tcx());
28 let crate_name = crate_name.as_str();
29
30 let mut collector =
31 SourceCollector { dst, cx, emitted_local_sources: FxHashSet::default(), crate_name };
32 collector.visit_crate(krate);
33 Ok(())
34}
35
36pub(crate) fn collect_local_sources(
37 tcx: TyCtxt<'_>,
38 src_root: &Path,
39 krate: &clean::Crate,
40) -> FxIndexMap<PathBuf, String> {
41 let mut lsc = LocalSourcesCollector { tcx, local_sources: FxIndexMap::default(), src_root };
42 lsc.visit_crate(krate);
43 lsc.local_sources
44}
45
46struct LocalSourcesCollector<'a, 'tcx> {
47 tcx: TyCtxt<'tcx>,
48 local_sources: FxIndexMap<PathBuf, String>,
49 src_root: &'a Path,
50}
51
52fn filename_real_and_local(span: clean::Span, sess: &Session) -> Option<RealFileName> {
53 if span.cnum(sess) == LOCAL_CRATE
54 && let FileName::Real(file) = span.filename(sess)
55 {
56 Some(file)
57 } else {
58 None
59 }
60}
61
62impl LocalSourcesCollector<'_, '_> {
63 fn add_local_source(&mut self, item: &clean::Item) {
64 let sess = self.tcx.sess;
65 let span = item.span(self.tcx);
66 let Some(span) = span else { return };
67 let Some(p) = filename_real_and_local(span, sess).and_then(|file| file.into_local_path())
69 else {
70 return;
71 };
72 if self.local_sources.contains_key(&*p) {
73 return;
75 }
76
77 let href = RefCell::new(PathBuf::new());
78 clean_path(
79 self.src_root,
80 &p,
81 |component| {
82 href.borrow_mut().push(component);
83 },
84 || {
85 href.borrow_mut().pop();
86 },
87 );
88
89 let mut href = href.into_inner().to_string_lossy().into_owned();
90 if let Some(c) = href.as_bytes().last()
91 && *c != b'/'
92 {
93 href.push('/');
94 }
95 let mut src_fname = p.file_name().expect("source has no filename").to_os_string();
96 src_fname.push(".html");
97 href.push_str(&src_fname.to_string_lossy());
98 self.local_sources.insert(p, href);
99 }
100}
101
102impl DocVisitor<'_> for LocalSourcesCollector<'_, '_> {
103 fn visit_item(&mut self, item: &clean::Item) {
104 self.add_local_source(item);
105
106 self.visit_item_recur(item)
107 }
108}
109
110struct SourceCollector<'a, 'tcx> {
112 cx: &'a mut Context<'tcx>,
113
114 dst: PathBuf,
116 emitted_local_sources: FxHashSet<PathBuf>,
117
118 crate_name: &'a str,
119}
120
121impl DocVisitor<'_> for SourceCollector<'_, '_> {
122 fn visit_item(&mut self, item: &clean::Item) {
123 if !self.cx.info.include_sources {
124 return;
125 }
126
127 let tcx = self.cx.tcx();
128 let span = item.span(tcx);
129 let Some(span) = span else { return };
130 let sess = tcx.sess;
131
132 if let Some(filename) = filename_real_and_local(span, sess) {
136 let span = span.inner();
137 let pos = sess.source_map().lookup_source_file(span.lo());
138 let file_span = span.with_lo(pos.start_pos).with_hi(pos.end_position());
139 self.cx.info.include_sources = match self.emit_source(&filename, file_span) {
145 Ok(()) => true,
146 Err(e) => {
147 self.cx.shared.tcx.dcx().span_err(
148 span,
149 format!(
150 "failed to render source code for `{filename}`: {e}",
151 filename = filename
152 .path(RemapPathScopeComponents::DIAGNOSTICS)
153 .to_string_lossy()
154 .into_owned(),
155 ),
156 );
157 false
158 }
159 };
160 }
161
162 self.visit_item_recur(item)
163 }
164}
165
166impl SourceCollector<'_, '_> {
167 fn emit_source(
169 &mut self,
170 file: &RealFileName,
171 file_span: rustc_span::Span,
172 ) -> Result<(), Error> {
173 let p = if let Some(local_path) = file.local_path() {
174 local_path.to_path_buf()
175 } else {
176 unreachable!("only the current crate should have sources emitted");
177 };
178 if self.emitted_local_sources.contains(&*p) {
179 return Ok(());
181 }
182
183 let contents = match fs::read_to_string(&p) {
184 Ok(contents) => contents,
185 Err(e) => {
186 return Err(Error::new(e, &p));
187 }
188 };
189
190 let contents = contents.trim_prefix('\u{feff}');
192
193 let shared = &self.cx.shared;
194 let cur = RefCell::new(PathBuf::new());
196 let extra_depth = Cell::new(0usize);
200
201 clean_path(
202 &shared.src_root,
203 &p,
204 |component| {
205 cur.borrow_mut().push(component);
206 extra_depth.set(extra_depth.get() + 1);
207 },
208 || {
209 cur.borrow_mut().pop();
210 extra_depth.set(extra_depth.get().saturating_sub(1));
211 },
212 );
213
214 let jump_to_def_path_depth = 2 + extra_depth.get();
215
216 let src_fname = p.file_name().expect("source has no filename").to_os_string();
217 let mut fname = src_fname.clone();
218 let mut file_path = Path::new(&self.crate_name).join(&*cur.borrow());
219 file_path.push(&fname);
220 fname.push(".html");
221 let mut cur = self.dst.join(cur.into_inner());
222 shared.ensure_dir(&cur)?;
223
224 cur.push(&fname);
225
226 let title = format!("{} - source", src_fname.to_string_lossy());
227 let desc = format!("Source of the Rust file `{}`.", p.to_string_lossy());
228 let root_path = "../".repeat(jump_to_def_path_depth);
229 let page = layout::Page {
230 title: &title,
231 short_title: &src_fname.to_string_lossy(),
232 css_class: "src",
233 root_path: &root_path,
234 static_root_path: shared.static_root_path.as_deref(),
235 description: &desc,
236 resource_suffix: &shared.resource_suffix,
237 rust_logo: has_doc_flag(self.cx.tcx(), LOCAL_CRATE.as_def_id(), |d| {
238 d.rust_logo.is_some()
239 }),
240 };
241 let source_context = SourceContext::Standalone { file_path };
242 let v = layout::render(
243 &shared.layout,
244 &page,
245 "",
246 fmt::from_fn(|f| {
247 print_src(
248 f,
249 contents,
250 file_span,
251 self.cx,
252 jump_to_def_path_depth,
253 &highlight::DecorationInfo::default(),
254 &source_context,
255 )
256 }),
257 &shared.style_files,
258 );
259 shared.fs.write(cur, v)?;
260 self.emitted_local_sources.insert(p);
261 Ok(())
262 }
263}
264
265pub(crate) fn clean_path<F, P>(src_root: &Path, p: &Path, mut f: F, mut parent: P)
272where
273 F: FnMut(&OsStr),
274 P: FnMut(),
275{
276 let p = p.strip_prefix(src_root).unwrap_or(p);
278
279 let mut iter = p.components().peekable();
280
281 while let Some(c) = iter.next() {
282 if iter.peek().is_none() {
283 break;
284 }
285
286 match c {
287 Component::ParentDir => parent(),
288 Component::Normal(c) => f(c),
289 _ => continue,
290 }
291 }
292}
293
294pub(crate) struct ScrapedInfo<'a> {
295 pub(crate) offset: usize,
296 pub(crate) name: &'a str,
297 pub(crate) url: &'a str,
298 pub(crate) title: &'a str,
299 pub(crate) locations: String,
300 pub(crate) needs_expansion: bool,
301}
302
303#[derive(Template)]
304#[template(path = "scraped_source.html")]
305struct ScrapedSource<'a, Code: std::fmt::Display> {
306 info: &'a ScrapedInfo<'a>,
307 code_html: Code,
308 max_nb_digits: u32,
309}
310
311#[derive(Template)]
312#[template(path = "source.html")]
313struct Source<Code: std::fmt::Display> {
314 code_html: Code,
315 file_path: Option<(String, String)>,
316 max_nb_digits: u32,
317}
318
319pub(crate) enum SourceContext<'a> {
320 Standalone { file_path: PathBuf },
321 Embedded(ScrapedInfo<'a>),
322}
323
324pub(crate) fn print_src(
327 mut writer: impl fmt::Write,
328 s: &str,
329 file_span: rustc_span::Span,
330 cx: &Context<'_>,
331 jump_to_def_path_depth: usize,
332 decoration_info: &highlight::DecorationInfo,
333 source_context: &SourceContext<'_>,
334) -> fmt::Result {
335 let mut lines = s.lines().count();
336 let line_info = if let SourceContext::Embedded(info) = source_context {
337 highlight::LineInfo::new_scraped(lines as u32, info.offset as u32)
338 } else {
339 highlight::LineInfo::new(lines as u32)
340 };
341 if line_info.is_scraped_example {
342 lines += line_info.start_line as usize;
343 }
344 let code = fmt::from_fn(move |fmt| {
345 let current_href = if let SourceContext::Embedded(info) = source_context {
348 info.url.to_string()
349 } else {
350 cx.href_from_span(clean::Span::new(file_span), false)
351 .expect("only local crates should have sources emitted")
352 };
353 highlight::write_code(
354 fmt,
355 s,
356 Some(highlight::HrefContext {
357 context: cx,
358 file_span: file_span.into(),
359 jump_to_def_path_depth,
360 current_href,
361 }),
362 Some(decoration_info),
363 cx.tcx().sess.edition(),
364 Some(line_info),
365 );
366 Ok(())
367 });
368 let max_nb_digits = if lines > 0 { lines.ilog10() + 1 } else { 1 };
369 match source_context {
370 SourceContext::Standalone { file_path } => Source {
371 code_html: code,
372 file_path: if let Some(file_name) = file_path.file_name()
373 && let Some(file_path) = file_path.parent()
374 {
375 Some((file_path.display().to_string(), file_name.display().to_string()))
376 } else {
377 None
378 },
379 max_nb_digits,
380 }
381 .render_into(&mut writer),
382 SourceContext::Embedded(info) => {
383 ScrapedSource { info, code_html: code, max_nb_digits }.render_into(&mut writer)
384 }
385 }?;
386 Ok(())
387}