1
Fork 0

Rollup merge of #106466 - clubby789:relative-module-fix, r=notriddle

Fix rustdoc source code rendering for `#[path = "../path/to/mod.rs"]` links

Fixes #103517

While generating the location for modules source HTML to be saved at, a `..` path component appeared to be translated to `/up/`.
Additionally, while generating the navigation sidebar, `..` path components were ignored. This means that (as in the issue above), a *real* directory structure of:
```
sys/
  unix/
    mod.rs  <-- contains #![path = "../unix/mod.rs]
    cmath.rs
```
was rendered as:
```
sys/
  unix/
    mod.rs
    unix/
      cmath.rs  <-- links to sys/unix/unix/cmath.rs.html, 404
```
While the *files* were stored as
```
sys/
  unix/
    mod.rs.html
    up/
      unix/
        cmath.rs.html
```
This commit is contained in:
Matthias Krüger 2023-01-06 21:26:11 +01:00 committed by GitHub
commit eb27b613b6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 115 additions and 47 deletions

View file

@ -309,7 +309,7 @@ impl<'tcx> Context<'tcx> {
pub(crate) fn href_from_span(&self, span: clean::Span, with_lines: bool) -> Option<String> { pub(crate) fn href_from_span(&self, span: clean::Span, with_lines: bool) -> Option<String> {
let mut root = self.root_path(); let mut root = self.root_path();
let mut path = String::new(); let mut path: String;
let cnum = span.cnum(self.sess()); let cnum = span.cnum(self.sess());
// We can safely ignore synthetic `SourceFile`s. // We can safely ignore synthetic `SourceFile`s.
@ -340,10 +340,24 @@ impl<'tcx> Context<'tcx> {
ExternalLocation::Unknown => return None, ExternalLocation::Unknown => return None,
}; };
sources::clean_path(&src_root, file, false, |component| { let href = RefCell::new(PathBuf::new());
path.push_str(&component.to_string_lossy()); sources::clean_path(
&src_root,
file,
|component| {
href.borrow_mut().push(component);
},
|| {
href.borrow_mut().pop();
},
);
path = href.into_inner().to_string_lossy().to_string();
if let Some(c) = path.as_bytes().last() && *c != b'/' {
path.push('/'); path.push('/');
}); }
let mut fname = file.file_name().expect("source has no filename").to_os_string(); let mut fname = file.file_name().expect("source has no filename").to_os_string();
fname.push(".html"); fname.push(".html");
path.push_str(&fname.to_string_lossy()); path.push_str(&fname.to_string_lossy());

View file

@ -1,8 +1,9 @@
use std::cell::RefCell;
use std::fs::{self, File}; use std::fs::{self, File};
use std::io::prelude::*; use std::io::prelude::*;
use std::io::{self, BufReader}; use std::io::{self, BufReader};
use std::path::{Component, Path}; use std::path::{Component, Path};
use std::rc::Rc; use std::rc::{Rc, Weak};
use itertools::Itertools; use itertools::Itertools;
use rustc_data_structures::flock; use rustc_data_structures::flock;
@ -184,23 +185,26 @@ pub(super) fn write_shared(
use std::ffi::OsString; use std::ffi::OsString;
#[derive(Debug)] #[derive(Debug, Default)]
struct Hierarchy { struct Hierarchy {
parent: Weak<Self>,
elem: OsString, elem: OsString,
children: FxHashMap<OsString, Hierarchy>, children: RefCell<FxHashMap<OsString, Rc<Self>>>,
elems: FxHashSet<OsString>, elems: RefCell<FxHashSet<OsString>>,
} }
impl Hierarchy { impl Hierarchy {
fn new(elem: OsString) -> Hierarchy { fn with_parent(elem: OsString, parent: &Rc<Self>) -> Self {
Hierarchy { elem, children: FxHashMap::default(), elems: FxHashSet::default() } Self { elem, parent: Rc::downgrade(parent), ..Self::default() }
} }
fn to_json_string(&self) -> String { fn to_json_string(&self) -> String {
let mut subs: Vec<&Hierarchy> = self.children.values().collect(); let borrow = self.children.borrow();
let mut subs: Vec<_> = borrow.values().collect();
subs.sort_unstable_by(|a, b| a.elem.cmp(&b.elem)); subs.sort_unstable_by(|a, b| a.elem.cmp(&b.elem));
let mut files = self let mut files = self
.elems .elems
.borrow()
.iter() .iter()
.map(|s| format!("\"{}\"", s.to_str().expect("invalid osstring conversion"))) .map(|s| format!("\"{}\"", s.to_str().expect("invalid osstring conversion")))
.collect::<Vec<_>>(); .collect::<Vec<_>>();
@ -220,36 +224,52 @@ pub(super) fn write_shared(
files = files files = files
) )
} }
fn add_path(self: &Rc<Self>, path: &Path) {
let mut h = Rc::clone(&self);
let mut elems = path
.components()
.filter_map(|s| match s {
Component::Normal(s) => Some(s.to_owned()),
Component::ParentDir => Some(OsString::from("..")),
_ => None,
})
.peekable();
loop {
let cur_elem = elems.next().expect("empty file path");
if cur_elem == ".." {
if let Some(parent) = h.parent.upgrade() {
h = parent;
}
continue;
}
if elems.peek().is_none() {
h.elems.borrow_mut().insert(cur_elem);
break;
} else {
let entry = Rc::clone(
h.children
.borrow_mut()
.entry(cur_elem.clone())
.or_insert_with(|| Rc::new(Self::with_parent(cur_elem, &h))),
);
h = entry;
}
}
}
} }
if cx.include_sources { if cx.include_sources {
let mut hierarchy = Hierarchy::new(OsString::new()); let hierarchy = Rc::new(Hierarchy::default());
for source in cx for source in cx
.shared .shared
.local_sources .local_sources
.iter() .iter()
.filter_map(|p| p.0.strip_prefix(&cx.shared.src_root).ok()) .filter_map(|p| p.0.strip_prefix(&cx.shared.src_root).ok())
{ {
let mut h = &mut hierarchy; hierarchy.add_path(source);
let mut elems = source
.components()
.filter_map(|s| match s {
Component::Normal(s) => Some(s.to_owned()),
_ => None,
})
.peekable();
loop {
let cur_elem = elems.next().expect("empty file path");
if elems.peek().is_none() {
h.elems.insert(cur_elem);
break;
} else {
let e = cur_elem.clone();
h = h.children.entry(cur_elem.clone()).or_insert_with(|| Hierarchy::new(e));
}
}
} }
let hierarchy = Rc::try_unwrap(hierarchy).unwrap();
let dst = cx.dst.join(&format!("source-files{}.js", cx.shared.resource_suffix)); let dst = cx.dst.join(&format!("source-files{}.js", cx.shared.resource_suffix));
let make_sources = || { let make_sources = || {
let (mut all_sources, _krates) = let (mut all_sources, _krates) =

View file

@ -13,6 +13,7 @@ use rustc_middle::ty::TyCtxt;
use rustc_session::Session; use rustc_session::Session;
use rustc_span::source_map::FileName; use rustc_span::source_map::FileName;
use std::cell::RefCell;
use std::ffi::OsStr; use std::ffi::OsStr;
use std::fs; use std::fs;
use std::path::{Component, Path, PathBuf}; use std::path::{Component, Path, PathBuf};
@ -72,12 +73,22 @@ impl LocalSourcesCollector<'_, '_> {
return; return;
} }
let mut href = String::new(); let href = RefCell::new(PathBuf::new());
clean_path(self.src_root, &p, false, |component| { clean_path(
href.push_str(&component.to_string_lossy()); &self.src_root,
href.push('/'); &p,
}); |component| {
href.borrow_mut().push(component);
},
|| {
href.borrow_mut().pop();
},
);
let mut href = href.into_inner().to_string_lossy().to_string();
if let Some(c) = href.as_bytes().last() && *c != b'/' {
href.push('/');
}
let mut src_fname = p.file_name().expect("source has no filename").to_os_string(); let mut src_fname = p.file_name().expect("source has no filename").to_os_string();
src_fname.push(".html"); src_fname.push(".html");
href.push_str(&src_fname.to_string_lossy()); href.push_str(&src_fname.to_string_lossy());
@ -180,13 +191,28 @@ impl SourceCollector<'_, '_> {
let shared = Rc::clone(&self.cx.shared); let shared = Rc::clone(&self.cx.shared);
// Create the intermediate directories // Create the intermediate directories
let mut cur = self.dst.clone(); let cur = RefCell::new(PathBuf::new());
let mut root_path = String::from("../../"); let root_path = RefCell::new(PathBuf::new());
clean_path(&shared.src_root, &p, false, |component| {
cur.push(component);
root_path.push_str("../");
});
clean_path(
&shared.src_root,
&p,
|component| {
cur.borrow_mut().push(component);
root_path.borrow_mut().push("..");
},
|| {
cur.borrow_mut().pop();
root_path.borrow_mut().pop();
},
);
let root_path = PathBuf::from("../../").join(root_path.into_inner());
let mut root_path = root_path.to_string_lossy();
if let Some(c) = root_path.as_bytes().last() && *c != b'/' {
root_path += "/";
}
let mut cur = self.dst.join(cur.into_inner());
shared.ensure_dir(&cur)?; shared.ensure_dir(&cur)?;
let src_fname = p.file_name().expect("source has no filename").to_os_string(); let src_fname = p.file_name().expect("source has no filename").to_os_string();
@ -232,11 +258,13 @@ impl SourceCollector<'_, '_> {
/// Takes a path to a source file and cleans the path to it. This canonicalizes /// Takes a path to a source file and cleans the path to it. This canonicalizes
/// things like ".." to components which preserve the "top down" hierarchy of a /// things like ".." to components which preserve the "top down" hierarchy of a
/// static HTML tree. Each component in the cleaned path will be passed as an /// static HTML tree. Each component in the cleaned path will be passed as an
/// argument to `f`. The very last component of the path (ie the file name) will /// argument to `f`. The very last component of the path (ie the file name) is ignored.
/// be passed to `f` if `keep_filename` is true, and ignored otherwise. /// If a `..` is encountered, the `parent` closure will be called to allow the callee to
pub(crate) fn clean_path<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F) /// handle it.
pub(crate) fn clean_path<F, P>(src_root: &Path, p: &Path, mut f: F, mut parent: P)
where where
F: FnMut(&OsStr), F: FnMut(&OsStr),
P: FnMut(),
{ {
// make it relative, if possible // make it relative, if possible
let p = p.strip_prefix(src_root).unwrap_or(p); let p = p.strip_prefix(src_root).unwrap_or(p);
@ -244,12 +272,12 @@ where
let mut iter = p.components().peekable(); let mut iter = p.components().peekable();
while let Some(c) = iter.next() { while let Some(c) = iter.next() {
if !keep_filename && iter.peek().is_none() { if iter.peek().is_none() {
break; break;
} }
match c { match c {
Component::ParentDir => f("up".as_ref()), Component::ParentDir => parent(),
Component::Normal(c) => f(c), Component::Normal(c) => f(c),
_ => continue, _ => continue,
} }

View file

@ -7,6 +7,11 @@
#[path = "src-links/mod.rs"] #[path = "src-links/mod.rs"]
pub mod qux; pub mod qux;
// @has src/foo/src-links.rs.html
// @has foo/fizz/index.html '//a/@href' '../src/foo/src-links/fizz.rs.html'
#[path = "src-links/../src-links/fizz.rs"]
pub mod fizz;
// @has foo/bar/index.html '//a/@href' '../../src/foo/src-links.rs.html' // @has foo/bar/index.html '//a/@href' '../../src/foo/src-links.rs.html'
pub mod bar { pub mod bar {

View file

@ -0,0 +1 @@
pub struct Buzz;