Make all rustdoc functions and structs crate-private

This gives warnings about dead code.
This commit is contained in:
Joshua Nelson 2020-11-14 17:59:58 -05:00
parent 5fab31e5dd
commit d6c16e4253
51 changed files with 927 additions and 927 deletions

View File

@ -20,13 +20,13 @@ struct RegionDeps<'tcx> {
smaller: FxHashSet<RegionTarget<'tcx>>, smaller: FxHashSet<RegionTarget<'tcx>>,
} }
pub struct AutoTraitFinder<'a, 'tcx> { crate struct AutoTraitFinder<'a, 'tcx> {
pub cx: &'a core::DocContext<'tcx>, crate cx: &'a core::DocContext<'tcx>,
pub f: auto_trait::AutoTraitFinder<'tcx>, crate f: auto_trait::AutoTraitFinder<'tcx>,
} }
impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx> { impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx> {
pub fn new(cx: &'a core::DocContext<'tcx>) -> Self { crate fn new(cx: &'a core::DocContext<'tcx>) -> Self {
let f = auto_trait::AutoTraitFinder::new(cx.tcx); let f = auto_trait::AutoTraitFinder::new(cx.tcx);
AutoTraitFinder { cx, f } AutoTraitFinder { cx, f }
@ -34,7 +34,7 @@ impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx> {
// FIXME(eddyb) figure out a better way to pass information about // FIXME(eddyb) figure out a better way to pass information about
// parametrization of `ty` than `param_env_def_id`. // parametrization of `ty` than `param_env_def_id`.
pub fn get_auto_trait_impls(&self, ty: Ty<'tcx>, param_env_def_id: DefId) -> Vec<Item> { crate fn get_auto_trait_impls(&self, ty: Ty<'tcx>, param_env_def_id: DefId) -> Vec<Item> {
let param_env = self.cx.tcx.param_env(param_env_def_id); let param_env = self.cx.tcx.param_env(param_env_def_id);
debug!("get_auto_trait_impls({:?})", ty); debug!("get_auto_trait_impls({:?})", ty);

View File

@ -9,18 +9,18 @@ use rustc_span::DUMMY_SP;
use super::*; use super::*;
pub struct BlanketImplFinder<'a, 'tcx> { crate struct BlanketImplFinder<'a, 'tcx> {
pub cx: &'a core::DocContext<'tcx>, crate cx: &'a core::DocContext<'tcx>,
} }
impl<'a, 'tcx> BlanketImplFinder<'a, 'tcx> { impl<'a, 'tcx> BlanketImplFinder<'a, 'tcx> {
pub fn new(cx: &'a core::DocContext<'tcx>) -> Self { crate fn new(cx: &'a core::DocContext<'tcx>) -> Self {
BlanketImplFinder { cx } BlanketImplFinder { cx }
} }
// FIXME(eddyb) figure out a better way to pass information about // FIXME(eddyb) figure out a better way to pass information about
// parametrization of `ty` than `param_env_def_id`. // parametrization of `ty` than `param_env_def_id`.
pub fn get_blanket_impls(&self, ty: Ty<'tcx>, param_env_def_id: DefId) -> Vec<Item> { crate fn get_blanket_impls(&self, ty: Ty<'tcx>, param_env_def_id: DefId) -> Vec<Item> {
let param_env = self.cx.tcx.param_env(param_env_def_id); let param_env = self.cx.tcx.param_env(param_env_def_id);
debug!("get_blanket_impls({:?})", ty); debug!("get_blanket_impls({:?})", ty);

View File

@ -20,7 +20,7 @@ use crate::html::escape::Escape;
mod tests; mod tests;
#[derive(Clone, Debug, PartialEq, Eq, Hash)] #[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Cfg { crate enum Cfg {
/// Accepts all configurations. /// Accepts all configurations.
True, True,
/// Denies all configurations. /// Denies all configurations.
@ -36,9 +36,9 @@ pub enum Cfg {
} }
#[derive(PartialEq, Debug)] #[derive(PartialEq, Debug)]
pub struct InvalidCfgError { crate struct InvalidCfgError {
pub msg: &'static str, crate msg: &'static str,
pub span: Span, crate span: Span,
} }
impl Cfg { impl Cfg {
@ -59,7 +59,7 @@ impl Cfg {
/// ///
/// If the content is not properly formatted, it will return an error indicating what and where /// If the content is not properly formatted, it will return an error indicating what and where
/// the error is. /// the error is.
pub fn parse(cfg: &MetaItem) -> Result<Cfg, InvalidCfgError> { crate fn parse(cfg: &MetaItem) -> Result<Cfg, InvalidCfgError> {
let name = match cfg.ident() { let name = match cfg.ident() {
Some(ident) => ident.name, Some(ident) => ident.name,
None => { None => {
@ -102,7 +102,7 @@ impl Cfg {
/// ///
/// Equivalent to `attr::cfg_matches`. /// Equivalent to `attr::cfg_matches`.
// FIXME: Actually make use of `features`. // FIXME: Actually make use of `features`.
pub fn matches(&self, parse_sess: &ParseSess, features: Option<&Features>) -> bool { crate fn matches(&self, parse_sess: &ParseSess, features: Option<&Features>) -> bool {
match *self { match *self {
Cfg::False => false, Cfg::False => false,
Cfg::True => true, Cfg::True => true,

View File

@ -3,11 +3,11 @@
mod auto_trait; mod auto_trait;
mod blanket_impl; mod blanket_impl;
pub mod cfg; crate mod cfg;
pub mod inline; crate mod inline;
mod simplify; mod simplify;
pub mod types; crate mod types;
pub mod utils; crate mod utils;
use rustc_ast as ast; use rustc_ast as ast;
use rustc_attr as attr; use rustc_attr as attr;
@ -39,18 +39,18 @@ use crate::doctree;
use utils::*; use utils::*;
pub use utils::{get_auto_trait_and_blanket_impls, krate, register_res}; crate use utils::{get_auto_trait_and_blanket_impls, krate, register_res};
pub use self::types::FnRetTy::*; crate use self::types::FnRetTy::*;
pub use self::types::ItemKind::*; crate use self::types::ItemKind::*;
pub use self::types::SelfTy::*; crate use self::types::SelfTy::*;
pub use self::types::Type::*; crate use self::types::Type::*;
pub use self::types::Visibility::{Inherited, Public}; crate use self::types::Visibility::{Inherited, Public};
pub use self::types::*; crate use self::types::*;
const FN_OUTPUT_NAME: &str = "Output"; const FN_OUTPUT_NAME: &str = "Output";
pub trait Clean<T> { crate trait Clean<T> {
fn clean(&self, cx: &DocContext<'_>) -> T; fn clean(&self, cx: &DocContext<'_>) -> T;
} }

View File

@ -21,7 +21,7 @@ use crate::clean::GenericArgs as PP;
use crate::clean::WherePredicate as WP; use crate::clean::WherePredicate as WP;
use crate::core::DocContext; use crate::core::DocContext;
pub fn where_clauses(cx: &DocContext<'_>, clauses: Vec<WP>) -> Vec<WP> { crate fn where_clauses(cx: &DocContext<'_>, clauses: Vec<WP>) -> Vec<WP> {
// First, partition the where clause into its separate components // First, partition the where clause into its separate components
let mut params: BTreeMap<_, Vec<_>> = BTreeMap::new(); let mut params: BTreeMap<_, Vec<_>> = BTreeMap::new();
let mut lifetimes = Vec::new(); let mut lifetimes = Vec::new();
@ -74,7 +74,7 @@ pub fn where_clauses(cx: &DocContext<'_>, clauses: Vec<WP>) -> Vec<WP> {
clauses clauses
} }
pub fn merge_bounds( crate fn merge_bounds(
cx: &clean::DocContext<'_>, cx: &clean::DocContext<'_>,
bounds: &mut Vec<clean::GenericBound>, bounds: &mut Vec<clean::GenericBound>,
trait_did: DefId, trait_did: DefId,

File diff suppressed because it is too large Load Diff

View File

@ -20,7 +20,7 @@ use rustc_middle::ty::{self, DefIdTree, Ty};
use rustc_span::symbol::{kw, sym, Symbol}; use rustc_span::symbol::{kw, sym, Symbol};
use std::mem; use std::mem;
pub fn krate(mut cx: &mut DocContext<'_>) -> Crate { crate fn krate(mut cx: &mut DocContext<'_>) -> Crate {
use crate::visit_lib::LibEmbargoVisitor; use crate::visit_lib::LibEmbargoVisitor;
let krate = cx.tcx.hir().krate(); let krate = cx.tcx.hir().krate();
@ -102,11 +102,11 @@ pub fn krate(mut cx: &mut DocContext<'_>) -> Crate {
} }
// extract the stability index for a node from tcx, if possible // extract the stability index for a node from tcx, if possible
pub fn get_stability(cx: &DocContext<'_>, def_id: DefId) -> Option<Stability> { crate fn get_stability(cx: &DocContext<'_>, def_id: DefId) -> Option<Stability> {
cx.tcx.lookup_stability(def_id).cloned() cx.tcx.lookup_stability(def_id).cloned()
} }
pub fn get_deprecation(cx: &DocContext<'_>, def_id: DefId) -> Option<Deprecation> { crate fn get_deprecation(cx: &DocContext<'_>, def_id: DefId) -> Option<Deprecation> {
cx.tcx.lookup_deprecation(def_id).clean(cx) cx.tcx.lookup_deprecation(def_id).clean(cx)
} }
@ -183,7 +183,7 @@ pub(super) fn external_path(
/// i.e. `[T, U]` when you have the following bounds: `T: Display, U: Option<T>` will return /// i.e. `[T, U]` when you have the following bounds: `T: Display, U: Option<T>` will return
/// `[Display, Option]` (we just returns the list of the types, we don't care about the /// `[Display, Option]` (we just returns the list of the types, we don't care about the
/// wrapped types in here). /// wrapped types in here).
pub fn get_real_types( crate fn get_real_types(
generics: &Generics, generics: &Generics,
arg: &Type, arg: &Type,
cx: &DocContext<'_>, cx: &DocContext<'_>,
@ -261,7 +261,7 @@ pub fn get_real_types(
/// ///
/// i.e. `fn foo<A: Display, B: Option<A>>(x: u32, y: B)` will return /// i.e. `fn foo<A: Display, B: Option<A>>(x: u32, y: B)` will return
/// `[u32, Display, Option]`. /// `[u32, Display, Option]`.
pub fn get_all_types( crate fn get_all_types(
generics: &Generics, generics: &Generics,
decl: &FnDecl, decl: &FnDecl,
cx: &DocContext<'_>, cx: &DocContext<'_>,
@ -296,7 +296,7 @@ pub fn get_all_types(
(all_types.into_iter().collect(), ret_types) (all_types.into_iter().collect(), ret_types)
} }
pub fn strip_type(ty: Type) -> Type { crate fn strip_type(ty: Type) -> Type {
match ty { match ty {
Type::ResolvedPath { path, param_names, did, is_generic } => { Type::ResolvedPath { path, param_names, did, is_generic } => {
Type::ResolvedPath { path: strip_path(&path), param_names, did, is_generic } Type::ResolvedPath { path: strip_path(&path), param_names, did, is_generic }
@ -319,7 +319,7 @@ pub fn strip_type(ty: Type) -> Type {
} }
} }
pub fn strip_path(path: &Path) -> Path { crate fn strip_path(path: &Path) -> Path {
let segments = path let segments = path
.segments .segments
.iter() .iter()
@ -332,7 +332,7 @@ pub fn strip_path(path: &Path) -> Path {
Path { global: path.global, res: path.res, segments } Path { global: path.global, res: path.res, segments }
} }
pub fn qpath_to_string(p: &hir::QPath<'_>) -> String { crate fn qpath_to_string(p: &hir::QPath<'_>) -> String {
let segments = match *p { let segments = match *p {
hir::QPath::Resolved(_, ref path) => &path.segments, hir::QPath::Resolved(_, ref path) => &path.segments,
hir::QPath::TypeRelative(_, ref segment) => return segment.ident.to_string(), hir::QPath::TypeRelative(_, ref segment) => return segment.ident.to_string(),
@ -351,7 +351,7 @@ pub fn qpath_to_string(p: &hir::QPath<'_>) -> String {
s s
} }
pub fn build_deref_target_impls(cx: &DocContext<'_>, items: &[Item], ret: &mut Vec<Item>) { crate fn build_deref_target_impls(cx: &DocContext<'_>, items: &[Item], ret: &mut Vec<Item>) {
let tcx = cx.tcx; let tcx = cx.tcx;
for item in items { for item in items {
@ -378,7 +378,7 @@ pub fn build_deref_target_impls(cx: &DocContext<'_>, items: &[Item], ret: &mut V
} }
} }
pub trait ToSource { crate trait ToSource {
fn to_src(&self, cx: &DocContext<'_>) -> String; fn to_src(&self, cx: &DocContext<'_>) -> String;
} }
@ -394,7 +394,7 @@ impl ToSource for rustc_span::Span {
} }
} }
pub fn name_from_pat(p: &hir::Pat<'_>) -> String { crate fn name_from_pat(p: &hir::Pat<'_>) -> String {
use rustc_hir::*; use rustc_hir::*;
debug!("trying to get a name from pattern: {:?}", p); debug!("trying to get a name from pattern: {:?}", p);
@ -440,7 +440,7 @@ pub fn name_from_pat(p: &hir::Pat<'_>) -> String {
} }
} }
pub fn print_const(cx: &DocContext<'_>, n: &'tcx ty::Const<'_>) -> String { crate fn print_const(cx: &DocContext<'_>, n: &'tcx ty::Const<'_>) -> String {
match n.val { match n.val {
ty::ConstKind::Unevaluated(def, _, promoted) => { ty::ConstKind::Unevaluated(def, _, promoted) => {
let mut s = if let Some(def) = def.as_local() { let mut s = if let Some(def) = def.as_local() {
@ -470,7 +470,7 @@ pub fn print_const(cx: &DocContext<'_>, n: &'tcx ty::Const<'_>) -> String {
} }
} }
pub fn print_evaluated_const(cx: &DocContext<'_>, def_id: DefId) -> Option<String> { crate fn print_evaluated_const(cx: &DocContext<'_>, def_id: DefId) -> Option<String> {
cx.tcx.const_eval_poly(def_id).ok().and_then(|val| { cx.tcx.const_eval_poly(def_id).ok().and_then(|val| {
let ty = cx.tcx.type_of(def_id); let ty = cx.tcx.type_of(def_id);
match (val, ty.kind()) { match (val, ty.kind()) {
@ -518,7 +518,7 @@ fn print_const_with_custom_print_scalar(cx: &DocContext<'_>, ct: &'tcx ty::Const
} }
} }
pub fn is_literal_expr(cx: &DocContext<'_>, hir_id: hir::HirId) -> bool { crate fn is_literal_expr(cx: &DocContext<'_>, hir_id: hir::HirId) -> bool {
if let hir::Node::Expr(expr) = cx.tcx.hir().get(hir_id) { if let hir::Node::Expr(expr) = cx.tcx.hir().get(hir_id) {
if let hir::ExprKind::Lit(_) = &expr.kind { if let hir::ExprKind::Lit(_) = &expr.kind {
return true; return true;
@ -534,7 +534,7 @@ pub fn is_literal_expr(cx: &DocContext<'_>, hir_id: hir::HirId) -> bool {
false false
} }
pub fn print_const_expr(cx: &DocContext<'_>, body: hir::BodyId) -> String { crate fn print_const_expr(cx: &DocContext<'_>, body: hir::BodyId) -> String {
let value = &cx.tcx.hir().body(body).value; let value = &cx.tcx.hir().body(body).value;
let snippet = if !value.span.from_expansion() { let snippet = if !value.span.from_expansion() {
@ -547,7 +547,7 @@ pub fn print_const_expr(cx: &DocContext<'_>, body: hir::BodyId) -> String {
} }
/// Given a type Path, resolve it to a Type using the TyCtxt /// Given a type Path, resolve it to a Type using the TyCtxt
pub fn resolve_type(cx: &DocContext<'_>, path: Path, id: hir::HirId) -> Type { crate fn resolve_type(cx: &DocContext<'_>, path: Path, id: hir::HirId) -> Type {
debug!("resolve_type({:?},{:?})", path, id); debug!("resolve_type({:?},{:?})", path, id);
let is_generic = match path.res { let is_generic = match path.res {
@ -565,7 +565,7 @@ pub fn resolve_type(cx: &DocContext<'_>, path: Path, id: hir::HirId) -> Type {
ResolvedPath { path, param_names: None, did, is_generic } ResolvedPath { path, param_names: None, did, is_generic }
} }
pub fn get_auto_trait_and_blanket_impls( crate fn get_auto_trait_and_blanket_impls(
cx: &DocContext<'tcx>, cx: &DocContext<'tcx>,
ty: Ty<'tcx>, ty: Ty<'tcx>,
param_env_def_id: DefId, param_env_def_id: DefId,
@ -576,7 +576,7 @@ pub fn get_auto_trait_and_blanket_impls(
.chain(BlanketImplFinder::new(cx).get_blanket_impls(ty, param_env_def_id)) .chain(BlanketImplFinder::new(cx).get_blanket_impls(ty, param_env_def_id))
} }
pub fn register_res(cx: &DocContext<'_>, res: Res) -> DefId { crate fn register_res(cx: &DocContext<'_>, res: Res) -> DefId {
debug!("register_res({:?})", res); debug!("register_res({:?})", res);
let (did, kind) = match res { let (did, kind) = match res {
@ -616,14 +616,14 @@ pub fn register_res(cx: &DocContext<'_>, res: Res) -> DefId {
did did
} }
pub fn resolve_use_source(cx: &DocContext<'_>, path: Path) -> ImportSource { crate fn resolve_use_source(cx: &DocContext<'_>, path: Path) -> ImportSource {
ImportSource { ImportSource {
did: if path.res.opt_def_id().is_none() { None } else { Some(register_res(cx, path.res)) }, did: if path.res.opt_def_id().is_none() { None } else { Some(register_res(cx, path.res)) },
path, path,
} }
} }
pub fn enter_impl_trait<F, R>(cx: &DocContext<'_>, f: F) -> R crate fn enter_impl_trait<F, R>(cx: &DocContext<'_>, f: F) -> R
where where
F: FnOnce() -> R, F: FnOnce() -> R,
{ {

View File

@ -30,13 +30,13 @@ use crate::passes::{self, Condition, DefaultPassOption};
use crate::theme; use crate::theme;
#[derive(Clone, Copy, PartialEq, Eq, Debug)] #[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum OutputFormat { crate enum OutputFormat {
Json, Json,
Html, Html,
} }
impl OutputFormat { impl OutputFormat {
pub fn is_json(&self) -> bool { crate fn is_json(&self) -> bool {
match self { match self {
OutputFormat::Json => true, OutputFormat::Json => true,
_ => false, _ => false,
@ -58,96 +58,96 @@ impl TryFrom<&str> for OutputFormat {
/// Configuration options for rustdoc. /// Configuration options for rustdoc.
#[derive(Clone)] #[derive(Clone)]
pub struct Options { crate struct Options {
// Basic options / Options passed directly to rustc // Basic options / Options passed directly to rustc
/// The crate root or Markdown file to load. /// The crate root or Markdown file to load.
pub input: PathBuf, crate input: PathBuf,
/// The name of the crate being documented. /// The name of the crate being documented.
pub crate_name: Option<String>, crate crate_name: Option<String>,
/// Whether or not this is a proc-macro crate /// Whether or not this is a proc-macro crate
pub proc_macro_crate: bool, crate proc_macro_crate: bool,
/// How to format errors and warnings. /// How to format errors and warnings.
pub error_format: ErrorOutputType, crate error_format: ErrorOutputType,
/// Library search paths to hand to the compiler. /// Library search paths to hand to the compiler.
pub libs: Vec<SearchPath>, crate libs: Vec<SearchPath>,
/// Library search paths strings to hand to the compiler. /// Library search paths strings to hand to the compiler.
pub lib_strs: Vec<String>, crate lib_strs: Vec<String>,
/// The list of external crates to link against. /// The list of external crates to link against.
pub externs: Externs, crate externs: Externs,
/// The list of external crates strings to link against. /// The list of external crates strings to link against.
pub extern_strs: Vec<String>, crate extern_strs: Vec<String>,
/// List of `cfg` flags to hand to the compiler. Always includes `rustdoc`. /// List of `cfg` flags to hand to the compiler. Always includes `rustdoc`.
pub cfgs: Vec<String>, crate cfgs: Vec<String>,
/// Codegen options to hand to the compiler. /// Codegen options to hand to the compiler.
pub codegen_options: CodegenOptions, crate codegen_options: CodegenOptions,
/// Codegen options strings to hand to the compiler. /// Codegen options strings to hand to the compiler.
pub codegen_options_strs: Vec<String>, crate codegen_options_strs: Vec<String>,
/// Debugging (`-Z`) options to pass to the compiler. /// Debugging (`-Z`) options to pass to the compiler.
pub debugging_opts: DebuggingOptions, crate debugging_opts: DebuggingOptions,
/// Debugging (`-Z`) options strings to pass to the compiler. /// Debugging (`-Z`) options strings to pass to the compiler.
pub debugging_opts_strs: Vec<String>, crate debugging_opts_strs: Vec<String>,
/// The target used to compile the crate against. /// The target used to compile the crate against.
pub target: TargetTriple, crate target: TargetTriple,
/// Edition used when reading the crate. Defaults to "2015". Also used by default when /// Edition used when reading the crate. Defaults to "2015". Also used by default when
/// compiling doctests from the crate. /// compiling doctests from the crate.
pub edition: Edition, crate edition: Edition,
/// The path to the sysroot. Used during the compilation process. /// The path to the sysroot. Used during the compilation process.
pub maybe_sysroot: Option<PathBuf>, crate maybe_sysroot: Option<PathBuf>,
/// Lint information passed over the command-line. /// Lint information passed over the command-line.
pub lint_opts: Vec<(String, Level)>, crate lint_opts: Vec<(String, Level)>,
/// Whether to ask rustc to describe the lints it knows. Practically speaking, this will not be /// Whether to ask rustc to describe the lints it knows. Practically speaking, this will not be
/// used, since we abort if we have no input file, but it's included for completeness. /// used, since we abort if we have no input file, but it's included for completeness.
pub describe_lints: bool, crate describe_lints: bool,
/// What level to cap lints at. /// What level to cap lints at.
pub lint_cap: Option<Level>, crate lint_cap: Option<Level>,
// Options specific to running doctests // Options specific to running doctests
/// Whether we should run doctests instead of generating docs. /// Whether we should run doctests instead of generating docs.
pub should_test: bool, crate should_test: bool,
/// List of arguments to pass to the test harness, if running tests. /// List of arguments to pass to the test harness, if running tests.
pub test_args: Vec<String>, crate test_args: Vec<String>,
/// Optional path to persist the doctest executables to, defaults to a /// Optional path to persist the doctest executables to, defaults to a
/// temporary directory if not set. /// temporary directory if not set.
pub persist_doctests: Option<PathBuf>, crate persist_doctests: Option<PathBuf>,
/// Runtool to run doctests with /// Runtool to run doctests with
pub runtool: Option<String>, crate runtool: Option<String>,
/// Arguments to pass to the runtool /// Arguments to pass to the runtool
pub runtool_args: Vec<String>, crate runtool_args: Vec<String>,
/// Whether to allow ignoring doctests on a per-target basis /// Whether to allow ignoring doctests on a per-target basis
/// For example, using ignore-foo to ignore running the doctest on any target that /// For example, using ignore-foo to ignore running the doctest on any target that
/// contains "foo" as a substring /// contains "foo" as a substring
pub enable_per_target_ignores: bool, crate enable_per_target_ignores: bool,
/// The path to a rustc-like binary to build tests with. If not set, we /// The path to a rustc-like binary to build tests with. If not set, we
/// default to loading from $sysroot/bin/rustc. /// default to loading from $sysroot/bin/rustc.
pub test_builder: Option<PathBuf>, crate test_builder: Option<PathBuf>,
// Options that affect the documentation process // Options that affect the documentation process
/// The selected default set of passes to use. /// The selected default set of passes to use.
/// ///
/// Be aware: This option can come both from the CLI and from crate attributes! /// Be aware: This option can come both from the CLI and from crate attributes!
pub default_passes: DefaultPassOption, crate default_passes: DefaultPassOption,
/// Any passes manually selected by the user. /// Any passes manually selected by the user.
/// ///
/// Be aware: This option can come both from the CLI and from crate attributes! /// Be aware: This option can come both from the CLI and from crate attributes!
pub manual_passes: Vec<String>, crate manual_passes: Vec<String>,
/// Whether to display warnings during doc generation or while gathering doctests. By default, /// Whether to display warnings during doc generation or while gathering doctests. By default,
/// all non-rustdoc-specific lints are allowed when generating docs. /// all non-rustdoc-specific lints are allowed when generating docs.
pub display_warnings: bool, crate display_warnings: bool,
/// Whether to run the `calculate-doc-coverage` pass, which counts the number of public items /// Whether to run the `calculate-doc-coverage` pass, which counts the number of public items
/// with and without documentation. /// with and without documentation.
pub show_coverage: bool, crate show_coverage: bool,
// Options that alter generated documentation pages // Options that alter generated documentation pages
/// Crate version to note on the sidebar of generated docs. /// Crate version to note on the sidebar of generated docs.
pub crate_version: Option<String>, crate crate_version: Option<String>,
/// Collected options specific to outputting final pages. /// Collected options specific to outputting final pages.
pub render_options: RenderOptions, crate render_options: RenderOptions,
/// Output format rendering (used only for "show-coverage" option for the moment) /// Output format rendering (used only for "show-coverage" option for the moment)
pub output_format: Option<OutputFormat>, crate output_format: Option<OutputFormat>,
/// If this option is set to `true`, rustdoc will only run checks and not generate /// If this option is set to `true`, rustdoc will only run checks and not generate
/// documentation. /// documentation.
pub run_check: bool, crate run_check: bool,
} }
impl fmt::Debug for Options { impl fmt::Debug for Options {
@ -195,89 +195,89 @@ impl fmt::Debug for Options {
/// Configuration options for the HTML page-creation process. /// Configuration options for the HTML page-creation process.
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct RenderOptions { crate struct RenderOptions {
/// Output directory to generate docs into. Defaults to `doc`. /// Output directory to generate docs into. Defaults to `doc`.
pub output: PathBuf, crate output: PathBuf,
/// External files to insert into generated pages. /// External files to insert into generated pages.
pub external_html: ExternalHtml, crate external_html: ExternalHtml,
/// A pre-populated `IdMap` with the default headings and any headings added by Markdown files /// A pre-populated `IdMap` with the default headings and any headings added by Markdown files
/// processed by `external_html`. /// processed by `external_html`.
pub id_map: IdMap, crate id_map: IdMap,
/// If present, playground URL to use in the "Run" button added to code samples. /// If present, playground URL to use in the "Run" button added to code samples.
/// ///
/// Be aware: This option can come both from the CLI and from crate attributes! /// Be aware: This option can come both from the CLI and from crate attributes!
pub playground_url: Option<String>, crate playground_url: Option<String>,
/// Whether to sort modules alphabetically on a module page instead of using declaration order. /// Whether to sort modules alphabetically on a module page instead of using declaration order.
/// `true` by default. /// `true` by default.
// //
// FIXME(misdreavus): the flag name is `--sort-modules-by-appearance` but the meaning is // FIXME(misdreavus): the flag name is `--sort-modules-by-appearance` but the meaning is
// inverted once read. // inverted once read.
pub sort_modules_alphabetically: bool, crate sort_modules_alphabetically: bool,
/// List of themes to extend the docs with. Original argument name is included to assist in /// List of themes to extend the docs with. Original argument name is included to assist in
/// displaying errors if it fails a theme check. /// displaying errors if it fails a theme check.
pub themes: Vec<StylePath>, crate themes: Vec<StylePath>,
/// If present, CSS file that contains rules to add to the default CSS. /// If present, CSS file that contains rules to add to the default CSS.
pub extension_css: Option<PathBuf>, crate extension_css: Option<PathBuf>,
/// A map of crate names to the URL to use instead of querying the crate's `html_root_url`. /// A map of crate names to the URL to use instead of querying the crate's `html_root_url`.
pub extern_html_root_urls: BTreeMap<String, String>, crate extern_html_root_urls: BTreeMap<String, String>,
/// A map of the default settings (values are as for DOM storage API). Keys should lack the /// A map of the default settings (values are as for DOM storage API). Keys should lack the
/// `rustdoc-` prefix. /// `rustdoc-` prefix.
pub default_settings: HashMap<String, String>, crate default_settings: HashMap<String, String>,
/// If present, suffix added to CSS/JavaScript files when referencing them in generated pages. /// If present, suffix added to CSS/JavaScript files when referencing them in generated pages.
pub resource_suffix: String, crate resource_suffix: String,
/// Whether to run the static CSS/JavaScript through a minifier when outputting them. `true` by /// Whether to run the static CSS/JavaScript through a minifier when outputting them. `true` by
/// default. /// default.
// //
// FIXME(misdreavus): the flag name is `--disable-minification` but the meaning is inverted // FIXME(misdreavus): the flag name is `--disable-minification` but the meaning is inverted
// once read. // once read.
pub enable_minification: bool, crate enable_minification: bool,
/// Whether to create an index page in the root of the output directory. If this is true but /// Whether to create an index page in the root of the output directory. If this is true but
/// `enable_index_page` is None, generate a static listing of crates instead. /// `enable_index_page` is None, generate a static listing of crates instead.
pub enable_index_page: bool, crate enable_index_page: bool,
/// A file to use as the index page at the root of the output directory. Overrides /// A file to use as the index page at the root of the output directory. Overrides
/// `enable_index_page` to be true if set. /// `enable_index_page` to be true if set.
pub index_page: Option<PathBuf>, crate index_page: Option<PathBuf>,
/// An optional path to use as the location of static files. If not set, uses combinations of /// An optional path to use as the location of static files. If not set, uses combinations of
/// `../` to reach the documentation root. /// `../` to reach the documentation root.
pub static_root_path: Option<String>, crate static_root_path: Option<String>,
// Options specific to reading standalone Markdown files // Options specific to reading standalone Markdown files
/// Whether to generate a table of contents on the output file when reading a standalone /// Whether to generate a table of contents on the output file when reading a standalone
/// Markdown file. /// Markdown file.
pub markdown_no_toc: bool, crate markdown_no_toc: bool,
/// Additional CSS files to link in pages generated from standalone Markdown files. /// Additional CSS files to link in pages generated from standalone Markdown files.
pub markdown_css: Vec<String>, crate markdown_css: Vec<String>,
/// If present, playground URL to use in the "Run" button added to code samples generated from /// If present, playground URL to use in the "Run" button added to code samples generated from
/// standalone Markdown files. If not present, `playground_url` is used. /// standalone Markdown files. If not present, `playground_url` is used.
pub markdown_playground_url: Option<String>, crate markdown_playground_url: Option<String>,
/// If false, the `select` element to have search filtering by crates on rendered docs /// If false, the `select` element to have search filtering by crates on rendered docs
/// won't be generated. /// won't be generated.
pub generate_search_filter: bool, crate generate_search_filter: bool,
/// Document items that have lower than `pub` visibility. /// Document items that have lower than `pub` visibility.
pub document_private: bool, crate document_private: bool,
/// Document items that have `doc(hidden)`. /// Document items that have `doc(hidden)`.
pub document_hidden: bool, crate document_hidden: bool,
pub unstable_features: rustc_feature::UnstableFeatures, crate unstable_features: rustc_feature::UnstableFeatures,
} }
/// Temporary storage for data obtained during `RustdocVisitor::clean()`. /// Temporary storage for data obtained during `RustdocVisitor::clean()`.
/// Later on moved into `CACHE_KEY`. /// Later on moved into `CACHE_KEY`.
#[derive(Default, Clone)] #[derive(Default, Clone)]
pub struct RenderInfo { crate struct RenderInfo {
pub inlined: FxHashSet<DefId>, crate inlined: FxHashSet<DefId>,
pub external_paths: crate::core::ExternalPaths, crate external_paths: crate::core::ExternalPaths,
pub exact_paths: FxHashMap<DefId, Vec<String>>, crate exact_paths: FxHashMap<DefId, Vec<String>>,
pub access_levels: AccessLevels<DefId>, crate access_levels: AccessLevels<DefId>,
pub deref_trait_did: Option<DefId>, crate deref_trait_did: Option<DefId>,
pub deref_mut_trait_did: Option<DefId>, crate deref_mut_trait_did: Option<DefId>,
pub owned_box_did: Option<DefId>, crate owned_box_did: Option<DefId>,
pub output_format: Option<OutputFormat>, crate output_format: Option<OutputFormat>,
} }
impl Options { impl Options {
/// Parses the given command-line for options. If an error message or other early-return has /// Parses the given command-line for options. If an error message or other early-return has
/// been printed, returns `Err` with the exit code. /// been printed, returns `Err` with the exit code.
pub fn from_matches(matches: &getopts::Matches) -> Result<Options, i32> { crate fn from_matches(matches: &getopts::Matches) -> Result<Options, i32> {
// Check for unstable options. // Check for unstable options.
nightly_options::check_nightly_options(&matches, &opts()); nightly_options::check_nightly_options(&matches, &opts());
@ -656,7 +656,7 @@ impl Options {
} }
/// Returns `true` if the file given as `self.input` is a Markdown file. /// Returns `true` if the file given as `self.input` is a Markdown file.
pub fn markdown_input(&self) -> bool { crate fn markdown_input(&self) -> bool {
self.input.extension().map_or(false, |e| e == "md" || e == "markdown") self.input.extension().map_or(false, |e| e == "md" || e == "markdown")
} }
} }

View File

@ -36,52 +36,52 @@ use crate::config::{Options as RustdocOptions, RenderOptions};
use crate::config::{OutputFormat, RenderInfo}; use crate::config::{OutputFormat, RenderInfo};
use crate::passes::{self, Condition::*, ConditionalPass}; use crate::passes::{self, Condition::*, ConditionalPass};
pub use rustc_session::config::{CodegenOptions, DebuggingOptions, Input, Options}; crate use rustc_session::config::{CodegenOptions, DebuggingOptions, Input, Options};
pub use rustc_session::search_paths::SearchPath; crate use rustc_session::search_paths::SearchPath;
pub type ExternalPaths = FxHashMap<DefId, (Vec<String>, clean::TypeKind)>; crate type ExternalPaths = FxHashMap<DefId, (Vec<String>, clean::TypeKind)>;
pub struct DocContext<'tcx> { crate struct DocContext<'tcx> {
pub tcx: TyCtxt<'tcx>, crate tcx: TyCtxt<'tcx>,
pub resolver: Rc<RefCell<interface::BoxedResolver>>, crate resolver: Rc<RefCell<interface::BoxedResolver>>,
/// Later on moved into `CACHE_KEY` /// Later on moved into `CACHE_KEY`
pub renderinfo: RefCell<RenderInfo>, crate renderinfo: RefCell<RenderInfo>,
/// Later on moved through `clean::Crate` into `CACHE_KEY` /// Later on moved through `clean::Crate` into `CACHE_KEY`
pub external_traits: Rc<RefCell<FxHashMap<DefId, clean::Trait>>>, crate external_traits: Rc<RefCell<FxHashMap<DefId, clean::Trait>>>,
/// Used while populating `external_traits` to ensure we don't process the same trait twice at /// Used while populating `external_traits` to ensure we don't process the same trait twice at
/// the same time. /// the same time.
pub active_extern_traits: RefCell<FxHashSet<DefId>>, crate active_extern_traits: RefCell<FxHashSet<DefId>>,
// The current set of type and lifetime substitutions, // The current set of type and lifetime substitutions,
// for expanding type aliases at the HIR level: // for expanding type aliases at the HIR level:
/// Table `DefId` of type parameter -> substituted type /// Table `DefId` of type parameter -> substituted type
pub ty_substs: RefCell<FxHashMap<DefId, clean::Type>>, crate ty_substs: RefCell<FxHashMap<DefId, clean::Type>>,
/// Table `DefId` of lifetime parameter -> substituted lifetime /// Table `DefId` of lifetime parameter -> substituted lifetime
pub lt_substs: RefCell<FxHashMap<DefId, clean::Lifetime>>, crate lt_substs: RefCell<FxHashMap<DefId, clean::Lifetime>>,
/// Table `DefId` of const parameter -> substituted const /// Table `DefId` of const parameter -> substituted const
pub ct_substs: RefCell<FxHashMap<DefId, clean::Constant>>, crate ct_substs: RefCell<FxHashMap<DefId, clean::Constant>>,
/// Table synthetic type parameter for `impl Trait` in argument position -> bounds /// Table synthetic type parameter for `impl Trait` in argument position -> bounds
pub impl_trait_bounds: RefCell<FxHashMap<ImplTraitParam, Vec<clean::GenericBound>>>, crate impl_trait_bounds: RefCell<FxHashMap<ImplTraitParam, Vec<clean::GenericBound>>>,
pub fake_def_ids: RefCell<FxHashMap<CrateNum, DefId>>, crate fake_def_ids: RefCell<FxHashMap<CrateNum, DefId>>,
pub all_fake_def_ids: RefCell<FxHashSet<DefId>>, crate all_fake_def_ids: RefCell<FxHashSet<DefId>>,
/// Auto-trait or blanket impls processed so far, as `(self_ty, trait_def_id)`. /// Auto-trait or blanket impls processed so far, as `(self_ty, trait_def_id)`.
// FIXME(eddyb) make this a `ty::TraitRef<'tcx>` set. // FIXME(eddyb) make this a `ty::TraitRef<'tcx>` set.
pub generated_synthetics: RefCell<FxHashSet<(Ty<'tcx>, DefId)>>, crate generated_synthetics: RefCell<FxHashSet<(Ty<'tcx>, DefId)>>,
pub auto_traits: Vec<DefId>, crate auto_traits: Vec<DefId>,
/// The options given to rustdoc that could be relevant to a pass. /// The options given to rustdoc that could be relevant to a pass.
pub render_options: RenderOptions, crate render_options: RenderOptions,
/// The traits in scope for a given module. /// The traits in scope for a given module.
/// ///
/// See `collect_intra_doc_links::traits_implemented_by` for more details. /// See `collect_intra_doc_links::traits_implemented_by` for more details.
/// `map<module, set<trait>>` /// `map<module, set<trait>>`
pub module_trait_cache: RefCell<FxHashMap<DefId, FxHashSet<DefId>>>, crate module_trait_cache: RefCell<FxHashMap<DefId, FxHashSet<DefId>>>,
} }
impl<'tcx> DocContext<'tcx> { impl<'tcx> DocContext<'tcx> {
pub fn sess(&self) -> &Session { crate fn sess(&self) -> &Session {
&self.tcx.sess &self.tcx.sess
} }
pub fn enter_resolver<F, R>(&self, f: F) -> R crate fn enter_resolver<F, R>(&self, f: F) -> R
where where
F: FnOnce(&mut resolve::Resolver<'_>) -> R, F: FnOnce(&mut resolve::Resolver<'_>) -> R,
{ {
@ -90,7 +90,7 @@ impl<'tcx> DocContext<'tcx> {
/// Call the closure with the given parameters set as /// Call the closure with the given parameters set as
/// the substitutions for a type alias' RHS. /// the substitutions for a type alias' RHS.
pub fn enter_alias<F, R>( crate fn enter_alias<F, R>(
&self, &self,
ty_substs: FxHashMap<DefId, clean::Type>, ty_substs: FxHashMap<DefId, clean::Type>,
lt_substs: FxHashMap<DefId, clean::Lifetime>, lt_substs: FxHashMap<DefId, clean::Lifetime>,
@ -120,7 +120,7 @@ impl<'tcx> DocContext<'tcx> {
// Instead, we construct 'fake' def ids, which start immediately after the last DefId. // Instead, we construct 'fake' def ids, which start immediately after the last DefId.
// In the Debug impl for clean::Item, we explicitly check for fake // In the Debug impl for clean::Item, we explicitly check for fake
// def ids, as we'll end up with a panic if we use the DefId Debug impl for fake DefIds // def ids, as we'll end up with a panic if we use the DefId Debug impl for fake DefIds
pub fn next_def_id(&self, crate_num: CrateNum) -> DefId { crate fn next_def_id(&self, crate_num: CrateNum) -> DefId {
let start_def_id = { let start_def_id = {
let num_def_ids = if crate_num == LOCAL_CRATE { let num_def_ids = if crate_num == LOCAL_CRATE {
self.tcx.hir().definitions().def_path_table().num_def_ids() self.tcx.hir().definitions().def_path_table().num_def_ids()
@ -150,7 +150,7 @@ impl<'tcx> DocContext<'tcx> {
/// Like `hir().local_def_id_to_hir_id()`, but skips calling it on fake DefIds. /// Like `hir().local_def_id_to_hir_id()`, but skips calling it on fake DefIds.
/// (This avoids a slice-index-out-of-bounds panic.) /// (This avoids a slice-index-out-of-bounds panic.)
pub fn as_local_hir_id(&self, def_id: DefId) -> Option<HirId> { crate fn as_local_hir_id(&self, def_id: DefId) -> Option<HirId> {
if self.all_fake_def_ids.borrow().contains(&def_id) { if self.all_fake_def_ids.borrow().contains(&def_id) {
None None
} else { } else {
@ -158,7 +158,7 @@ impl<'tcx> DocContext<'tcx> {
} }
} }
pub fn stability(&self, id: HirId) -> Option<attr::Stability> { crate fn stability(&self, id: HirId) -> Option<attr::Stability> {
self.tcx self.tcx
.hir() .hir()
.opt_local_def_id(id) .opt_local_def_id(id)
@ -166,7 +166,7 @@ impl<'tcx> DocContext<'tcx> {
.cloned() .cloned()
} }
pub fn deprecation(&self, id: HirId) -> Option<attr::Deprecation> { crate fn deprecation(&self, id: HirId) -> Option<attr::Deprecation> {
self.tcx self.tcx
.hir() .hir()
.opt_local_def_id(id) .opt_local_def_id(id)
@ -178,7 +178,7 @@ impl<'tcx> DocContext<'tcx> {
/// ///
/// If the given `error_format` is `ErrorOutputType::Json` and no `SourceMap` is given, a new one /// If the given `error_format` is `ErrorOutputType::Json` and no `SourceMap` is given, a new one
/// will be created for the handler. /// will be created for the handler.
pub fn new_handler( crate fn new_handler(
error_format: ErrorOutputType, error_format: ErrorOutputType,
source_map: Option<Lrc<source_map::SourceMap>>, source_map: Option<Lrc<source_map::SourceMap>>,
debugging_opts: &DebuggingOptions, debugging_opts: &DebuggingOptions,
@ -280,7 +280,7 @@ where
(lint_opts, lint_caps) (lint_opts, lint_caps)
} }
pub fn run_core( crate fn run_core(
options: RustdocOptions, options: RustdocOptions,
) -> (clean::Crate, RenderInfo, RenderOptions, Lrc<Session>) { ) -> (clean::Crate, RenderInfo, RenderOptions, Lrc<Session>) {
// Parse, resolve, and typecheck the given crate. // Parse, resolve, and typecheck the given crate.
@ -725,7 +725,7 @@ impl<'tcx> Visitor<'tcx> for EmitIgnoredResolutionErrors<'tcx> {
/// `DefId` or parameter index (`ty::ParamTy.index`) of a synthetic type parameter /// `DefId` or parameter index (`ty::ParamTy.index`) of a synthetic type parameter
/// for `impl Trait` in argument position. /// for `impl Trait` in argument position.
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum ImplTraitParam { crate enum ImplTraitParam {
DefId(DefId), DefId(DefId),
ParamIndex(u32), ParamIndex(u32),
} }

View File

@ -24,38 +24,38 @@ macro_rules! try_err {
}; };
} }
pub trait PathError { crate trait PathError {
fn new<S, P: AsRef<Path>>(e: S, path: P) -> Self fn new<S, P: AsRef<Path>>(e: S, path: P) -> Self
where where
S: ToString + Sized; S: ToString + Sized;
} }
pub struct DocFS { crate struct DocFS {
sync_only: bool, sync_only: bool,
errors: Option<Sender<String>>, errors: Option<Sender<String>>,
} }
impl DocFS { impl DocFS {
pub fn new(errors: Sender<String>) -> DocFS { crate fn new(errors: Sender<String>) -> DocFS {
DocFS { sync_only: false, errors: Some(errors) } DocFS { sync_only: false, errors: Some(errors) }
} }
pub fn set_sync_only(&mut self, sync_only: bool) { crate fn set_sync_only(&mut self, sync_only: bool) {
self.sync_only = sync_only; self.sync_only = sync_only;
} }
pub fn close(&mut self) { crate fn close(&mut self) {
self.errors = None; self.errors = None;
} }
pub fn create_dir_all<P: AsRef<Path>>(&self, path: P) -> io::Result<()> { crate fn create_dir_all<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
// For now, dir creation isn't a huge time consideration, do it // For now, dir creation isn't a huge time consideration, do it
// synchronously, which avoids needing ordering between write() actions // synchronously, which avoids needing ordering between write() actions
// and directory creation. // and directory creation.
fs::create_dir_all(path) fs::create_dir_all(path)
} }
pub fn write<P, C, E>(&self, path: P, contents: C) -> Result<(), E> crate fn write<P, C, E>(&self, path: P, contents: C) -> Result<(), E>
where where
P: AsRef<Path>, P: AsRef<Path>,
C: AsRef<[u8]>, C: AsRef<[u8]>,

View File

@ -31,17 +31,17 @@ use crate::html::markdown::{self, ErrorCodes, Ignore, LangString};
use crate::passes::span_of_attrs; use crate::passes::span_of_attrs;
#[derive(Clone, Default)] #[derive(Clone, Default)]
pub struct TestOptions { crate struct TestOptions {
/// Whether to disable the default `extern crate my_crate;` when creating doctests. /// Whether to disable the default `extern crate my_crate;` when creating doctests.
pub no_crate_inject: bool, crate no_crate_inject: bool,
/// Whether to emit compilation warnings when compiling doctests. Setting this will suppress /// Whether to emit compilation warnings when compiling doctests. Setting this will suppress
/// the default `#![allow(unused)]`. /// the default `#![allow(unused)]`.
pub display_warnings: bool, crate display_warnings: bool,
/// Additional crate-level attributes to add to doctests. /// Additional crate-level attributes to add to doctests.
pub attrs: Vec<String>, crate attrs: Vec<String>,
} }
pub fn run(options: Options) -> Result<(), ErrorReported> { crate fn run(options: Options) -> Result<(), ErrorReported> {
let input = config::Input::File(options.input.clone()); let input = config::Input::File(options.input.clone());
let invalid_codeblock_attributes_name = rustc_lint::builtin::INVALID_CODEBLOCK_ATTRIBUTES.name; let invalid_codeblock_attributes_name = rustc_lint::builtin::INVALID_CODEBLOCK_ATTRIBUTES.name;
@ -363,7 +363,7 @@ fn run_test(
/// Transforms a test into code that can be compiled into a Rust binary, and returns the number of /// Transforms a test into code that can be compiled into a Rust binary, and returns the number of
/// lines before the test code begins. /// lines before the test code begins.
pub fn make_test( crate fn make_test(
s: &str, s: &str,
cratename: Option<&str>, cratename: Option<&str>,
dont_insert_main: bool, dont_insert_main: bool,
@ -605,7 +605,7 @@ fn partition_source(s: &str) -> (String, String, String) {
(before, after, crates) (before, after, crates)
} }
pub trait Tester { crate trait Tester {
fn add_test(&mut self, test: String, config: LangString, line: usize); fn add_test(&mut self, test: String, config: LangString, line: usize);
fn get_line(&self) -> usize { fn get_line(&self) -> usize {
0 0
@ -613,8 +613,8 @@ pub trait Tester {
fn register_header(&mut self, _name: &str, _level: u32) {} fn register_header(&mut self, _name: &str, _level: u32) {}
} }
pub struct Collector { crate struct Collector {
pub tests: Vec<testing::TestDescAndFn>, crate tests: Vec<testing::TestDescAndFn>,
// The name of the test displayed to the user, separated by `::`. // The name of the test displayed to the user, separated by `::`.
// //
@ -650,7 +650,7 @@ pub struct Collector {
} }
impl Collector { impl Collector {
pub fn new( crate fn new(
cratename: String, cratename: String,
options: Options, options: Options,
use_headers: bool, use_headers: bool,
@ -682,7 +682,7 @@ impl Collector {
format!("{} - {}(line {})", filename, item_path, line) format!("{} - {}(line {})", filename, item_path, line)
} }
pub fn set_position(&mut self, position: Span) { crate fn set_position(&mut self, position: Span) {
self.position = position; self.position = position;
} }

View File

@ -1,6 +1,6 @@
//! This module is used to store stuff from Rust's AST in a more convenient //! This module is used to store stuff from Rust's AST in a more convenient
//! manner (and with prettier names) before cleaning. //! manner (and with prettier names) before cleaning.
pub use self::StructType::*; crate use self::StructType::*;
use rustc_ast as ast; use rustc_ast as ast;
use rustc_span::hygiene::MacroKind; use rustc_span::hygiene::MacroKind;
@ -10,35 +10,35 @@ use rustc_hir as hir;
use rustc_hir::def_id::CrateNum; use rustc_hir::def_id::CrateNum;
use rustc_hir::HirId; use rustc_hir::HirId;
pub struct Module<'hir> { crate struct Module<'hir> {
pub name: Option<Symbol>, crate name: Option<Symbol>,
pub attrs: &'hir [ast::Attribute], crate attrs: &'hir [ast::Attribute],
pub where_outer: Span, crate where_outer: Span,
pub where_inner: Span, crate where_inner: Span,
pub extern_crates: Vec<ExternCrate<'hir>>, crate extern_crates: Vec<ExternCrate<'hir>>,
pub imports: Vec<Import<'hir>>, crate imports: Vec<Import<'hir>>,
pub structs: Vec<Struct<'hir>>, crate structs: Vec<Struct<'hir>>,
pub unions: Vec<Union<'hir>>, crate unions: Vec<Union<'hir>>,
pub enums: Vec<Enum<'hir>>, crate enums: Vec<Enum<'hir>>,
pub fns: Vec<Function<'hir>>, crate fns: Vec<Function<'hir>>,
pub mods: Vec<Module<'hir>>, crate mods: Vec<Module<'hir>>,
pub id: hir::HirId, crate id: hir::HirId,
pub typedefs: Vec<Typedef<'hir>>, crate typedefs: Vec<Typedef<'hir>>,
pub opaque_tys: Vec<OpaqueTy<'hir>>, crate opaque_tys: Vec<OpaqueTy<'hir>>,
pub statics: Vec<Static<'hir>>, crate statics: Vec<Static<'hir>>,
pub constants: Vec<Constant<'hir>>, crate constants: Vec<Constant<'hir>>,
pub traits: Vec<Trait<'hir>>, crate traits: Vec<Trait<'hir>>,
pub vis: &'hir hir::Visibility<'hir>, crate vis: &'hir hir::Visibility<'hir>,
pub impls: Vec<Impl<'hir>>, crate impls: Vec<Impl<'hir>>,
pub foreigns: Vec<ForeignItem<'hir>>, crate foreigns: Vec<ForeignItem<'hir>>,
pub macros: Vec<Macro<'hir>>, crate macros: Vec<Macro<'hir>>,
pub proc_macros: Vec<ProcMacro<'hir>>, crate proc_macros: Vec<ProcMacro<'hir>>,
pub trait_aliases: Vec<TraitAlias<'hir>>, crate trait_aliases: Vec<TraitAlias<'hir>>,
pub is_crate: bool, crate is_crate: bool,
} }
impl Module<'hir> { impl Module<'hir> {
pub fn new( crate fn new(
name: Option<Symbol>, name: Option<Symbol>,
attrs: &'hir [ast::Attribute], attrs: &'hir [ast::Attribute],
vis: &'hir hir::Visibility<'hir>, vis: &'hir hir::Visibility<'hir>,
@ -73,7 +73,7 @@ impl Module<'hir> {
} }
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
pub enum StructType { crate enum StructType {
/// A braced struct /// A braced struct
Plain, Plain,
/// A tuple struct /// A tuple struct
@ -82,190 +82,190 @@ pub enum StructType {
Unit, Unit,
} }
pub struct Struct<'hir> { crate struct Struct<'hir> {
pub vis: &'hir hir::Visibility<'hir>, crate vis: &'hir hir::Visibility<'hir>,
pub id: hir::HirId, crate id: hir::HirId,
pub struct_type: StructType, crate struct_type: StructType,
pub name: Symbol, crate name: Symbol,
pub generics: &'hir hir::Generics<'hir>, crate generics: &'hir hir::Generics<'hir>,
pub attrs: &'hir [ast::Attribute], crate attrs: &'hir [ast::Attribute],
pub fields: &'hir [hir::StructField<'hir>], crate fields: &'hir [hir::StructField<'hir>],
pub span: Span, crate span: Span,
} }
pub struct Union<'hir> { crate struct Union<'hir> {
pub vis: &'hir hir::Visibility<'hir>, crate vis: &'hir hir::Visibility<'hir>,
pub id: hir::HirId, crate id: hir::HirId,
pub struct_type: StructType, crate struct_type: StructType,
pub name: Symbol, crate name: Symbol,
pub generics: &'hir hir::Generics<'hir>, crate generics: &'hir hir::Generics<'hir>,
pub attrs: &'hir [ast::Attribute], crate attrs: &'hir [ast::Attribute],
pub fields: &'hir [hir::StructField<'hir>], crate fields: &'hir [hir::StructField<'hir>],
pub span: Span, crate span: Span,
} }
pub struct Enum<'hir> { crate struct Enum<'hir> {
pub vis: &'hir hir::Visibility<'hir>, crate vis: &'hir hir::Visibility<'hir>,
pub variants: Vec<Variant<'hir>>, crate variants: Vec<Variant<'hir>>,
pub generics: &'hir hir::Generics<'hir>, crate generics: &'hir hir::Generics<'hir>,
pub attrs: &'hir [ast::Attribute], crate attrs: &'hir [ast::Attribute],
pub id: hir::HirId, crate id: hir::HirId,
pub span: Span, crate span: Span,
pub name: Symbol, crate name: Symbol,
} }
pub struct Variant<'hir> { crate struct Variant<'hir> {
pub name: Symbol, crate name: Symbol,
pub id: hir::HirId, crate id: hir::HirId,
pub attrs: &'hir [ast::Attribute], crate attrs: &'hir [ast::Attribute],
pub def: &'hir hir::VariantData<'hir>, crate def: &'hir hir::VariantData<'hir>,
pub span: Span, crate span: Span,
} }
pub struct Function<'hir> { crate struct Function<'hir> {
pub decl: &'hir hir::FnDecl<'hir>, crate decl: &'hir hir::FnDecl<'hir>,
pub attrs: &'hir [ast::Attribute], crate attrs: &'hir [ast::Attribute],
pub id: hir::HirId, crate id: hir::HirId,
pub name: Symbol, crate name: Symbol,
pub vis: &'hir hir::Visibility<'hir>, crate vis: &'hir hir::Visibility<'hir>,
pub header: hir::FnHeader, crate header: hir::FnHeader,
pub span: Span, crate span: Span,
pub generics: &'hir hir::Generics<'hir>, crate generics: &'hir hir::Generics<'hir>,
pub body: hir::BodyId, crate body: hir::BodyId,
} }
pub struct Typedef<'hir> { crate struct Typedef<'hir> {
pub ty: &'hir hir::Ty<'hir>, crate ty: &'hir hir::Ty<'hir>,
pub gen: &'hir hir::Generics<'hir>, crate gen: &'hir hir::Generics<'hir>,
pub name: Symbol, crate name: Symbol,
pub id: hir::HirId, crate id: hir::HirId,
pub attrs: &'hir [ast::Attribute], crate attrs: &'hir [ast::Attribute],
pub span: Span, crate span: Span,
pub vis: &'hir hir::Visibility<'hir>, crate vis: &'hir hir::Visibility<'hir>,
} }
pub struct OpaqueTy<'hir> { crate struct OpaqueTy<'hir> {
pub opaque_ty: &'hir hir::OpaqueTy<'hir>, crate opaque_ty: &'hir hir::OpaqueTy<'hir>,
pub name: Symbol, crate name: Symbol,
pub id: hir::HirId, crate id: hir::HirId,
pub attrs: &'hir [ast::Attribute], crate attrs: &'hir [ast::Attribute],
pub span: Span, crate span: Span,
pub vis: &'hir hir::Visibility<'hir>, crate vis: &'hir hir::Visibility<'hir>,
} }
#[derive(Debug)] #[derive(Debug)]
pub struct Static<'hir> { crate struct Static<'hir> {
pub type_: &'hir hir::Ty<'hir>, crate type_: &'hir hir::Ty<'hir>,
pub mutability: hir::Mutability, crate mutability: hir::Mutability,
pub expr: hir::BodyId, crate expr: hir::BodyId,
pub name: Symbol, crate name: Symbol,
pub attrs: &'hir [ast::Attribute], crate attrs: &'hir [ast::Attribute],
pub vis: &'hir hir::Visibility<'hir>, crate vis: &'hir hir::Visibility<'hir>,
pub id: hir::HirId, crate id: hir::HirId,
pub span: Span, crate span: Span,
} }
pub struct Constant<'hir> { crate struct Constant<'hir> {
pub type_: &'hir hir::Ty<'hir>, crate type_: &'hir hir::Ty<'hir>,
pub expr: hir::BodyId, crate expr: hir::BodyId,
pub name: Symbol, crate name: Symbol,
pub attrs: &'hir [ast::Attribute], crate attrs: &'hir [ast::Attribute],
pub vis: &'hir hir::Visibility<'hir>, crate vis: &'hir hir::Visibility<'hir>,
pub id: hir::HirId, crate id: hir::HirId,
pub span: Span, crate span: Span,
} }
pub struct Trait<'hir> { crate struct Trait<'hir> {
pub is_auto: hir::IsAuto, crate is_auto: hir::IsAuto,
pub unsafety: hir::Unsafety, crate unsafety: hir::Unsafety,
pub name: Symbol, crate name: Symbol,
pub items: Vec<&'hir hir::TraitItem<'hir>>, crate items: Vec<&'hir hir::TraitItem<'hir>>,
pub generics: &'hir hir::Generics<'hir>, crate generics: &'hir hir::Generics<'hir>,
pub bounds: &'hir [hir::GenericBound<'hir>], crate bounds: &'hir [hir::GenericBound<'hir>],
pub attrs: &'hir [ast::Attribute], crate attrs: &'hir [ast::Attribute],
pub id: hir::HirId, crate id: hir::HirId,
pub span: Span, crate span: Span,
pub vis: &'hir hir::Visibility<'hir>, crate vis: &'hir hir::Visibility<'hir>,
} }
pub struct TraitAlias<'hir> { crate struct TraitAlias<'hir> {
pub name: Symbol, crate name: Symbol,
pub generics: &'hir hir::Generics<'hir>, crate generics: &'hir hir::Generics<'hir>,
pub bounds: &'hir [hir::GenericBound<'hir>], crate bounds: &'hir [hir::GenericBound<'hir>],
pub attrs: &'hir [ast::Attribute], crate attrs: &'hir [ast::Attribute],
pub id: hir::HirId, crate id: hir::HirId,
pub span: Span, crate span: Span,
pub vis: &'hir hir::Visibility<'hir>, crate vis: &'hir hir::Visibility<'hir>,
} }
#[derive(Debug)] #[derive(Debug)]
pub struct Impl<'hir> { crate struct Impl<'hir> {
pub unsafety: hir::Unsafety, crate unsafety: hir::Unsafety,
pub polarity: hir::ImplPolarity, crate polarity: hir::ImplPolarity,
pub defaultness: hir::Defaultness, crate defaultness: hir::Defaultness,
pub constness: hir::Constness, crate constness: hir::Constness,
pub generics: &'hir hir::Generics<'hir>, crate generics: &'hir hir::Generics<'hir>,
pub trait_: &'hir Option<hir::TraitRef<'hir>>, crate trait_: &'hir Option<hir::TraitRef<'hir>>,
pub for_: &'hir hir::Ty<'hir>, crate for_: &'hir hir::Ty<'hir>,
pub items: Vec<&'hir hir::ImplItem<'hir>>, crate items: Vec<&'hir hir::ImplItem<'hir>>,
pub attrs: &'hir [ast::Attribute], crate attrs: &'hir [ast::Attribute],
pub span: Span, crate span: Span,
pub vis: &'hir hir::Visibility<'hir>, crate vis: &'hir hir::Visibility<'hir>,
pub id: hir::HirId, crate id: hir::HirId,
} }
pub struct ForeignItem<'hir> { crate struct ForeignItem<'hir> {
pub vis: &'hir hir::Visibility<'hir>, crate vis: &'hir hir::Visibility<'hir>,
pub id: hir::HirId, crate id: hir::HirId,
pub name: Symbol, crate name: Symbol,
pub kind: &'hir hir::ForeignItemKind<'hir>, crate kind: &'hir hir::ForeignItemKind<'hir>,
pub attrs: &'hir [ast::Attribute], crate attrs: &'hir [ast::Attribute],
pub span: Span, crate span: Span,
} }
// For Macro we store the DefId instead of the NodeId, since we also create // For Macro we store the DefId instead of the NodeId, since we also create
// these imported macro_rules (which only have a DUMMY_NODE_ID). // these imported macro_rules (which only have a DUMMY_NODE_ID).
pub struct Macro<'hir> { crate struct Macro<'hir> {
pub name: Symbol, crate name: Symbol,
pub hid: hir::HirId, crate hid: hir::HirId,
pub def_id: hir::def_id::DefId, crate def_id: hir::def_id::DefId,
pub attrs: &'hir [ast::Attribute], crate attrs: &'hir [ast::Attribute],
pub span: Span, crate span: Span,
pub matchers: Vec<Span>, crate matchers: Vec<Span>,
pub imported_from: Option<Symbol>, crate imported_from: Option<Symbol>,
} }
pub struct ExternCrate<'hir> { crate struct ExternCrate<'hir> {
pub name: Symbol, crate name: Symbol,
pub hir_id: HirId, crate hir_id: HirId,
pub cnum: CrateNum, crate cnum: CrateNum,
pub path: Option<String>, crate path: Option<String>,
pub vis: &'hir hir::Visibility<'hir>, crate vis: &'hir hir::Visibility<'hir>,
pub attrs: &'hir [ast::Attribute], crate attrs: &'hir [ast::Attribute],
pub span: Span, crate span: Span,
} }
#[derive(Debug)] #[derive(Debug)]
pub struct Import<'hir> { crate struct Import<'hir> {
pub name: Symbol, crate name: Symbol,
pub id: hir::HirId, crate id: hir::HirId,
pub vis: &'hir hir::Visibility<'hir>, crate vis: &'hir hir::Visibility<'hir>,
pub attrs: &'hir [ast::Attribute], crate attrs: &'hir [ast::Attribute],
pub path: &'hir hir::Path<'hir>, crate path: &'hir hir::Path<'hir>,
pub glob: bool, crate glob: bool,
pub span: Span, crate span: Span,
} }
pub struct ProcMacro<'hir> { crate struct ProcMacro<'hir> {
pub name: Symbol, crate name: Symbol,
pub id: hir::HirId, crate id: hir::HirId,
pub kind: MacroKind, crate kind: MacroKind,
pub helpers: Vec<Symbol>, crate helpers: Vec<Symbol>,
pub attrs: &'hir [ast::Attribute], crate attrs: &'hir [ast::Attribute],
pub span: Span, crate span: Span,
} }
pub fn struct_type_from_def(vdata: &hir::VariantData<'_>) -> StructType { crate fn struct_type_from_def(vdata: &hir::VariantData<'_>) -> StructType {
match *vdata { match *vdata {
hir::VariantData::Struct(..) => Plain, hir::VariantData::Struct(..) => Plain,
hir::VariantData::Tuple(..) => Tuple, hir::VariantData::Tuple(..) => Tuple,

View File

@ -5,9 +5,9 @@ use std::path::{Path, PathBuf};
use crate::docfs::PathError; use crate::docfs::PathError;
#[derive(Debug)] #[derive(Debug)]
pub struct Error { crate struct Error {
pub file: PathBuf, crate file: PathBuf,
pub error: String, crate error: String,
} }
impl error::Error for Error {} impl error::Error for Error {}

View File

@ -5,20 +5,20 @@ use std::path::Path;
use std::str; use std::str;
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct ExternalHtml { crate struct ExternalHtml {
/// Content that will be included inline in the <head> section of a /// Content that will be included inline in the <head> section of a
/// rendered Markdown file or generated documentation /// rendered Markdown file or generated documentation
pub in_header: String, crate in_header: String,
/// Content that will be included inline between <body> and the content of /// Content that will be included inline between <body> and the content of
/// a rendered Markdown file or generated documentation /// a rendered Markdown file or generated documentation
pub before_content: String, crate before_content: String,
/// Content that will be included inline between the content and </body> of /// Content that will be included inline between the content and </body> of
/// a rendered Markdown file or generated documentation /// a rendered Markdown file or generated documentation
pub after_content: String, crate after_content: String,
} }
impl ExternalHtml { impl ExternalHtml {
pub fn load( crate fn load(
in_header: &[String], in_header: &[String],
before_content: &[String], before_content: &[String],
after_content: &[String], after_content: &[String],
@ -50,12 +50,12 @@ impl ExternalHtml {
} }
} }
pub enum LoadStringError { crate enum LoadStringError {
ReadFail, ReadFail,
BadUtf8, BadUtf8,
} }
pub fn load_string<P: AsRef<Path>>( crate fn load_string<P: AsRef<Path>>(
file_path: P, file_path: P,
diag: &rustc_errors::Handler, diag: &rustc_errors::Handler,
) -> Result<String, LoadStringError> { ) -> Result<String, LoadStringError> {

View File

@ -1,9 +1,9 @@
use crate::clean::*; use crate::clean::*;
pub struct StripItem(pub Item); crate struct StripItem(pub Item);
impl StripItem { impl StripItem {
pub fn strip(self) -> Option<Item> { crate fn strip(self) -> Option<Item> {
match self.0 { match self.0 {
Item { kind: StrippedItem(..), .. } => Some(self.0), Item { kind: StrippedItem(..), .. } => Some(self.0),
mut i => { mut i => {
@ -14,7 +14,7 @@ impl StripItem {
} }
} }
pub trait DocFolder: Sized { crate trait DocFolder: Sized {
fn fold_item(&mut self, item: Item) -> Option<Item> { fn fold_item(&mut self, item: Item) -> Option<Item> {
self.fold_item_recur(item) self.fold_item_recur(item)
} }

View File

@ -30,25 +30,25 @@ thread_local!(crate static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
/// to `Send` so it may be stored in a `Arc` instance and shared among the various /// to `Send` so it may be stored in a `Arc` instance and shared among the various
/// rendering threads. /// rendering threads.
#[derive(Default)] #[derive(Default)]
pub struct Cache { crate struct Cache {
/// Maps a type ID to all known implementations for that type. This is only /// 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 /// recognized for intra-crate `ResolvedPath` types, and is used to print
/// out extra documentation on the page of an enum/struct. /// out extra documentation on the page of an enum/struct.
/// ///
/// The values of the map are a list of implementations and documentation /// The values of the map are a list of implementations and documentation
/// found on that implementation. /// found on that implementation.
pub impls: FxHashMap<DefId, Vec<Impl>>, crate impls: FxHashMap<DefId, Vec<Impl>>,
/// Maintains a mapping of local crate `DefId`s to the fully qualified name /// 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 /// 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 /// 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 /// this map because the `External` type itself has all the information
/// necessary. /// necessary.
pub paths: FxHashMap<DefId, (Vec<String>, ItemType)>, crate paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
/// Similar to `paths`, but only holds external paths. This is only used for /// Similar to `paths`, but only holds external paths. This is only used for
/// generating explicit hyperlinks to other crates. /// generating explicit hyperlinks to other crates.
pub external_paths: FxHashMap<DefId, (Vec<String>, ItemType)>, crate external_paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
/// Maps local `DefId`s of exported types to fully qualified paths. /// Maps local `DefId`s of exported types to fully qualified paths.
/// Unlike 'paths', this mapping ignores any renames that occur /// Unlike 'paths', this mapping ignores any renames that occur
@ -60,36 +60,36 @@ pub struct Cache {
/// to the path used if the corresponding type is inlined. By /// 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 /// doing this, we can detect duplicate impls on a trait page, and only display
/// the impl for the inlined type. /// the impl for the inlined type.
pub exact_paths: FxHashMap<DefId, Vec<String>>, crate exact_paths: FxHashMap<DefId, Vec<String>>,
/// This map contains information about all known traits of this crate. /// This map contains information about all known traits of this crate.
/// Implementations of a crate should inherit the documentation of the /// Implementations of a crate should inherit the documentation of the
/// parent trait if no extra documentation is specified, and default methods /// parent trait if no extra documentation is specified, and default methods
/// should show up in documentation about trait implementations. /// should show up in documentation about trait implementations.
pub traits: FxHashMap<DefId, clean::Trait>, crate traits: FxHashMap<DefId, clean::Trait>,
/// When rendering traits, it's often useful to be able to list all /// 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 /// implementors of the trait, and this mapping is exactly, that: a mapping
/// of trait ids to the list of known implementors of the trait /// of trait ids to the list of known implementors of the trait
pub implementors: FxHashMap<DefId, Vec<Impl>>, crate implementors: FxHashMap<DefId, Vec<Impl>>,
/// Cache of where external crate documentation can be found. /// Cache of where external crate documentation can be found.
pub extern_locations: FxHashMap<CrateNum, (String, PathBuf, ExternalLocation)>, crate extern_locations: FxHashMap<CrateNum, (String, PathBuf, ExternalLocation)>,
/// Cache of where documentation for primitives can be found. /// Cache of where documentation for primitives can be found.
pub primitive_locations: FxHashMap<clean::PrimitiveType, DefId>, crate primitive_locations: FxHashMap<clean::PrimitiveType, DefId>,
// Note that external items for which `doc(hidden)` applies to are shown as // 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 // non-reachable while local items aren't. This is because we're reusing
// the access levels from the privacy check pass. // the access levels from the privacy check pass.
pub access_levels: AccessLevels<DefId>, crate access_levels: AccessLevels<DefId>,
/// The version of the crate being documented, if given from the `--crate-version` flag. /// The version of the crate being documented, if given from the `--crate-version` flag.
pub crate_version: Option<String>, crate crate_version: Option<String>,
/// Whether to document private items. /// Whether to document private items.
/// This is stored in `Cache` so it doesn't need to be passed through all rustdoc functions. /// This is stored in `Cache` so it doesn't need to be passed through all rustdoc functions.
pub document_private: bool, crate document_private: bool,
// Private fields only used when initially crawling a crate to build a cache // Private fields only used when initially crawling a crate to build a cache
stack: Vec<String>, stack: Vec<String>,
@ -98,17 +98,17 @@ pub struct Cache {
stripped_mod: bool, stripped_mod: bool,
masked_crates: FxHashSet<CrateNum>, masked_crates: FxHashSet<CrateNum>,
pub search_index: Vec<IndexItem>, crate search_index: Vec<IndexItem>,
pub deref_trait_did: Option<DefId>, crate deref_trait_did: Option<DefId>,
pub deref_mut_trait_did: Option<DefId>, crate deref_mut_trait_did: Option<DefId>,
pub owned_box_did: Option<DefId>, crate owned_box_did: Option<DefId>,
// In rare case where a structure is defined in one module but implemented // In rare case where a structure is defined in one module but implemented
// in another, if the implementing module is parsed before defining module, // in another, if the implementing module is parsed before defining module,
// then the fully qualified name of the structure isn't presented in `paths` // then the fully qualified name of the structure isn't presented in `paths`
// yet when its implementation methods are being indexed. Caches such methods // 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. // and their parent id here and indexes them at the end of crate parsing.
pub orphan_impl_items: Vec<(DefId, clean::Item)>, crate orphan_impl_items: Vec<(DefId, clean::Item)>,
// Similarly to `orphan_impl_items`, sometimes trait impls are picked up // 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 // even though the trait itself is not exported. This can happen if a trait
@ -121,11 +121,11 @@ pub struct Cache {
/// Aliases added through `#[doc(alias = "...")]`. Since a few items can have the same alias, /// 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. /// we need the alias element to have an array of items.
pub aliases: BTreeMap<String, Vec<usize>>, crate aliases: BTreeMap<String, Vec<usize>>,
} }
impl Cache { impl Cache {
pub fn from_krate( crate fn from_krate(
render_info: RenderInfo, render_info: RenderInfo,
document_private: bool, document_private: bool,
extern_html_root_urls: &BTreeMap<String, String>, extern_html_root_urls: &BTreeMap<String, String>,

View File

@ -20,7 +20,7 @@ use crate::clean;
/// a heading, edit the listing in `html/render.rs`, function `sidebar_module`. This uses an /// a heading, edit the listing in `html/render.rs`, function `sidebar_module`. This uses an
/// ordering based on a helper function inside `item_module`, in the same file. /// ordering based on a helper function inside `item_module`, in the same file.
#[derive(Copy, PartialEq, Eq, Clone, Debug, PartialOrd, Ord)] #[derive(Copy, PartialEq, Eq, Clone, Debug, PartialOrd, Ord)]
pub enum ItemType { crate enum ItemType {
Module = 0, Module = 0,
ExternCrate = 1, ExternCrate = 1,
Import = 2, Import = 2,
@ -124,7 +124,7 @@ impl From<clean::TypeKind> for ItemType {
} }
impl ItemType { impl ItemType {
pub fn as_str(&self) -> &'static str { crate fn as_str(&self) -> &'static str {
match *self { match *self {
ItemType::Module => "mod", ItemType::Module => "mod",
ItemType::ExternCrate => "externcrate", ItemType::ExternCrate => "externcrate",

View File

@ -1,8 +1,8 @@
pub mod cache; crate mod cache;
pub mod item_type; crate mod item_type;
pub mod renderer; crate mod renderer;
pub use renderer::{run_format, FormatRenderer}; crate use renderer::{run_format, FormatRenderer};
use rustc_span::def_id::DefId; use rustc_span::def_id::DefId;
@ -11,7 +11,7 @@ use crate::clean::types::GetDefId;
/// Specifies whether rendering directly implemented trait items or ones from a certain Deref /// Specifies whether rendering directly implemented trait items or ones from a certain Deref
/// impl. /// impl.
pub enum AssocItemRender<'a> { crate enum AssocItemRender<'a> {
All, All,
DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }, DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool },
} }
@ -19,26 +19,26 @@ pub enum AssocItemRender<'a> {
/// For different handling of associated items from the Deref target of a type rather than the type /// For different handling of associated items from the Deref target of a type rather than the type
/// itself. /// itself.
#[derive(Copy, Clone, PartialEq)] #[derive(Copy, Clone, PartialEq)]
pub enum RenderMode { crate enum RenderMode {
Normal, Normal,
ForDeref { mut_: bool }, ForDeref { mut_: bool },
} }
/// Metadata about implementations for a type or trait. /// Metadata about implementations for a type or trait.
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct Impl { crate struct Impl {
pub impl_item: clean::Item, crate impl_item: clean::Item,
} }
impl Impl { impl Impl {
pub fn inner_impl(&self) -> &clean::Impl { crate fn inner_impl(&self) -> &clean::Impl {
match self.impl_item.kind { match self.impl_item.kind {
clean::ImplItem(ref impl_) => impl_, clean::ImplItem(ref impl_) => impl_,
_ => panic!("non-impl item found in impl"), _ => panic!("non-impl item found in impl"),
} }
} }
pub fn trait_did(&self) -> Option<DefId> { crate fn trait_did(&self) -> Option<DefId> {
self.inner_impl().trait_.def_id() self.inner_impl().trait_.def_id()
} }
} }

View File

@ -10,7 +10,7 @@ use crate::formats::cache::{Cache, CACHE_KEY};
/// Allows for different backends to rustdoc to be used with the `run_format()` function. Each /// 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 /// backend renderer has hooks for initialization, documenting an item, entering and exiting a
/// module, and cleanup/finalizing output. /// module, and cleanup/finalizing output.
pub trait FormatRenderer: Clone { crate trait FormatRenderer: Clone {
/// Sets up any state required for the renderer. When this is called the cache has already been /// Sets up any state required for the renderer. When this is called the cache has already been
/// populated. /// populated.
fn init( fn init(
@ -43,7 +43,7 @@ pub trait FormatRenderer: Clone {
} }
/// Main method for rendering a crate. /// Main method for rendering a crate.
pub fn run_format<T: FormatRenderer>( crate fn run_format<T: FormatRenderer>(
krate: clean::Crate, krate: clean::Crate,
options: RenderOptions, options: RenderOptions,
render_info: RenderInfo, render_info: RenderInfo,

View File

@ -7,7 +7,7 @@ use std::fmt;
/// Wrapper struct which will emit the HTML-escaped version of the contained /// Wrapper struct which will emit the HTML-escaped version of the contained
/// string when passed to a format string. /// string when passed to a format string.
pub struct Escape<'a>(pub &'a str); crate struct Escape<'a>(pub &'a str);
impl<'a> fmt::Display for Escape<'a> { impl<'a> fmt::Display for Escape<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {

View File

@ -21,7 +21,7 @@ use crate::html::escape::Escape;
use crate::html::render::cache::ExternalLocation; use crate::html::render::cache::ExternalLocation;
use crate::html::render::CURRENT_DEPTH; use crate::html::render::CURRENT_DEPTH;
pub trait Print { crate trait Print {
fn print(self, buffer: &mut Buffer); fn print(self, buffer: &mut Buffer);
} }
@ -47,7 +47,7 @@ impl Print for &'_ str {
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Buffer { crate struct Buffer {
for_html: bool, for_html: bool,
buffer: String, buffer: String,
} }
@ -115,28 +115,28 @@ impl Buffer {
} }
/// Wrapper struct for properly emitting a function or method declaration. /// Wrapper struct for properly emitting a function or method declaration.
pub struct Function<'a> { crate struct Function<'a> {
/// The declaration to emit. /// The declaration to emit.
pub decl: &'a clean::FnDecl, crate decl: &'a clean::FnDecl,
/// The length of the function header and name. In other words, the number of characters in the /// The length of the function header and name. In other words, the number of characters in the
/// function declaration up to but not including the parentheses. /// function declaration up to but not including the parentheses.
/// ///
/// Used to determine line-wrapping. /// Used to determine line-wrapping.
pub header_len: usize, crate header_len: usize,
/// The number of spaces to indent each successive line with, if line-wrapping is necessary. /// The number of spaces to indent each successive line with, if line-wrapping is necessary.
pub indent: usize, crate indent: usize,
/// Whether the function is async or not. /// Whether the function is async or not.
pub asyncness: hir::IsAsync, crate asyncness: hir::IsAsync,
} }
/// Wrapper struct for emitting a where-clause from Generics. /// Wrapper struct for emitting a where-clause from Generics.
pub struct WhereClause<'a> { crate struct WhereClause<'a> {
/// The Generics from which to emit a where-clause. /// The Generics from which to emit a where-clause.
pub gens: &'a clean::Generics, crate gens: &'a clean::Generics,
/// The number of spaces to indent each line with. /// The number of spaces to indent each line with.
pub indent: usize, crate indent: usize,
/// Whether the where-clause needs to add a comma and newline after the last bound. /// Whether the where-clause needs to add a comma and newline after the last bound.
pub end_newline: bool, crate end_newline: bool,
} }
fn comma_sep<T: fmt::Display>(items: impl Iterator<Item = T>) -> impl fmt::Display { fn comma_sep<T: fmt::Display>(items: impl Iterator<Item = T>) -> impl fmt::Display {
@ -480,7 +480,7 @@ impl clean::Path {
} }
} }
pub fn href(did: DefId) -> Option<(String, ItemType, Vec<String>)> { crate fn href(did: DefId) -> Option<(String, ItemType, Vec<String>)> {
let cache = cache(); let cache = cache();
if !did.is_local() && !cache.access_levels.is_public(did) && !cache.document_private { if !did.is_local() && !cache.access_levels.is_public(did) && !cache.document_private {
return None; return None;
@ -618,7 +618,7 @@ fn tybounds(param_names: &Option<Vec<clean::GenericBound>>) -> impl fmt::Display
}) })
} }
pub fn anchor(did: DefId, text: &str) -> impl fmt::Display + '_ { crate fn anchor(did: DefId, text: &str) -> impl fmt::Display + '_ {
display_fn(move |f| { display_fn(move |f| {
if let Some((url, short_ty, fqp)) = href(did) { if let Some((url, short_ty, fqp)) = href(did) {
write!( write!(
@ -910,7 +910,7 @@ impl clean::Impl {
} }
// The difference from above is that trait is not hyperlinked. // The difference from above is that trait is not hyperlinked.
pub fn fmt_impl_for_trait_page(i: &clean::Impl, f: &mut Buffer, use_absolute: bool) { crate fn fmt_impl_for_trait_page(i: &clean::Impl, f: &mut Buffer, use_absolute: bool) {
f.from_display(i.print_inner(false, use_absolute)) f.from_display(i.print_inner(false, use_absolute))
} }

View File

@ -15,7 +15,7 @@ use rustc_span::symbol::Ident;
use rustc_span::with_default_session_globals; use rustc_span::with_default_session_globals;
/// Highlights `src`, returning the HTML output. /// Highlights `src`, returning the HTML output.
pub fn render_with_highlighting( crate fn render_with_highlighting(
src: String, src: String,
class: Option<&str>, class: Option<&str>,
playground_button: Option<&str>, playground_button: Option<&str>,

View File

@ -7,33 +7,33 @@ use crate::html::format::{Buffer, Print};
use crate::html::render::{ensure_trailing_slash, StylePath}; use crate::html::render::{ensure_trailing_slash, StylePath};
#[derive(Clone)] #[derive(Clone)]
pub struct Layout { crate struct Layout {
pub logo: String, crate logo: String,
pub favicon: String, crate favicon: String,
pub external_html: ExternalHtml, crate external_html: ExternalHtml,
pub default_settings: HashMap<String, String>, crate default_settings: HashMap<String, String>,
pub krate: String, crate krate: String,
/// The given user css file which allow to customize the generated /// The given user css file which allow to customize the generated
/// documentation theme. /// documentation theme.
pub css_file_extension: Option<PathBuf>, crate css_file_extension: Option<PathBuf>,
/// If false, the `select` element to have search filtering by crates on rendered docs /// If false, the `select` element to have search filtering by crates on rendered docs
/// won't be generated. /// won't be generated.
pub generate_search_filter: bool, crate generate_search_filter: bool,
} }
pub struct Page<'a> { crate struct Page<'a> {
pub title: &'a str, crate title: &'a str,
pub css_class: &'a str, crate css_class: &'a str,
pub root_path: &'a str, crate root_path: &'a str,
pub static_root_path: Option<&'a str>, crate static_root_path: Option<&'a str>,
pub description: &'a str, crate description: &'a str,
pub keywords: &'a str, crate keywords: &'a str,
pub resource_suffix: &'a str, crate resource_suffix: &'a str,
pub extra_scripts: &'a [&'a str], crate extra_scripts: &'a [&'a str],
pub static_extra_scripts: &'a [&'a str], crate static_extra_scripts: &'a [&'a str],
} }
pub fn render<T: Print, S: Print>( crate fn render<T: Print, S: Print>(
layout: &Layout, layout: &Layout,
page: &Page<'_>, page: &Page<'_>,
sidebar: S, sidebar: S,
@ -228,7 +228,7 @@ pub fn render<T: Print, S: Print>(
) )
} }
pub fn redirect(url: &str) -> String { crate fn redirect(url: &str) -> String {
// <script> triggers a redirect before refresh, so this is fine. // <script> triggers a redirect before refresh, so this is fine.
format!( format!(
r##"<!DOCTYPE html> r##"<!DOCTYPE html>

View File

@ -49,52 +49,52 @@ pub(crate) fn opts() -> Options {
/// When `to_string` is called, this struct will emit the HTML corresponding to /// When `to_string` is called, this struct will emit the HTML corresponding to
/// the rendered version of the contained markdown string. /// the rendered version of the contained markdown string.
pub struct Markdown<'a>( crate struct Markdown<'a>(
pub &'a str, crate &'a str,
/// A list of link replacements. /// A list of link replacements.
pub &'a [RenderedLink], crate &'a [RenderedLink],
/// The current list of used header IDs. /// The current list of used header IDs.
pub &'a mut IdMap, crate &'a mut IdMap,
/// Whether to allow the use of explicit error codes in doctest lang strings. /// Whether to allow the use of explicit error codes in doctest lang strings.
pub ErrorCodes, crate ErrorCodes,
/// Default edition to use when parsing doctests (to add a `fn main`). /// Default edition to use when parsing doctests (to add a `fn main`).
pub Edition, crate Edition,
pub &'a Option<Playground>, crate &'a Option<Playground>,
); );
/// A tuple struct like `Markdown` that renders the markdown with a table of contents. /// A tuple struct like `Markdown` that renders the markdown with a table of contents.
pub struct MarkdownWithToc<'a>( crate struct MarkdownWithToc<'a>(
pub &'a str, crate &'a str,
pub &'a mut IdMap, crate &'a mut IdMap,
pub ErrorCodes, crate ErrorCodes,
pub Edition, crate Edition,
pub &'a Option<Playground>, crate &'a Option<Playground>,
); );
/// A tuple struct like `Markdown` that renders the markdown escaping HTML tags. /// A tuple struct like `Markdown` that renders the markdown escaping HTML tags.
pub struct MarkdownHtml<'a>( crate struct MarkdownHtml<'a>(
pub &'a str, crate &'a str,
pub &'a mut IdMap, crate &'a mut IdMap,
pub ErrorCodes, crate ErrorCodes,
pub Edition, crate Edition,
pub &'a Option<Playground>, crate &'a Option<Playground>,
); );
/// A tuple struct like `Markdown` that renders only the first paragraph. /// A tuple struct like `Markdown` that renders only the first paragraph.
pub struct MarkdownSummaryLine<'a>(pub &'a str, pub &'a [RenderedLink]); crate struct MarkdownSummaryLine<'a>(pub &'a str, pub &'a [RenderedLink]);
#[derive(Copy, Clone, PartialEq, Debug)] #[derive(Copy, Clone, PartialEq, Debug)]
pub enum ErrorCodes { crate enum ErrorCodes {
Yes, Yes,
No, No,
} }
impl ErrorCodes { impl ErrorCodes {
pub fn from(b: bool) -> Self { crate fn from(b: bool) -> Self {
match b { match b {
true => ErrorCodes::Yes, true => ErrorCodes::Yes,
false => ErrorCodes::No, false => ErrorCodes::No,
} }
} }
pub fn as_bool(self) -> bool { crate fn as_bool(self) -> bool {
match self { match self {
ErrorCodes::Yes => true, ErrorCodes::Yes => true,
ErrorCodes::No => false, ErrorCodes::No => false,
@ -160,9 +160,9 @@ fn slugify(c: char) -> Option<char> {
} }
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct Playground { crate struct Playground {
pub crate_name: Option<String>, crate crate_name: Option<String>,
pub url: String, crate url: String,
} }
/// Adds syntax highlighting and playground Run buttons to Rust code blocks. /// Adds syntax highlighting and playground Run buttons to Rust code blocks.
@ -643,7 +643,7 @@ impl<'a, I: Iterator<Item = Event<'a>>> Iterator for Footnotes<'a, I> {
} }
} }
pub fn find_testable_code<T: doctest::Tester>( crate fn find_testable_code<T: doctest::Tester>(
doc: &str, doc: &str,
tests: &mut T, tests: &mut T,
error_codes: ErrorCodes, error_codes: ErrorCodes,
@ -709,7 +709,7 @@ pub fn find_testable_code<T: doctest::Tester>(
} }
} }
pub struct ExtraInfo<'a, 'b> { crate struct ExtraInfo<'a, 'b> {
hir_id: Option<HirId>, hir_id: Option<HirId>,
item_did: Option<DefId>, item_did: Option<DefId>,
sp: Span, sp: Span,
@ -717,11 +717,11 @@ pub struct ExtraInfo<'a, 'b> {
} }
impl<'a, 'b> ExtraInfo<'a, 'b> { impl<'a, 'b> ExtraInfo<'a, 'b> {
pub fn new(tcx: &'a TyCtxt<'b>, hir_id: HirId, sp: Span) -> ExtraInfo<'a, 'b> { crate fn new(tcx: &'a TyCtxt<'b>, hir_id: HirId, sp: Span) -> ExtraInfo<'a, 'b> {
ExtraInfo { hir_id: Some(hir_id), item_did: None, sp, tcx } ExtraInfo { hir_id: Some(hir_id), item_did: None, sp, tcx }
} }
pub fn new_did(tcx: &'a TyCtxt<'b>, did: DefId, sp: Span) -> ExtraInfo<'a, 'b> { crate fn new_did(tcx: &'a TyCtxt<'b>, did: DefId, sp: Span) -> ExtraInfo<'a, 'b> {
ExtraInfo { hir_id: None, item_did: Some(did), sp, tcx } ExtraInfo { hir_id: None, item_did: Some(did), sp, tcx }
} }
@ -753,21 +753,21 @@ impl<'a, 'b> ExtraInfo<'a, 'b> {
} }
#[derive(Eq, PartialEq, Clone, Debug)] #[derive(Eq, PartialEq, Clone, Debug)]
pub struct LangString { crate struct LangString {
original: String, original: String,
pub should_panic: bool, crate should_panic: bool,
pub no_run: bool, crate no_run: bool,
pub ignore: Ignore, crate ignore: Ignore,
pub rust: bool, crate rust: bool,
pub test_harness: bool, crate test_harness: bool,
pub compile_fail: bool, crate compile_fail: bool,
pub error_codes: Vec<String>, crate error_codes: Vec<String>,
pub allow_fail: bool, crate allow_fail: bool,
pub edition: Option<Edition>, crate edition: Option<Edition>,
} }
#[derive(Eq, PartialEq, Clone, Debug)] #[derive(Eq, PartialEq, Clone, Debug)]
pub enum Ignore { crate enum Ignore {
All, All,
None, None,
Some(Vec<String>), Some(Vec<String>),
@ -923,7 +923,7 @@ impl LangString {
} }
impl Markdown<'_> { impl Markdown<'_> {
pub fn into_string(self) -> String { crate fn into_string(self) -> String {
let Markdown(md, links, mut ids, codes, edition, playground) = self; let Markdown(md, links, mut ids, codes, edition, playground) = self;
// This is actually common enough to special-case // This is actually common enough to special-case
@ -955,7 +955,7 @@ impl Markdown<'_> {
} }
impl MarkdownWithToc<'_> { impl MarkdownWithToc<'_> {
pub fn into_string(self) -> String { crate fn into_string(self) -> String {
let MarkdownWithToc(md, mut ids, codes, edition, playground) = self; let MarkdownWithToc(md, mut ids, codes, edition, playground) = self;
let p = Parser::new_ext(md, opts()); let p = Parser::new_ext(md, opts());
@ -976,7 +976,7 @@ impl MarkdownWithToc<'_> {
} }
impl MarkdownHtml<'_> { impl MarkdownHtml<'_> {
pub fn into_string(self) -> String { crate fn into_string(self) -> String {
let MarkdownHtml(md, mut ids, codes, edition, playground) = self; let MarkdownHtml(md, mut ids, codes, edition, playground) = self;
// This is actually common enough to special-case // This is actually common enough to special-case
@ -1003,7 +1003,7 @@ impl MarkdownHtml<'_> {
} }
impl MarkdownSummaryLine<'_> { impl MarkdownSummaryLine<'_> {
pub fn into_string(self) -> String { crate fn into_string(self) -> String {
let MarkdownSummaryLine(md, links) = self; let MarkdownSummaryLine(md, links) = self;
// This is actually common enough to special-case // This is actually common enough to special-case
if md.is_empty() { if md.is_empty() {
@ -1039,7 +1039,7 @@ impl MarkdownSummaryLine<'_> {
/// - Headings, links, and formatting are stripped. /// - Headings, links, and formatting are stripped.
/// - Inline code is rendered as-is, surrounded by backticks. /// - Inline code is rendered as-is, surrounded by backticks.
/// - HTML and code blocks are ignored. /// - HTML and code blocks are ignored.
pub fn plain_text_summary(md: &str) -> String { crate fn plain_text_summary(md: &str) -> String {
if md.is_empty() { if md.is_empty() {
return String::new(); return String::new();
} }
@ -1064,7 +1064,7 @@ pub fn plain_text_summary(md: &str) -> String {
s s
} }
pub fn markdown_links(md: &str) -> Vec<(String, Option<Range<usize>>)> { crate fn markdown_links(md: &str) -> Vec<(String, Option<Range<usize>>)> {
if md.is_empty() { if md.is_empty() {
return vec![]; return vec![];
} }
@ -1120,11 +1120,11 @@ pub fn markdown_links(md: &str) -> Vec<(String, Option<Range<usize>>)> {
crate struct RustCodeBlock { crate struct RustCodeBlock {
/// The range in the markdown that the code block occupies. Note that this includes the fences /// The range in the markdown that the code block occupies. Note that this includes the fences
/// for fenced code blocks. /// for fenced code blocks.
pub range: Range<usize>, crate range: Range<usize>,
/// The range in the markdown that the code within the code block occupies. /// The range in the markdown that the code within the code block occupies.
pub code: Range<usize>, crate code: Range<usize>,
pub is_fenced: bool, crate is_fenced: bool,
pub syntax: Option<String>, crate syntax: Option<String>,
} }
/// Returns a range of bytes for each code block in the markdown that is tagged as `rust` or /// Returns a range of bytes for each code block in the markdown that is tagged as `rust` or
@ -1210,7 +1210,7 @@ crate fn rust_code_blocks(md: &str, extra_info: &ExtraInfo<'_, '_>) -> Vec<RustC
} }
#[derive(Clone, Default, Debug)] #[derive(Clone, Default, Debug)]
pub struct IdMap { crate struct IdMap {
map: FxHashMap<String, usize>, map: FxHashMap<String, usize>,
} }
@ -1243,21 +1243,21 @@ fn init_id_map() -> FxHashMap<String, usize> {
} }
impl IdMap { impl IdMap {
pub fn new() -> Self { crate fn new() -> Self {
IdMap { map: init_id_map() } IdMap { map: init_id_map() }
} }
pub fn populate<I: IntoIterator<Item = String>>(&mut self, ids: I) { crate fn populate<I: IntoIterator<Item = String>>(&mut self, ids: I) {
for id in ids { for id in ids {
let _ = self.derive(id); let _ = self.derive(id);
} }
} }
pub fn reset(&mut self) { crate fn reset(&mut self) {
self.map = init_id_map(); self.map = init_id_map();
} }
pub fn derive(&mut self, candidate: String) -> String { crate fn derive(&mut self, candidate: String) -> String {
let id = match self.map.get_mut(&candidate) { let id = match self.map.get_mut(&candidate) {
None => candidate, None => candidate,
Some(a) => { Some(a) => {

View File

@ -2,8 +2,8 @@ crate mod escape;
crate mod format; crate mod format;
crate mod highlight; crate mod highlight;
crate mod layout; crate mod layout;
pub mod markdown; crate mod markdown;
pub mod render; crate mod render;
crate mod sources; crate mod sources;
crate mod static_files; crate mod static_files;
crate mod toc; crate mod toc;

View File

@ -13,7 +13,7 @@ use crate::html::render::{plain_text_summary, shorten};
use crate::html::render::{Generic, IndexItem, IndexItemFunctionType, RenderType, TypeWithKind}; use crate::html::render::{Generic, IndexItem, IndexItemFunctionType, RenderType, TypeWithKind};
/// Indicates where an external crate can be found. /// Indicates where an external crate can be found.
pub enum ExternalLocation { crate enum ExternalLocation {
/// Remote URL root of the external crate /// Remote URL root of the external crate
Remote(String), Remote(String),
/// This external crate can be found in the local doc/ folder /// This external crate can be found in the local doc/ folder
@ -24,7 +24,7 @@ pub enum ExternalLocation {
/// Attempts to find where an external crate is located, given that we're /// Attempts to find where an external crate is located, given that we're
/// rendering in to the specified source destination. /// rendering in to the specified source destination.
pub fn extern_location( crate fn extern_location(
e: &clean::ExternalCrate, e: &clean::ExternalCrate,
extern_url: Option<&str>, extern_url: Option<&str>,
dst: &Path, dst: &Path,
@ -62,7 +62,7 @@ pub fn extern_location(
} }
/// Builds the search index from the collected metadata /// Builds the search index from the collected metadata
pub fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String { crate fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
let mut defid_to_pathid = FxHashMap::default(); let mut defid_to_pathid = FxHashMap::default();
let mut crate_items = Vec::with_capacity(cache.search_index.len()); let mut crate_items = Vec::with_capacity(cache.search_index.len());
let mut crate_paths = vec![]; let mut crate_paths = vec![];

View File

@ -25,7 +25,7 @@
//! These threads are not parallelized (they haven't been a bottleneck yet), and //! These threads are not parallelized (they haven't been a bottleneck yet), and
//! both occur before the crate is rendered. //! both occur before the crate is rendered.
pub mod cache; crate mod cache;
#[cfg(test)] #[cfg(test)]
mod tests; mod tests;
@ -82,7 +82,7 @@ use crate::html::{highlight, layout, static_files};
use cache::{build_index, ExternalLocation}; use cache::{build_index, ExternalLocation};
/// A pair of name and its optional document. /// A pair of name and its optional document.
pub type NameDoc = (String, Option<String>); crate type NameDoc = (String, Option<String>);
crate fn ensure_trailing_slash(v: &str) -> impl fmt::Display + '_ { crate fn ensure_trailing_slash(v: &str) -> impl fmt::Display + '_ {
crate::html::format::display_fn(move |f| { crate::html::format::display_fn(move |f| {
@ -101,60 +101,60 @@ crate fn ensure_trailing_slash(v: &str) -> impl fmt::Display + '_ {
crate struct Context { crate struct Context {
/// Current hierarchy of components leading down to what's currently being /// Current hierarchy of components leading down to what's currently being
/// rendered /// rendered
pub current: Vec<String>, crate current: Vec<String>,
/// The current destination folder of where HTML artifacts should be placed. /// The current destination folder of where HTML artifacts should be placed.
/// This changes as the context descends into the module hierarchy. /// This changes as the context descends into the module hierarchy.
pub dst: PathBuf, crate dst: PathBuf,
/// A flag, which when `true`, will render pages which redirect to the /// A flag, which when `true`, will render pages which redirect to the
/// real location of an item. This is used to allow external links to /// real location of an item. This is used to allow external links to
/// publicly reused items to redirect to the right location. /// publicly reused items to redirect to the right location.
pub render_redirect_pages: bool, crate render_redirect_pages: bool,
/// The map used to ensure all generated 'id=' attributes are unique. /// The map used to ensure all generated 'id=' attributes are unique.
id_map: Rc<RefCell<IdMap>>, id_map: Rc<RefCell<IdMap>>,
pub shared: Arc<SharedContext>, crate shared: Arc<SharedContext>,
all: Rc<RefCell<AllTypes>>, all: Rc<RefCell<AllTypes>>,
/// Storage for the errors produced while generating documentation so they /// Storage for the errors produced while generating documentation so they
/// can be printed together at the end. /// can be printed together at the end.
pub errors: Rc<Receiver<String>>, crate errors: Rc<Receiver<String>>,
} }
crate struct SharedContext { crate struct SharedContext {
/// The path to the crate root source minus the file name. /// The path to the crate root source minus the file name.
/// Used for simplifying paths to the highlighted source code files. /// Used for simplifying paths to the highlighted source code files.
pub src_root: PathBuf, crate src_root: PathBuf,
/// This describes the layout of each page, and is not modified after /// This describes the layout of each page, and is not modified after
/// creation of the context (contains info like the favicon and added html). /// creation of the context (contains info like the favicon and added html).
pub layout: layout::Layout, crate layout: layout::Layout,
/// This flag indicates whether `[src]` links should be generated or not. If /// This flag indicates whether `[src]` links should be generated or not. If
/// the source files are present in the html rendering, then this will be /// the source files are present in the html rendering, then this will be
/// `true`. /// `true`.
pub include_sources: bool, crate include_sources: bool,
/// The local file sources we've emitted and their respective url-paths. /// The local file sources we've emitted and their respective url-paths.
pub local_sources: FxHashMap<PathBuf, String>, crate local_sources: FxHashMap<PathBuf, String>,
/// Whether the collapsed pass ran /// Whether the collapsed pass ran
pub collapsed: bool, crate collapsed: bool,
/// The base-URL of the issue tracker for when an item has been tagged with /// The base-URL of the issue tracker for when an item has been tagged with
/// an issue number. /// an issue number.
pub issue_tracker_base_url: Option<String>, crate issue_tracker_base_url: Option<String>,
/// The directories that have already been created in this doc run. Used to reduce the number /// The directories that have already been created in this doc run. Used to reduce the number
/// of spurious `create_dir_all` calls. /// of spurious `create_dir_all` calls.
pub created_dirs: RefCell<FxHashSet<PathBuf>>, crate created_dirs: RefCell<FxHashSet<PathBuf>>,
/// This flag indicates whether listings of modules (in the side bar and documentation itself) /// This flag indicates whether listings of modules (in the side bar and documentation itself)
/// should be ordered alphabetically or in order of appearance (in the source code). /// should be ordered alphabetically or in order of appearance (in the source code).
pub sort_modules_alphabetically: bool, crate sort_modules_alphabetically: bool,
/// Additional CSS files to be added to the generated docs. /// Additional CSS files to be added to the generated docs.
pub style_files: Vec<StylePath>, crate style_files: Vec<StylePath>,
/// Suffix to be added on resource files (if suffix is "-v2" then "light.css" becomes /// Suffix to be added on resource files (if suffix is "-v2" then "light.css" becomes
/// "light-v2.css"). /// "light-v2.css").
pub resource_suffix: String, crate resource_suffix: String,
/// Optional path string to be used to load static files on output pages. If not set, uses /// Optional path string to be used to load static files on output pages. If not set, uses
/// combinations of `../` to reach the documentation root. /// combinations of `../` to reach the documentation root.
pub static_root_path: Option<String>, crate static_root_path: Option<String>,
/// The fs handle we are working with. /// The fs handle we are working with.
pub fs: DocFS, crate fs: DocFS,
/// The default edition used to parse doctests. /// The default edition used to parse doctests.
pub edition: Edition, crate edition: Edition,
pub codes: ErrorCodes, crate codes: ErrorCodes,
playground: Option<markdown::Playground>, playground: Option<markdown::Playground>,
} }
@ -186,7 +186,7 @@ impl SharedContext {
/// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
/// `collapsed_doc_value` of the given item. /// `collapsed_doc_value` of the given item.
pub fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<Cow<'a, str>> { crate fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<Cow<'a, str>> {
if self.collapsed { if self.collapsed {
item.collapsed_doc_value().map(|s| s.into()) item.collapsed_doc_value().map(|s| s.into())
} else { } else {
@ -201,14 +201,14 @@ impl SharedContext {
/// Struct representing one entry in the JS search index. These are all emitted /// Struct representing one entry in the JS search index. These are all emitted
/// by hand to a large JS file at the end of cache-creation. /// by hand to a large JS file at the end of cache-creation.
#[derive(Debug)] #[derive(Debug)]
pub struct IndexItem { crate struct IndexItem {
pub ty: ItemType, crate ty: ItemType,
pub name: String, crate name: String,
pub path: String, crate path: String,
pub desc: String, crate desc: String,
pub parent: Option<DefId>, crate parent: Option<DefId>,
pub parent_idx: Option<usize>, crate parent_idx: Option<usize>,
pub search_type: Option<IndexItemFunctionType>, crate search_type: Option<IndexItemFunctionType>,
} }
impl Serialize for IndexItem { impl Serialize for IndexItem {
@ -282,7 +282,7 @@ impl Serialize for Generic {
/// Full type of functions/methods in the search index. /// Full type of functions/methods in the search index.
#[derive(Debug)] #[derive(Debug)]
pub struct IndexItemFunctionType { crate struct IndexItemFunctionType {
inputs: Vec<TypeWithKind>, inputs: Vec<TypeWithKind>,
output: Option<Vec<TypeWithKind>>, output: Option<Vec<TypeWithKind>>,
} }
@ -340,16 +340,16 @@ impl Serialize for TypeWithKind {
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct StylePath { crate struct StylePath {
/// The path to the theme /// The path to the theme
pub path: PathBuf, crate path: PathBuf,
/// What the `disabled` attribute should be set to in the HTML tag /// What the `disabled` attribute should be set to in the HTML tag
pub disabled: bool, crate disabled: bool,
} }
thread_local!(pub static CURRENT_DEPTH: Cell<usize> = Cell::new(0)); thread_local!(crate static CURRENT_DEPTH: Cell<usize> = Cell::new(0));
pub fn initial_ids() -> Vec<String> { crate fn initial_ids() -> Vec<String> {
[ [
"main", "main",
"search", "search",
@ -1701,7 +1701,7 @@ fn print_item(cx: &Context, item: &clean::Item, buf: &mut Buffer, cache: &Cache)
// Write `src` tag // Write `src` tag
// //
// When this item is part of a `pub use` in a downstream crate, the // When this item is part of a `crate use` in a downstream crate, the
// [src] link in the downstream documentation will actually come back to // [src] link in the downstream documentation will actually come back to
// this page, and this link will be auto-clicked. The `id` attribute is // this page, and this link will be auto-clicked. The `id` attribute is
// used to find the link to auto-click. // used to find the link to auto-click.
@ -1994,7 +1994,7 @@ fn document_non_exhaustive(w: &mut Buffer, item: &clean::Item) {
} }
/// Compare two strings treating multi-digit numbers as single units (i.e. natural sort order). /// Compare two strings treating multi-digit numbers as single units (i.e. natural sort order).
pub fn compare_names(mut lhs: &str, mut rhs: &str) -> Ordering { crate fn compare_names(mut lhs: &str, mut rhs: &str) -> Ordering {
/// Takes a non-numeric and a numeric part from the given &str. /// Takes a non-numeric and a numeric part from the given &str.
fn take_parts<'a>(s: &mut &'a str) -> (&'a str, &'a str) { fn take_parts<'a>(s: &mut &'a str) -> (&'a str, &'a str) {
let i = s.find(|c: char| c.is_ascii_digit()); let i = s.find(|c: char| c.is_ascii_digit());
@ -2081,14 +2081,14 @@ fn item_module(w: &mut Buffer, cx: &Context, item: &clean::Item, items: &[clean:
// This call is to remove re-export duplicates in cases such as: // This call is to remove re-export duplicates in cases such as:
// //
// ``` // ```
// pub mod foo { // crate mod foo {
// pub mod bar { // crate mod bar {
// pub trait Double { fn foo(); } // crate trait Double { fn foo(); }
// } // }
// } // }
// //
// pub use foo::bar::*; // crate use foo::bar::*;
// pub use foo::*; // crate use foo::*;
// ``` // ```
// //
// `Double` will appear twice in the generated docs. // `Double` will appear twice in the generated docs.

View File

@ -137,7 +137,7 @@ impl<'a> SourceCollector<'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) will
/// be passed to `f` if `keep_filename` is true, and ignored otherwise. /// be passed to `f` if `keep_filename` is true, and ignored otherwise.
pub fn clean_path<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F) crate fn clean_path<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F)
where where
F: FnMut(&OsStr), F: FnMut(&OsStr),
{ {

View File

@ -8,111 +8,111 @@
//! directly written to a `Write` handle. //! directly written to a `Write` handle.
/// The file contents of the main `rustdoc.css` file, responsible for the core layout of the page. /// The file contents of the main `rustdoc.css` file, responsible for the core layout of the page.
pub static RUSTDOC_CSS: &str = include_str!("static/rustdoc.css"); crate static RUSTDOC_CSS: &str = include_str!("static/rustdoc.css");
/// The file contents of `settings.css`, responsible for the items on the settings page. /// The file contents of `settings.css`, responsible for the items on the settings page.
pub static SETTINGS_CSS: &str = include_str!("static/settings.css"); crate static SETTINGS_CSS: &str = include_str!("static/settings.css");
/// The file contents of the `noscript.css` file, used in case JS isn't supported or is disabled. /// The file contents of the `noscript.css` file, used in case JS isn't supported or is disabled.
pub static NOSCRIPT_CSS: &str = include_str!("static/noscript.css"); crate static NOSCRIPT_CSS: &str = include_str!("static/noscript.css");
/// The file contents of `normalize.css`, included to even out standard elements between browser /// The file contents of `normalize.css`, included to even out standard elements between browser
/// implementations. /// implementations.
pub static NORMALIZE_CSS: &str = include_str!("static/normalize.css"); crate static NORMALIZE_CSS: &str = include_str!("static/normalize.css");
/// The file contents of `main.js`, which contains the core JavaScript used on documentation pages, /// The file contents of `main.js`, which contains the core JavaScript used on documentation pages,
/// including search behavior and docblock folding, among others. /// including search behavior and docblock folding, among others.
pub static MAIN_JS: &str = include_str!("static/main.js"); crate static MAIN_JS: &str = include_str!("static/main.js");
/// The file contents of `settings.js`, which contains the JavaScript used to handle the settings /// The file contents of `settings.js`, which contains the JavaScript used to handle the settings
/// page. /// page.
pub static SETTINGS_JS: &str = include_str!("static/settings.js"); crate static SETTINGS_JS: &str = include_str!("static/settings.js");
/// The file contents of `storage.js`, which contains functionality related to browser Local /// The file contents of `storage.js`, which contains functionality related to browser Local
/// Storage, used to store documentation settings. /// Storage, used to store documentation settings.
pub static STORAGE_JS: &str = include_str!("static/storage.js"); crate static STORAGE_JS: &str = include_str!("static/storage.js");
/// The file contents of `brush.svg`, the icon used for the theme-switch button. /// The file contents of `brush.svg`, the icon used for the theme-switch button.
pub static BRUSH_SVG: &[u8] = include_bytes!("static/brush.svg"); crate static BRUSH_SVG: &[u8] = include_bytes!("static/brush.svg");
/// The file contents of `wheel.svg`, the icon used for the settings button. /// The file contents of `wheel.svg`, the icon used for the settings button.
pub static WHEEL_SVG: &[u8] = include_bytes!("static/wheel.svg"); crate static WHEEL_SVG: &[u8] = include_bytes!("static/wheel.svg");
/// The file contents of `down-arrow.svg`, the icon used for the crate choice combobox. /// The file contents of `down-arrow.svg`, the icon used for the crate choice combobox.
pub static DOWN_ARROW_SVG: &[u8] = include_bytes!("static/down-arrow.svg"); crate static DOWN_ARROW_SVG: &[u8] = include_bytes!("static/down-arrow.svg");
/// The contents of `COPYRIGHT.txt`, the license listing for files distributed with documentation /// The contents of `COPYRIGHT.txt`, the license listing for files distributed with documentation
/// output. /// output.
pub static COPYRIGHT: &[u8] = include_bytes!("static/COPYRIGHT.txt"); crate static COPYRIGHT: &[u8] = include_bytes!("static/COPYRIGHT.txt");
/// The contents of `LICENSE-APACHE.txt`, the text of the Apache License, version 2.0. /// The contents of `LICENSE-APACHE.txt`, the text of the Apache License, version 2.0.
pub static LICENSE_APACHE: &[u8] = include_bytes!("static/LICENSE-APACHE.txt"); crate static LICENSE_APACHE: &[u8] = include_bytes!("static/LICENSE-APACHE.txt");
/// The contents of `LICENSE-MIT.txt`, the text of the MIT License. /// The contents of `LICENSE-MIT.txt`, the text of the MIT License.
pub static LICENSE_MIT: &[u8] = include_bytes!("static/LICENSE-MIT.txt"); crate static LICENSE_MIT: &[u8] = include_bytes!("static/LICENSE-MIT.txt");
/// The contents of `rust-logo.png`, the default icon of the documentation. /// The contents of `rust-logo.png`, the default icon of the documentation.
pub static RUST_LOGO: &[u8] = include_bytes!("static/rust-logo.png"); crate static RUST_LOGO: &[u8] = include_bytes!("static/rust-logo.png");
/// The default documentation favicons (SVG and PNG fallbacks) /// The default documentation favicons (SVG and PNG fallbacks)
pub static RUST_FAVICON_SVG: &[u8] = include_bytes!("static/favicon.svg"); crate static RUST_FAVICON_SVG: &[u8] = include_bytes!("static/favicon.svg");
pub static RUST_FAVICON_PNG_16: &[u8] = include_bytes!("static/favicon-16x16.png"); crate static RUST_FAVICON_PNG_16: &[u8] = include_bytes!("static/favicon-16x16.png");
pub static RUST_FAVICON_PNG_32: &[u8] = include_bytes!("static/favicon-32x32.png"); crate static RUST_FAVICON_PNG_32: &[u8] = include_bytes!("static/favicon-32x32.png");
/// The built-in themes given to every documentation site. /// The built-in themes given to every documentation site.
pub mod themes { crate mod themes {
/// The "light" theme, selected by default when no setting is available. Used as the basis for /// The "light" theme, selected by default when no setting is available. Used as the basis for
/// the `--check-theme` functionality. /// the `--check-theme` functionality.
pub static LIGHT: &str = include_str!("static/themes/light.css"); crate static LIGHT: &str = include_str!("static/themes/light.css");
/// The "dark" theme. /// The "dark" theme.
pub static DARK: &str = include_str!("static/themes/dark.css"); crate static DARK: &str = include_str!("static/themes/dark.css");
/// The "ayu" theme. /// The "ayu" theme.
pub static AYU: &str = include_str!("static/themes/ayu.css"); crate static AYU: &str = include_str!("static/themes/ayu.css");
} }
/// Files related to the Fira Sans font. /// Files related to the Fira Sans font.
pub mod fira_sans { crate mod fira_sans {
/// The file `FiraSans-Regular.woff`, the Regular variant of the Fira Sans font. /// The file `FiraSans-Regular.woff`, the Regular variant of the Fira Sans font.
pub static REGULAR: &[u8] = include_bytes!("static/FiraSans-Regular.woff"); crate static REGULAR: &[u8] = include_bytes!("static/FiraSans-Regular.woff");
/// The file `FiraSans-Medium.woff`, the Medium variant of the Fira Sans font. /// The file `FiraSans-Medium.woff`, the Medium variant of the Fira Sans font.
pub static MEDIUM: &[u8] = include_bytes!("static/FiraSans-Medium.woff"); crate static MEDIUM: &[u8] = include_bytes!("static/FiraSans-Medium.woff");
/// The file `FiraSans-LICENSE.txt`, the license text for the Fira Sans font. /// The file `FiraSans-LICENSE.txt`, the license text for the Fira Sans font.
pub static LICENSE: &[u8] = include_bytes!("static/FiraSans-LICENSE.txt"); crate static LICENSE: &[u8] = include_bytes!("static/FiraSans-LICENSE.txt");
} }
/// Files related to the Source Serif Pro font. /// Files related to the Source Serif Pro font.
pub mod source_serif_pro { crate mod source_serif_pro {
/// The file `SourceSerifPro-Regular.ttf.woff`, the Regular variant of the Source Serif Pro /// The file `SourceSerifPro-Regular.ttf.woff`, the Regular variant of the Source Serif Pro
/// font. /// font.
pub static REGULAR: &[u8] = include_bytes!("static/SourceSerifPro-Regular.ttf.woff"); crate static REGULAR: &[u8] = include_bytes!("static/SourceSerifPro-Regular.ttf.woff");
/// The file `SourceSerifPro-Bold.ttf.woff`, the Bold variant of the Source Serif Pro font. /// The file `SourceSerifPro-Bold.ttf.woff`, the Bold variant of the Source Serif Pro font.
pub static BOLD: &[u8] = include_bytes!("static/SourceSerifPro-Bold.ttf.woff"); crate static BOLD: &[u8] = include_bytes!("static/SourceSerifPro-Bold.ttf.woff");
/// The file `SourceSerifPro-It.ttf.woff`, the Italic variant of the Source Serif Pro font. /// The file `SourceSerifPro-It.ttf.woff`, the Italic variant of the Source Serif Pro font.
pub static ITALIC: &[u8] = include_bytes!("static/SourceSerifPro-It.ttf.woff"); crate static ITALIC: &[u8] = include_bytes!("static/SourceSerifPro-It.ttf.woff");
/// The file `SourceSerifPro-LICENSE.txt`, the license text for the Source Serif Pro font. /// The file `SourceSerifPro-LICENSE.txt`, the license text for the Source Serif Pro font.
pub static LICENSE: &[u8] = include_bytes!("static/SourceSerifPro-LICENSE.md"); crate static LICENSE: &[u8] = include_bytes!("static/SourceSerifPro-LICENSE.md");
} }
/// Files related to the Source Code Pro font. /// Files related to the Source Code Pro font.
pub mod source_code_pro { crate mod source_code_pro {
/// The file `SourceCodePro-Regular.woff`, the Regular variant of the Source Code Pro font. /// The file `SourceCodePro-Regular.woff`, the Regular variant of the Source Code Pro font.
pub static REGULAR: &[u8] = include_bytes!("static/SourceCodePro-Regular.woff"); crate static REGULAR: &[u8] = include_bytes!("static/SourceCodePro-Regular.woff");
/// The file `SourceCodePro-Semibold.woff`, the Semibold variant of the Source Code Pro font. /// The file `SourceCodePro-Semibold.woff`, the Semibold variant of the Source Code Pro font.
pub static SEMIBOLD: &[u8] = include_bytes!("static/SourceCodePro-Semibold.woff"); crate static SEMIBOLD: &[u8] = include_bytes!("static/SourceCodePro-Semibold.woff");
/// The file `SourceCodePro-LICENSE.txt`, the license text of the Source Code Pro font. /// The file `SourceCodePro-LICENSE.txt`, the license text of the Source Code Pro font.
pub static LICENSE: &[u8] = include_bytes!("static/SourceCodePro-LICENSE.txt"); crate static LICENSE: &[u8] = include_bytes!("static/SourceCodePro-LICENSE.txt");
} }
/// Files related to the sidebar in rustdoc sources. /// Files related to the sidebar in rustdoc sources.
pub mod sidebar { crate mod sidebar {
/// File script to handle sidebar. /// File script to handle sidebar.
pub static SOURCE_SCRIPT: &str = include_str!("static/source-script.js"); crate static SOURCE_SCRIPT: &str = include_str!("static/source-script.js");
} }

View File

@ -2,7 +2,7 @@
/// A (recursive) table of contents /// A (recursive) table of contents
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]
pub struct Toc { crate struct Toc {
/// The levels are strictly decreasing, i.e. /// The levels are strictly decreasing, i.e.
/// ///
/// `entries[0].level >= entries[1].level >= ...` /// `entries[0].level >= entries[1].level >= ...`
@ -26,7 +26,7 @@ impl Toc {
} }
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]
pub struct TocEntry { crate struct TocEntry {
level: u32, level: u32,
sec_number: String, sec_number: String,
name: String, name: String,
@ -36,7 +36,7 @@ pub struct TocEntry {
/// Progressive construction of a table of contents. /// Progressive construction of a table of contents.
#[derive(PartialEq)] #[derive(PartialEq)]
pub struct TocBuilder { crate struct TocBuilder {
top_level: Toc, top_level: Toc,
/// The current hierarchy of parent headings, the levels are /// The current hierarchy of parent headings, the levels are
/// strictly increasing (i.e., `chain[0].level < chain[1].level < /// strictly increasing (i.e., `chain[0].level < chain[1].level <
@ -50,12 +50,12 @@ pub struct TocBuilder {
} }
impl TocBuilder { impl TocBuilder {
pub fn new() -> TocBuilder { crate fn new() -> TocBuilder {
TocBuilder { top_level: Toc { entries: Vec::new() }, chain: Vec::new() } TocBuilder { top_level: Toc { entries: Vec::new() }, chain: Vec::new() }
} }
/// Converts into a true `Toc` struct. /// Converts into a true `Toc` struct.
pub fn into_toc(mut self) -> Toc { crate fn into_toc(mut self) -> Toc {
// we know all levels are >= 1. // we know all levels are >= 1.
self.fold_until(0); self.fold_until(0);
self.top_level self.top_level
@ -115,7 +115,7 @@ impl TocBuilder {
/// Push a level `level` heading into the appropriate place in the /// Push a level `level` heading into the appropriate place in the
/// hierarchy, returning a string containing the section number in /// hierarchy, returning a string containing the section number in
/// `<num>.<num>.<num>` format. /// `<num>.<num>.<num>` format.
pub fn push(&mut self, level: u32, name: String, id: String) -> &str { crate fn push(&mut self, level: u32, name: String, id: String) -> &str {
assert!(level >= 1); assert!(level >= 1);
// collapse all previous sections into their parents until we // collapse all previous sections into their parents until we

View File

@ -7,7 +7,7 @@ use crate::formats::FormatRenderer;
use rustc_span::edition::Edition; use rustc_span::edition::Edition;
#[derive(Clone)] #[derive(Clone)]
pub struct JsonRenderer {} crate struct JsonRenderer {}
impl FormatRenderer for JsonRenderer { impl FormatRenderer for JsonRenderer {
fn init( fn init(

View File

@ -77,7 +77,7 @@ mod error;
mod doctest; mod doctest;
mod fold; mod fold;
crate mod formats; crate mod formats;
pub mod html; crate mod html;
mod json; mod json;
mod markdown; mod markdown;
mod passes; mod passes;
@ -85,7 +85,7 @@ mod theme;
mod visit_ast; mod visit_ast;
mod visit_lib; mod visit_lib;
pub fn main() { crate fn main() {
rustc_driver::set_sigpipe_handler(); rustc_driver::set_sigpipe_handler();
rustc_driver::install_ice_hook(); rustc_driver::install_ice_hook();
rustc_driver::init_env_logger("RUSTDOC_LOG"); rustc_driver::init_env_logger("RUSTDOC_LOG");

View File

@ -32,7 +32,7 @@ fn extract_leading_metadata(s: &str) -> (Vec<&str>, &str) {
/// Render `input` (e.g., "foo.md") into an HTML file in `output` /// Render `input` (e.g., "foo.md") into an HTML file in `output`
/// (e.g., output = "bar" => "bar/foo.html"). /// (e.g., output = "bar" => "bar/foo.html").
pub fn render<P: AsRef<Path>>( crate fn render<P: AsRef<Path>>(
input: P, input: P,
options: RenderOptions, options: RenderOptions,
edition: Edition, edition: Edition,
@ -114,7 +114,7 @@ pub fn render<P: AsRef<Path>>(
} }
/// Runs any tests/code examples in the markdown file `input`. /// Runs any tests/code examples in the markdown file `input`.
pub fn test(mut options: Options) -> Result<(), String> { crate fn test(mut options: Options) -> Result<(), String> {
let input_str = read_to_string(&options.input) let input_str = read_to_string(&options.input)
.map_err(|err| format!("{}: {}", options.input.display(), err))?; .map_err(|err| format!("{}: {}", options.input.display(), err))?;
let mut opts = TestOptions::default(); let mut opts = TestOptions::default();

View File

@ -14,7 +14,7 @@ use serde::Serialize;
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::ops; use std::ops;
pub const CALCULATE_DOC_COVERAGE: Pass = Pass { crate const CALCULATE_DOC_COVERAGE: Pass = Pass {
name: "calculate-doc-coverage", name: "calculate-doc-coverage",
run: calculate_doc_coverage, run: calculate_doc_coverage,
description: "counts the number of items with and without documentation", description: "counts the number of items with and without documentation",

View File

@ -11,13 +11,13 @@ use crate::fold::DocFolder;
use crate::html::markdown::{self, RustCodeBlock}; use crate::html::markdown::{self, RustCodeBlock};
use crate::passes::{span_of_attrs, Pass}; use crate::passes::{span_of_attrs, Pass};
pub const CHECK_CODE_BLOCK_SYNTAX: Pass = Pass { crate const CHECK_CODE_BLOCK_SYNTAX: Pass = Pass {
name: "check-code-block-syntax", name: "check-code-block-syntax",
run: check_code_block_syntax, run: check_code_block_syntax,
description: "validates syntax inside Rust code blocks", description: "validates syntax inside Rust code blocks",
}; };
pub fn check_code_block_syntax(krate: clean::Crate, cx: &DocContext<'_>) -> clean::Crate { crate fn check_code_block_syntax(krate: clean::Crate, cx: &DocContext<'_>) -> clean::Crate {
SyntaxChecker { cx }.fold_crate(krate) SyntaxChecker { cx }.fold_crate(krate)
} }

View File

@ -6,13 +6,13 @@ use crate::passes::Pass;
use std::mem::take; use std::mem::take;
pub const COLLAPSE_DOCS: Pass = Pass { crate const COLLAPSE_DOCS: Pass = Pass {
name: "collapse-docs", name: "collapse-docs",
run: collapse_docs, run: collapse_docs,
description: "concatenates all document attributes into one document attribute", description: "concatenates all document attributes into one document attribute",
}; };
pub fn collapse_docs(krate: clean::Crate, _: &DocContext<'_>) -> clean::Crate { crate fn collapse_docs(krate: clean::Crate, _: &DocContext<'_>) -> clean::Crate {
let mut krate = Collapser.fold_crate(krate); let mut krate = Collapser.fold_crate(krate);
krate.collapsed = true; krate.collapsed = true;
krate krate
@ -66,7 +66,7 @@ fn collapse(doc_strings: &mut Vec<DocFragment>) {
} }
impl clean::Attributes { impl clean::Attributes {
pub fn collapse_doc_comments(&mut self) { crate fn collapse_doc_comments(&mut self) {
collapse(&mut self.doc_strings); collapse(&mut self.doc_strings);
} }
} }

View File

@ -39,13 +39,13 @@ use crate::passes::Pass;
use super::span_of_attrs; use super::span_of_attrs;
pub const COLLECT_INTRA_DOC_LINKS: Pass = Pass { crate const COLLECT_INTRA_DOC_LINKS: Pass = Pass {
name: "collect-intra-doc-links", name: "collect-intra-doc-links",
run: collect_intra_doc_links, run: collect_intra_doc_links,
description: "reads a crate's documentation to resolve intra-doc-links", description: "reads a crate's documentation to resolve intra-doc-links",
}; };
pub fn collect_intra_doc_links(krate: Crate, cx: &DocContext<'_>) -> Crate { crate fn collect_intra_doc_links(krate: Crate, cx: &DocContext<'_>) -> Crate {
LinkCollector::new(cx).fold_crate(krate) LinkCollector::new(cx).fold_crate(krate)
} }

View File

@ -7,13 +7,13 @@ use rustc_data_structures::fx::FxHashSet;
use rustc_hir::def_id::{DefId, LOCAL_CRATE}; use rustc_hir::def_id::{DefId, LOCAL_CRATE};
use rustc_span::symbol::sym; use rustc_span::symbol::sym;
pub const COLLECT_TRAIT_IMPLS: Pass = Pass { crate const COLLECT_TRAIT_IMPLS: Pass = Pass {
name: "collect-trait-impls", name: "collect-trait-impls",
run: collect_trait_impls, run: collect_trait_impls,
description: "retrieves trait impls for items in the crate", description: "retrieves trait impls for items in the crate",
}; };
pub fn collect_trait_impls(krate: Crate, cx: &DocContext<'_>) -> Crate { crate fn collect_trait_impls(krate: Crate, cx: &DocContext<'_>) -> Crate {
let mut synth = SyntheticImplCollector::new(cx); let mut synth = SyntheticImplCollector::new(cx);
let mut krate = synth.fold_crate(krate); let mut krate = synth.fold_crate(krate);

View File

@ -12,7 +12,7 @@ use crate::html::markdown::{find_testable_code, ErrorCodes, Ignore, LangString};
use rustc_middle::lint::LintSource; use rustc_middle::lint::LintSource;
use rustc_session::lint; use rustc_session::lint;
pub const CHECK_PRIVATE_ITEMS_DOC_TESTS: Pass = Pass { crate const CHECK_PRIVATE_ITEMS_DOC_TESTS: Pass = Pass {
name: "check-private-items-doc-tests", name: "check-private-items-doc-tests",
run: check_private_items_doc_tests, run: check_private_items_doc_tests,
description: "check private items doc tests", description: "check private items doc tests",
@ -28,7 +28,7 @@ impl<'a, 'tcx> PrivateItemDocTestLinter<'a, 'tcx> {
} }
} }
pub fn check_private_items_doc_tests(krate: Crate, cx: &DocContext<'_>) -> Crate { crate fn check_private_items_doc_tests(krate: Crate, cx: &DocContext<'_>) -> Crate {
let mut coll = PrivateItemDocTestLinter::new(cx); let mut coll = PrivateItemDocTestLinter::new(cx);
coll.fold_crate(krate) coll.fold_crate(krate)
@ -57,7 +57,7 @@ impl crate::doctest::Tester for Tests {
} }
} }
pub fn should_have_doc_example(cx: &DocContext<'_>, item: &clean::Item) -> bool { crate fn should_have_doc_example(cx: &DocContext<'_>, item: &clean::Item) -> bool {
if matches!(item.kind, if matches!(item.kind,
clean::StructFieldItem(_) clean::StructFieldItem(_)
| clean::VariantItem(_) | clean::VariantItem(_)
@ -79,7 +79,7 @@ pub fn should_have_doc_example(cx: &DocContext<'_>, item: &clean::Item) -> bool
level != lint::Level::Allow || matches!(source, LintSource::Default) level != lint::Level::Allow || matches!(source, LintSource::Default)
} }
pub fn look_for_tests<'tcx>(cx: &DocContext<'tcx>, dox: &str, item: &Item) { crate fn look_for_tests<'tcx>(cx: &DocContext<'tcx>, dox: &str, item: &Item) {
let hir_id = match cx.as_local_hir_id(item.def_id) { let hir_id = match cx.as_local_hir_id(item.def_id) {
Some(hir_id) => hir_id, Some(hir_id) => hir_id,
None => { None => {

View File

@ -9,7 +9,7 @@ use rustc_session::lint;
use std::iter::Peekable; use std::iter::Peekable;
use std::str::CharIndices; use std::str::CharIndices;
pub const CHECK_INVALID_HTML_TAGS: Pass = Pass { crate const CHECK_INVALID_HTML_TAGS: Pass = Pass {
name: "check-invalid-html-tags", name: "check-invalid-html-tags",
run: check_invalid_html_tags, run: check_invalid_html_tags,
description: "detects invalid HTML tags in doc comments", description: "detects invalid HTML tags in doc comments",
@ -25,7 +25,7 @@ impl<'a, 'tcx> InvalidHtmlTagsLinter<'a, 'tcx> {
} }
} }
pub fn check_invalid_html_tags(krate: Crate, cx: &DocContext<'_>) -> Crate { crate fn check_invalid_html_tags(krate: Crate, cx: &DocContext<'_>) -> Crate {
if !cx.tcx.sess.is_nightly_build() { if !cx.tcx.sess.is_nightly_build() {
krate krate
} else { } else {

View File

@ -9,67 +9,67 @@ use crate::clean::{self, DocFragmentKind};
use crate::core::DocContext; use crate::core::DocContext;
mod stripper; mod stripper;
pub use stripper::*; crate use stripper::*;
mod non_autolinks; mod non_autolinks;
pub use self::non_autolinks::CHECK_NON_AUTOLINKS; crate use self::non_autolinks::CHECK_NON_AUTOLINKS;
mod collapse_docs; mod collapse_docs;
pub use self::collapse_docs::COLLAPSE_DOCS; crate use self::collapse_docs::COLLAPSE_DOCS;
mod strip_hidden; mod strip_hidden;
pub use self::strip_hidden::STRIP_HIDDEN; crate use self::strip_hidden::STRIP_HIDDEN;
mod strip_private; mod strip_private;
pub use self::strip_private::STRIP_PRIVATE; crate use self::strip_private::STRIP_PRIVATE;
mod strip_priv_imports; mod strip_priv_imports;
pub use self::strip_priv_imports::STRIP_PRIV_IMPORTS; crate use self::strip_priv_imports::STRIP_PRIV_IMPORTS;
mod unindent_comments; mod unindent_comments;
pub use self::unindent_comments::UNINDENT_COMMENTS; crate use self::unindent_comments::UNINDENT_COMMENTS;
mod propagate_doc_cfg; mod propagate_doc_cfg;
pub use self::propagate_doc_cfg::PROPAGATE_DOC_CFG; crate use self::propagate_doc_cfg::PROPAGATE_DOC_CFG;
mod collect_intra_doc_links; mod collect_intra_doc_links;
pub use self::collect_intra_doc_links::COLLECT_INTRA_DOC_LINKS; crate use self::collect_intra_doc_links::COLLECT_INTRA_DOC_LINKS;
mod doc_test_lints; mod doc_test_lints;
pub use self::doc_test_lints::CHECK_PRIVATE_ITEMS_DOC_TESTS; crate use self::doc_test_lints::CHECK_PRIVATE_ITEMS_DOC_TESTS;
mod collect_trait_impls; mod collect_trait_impls;
pub use self::collect_trait_impls::COLLECT_TRAIT_IMPLS; crate use self::collect_trait_impls::COLLECT_TRAIT_IMPLS;
mod check_code_block_syntax; mod check_code_block_syntax;
pub use self::check_code_block_syntax::CHECK_CODE_BLOCK_SYNTAX; crate use self::check_code_block_syntax::CHECK_CODE_BLOCK_SYNTAX;
mod calculate_doc_coverage; mod calculate_doc_coverage;
pub use self::calculate_doc_coverage::CALCULATE_DOC_COVERAGE; crate use self::calculate_doc_coverage::CALCULATE_DOC_COVERAGE;
mod html_tags; mod html_tags;
pub use self::html_tags::CHECK_INVALID_HTML_TAGS; crate use self::html_tags::CHECK_INVALID_HTML_TAGS;
/// A single pass over the cleaned documentation. /// A single pass over the cleaned documentation.
/// ///
/// Runs in the compiler context, so it has access to types and traits and the like. /// Runs in the compiler context, so it has access to types and traits and the like.
#[derive(Copy, Clone)] #[derive(Copy, Clone)]
pub struct Pass { crate struct Pass {
pub name: &'static str, crate name: &'static str,
pub run: fn(clean::Crate, &DocContext<'_>) -> clean::Crate, crate run: fn(clean::Crate, &DocContext<'_>) -> clean::Crate,
pub description: &'static str, crate description: &'static str,
} }
/// In a list of passes, a pass that may or may not need to be run depending on options. /// In a list of passes, a pass that may or may not need to be run depending on options.
#[derive(Copy, Clone)] #[derive(Copy, Clone)]
pub struct ConditionalPass { crate struct ConditionalPass {
pub pass: Pass, crate pass: Pass,
pub condition: Condition, crate condition: Condition,
} }
/// How to decide whether to run a conditional pass. /// How to decide whether to run a conditional pass.
#[derive(Copy, Clone)] #[derive(Copy, Clone)]
pub enum Condition { crate enum Condition {
Always, Always,
/// When `--document-private-items` is passed. /// When `--document-private-items` is passed.
WhenDocumentPrivate, WhenDocumentPrivate,
@ -80,7 +80,7 @@ pub enum Condition {
} }
/// The full list of passes. /// The full list of passes.
pub const PASSES: &[Pass] = &[ crate const PASSES: &[Pass] = &[
CHECK_PRIVATE_ITEMS_DOC_TESTS, CHECK_PRIVATE_ITEMS_DOC_TESTS,
STRIP_HIDDEN, STRIP_HIDDEN,
UNINDENT_COMMENTS, UNINDENT_COMMENTS,
@ -97,7 +97,7 @@ pub const PASSES: &[Pass] = &[
]; ];
/// The list of passes run by default. /// The list of passes run by default.
pub const DEFAULT_PASSES: &[ConditionalPass] = &[ crate const DEFAULT_PASSES: &[ConditionalPass] = &[
ConditionalPass::always(COLLECT_TRAIT_IMPLS), ConditionalPass::always(COLLECT_TRAIT_IMPLS),
ConditionalPass::always(COLLAPSE_DOCS), ConditionalPass::always(COLLAPSE_DOCS),
ConditionalPass::always(UNINDENT_COMMENTS), ConditionalPass::always(UNINDENT_COMMENTS),
@ -113,7 +113,7 @@ pub const DEFAULT_PASSES: &[ConditionalPass] = &[
]; ];
/// The list of default passes run when `--doc-coverage` is passed to rustdoc. /// The list of default passes run when `--doc-coverage` is passed to rustdoc.
pub const COVERAGE_PASSES: &[ConditionalPass] = &[ crate const COVERAGE_PASSES: &[ConditionalPass] = &[
ConditionalPass::always(COLLECT_TRAIT_IMPLS), ConditionalPass::always(COLLECT_TRAIT_IMPLS),
ConditionalPass::new(STRIP_HIDDEN, WhenNotDocumentHidden), ConditionalPass::new(STRIP_HIDDEN, WhenNotDocumentHidden),
ConditionalPass::new(STRIP_PRIVATE, WhenNotDocumentPrivate), ConditionalPass::new(STRIP_PRIVATE, WhenNotDocumentPrivate),
@ -121,11 +121,11 @@ pub const COVERAGE_PASSES: &[ConditionalPass] = &[
]; ];
impl ConditionalPass { impl ConditionalPass {
pub const fn always(pass: Pass) -> Self { crate const fn always(pass: Pass) -> Self {
Self::new(pass, Always) Self::new(pass, Always)
} }
pub const fn new(pass: Pass, condition: Condition) -> Self { crate const fn new(pass: Pass, condition: Condition) -> Self {
ConditionalPass { pass, condition } ConditionalPass { pass, condition }
} }
} }
@ -133,14 +133,14 @@ impl ConditionalPass {
/// A shorthand way to refer to which set of passes to use, based on the presence of /// A shorthand way to refer to which set of passes to use, based on the presence of
/// `--no-defaults` and `--show-coverage`. /// `--no-defaults` and `--show-coverage`.
#[derive(Copy, Clone, PartialEq, Eq, Debug)] #[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum DefaultPassOption { crate enum DefaultPassOption {
Default, Default,
Coverage, Coverage,
None, None,
} }
/// Returns the given default set of passes. /// Returns the given default set of passes.
pub fn defaults(default_set: DefaultPassOption) -> &'static [ConditionalPass] { crate fn defaults(default_set: DefaultPassOption) -> &'static [ConditionalPass] {
match default_set { match default_set {
DefaultPassOption::Default => DEFAULT_PASSES, DefaultPassOption::Default => DEFAULT_PASSES,
DefaultPassOption::Coverage => COVERAGE_PASSES, DefaultPassOption::Coverage => COVERAGE_PASSES,
@ -149,7 +149,7 @@ pub fn defaults(default_set: DefaultPassOption) -> &'static [ConditionalPass] {
} }
/// If the given name matches a known pass, returns its information. /// If the given name matches a known pass, returns its information.
pub fn find_pass(pass_name: &str) -> Option<Pass> { crate fn find_pass(pass_name: &str) -> Option<Pass> {
PASSES.iter().find(|p| p.name == pass_name).copied() PASSES.iter().find(|p| p.name == pass_name).copied()
} }

View File

@ -9,7 +9,7 @@ use regex::Regex;
use rustc_errors::Applicability; use rustc_errors::Applicability;
use rustc_session::lint; use rustc_session::lint;
pub const CHECK_NON_AUTOLINKS: Pass = Pass { crate const CHECK_NON_AUTOLINKS: Pass = Pass {
name: "check-non-autolinks", name: "check-non-autolinks",
run: check_non_autolinks, run: check_non_autolinks,
description: "detects URLS that could be written using angle brackets", description: "detects URLS that could be written using angle brackets",
@ -52,7 +52,7 @@ impl<'a, 'tcx> NonAutolinksLinter<'a, 'tcx> {
} }
} }
pub fn check_non_autolinks(krate: Crate, cx: &DocContext<'_>) -> Crate { crate fn check_non_autolinks(krate: Crate, cx: &DocContext<'_>) -> Crate {
if !cx.tcx.sess.is_nightly_build() { if !cx.tcx.sess.is_nightly_build() {
krate krate
} else { } else {

View File

@ -6,13 +6,13 @@ use crate::core::DocContext;
use crate::fold::DocFolder; use crate::fold::DocFolder;
use crate::passes::Pass; use crate::passes::Pass;
pub const PROPAGATE_DOC_CFG: Pass = Pass { crate const PROPAGATE_DOC_CFG: Pass = Pass {
name: "propagate-doc-cfg", name: "propagate-doc-cfg",
run: propagate_doc_cfg, run: propagate_doc_cfg,
description: "propagates `#[doc(cfg(...))]` to child items", description: "propagates `#[doc(cfg(...))]` to child items",
}; };
pub fn propagate_doc_cfg(cr: Crate, _: &DocContext<'_>) -> Crate { crate fn propagate_doc_cfg(cr: Crate, _: &DocContext<'_>) -> Crate {
CfgPropagator { parent_cfg: None }.fold_crate(cr) CfgPropagator { parent_cfg: None }.fold_crate(cr)
} }

View File

@ -8,14 +8,14 @@ use crate::core::DocContext;
use crate::fold::{DocFolder, StripItem}; use crate::fold::{DocFolder, StripItem};
use crate::passes::{ImplStripper, Pass}; use crate::passes::{ImplStripper, Pass};
pub const STRIP_HIDDEN: Pass = Pass { crate const STRIP_HIDDEN: Pass = Pass {
name: "strip-hidden", name: "strip-hidden",
run: strip_hidden, run: strip_hidden,
description: "strips all doc(hidden) items from the output", description: "strips all doc(hidden) items from the output",
}; };
/// Strip items marked `#[doc(hidden)]` /// Strip items marked `#[doc(hidden)]`
pub fn strip_hidden(krate: clean::Crate, _: &DocContext<'_>) -> clean::Crate { crate fn strip_hidden(krate: clean::Crate, _: &DocContext<'_>) -> clean::Crate {
let mut retained = DefIdSet::default(); let mut retained = DefIdSet::default();
// strip all #[doc(hidden)] items // strip all #[doc(hidden)] items

View File

@ -3,12 +3,12 @@ use crate::core::DocContext;
use crate::fold::DocFolder; use crate::fold::DocFolder;
use crate::passes::{ImportStripper, Pass}; use crate::passes::{ImportStripper, Pass};
pub const STRIP_PRIV_IMPORTS: Pass = Pass { crate const STRIP_PRIV_IMPORTS: Pass = Pass {
name: "strip-priv-imports", name: "strip-priv-imports",
run: strip_priv_imports, run: strip_priv_imports,
description: "strips all private import statements (`use`, `extern crate`) from a crate", description: "strips all private import statements (`use`, `extern crate`) from a crate",
}; };
pub fn strip_priv_imports(krate: clean::Crate, _: &DocContext<'_>) -> clean::Crate { crate fn strip_priv_imports(krate: clean::Crate, _: &DocContext<'_>) -> clean::Crate {
ImportStripper.fold_crate(krate) ImportStripper.fold_crate(krate)
} }

View File

@ -5,7 +5,7 @@ use crate::core::DocContext;
use crate::fold::DocFolder; use crate::fold::DocFolder;
use crate::passes::{ImplStripper, ImportStripper, Pass, Stripper}; use crate::passes::{ImplStripper, ImportStripper, Pass, Stripper};
pub const STRIP_PRIVATE: Pass = Pass { crate const STRIP_PRIVATE: Pass = Pass {
name: "strip-private", name: "strip-private",
run: strip_private, run: strip_private,
description: "strips all private items from a crate which cannot be seen externally, \ description: "strips all private items from a crate which cannot be seen externally, \
@ -14,7 +14,7 @@ pub const STRIP_PRIVATE: Pass = Pass {
/// Strip private items from the point of view of a crate or externally from a /// Strip private items from the point of view of a crate or externally from a
/// crate, specified by the `xcrate` flag. /// crate, specified by the `xcrate` flag.
pub fn strip_private(mut krate: clean::Crate, cx: &DocContext<'_>) -> clean::Crate { crate fn strip_private(mut krate: clean::Crate, cx: &DocContext<'_>) -> clean::Crate {
// This stripper collects all *retained* nodes. // This stripper collects all *retained* nodes.
let mut retained = DefIdSet::default(); let mut retained = DefIdSet::default();
let access_levels = cx.renderinfo.borrow().access_levels.clone(); let access_levels = cx.renderinfo.borrow().access_levels.clone();

View File

@ -5,10 +5,10 @@ use std::mem;
use crate::clean::{self, GetDefId, Item}; use crate::clean::{self, GetDefId, Item};
use crate::fold::{DocFolder, StripItem}; use crate::fold::{DocFolder, StripItem};
pub struct Stripper<'a> { crate struct Stripper<'a> {
pub retained: &'a mut DefIdSet, crate retained: &'a mut DefIdSet,
pub access_levels: &'a AccessLevels<DefId>, crate access_levels: &'a AccessLevels<DefId>,
pub update_retained: bool, crate update_retained: bool,
} }
impl<'a> DocFolder for Stripper<'a> { impl<'a> DocFolder for Stripper<'a> {
@ -117,8 +117,8 @@ impl<'a> DocFolder for Stripper<'a> {
} }
/// This stripper discards all impls which reference stripped items /// This stripper discards all impls which reference stripped items
pub struct ImplStripper<'a> { crate struct ImplStripper<'a> {
pub retained: &'a DefIdSet, crate retained: &'a DefIdSet,
} }
impl<'a> DocFolder for ImplStripper<'a> { impl<'a> DocFolder for ImplStripper<'a> {
@ -158,7 +158,7 @@ impl<'a> DocFolder for ImplStripper<'a> {
} }
/// This stripper discards all private import statements (`use`, `extern crate`) /// This stripper discards all private import statements (`use`, `extern crate`)
pub struct ImportStripper; crate struct ImportStripper;
impl DocFolder for ImportStripper { impl DocFolder for ImportStripper {
fn fold_item(&mut self, i: Item) -> Option<Item> { fn fold_item(&mut self, i: Item) -> Option<Item> {

View File

@ -8,13 +8,13 @@ use crate::passes::Pass;
#[cfg(test)] #[cfg(test)]
mod tests; mod tests;
pub const UNINDENT_COMMENTS: Pass = Pass { crate const UNINDENT_COMMENTS: Pass = Pass {
name: "unindent-comments", name: "unindent-comments",
run: unindent_comments, run: unindent_comments,
description: "removes excess indentation on comments in order for markdown to like it", description: "removes excess indentation on comments in order for markdown to like it",
}; };
pub fn unindent_comments(krate: clean::Crate, _: &DocContext<'_>) -> clean::Crate { crate fn unindent_comments(krate: clean::Crate, _: &DocContext<'_>) -> clean::Crate {
CommentCleaner.fold_crate(krate) CommentCleaner.fold_crate(krate)
} }
@ -28,7 +28,7 @@ impl fold::DocFolder for CommentCleaner {
} }
impl clean::Attributes { impl clean::Attributes {
pub fn unindent_doc_comments(&mut self) { crate fn unindent_doc_comments(&mut self) {
unindent_fragments(&mut self.doc_strings); unindent_fragments(&mut self.doc_strings);
} }
} }

View File

@ -9,9 +9,9 @@ use rustc_errors::Handler;
mod tests; mod tests;
#[derive(Debug, Clone, Eq)] #[derive(Debug, Clone, Eq)]
pub struct CssPath { crate struct CssPath {
pub name: String, crate name: String,
pub children: FxHashSet<CssPath>, crate children: FxHashSet<CssPath>,
} }
// This PartialEq implementation IS NOT COMMUTATIVE!!! // This PartialEq implementation IS NOT COMMUTATIVE!!!
@ -212,7 +212,7 @@ fn inner(v: &[u8], events: &[Events], pos: &mut usize) -> FxHashSet<CssPath> {
paths.iter().cloned().collect() paths.iter().cloned().collect()
} }
pub fn load_css_paths(v: &[u8]) -> CssPath { crate fn load_css_paths(v: &[u8]) -> CssPath {
let events = load_css_events(v); let events = load_css_events(v);
let mut pos = 0; let mut pos = 0;
@ -221,7 +221,7 @@ pub fn load_css_paths(v: &[u8]) -> CssPath {
parent parent
} }
pub fn get_differences(against: &CssPath, other: &CssPath, v: &mut Vec<String>) { crate fn get_differences(against: &CssPath, other: &CssPath, v: &mut Vec<String>) {
if against.name == other.name { if against.name == other.name {
for child in &against.children { for child in &against.children {
let mut found = false; let mut found = false;
@ -248,7 +248,7 @@ pub fn get_differences(against: &CssPath, other: &CssPath, v: &mut Vec<String>)
} }
} }
pub fn test_theme_against<P: AsRef<Path>>( crate fn test_theme_against<P: AsRef<Path>>(
f: &P, f: &P,
against: &CssPath, against: &CssPath,
diag: &Handler, diag: &Handler,

View File

@ -34,7 +34,7 @@ fn def_id_to_path(tcx: TyCtxt<'_>, did: DefId) -> Vec<String> {
// Also, is there some reason that this doesn't use the 'visit' // Also, is there some reason that this doesn't use the 'visit'
// framework from syntax?. // framework from syntax?.
pub struct RustdocVisitor<'a, 'tcx> { crate struct RustdocVisitor<'a, 'tcx> {
cx: &'a mut core::DocContext<'tcx>, cx: &'a mut core::DocContext<'tcx>,
view_item_stack: FxHashSet<hir::HirId>, view_item_stack: FxHashSet<hir::HirId>,
inlining: bool, inlining: bool,
@ -44,7 +44,7 @@ pub struct RustdocVisitor<'a, 'tcx> {
} }
impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
pub fn new(cx: &'a mut core::DocContext<'tcx>) -> RustdocVisitor<'a, 'tcx> { crate fn new(cx: &'a mut core::DocContext<'tcx>) -> RustdocVisitor<'a, 'tcx> {
// If the root is re-exported, terminate all recursion. // If the root is re-exported, terminate all recursion.
let mut stack = FxHashSet::default(); let mut stack = FxHashSet::default();
stack.insert(hir::CRATE_HIR_ID); stack.insert(hir::CRATE_HIR_ID);
@ -62,7 +62,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
self.exact_paths.entry(did).or_insert_with(|| def_id_to_path(tcx, did)); self.exact_paths.entry(did).or_insert_with(|| def_id_to_path(tcx, did));
} }
pub fn visit(mut self, krate: &'tcx hir::Crate<'_>) -> Module<'tcx> { crate fn visit(mut self, krate: &'tcx hir::Crate<'_>) -> Module<'tcx> {
let mut module = self.visit_mod_contents( let mut module = self.visit_mod_contents(
krate.item.span, krate.item.span,
krate.item.attrs, krate.item.attrs,
@ -251,7 +251,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
om om
} }
/// Tries to resolve the target of a `pub use` statement and inlines the /// Tries to resolve the target of a `crate use` statement and inlines the
/// target if it is defined locally and would not be documented otherwise, /// target if it is defined locally and would not be documented otherwise,
/// or when it is specifically requested with `please_inline`. /// or when it is specifically requested with `please_inline`.
/// (the latter is the case when the import is marked `doc(inline)`) /// (the latter is the case when the import is marked `doc(inline)`)

View File

@ -11,7 +11,7 @@ use crate::clean::{AttributesExt, NestedAttributesExt};
/// Similar to `librustc_privacy::EmbargoVisitor`, but also takes /// Similar to `librustc_privacy::EmbargoVisitor`, but also takes
/// specific rustdoc annotations into account (i.e., `doc(hidden)`) /// specific rustdoc annotations into account (i.e., `doc(hidden)`)
pub struct LibEmbargoVisitor<'a, 'tcx> { crate struct LibEmbargoVisitor<'a, 'tcx> {
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
// Accessibility levels for reachable nodes // Accessibility levels for reachable nodes
access_levels: &'a mut AccessLevels<DefId>, access_levels: &'a mut AccessLevels<DefId>,
@ -22,7 +22,7 @@ pub struct LibEmbargoVisitor<'a, 'tcx> {
} }
impl<'a, 'tcx> LibEmbargoVisitor<'a, 'tcx> { impl<'a, 'tcx> LibEmbargoVisitor<'a, 'tcx> {
pub fn new(cx: &'a mut crate::core::DocContext<'tcx>) -> LibEmbargoVisitor<'a, 'tcx> { crate fn new(cx: &'a mut crate::core::DocContext<'tcx>) -> LibEmbargoVisitor<'a, 'tcx> {
LibEmbargoVisitor { LibEmbargoVisitor {
tcx: cx.tcx, tcx: cx.tcx,
access_levels: &mut cx.renderinfo.get_mut().access_levels, access_levels: &mut cx.renderinfo.get_mut().access_levels,
@ -31,7 +31,7 @@ impl<'a, 'tcx> LibEmbargoVisitor<'a, 'tcx> {
} }
} }
pub fn visit_lib(&mut self, cnum: CrateNum) { crate fn visit_lib(&mut self, cnum: CrateNum) {
let did = DefId { krate: cnum, index: CRATE_DEF_INDEX }; let did = DefId { krate: cnum, index: CRATE_DEF_INDEX };
self.update(did, Some(AccessLevel::Public)); self.update(did, Some(AccessLevel::Public));
self.visit_mod(did); self.visit_mod(did);
@ -51,7 +51,7 @@ impl<'a, 'tcx> LibEmbargoVisitor<'a, 'tcx> {
} }
} }
pub fn visit_mod(&mut self, def_id: DefId) { crate fn visit_mod(&mut self, def_id: DefId) {
if !self.visited_mods.insert(def_id) { if !self.visited_mods.insert(def_id) {
return; return;
} }