Refactor visibility_print_with_space to directly take an item

This commit is contained in:
Manish Goregaokar 2024-03-14 12:39:27 +01:00
parent 8da262139a
commit 343c77c102
7 changed files with 42 additions and 51 deletions

View File

@ -62,6 +62,9 @@ pub(crate) fn try_inline(
attrs_without_docs.as_ref().map(|(attrs, def_id)| (&attrs[..], *def_id)); attrs_without_docs.as_ref().map(|(attrs, def_id)| (&attrs[..], *def_id));
let import_def_id = attrs.and_then(|(_, def_id)| def_id); let import_def_id = attrs.and_then(|(_, def_id)| def_id);
let (attrs, cfg) = merge_attrs(cx, load_attrs(cx, did), attrs);
let kind = match res { let kind = match res {
Res::Def(DefKind::Trait, did) => { Res::Def(DefKind::Trait, did) => {
record_extern_fqn(cx, did, ItemType::Trait); record_extern_fqn(cx, did, ItemType::Trait);
@ -131,7 +134,7 @@ pub(crate) fn try_inline(
cx.with_param_env(did, |cx| clean::ConstantItem(build_const(cx, did))) cx.with_param_env(did, |cx| clean::ConstantItem(build_const(cx, did)))
} }
Res::Def(DefKind::Macro(kind), did) => { Res::Def(DefKind::Macro(kind), did) => {
let mac = build_macro(cx, did, name, import_def_id, kind); let mac = build_macro(cx, did, name, import_def_id, kind, attrs.is_doc_hidden());
let type_kind = match kind { let type_kind = match kind {
MacroKind::Bang => ItemType::Macro, MacroKind::Bang => ItemType::Macro,
@ -144,7 +147,6 @@ pub(crate) fn try_inline(
_ => return None, _ => return None,
}; };
let (attrs, cfg) = merge_attrs(cx, load_attrs(cx, did), attrs);
cx.inlined.insert(did.into()); cx.inlined.insert(did.into());
let mut item = let mut item =
clean::Item::from_def_id_and_attrs_and_parts(did, Some(name), kind, Box::new(attrs), cfg); clean::Item::from_def_id_and_attrs_and_parts(did, Some(name), kind, Box::new(attrs), cfg);
@ -751,6 +753,7 @@ fn build_macro(
name: Symbol, name: Symbol,
import_def_id: Option<DefId>, import_def_id: Option<DefId>,
macro_kind: MacroKind, macro_kind: MacroKind,
is_doc_hidden: bool,
) -> clean::ItemKind { ) -> clean::ItemKind {
match CStore::from_tcx(cx.tcx).load_macro_untracked(def_id, cx.tcx) { match CStore::from_tcx(cx.tcx).load_macro_untracked(def_id, cx.tcx) {
LoadedMacro::MacroDef(item_def, _) => match macro_kind { LoadedMacro::MacroDef(item_def, _) => match macro_kind {
@ -758,7 +761,14 @@ fn build_macro(
if let ast::ItemKind::MacroDef(ref def) = item_def.kind { if let ast::ItemKind::MacroDef(ref def) = item_def.kind {
let vis = 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 { clean::MacroItem(clean::Macro {
source: utils::display_macro_source(cx, name, def, def_id, vis), source: utils::display_macro_source(
cx,
name,
def,
def_id,
vis,
is_doc_hidden,
),
}) })
} else { } else {
unreachable!() unreachable!()

View File

@ -2796,7 +2796,8 @@ fn clean_maybe_renamed_item<'tcx>(
ItemKind::Macro(ref macro_def, MacroKind::Bang) => { ItemKind::Macro(ref macro_def, MacroKind::Bang) => {
let ty_vis = cx.tcx.visibility(def_id); let ty_vis = cx.tcx.visibility(def_id);
MacroItem(Macro { MacroItem(Macro {
source: display_macro_source(cx, name, macro_def, def_id, ty_vis), // FIXME this shouldn't be false
source: display_macro_source(cx, name, macro_def, def_id, ty_vis, false),
}) })
} }
ItemKind::Macro(_, macro_kind) => clean_proc_macro(item, &mut name, macro_kind, cx), ItemKind::Macro(_, macro_kind) => clean_proc_macro(item, &mut name, macro_kind, cx),

View File

@ -1161,7 +1161,7 @@ pub(crate) fn has_doc_flag(&self, flag: Symbol) -> bool {
false false
} }
fn is_doc_hidden(&self) -> bool { pub(crate) fn is_doc_hidden(&self) -> bool {
self.has_doc_flag(sym::hidden) self.has_doc_flag(sym::hidden)
} }

View File

@ -625,6 +625,7 @@ pub(super) fn display_macro_source(
def: &ast::MacroDef, def: &ast::MacroDef,
def_id: DefId, def_id: DefId,
vis: ty::Visibility<DefId>, vis: ty::Visibility<DefId>,
is_doc_hidden: bool,
) -> String { ) -> String {
// Extract the spans of all matchers. They represent the "interface" of the macro. // Extract the spans of all matchers. They represent the "interface" of the macro.
let matchers = def.body.tokens.chunks(4).map(|arm| &arm[0]); let matchers = def.body.tokens.chunks(4).map(|arm| &arm[0]);
@ -635,7 +636,7 @@ pub(super) fn display_macro_source(
if matchers.len() <= 1 { if matchers.len() <= 1 {
format!( format!(
"{vis}macro {name}{matchers} {{\n ...\n}}", "{vis}macro {name}{matchers} {{\n ...\n}}",
vis = visibility_to_src_with_space(Some(vis), cx.tcx, def_id), vis = visibility_to_src_with_space(Some(vis), cx.tcx, def_id, is_doc_hidden),
matchers = matchers matchers = matchers
.map(|matcher| render_macro_matcher(cx.tcx, matcher)) .map(|matcher| render_macro_matcher(cx.tcx, matcher))
.collect::<String>(), .collect::<String>(),
@ -643,7 +644,7 @@ pub(super) fn display_macro_source(
} else { } else {
format!( format!(
"{vis}macro {name} {{\n{arms}}}", "{vis}macro {name} {{\n{arms}}}",
vis = visibility_to_src_with_space(Some(vis), cx.tcx, def_id), vis = visibility_to_src_with_space(Some(vis), cx.tcx, def_id, is_doc_hidden),
arms = render_macro_arms(cx.tcx, matchers, ","), arms = render_macro_arms(cx.tcx, matchers, ","),
) )
} }

View File

@ -29,8 +29,7 @@
use itertools::Itertools; use itertools::Itertools;
use crate::clean::{ use crate::clean::{
self, types::ExternalLocation, utils::find_nearest_parent_module, ExternalCrate, ItemId, self, types::ExternalLocation, utils::find_nearest_parent_module, ExternalCrate, PrimitiveType,
PrimitiveType,
}; };
use crate::formats::cache::Cache; use crate::formats::cache::Cache;
use crate::formats::item_type::ItemType; use crate::formats::item_type::ItemType;
@ -1506,20 +1505,18 @@ fn print_output<'a, 'tcx: 'a>(
} }
pub(crate) fn visibility_print_with_space<'a, 'tcx: 'a>( pub(crate) fn visibility_print_with_space<'a, 'tcx: 'a>(
visibility: Option<ty::Visibility<DefId>>, item: &clean::Item,
item_did: ItemId,
cx: &'a Context<'tcx>, cx: &'a Context<'tcx>,
) -> impl Display + 'a + Captures<'tcx> { ) -> impl Display + 'a + Captures<'tcx> {
use std::fmt::Write as _; use std::fmt::Write as _;
let to_print: Cow<'static, str> = match item.visibility(cx.tcx()) {
let to_print: Cow<'static, str> = match visibility {
None => "".into(), None => "".into(),
Some(ty::Visibility::Public) => "pub ".into(), Some(ty::Visibility::Public) => "pub ".into(),
Some(ty::Visibility::Restricted(vis_did)) => { Some(ty::Visibility::Restricted(vis_did)) => {
// FIXME(camelid): This may not work correctly if `item_did` is a module. // FIXME(camelid): This may not work correctly if `item_did` is a module.
// However, rustdoc currently never displays a module's // However, rustdoc currently never displays a module's
// visibility, so it shouldn't matter. // visibility, so it shouldn't matter.
let parent_module = find_nearest_parent_module(cx.tcx(), item_did.expect_def_id()); let parent_module = find_nearest_parent_module(cx.tcx(), item.item_id.expect_def_id());
if vis_did.is_crate_root() { if vis_did.is_crate_root() {
"pub(crate) ".into() "pub(crate) ".into()
@ -1557,6 +1554,7 @@ pub(crate) fn visibility_to_src_with_space<'a, 'tcx: 'a>(
visibility: Option<ty::Visibility<DefId>>, visibility: Option<ty::Visibility<DefId>>,
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
item_did: DefId, item_did: DefId,
_is_doc_hidden: bool,
) -> impl Display + 'a + Captures<'tcx> { ) -> impl Display + 'a + Captures<'tcx> {
let to_print: Cow<'static, str> = match visibility { let to_print: Cow<'static, str> = match visibility {
None => "".into(), None => "".into(),

View File

@ -883,7 +883,7 @@ fn assoc_const(
w, w,
"{indent}{vis}const <a{href} class=\"constant\">{name}</a>{generics}: {ty}", "{indent}{vis}const <a{href} class=\"constant\">{name}</a>{generics}: {ty}",
indent = " ".repeat(indent), indent = " ".repeat(indent),
vis = visibility_print_with_space(it.visibility(tcx), it.item_id, cx), vis = visibility_print_with_space(it, cx),
href = assoc_href_attr(it, link, cx), href = assoc_href_attr(it, link, cx),
name = it.name.as_ref().unwrap(), name = it.name.as_ref().unwrap(),
generics = generics.print(cx), generics = generics.print(cx),
@ -912,12 +912,11 @@ fn assoc_type(
indent: usize, indent: usize,
cx: &Context<'_>, cx: &Context<'_>,
) { ) {
let tcx = cx.tcx();
write!( write!(
w, w,
"{indent}{vis}type <a{href} class=\"associatedtype\">{name}</a>{generics}", "{indent}{vis}type <a{href} class=\"associatedtype\">{name}</a>{generics}",
indent = " ".repeat(indent), indent = " ".repeat(indent),
vis = visibility_print_with_space(it.visibility(tcx), it.item_id, cx), vis = visibility_print_with_space(it, cx),
href = assoc_href_attr(it, link, cx), href = assoc_href_attr(it, link, cx),
name = it.name.as_ref().unwrap(), name = it.name.as_ref().unwrap(),
generics = generics.print(cx), generics = generics.print(cx),
@ -945,7 +944,7 @@ fn assoc_method(
let tcx = cx.tcx(); let tcx = cx.tcx();
let header = meth.fn_header(tcx).expect("Trying to get header from a non-function item"); let header = meth.fn_header(tcx).expect("Trying to get header from a non-function item");
let name = meth.name.as_ref().unwrap(); let name = meth.name.as_ref().unwrap();
let vis = visibility_print_with_space(meth.visibility(tcx), meth.item_id, cx).to_string(); let vis = visibility_print_with_space(meth, cx).to_string();
let defaultness = print_default_space(meth.is_default()); let defaultness = print_default_space(meth.is_default());
// FIXME: Once https://github.com/rust-lang/rust/issues/67792 is implemented, we can remove // FIXME: Once https://github.com/rust-lang/rust/issues/67792 is implemented, we can remove
// this condition. // this condition.

View File

@ -445,14 +445,14 @@ fn cmp(
Some(src) => write!( Some(src) => write!(
w, w,
"<div class=\"item-name\"><code>{}extern crate {} as {};", "<div class=\"item-name\"><code>{}extern crate {} as {};",
visibility_print_with_space(myitem.visibility(tcx), myitem.item_id, cx), visibility_print_with_space(myitem, cx),
anchor(myitem.item_id.expect_def_id(), src, cx), anchor(myitem.item_id.expect_def_id(), src, cx),
myitem.name.unwrap(), myitem.name.unwrap(),
), ),
None => write!( None => write!(
w, w,
"<div class=\"item-name\"><code>{}extern crate {};", "<div class=\"item-name\"><code>{}extern crate {};",
visibility_print_with_space(myitem.visibility(tcx), myitem.item_id, cx), visibility_print_with_space(myitem, cx),
anchor(myitem.item_id.expect_def_id(), myitem.name.unwrap(), cx), anchor(myitem.item_id.expect_def_id(), myitem.name.unwrap(), cx),
), ),
} }
@ -491,7 +491,7 @@ fn cmp(
<code>{vis}{imp}</code>\ <code>{vis}{imp}</code>\
</div>\ </div>\
{stab_tags_before}{stab_tags}{stab_tags_after}", {stab_tags_before}{stab_tags}{stab_tags_after}",
vis = visibility_print_with_space(myitem.visibility(tcx), myitem.item_id, cx), vis = visibility_print_with_space(myitem, cx),
imp = import.print(cx), imp = import.print(cx),
); );
w.write_str(ITEM_TABLE_ROW_CLOSE); w.write_str(ITEM_TABLE_ROW_CLOSE);
@ -631,7 +631,7 @@ fn item_function(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, f: &cle
let unsafety = header.unsafety.print_with_space(); let unsafety = header.unsafety.print_with_space();
let abi = print_abi_with_space(header.abi).to_string(); let abi = print_abi_with_space(header.abi).to_string();
let asyncness = header.asyncness.print_with_space(); let asyncness = header.asyncness.print_with_space();
let visibility = visibility_print_with_space(it.visibility(tcx), it.item_id, cx).to_string(); let visibility = visibility_print_with_space(it, cx).to_string();
let name = it.name.unwrap(); let name = it.name.unwrap();
let generics_len = format!("{:#}", f.generics.print(cx)).len(); let generics_len = format!("{:#}", f.generics.print(cx)).len();
@ -688,7 +688,7 @@ fn item_trait(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean:
w, w,
"{attrs}{vis}{unsafety}{is_auto}trait {name}{generics}{bounds}", "{attrs}{vis}{unsafety}{is_auto}trait {name}{generics}{bounds}",
attrs = render_attributes_in_pre(it, "", cx), attrs = render_attributes_in_pre(it, "", cx),
vis = visibility_print_with_space(it.visibility(tcx), it.item_id, cx), vis = visibility_print_with_space(it, cx),
unsafety = t.unsafety(tcx).print_with_space(), unsafety = t.unsafety(tcx).print_with_space(),
is_auto = if t.is_auto(tcx) { "auto " } else { "" }, is_auto = if t.is_auto(tcx) { "auto " } else { "" },
name = it.name.unwrap(), name = it.name.unwrap(),
@ -1243,7 +1243,7 @@ fn write_content(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::
w, w,
"{attrs}{vis}type {name}{generics}{where_clause} = {type_};", "{attrs}{vis}type {name}{generics}{where_clause} = {type_};",
attrs = render_attributes_in_pre(it, "", cx), attrs = render_attributes_in_pre(it, "", cx),
vis = visibility_print_with_space(it.visibility(cx.tcx()), it.item_id, cx), vis = visibility_print_with_space(it, cx),
name = it.name.unwrap(), name = it.name.unwrap(),
generics = t.generics.print(cx), generics = t.generics.print(cx),
where_clause = print_where_clause(&t.generics, cx, 0, Ending::Newline), where_clause = print_where_clause(&t.generics, cx, 0, Ending::Newline),
@ -1522,14 +1522,13 @@ fn print_tuple_struct_fields<'a, 'cx: 'a>(
} }
fn item_enum(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, e: &clean::Enum) { fn item_enum(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, e: &clean::Enum) {
let tcx = cx.tcx();
let count_variants = e.variants().count(); let count_variants = e.variants().count();
wrap_item(w, |w| { wrap_item(w, |w| {
render_attributes_in_code(w, it, cx); render_attributes_in_code(w, it, cx);
write!( write!(
w, w,
"{}enum {}{}", "{}enum {}{}",
visibility_print_with_space(it.visibility(tcx), it.item_id, cx), visibility_print_with_space(it, cx),
it.name.unwrap(), it.name.unwrap(),
e.generics.print(cx), e.generics.print(cx),
); );
@ -1860,7 +1859,7 @@ fn item_constant(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, c: &cle
write!( write!(
w, w,
"{vis}const {name}{generics}: {typ}{where_clause}", "{vis}const {name}{generics}: {typ}{where_clause}",
vis = visibility_print_with_space(it.visibility(tcx), it.item_id, cx), vis = visibility_print_with_space(it, cx),
name = it.name.unwrap(), name = it.name.unwrap(),
generics = c.generics.print(cx), generics = c.generics.print(cx),
typ = c.type_.print(cx), typ = c.type_.print(cx),
@ -1964,7 +1963,7 @@ fn item_static(w: &mut impl fmt::Write, cx: &mut Context<'_>, it: &clean::Item,
write!( write!(
buffer, buffer,
"{vis}static {mutability}{name}: {typ}", "{vis}static {mutability}{name}: {typ}",
vis = visibility_print_with_space(it.visibility(cx.tcx()), it.item_id, cx), vis = visibility_print_with_space(it, cx),
mutability = s.mutability.print_with_space(), mutability = s.mutability.print_with_space(),
name = it.name.unwrap(), name = it.name.unwrap(),
typ = s.type_.print(cx) typ = s.type_.print(cx)
@ -1982,7 +1981,7 @@ fn item_foreign_type(w: &mut impl fmt::Write, cx: &mut Context<'_>, it: &clean::
write!( write!(
buffer, buffer,
" {}type {};\n}}", " {}type {};\n}}",
visibility_print_with_space(it.visibility(cx.tcx()), it.item_id, cx), visibility_print_with_space(it, cx),
it.name.unwrap(), it.name.unwrap(),
) )
.unwrap(); .unwrap();
@ -2139,13 +2138,7 @@ fn render_union<'a, 'cx: 'a>(
cx: &'a Context<'cx>, cx: &'a Context<'cx>,
) -> impl fmt::Display + 'a + Captures<'cx> { ) -> impl fmt::Display + 'a + Captures<'cx> {
display_fn(move |mut f| { display_fn(move |mut f| {
let tcx = cx.tcx(); write!(f, "{}union {}", visibility_print_with_space(it, cx), it.name.unwrap(),)?;
write!(
f,
"{}union {}",
visibility_print_with_space(it.visibility(tcx), it.item_id, cx),
it.name.unwrap(),
)?;
let where_displayed = g let where_displayed = g
.map(|g| { .map(|g| {
@ -2175,7 +2168,7 @@ fn render_union<'a, 'cx: 'a>(
write!( write!(
f, f,
" {}{}: {},\n", " {}{}: {},\n",
visibility_print_with_space(field.visibility(tcx), field.item_id, cx), visibility_print_with_space(field, cx),
field.name.unwrap(), field.name.unwrap(),
ty.print(cx) ty.print(cx)
)?; )?;
@ -2203,11 +2196,10 @@ fn render_struct(
structhead: bool, structhead: bool,
cx: &Context<'_>, cx: &Context<'_>,
) { ) {
let tcx = cx.tcx();
write!( write!(
w, w,
"{}{}{}", "{}{}{}",
visibility_print_with_space(it.visibility(tcx), it.item_id, cx), visibility_print_with_space(it, cx),
if structhead { "struct " } else { "" }, if structhead { "struct " } else { "" },
it.name.unwrap() it.name.unwrap()
); );
@ -2236,7 +2228,6 @@ fn render_struct_fields(
has_stripped_entries: bool, has_stripped_entries: bool,
cx: &Context<'_>, cx: &Context<'_>,
) { ) {
let tcx = cx.tcx();
match ty { match ty {
None => { None => {
let where_displayed = let where_displayed =
@ -2260,7 +2251,7 @@ fn render_struct_fields(
write!( write!(
w, w,
"\n{tab} {vis}{name}: {ty},", "\n{tab} {vis}{name}: {ty},",
vis = visibility_print_with_space(field.visibility(tcx), field.item_id, cx), vis = visibility_print_with_space(field, cx),
name = field.name.unwrap(), name = field.name.unwrap(),
ty = ty.print(cx), ty = ty.print(cx),
); );
@ -2296,16 +2287,7 @@ fn render_struct_fields(
match *field.kind { match *field.kind {
clean::StrippedItem(box clean::StructFieldItem(..)) => write!(w, "_"), clean::StrippedItem(box clean::StructFieldItem(..)) => write!(w, "_"),
clean::StructFieldItem(ref ty) => { clean::StructFieldItem(ref ty) => {
write!( write!(w, "{}{}", visibility_print_with_space(field, cx), ty.print(cx),)
w,
"{}{}",
visibility_print_with_space(
field.visibility(tcx),
field.item_id,
cx
),
ty.print(cx),
)
} }
_ => unreachable!(), _ => unreachable!(),
} }