Skip to content

Add an item-info for non-public visibility, and remove redundant pub #90242

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
131 changes: 71 additions & 60 deletions src/librustdoc/html/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1221,50 +1221,80 @@ impl clean::FnDecl {
}
}

pub(crate) enum VisibilityScope {
Inherited,
Crate,
Super,
Path(Vec<String>),
}

impl VisibilityScope {
crate fn new<'tcx>(vis_did: DefId, item_did: DefId, tcx: TyCtxt<'tcx>) -> VisibilityScope {
// 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.index == CRATE_DEF_INDEX {
VisibilityScope::Crate
} else if parent_module == Some(vis_did) {
// `pub(in foo)` where `foo` is the parent module
// is the same as no visibility modifier
VisibilityScope::Inherited
} else if parent_module.map(|parent| find_nearest_parent_module(tcx, parent)).flatten()
== Some(vis_did)
{
VisibilityScope::Super
} else {
let path = tcx.def_path(vis_did);
debug!("path={:?}", path);
let mut components: Vec<String> = vec![];
for seg in &path.data {
components.push(seg.data.get_opt_name().unwrap().to_string());
}
VisibilityScope::Path(components)
}
}
}

impl fmt::Display for VisibilityScope {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
VisibilityScope::Inherited => f.write_str(""),
VisibilityScope::Crate => f.write_str("crate"),
VisibilityScope::Super => f.write_str("super"),
VisibilityScope::Path(components) => {
f.write_str("in ")?;
for (i, c) in components.iter().enumerate() {
if i > 0 {
f.write_str("::")?;
}
f.write_str(c)?;
}
Ok(())
}
}
}
}

impl clean::Visibility {
crate fn print_with_space<'a, 'tcx: 'a>(
self,
item_did: ItemId,
cx: &'a Context<'tcx>,
) -> impl fmt::Display + 'a + Captures<'tcx> {
let to_print = match self {
clean::Public => "pub ".to_owned(),
clean::Inherited => String::new(),
display_fn(move |f| match self {
clean::Public => write!(f, "pub "),
clean::Inherited => write!(f, ""),
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.index == CRATE_DEF_INDEX {
"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
.map(|parent| find_nearest_parent_module(cx.tcx(), parent))
.flatten()
== Some(vis_did)
{
"pub(super) ".to_owned()
} 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.as_str(), cx).to_string();

let mut s = "pub(in ".to_owned();
for seg in &path.data[..path.data.len() - 1] {
s.push_str(&format!("{}::", seg.data.get_opt_name().unwrap()));
}
s.push_str(&format!("{}) ", anchor));
s
let mut scope = VisibilityScope::new(vis_did, item_did.expect_def_id(), cx.tcx());
if let VisibilityScope::Path(ref mut components) = scope {
let last_name = components.pop().unwrap();
components.push(anchor(vis_did, &last_name.as_str(), cx).to_string());
}
write!(f, "pub({}) ", scope)
}
};
display_fn(move |f| f.write_str(&to_print))
})
}

/// This function is the same as print_with_space, except that it renders no links.
Expand All @@ -1275,33 +1305,14 @@ impl clean::Visibility {
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(),
display_fn(move |f| match self {
clean::Public => write!(f, "pub "),
clean::Inherited => write!(f, ""),
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.index == CRATE_DEF_INDEX {
"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
.map(|parent| find_nearest_parent_module(tcx, parent))
.flatten()
== Some(vis_did)
{
"pub(super) ".to_owned()
} else {
format!("pub(in {}) ", tcx.def_path_str(vis_did))
}
let scope = VisibilityScope::new(vis_did, item_did, tcx);
write!(f, "pub({}) ", scope)
}
};
display_fn(move |f| f.write_str(&to_print))
})
}
}

Expand Down
56 changes: 51 additions & 5 deletions src/librustdoc/html/render/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ use crate::formats::{AssocItemRender, Impl, RenderMode};
use crate::html::escape::Escape;
use crate::html::format::{
href, print_abi_with_space, print_constness_with_space, print_default_space,
print_generic_bounds, print_where_clause, Buffer, HrefError, PrintWithSpace,
print_generic_bounds, print_where_clause, Buffer, HrefError, PrintWithSpace, VisibilityScope,
};
use crate::html::markdown::{HeadingOffset, Markdown, MarkdownHtml, MarkdownSummaryLine};

Expand Down Expand Up @@ -589,6 +589,7 @@ fn document_full_inner(

/// Add extra information about an item such as:
///
/// * Visibility
/// * Stability
/// * Deprecated
/// * Required features (through the `doc_cfg` feature)
Expand Down Expand Up @@ -619,6 +620,49 @@ fn portability(item: &clean::Item, parent: Option<&clean::Item>) -> Option<Strin
Some(format!("<div class=\"stab portability\">{}</div>", cfg?.render_long_html()))
}

