Skip to content

Commit f2b66d0

Browse files
committed
rustdoc: elide cross-crate default generic arguments
1 parent 7cc36de commit f2b66d0

File tree

8 files changed

+289
-32
lines changed

8 files changed

+289
-32
lines changed

src/librustdoc/clean/utils.rs

Lines changed: 126 additions & 22 deletions
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,44 +82,142 @@ 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-
))),
134+
)))
135+
}
136+
GenericArgKind::Const(ct) => {
107137
// FIXME(effects): this relies on the host effect being called `host`, which users could also name
108138
// their const generics.
109139
// FIXME(effects): this causes `host = true` and `host = false` generics to also be emitted.
110-
GenericArgKind::Const(ct) if let ty::ConstKind::Param(p) = ct.kind() && p.name == sym::host => None,
111-
GenericArgKind::Const(ct) => {
112-
Some(GenericArg::Const(Box::new(clean_middle_const(kind.rebind(ct), cx))))
140+
if let ty::ConstKind::Param(p) = ct.kind()
141+
&& p.name == sym::host
142+
{
143+
return None;
113144
}
145+
146+
if !elision_has_failed_once_before
147+
&& let Some(params) = params
148+
&& let Some(default) = params[index].default_value(cx.tcx)
149+
{
150+
let default =
151+
ty_args.map_bound(|args| default.instantiate(cx.tcx, args).expect_const());
152+
153+
if can_elide_generic_arg(
154+
cx.tcx,
155+
&cause,
156+
param_env,
157+
ty_args.rebind(ct),
158+
default,
159+
params[index].def_id,
160+
) {
161+
return None;
162+
}
163+
164+
elision_has_failed_once_before = true;
165+
}
166+
167+
Some(GenericArg::Const(Box::new(clean_middle_const(ty_args.rebind(ct), cx))))
114168
}
115-
}));
116-
ret_val
169+
};
170+
171+
args.extend(ty_args.skip_binder().iter().enumerate().rev().filter_map(ty_arg_to_arg));
172+
args.reverse();
173+
args
174+
}
175+
176+
/// Check if the generic argument `actual` coincides with the `default` and can therefore be elided.
177+
fn can_elide_generic_arg<'tcx, T: ToTrace<'tcx> + TypeVisitable<TyCtxt<'tcx>>>(
178+
tcx: TyCtxt<'tcx>,
179+
cause: &ObligationCause<'tcx>,
180+
param_env: ty::ParamEnv<'tcx>,
181+
actual: ty::Binder<'tcx, T>,
182+
default: ty::Binder<'tcx, T>,
183+
did: DefId,
184+
) -> bool {
185+
// The operations below are only correct if we don't have any inference variables.
186+
debug_assert!(!actual.has_infer());
187+
debug_assert!(!default.has_infer());
188+
189+
// Since we don't properly keep track of bound variables, don't attempt to make
190+
// any sense out of escaping bound variables (we just don't have enough context).
191+
if actual.has_escaping_bound_vars() || default.has_escaping_bound_vars() {
192+
return false;
193+
}
194+
195+
// If the arguments contain projections or (non-escaping) late-bound regions, we have to examine
196+
// them more closely and can't take the fast path.
197+
// Having projections means that there's potential to be further normalized thereby revealing if
198+
// they are equal after all. Regarding late-bound regions, they can be liberated allowing us to
199+
// consider more types to be equal by ignoring the names of binders.
200+
if !actual.has_late_bound_regions()
201+
&& !actual.has_projections()
202+
&& !default.has_late_bound_regions()
203+
&& !default.has_projections()
204+
{
205+
// Check the memory addresses of the interned arguments for equality.
206+
return actual.skip_binder() == default.skip_binder();
207+
}
208+
209+
let actual = tcx.liberate_late_bound_regions(did, actual);
210+
let default = tcx.liberate_late_bound_regions(did, default);
211+
212+
let infcx = tcx.infer_ctxt().build();
213+
let ocx = ObligationCtxt::new(&infcx);
214+
215+
let actual = ocx.normalize(cause, param_env, actual);
216+
let default = ocx.normalize(cause, param_env, default);
217+
218+
ocx.eq(cause, param_env, actual, default).is_ok()
219+
&& ocx.select_all_or_error().is_empty()
220+
&& infcx.resolve_regions(&OutlivesEnvironment::new(param_env)).is_empty()
117221
}
118222

119223
fn external_generic_args<'tcx>(

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

Lines changed: 1 addition & 1 deletion
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

Lines changed: 45 additions & 0 deletions
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>;
Lines changed: 108 additions & 0 deletions
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

Lines changed: 4 additions & 4 deletions
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

Lines changed: 2 additions & 2 deletions
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

@@ -34,6 +34,6 @@ pub use impl_trait_aux::func4;
3434
pub use impl_trait_aux::func5;
3535

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

0 commit comments

Comments
 (0)