Skip to content

Commit 6bc50e2

Browse files
committed
Auto merge of rust-lang#112463 - fmease:rustdoc-elide-x-crate-def-gen-args, r=<try>
rustdoc: elide cross-crate default generic arguments Early draft. Requesting perf run. Thx :) CC `@GuillaumeGomez` Elide cross-crate generic arguments if they coincide with their default. TL;DR: Most notably, no more `Box<…, Global>` in `std`'s docs, just `Box<…>` from now on. Fixes rust-lang#80379. Also helps with rust-lang#44306. Follow-up to rust-lang#103885,rust-lang#107637. `@rustbot` label T-rustdoc A-cross-crate-reexports S-experimental r? `@ghost`
2 parents e4133ba + ac18bb3 commit 6bc50e2

File tree

8 files changed

+283
-31
lines changed

8 files changed

+283
-31
lines changed

src/librustdoc/clean/utils.rs

+120-21
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,16 @@ use rustc_ast::tokenstream::TokenTree;
1414
use rustc_hir as hir;
1515
use rustc_hir::def::{DefKind, Res};
1616
use rustc_hir::def_id::{DefId, LocalDefId, LOCAL_CRATE};
17+
use rustc_infer::infer::at::ToTrace;
18+
use rustc_infer::infer::outlives::env::OutlivesEnvironment;
1719
use rustc_metadata::rendered_const;
1820
use rustc_middle::mir;
21+
use rustc_middle::traits::ObligationCause;
1922
use rustc_middle::ty::{self, GenericArgKind, GenericArgsRef, TyCtxt};
23+
use rustc_middle::ty::{TypeVisitable, TypeVisitableExt};
2024
use rustc_span::symbol::{kw, sym, Symbol};
25+
use rustc_trait_selection::infer::TyCtxtInferExt;
26+
use rustc_trait_selection::traits::ObligationCtxt;
2127
use std::fmt::Write as _;
2228
use std::mem;
2329
use std::sync::LazyLock as Lazy;
@@ -76,40 +82,133 @@ pub(crate) fn krate(cx: &mut DocContext<'_>) -> Crate {
7682

7783
pub(crate) fn ty_args_to_args<'tcx>(
7884
cx: &mut DocContext<'tcx>,
79-
args: ty::Binder<'tcx, &'tcx [ty::GenericArg<'tcx>]>,
85+
ty_args: ty::Binder<'tcx, &'tcx [ty::GenericArg<'tcx>]>,
8086
has_self: bool,
8187
container: Option<DefId>,
8288
) -> Vec<GenericArg> {
83-
let mut skip_first = has_self;
84-
let mut ret_val =
85-
Vec::with_capacity(args.skip_binder().len().saturating_sub(if skip_first { 1 } else { 0 }));
86-
87-
ret_val.extend(args.iter().enumerate().filter_map(|(index, kind)| {
88-
match kind.skip_binder().unpack() {
89-
GenericArgKind::Lifetime(lt) => {
90-
Some(GenericArg::Lifetime(clean_middle_region(lt).unwrap_or(Lifetime::elided())))
91-
}
92-
GenericArgKind::Type(_) if skip_first => {
93-
skip_first = false;
94-
None
89+
let param_env = ty::ParamEnv::empty();
90+
let cause = ObligationCause::dummy();
91+
let params = container.map(|container| &cx.tcx.generics_of(container).params);
92+
let mut elision_has_failed_once_before = false;
93+
94+
let offset = if has_self { 1 } else { 0 };
95+
let mut args = Vec::with_capacity(ty_args.skip_binder().len().saturating_sub(offset));
96+
97+
let ty_arg_to_arg = |(index, arg): (usize, &ty::GenericArg<'tcx>)| match arg.unpack() {
98+
GenericArgKind::Lifetime(lt) => {
99+
Some(GenericArg::Lifetime(clean_middle_region(lt).unwrap_or(Lifetime::elided())))
100+
}
101+
GenericArgKind::Type(_) if has_self && index == 0 => None,
102+
GenericArgKind::Type(ty) => {
103+
if !elision_has_failed_once_before
104+
&& let Some(params) = params
105+
&& let Some(default) = params[index].default_value(cx.tcx)
106+
{
107+
let default =
108+
ty_args.map_bound(|args| default.instantiate(cx.tcx, args).expect_ty());
109+
110+
if can_elide_generic_arg(
111+
cx.tcx,
112+
&cause,
113+
param_env,
114+
ty_args.rebind(ty),
115+
default,
116+
params[index].def_id,
117+
) {
118+
return None;
119+
}
120+
121+
elision_has_failed_once_before = true;
95122
}
96-
GenericArgKind::Type(ty) => Some(GenericArg::Type(clean_middle_ty(
97-
kind.rebind(ty),
123+
124+
Some(GenericArg::Type(clean_middle_ty(
125+
ty_args.rebind(ty),
98126
cx,
99127
None,
100128
container.map(|container| crate::clean::ContainerTy::Regular {
101129
ty: container,
102-
args,
130+
args: ty_args,
103131
has_self,
104132
arg: index,
105133
}),
106-
))),
107-
GenericArgKind::Const(ct) => {
108-
Some(GenericArg::Const(Box::new(clean_middle_const(kind.rebind(ct), cx))))
134+
)))
135+
}
136+
GenericArgKind::Const(ct) => {
137+
if !elision_has_failed_once_before
138+
&& let Some(params) = params
139+
&& let Some(default) = params[index].default_value(cx.tcx)
140+
{
141+
let default =
142+
ty_args.map_bound(|args| default.instantiate(cx.tcx, args).expect_const());
143+
144+
if can_elide_generic_arg(
145+
cx.tcx,
146+
&cause,
147+
param_env,
148+
ty_args.rebind(ct),
149+
default,
150+
params[index].def_id,
151+
) {
152+
return None;
153+
}
154+
155+
elision_has_failed_once_before = true;
109156
}
157+
158+
Some(GenericArg::Const(Box::new(clean_middle_const(ty_args.rebind(ct), cx))))
110159
}
111-
}));
112-
ret_val
160+
};
161+
162+
args.extend(ty_args.skip_binder().iter().enumerate().rev().filter_map(ty_arg_to_arg));
163+
args.reverse();
164+
args
165+
}
166+
167+
/// Check if the generic argument `actual` coincides with the `default` and can therefore be elided.
168+
fn can_elide_generic_arg<'tcx, T: ToTrace<'tcx> + TypeVisitable<TyCtxt<'tcx>>>(
169+
tcx: TyCtxt<'tcx>,
170+
cause: &ObligationCause<'tcx>,
171+
param_env: ty::ParamEnv<'tcx>,
172+
actual: ty::Binder<'tcx, T>,
173+
default: ty::Binder<'tcx, T>,
174+
did: DefId,
175+
) -> bool {
176+
// The operations below are only correct if we don't have any inference variables.
177+
debug_assert!(!actual.has_infer());
178+
debug_assert!(!default.has_infer());
179+
180+
// Since we don't properly keep track of bound variables, don't attempt to make
181+
// any sense out of escaping bound variables (we just don't have enough context).
182+
if actual.has_escaping_bound_vars() || default.has_escaping_bound_vars() {
183+
return false;
184+
}
185+
186+
// If the arguments contain projections or (non-escaping) late-bound regions, we have to examine
187+
// them more closely and can't take the fast path.
188+
// Having projections means that there's potential to be further normalized thereby revealing if
189+
// they are equal after all. Regarding late-bound regions, they can be liberated allowing us to
190+
// consider more types to be equal by ignoring the names of binders.
191+
if !actual.has_late_bound_regions()
192+
&& !actual.has_projections()
193+
&& !default.has_late_bound_regions()
194+
&& !default.has_projections()
195+
{
196+
// Check the memory addresses of the interned arguments for equality.
197+
return actual.skip_binder() == default.skip_binder();
198+
}
199+
200+
let actual = tcx.liberate_late_bound_regions(did, actual);
201+
let default = tcx.liberate_late_bound_regions(did, default);
202+
203+
let infcx = tcx.infer_ctxt().build();
204+
let ocx = ObligationCtxt::new(&infcx);
205+
206+
let actual = ocx.normalize(cause, param_env, actual);
207+
let default = ocx.normalize(cause, param_env, default);
208+
209+
ocx.eq(cause, param_env, actual, default).is_ok()
210+
&& ocx.select_all_or_error().is_empty()
211+
&& infcx.resolve_regions(&OutlivesEnvironment::new(param_env)).is_empty()
113212
}
114213

115214
fn external_generic_args<'tcx>(

tests/rustdoc/const-generics/add-impl.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ pub struct Simd<T, const WIDTH: usize> {
77
inner: T,
88
}
99

10-
// @has foo/struct.Simd.html '//div[@id="trait-implementations-list"]//h3[@class="code-header"]' 'impl Add<Simd<u8, 16>> for Simd<u8, 16>'
10+
// @has foo/struct.Simd.html '//div[@id="trait-implementations-list"]//h3[@class="code-header"]' 'impl Add for Simd<u8, 16>'
1111
impl Add for Simd<u8, 16> {
1212
type Output = Self;
1313

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
pub type BoxedStr = Box<str>;
2+
pub type IntMap = std::collections::HashMap<i64, u64>;
3+
4+
pub struct TyPair<T, U = T>(T, U);
5+
6+
pub type T0 = TyPair<i32>;
7+
pub type T1 = TyPair<i32, u32>;
8+
pub type T2<K> = TyPair<i32, K>;
9+
pub type T3<Q> = TyPair<Q, Q>;
10+
11+
pub struct CtPair<const C: u32, const D: u32 = C>;
12+
13+
pub type C0 = CtPair<43, 43>;
14+
pub type C1 = CtPair<0, 1>;
15+
pub type C2 = CtPair<{1 + 2}, 3>;
16+
17+
pub struct Re<'a, U = &'a ()>(&'a (), U);
18+
19+
pub type R0<'q> = Re<'q>;
20+
pub type R1<'q> = Re<'q, &'q ()>;
21+
pub type R2<'q> = Re<'q, &'static ()>;
22+
pub type H0 = fn(for<'a> fn(Re<'a>));
23+
pub type H1 = for<'b> fn(for<'a> fn(Re<'a, &'b ()>));
24+
pub type H2 = for<'a> fn(for<'b> fn(Re<'a, &'b ()>));
25+
26+
pub struct Proj<T: Basis, U = <T as Basis>::Assoc>(T, U);
27+
pub trait Basis { type Assoc; }
28+
impl Basis for () { type Assoc = bool; }
29+
30+
pub type P0 = Proj<()>;
31+
pub type P1 = Proj<(), bool>;
32+
pub type P2 = Proj<(), ()>;
33+
34+
pub struct Alpha<T = for<'any> fn(&'any ())>(T);
35+
36+
pub type A0 = Alpha;
37+
pub type A1 = Alpha<for<'arbitrary> fn(&'arbitrary ())>;
38+
39+
pub struct Multi<A = u64, B = u64>(A, B);
40+
41+
pub type M0 = Multi<u64, ()>;
42+
43+
pub trait Trait<'a, T = &'a ()> {}
44+
45+
pub type F = dyn for<'a> Trait<'a>;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
#![crate_name = "user"]
2+
// aux-crate:default_generic_args=default-generic-args.rs
3+
// edition:2021
4+
5+
// @has user/type.BoxedStr.html
6+
// @has - '//*[@class="rust item-decl"]//code' "Box<str>"
7+
pub use default_generic_args::BoxedStr;
8+
9+
// @has user/type.IntMap.html
10+
// @has - '//*[@class="rust item-decl"]//code' "HashMap<i64, u64>"
11+
pub use default_generic_args::IntMap;
12+
13+
// @has user/type.T0.html
14+
// @has - '//*[@class="rust item-decl"]//code' "TyPair<i32>"
15+
pub use default_generic_args::T0;
16+
17+
// @has user/type.T1.html
18+
// @has - '//*[@class="rust item-decl"]//code' "TyPair<i32, u32>"
19+
pub use default_generic_args::T1;
20+
21+
// @has user/type.T2.html
22+
// @has - '//*[@class="rust item-decl"]//code' "TyPair<i32, K>"
23+
pub use default_generic_args::T2;
24+
25+
// @has user/type.T3.html
26+
// @has - '//*[@class="rust item-decl"]//code' "TyPair<Q>"
27+
pub use default_generic_args::T3;
28+
29+
// @has user/type.C0.html
30+
// @has - '//*[@class="rust item-decl"]//code' "CtPair<43>"
31+
pub use default_generic_args::C0;
32+
33+
// @has user/type.C1.html
34+
// @has - '//*[@class="rust item-decl"]//code' "CtPair<0, 1>"
35+
pub use default_generic_args::C1;
36+
37+
// @has user/type.C2.html
38+
// Test that we normalize constants in this case:
39+
// FIXME: Ideally, we would render `3` here instead of the def-path str of the normalized constant.
40+
// @has - '//*[@class="rust item-decl"]//code' "CtPair<default_generic_args::::C2::{constant#0}>"
41+
pub use default_generic_args::C2;
42+
43+
// @has user/type.R0.html
44+
// @has - '//*[@class="rust item-decl"]//code' "Re<'q>"
45+
pub use default_generic_args::R0;
46+
47+
// @has user/type.R1.html
48+
// @has - '//*[@class="rust item-decl"]//code' "Re<'q>"
49+
pub use default_generic_args::R1;
50+
51+
// @has user/type.R2.html
52+
// Check that we consider regions:
53+
// @has - '//*[@class="rust item-decl"]//code' "Re<'q, &'static ()>"
54+
pub use default_generic_args::R2;
55+
56+
// @has user/type.H0.html
57+
// Check that we handle higher-ranked regions correctly:
58+
// FIXME: Ideally we would also print the *binders* here.
59+
// @has - '//*[@class="rust item-decl"]//code' "fn(_: fn(_: Re<'a>))"
60+
pub use default_generic_args::H0;
61+
62+
// @has user/type.H1.html
63+
// Check that we don't conflate distinct universially quantified regions (#1):
64+
// FIXME: Ideally we would also print the *binders* here.
65+
// @has - '//*[@class="rust item-decl"]//code' "fn(_: fn(_: Re<'a, &'b ()>))"
66+
pub use default_generic_args::H1;
67+
68+
// @has user/type.H2.html
69+
// Check that we don't conflate distinct universially quantified regions (#2):
70+
// @has - '//*[@class="rust item-decl"]//code' "fn(_: fn(_: Re<'a, &'b ()>))"
71+
pub use default_generic_args::H2;
72+
73+
// @has user/type.P0.html
74+
// @has - '//*[@class="rust item-decl"]//code' "Proj<()>"
75+
pub use default_generic_args::P0;
76+
77+
// @has user/type.P1.html
78+
// @has - '//*[@class="rust item-decl"]//code' "Proj<()>"
79+
pub use default_generic_args::P1;
80+
81+
// @has user/type.P2.html
82+
// @has - '//*[@class="rust item-decl"]//code' "Proj<(), ()>"
83+
pub use default_generic_args::P2;
84+
85+
// @has user/type.A0.html
86+
// Ensure that we elide generic arguments that are alpha-equivalent to their respective
87+
// generic parameter (modulo substs) (#1):
88+
// @has - '//*[@class="rust item-decl"]//code' "Alpha"
89+
pub use default_generic_args::A0;
90+
91+
// @has user/type.A1.html
92+
// Ensure that we elide generic arguments that are alpha-equivalent to their respective
93+
// generic parameter (modulo substs) (#1):
94+
// @has - '//*[@class="rust item-decl"]//code' "Alpha"
95+
pub use default_generic_args::A1;
96+
97+
// @has user/type.M0.html
98+
// Test that we don't elide `u64` even if it coincides with `A`'s default precisely because
99+
// `()` is not the default of `B`. Mindlessly eliding `u64` would lead to `M<()>` which is a
100+
// different type (`M<(), u64>` versus `M<u64, ()>`).
101+
// @has - '//*[@class="rust item-decl"]//code' "Multi<u64, ()>"
102+
pub use default_generic_args::M0;
103+
104+
// @has user/type.F.html
105+
// FIXME: Ideally, we would elide `&'a ()` but `'a` is an escaping bound var which we can't reason
106+
// about at the moment since we don't keep track of bound vars.
107+
// @has - '//*[@class="rust item-decl"]//code' "dyn for<'a> Trait<'a, &'a ()>"
108+
pub use default_generic_args::F;

tests/rustdoc/inline_cross/dyn_trait.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -75,16 +75,16 @@ pub use dyn_trait::AmbiguousBoundWrappedEarly1;
7575
pub use dyn_trait::AmbiguousBoundWrappedStatic;
7676

7777
// @has user/type.NoBoundsWrappedDefaulted.html
78-
// @has - '//*[@class="rust item-decl"]//code' "Box<dyn Trait, Global>;"
78+
// @has - '//*[@class="rust item-decl"]//code' "Box<dyn Trait>;"
7979
pub use dyn_trait::NoBoundsWrappedDefaulted;
8080
// @has user/type.NoBoundsWrappedEarly.html
81-
// @has - '//*[@class="rust item-decl"]//code' "Box<dyn Trait + 'e, Global>;"
81+
// @has - '//*[@class="rust item-decl"]//code' "Box<dyn Trait + 'e>;"
8282
pub use dyn_trait::NoBoundsWrappedEarly;
8383
// @has user/fn.nbwl.html
84-
// @has - '//pre[@class="rust item-decl"]' "nbwl<'l>(_: Box<dyn Trait + 'l, Global>)"
84+
// @has - '//pre[@class="rust item-decl"]' "nbwl<'l>(_: Box<dyn Trait + 'l>)"
8585
pub use dyn_trait::no_bounds_wrapped_late as nbwl;
8686
// @has user/fn.nbwel.html
87-
// @has - '//pre[@class="rust item-decl"]' "nbwel(_: Box<dyn Trait + '_, Global>)"
87+
// @has - '//pre[@class="rust item-decl"]' "nbwel(_: Box<dyn Trait + '_>)"
8888
// NB: It might seem counterintuitive to display the explicitly elided lifetime `'_` here instead of
8989
// eliding it but this behavior is correct: The default is `'static` here which != `'_`.
9090
pub use dyn_trait::no_bounds_wrapped_elided as nbwel;

tests/rustdoc/inline_cross/impl_trait.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
extern crate impl_trait_aux;
55

66
// @has impl_trait/fn.func.html
7-
// @has - '//pre[@class="rust item-decl"]' "pub fn func<'a>(_x: impl Clone + Into<Vec<u8, Global>> + 'a)"
7+
// @has - '//pre[@class="rust item-decl"]' "pub fn func<'a>(_x: impl Clone + Into<Vec<u8>> + 'a)"
88
// @!has - '//pre[@class="rust item-decl"]' 'where'
99
pub use impl_trait_aux::func;
1010

@@ -38,7 +38,7 @@ pub use impl_trait_aux::func5;
3838
pub use impl_trait_aux::async_fn;
3939

4040
// @has impl_trait/struct.Foo.html
41-
// @has - '//*[@id="method.method"]//h4[@class="code-header"]' "pub fn method<'a>(_x: impl Clone + Into<Vec<u8, Global>> + 'a)"
41+
// @has - '//*[@id="method.method"]//h4[@class="code-header"]' "pub fn method<'a>(_x: impl Clone + Into<Vec<u8>> + 'a)"
4242
// @!has - '//*[@id="method.method"]//h4[@class="code-header"]' 'where'
4343
pub use impl_trait_aux::Foo;
4444

tests/rustdoc/normalize-assoc-item.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ pub fn f2() -> <isize as Trait>::X {
3030
}
3131

3232
pub struct S {
33-
// @has 'normalize_assoc_item/struct.S.html' '//span[@id="structfield.box_me_up"]' 'box_me_up: Box<S, Global>'
33+
// @has 'normalize_assoc_item/struct.S.html' '//span[@id="structfield.box_me_up"]' 'box_me_up: Box<S>'
3434
pub box_me_up: <S as Trait>::X,
3535
// @has 'normalize_assoc_item/struct.S.html' '//span[@id="structfield.generic"]' 'generic: (usize, isize)'
3636
pub generic: <Generic<usize> as Trait>::X,
@@ -76,7 +76,7 @@ extern crate inner;
7676
// @has 'normalize_assoc_item/fn.foo.html' '//pre[@class="rust item-decl"]' "pub fn foo() -> i32"
7777
pub use inner::foo;
7878

79-
// @has 'normalize_assoc_item/fn.h.html' '//pre[@class="rust item-decl"]' "pub fn h<T>() -> IntoIter<T, Global>"
79+
// @has 'normalize_assoc_item/fn.h.html' '//pre[@class="rust item-decl"]' "pub fn h<T>() -> IntoIter<T>"
8080
pub fn h<T>() -> <Vec<T> as IntoIterator>::IntoIter {
8181
vec![].into_iter()
8282
}

0 commit comments

Comments
 (0)