fn visibility(
item: &clean::Item,
cx: &Context<'_>,
parent: Option<&clean::Item>,
) -> Option<String> {
// For now, we only render visibility tags for methods and struct fields.
match *item.kind {
clean::ItemKind::MethodItem(_, _) | clean::ItemKind::StructFieldItem(_) => {}
_ => return None,
}

fn tag(contents: impl fmt::Display) -> Option<String> {
Some(format!(
r#"<div class="visibility"><span class="emoji">🙈</span> Visibility: {}</div>"#,
contents
))
}
const PRIVATE: &str = "private";

use clean::ItemKind::*;
use clean::Visibility::*;

match item.visibility {
Public => None,
// By default, everything in Rust is private, with two exceptions:
// Associated items in a pub Trait are public by default;
// Enum variants in a pub enum are also public by default.
// https://doc.rust-lang.org/reference/visibility-and-privacy.html
// Therefore we don't put "private" annotations on traits, trait impls,
// or enum variant fields.
Inherited => match parent.map(|p| &*p.kind) {
Some(TraitItem(_) | ImplItem(_) | VariantItem(_)) => None,
_ => tag(PRIVATE),
},
Restricted(vis_did) => {
match VisibilityScope::new(vis_did, item.def_id.expect_def_id(), cx.tcx()) {
VisibilityScope::Inherited => tag(PRIVATE),
scope => tag(scope),
}
}
}
}

/// Render the stability, deprecation and portability information that is displayed at the top of
/// the item's documentation.
fn short_item_info(
Expand All @@ -629,6 +673,10 @@ fn short_item_info(
let mut extra_info = vec![];
let error_codes = cx.shared.codes;

if let Some(visibility) = visibility(item, cx, parent) {
extra_info.push(visibility)
}

if let Some(depr @ Deprecation { note, since, is_since_rustc_version: _, suggestion: _ }) =
item.deprecation(cx.tcx())
{
Expand Down Expand Up @@ -903,7 +951,6 @@ fn render_assoc_item(
}
}
};
let vis = meth.visibility.print_with_space(meth.def_id, cx).to_string();
let constness =
print_constness_with_space(&header.constness, meth.const_stability(cx.tcx()));
let asyncness = header.asyncness.print_with_space();
Expand All @@ -914,7 +961,6 @@ fn render_assoc_item(
// NOTE: `{:#}` does not print HTML formatting, `{}` does. So `g.print` can't be reused between the length calculation and `write!`.
let generics_len = format!("{:#}", g.print(cx)).len();
let mut header_len = "fn ".len()
+ vis.len()
+ constness.len()
+ asyncness.len()
+ unsafety.len()
Expand All @@ -935,10 +981,9 @@ fn render_assoc_item(
w.reserve(header_len + "<a href=\"\" class=\"fnname\">{".len() + "</a>".len());
write!(
w,
"{indent}{vis}{constness}{asyncness}{unsafety}{defaultness}{abi}fn <a {href} class=\"fnname\">{name}</a>\
"{indent}{constness}{asyncness}{unsafety}{defaultness}{abi}fn <a {href} class=\"fnname\">{name}</a>\
{generics}{decl}{notable_traits}{where_clause}",
indent = indent_str,
vis = vis,
constness = constness,
asyncness = asyncness,
unsafety = unsafety,
Expand Down Expand Up @@ -1477,6 +1522,7 @@ fn render_impl(
}

w.push_buffer(info_buffer);

if toggled {
w.write_str("</summary>");
w.push_buffer(doc_buffer);
Expand Down
9 changes: 6 additions & 3 deletions src/librustdoc/html/static/css/rustdoc.css
Original file line number Diff line number Diff line change
Expand Up @@ -956,10 +956,12 @@ body.blur > :not(#help) {
padding: 0 20px 20px 17px;;
}

.item-info .stab {
.item-info .stab,
.item-info .visibility {
display: table;
}
.stab {
.stab,
.visibility {
border-width: 1px;
border-style: solid;
padding: 3px;
Expand All @@ -971,7 +973,8 @@ body.blur > :not(#help) {
display: inline;
}

.stab .emoji {
.stab .emoji
.visibility .emoji {
font-size: 1.5em;
}

Expand Down
1 change: 1 addition & 0 deletions src/librustdoc/html/static/css/themes/light.css
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,7 @@ details.undocumented > summary::before {
color: #000;
}

.visibility { background: #FFF5D6; border-color: #FFC600; }
.stab.unstable { background: #FFF5D6; border-color: #FFC600; }
.stab.deprecated { background: #ffc4c4; border-color: #db7b7b; }
.stab.portability { background: #F3DFFF; border-color: #b07bdb; }
Expand Down
Loading