Skip to content

Commit

Permalink
Remove rustdoc clean::Visibility type
Browse files Browse the repository at this point in the history
  • Loading branch information
GuillaumeGomez committed Nov 3, 2022
1 parent 432b1a4 commit df32694
Show file tree
Hide file tree
Showing 9 changed files with 129 additions and 153 deletions.
5 changes: 2 additions & 3 deletions src/librustdoc/clean/inline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,7 @@ use rustc_span::symbol::{kw, sym, Symbol};
use crate::clean::{
self, clean_fn_decl_from_did_and_sig, clean_generics, clean_impl_item, clean_middle_assoc_item,
clean_middle_field, clean_middle_ty, clean_trait_ref_with_bindings, clean_ty,
clean_ty_generics, clean_variant_def, clean_visibility, utils, Attributes, AttributesExt,
ImplKind, ItemId, Type,
clean_ty_generics, clean_variant_def, utils, Attributes, AttributesExt, ImplKind, ItemId, Type,
};
use crate::core::DocContext;
use crate::formats::item_type::ItemType;
Expand Down Expand Up @@ -654,7 +653,7 @@ fn build_macro(
match CStore::from_tcx(cx.tcx).load_macro_untracked(def_id, cx.sess()) {
LoadedMacro::MacroDef(item_def, _) => {
if let ast::ItemKind::MacroDef(ref def) = item_def.kind {
let vis = clean_visibility(cx.tcx.visibility(import_def_id.unwrap_or(def_id)));
let vis = cx.tcx.visibility(import_def_id.unwrap_or(def_id));
clean::MacroItem(clean::Macro {
source: utils::display_macro_source(cx, name, def, def_id, vis),
})
Expand Down
9 changes: 1 addition & 8 deletions src/librustdoc/clean/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1799,13 +1799,6 @@ pub(crate) fn clean_field_with_def_id(
Item::from_def_id_and_parts(def_id, Some(name), StructFieldItem(ty), cx)
}

pub(crate) fn clean_visibility(vis: ty::Visibility<DefId>) -> Visibility {
match vis {
ty::Visibility::Public => Visibility::Public,
ty::Visibility::Restricted(module) => Visibility::Restricted(module),
}
}

pub(crate) fn clean_variant_def<'tcx>(variant: &ty::VariantDef, cx: &mut DocContext<'tcx>) -> Item {
let kind = match variant.ctor_kind {
CtorKind::Const => Variant::CLike(match variant.discr {
Expand Down Expand Up @@ -1962,7 +1955,7 @@ fn clean_maybe_renamed_item<'tcx>(
clean_fn_or_proc_macro(item, sig, generics, body_id, &mut name, cx)
}
ItemKind::Macro(ref macro_def, _) => {
let ty_vis = clean_visibility(cx.tcx.visibility(def_id));
let ty_vis = cx.tcx.visibility(def_id);
MacroItem(Macro {
source: display_macro_source(cx, name, macro_def, def_id, ty_vis),
})
Expand Down
40 changes: 11 additions & 29 deletions src/librustdoc/clean/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ use rustc_hir::{BodyId, Mutability};
use rustc_hir_analysis::check::intrinsic::intrinsic_operation_unsafety;
use rustc_index::vec::IndexVec;
use rustc_middle::ty::fast_reject::SimplifiedType;
use rustc_middle::ty::{self, DefIdTree, TyCtxt};
use rustc_middle::ty::{self, DefIdTree, TyCtxt, Visibility};
use rustc_session::Session;
use rustc_span::hygiene::MacroKind;
use rustc_span::source_map::DUMMY_SP;
Expand All @@ -34,7 +34,6 @@ use rustc_target::abi::VariantIdx;
use rustc_target::spec::abi::Abi;

use crate::clean::cfg::Cfg;
use crate::clean::clean_visibility;
use crate::clean::external_path;
use crate::clean::inline::{self, print_inlined_const};
use crate::clean::utils::{is_literal_expr, print_const_expr, print_evaluated_const};
Expand All @@ -51,7 +50,6 @@ pub(crate) use self::Type::{
Array, BareFunction, BorrowedRef, DynTrait, Generic, ImplTrait, Infer, Primitive, QPath,
RawPointer, Slice, Tuple,
};
pub(crate) use self::Visibility::{Inherited, Public};

#[cfg(test)]
mod tests;
Expand Down Expand Up @@ -706,26 +704,28 @@ impl Item {
Some(header)
}

pub(crate) fn visibility(&self, tcx: TyCtxt<'_>) -> Visibility {
/// Returns the visibility of the current item. If the visibility is "inherited", then `None`
/// is returned.
pub(crate) fn visibility(&self, tcx: TyCtxt<'_>) -> Option<Visibility<DefId>> {
let def_id = match self.item_id {
// Anything but DefId *shouldn't* matter, but return a reasonable value anyway.
ItemId::Auto { .. } | ItemId::Blanket { .. } => return Visibility::Inherited,
ItemId::Auto { .. } | ItemId::Blanket { .. } => return None,
// Primitives and Keywords are written in the source code as private modules.
// The modules need to be private so that nobody actually uses them, but the
// keywords and primitives that they are documenting are public.
ItemId::Primitive(..) => return Visibility::Public,
ItemId::Primitive(..) => return Some(Visibility::Public),
ItemId::DefId(def_id) => def_id,
};

match *self.kind {
// Explication on `ItemId::Primitive` just above.
ItemKind::KeywordItem | ItemKind::PrimitiveItem(_) => return Visibility::Public,
ItemKind::KeywordItem | ItemKind::PrimitiveItem(_) => return Some(Visibility::Public),
// Variant fields inherit their enum's visibility.
StructFieldItem(..) if is_field_vis_inherited(tcx, def_id) => {
return Visibility::Inherited;
return None;
}
// Variants always inherit visibility
VariantItem(..) => return Visibility::Inherited,
VariantItem(..) => return None,
// Trait items inherit the trait's visibility
AssocConstItem(..) | TyAssocConstItem(..) | AssocTypeItem(..) | TyAssocTypeItem(..)
| TyMethodItem(..) | MethodItem(..) => {
Expand All @@ -739,7 +739,7 @@ impl Item {
}
};
if is_trait_item {
return Visibility::Inherited;
return None;
}
}
_ => {}
Expand All @@ -748,7 +748,7 @@ impl Item {
Some(inlined) => inlined,
None => def_id,
};
clean_visibility(tcx.visibility(def_id))
Some(tcx.visibility(def_id))
}
}

Expand Down Expand Up @@ -2078,24 +2078,6 @@ impl From<hir::PrimTy> for PrimitiveType {
}
}

#[derive(Copy, Clone, Debug)]
pub(crate) enum Visibility {
/// `pub`
Public,
/// Visibility inherited from parent.
///
/// For example, this is the visibility of private items and of enum variants.
Inherited,
/// `pub(crate)`, `pub(super)`, or `pub(in path::to::somewhere)`
Restricted(DefId),
}

impl Visibility {
pub(crate) fn is_public(&self) -> bool {
matches!(self, Visibility::Public)
}
}

#[derive(Clone, Debug)]
pub(crate) struct Struct {
pub(crate) struct_type: CtorKind,
Expand Down
9 changes: 5 additions & 4 deletions src/librustdoc/clean/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@ use crate::clean::render_macro_matchers::render_macro_matcher;
use crate::clean::{
clean_doc_module, clean_middle_const, clean_middle_region, clean_middle_ty, inline, Crate,
ExternalCrate, Generic, GenericArg, GenericArgs, ImportSource, Item, ItemKind, Lifetime, Path,
PathSegment, Primitive, PrimitiveType, Type, TypeBinding, Visibility,
PathSegment, Primitive, PrimitiveType, Type, TypeBinding,
};
use crate::core::DocContext;
use crate::html::format::visibility_to_src_with_space;

use rustc_ast as ast;
use rustc_ast::tokenstream::TokenTree;
Expand Down Expand Up @@ -583,7 +584,7 @@ pub(super) fn display_macro_source(
name: Symbol,
def: &ast::MacroDef,
def_id: DefId,
vis: Visibility,
vis: ty::Visibility<DefId>,
) -> String {
let tts: Vec<_> = def.body.inner_tokens().into_trees().collect();
// Extract the spans of all matchers. They represent the "interface" of the macro.
Expand All @@ -595,14 +596,14 @@ pub(super) fn display_macro_source(
if matchers.len() <= 1 {
format!(
"{}macro {}{} {{\n ...\n}}",
vis.to_src_with_space(cx.tcx, def_id),
visibility_to_src_with_space(Some(vis), cx.tcx, def_id),
name,
matchers.map(|matcher| render_macro_matcher(cx.tcx, matcher)).collect::<String>(),
)
} else {
format!(
"{}macro {} {{\n{}}}",
vis.to_src_with_space(cx.tcx, def_id),
visibility_to_src_with_space(Some(vis), cx.tcx, def_id),
name,
render_macro_arms(cx.tcx, matchers, ","),
)
Expand Down
151 changes: 74 additions & 77 deletions src/librustdoc/html/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1420,87 +1420,84 @@ impl clean::FnDecl {
}
}

impl clean::Visibility {
pub(crate) fn print_with_space<'a, 'tcx: 'a>(
self,
item_did: ItemId,
cx: &'a Context<'tcx>,
) -> impl fmt::Display + 'a + Captures<'tcx> {
use std::fmt::Write as _;

let to_print: Cow<'static, str> = match self {
clean::Public => "pub ".into(),
clean::Inherited => "".into(),
clean::Visibility::Restricted(vis_did) => {
// FIXME(camelid): This may not work correctly if `item_did` is a module.
// However, rustdoc currently never displays a module's
// visibility, so it shouldn't matter.
let parent_module = find_nearest_parent_module(cx.tcx(), item_did.expect_def_id());

if vis_did.is_crate_root() {
"pub(crate) ".into()
} else if parent_module == Some(vis_did) {
// `pub(in foo)` where `foo` is the parent module
// is the same as no visibility modifier
"".into()
} else if parent_module
.and_then(|parent| find_nearest_parent_module(cx.tcx(), parent))
== Some(vis_did)
{
"pub(super) ".into()
} else {
let path = cx.tcx().def_path(vis_did);
debug!("path={:?}", path);
// modified from `resolved_path()` to work with `DefPathData`
let last_name = path.data.last().unwrap().data.get_opt_name().unwrap();
let anchor = anchor(vis_did, last_name, cx).to_string();

let mut s = "pub(in ".to_owned();
for seg in &path.data[..path.data.len() - 1] {
let _ = write!(s, "{}::", seg.data.get_opt_name().unwrap());
}
let _ = write!(s, "{}) ", anchor);
s.into()
pub(crate) fn visibility_print_with_space<'a, 'tcx: 'a>(
visibility: Option<ty::Visibility<DefId>>,
item_did: ItemId,
cx: &'a Context<'tcx>,
) -> impl fmt::Display + 'a + Captures<'tcx> {
use std::fmt::Write as _;

let to_print: Cow<'static, str> = match visibility {
None => "".into(),
Some(ty::Visibility::Public) => "pub ".into(),
Some(ty::Visibility::Restricted(vis_did)) => {
// FIXME(camelid): This may not work correctly if `item_did` is a module.
// However, rustdoc currently never displays a module's
// visibility, so it shouldn't matter.
let parent_module = find_nearest_parent_module(cx.tcx(), item_did.expect_def_id());

if vis_did.is_crate_root() {
"pub(crate) ".into()
} else if parent_module == Some(vis_did) {
// `pub(in foo)` where `foo` is the parent module
// is the same as no visibility modifier
"".into()
} else if parent_module.and_then(|parent| find_nearest_parent_module(cx.tcx(), parent))
== Some(vis_did)
{
"pub(super) ".into()
} else {
let path = cx.tcx().def_path(vis_did);
debug!("path={:?}", path);
// modified from `resolved_path()` to work with `DefPathData`
let last_name = path.data.last().unwrap().data.get_opt_name().unwrap();
let anchor = anchor(vis_did, last_name, cx).to_string();

let mut s = "pub(in ".to_owned();
for seg in &path.data[..path.data.len() - 1] {
let _ = write!(s, "{}::", seg.data.get_opt_name().unwrap());
}
let _ = write!(s, "{}) ", anchor);
s.into()
}
};
display_fn(move |f| write!(f, "{}", to_print))
}
}
};
display_fn(move |f| write!(f, "{}", to_print))
}

/// This function is the same as print_with_space, except that it renders no links.
/// It's used for macros' rendered source view, which is syntax highlighted and cannot have
/// any HTML in it.
pub(crate) fn to_src_with_space<'a, 'tcx: 'a>(
self,
tcx: TyCtxt<'tcx>,
item_did: DefId,
) -> impl fmt::Display + 'a + Captures<'tcx> {
let to_print = match self {
clean::Public => "pub ".to_owned(),
clean::Inherited => String::new(),
clean::Visibility::Restricted(vis_did) => {
// FIXME(camelid): This may not work correctly if `item_did` is a module.
// However, rustdoc currently never displays a module's
// visibility, so it shouldn't matter.
let parent_module = find_nearest_parent_module(tcx, item_did);

if vis_did.is_crate_root() {
"pub(crate) ".to_owned()
} else if parent_module == Some(vis_did) {
// `pub(in foo)` where `foo` is the parent module
// is the same as no visibility modifier
String::new()
} else if parent_module.and_then(|parent| find_nearest_parent_module(tcx, parent))
== Some(vis_did)
{
"pub(super) ".to_owned()
} else {
format!("pub(in {}) ", tcx.def_path_str(vis_did))
}
/// This function is the same as print_with_space, except that it renders no links.
/// It's used for macros' rendered source view, which is syntax highlighted and cannot have
/// any HTML in it.
pub(crate) fn visibility_to_src_with_space<'a, 'tcx: 'a>(
visibility: Option<ty::Visibility<DefId>>,
tcx: TyCtxt<'tcx>,
item_did: DefId,
) -> impl fmt::Display + 'a + Captures<'tcx> {
let to_print = match visibility {
None => String::new(),
Some(ty::Visibility::Public) => "pub ".to_owned(),
Some(ty::Visibility::Restricted(vis_did)) => {
// FIXME(camelid): This may not work correctly if `item_did` is a module.
// However, rustdoc currently never displays a module's
// visibility, so it shouldn't matter.
let parent_module = find_nearest_parent_module(tcx, item_did);

if vis_did.is_crate_root() {
"pub(crate) ".to_owned()
} else if parent_module == Some(vis_did) {
// `pub(in foo)` where `foo` is the parent module
// is the same as no visibility modifier
String::new()
} else if parent_module.and_then(|parent| find_nearest_parent_module(tcx, parent))
== Some(vis_did)
{
"pub(super) ".to_owned()
} else {
format!("pub(in {}) ", tcx.def_path_str(vis_did))
}
};
display_fn(move |f| f.write_str(&to_print))
}
}
};
display_fn(move |f| f.write_str(&to_print))
}

pub(crate) trait PrintWithSpace {
Expand Down
8 changes: 4 additions & 4 deletions src/librustdoc/html/render/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,8 @@ use crate::formats::{AssocItemRender, Impl, RenderMode};
use crate::html::escape::Escape;
use crate::html::format::{
href, join_with_double_colon, print_abi_with_space, print_constness_with_space,
print_default_space, print_generic_bounds, print_where_clause, Buffer, Ending, HrefError,
PrintWithSpace,
print_default_space, print_generic_bounds, print_where_clause, visibility_print_with_space,
Buffer, Ending, HrefError, PrintWithSpace,
};
use crate::html::highlight;
use crate::html::markdown::{
Expand Down Expand Up @@ -752,7 +752,7 @@ fn assoc_const(
w,
"{extra}{vis}const <a{href} class=\"constant\">{name}</a>: {ty}",
extra = extra,
vis = it.visibility(tcx).print_with_space(it.item_id, cx),
vis = visibility_print_with_space(it.visibility(tcx), it.item_id, cx),
href = assoc_href_attr(it, link, cx),
name = it.name.as_ref().unwrap(),
ty = ty.print(cx),
Expand Down Expand Up @@ -809,7 +809,7 @@ fn assoc_method(
let tcx = cx.tcx();
let header = meth.fn_header(tcx).expect("Trying to get header from a non-function item");
let name = meth.name.as_ref().unwrap();
let vis = meth.visibility(tcx).print_with_space(meth.item_id, cx).to_string();
let vis = visibility_print_with_space(meth.visibility(tcx), meth.item_id, cx).to_string();
// FIXME: Once https://github.com/rust-lang/rust/issues/67792 is implemented, we can remove
// this condition.
let constness = match render_mode {
Expand Down
Loading

0 comments on commit df32694

Please sign in to comment.