Auto merge of #73767 - P1n3appl3:rustdoc-formats, r=tmandry
Refactor librustdoc html backend This PR moves several types out of the librustdoc::html module so that they can be used by a future json backend. These changes are a re-implementation of [some work done 6 months ago](https://github.com/rust-lang/rust/compare/master...GuillaumeGomez:multiple-output-formats) by @GuillaumeGomez. I'm currently working on said json backend and will put up an RFC soon with the proposed implementation. There are a couple of changes that are more substantial than relocating structs to a different module: 1. The `Cache` is no longer part of the `html::render::Context` type and therefor it needs to be explicitly passed to any functions that access it. 2. The driving function `html::render::run` has been rewritten to use the `FormatRenderer` trait which should allow different backends to re-use the driving code. r? @GuillaumeGomez cc @tmandry @betamos
This commit is contained in:
commit
6b269e4432
@ -32,8 +32,9 @@ use crate::clean::inline;
|
||||
use crate::clean::types::Type::{QPath, ResolvedPath};
|
||||
use crate::core::DocContext;
|
||||
use crate::doctree;
|
||||
use crate::html::item_type::ItemType;
|
||||
use crate::html::render::{cache, ExternalLocation};
|
||||
use crate::formats::cache::cache;
|
||||
use crate::formats::item_type::ItemType;
|
||||
use crate::html::render::cache::ExternalLocation;
|
||||
|
||||
use self::FnRetTy::*;
|
||||
use self::ItemEnum::*;
|
||||
@ -1172,7 +1173,7 @@ impl GetDefId for Type {
|
||||
fn def_id(&self) -> Option<DefId> {
|
||||
match *self {
|
||||
ResolvedPath { did, .. } => Some(did),
|
||||
Primitive(p) => crate::html::render::cache().primitive_locations.get(&p).cloned(),
|
||||
Primitive(p) => cache().primitive_locations.get(&p).cloned(),
|
||||
BorrowedRef { type_: box Generic(..), .. } => {
|
||||
Primitive(PrimitiveType::Reference).def_id()
|
||||
}
|
||||
|
@ -4,6 +4,9 @@ use std::ffi::OsStr;
|
||||
use std::fmt;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
|
||||
use rustc_hir::def_id::DefId;
|
||||
use rustc_middle::middle::privacy::AccessLevels;
|
||||
use rustc_session::config::{self, parse_crate_types_from_list, parse_externs, CrateType};
|
||||
use rustc_session::config::{
|
||||
build_codegen_options, build_debugging_options, get_cmd_lint_options, host_triple,
|
||||
@ -249,6 +252,20 @@ pub struct RenderOptions {
|
||||
pub document_hidden: bool,
|
||||
}
|
||||
|
||||
/// Temporary storage for data obtained during `RustdocVisitor::clean()`.
|
||||
/// Later on moved into `CACHE_KEY`.
|
||||
#[derive(Default, Clone)]
|
||||
pub struct RenderInfo {
|
||||
pub inlined: FxHashSet<DefId>,
|
||||
pub external_paths: crate::core::ExternalPaths,
|
||||
pub exact_paths: FxHashMap<DefId, Vec<String>>,
|
||||
pub access_levels: AccessLevels<DefId>,
|
||||
pub deref_trait_did: Option<DefId>,
|
||||
pub deref_mut_trait_did: Option<DefId>,
|
||||
pub owned_box_did: Option<DefId>,
|
||||
pub output_format: Option<OutputFormat>,
|
||||
}
|
||||
|
||||
impl Options {
|
||||
/// Parses the given command-line for options. If an error message or other early-return has
|
||||
/// been printed, returns `Err` with the exit code.
|
||||
|
@ -32,8 +32,8 @@ use std::rc::Rc;
|
||||
|
||||
use crate::clean;
|
||||
use crate::clean::{AttributesExt, MAX_DEF_ID};
|
||||
use crate::config::RenderInfo;
|
||||
use crate::config::{Options as RustdocOptions, RenderOptions};
|
||||
use crate::html::render::RenderInfo;
|
||||
use crate::passes::{self, Condition::*, ConditionalPass};
|
||||
|
||||
pub use rustc_session::config::{CodegenOptions, DebuggingOptions, Input, Options};
|
||||
@ -44,9 +44,9 @@ pub type ExternalPaths = FxHashMap<DefId, (Vec<String>, clean::TypeKind)>;
|
||||
pub struct DocContext<'tcx> {
|
||||
pub tcx: TyCtxt<'tcx>,
|
||||
pub resolver: Rc<RefCell<interface::BoxedResolver>>,
|
||||
/// Later on moved into `html::render::CACHE_KEY`
|
||||
/// Later on moved into `CACHE_KEY`
|
||||
pub renderinfo: RefCell<RenderInfo>,
|
||||
/// Later on moved through `clean::Crate` into `html::render::CACHE_KEY`
|
||||
/// Later on moved through `clean::Crate` into `CACHE_KEY`
|
||||
pub external_traits: Rc<RefCell<FxHashMap<DefId, clean::Trait>>>,
|
||||
/// Used while populating `external_traits` to ensure we don't process the same trait twice at
|
||||
/// the same time.
|
||||
|
@ -13,8 +13,7 @@ use std::fs;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use std::string::ToString;
|
||||
use std::sync::mpsc::{channel, Receiver, Sender};
|
||||
use std::sync::Arc;
|
||||
use std::sync::mpsc::Sender;
|
||||
|
||||
macro_rules! try_err {
|
||||
($e:expr, $file:expr) => {
|
||||
@ -31,47 +30,24 @@ pub trait PathError {
|
||||
S: ToString + Sized;
|
||||
}
|
||||
|
||||
pub struct ErrorStorage {
|
||||
sender: Option<Sender<Option<String>>>,
|
||||
receiver: Receiver<Option<String>>,
|
||||
}
|
||||
|
||||
impl ErrorStorage {
|
||||
pub fn new() -> ErrorStorage {
|
||||
let (sender, receiver) = channel();
|
||||
ErrorStorage { sender: Some(sender), receiver }
|
||||
}
|
||||
|
||||
/// Prints all stored errors. Returns the number of printed errors.
|
||||
pub fn write_errors(&mut self, diag: &rustc_errors::Handler) -> usize {
|
||||
let mut printed = 0;
|
||||
// In order to drop the sender part of the channel.
|
||||
self.sender = None;
|
||||
|
||||
for msg in self.receiver.iter() {
|
||||
if let Some(ref error) = msg {
|
||||
diag.struct_err(&error).emit();
|
||||
printed += 1;
|
||||
}
|
||||
}
|
||||
printed
|
||||
}
|
||||
}
|
||||
|
||||
pub struct DocFS {
|
||||
sync_only: bool,
|
||||
errors: Arc<ErrorStorage>,
|
||||
errors: Option<Sender<String>>,
|
||||
}
|
||||
|
||||
impl DocFS {
|
||||
pub fn new(errors: &Arc<ErrorStorage>) -> DocFS {
|
||||
DocFS { sync_only: false, errors: Arc::clone(errors) }
|
||||
pub fn new(errors: Sender<String>) -> DocFS {
|
||||
DocFS { sync_only: false, errors: Some(errors) }
|
||||
}
|
||||
|
||||
pub fn set_sync_only(&mut self, sync_only: bool) {
|
||||
self.sync_only = sync_only;
|
||||
}
|
||||
|
||||
pub fn close(&mut self) {
|
||||
self.errors = None;
|
||||
}
|
||||
|
||||
pub fn create_dir_all<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
|
||||
// For now, dir creation isn't a huge time consideration, do it
|
||||
// synchronously, which avoids needing ordering between write() actions
|
||||
@ -88,20 +64,15 @@ impl DocFS {
|
||||
if !self.sync_only && cfg!(windows) {
|
||||
// A possible future enhancement after more detailed profiling would
|
||||
// be to create the file sync so errors are reported eagerly.
|
||||
let contents = contents.as_ref().to_vec();
|
||||
let path = path.as_ref().to_path_buf();
|
||||
let sender = self.errors.sender.clone().unwrap();
|
||||
rayon::spawn(move || match fs::write(&path, &contents) {
|
||||
Ok(_) => {
|
||||
sender.send(None).unwrap_or_else(|_| {
|
||||
panic!("failed to send error on \"{}\"", path.display())
|
||||
});
|
||||
}
|
||||
Err(e) => {
|
||||
sender.send(Some(format!("\"{}\": {}", path.display(), e))).unwrap_or_else(
|
||||
|_| panic!("failed to send non-error on \"{}\"", path.display()),
|
||||
);
|
||||
}
|
||||
let contents = contents.as_ref().to_vec();
|
||||
let sender = self.errors.clone().expect("can't write after closing");
|
||||
rayon::spawn(move || {
|
||||
fs::write(&path, contents).unwrap_or_else(|e| {
|
||||
sender
|
||||
.send(format!("\"{}\": {}", path.display(), e))
|
||||
.expect(&format!("failed to send error on \"{}\"", path.display()));
|
||||
});
|
||||
});
|
||||
Ok(())
|
||||
} else {
|
||||
|
56
src/librustdoc/error.rs
Normal file
56
src/librustdoc/error.rs
Normal file
@ -0,0 +1,56 @@
|
||||
use std::error;
|
||||
use std::fmt::{self, Formatter};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::docfs::PathError;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Error {
|
||||
pub file: PathBuf,
|
||||
pub error: String,
|
||||
}
|
||||
|
||||
impl error::Error for Error {}
|
||||
|
||||
impl std::fmt::Display for Error {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
||||
let file = self.file.display().to_string();
|
||||
if file.is_empty() {
|
||||
write!(f, "{}", self.error)
|
||||
} else {
|
||||
write!(f, "\"{}\": {}", self.file.display(), self.error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PathError for Error {
|
||||
fn new<S, P: AsRef<Path>>(e: S, path: P) -> Error
|
||||
where
|
||||
S: ToString + Sized,
|
||||
{
|
||||
Error { file: path.as_ref().to_path_buf(), error: e.to_string() }
|
||||
}
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! try_none {
|
||||
($e:expr, $file:expr) => {{
|
||||
use std::io;
|
||||
match $e {
|
||||
Some(e) => e,
|
||||
None => {
|
||||
return Err(Error::new(io::Error::new(io::ErrorKind::Other, "not found"), $file));
|
||||
}
|
||||
}
|
||||
}};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! try_err {
|
||||
($e:expr, $file:expr) => {{
|
||||
match $e {
|
||||
Ok(e) => e,
|
||||
Err(e) => return Err(Error::new(e, $file)),
|
||||
}
|
||||
}};
|
||||
}
|
488
src/librustdoc/formats/cache.rs
Normal file
488
src/librustdoc/formats/cache.rs
Normal file
@ -0,0 +1,488 @@
|
||||
use std::cell::RefCell;
|
||||
use std::collections::BTreeMap;
|
||||
use std::mem;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
|
||||
use rustc_hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX};
|
||||
use rustc_middle::middle::privacy::AccessLevels;
|
||||
use rustc_span::source_map::FileName;
|
||||
|
||||
use crate::clean::{self, GetDefId};
|
||||
use crate::config::RenderInfo;
|
||||
use crate::fold::DocFolder;
|
||||
use crate::formats::item_type::ItemType;
|
||||
use crate::formats::Impl;
|
||||
use crate::html::render::cache::{extern_location, get_index_search_type, ExternalLocation};
|
||||
use crate::html::render::IndexItem;
|
||||
use crate::html::render::{plain_summary_line, shorten};
|
||||
|
||||
thread_local!(crate static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
|
||||
|
||||
/// This cache is used to store information about the `clean::Crate` being
|
||||
/// rendered in order to provide more useful documentation. This contains
|
||||
/// information like all implementors of a trait, all traits a type implements,
|
||||
/// documentation for all known traits, etc.
|
||||
///
|
||||
/// This structure purposefully does not implement `Clone` because it's intended
|
||||
/// to be a fairly large and expensive structure to clone. Instead this adheres
|
||||
/// to `Send` so it may be stored in a `Arc` instance and shared among the various
|
||||
/// rendering threads.
|
||||
#[derive(Default)]
|
||||
pub struct Cache {
|
||||
/// Maps a type ID to all known implementations for that type. This is only
|
||||
/// recognized for intra-crate `ResolvedPath` types, and is used to print
|
||||
/// out extra documentation on the page of an enum/struct.
|
||||
///
|
||||
/// The values of the map are a list of implementations and documentation
|
||||
/// found on that implementation.
|
||||
pub impls: FxHashMap<DefId, Vec<Impl>>,
|
||||
|
||||
/// Maintains a mapping of local crate `DefId`s to the fully qualified name
|
||||
/// and "short type description" of that node. This is used when generating
|
||||
/// URLs when a type is being linked to. External paths are not located in
|
||||
/// this map because the `External` type itself has all the information
|
||||
/// necessary.
|
||||
pub paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
|
||||
|
||||
/// Similar to `paths`, but only holds external paths. This is only used for
|
||||
/// generating explicit hyperlinks to other crates.
|
||||
pub external_paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
|
||||
|
||||
/// Maps local `DefId`s of exported types to fully qualified paths.
|
||||
/// Unlike 'paths', this mapping ignores any renames that occur
|
||||
/// due to 'use' statements.
|
||||
///
|
||||
/// This map is used when writing out the special 'implementors'
|
||||
/// javascript file. By using the exact path that the type
|
||||
/// is declared with, we ensure that each path will be identical
|
||||
/// to the path used if the corresponding type is inlined. By
|
||||
/// doing this, we can detect duplicate impls on a trait page, and only display
|
||||
/// the impl for the inlined type.
|
||||
pub exact_paths: FxHashMap<DefId, Vec<String>>,
|
||||
|
||||
/// This map contains information about all known traits of this crate.
|
||||
/// Implementations of a crate should inherit the documentation of the
|
||||
/// parent trait if no extra documentation is specified, and default methods
|
||||
/// should show up in documentation about trait implementations.
|
||||
pub traits: FxHashMap<DefId, clean::Trait>,
|
||||
|
||||
/// When rendering traits, it's often useful to be able to list all
|
||||
/// implementors of the trait, and this mapping is exactly, that: a mapping
|
||||
/// of trait ids to the list of known implementors of the trait
|
||||
pub implementors: FxHashMap<DefId, Vec<Impl>>,
|
||||
|
||||
/// Cache of where external crate documentation can be found.
|
||||
pub extern_locations: FxHashMap<CrateNum, (String, PathBuf, ExternalLocation)>,
|
||||
|
||||
/// Cache of where documentation for primitives can be found.
|
||||
pub primitive_locations: FxHashMap<clean::PrimitiveType, DefId>,
|
||||
|
||||
// Note that external items for which `doc(hidden)` applies to are shown as
|
||||
// non-reachable while local items aren't. This is because we're reusing
|
||||
// the access levels from the privacy check pass.
|
||||
pub access_levels: AccessLevels<DefId>,
|
||||
|
||||
/// The version of the crate being documented, if given from the `--crate-version` flag.
|
||||
pub crate_version: Option<String>,
|
||||
|
||||
/// Whether to document private items.
|
||||
/// This is stored in `Cache` so it doesn't need to be passed through all rustdoc functions.
|
||||
pub document_private: bool,
|
||||
|
||||
// Private fields only used when initially crawling a crate to build a cache
|
||||
stack: Vec<String>,
|
||||
parent_stack: Vec<DefId>,
|
||||
parent_is_trait_impl: bool,
|
||||
stripped_mod: bool,
|
||||
masked_crates: FxHashSet<CrateNum>,
|
||||
|
||||
pub search_index: Vec<IndexItem>,
|
||||
pub deref_trait_did: Option<DefId>,
|
||||
pub deref_mut_trait_did: Option<DefId>,
|
||||
pub owned_box_did: Option<DefId>,
|
||||
|
||||
// In rare case where a structure is defined in one module but implemented
|
||||
// in another, if the implementing module is parsed before defining module,
|
||||
// then the fully qualified name of the structure isn't presented in `paths`
|
||||
// yet when its implementation methods are being indexed. Caches such methods
|
||||
// and their parent id here and indexes them at the end of crate parsing.
|
||||
pub orphan_impl_items: Vec<(DefId, clean::Item)>,
|
||||
|
||||
// Similarly to `orphan_impl_items`, sometimes trait impls are picked up
|
||||
// even though the trait itself is not exported. This can happen if a trait
|
||||
// was defined in function/expression scope, since the impl will be picked
|
||||
// up by `collect-trait-impls` but the trait won't be scraped out in the HIR
|
||||
// crawl. In order to prevent crashes when looking for spotlight traits or
|
||||
// when gathering trait documentation on a type, hold impls here while
|
||||
// folding and add them to the cache later on if we find the trait.
|
||||
orphan_trait_impls: Vec<(DefId, FxHashSet<DefId>, Impl)>,
|
||||
|
||||
/// Aliases added through `#[doc(alias = "...")]`. Since a few items can have the same alias,
|
||||
/// we need the alias element to have an array of items.
|
||||
pub aliases: BTreeMap<String, Vec<usize>>,
|
||||
}
|
||||
|
||||
impl Cache {
|
||||
pub fn from_krate(
|
||||
render_info: RenderInfo,
|
||||
document_private: bool,
|
||||
extern_html_root_urls: &BTreeMap<String, String>,
|
||||
dst: &Path,
|
||||
mut krate: clean::Crate,
|
||||
) -> (clean::Crate, Cache) {
|
||||
// Crawl the crate to build various caches used for the output
|
||||
let RenderInfo {
|
||||
inlined: _,
|
||||
external_paths,
|
||||
exact_paths,
|
||||
access_levels,
|
||||
deref_trait_did,
|
||||
deref_mut_trait_did,
|
||||
owned_box_did,
|
||||
..
|
||||
} = render_info;
|
||||
|
||||
let external_paths =
|
||||
external_paths.into_iter().map(|(k, (v, t))| (k, (v, ItemType::from(t)))).collect();
|
||||
|
||||
let mut cache = Cache {
|
||||
external_paths,
|
||||
exact_paths,
|
||||
parent_is_trait_impl: false,
|
||||
stripped_mod: false,
|
||||
access_levels,
|
||||
crate_version: krate.version.take(),
|
||||
document_private,
|
||||
traits: krate.external_traits.replace(Default::default()),
|
||||
deref_trait_did,
|
||||
deref_mut_trait_did,
|
||||
owned_box_did,
|
||||
masked_crates: mem::take(&mut krate.masked_crates),
|
||||
..Cache::default()
|
||||
};
|
||||
|
||||
// Cache where all our extern crates are located
|
||||
// FIXME: this part is specific to HTML so it'd be nice to remove it from the common code
|
||||
for &(n, ref e) in &krate.externs {
|
||||
let src_root = match e.src {
|
||||
FileName::Real(ref p) => match p.local_path().parent() {
|
||||
Some(p) => p.to_path_buf(),
|
||||
None => PathBuf::new(),
|
||||
},
|
||||
_ => PathBuf::new(),
|
||||
};
|
||||
let extern_url = extern_html_root_urls.get(&e.name).map(|u| &**u);
|
||||
cache
|
||||
.extern_locations
|
||||
.insert(n, (e.name.clone(), src_root, extern_location(e, extern_url, &dst)));
|
||||
|
||||
let did = DefId { krate: n, index: CRATE_DEF_INDEX };
|
||||
cache.external_paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
|
||||
}
|
||||
|
||||
// Cache where all known primitives have their documentation located.
|
||||
//
|
||||
// Favor linking to as local extern as possible, so iterate all crates in
|
||||
// reverse topological order.
|
||||
for &(_, ref e) in krate.externs.iter().rev() {
|
||||
for &(def_id, prim, _) in &e.primitives {
|
||||
cache.primitive_locations.insert(prim, def_id);
|
||||
}
|
||||
}
|
||||
for &(def_id, prim, _) in &krate.primitives {
|
||||
cache.primitive_locations.insert(prim, def_id);
|
||||
}
|
||||
|
||||
cache.stack.push(krate.name.clone());
|
||||
krate = cache.fold_crate(krate);
|
||||
|
||||
for (trait_did, dids, impl_) in cache.orphan_trait_impls.drain(..) {
|
||||
if cache.traits.contains_key(&trait_did) {
|
||||
for did in dids {
|
||||
cache.impls.entry(did).or_default().push(impl_.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
(krate, cache)
|
||||
}
|
||||
}
|
||||
|
||||
impl DocFolder for Cache {
|
||||
fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
|
||||
if item.def_id.is_local() {
|
||||
debug!("folding {} \"{:?}\", id {:?}", item.type_(), item.name, item.def_id);
|
||||
}
|
||||
|
||||
// If this is a stripped module,
|
||||
// we don't want it or its children in the search index.
|
||||
let orig_stripped_mod = match item.inner {
|
||||
clean::StrippedItem(box clean::ModuleItem(..)) => {
|
||||
mem::replace(&mut self.stripped_mod, true)
|
||||
}
|
||||
_ => self.stripped_mod,
|
||||
};
|
||||
|
||||
// If the impl is from a masked crate or references something from a
|
||||
// masked crate then remove it completely.
|
||||
if let clean::ImplItem(ref i) = item.inner {
|
||||
if self.masked_crates.contains(&item.def_id.krate)
|
||||
|| i.trait_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate))
|
||||
|| i.for_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
}
|
||||
|
||||
// Propagate a trait method's documentation to all implementors of the
|
||||
// trait.
|
||||
if let clean::TraitItem(ref t) = item.inner {
|
||||
self.traits.entry(item.def_id).or_insert_with(|| t.clone());
|
||||
}
|
||||
|
||||
// Collect all the implementors of traits.
|
||||
if let clean::ImplItem(ref i) = item.inner {
|
||||
if let Some(did) = i.trait_.def_id() {
|
||||
if i.blanket_impl.is_none() {
|
||||
self.implementors
|
||||
.entry(did)
|
||||
.or_default()
|
||||
.push(Impl { impl_item: item.clone() });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Index this method for searching later on.
|
||||
if let Some(ref s) = item.name {
|
||||
let (parent, is_inherent_impl_item) = match item.inner {
|
||||
clean::StrippedItem(..) => ((None, None), false),
|
||||
clean::AssocConstItem(..) | clean::TypedefItem(_, true)
|
||||
if self.parent_is_trait_impl =>
|
||||
{
|
||||
// skip associated items in trait impls
|
||||
((None, None), false)
|
||||
}
|
||||
clean::AssocTypeItem(..)
|
||||
| clean::TyMethodItem(..)
|
||||
| clean::StructFieldItem(..)
|
||||
| clean::VariantItem(..) => (
|
||||
(
|
||||
Some(*self.parent_stack.last().expect("parent_stack is empty")),
|
||||
Some(&self.stack[..self.stack.len() - 1]),
|
||||
),
|
||||
false,
|
||||
),
|
||||
clean::MethodItem(..) | clean::AssocConstItem(..) => {
|
||||
if self.parent_stack.is_empty() {
|
||||
((None, None), false)
|
||||
} else {
|
||||
let last = self.parent_stack.last().expect("parent_stack is empty 2");
|
||||
let did = *last;
|
||||
let path = match self.paths.get(&did) {
|
||||
// The current stack not necessarily has correlation
|
||||
// for where the type was defined. On the other
|
||||
// hand, `paths` always has the right
|
||||
// information if present.
|
||||
Some(&(
|
||||
ref fqp,
|
||||
ItemType::Trait
|
||||
| ItemType::Struct
|
||||
| ItemType::Union
|
||||
| ItemType::Enum,
|
||||
)) => Some(&fqp[..fqp.len() - 1]),
|
||||
Some(..) => Some(&*self.stack),
|
||||
None => None,
|
||||
};
|
||||
((Some(*last), path), true)
|
||||
}
|
||||
}
|
||||
_ => ((None, Some(&*self.stack)), false),
|
||||
};
|
||||
|
||||
match parent {
|
||||
(parent, Some(path)) if is_inherent_impl_item || !self.stripped_mod => {
|
||||
debug_assert!(!item.is_stripped());
|
||||
|
||||
// A crate has a module at its root, containing all items,
|
||||
// which should not be indexed. The crate-item itself is
|
||||
// inserted later on when serializing the search-index.
|
||||
if item.def_id.index != CRATE_DEF_INDEX {
|
||||
self.search_index.push(IndexItem {
|
||||
ty: item.type_(),
|
||||
name: s.to_string(),
|
||||
path: path.join("::"),
|
||||
desc: shorten(plain_summary_line(item.doc_value())),
|
||||
parent,
|
||||
parent_idx: None,
|
||||
search_type: get_index_search_type(&item),
|
||||
});
|
||||
|
||||
for alias in item.attrs.get_doc_aliases() {
|
||||
self.aliases
|
||||
.entry(alias.to_lowercase())
|
||||
.or_insert(Vec::new())
|
||||
.push(self.search_index.len() - 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
(Some(parent), None) if is_inherent_impl_item => {
|
||||
// We have a parent, but we don't know where they're
|
||||
// defined yet. Wait for later to index this item.
|
||||
self.orphan_impl_items.push((parent, item.clone()));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
// Keep track of the fully qualified path for this item.
|
||||
let pushed = match item.name {
|
||||
Some(ref n) if !n.is_empty() => {
|
||||
self.stack.push(n.to_string());
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
|
||||
match item.inner {
|
||||
clean::StructItem(..)
|
||||
| clean::EnumItem(..)
|
||||
| clean::TypedefItem(..)
|
||||
| clean::TraitItem(..)
|
||||
| clean::FunctionItem(..)
|
||||
| clean::ModuleItem(..)
|
||||
| clean::ForeignFunctionItem(..)
|
||||
| clean::ForeignStaticItem(..)
|
||||
| clean::ConstantItem(..)
|
||||
| clean::StaticItem(..)
|
||||
| clean::UnionItem(..)
|
||||
| clean::ForeignTypeItem
|
||||
| clean::MacroItem(..)
|
||||
| clean::ProcMacroItem(..)
|
||||
| clean::VariantItem(..)
|
||||
if !self.stripped_mod =>
|
||||
{
|
||||
// Re-exported items mean that the same id can show up twice
|
||||
// in the rustdoc ast that we're looking at. We know,
|
||||
// however, that a re-exported item doesn't show up in the
|
||||
// `public_items` map, so we can skip inserting into the
|
||||
// paths map if there was already an entry present and we're
|
||||
// not a public item.
|
||||
if !self.paths.contains_key(&item.def_id)
|
||||
|| self.access_levels.is_public(item.def_id)
|
||||
{
|
||||
self.paths.insert(item.def_id, (self.stack.clone(), item.type_()));
|
||||
}
|
||||
}
|
||||
clean::PrimitiveItem(..) => {
|
||||
self.paths.insert(item.def_id, (self.stack.clone(), item.type_()));
|
||||
}
|
||||
|
||||
_ => {}
|
||||
}
|
||||
|
||||
// Maintain the parent stack
|
||||
let orig_parent_is_trait_impl = self.parent_is_trait_impl;
|
||||
let parent_pushed = match item.inner {
|
||||
clean::TraitItem(..)
|
||||
| clean::EnumItem(..)
|
||||
| clean::ForeignTypeItem
|
||||
| clean::StructItem(..)
|
||||
| clean::UnionItem(..)
|
||||
| clean::VariantItem(..) => {
|
||||
self.parent_stack.push(item.def_id);
|
||||
self.parent_is_trait_impl = false;
|
||||
true
|
||||
}
|
||||
clean::ImplItem(ref i) => {
|
||||
self.parent_is_trait_impl = i.trait_.is_some();
|
||||
match i.for_ {
|
||||
clean::ResolvedPath { did, .. } => {
|
||||
self.parent_stack.push(did);
|
||||
true
|
||||
}
|
||||
ref t => {
|
||||
let prim_did = t
|
||||
.primitive_type()
|
||||
.and_then(|t| self.primitive_locations.get(&t).cloned());
|
||||
match prim_did {
|
||||
Some(did) => {
|
||||
self.parent_stack.push(did);
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
|
||||
// Once we've recursively found all the generics, hoard off all the
|
||||
// implementations elsewhere.
|
||||
let ret = self.fold_item_recur(item).and_then(|item| {
|
||||
if let clean::Item { inner: clean::ImplItem(_), .. } = item {
|
||||
// Figure out the id of this impl. This may map to a
|
||||
// primitive rather than always to a struct/enum.
|
||||
// Note: matching twice to restrict the lifetime of the `i` borrow.
|
||||
let mut dids = FxHashSet::default();
|
||||
if let clean::Item { inner: clean::ImplItem(ref i), .. } = item {
|
||||
match i.for_ {
|
||||
clean::ResolvedPath { did, .. }
|
||||
| clean::BorrowedRef {
|
||||
type_: box clean::ResolvedPath { did, .. }, ..
|
||||
} => {
|
||||
dids.insert(did);
|
||||
}
|
||||
ref t => {
|
||||
let did = t
|
||||
.primitive_type()
|
||||
.and_then(|t| self.primitive_locations.get(&t).cloned());
|
||||
|
||||
if let Some(did) = did {
|
||||
dids.insert(did);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) {
|
||||
for bound in generics {
|
||||
if let Some(did) = bound.def_id() {
|
||||
dids.insert(did);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
unreachable!()
|
||||
};
|
||||
let impl_item = Impl { impl_item: item };
|
||||
if impl_item.trait_did().map_or(true, |d| self.traits.contains_key(&d)) {
|
||||
for did in dids {
|
||||
self.impls.entry(did).or_insert(vec![]).push(impl_item.clone());
|
||||
}
|
||||
} else {
|
||||
let trait_did = impl_item.trait_did().expect("no trait did");
|
||||
self.orphan_trait_impls.push((trait_did, dids, impl_item));
|
||||
}
|
||||
None
|
||||
} else {
|
||||
Some(item)
|
||||
}
|
||||
});
|
||||
|
||||
if pushed {
|
||||
self.stack.pop().expect("stack already empty");
|
||||
}
|
||||
if parent_pushed {
|
||||
self.parent_stack.pop().expect("parent stack already empty");
|
||||
}
|
||||
self.stripped_mod = orig_stripped_mod;
|
||||
self.parent_is_trait_impl = orig_parent_is_trait_impl;
|
||||
ret
|
||||
}
|
||||
}
|
||||
|
||||
crate fn cache() -> Arc<Cache> {
|
||||
CACHE_KEY.with(|c| c.borrow().clone())
|
||||
}
|
@ -13,7 +13,7 @@ use crate::clean;
|
||||
/// The search index uses item types encoded as smaller numbers which equal to
|
||||
/// discriminants. JavaScript then is used to decode them into the original value.
|
||||
/// Consequently, every change to this type should be synchronized to
|
||||
/// the `itemTypes` mapping table in `static/main.js`.
|
||||
/// the `itemTypes` mapping table in `html/static/main.js`.
|
||||
///
|
||||
/// In addition, code in `html::render` uses this enum to generate CSS classes, page prefixes, and
|
||||
/// module headings. If you are adding to this enum and want to ensure that the sidebar also prints
|
44
src/librustdoc/formats/mod.rs
Normal file
44
src/librustdoc/formats/mod.rs
Normal file
@ -0,0 +1,44 @@
|
||||
pub mod cache;
|
||||
pub mod item_type;
|
||||
pub mod renderer;
|
||||
|
||||
pub use renderer::{run_format, FormatRenderer};
|
||||
|
||||
use rustc_span::def_id::DefId;
|
||||
|
||||
use crate::clean;
|
||||
use crate::clean::types::GetDefId;
|
||||
|
||||
/// Specifies whether rendering directly implemented trait items or ones from a certain Deref
|
||||
/// impl.
|
||||
pub enum AssocItemRender<'a> {
|
||||
All,
|
||||
DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool },
|
||||
}
|
||||
|
||||
/// For different handling of associated items from the Deref target of a type rather than the type
|
||||
/// itself.
|
||||
#[derive(Copy, Clone, PartialEq)]
|
||||
pub enum RenderMode {
|
||||
Normal,
|
||||
ForDeref { mut_: bool },
|
||||
}
|
||||
|
||||
/// Metadata about implementations for a type or trait.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Impl {
|
||||
pub impl_item: clean::Item,
|
||||
}
|
||||
|
||||
impl Impl {
|
||||
pub fn inner_impl(&self) -> &clean::Impl {
|
||||
match self.impl_item.inner {
|
||||
clean::ImplItem(ref impl_) => impl_,
|
||||
_ => panic!("non-impl item found in impl"),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn trait_did(&self) -> Option<DefId> {
|
||||
self.inner_impl().trait_.def_id()
|
||||
}
|
||||
}
|
106
src/librustdoc/formats/renderer.rs
Normal file
106
src/librustdoc/formats/renderer.rs
Normal file
@ -0,0 +1,106 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use rustc_span::edition::Edition;
|
||||
|
||||
use crate::clean;
|
||||
use crate::config::{RenderInfo, RenderOptions};
|
||||
use crate::error::Error;
|
||||
use crate::formats::cache::{Cache, CACHE_KEY};
|
||||
|
||||
/// Allows for different backends to rustdoc to be used with the `run_format()` function. Each
|
||||
/// backend renderer has hooks for initialization, documenting an item, entering and exiting a
|
||||
/// module, and cleanup/finalizing output.
|
||||
pub trait FormatRenderer: Clone {
|
||||
/// Sets up any state required for the renderer. When this is called the cache has already been
|
||||
/// populated.
|
||||
fn init(
|
||||
krate: clean::Crate,
|
||||
options: RenderOptions,
|
||||
render_info: RenderInfo,
|
||||
edition: Edition,
|
||||
cache: &mut Cache,
|
||||
) -> Result<(Self, clean::Crate), Error>;
|
||||
|
||||
/// Renders a single non-module item. This means no recursive sub-item rendering is required.
|
||||
fn item(&mut self, item: clean::Item, cache: &Cache) -> Result<(), Error>;
|
||||
|
||||
/// Renders a module (should not handle recursing into children).
|
||||
fn mod_item_in(
|
||||
&mut self,
|
||||
item: &clean::Item,
|
||||
item_name: &str,
|
||||
cache: &Cache,
|
||||
) -> Result<(), Error>;
|
||||
|
||||
/// Runs after recursively rendering all sub-items of a module.
|
||||
fn mod_item_out(&mut self, item_name: &str) -> Result<(), Error>;
|
||||
|
||||
/// Post processing hook for cleanup and dumping output to files.
|
||||
fn after_krate(&mut self, krate: &clean::Crate, cache: &Cache) -> Result<(), Error>;
|
||||
|
||||
/// Called after everything else to write out errors.
|
||||
fn after_run(&mut self, diag: &rustc_errors::Handler) -> Result<(), Error>;
|
||||
}
|
||||
|
||||
/// Main method for rendering a crate.
|
||||
pub fn run_format<T: FormatRenderer>(
|
||||
krate: clean::Crate,
|
||||
options: RenderOptions,
|
||||
render_info: RenderInfo,
|
||||
diag: &rustc_errors::Handler,
|
||||
edition: Edition,
|
||||
) -> Result<(), Error> {
|
||||
let (krate, mut cache) = Cache::from_krate(
|
||||
render_info.clone(),
|
||||
options.document_private,
|
||||
&options.extern_html_root_urls,
|
||||
&options.output,
|
||||
krate,
|
||||
);
|
||||
|
||||
let (mut format_renderer, mut krate) =
|
||||
T::init(krate, options, render_info, edition, &mut cache)?;
|
||||
|
||||
let cache = Arc::new(cache);
|
||||
// Freeze the cache now that the index has been built. Put an Arc into TLS for future
|
||||
// parallelization opportunities
|
||||
CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
|
||||
|
||||
let mut item = match krate.module.take() {
|
||||
Some(i) => i,
|
||||
None => return Ok(()),
|
||||
};
|
||||
|
||||
item.name = Some(krate.name.clone());
|
||||
|
||||
// Render the crate documentation
|
||||
let mut work = vec![(format_renderer.clone(), item)];
|
||||
|
||||
while let Some((mut cx, item)) = work.pop() {
|
||||
if item.is_mod() {
|
||||
// modules are special because they add a namespace. We also need to
|
||||
// recurse into the items of the module as well.
|
||||
let name = item.name.as_ref().unwrap().to_string();
|
||||
if name.is_empty() {
|
||||
panic!("Unexpected module with empty name");
|
||||
}
|
||||
|
||||
cx.mod_item_in(&item, &name, &cache)?;
|
||||
let module = match item.inner {
|
||||
clean::StrippedItem(box clean::ModuleItem(m)) | clean::ModuleItem(m) => m,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
for it in module.items {
|
||||
debug!("Adding {:?} to worklist", it.name);
|
||||
work.push((cx.clone(), it));
|
||||
}
|
||||
|
||||
cx.mod_item_out(&name)?;
|
||||
} else if item.name.is_some() {
|
||||
cx.item(item, &cache)?;
|
||||
}
|
||||
}
|
||||
|
||||
format_renderer.after_krate(&krate, &cache)?;
|
||||
format_renderer.after_run(diag)
|
||||
}
|
@ -11,13 +11,15 @@ use std::fmt;
|
||||
|
||||
use rustc_data_structures::fx::FxHashSet;
|
||||
use rustc_hir as hir;
|
||||
use rustc_hir::def_id::DefId;
|
||||
use rustc_span::def_id::DefId;
|
||||
use rustc_target::spec::abi::Abi;
|
||||
|
||||
use crate::clean::{self, PrimitiveType};
|
||||
use crate::formats::cache::cache;
|
||||
use crate::formats::item_type::ItemType;
|
||||
use crate::html::escape::Escape;
|
||||
use crate::html::item_type::ItemType;
|
||||
use crate::html::render::{self, cache, CURRENT_DEPTH};
|
||||
use crate::html::render::cache::ExternalLocation;
|
||||
use crate::html::render::CURRENT_DEPTH;
|
||||
|
||||
pub trait Print {
|
||||
fn print(self, buffer: &mut Buffer);
|
||||
@ -493,9 +495,9 @@ pub fn href(did: DefId) -> Option<(String, ItemType, Vec<String>)> {
|
||||
fqp,
|
||||
shortty,
|
||||
match cache.extern_locations[&did.krate] {
|
||||
(.., render::Remote(ref s)) => s.to_string(),
|
||||
(.., render::Local) => "../".repeat(depth),
|
||||
(.., render::Unknown) => return None,
|
||||
(.., ExternalLocation::Remote(ref s)) => s.to_string(),
|
||||
(.., ExternalLocation::Local) => "../".repeat(depth),
|
||||
(.., ExternalLocation::Unknown) => return None,
|
||||
},
|
||||
)
|
||||
}
|
||||
@ -574,12 +576,12 @@ fn primitive_link(
|
||||
}
|
||||
Some(&def_id) => {
|
||||
let loc = match m.extern_locations[&def_id.krate] {
|
||||
(ref cname, _, render::Remote(ref s)) => Some((cname, s.to_string())),
|
||||
(ref cname, _, render::Local) => {
|
||||
(ref cname, _, ExternalLocation::Remote(ref s)) => Some((cname, s.to_string())),
|
||||
(ref cname, _, ExternalLocation::Local) => {
|
||||
let len = CURRENT_DEPTH.with(|s| s.get());
|
||||
Some((cname, "../".repeat(len)))
|
||||
}
|
||||
(.., render::Unknown) => None,
|
||||
(.., ExternalLocation::Unknown) => None,
|
||||
};
|
||||
if let Some((cname, root)) = loc {
|
||||
write!(
|
||||
|
9
src/librustdoc/html/mod.rs
Normal file
9
src/librustdoc/html/mod.rs
Normal file
@ -0,0 +1,9 @@
|
||||
crate mod escape;
|
||||
crate mod format;
|
||||
crate mod highlight;
|
||||
crate mod layout;
|
||||
pub mod markdown;
|
||||
pub mod render;
|
||||
crate mod sources;
|
||||
crate mod static_files;
|
||||
crate mod toc;
|
@ -1,18 +1,16 @@
|
||||
use crate::clean::{self, AttributesExt, GetDefId};
|
||||
use crate::fold::DocFolder;
|
||||
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
|
||||
use rustc_hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX};
|
||||
use rustc_middle::middle::privacy::AccessLevels;
|
||||
use rustc_span::source_map::FileName;
|
||||
use rustc_span::symbol::sym;
|
||||
use std::collections::BTreeMap;
|
||||
use std::mem;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::path::Path;
|
||||
|
||||
use rustc_data_structures::fx::FxHashMap;
|
||||
use rustc_span::symbol::sym;
|
||||
use serde::Serialize;
|
||||
|
||||
use super::{plain_summary_line, shorten, Impl, IndexItem, IndexItemFunctionType, ItemType};
|
||||
use super::{Generic, RenderInfo, RenderType, TypeWithKind};
|
||||
use crate::clean::types::GetDefId;
|
||||
use crate::clean::{self, AttributesExt};
|
||||
use crate::formats::cache::Cache;
|
||||
use crate::formats::item_type::ItemType;
|
||||
use crate::html::render::{plain_summary_line, shorten};
|
||||
use crate::html::render::{Generic, IndexItem, IndexItemFunctionType, RenderType, TypeWithKind};
|
||||
|
||||
/// Indicates where an external crate can be found.
|
||||
pub enum ExternalLocation {
|
||||
@ -24,483 +22,9 @@ pub enum ExternalLocation {
|
||||
Unknown,
|
||||
}
|
||||
|
||||
/// This cache is used to store information about the `clean::Crate` being
|
||||
/// rendered in order to provide more useful documentation. This contains
|
||||
/// information like all implementors of a trait, all traits a type implements,
|
||||
/// documentation for all known traits, etc.
|
||||
///
|
||||
/// This structure purposefully does not implement `Clone` because it's intended
|
||||
/// to be a fairly large and expensive structure to clone. Instead this adheres
|
||||
/// to `Send` so it may be stored in a `Arc` instance and shared among the various
|
||||
/// rendering threads.
|
||||
#[derive(Default)]
|
||||
crate struct Cache {
|
||||
/// Maps a type ID to all known implementations for that type. This is only
|
||||
/// recognized for intra-crate `ResolvedPath` types, and is used to print
|
||||
/// out extra documentation on the page of an enum/struct.
|
||||
///
|
||||
/// The values of the map are a list of implementations and documentation
|
||||
/// found on that implementation.
|
||||
pub impls: FxHashMap<DefId, Vec<Impl>>,
|
||||
|
||||
/// Maintains a mapping of local crate `DefId`s to the fully qualified name
|
||||
/// and "short type description" of that node. This is used when generating
|
||||
/// URLs when a type is being linked to. External paths are not located in
|
||||
/// this map because the `External` type itself has all the information
|
||||
/// necessary.
|
||||
pub paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
|
||||
|
||||
/// Similar to `paths`, but only holds external paths. This is only used for
|
||||
/// generating explicit hyperlinks to other crates.
|
||||
pub external_paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
|
||||
|
||||
/// Maps local `DefId`s of exported types to fully qualified paths.
|
||||
/// Unlike 'paths', this mapping ignores any renames that occur
|
||||
/// due to 'use' statements.
|
||||
///
|
||||
/// This map is used when writing out the special 'implementors'
|
||||
/// javascript file. By using the exact path that the type
|
||||
/// is declared with, we ensure that each path will be identical
|
||||
/// to the path used if the corresponding type is inlined. By
|
||||
/// doing this, we can detect duplicate impls on a trait page, and only display
|
||||
/// the impl for the inlined type.
|
||||
pub exact_paths: FxHashMap<DefId, Vec<String>>,
|
||||
|
||||
/// This map contains information about all known traits of this crate.
|
||||
/// Implementations of a crate should inherit the documentation of the
|
||||
/// parent trait if no extra documentation is specified, and default methods
|
||||
/// should show up in documentation about trait implementations.
|
||||
pub traits: FxHashMap<DefId, clean::Trait>,
|
||||
|
||||
/// When rendering traits, it's often useful to be able to list all
|
||||
/// implementors of the trait, and this mapping is exactly, that: a mapping
|
||||
/// of trait ids to the list of known implementors of the trait
|
||||
pub implementors: FxHashMap<DefId, Vec<Impl>>,
|
||||
|
||||
/// Cache of where external crate documentation can be found.
|
||||
pub extern_locations: FxHashMap<CrateNum, (String, PathBuf, ExternalLocation)>,
|
||||
|
||||
/// Cache of where documentation for primitives can be found.
|
||||
pub primitive_locations: FxHashMap<clean::PrimitiveType, DefId>,
|
||||
|
||||
// Note that external items for which `doc(hidden)` applies to are shown as
|
||||
// non-reachable while local items aren't. This is because we're reusing
|
||||
// the access levels from the privacy check pass.
|
||||
pub access_levels: AccessLevels<DefId>,
|
||||
|
||||
/// The version of the crate being documented, if given from the `--crate-version` flag.
|
||||
pub crate_version: Option<String>,
|
||||
|
||||
/// Whether to document private items.
|
||||
/// This is stored in `Cache` so it doesn't need to be passed through all rustdoc functions.
|
||||
pub document_private: bool,
|
||||
|
||||
// Private fields only used when initially crawling a crate to build a cache
|
||||
stack: Vec<String>,
|
||||
parent_stack: Vec<DefId>,
|
||||
parent_is_trait_impl: bool,
|
||||
search_index: Vec<IndexItem>,
|
||||
stripped_mod: bool,
|
||||
pub deref_trait_did: Option<DefId>,
|
||||
pub deref_mut_trait_did: Option<DefId>,
|
||||
pub owned_box_did: Option<DefId>,
|
||||
masked_crates: FxHashSet<CrateNum>,
|
||||
|
||||
// In rare case where a structure is defined in one module but implemented
|
||||
// in another, if the implementing module is parsed before defining module,
|
||||
// then the fully qualified name of the structure isn't presented in `paths`
|
||||
// yet when its implementation methods are being indexed. Caches such methods
|
||||
// and their parent id here and indexes them at the end of crate parsing.
|
||||
orphan_impl_items: Vec<(DefId, clean::Item)>,
|
||||
|
||||
// Similarly to `orphan_impl_items`, sometimes trait impls are picked up
|
||||
// even though the trait itself is not exported. This can happen if a trait
|
||||
// was defined in function/expression scope, since the impl will be picked
|
||||
// up by `collect-trait-impls` but the trait won't be scraped out in the HIR
|
||||
// crawl. In order to prevent crashes when looking for spotlight traits or
|
||||
// when gathering trait documentation on a type, hold impls here while
|
||||
// folding and add them to the cache later on if we find the trait.
|
||||
orphan_trait_impls: Vec<(DefId, FxHashSet<DefId>, Impl)>,
|
||||
|
||||
/// Aliases added through `#[doc(alias = "...")]`. Since a few items can have the same alias,
|
||||
/// we need the alias element to have an array of items.
|
||||
pub(super) aliases: BTreeMap<String, Vec<usize>>,
|
||||
}
|
||||
|
||||
impl Cache {
|
||||
pub fn from_krate(
|
||||
renderinfo: RenderInfo,
|
||||
document_private: bool,
|
||||
extern_html_root_urls: &BTreeMap<String, String>,
|
||||
dst: &Path,
|
||||
mut krate: clean::Crate,
|
||||
) -> (clean::Crate, String, Cache) {
|
||||
// Crawl the crate to build various caches used for the output
|
||||
let RenderInfo {
|
||||
inlined: _,
|
||||
external_paths,
|
||||
exact_paths,
|
||||
access_levels,
|
||||
deref_trait_did,
|
||||
deref_mut_trait_did,
|
||||
owned_box_did,
|
||||
..
|
||||
} = renderinfo;
|
||||
|
||||
let external_paths =
|
||||
external_paths.into_iter().map(|(k, (v, t))| (k, (v, ItemType::from(t)))).collect();
|
||||
|
||||
let mut cache = Cache {
|
||||
impls: Default::default(),
|
||||
external_paths,
|
||||
exact_paths,
|
||||
paths: Default::default(),
|
||||
implementors: Default::default(),
|
||||
stack: Vec::new(),
|
||||
parent_stack: Vec::new(),
|
||||
search_index: Vec::new(),
|
||||
parent_is_trait_impl: false,
|
||||
extern_locations: Default::default(),
|
||||
primitive_locations: Default::default(),
|
||||
stripped_mod: false,
|
||||
access_levels,
|
||||
crate_version: krate.version.take(),
|
||||
document_private,
|
||||
orphan_impl_items: Vec::new(),
|
||||
orphan_trait_impls: Vec::new(),
|
||||
traits: krate.external_traits.replace(Default::default()),
|
||||
deref_trait_did,
|
||||
deref_mut_trait_did,
|
||||
owned_box_did,
|
||||
masked_crates: mem::take(&mut krate.masked_crates),
|
||||
aliases: Default::default(),
|
||||
};
|
||||
|
||||
// Cache where all our extern crates are located
|
||||
for &(n, ref e) in &krate.externs {
|
||||
let src_root = match e.src {
|
||||
FileName::Real(ref p) => match p.local_path().parent() {
|
||||
Some(p) => p.to_path_buf(),
|
||||
None => PathBuf::new(),
|
||||
},
|
||||
_ => PathBuf::new(),
|
||||
};
|
||||
let extern_url = extern_html_root_urls.get(&e.name).map(|u| &**u);
|
||||
cache
|
||||
.extern_locations
|
||||
.insert(n, (e.name.clone(), src_root, extern_location(e, extern_url, &dst)));
|
||||
|
||||
let did = DefId { krate: n, index: CRATE_DEF_INDEX };
|
||||
cache.external_paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
|
||||
}
|
||||
|
||||
// Cache where all known primitives have their documentation located.
|
||||
//
|
||||
// Favor linking to as local extern as possible, so iterate all crates in
|
||||
// reverse topological order.
|
||||
for &(_, ref e) in krate.externs.iter().rev() {
|
||||
for &(def_id, prim, _) in &e.primitives {
|
||||
cache.primitive_locations.insert(prim, def_id);
|
||||
}
|
||||
}
|
||||
for &(def_id, prim, _) in &krate.primitives {
|
||||
cache.primitive_locations.insert(prim, def_id);
|
||||
}
|
||||
|
||||
cache.stack.push(krate.name.clone());
|
||||
krate = cache.fold_crate(krate);
|
||||
|
||||
for (trait_did, dids, impl_) in cache.orphan_trait_impls.drain(..) {
|
||||
if cache.traits.contains_key(&trait_did) {
|
||||
for did in dids {
|
||||
cache.impls.entry(did).or_insert(vec![]).push(impl_.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Build our search index
|
||||
let index = build_index(&krate, &mut cache);
|
||||
|
||||
(krate, index, cache)
|
||||
}
|
||||
}
|
||||
|
||||
impl DocFolder for Cache {
|
||||
fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
|
||||
if item.def_id.is_local() {
|
||||
debug!("folding {} \"{:?}\", id {:?}", item.type_(), item.name, item.def_id);
|
||||
}
|
||||
|
||||
// If this is a stripped module,
|
||||
// we don't want it or its children in the search index.
|
||||
let orig_stripped_mod = match item.inner {
|
||||
clean::StrippedItem(box clean::ModuleItem(..)) => {
|
||||
mem::replace(&mut self.stripped_mod, true)
|
||||
}
|
||||
_ => self.stripped_mod,
|
||||
};
|
||||
|
||||
// If the impl is from a masked crate or references something from a
|
||||
// masked crate then remove it completely.
|
||||
if let clean::ImplItem(ref i) = item.inner {
|
||||
if self.masked_crates.contains(&item.def_id.krate)
|
||||
|| i.trait_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate))
|
||||
|| i.for_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
}
|
||||
|
||||
// Propagate a trait method's documentation to all implementors of the
|
||||
// trait.
|
||||
if let clean::TraitItem(ref t) = item.inner {
|
||||
self.traits.entry(item.def_id).or_insert_with(|| t.clone());
|
||||
}
|
||||
|
||||
// Collect all the implementors of traits.
|
||||
if let clean::ImplItem(ref i) = item.inner {
|
||||
if let Some(did) = i.trait_.def_id() {
|
||||
if i.blanket_impl.is_none() {
|
||||
self.implementors
|
||||
.entry(did)
|
||||
.or_default()
|
||||
.push(Impl { impl_item: item.clone() });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Index this method for searching later on.
|
||||
if let Some(ref s) = item.name {
|
||||
let (parent, is_inherent_impl_item) = match item.inner {
|
||||
clean::StrippedItem(..) => ((None, None), false),
|
||||
clean::AssocConstItem(..) | clean::TypedefItem(_, true)
|
||||
if self.parent_is_trait_impl =>
|
||||
{
|
||||
// skip associated items in trait impls
|
||||
((None, None), false)
|
||||
}
|
||||
clean::AssocTypeItem(..)
|
||||
| clean::TyMethodItem(..)
|
||||
| clean::StructFieldItem(..)
|
||||
| clean::VariantItem(..) => (
|
||||
(
|
||||
Some(*self.parent_stack.last().expect("parent_stack is empty")),
|
||||
Some(&self.stack[..self.stack.len() - 1]),
|
||||
),
|
||||
false,
|
||||
),
|
||||
clean::MethodItem(..) | clean::AssocConstItem(..) => {
|
||||
if self.parent_stack.is_empty() {
|
||||
((None, None), false)
|
||||
} else {
|
||||
let last = self.parent_stack.last().expect("parent_stack is empty 2");
|
||||
let did = *last;
|
||||
let path = match self.paths.get(&did) {
|
||||
// The current stack not necessarily has correlation
|
||||
// for where the type was defined. On the other
|
||||
// hand, `paths` always has the right
|
||||
// information if present.
|
||||
Some(&(
|
||||
ref fqp,
|
||||
ItemType::Trait
|
||||
| ItemType::Struct
|
||||
| ItemType::Union
|
||||
| ItemType::Enum,
|
||||
)) => Some(&fqp[..fqp.len() - 1]),
|
||||
Some(..) => Some(&*self.stack),
|
||||
None => None,
|
||||
};
|
||||
((Some(*last), path), true)
|
||||
}
|
||||
}
|
||||
_ => ((None, Some(&*self.stack)), false),
|
||||
};
|
||||
|
||||
match parent {
|
||||
(parent, Some(path)) if is_inherent_impl_item || !self.stripped_mod => {
|
||||
debug_assert!(!item.is_stripped());
|
||||
|
||||
// A crate has a module at its root, containing all items,
|
||||
// which should not be indexed. The crate-item itself is
|
||||
// inserted later on when serializing the search-index.
|
||||
if item.def_id.index != CRATE_DEF_INDEX {
|
||||
self.search_index.push(IndexItem {
|
||||
ty: item.type_(),
|
||||
name: s.to_string(),
|
||||
path: path.join("::"),
|
||||
desc: shorten(plain_summary_line(item.doc_value())),
|
||||
parent,
|
||||
parent_idx: None,
|
||||
search_type: get_index_search_type(&item),
|
||||
});
|
||||
|
||||
for alias in item.attrs.get_doc_aliases() {
|
||||
self.aliases
|
||||
.entry(alias.to_lowercase())
|
||||
.or_insert(Vec::new())
|
||||
.push(self.search_index.len() - 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
(Some(parent), None) if is_inherent_impl_item => {
|
||||
// We have a parent, but we don't know where they're
|
||||
// defined yet. Wait for later to index this item.
|
||||
self.orphan_impl_items.push((parent, item.clone()));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
// Keep track of the fully qualified path for this item.
|
||||
let pushed = match item.name {
|
||||
Some(ref n) if !n.is_empty() => {
|
||||
self.stack.push(n.to_string());
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
|
||||
match item.inner {
|
||||
clean::StructItem(..)
|
||||
| clean::EnumItem(..)
|
||||
| clean::TypedefItem(..)
|
||||
| clean::TraitItem(..)
|
||||
| clean::FunctionItem(..)
|
||||
| clean::ModuleItem(..)
|
||||
| clean::ForeignFunctionItem(..)
|
||||
| clean::ForeignStaticItem(..)
|
||||
| clean::ConstantItem(..)
|
||||
| clean::StaticItem(..)
|
||||
| clean::UnionItem(..)
|
||||
| clean::ForeignTypeItem
|
||||
| clean::MacroItem(..)
|
||||
| clean::ProcMacroItem(..)
|
||||
| clean::VariantItem(..)
|
||||
if !self.stripped_mod =>
|
||||
{
|
||||
// Re-exported items mean that the same id can show up twice
|
||||
// in the rustdoc ast that we're looking at. We know,
|
||||
// however, that a re-exported item doesn't show up in the
|
||||
// `public_items` map, so we can skip inserting into the
|
||||
// paths map if there was already an entry present and we're
|
||||
// not a public item.
|
||||
if !self.paths.contains_key(&item.def_id)
|
||||
|| self.access_levels.is_public(item.def_id)
|
||||
{
|
||||
self.paths.insert(item.def_id, (self.stack.clone(), item.type_()));
|
||||
}
|
||||
}
|
||||
clean::PrimitiveItem(..) => {
|
||||
self.paths.insert(item.def_id, (self.stack.clone(), item.type_()));
|
||||
}
|
||||
|
||||
_ => {}
|
||||
}
|
||||
|
||||
// Maintain the parent stack
|
||||
let orig_parent_is_trait_impl = self.parent_is_trait_impl;
|
||||
let parent_pushed = match item.inner {
|
||||
clean::TraitItem(..)
|
||||
| clean::EnumItem(..)
|
||||
| clean::ForeignTypeItem
|
||||
| clean::StructItem(..)
|
||||
| clean::UnionItem(..)
|
||||
| clean::VariantItem(..) => {
|
||||
self.parent_stack.push(item.def_id);
|
||||
self.parent_is_trait_impl = false;
|
||||
true
|
||||
}
|
||||
clean::ImplItem(ref i) => {
|
||||
self.parent_is_trait_impl = i.trait_.is_some();
|
||||
match i.for_ {
|
||||
clean::ResolvedPath { did, .. } => {
|
||||
self.parent_stack.push(did);
|
||||
true
|
||||
}
|
||||
ref t => {
|
||||
let prim_did = t
|
||||
.primitive_type()
|
||||
.and_then(|t| self.primitive_locations.get(&t).cloned());
|
||||
match prim_did {
|
||||
Some(did) => {
|
||||
self.parent_stack.push(did);
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
|
||||
// Once we've recursively found all the generics, hoard off all the
|
||||
// implementations elsewhere.
|
||||
let ret = self.fold_item_recur(item).and_then(|item| {
|
||||
if let clean::Item { inner: clean::ImplItem(_), .. } = item {
|
||||
// Figure out the id of this impl. This may map to a
|
||||
// primitive rather than always to a struct/enum.
|
||||
// Note: matching twice to restrict the lifetime of the `i` borrow.
|
||||
let mut dids = FxHashSet::default();
|
||||
if let clean::Item { inner: clean::ImplItem(ref i), .. } = item {
|
||||
match i.for_ {
|
||||
clean::ResolvedPath { did, .. }
|
||||
| clean::BorrowedRef {
|
||||
type_: box clean::ResolvedPath { did, .. }, ..
|
||||
} => {
|
||||
dids.insert(did);
|
||||
}
|
||||
ref t => {
|
||||
let did = t
|
||||
.primitive_type()
|
||||
.and_then(|t| self.primitive_locations.get(&t).cloned());
|
||||
|
||||
if let Some(did) = did {
|
||||
dids.insert(did);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) {
|
||||
for bound in generics {
|
||||
if let Some(did) = bound.def_id() {
|
||||
dids.insert(did);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
unreachable!()
|
||||
};
|
||||
let impl_item = Impl { impl_item: item };
|
||||
if impl_item.trait_did().map_or(true, |d| self.traits.contains_key(&d)) {
|
||||
for did in dids {
|
||||
self.impls.entry(did).or_insert(vec![]).push(impl_item.clone());
|
||||
}
|
||||
} else {
|
||||
let trait_did = impl_item.trait_did().expect("no trait did");
|
||||
self.orphan_trait_impls.push((trait_did, dids, impl_item));
|
||||
}
|
||||
None
|
||||
} else {
|
||||
Some(item)
|
||||
}
|
||||
});
|
||||
|
||||
if pushed {
|
||||
self.stack.pop().expect("stack already empty");
|
||||
}
|
||||
if parent_pushed {
|
||||
self.parent_stack.pop().expect("parent stack already empty");
|
||||
}
|
||||
self.stripped_mod = orig_stripped_mod;
|
||||
self.parent_is_trait_impl = orig_parent_is_trait_impl;
|
||||
ret
|
||||
}
|
||||
}
|
||||
|
||||
/// Attempts to find where an external crate is located, given that we're
|
||||
/// rendering in to the specified source destination.
|
||||
fn extern_location(
|
||||
pub fn extern_location(
|
||||
e: &clean::ExternalCrate,
|
||||
extern_url: Option<&str>,
|
||||
dst: &Path,
|
||||
@ -538,7 +62,7 @@ fn extern_location(
|
||||
}
|
||||
|
||||
/// Builds the search index from the collected metadata
|
||||
fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
|
||||
pub fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
|
||||
let mut defid_to_pathid = FxHashMap::default();
|
||||
let mut crate_items = Vec::with_capacity(cache.search_index.len());
|
||||
let mut crate_paths = vec![];
|
||||
@ -640,7 +164,7 @@ fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {
|
||||
crate fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {
|
||||
let (all_types, ret_types) = match item.inner {
|
||||
clean::FunctionItem(ref f) => (&f.all_types, &f.ret_types),
|
||||
clean::MethodItem(ref m) => (&m.all_types, &m.ret_types),
|
||||
|
File diff suppressed because it is too large
Load Diff
@ -1,10 +1,11 @@
|
||||
use crate::clean;
|
||||
use crate::docfs::PathError;
|
||||
use crate::error::Error;
|
||||
use crate::fold::DocFolder;
|
||||
use crate::html::format::Buffer;
|
||||
use crate::html::highlight;
|
||||
use crate::html::layout;
|
||||
use crate::html::render::{Error, SharedContext, BASIC_KEYWORDS};
|
||||
use crate::html::render::{SharedContext, BASIC_KEYWORDS};
|
||||
use rustc_hir::def_id::LOCAL_CRATE;
|
||||
use rustc_span::source_map::FileName;
|
||||
use std::ffi::OsStr;
|
||||
|
@ -63,19 +63,11 @@ mod config;
|
||||
mod core;
|
||||
mod docfs;
|
||||
mod doctree;
|
||||
#[macro_use]
|
||||
mod error;
|
||||
mod fold;
|
||||
pub mod html {
|
||||
crate mod escape;
|
||||
crate mod format;
|
||||
crate mod highlight;
|
||||
crate mod item_type;
|
||||
crate mod layout;
|
||||
pub mod markdown;
|
||||
crate mod render;
|
||||
crate mod sources;
|
||||
crate mod static_files;
|
||||
crate mod toc;
|
||||
}
|
||||
crate mod formats;
|
||||
pub mod html;
|
||||
mod markdown;
|
||||
mod passes;
|
||||
mod test;
|
||||
@ -85,7 +77,7 @@ mod visit_lib;
|
||||
|
||||
struct Output {
|
||||
krate: clean::Crate,
|
||||
renderinfo: html::render::RenderInfo,
|
||||
renderinfo: config::RenderInfo,
|
||||
renderopts: config::RenderOptions,
|
||||
}
|
||||
|
||||
@ -510,12 +502,19 @@ fn main_options(options: config::Options) -> i32 {
|
||||
info!("going to format");
|
||||
let (error_format, edition, debugging_options) = diag_opts;
|
||||
let diag = core::new_handler(error_format, None, &debugging_options);
|
||||
match html::render::run(krate, renderopts, renderinfo, &diag, edition) {
|
||||
match formats::run_format::<html::render::Context>(
|
||||
krate, renderopts, renderinfo, &diag, edition,
|
||||
) {
|
||||
Ok(_) => rustc_driver::EXIT_SUCCESS,
|
||||
Err(e) => {
|
||||
diag.struct_err(&format!("couldn't generate documentation: {}", e.error))
|
||||
.note(&format!("failed to create or modify \"{}\"", e.file.display()))
|
||||
.emit();
|
||||
let mut msg =
|
||||
diag.struct_err(&format!("couldn't generate documentation: {}", e.error));
|
||||
let file = e.file.display().to_string();
|
||||
if file.is_empty() {
|
||||
msg.emit()
|
||||
} else {
|
||||
msg.note(&format!("failed to create or modify \"{}\"", file)).emit()
|
||||
}
|
||||
rustc_driver::EXIT_FAILURE
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user