Skip to content

Commit 6226747

Browse files
committed
Refactor src-link creation for local sources
Since we emit the sources beforhand we actually **know** whether we can safely create src-links to these files and where they are stored.
1 parent f6e125f commit 6226747

File tree

1 file changed

+32
-41
lines changed

1 file changed

+32
-41
lines changed

src/librustdoc/html/render.rs

Lines changed: 32 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,8 @@ pub struct Context {
104104
/// the source files are present in the html rendering, then this will be
105105
/// `true`.
106106
pub include_sources: bool,
107+
/// The local file sources we've emitted and their respective url-paths.
108+
pub local_sources: HashMap<PathBuf, String>,
107109
/// A flag, which when turned off, will render pages which redirect to the
108110
/// real location of an item. This is used to allow external links to
109111
/// publicly reused items to redirect to the right location.
@@ -262,8 +264,6 @@ pub struct Cache {
262264
struct SourceCollector<'a> {
263265
cx: &'a mut Context,
264266

265-
/// Processed source-file paths
266-
seen: HashSet<String>,
267267
/// Root destination to place all HTML output into
268268
dst: PathBuf,
269269
}
@@ -423,6 +423,7 @@ pub fn run(mut krate: clean::Crate,
423423
playground_url: "".to_string(),
424424
},
425425
include_sources: true,
426+
local_sources: HashMap::new(),
426427
render_redirect_pages: false,
427428
issue_tracker_base_url: None,
428429
};
@@ -770,11 +771,8 @@ fn render_sources(cx: &mut Context,
770771
try_err!(mkdir(&dst), &dst);
771772
let mut folder = SourceCollector {
772773
dst: dst,
773-
seen: HashSet::new(),
774774
cx: cx,
775775
};
776-
// skip all invalid spans
777-
folder.seen.insert("".to_string());
778776
Ok(folder.fold_crate(krate))
779777
}
780778

