提交 3debe9ac 编写于 作者: B bors

Auto merge of #82873 - GuillaumeGomez:rustdoc-const-ty, r=jyn514

Rework rustdoc const type

This PR is mostly about two things:
 1. Not storing some information in the `clean::Constant` type
 2. Using `TyCtxt` in the formatting (which we will need in any case as we move forward in any case).

Also: I'm very curious of the perf change in here.

Thanks a lot `@danielhenrymantilla` for your `Captures` idea! It allowed me to solve the lifetime issue completely. :)

r? `@jyn514`
...@@ -9,7 +9,7 @@ ...@@ -9,7 +9,7 @@
use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX}; use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX};
use rustc_hir::Mutability; use rustc_hir::Mutability;
use rustc_metadata::creader::LoadedMacro; use rustc_metadata::creader::LoadedMacro;
use rustc_middle::ty; use rustc_middle::ty::{self, TyCtxt};
use rustc_mir::const_eval::is_min_const_fn; use rustc_mir::const_eval::is_min_const_fn;
use rustc_span::hygiene::MacroKind; use rustc_span::hygiene::MacroKind;
use rustc_span::symbol::{kw, sym, Symbol}; use rustc_span::symbol::{kw, sym, Symbol};
...@@ -490,23 +490,19 @@ fn build_module( ...@@ -490,23 +490,19 @@ fn build_module(
clean::Module { items, is_crate: false } clean::Module { items, is_crate: false }
} }
crate fn print_inlined_const(cx: &DocContext<'_>, did: DefId) -> String { crate fn print_inlined_const(tcx: TyCtxt<'_>, did: DefId) -> String {
if let Some(did) = did.as_local() { if let Some(did) = did.as_local() {
let hir_id = cx.tcx.hir().local_def_id_to_hir_id(did); let hir_id = tcx.hir().local_def_id_to_hir_id(did);
rustc_hir_pretty::id_to_string(&cx.tcx.hir(), hir_id) rustc_hir_pretty::id_to_string(&tcx.hir(), hir_id)
} else { } else {
cx.tcx.rendered_const(did) tcx.rendered_const(did)
} }
} }
fn build_const(cx: &mut DocContext<'_>, did: DefId) -> clean::Constant { fn build_const(cx: &mut DocContext<'_>, def_id: DefId) -> clean::Constant {
clean::Constant { clean::Constant {
type_: cx.tcx.type_of(did).clean(cx), type_: cx.tcx.type_of(def_id).clean(cx),
expr: print_inlined_const(cx, did), kind: clean::ConstantKind::Extern { def_id },
value: clean::utils::print_evaluated_const(cx, did),
is_literal: did.as_local().map_or(false, |did| {
clean::utils::is_literal_expr(cx, cx.tcx.hir().local_def_id_to_hir_id(did))
}),
} }
} }
......
...@@ -398,9 +398,7 @@ fn clean(&self, cx: &mut DocContext<'_>) -> Constant { ...@@ -398,9 +398,7 @@ fn clean(&self, cx: &mut DocContext<'_>) -> Constant {
.tcx .tcx
.type_of(cx.tcx.hir().body_owner_def_id(self.value.body).to_def_id()) .type_of(cx.tcx.hir().body_owner_def_id(self.value.body).to_def_id())
.clean(cx), .clean(cx),
expr: print_const_expr(cx.tcx, self.value.body), kind: ConstantKind::Anonymous { body: self.value.body },
value: None,
is_literal: is_literal_expr(cx, self.value.body.hir_id),
} }
} }
} }
...@@ -1135,7 +1133,7 @@ fn clean(&self, cx: &mut DocContext<'_>) -> Item { ...@@ -1135,7 +1133,7 @@ fn clean(&self, cx: &mut DocContext<'_>) -> Item {
ty::AssocKind::Const => { ty::AssocKind::Const => {
let ty = tcx.type_of(self.def_id); let ty = tcx.type_of(self.def_id);
let default = if self.defaultness.has_value() { let default = if self.defaultness.has_value() {
Some(inline::print_inlined_const(cx, self.def_id)) Some(inline::print_inlined_const(tcx, self.def_id))
} else { } else {
None None
}; };
...@@ -1745,11 +1743,10 @@ fn clean(&self, cx: &mut DocContext<'_>) -> Type { ...@@ -1745,11 +1743,10 @@ fn clean(&self, cx: &mut DocContext<'_>) -> Type {
impl<'tcx> Clean<Constant> for ty::Const<'tcx> { impl<'tcx> Clean<Constant> for ty::Const<'tcx> {
fn clean(&self, cx: &mut DocContext<'_>) -> Constant { fn clean(&self, cx: &mut DocContext<'_>) -> Constant {
// FIXME: instead of storing the stringified expression, store `self` directly instead.
Constant { Constant {
type_: self.ty.clean(cx), type_: self.ty.clean(cx),
expr: format!("{}", self), kind: ConstantKind::TyConst { expr: self.to_string() },
value: None,
is_literal: false,
} }
} }
} }
...@@ -1953,9 +1950,7 @@ fn clean(&self, cx: &mut DocContext<'_>) -> Vec<Item> { ...@@ -1953,9 +1950,7 @@ fn clean(&self, cx: &mut DocContext<'_>) -> Vec<Item> {
} }
ItemKind::Const(ty, body_id) => ConstantItem(Constant { ItemKind::Const(ty, body_id) => ConstantItem(Constant {
type_: ty.clean(cx), type_: ty.clean(cx),
expr: print_const_expr(cx.tcx, body_id), kind: ConstantKind::Local { body: body_id, def_id },
value: print_evaluated_const(cx, def_id),
is_literal: is_literal_expr(cx, body_id.hir_id),
}), }),
ItemKind::OpaqueTy(ref ty) => OpaqueTyItem(OpaqueTy { ItemKind::OpaqueTy(ref ty) => OpaqueTyItem(OpaqueTy {
bounds: ty.bounds.clean(cx), bounds: ty.bounds.clean(cx),
......
...@@ -32,8 +32,9 @@ ...@@ -32,8 +32,9 @@
use crate::clean::cfg::Cfg; use crate::clean::cfg::Cfg;
use crate::clean::external_path; use crate::clean::external_path;
use crate::clean::inline; use crate::clean::inline::{self, print_inlined_const};
use crate::clean::types::Type::{QPath, ResolvedPath}; use crate::clean::types::Type::{QPath, ResolvedPath};
use crate::clean::utils::{is_literal_expr, print_const_expr, print_evaluated_const};
use crate::clean::Clean; use crate::clean::Clean;
use crate::core::DocContext; use crate::core::DocContext;
use crate::formats::cache::Cache; use crate::formats::cache::Cache;
...@@ -1988,9 +1989,58 @@ fn def_id_full(&self, cache: &Cache) -> Option<DefId> { ...@@ -1988,9 +1989,58 @@ fn def_id_full(&self, cache: &Cache) -> Option<DefId> {
#[derive(Clone, PartialEq, Eq, Hash, Debug)] #[derive(Clone, PartialEq, Eq, Hash, Debug)]
crate struct Constant { crate struct Constant {
crate type_: Type, crate type_: Type,
crate expr: String, crate kind: ConstantKind,
crate value: Option<String>, }
crate is_literal: bool,
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
crate enum ConstantKind {
/// This is the wrapper around `ty::Const` for a non-local constant. Because it doesn't have a
/// `BodyId`, we need to handle it on its own.
///
/// Note that `ty::Const` includes generic parameters, and may not always be uniquely identified
/// by a DefId. So this field must be different from `Extern`.
TyConst { expr: String },
/// A constant (expression) that's not an item or associated item. These are usually found
/// nested inside types (e.g., array lengths) or expressions (e.g., repeat counts), and also
/// used to define explicit discriminant values for enum variants.
Anonymous { body: BodyId },
/// A constant from a different crate.
Extern { def_id: DefId },
/// `const FOO: u32 = ...;`
Local { def_id: DefId, body: BodyId },
}
impl Constant {
crate fn expr(&self, tcx: TyCtxt<'_>) -> String {
match self.kind {
ConstantKind::TyConst { ref expr } => expr.clone(),
ConstantKind::Extern { def_id } => print_inlined_const(tcx, def_id),
ConstantKind::Local { body, .. } | ConstantKind::Anonymous { body } => {
print_const_expr(tcx, body)
}
}
}
crate fn value(&self, tcx: TyCtxt<'_>) -> Option<String> {
match self.kind {
ConstantKind::TyConst { .. } | ConstantKind::Anonymous { .. } => None,
ConstantKind::Extern { def_id } | ConstantKind::Local { def_id, .. } => {
print_evaluated_const(tcx, def_id)
}
}
}
crate fn is_literal(&self, tcx: TyCtxt<'_>) -> bool {
match self.kind {
ConstantKind::TyConst { .. } => false,
ConstantKind::Extern { def_id } => def_id.as_local().map_or(false, |def_id| {
is_literal_expr(tcx, tcx.hir().local_def_id_to_hir_id(def_id))
}),
ConstantKind::Local { body, .. } | ConstantKind::Anonymous { body } => {
is_literal_expr(tcx, body.hir_id)
}
}
}
} }
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
......
...@@ -301,7 +301,7 @@ fn to_src(&self, cx: &DocContext<'_>) -> String { ...@@ -301,7 +301,7 @@ fn to_src(&self, cx: &DocContext<'_>) -> String {
let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def.did); let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def.did);
print_const_expr(cx.tcx, cx.tcx.hir().body_owned_by(hir_id)) print_const_expr(cx.tcx, cx.tcx.hir().body_owned_by(hir_id))
} else { } else {
inline::print_inlined_const(cx, def.did) inline::print_inlined_const(cx.tcx, def.did)
}; };
if let Some(promoted) = promoted { if let Some(promoted) = promoted {
s.push_str(&format!("::{:?}", promoted)) s.push_str(&format!("::{:?}", promoted))
...@@ -324,15 +324,15 @@ fn to_src(&self, cx: &DocContext<'_>) -> String { ...@@ -324,15 +324,15 @@ fn to_src(&self, cx: &DocContext<'_>) -> String {
} }
} }
crate fn print_evaluated_const(cx: &DocContext<'_>, def_id: DefId) -> Option<String> { crate fn print_evaluated_const(tcx: TyCtxt<'_>, def_id: DefId) -> Option<String> {
cx.tcx.const_eval_poly(def_id).ok().and_then(|val| { tcx.const_eval_poly(def_id).ok().and_then(|val| {
let ty = cx.tcx.type_of(def_id); let ty = tcx.type_of(def_id);
match (val, ty.kind()) { match (val, ty.kind()) {
(_, &ty::Ref(..)) => None, (_, &ty::Ref(..)) => None,
(ConstValue::Scalar(_), &ty::Adt(_, _)) => None, (ConstValue::Scalar(_), &ty::Adt(_, _)) => None,
(ConstValue::Scalar(_), _) => { (ConstValue::Scalar(_), _) => {
let const_ = ty::Const::from_value(cx.tcx, val, ty); let const_ = ty::Const::from_value(tcx, val, ty);
Some(print_const_with_custom_print_scalar(cx, const_)) Some(print_const_with_custom_print_scalar(tcx, const_))
} }
_ => None, _ => None,
} }
...@@ -349,7 +349,7 @@ fn format_integer_with_underscore_sep(num: &str) -> String { ...@@ -349,7 +349,7 @@ fn format_integer_with_underscore_sep(num: &str) -> String {
.collect() .collect()
} }
fn print_const_with_custom_print_scalar(cx: &DocContext<'_>, ct: &'tcx ty::Const<'tcx>) -> String { fn print_const_with_custom_print_scalar(tcx: TyCtxt<'_>, ct: &'tcx ty::Const<'tcx>) -> String {
// Use a slightly different format for integer types which always shows the actual value. // Use a slightly different format for integer types which always shows the actual value.
// For all other types, fallback to the original `pretty_print_const`. // For all other types, fallback to the original `pretty_print_const`.
match (ct.val, ct.ty.kind()) { match (ct.val, ct.ty.kind()) {
...@@ -357,8 +357,8 @@ fn print_const_with_custom_print_scalar(cx: &DocContext<'_>, ct: &'tcx ty::Const ...@@ -357,8 +357,8 @@ fn print_const_with_custom_print_scalar(cx: &DocContext<'_>, ct: &'tcx ty::Const
format!("{}{}", format_integer_with_underscore_sep(&int.to_string()), ui.name_str()) format!("{}{}", format_integer_with_underscore_sep(&int.to_string()), ui.name_str())
} }
(ty::ConstKind::Value(ConstValue::Scalar(int)), ty::Int(i)) => { (ty::ConstKind::Value(ConstValue::Scalar(int)), ty::Int(i)) => {
let ty = cx.tcx.lift(ct.ty).unwrap(); let ty = tcx.lift(ct.ty).unwrap();
let size = cx.tcx.layout_of(ty::ParamEnv::empty().and(ty)).unwrap().size; let size = tcx.layout_of(ty::ParamEnv::empty().and(ty)).unwrap().size;
let data = int.assert_bits(size); let data = int.assert_bits(size);
let sign_extended_data = size.sign_extend(data) as i128; let sign_extended_data = size.sign_extend(data) as i128;
...@@ -372,8 +372,8 @@ fn print_const_with_custom_print_scalar(cx: &DocContext<'_>, ct: &'tcx ty::Const ...@@ -372,8 +372,8 @@ fn print_const_with_custom_print_scalar(cx: &DocContext<'_>, ct: &'tcx ty::Const
} }
} }
crate fn is_literal_expr(cx: &DocContext<'_>, hir_id: hir::HirId) -> bool { crate fn is_literal_expr(tcx: TyCtxt<'_>, hir_id: hir::HirId) -> bool {
if let hir::Node::Expr(expr) = cx.tcx.hir().get(hir_id) { if let hir::Node::Expr(expr) = tcx.hir().get(hir_id) {
if let hir::ExprKind::Lit(_) = &expr.kind { if let hir::ExprKind::Lit(_) = &expr.kind {
return true; return true;
} }
...@@ -411,7 +411,7 @@ fn print_const_with_custom_print_scalar(cx: &DocContext<'_>, ct: &'tcx ty::Const ...@@ -411,7 +411,7 @@ fn print_const_with_custom_print_scalar(cx: &DocContext<'_>, ct: &'tcx ty::Const
return Generic(kw::SelfUpper); return Generic(kw::SelfUpper);
} }
Res::Def(DefKind::TyParam, _) if path.segments.len() == 1 => { Res::Def(DefKind::TyParam, _) if path.segments.len() == 1 => {
return Generic(Symbol::intern(&format!("{:#}", path.print(&cx.cache)))); return Generic(Symbol::intern(&format!("{:#}", path.print(&cx.cache, cx.tcx))));
} }
Res::SelfTy(..) | Res::Def(DefKind::TyParam | DefKind::AssocTy, _) => true, Res::SelfTy(..) | Res::Def(DefKind::TyParam | DefKind::AssocTy, _) => true,
_ => false, _ => false,
......
此差异已折叠。
此差异已折叠。
...@@ -19,7 +19,7 @@ ...@@ -19,7 +19,7 @@
use crate::formats::item_type::ItemType; use crate::formats::item_type::ItemType;
use crate::formats::{AssocItemRender, FormatRenderer, Impl, RenderMode}; use crate::formats::{AssocItemRender, FormatRenderer, Impl, RenderMode};
use crate::html::escape::Escape; use crate::html::escape::Escape;
use crate::html::format::{print_abi_with_space, Buffer, Function, PrintWithSpace, WhereClause}; use crate::html::format::{print_abi_with_space, print_where_clause, Buffer, PrintWithSpace};
use crate::html::highlight; use crate::html::highlight;
use crate::html::markdown::MarkdownSummaryLine; use crate::html::markdown::MarkdownSummaryLine;
...@@ -266,7 +266,7 @@ fn cmp( ...@@ -266,7 +266,7 @@ fn cmp(
w, w,
"<tr><td><code>{}{}</code></td></tr>", "<tr><td><code>{}{}</code></td></tr>",
myitem.visibility.print_with_space(cx.tcx(), myitem.def_id, cx.cache()), myitem.visibility.print_with_space(cx.tcx(), myitem.def_id, cx.cache()),
import.print(cx.cache()) import.print(cx.cache(), cx.tcx()),
); );
} }
...@@ -372,7 +372,7 @@ fn item_function(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, f: &clean:: ...@@ -372,7 +372,7 @@ fn item_function(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, f: &clean::
f.header.unsafety.print_with_space(), f.header.unsafety.print_with_space(),
print_abi_with_space(f.header.abi), print_abi_with_space(f.header.abi),
it.name.as_ref().unwrap(), it.name.as_ref().unwrap(),
f.generics.print(cx.cache()) f.generics.print(cx.cache(), cx.tcx())
) )
.len(); .len();
w.write_str("<pre class=\"rust fn\">"); w.write_str("<pre class=\"rust fn\">");
...@@ -387,18 +387,16 @@ fn item_function(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, f: &clean:: ...@@ -387,18 +387,16 @@ fn item_function(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, f: &clean::
unsafety = f.header.unsafety.print_with_space(), unsafety = f.header.unsafety.print_with_space(),
abi = print_abi_with_space(f.header.abi), abi = print_abi_with_space(f.header.abi),
name = it.name.as_ref().unwrap(), name = it.name.as_ref().unwrap(),
generics = f.generics.print(cx.cache()), generics = f.generics.print(cx.cache(), cx.tcx()),
where_clause = where_clause = print_where_clause(&f.generics, cx.cache(), cx.tcx(), 0, true),
WhereClause { gens: &f.generics, indent: 0, end_newline: true }.print(cx.cache()), decl = f.decl.full_print(cx.cache(), cx.tcx(), header_len, 0, f.header.asyncness),
decl = Function { decl: &f.decl, header_len, indent: 0, asyncness: f.header.asyncness } spotlight = spotlight_decl(&f.decl, cx.cache(), cx.tcx()),
.print(cx.cache()),
spotlight = spotlight_decl(&f.decl, cx.cache()),
); );
document(w, cx, it, None) document(w, cx, it, None)
} }
fn item_trait(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Trait) { fn item_trait(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Trait) {
let bounds = bounds(&t.bounds, false, cx.cache()); let bounds = bounds(&t.bounds, false, cx.cache(), cx.tcx());
let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>(); let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>(); let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>(); let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
...@@ -415,13 +413,12 @@ fn item_trait(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Tra ...@@ -415,13 +413,12 @@ fn item_trait(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Tra
t.unsafety.print_with_space(), t.unsafety.print_with_space(),
if t.is_auto { "auto " } else { "" }, if t.is_auto { "auto " } else { "" },
it.name.as_ref().unwrap(), it.name.as_ref().unwrap(),
t.generics.print(cx.cache()), t.generics.print(cx.cache(), cx.tcx()),
bounds bounds
); );
if !t.generics.where_predicates.is_empty() { if !t.generics.where_predicates.is_empty() {
let where_ = WhereClause { gens: &t.generics, indent: 0, end_newline: true }; write!(w, "{}", print_where_clause(&t.generics, cx.cache(), cx.tcx(), 0, true));
write!(w, "{}", where_.print(cx.cache()));
} else { } else {
w.write_str(" "); w.write_str(" ");
} }
...@@ -594,8 +591,8 @@ fn trait_item(w: &mut Buffer, cx: &Context<'_>, m: &clean::Item, t: &clean::Item ...@@ -594,8 +591,8 @@ fn trait_item(w: &mut Buffer, cx: &Context<'_>, m: &clean::Item, t: &clean::Item
let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) = let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) =
local.iter().partition(|i| i.inner_impl().synthetic); local.iter().partition(|i| i.inner_impl().synthetic);
synthetic.sort_by(|a, b| compare_impl(a, b, cx.cache())); synthetic.sort_by(|a, b| compare_impl(a, b, cx.cache(), cx.tcx()));
concrete.sort_by(|a, b| compare_impl(a, b, cx.cache())); concrete.sort_by(|a, b| compare_impl(a, b, cx.cache(), cx.tcx()));
if !foreign.is_empty() { if !foreign.is_empty() {
write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", ""); write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "");
...@@ -700,9 +697,9 @@ fn item_trait_alias(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clea ...@@ -700,9 +697,9 @@ fn item_trait_alias(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clea
w, w,
"trait {}{}{} = {};</pre>", "trait {}{}{} = {};</pre>",
it.name.as_ref().unwrap(), it.name.as_ref().unwrap(),
t.generics.print(cx.cache()), t.generics.print(cx.cache(), cx.tcx()),
WhereClause { gens: &t.generics, indent: 0, end_newline: true }.print(cx.cache()), print_where_clause(&t.generics, cx.cache(), cx.tcx(), 0, true),
bounds(&t.bounds, true, cx.cache()) bounds(&t.bounds, true, cx.cache(), cx.tcx())
); );
document(w, cx, it, None); document(w, cx, it, None);
...@@ -721,10 +718,9 @@ fn item_opaque_ty(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean: ...@@ -721,10 +718,9 @@ fn item_opaque_ty(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean:
w, w,
"type {}{}{where_clause} = impl {bounds};</pre>", "type {}{}{where_clause} = impl {bounds};</pre>",
it.name.as_ref().unwrap(), it.name.as_ref().unwrap(),
t.generics.print(cx.cache()), t.generics.print(cx.cache(), cx.tcx()),
where_clause = where_clause = print_where_clause(&t.generics, cx.cache(), cx.tcx(), 0, true),
WhereClause { gens: &t.generics, indent: 0, end_newline: true }.print(cx.cache()), bounds = bounds(&t.bounds, false, cx.cache(), cx.tcx()),
bounds = bounds(&t.bounds, false, cx.cache())
); );
document(w, cx, it, None); document(w, cx, it, None);
...@@ -743,10 +739,9 @@ fn item_typedef(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::T ...@@ -743,10 +739,9 @@ fn item_typedef(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::T
w, w,
"type {}{}{where_clause} = {type_};</pre>", "type {}{}{where_clause} = {type_};</pre>",
it.name.as_ref().unwrap(), it.name.as_ref().unwrap(),
t.generics.print(cx.cache()), t.generics.print(cx.cache(), cx.tcx()),
where_clause = where_clause = print_where_clause(&t.generics, cx.cache(), cx.tcx(), 0, true),
WhereClause { gens: &t.generics, indent: 0, end_newline: true }.print(cx.cache()), type_ = t.type_.print(cx.cache(), cx.tcx()),
type_ = t.type_.print(cx.cache())
); );
document(w, cx, it, None); document(w, cx, it, None);
...@@ -793,7 +788,7 @@ fn item_union(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Uni ...@@ -793,7 +788,7 @@ fn item_union(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Uni
id = id, id = id,
name = name, name = name,
shortty = ItemType::StructField, shortty = ItemType::StructField,
ty = ty.print(cx.cache()) ty = ty.print(cx.cache(), cx.tcx()),
); );
if let Some(stability_class) = field.stability_class(cx.tcx()) { if let Some(stability_class) = field.stability_class(cx.tcx()) {
write!(w, "<span class=\"stab {stab}\"></span>", stab = stability_class); write!(w, "<span class=\"stab {stab}\"></span>", stab = stability_class);
...@@ -813,8 +808,8 @@ fn item_enum(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, e: &clean::Enum ...@@ -813,8 +808,8 @@ fn item_enum(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, e: &clean::Enum
"{}enum {}{}{}", "{}enum {}{}{}",
it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()), it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
it.name.as_ref().unwrap(), it.name.as_ref().unwrap(),
e.generics.print(cx.cache()), e.generics.print(cx.cache(), cx.tcx()),
WhereClause { gens: &e.generics, indent: 0, end_newline: true }.print(cx.cache()) print_where_clause(&e.generics, cx.cache(), cx.tcx(), 0, true),
); );
if e.variants.is_empty() && !e.variants_stripped { if e.variants.is_empty() && !e.variants_stripped {
w.write_str(" {}"); w.write_str(" {}");
...@@ -832,7 +827,7 @@ fn item_enum(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, e: &clean::Enum ...@@ -832,7 +827,7 @@ fn item_enum(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, e: &clean::Enum
if i > 0 { if i > 0 {
w.write_str(",&nbsp;") w.write_str(",&nbsp;")
} }
write!(w, "{}", ty.print(cx.cache())); write!(w, "{}", ty.print(cx.cache(), cx.tcx()));
} }
w.write_str(")"); w.write_str(")");
} }
...@@ -879,7 +874,7 @@ fn item_enum(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, e: &clean::Enum ...@@ -879,7 +874,7 @@ fn item_enum(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, e: &clean::Enum
if i > 0 { if i > 0 {
w.write_str(",&nbsp;"); w.write_str(",&nbsp;");
} }
write!(w, "{}", ty.print(cx.cache())); write!(w, "{}", ty.print(cx.cache(), cx.tcx()));
} }
w.write_str(")"); w.write_str(")");
} }
...@@ -916,7 +911,7 @@ fn item_enum(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, e: &clean::Enum ...@@ -916,7 +911,7 @@ fn item_enum(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, e: &clean::Enum
</span>", </span>",
id = id, id = id,
f = field.name.as_ref().unwrap(), f = field.name.as_ref().unwrap(),
t = ty.print(cx.cache()) t = ty.print(cx.cache(), cx.tcx())
); );
document(w, cx, field, Some(variant)); document(w, cx, field, Some(variant));
} }
...@@ -987,19 +982,22 @@ fn item_constant(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, c: &clean:: ...@@ -987,19 +982,22 @@ fn item_constant(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, c: &clean::
"{vis}const {name}: {typ}", "{vis}const {name}: {typ}",
vis = it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()), vis = it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
name = it.name.as_ref().unwrap(), name = it.name.as_ref().unwrap(),
typ = c.type_.print(cx.cache()), typ = c.type_.print(cx.cache(), cx.tcx()),
); );
if c.value.is_some() || c.is_literal { let value = c.value(cx.tcx());
write!(w, " = {expr};", expr = Escape(&c.expr)); let is_literal = c.is_literal(cx.tcx());
let expr = c.expr(cx.tcx());
if value.is_some() || is_literal {
write!(w, " = {expr};", expr = Escape(&expr));
} else { } else {
w.write_str(";"); w.write_str(";");
} }
if let Some(value) = &c.value { if !is_literal {
if !c.is_literal { if let Some(value) = &value {
let value_lowercase = value.to_lowercase(); let value_lowercase = value.to_lowercase();
let expr_lowercase = c.expr.to_lowercase(); let expr_lowercase = expr.to_lowercase();
if value_lowercase != expr_lowercase if value_lowercase != expr_lowercase
&& value_lowercase.trim_end_matches("i32") != expr_lowercase && value_lowercase.trim_end_matches("i32") != expr_lowercase
...@@ -1054,7 +1052,7 @@ fn item_struct(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::St ...@@ -1054,7 +1052,7 @@ fn item_struct(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::St
item_type = ItemType::StructField, item_type = ItemType::StructField,
id = id, id = id,
name = field.name.as_ref().unwrap(), name = field.name.as_ref().unwrap(),
ty = ty.print(cx.cache()) ty = ty.print(cx.cache(), cx.tcx())
); );
document(w, cx, field, Some(it)); document(w, cx, field, Some(it));
} }
...@@ -1072,7 +1070,7 @@ fn item_static(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::St ...@@ -1072,7 +1070,7 @@ fn item_static(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::St
vis = it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()), vis = it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
mutability = s.mutability.print_with_space(), mutability = s.mutability.print_with_space(),
name = it.name.as_ref().unwrap(), name = it.name.as_ref().unwrap(),
typ = s.type_.print(cx.cache()) typ = s.type_.print(cx.cache(), cx.tcx())
); );
document(w, cx, it, None) document(w, cx, it, None)
} }
...@@ -1147,7 +1145,12 @@ pub(super) fn item_path(ty: ItemType, name: &str) -> String { ...@@ -1147,7 +1145,12 @@ pub(super) fn item_path(ty: ItemType, name: &str) -> String {
} }
} }
fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool, cache: &Cache) -> String { fn bounds(
t_bounds: &[clean::GenericBound],
trait_alias: bool,
cache: &Cache,
tcx: TyCtxt<'_>,
) -> String {
let mut bounds = String::new(); let mut bounds = String::new();
if !t_bounds.is_empty() { if !t_bounds.is_empty() {
if !trait_alias { if !trait_alias {
...@@ -1157,7 +1160,7 @@ fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool, cache: &Cache) -> ...@@ -1157,7 +1160,7 @@ fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool, cache: &Cache) ->
if i > 0 { if i > 0 {
bounds.push_str(" + "); bounds.push_str(" + ");
} }
bounds.push_str(&p.print(cache).to_string()); bounds.push_str(&p.print(cache, tcx).to_string());
} }
} }
bounds bounds
...@@ -1187,9 +1190,14 @@ fn render_stability_since( ...@@ -1187,9 +1190,14 @@ fn render_stability_since(
) )
} }
fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl, cache: &Cache) -> Ordering { fn compare_impl<'a, 'b>(
let lhs = format!("{}", lhs.inner_impl().print(cache, false)); lhs: &'a &&Impl,
let rhs = format!("{}", rhs.inner_impl().print(cache, false)); rhs: &'b &&Impl,
cache: &Cache,
tcx: TyCtxt<'_>,
) -> Ordering {
let lhs = format!("{}", lhs.inner_impl().print(cache, false, tcx));
let rhs = format!("{}", rhs.inner_impl().print(cache, false, tcx));
// lhs and rhs are formatted as HTML, which may be unnecessary // lhs and rhs are formatted as HTML, which may be unnecessary
compare_names(&lhs, &rhs) compare_names(&lhs, &rhs)
...@@ -1247,8 +1255,8 @@ fn render_union( ...@@ -1247,8 +1255,8 @@ fn render_union(
it.name.as_ref().unwrap() it.name.as_ref().unwrap()
); );
if let Some(g) = g { if let Some(g) = g {
write!(w, "{}", g.print(cx.cache())); write!(w, "{}", g.print(cx.cache(), cx.tcx()));
write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true }.print(cx.cache())); write!(w, "{}", print_where_clause(&g, cx.cache(), cx.tcx(), 0, true));
} }
write!(w, " {{\n{}", tab); write!(w, " {{\n{}", tab);
...@@ -1259,7 +1267,7 @@ fn render_union( ...@@ -1259,7 +1267,7 @@ fn render_union(
" {}{}: {},\n{}", " {}{}: {},\n{}",
field.visibility.print_with_space(cx.tcx(), field.def_id, cx.cache()), field.visibility.print_with_space(cx.tcx(), field.def_id, cx.cache()),
field.name.as_ref().unwrap(), field.name.as_ref().unwrap(),
ty.print(cx.cache()), ty.print(cx.cache(), cx.tcx()),
tab tab
); );
} }
...@@ -1289,16 +1297,12 @@ fn render_struct( ...@@ -1289,16 +1297,12 @@ fn render_struct(
it.name.as_ref().unwrap() it.name.as_ref().unwrap()
); );
if let Some(g) = g { if let Some(g) = g {
write!(w, "{}", g.print(cx.cache())) write!(w, "{}", g.print(cx.cache(), cx.tcx()))
} }
match ty { match ty {
CtorKind::Fictive => { CtorKind::Fictive => {
if let Some(g) = g { if let Some(g) = g {
write!( write!(w, "{}", print_where_clause(g, cx.cache(), cx.tcx(), 0, true),)
w,
"{}",
WhereClause { gens: g, indent: 0, end_newline: true }.print(cx.cache())
)
} }
let mut has_visible_fields = false; let mut has_visible_fields = false;
w.write_str(" {"); w.write_str(" {");
...@@ -1310,7 +1314,7 @@ fn render_struct( ...@@ -1310,7 +1314,7 @@ fn render_struct(
tab, tab,
field.visibility.print_with_space(cx.tcx(), field.def_id, cx.cache()), field.visibility.print_with_space(cx.tcx(), field.def_id, cx.cache()),
field.name.as_ref().unwrap(), field.name.as_ref().unwrap(),
ty.print(cx.cache()) ty.print(cx.cache(), cx.tcx()),
); );
has_visible_fields = true; has_visible_fields = true;
} }
...@@ -1341,7 +1345,7 @@ fn render_struct( ...@@ -1341,7 +1345,7 @@ fn render_struct(
w, w,
"{}{}", "{}{}",
field.visibility.print_with_space(cx.tcx(), field.def_id, cx.cache()), field.visibility.print_with_space(cx.tcx(), field.def_id, cx.cache()),
ty.print(cx.cache()) ty.print(cx.cache(), cx.tcx()),
) )
} }
_ => unreachable!(), _ => unreachable!(),
...@@ -1349,22 +1353,14 @@ fn render_struct( ...@@ -1349,22 +1353,14 @@ fn render_struct(
} }
w.write_str(")"); w.write_str(")");
if let Some(g) = g { if let Some(g) = g {
write!( write!(w, "{}", print_where_clause(g, cx.cache(), cx.tcx(), 0, false),)
w,
"{}",
WhereClause { gens: g, indent: 0, end_newline: false }.print(cx.cache())
)
} }
w.write_str(";"); w.write_str(";");
} }
CtorKind::Const => { CtorKind::Const => {
// Needed for PhantomData. // Needed for PhantomData.
if let Some(g) = g { if let Some(g) = g {
write!( write!(w, "{}", print_where_clause(g, cx.cache(), cx.tcx(), 0, false),)
w,
"{}",
WhereClause { gens: g, indent: 0, end_newline: false }.print(cx.cache())
)
} }
w.write_str(";"); w.write_str(";");
} }
......
...@@ -430,7 +430,7 @@ struct Implementor { ...@@ -430,7 +430,7 @@ struct Implementor {
None None
} else { } else {
Some(Implementor { Some(Implementor {
text: imp.inner_impl().print(cx.cache(), false).to_string(), text: imp.inner_impl().print(cx.cache(), false, cx.tcx()).to_string(),
synthetic: imp.inner_impl().synthetic, synthetic: imp.inner_impl().synthetic,
types: collect_paths_for_type(imp.inner_impl().for_.clone(), cx.cache()), types: collect_paths_for_type(imp.inner_impl().for_.clone(), cx.cache()),
}) })
......
此差异已折叠。
...@@ -24,7 +24,7 @@ ...@@ -24,7 +24,7 @@
use crate::formats::cache::Cache; use crate::formats::cache::Cache;
use crate::formats::FormatRenderer; use crate::formats::FormatRenderer;
use crate::html::render::cache::ExternalLocation; use crate::html::render::cache::ExternalLocation;
use crate::json::conversions::from_def_id; use crate::json::conversions::{from_def_id, IntoWithTcx};
#[derive(Clone)] #[derive(Clone)]
crate struct JsonRenderer<'tcx> { crate struct JsonRenderer<'tcx> {
...@@ -108,7 +108,7 @@ fn get_trait_items(&mut self) -> Vec<(types::Id, types::Item)> { ...@@ -108,7 +108,7 @@ fn get_trait_items(&mut self) -> Vec<(types::Id, types::Item)> {
.last() .last()
.map(Clone::clone), .map(Clone::clone),
visibility: types::Visibility::Public, visibility: types::Visibility::Public,
inner: types::ItemEnum::Trait(trait_item.clone().into()), inner: types::ItemEnum::Trait(trait_item.clone().into_tcx(self.tcx)),
span: None, span: None,
docs: Default::default(), docs: Default::default(),
links: Default::default(), links: Default::default(),
...@@ -225,7 +225,11 @@ fn after_krate( ...@@ -225,7 +225,11 @@ fn after_krate(
.map(|(k, (path, kind))| { .map(|(k, (path, kind))| {
( (
from_def_id(k), from_def_id(k),
types::ItemSummary { crate_id: k.krate.as_u32(), path, kind: kind.into() }, types::ItemSummary {
crate_id: k.krate.as_u32(),
path,
kind: kind.into_tcx(self.tcx),
},
) )
}) })
.collect(), .collect(),
......
...@@ -216,8 +216,8 @@ fn fold_item(&mut self, i: clean::Item) -> Option<clean::Item> { ...@@ -216,8 +216,8 @@ fn fold_item(&mut self, i: clean::Item) -> Option<clean::Item> {
if let Some(ref tr) = impl_.trait_ { if let Some(ref tr) = impl_.trait_ {
debug!( debug!(
"impl {:#} for {:#} in {}", "impl {:#} for {:#} in {}",
tr.print(&self.ctx.cache), tr.print(&self.ctx.cache, self.ctx.tcx),
impl_.for_.print(&self.ctx.cache), impl_.for_.print(&self.ctx.cache, self.ctx.tcx),
filename, filename,
); );
...@@ -228,7 +228,11 @@ fn fold_item(&mut self, i: clean::Item) -> Option<clean::Item> { ...@@ -228,7 +228,11 @@ fn fold_item(&mut self, i: clean::Item) -> Option<clean::Item> {
// inherent impls *can* be documented, and those docs show up, but in most // inherent impls *can* be documented, and those docs show up, but in most
// cases it doesn't make sense, as all methods on a type are in one single // cases it doesn't make sense, as all methods on a type are in one single
// impl block // impl block
debug!("impl {:#} in {}", impl_.for_.print(&self.ctx.cache), filename); debug!(
"impl {:#} in {}",
impl_.for_.print(&self.ctx.cache, self.ctx.tcx),
filename
);
} }
} }
_ => { _ => {
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册