Skip to content

Commit d08f1c3

Browse files
committed
Auto merge of rust-lang#13382 - lowr:fix/reorder-dyn-bounds-on-render, r=lowr
fix: reorder dyn bounds on render Fixes rust-lang#13368 rust-lang#13192 changed the order of dyn bounds, violating the [contract](https://github.com/rust-lang/rust-analyzer/blob/3a69435af7a1e6273744085cb251adb2b9c30a03/crates/hir-ty/src/display.rs#L896-L901) with `write_bounds_like_dyn_trait()` on render. The projection bounds are expected to come right after the trait bound they are accompanied with. Although the reordering procedure can be made a bit more efficient, I opted for relying only on the [invariants](https://github.com/rust-lang/rust-analyzer/blob/3a69435af7a1e6273744085cb251adb2b9c30a03/crates/hir-ty/src/lower.rs#L995-L998) currently documented in `lower_dyn_trait()`. It's not the hottest path and dyn bounds tend to be short so I believe it shouldn't hurt performance noticeably.
2 parents 5d49951 + 5e43ea9 commit d08f1c3

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

crates/hir-ty/src/display.rs

+11-1
Original file line numberDiff line numberDiff line change
@@ -751,9 +751,19 @@ impl HirDisplay for Ty {
751751
}
752752
TyKind::BoundVar(idx) => idx.hir_fmt(f)?,
753753
TyKind::Dyn(dyn_ty) => {
754+
// Reorder bounds to satisfy `write_bounds_like_dyn_trait()`'s expectation.
755+
// FIXME: `Iterator::partition_in_place()` or `Vec::drain_filter()` may make it
756+
// more efficient when either of them hits stable.
757+
let mut bounds: SmallVec<[_; 4]> =
758+
dyn_ty.bounds.skip_binders().iter(Interner).cloned().collect();
759+
let (auto_traits, others): (SmallVec<[_; 4]>, _) =
760+
bounds.drain(1..).partition(|b| b.skip_binders().trait_id().is_some());
761+
bounds.extend(others);
762+
bounds.extend(auto_traits);
763+
754764
write_bounds_like_dyn_trait_with_prefix(
755765
"dyn",
756-
dyn_ty.bounds.skip_binders().interned(),
766+
&bounds,
757767
SizedByDefault::NotSized,
758768
f,
759769
)?;

crates/hir-ty/src/tests/display_source_code.rs

+22
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,28 @@ fn main() {
5555
);
5656
}
5757

58+
#[test]
59+
fn render_dyn_ty_independent_of_order() {
60+
check_types_source_code(
61+
r#"
62+
auto trait Send {}
63+
trait A {
64+
type Assoc;
65+
}
66+
trait B: A {}
67+
68+
fn test(
69+
_: &(dyn A<Assoc = ()> + Send),
70+
//^ &(dyn A<Assoc = ()> + Send)
71+
_: &(dyn Send + A<Assoc = ()>),
72+
//^ &(dyn A<Assoc = ()> + Send)
73+
_: &dyn B<Assoc = ()>,
74+
//^ &(dyn B<Assoc = ()>)
75+
) {}
76+
"#,
77+
);
78+
}
79+
5880
#[test]
5981
fn render_dyn_for_ty() {
6082
// FIXME

0 commit comments

Comments
 (0)