@@ -866,7 +864,13 @@ impl<'a> DocFolder for SourceCollector<'a> {
866864
fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
867865
// If we're including source files, and we haven't seen this file yet,
868866
// then we need to render it out to the filesystem
869-
if self.cx.include_sources && !self.seen.contains(&item.source.filename) {
867+
if self.cx.include_sources
868+
// skip all invalid spans
869+
&& item.source.filename != ""
870+
// macros from other libraries get special filenames which we can
871+
// safely ignore
872+
&& !(item.source.filename.starts_with("<")
873+
&& item.source.filename.ends_with("macros>")) {
870874

871875
// If it turns out that we couldn't read this file, then we probably
872876
// can't read any of the files (generating html output from json or
@@ -884,7 +888,6 @@ impl<'a> DocFolder for SourceCollector<'a> {
884888
false
885889
}
886890
};
887-
self.seen.insert(item.source.filename.clone());
888891
}
889892

890893
self.fold_item_recur(item)
@@ -895,19 +898,14 @@ impl<'a> SourceCollector<'a> {
895898
/// Renders the given filename into its corresponding HTML source file.
896899
fn emit_source(&mut self, filename: &str) -> io::Result<()> {
897900
let p = PathBuf::from(filename);
901+
if self.cx.local_sources.contains_key(&p) {
902+
// We've already emitted this source
903+
return Ok(());
904+
}
898905

899-
// If we couldn't open this file, then just returns because it
900-
// probably means that it's some standard library macro thing and we
901-
// can't have the source to it anyway.
902906
let mut contents = Vec::new();
903-
match File::open(&p).and_then(|mut f| f.read_to_end(&mut contents)) {
904-
Ok(r) => r,
905-
// macros from other libraries get special filenames which we can
906-
// safely ignore
907-
Err(..) if filename.starts_with("<") &&
908-
filename.ends_with("macros>") => return Ok(()),
909-
Err(e) => return Err(e)
910-
};
907+
try!(File::open(&p).and_then(|mut f| f.read_to_end(&mut contents)));
908+
911909
let contents = str::from_utf8(&contents).unwrap();
912910

913911
// Remove the utf-8 BOM if any
@@ -920,16 +918,20 @@ impl<'a> SourceCollector<'a> {
920918
// Create the intermediate directories
921919
let mut cur = self.dst.clone();
922920
let mut root_path = String::from("../../");
921+
let mut href = String::new();
923922
clean_srcpath(&self.cx.src_root, &p, false, |component| {
924923
cur.push(component);
925924
mkdir(&cur).unwrap();
926925
root_path.push_str("../");
926+
href.push_str(component);
927+
href.push('/');
927928
});
928-
929929
let mut fname = p.file_name().expect("source has no filename")
930930
.to_os_string();
931931
fname.push(".html");
932932
cur.push(&fname[..]);
933+
href.push_str(&fname.to_string_lossy());
934+
933935
let mut w = BufWriter::new(try!(File::create(&cur)));
934936
let title = format!("{} -- source", cur.file_name().unwrap()
935937
.to_string_lossy());
@@ -944,7 +946,8 @@ impl<'a> SourceCollector<'a> {
944946
try!(layout::render(&mut w, &self.cx.layout,
945947
&page, &(""), &Source(contents)));
946948
try!(w.flush());
947-
return Ok(());
949+
self.cx.local_sources.insert(p, href);
950+
Ok(())
948951
}
949952
}
950953

@@ -1459,7 +1462,7 @@ impl<'a> Item<'a> {
14591462
/// If `None` is returned, then a source link couldn't be generated. This
14601463
/// may happen, for example, with externally inlined items where the source
14611464
/// of their crate documentation isn't known.
1462-
fn href(&self, cx: &Context) -> Option<String> {
1465+
fn href(&self) -> Option<String> {
14631466
let href = if self.item.source.loline == self.item.source.hiline {
14641467
format!("{}", self.item.source.loline)
14651468
} else {
@@ -1492,25 +1495,13 @@ impl<'a> Item<'a> {
14921495
// know the span, so we plow forward and generate a proper url. The url
14931496
// has anchors for the line numbers that we're linking to.
14941497
} else if self.item.def_id.is_local() {
1495-
let mut path = Vec::new();
1496-
clean_srcpath(&cx.src_root, Path::new(&self.item.source.filename),
1497-
true, |component| {
1498-
path.push(component.to_string());
1499-
});
1500-
1501-
// If the span points into an external macro the
1502-
// source-file will be bogus, i.e `<foo macros>`
1503-
let filename = &self.item.source.filename;
1504-
if !(filename.starts_with("<") && filename.ends_with("macros>")) {
1505-
Some(format!("{root}src/{krate}/{path}.html#{href}",
1506-
root = self.cx.root_path,
1507-
krate = self.cx.layout.krate,
1508-
path = path.join("/"),
1509-
href = href))
1510-
} else {
1511-
None
1512-
}
1513-
1498+
self.cx.local_sources.get(&PathBuf::from(&self.item.source.filename)).map(|path| {
1499+
format!("{root}src/{krate}/{path}.html#{href}",
1500+
root = self.cx.root_path,
1501+
krate = self.cx.layout.krate,
1502+
path = path,
1503+
href = href)
1504+
})
15141505
// If this item is not part of the local crate, then things get a little
15151506
// trickier. We don't actually know the span of the external item, but
15161507
// we know that the documentation on the other end knows the span!
@@ -1590,7 +1581,7 @@ impl<'a> fmt::Display for Item<'a> {
15901581
// this page, and this link will be auto-clicked. The `id` attribute is
15911582
// used to find the link to auto-click.
15921583
if self.cx.include_sources && !is_primitive {
1593-
match self.href(self.cx) {
1584+
match self.href() {
15941585
Some(l) => {
15951586
try!(write!(fmt, "<a id='src-{}' class='srclink' \
15961587
href='{}' title='{}'>[src]</a>",

0 commit comments

Comments
 (0)