Skip to content

Commit db32a2e

Browse files
committed
Implement inline associated type bounds
Like `Iterator<Item: SomeTrait>`. This is an unstable feature, but it's used in the standard library e.g. in the definition of Flatten, so we can't get away with not implementing it :)
1 parent c388130 commit db32a2e

File tree

6 files changed

+120
-17
lines changed

6 files changed

+120
-17
lines changed

crates/ra_hir_def/src/data.rs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ use ra_syntax::ast::{
1515
use crate::{
1616
attr::Attrs,
1717
db::DefDatabase,
18-
path::{path, GenericArgs, Path},
18+
path::{path, AssociatedTypeBinding, GenericArgs, Path},
1919
src::HasSource,
2020
type_ref::{Mutability, TypeBound, TypeRef},
2121
visibility::RawVisibility,
@@ -95,7 +95,11 @@ fn desugar_future_path(orig: TypeRef) -> Path {
9595
let path = path![std::future::Future];
9696
let mut generic_args: Vec<_> = std::iter::repeat(None).take(path.segments.len() - 1).collect();
9797
let mut last = GenericArgs::empty();
98-
last.bindings.push((name![Output], orig));
98+
last.bindings.push(AssociatedTypeBinding {
99+
name: name![Output],
100+
type_ref: Some(orig),
101+
bounds: Vec::new(),
102+
});
99103
generic_args.push(Some(Arc::new(last)));
100104

101105
Path::from_known_path(path, generic_args)

crates/ra_hir_def/src/path.rs

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,10 @@ use hir_expand::{
1414
use ra_db::CrateId;
1515
use ra_syntax::ast;
1616

17-
use crate::{type_ref::TypeRef, InFile};
17+
use crate::{
18+
type_ref::{TypeBound, TypeRef},
19+
InFile,
20+
};
1821

1922
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
2023
pub struct ModPath {
@@ -111,7 +114,21 @@ pub struct GenericArgs {
111114
/// is left out.
112115
pub has_self_type: bool,
113116
/// Associated type bindings like in `Iterator<Item = T>`.
114-
pub bindings: Vec<(Name, TypeRef)>,
117+
pub bindings: Vec<AssociatedTypeBinding>,
118+
}
119+
120+
/// An associated type binding like in `Iterator<Item = T>`.
121+
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
122+
pub struct AssociatedTypeBinding {
123+
/// The name of the associated type.
124+
pub name: Name,
125+
/// The type bound to this associated type (in `Item = T`, this would be the
126+
/// `T`). This can be `None` if there are bounds instead.
127+
pub type_ref: Option<TypeRef>,
128+
/// Bounds for the associated type, like in `Iterator<Item:
129+
/// SomeOtherTrait>`. (This is the unstable `associated_type_bounds`
130+
/// feature.)
131+
pub bounds: Vec<TypeBound>,
115132
}
116133

117134
/// A single generic argument.

crates/ra_hir_def/src/path/lower.rs

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,12 @@ use hir_expand::{
99
hygiene::Hygiene,
1010
name::{name, AsName},
1111
};
12-
use ra_syntax::ast::{self, AstNode, TypeAscriptionOwner};
12+
use ra_syntax::ast::{self, AstNode, TypeAscriptionOwner, TypeBoundsOwner};
1313

14+
use super::AssociatedTypeBinding;
1415
use crate::{
1516
path::{GenericArg, GenericArgs, ModPath, Path, PathKind},
16-
type_ref::TypeRef,
17+
type_ref::{TypeBound, TypeRef},
1718
};
1819

1920
pub(super) use lower_use::lower_use_tree;
@@ -136,10 +137,16 @@ pub(super) fn lower_generic_args(node: ast::TypeArgList) -> Option<GenericArgs>
136137
// lifetimes ignored for now
137138
let mut bindings = Vec::new();
138139
for assoc_type_arg in node.assoc_type_args() {
140+
let assoc_type_arg: ast::AssocTypeArg = assoc_type_arg;
139141
if let Some(name_ref) = assoc_type_arg.name_ref() {
140142
let name = name_ref.as_name();
141-
let type_ref = TypeRef::from_ast_opt(assoc_type_arg.type_ref());
142-
bindings.push((name, type_ref));
143+
let type_ref = assoc_type_arg.type_ref().map(TypeRef::from_ast);
144+
let bounds = if let Some(l) = assoc_type_arg.type_bound_list() {
145+
l.bounds().map(TypeBound::from_ast).collect()
146+
} else {
147+
Vec::new()
148+
};
149+
bindings.push(AssociatedTypeBinding { name, type_ref, bounds });
143150
}
144151
}
145152
if args.is_empty() && bindings.is_empty() {
@@ -168,7 +175,11 @@ fn lower_generic_args_from_fn_path(
168175
}
169176
if let Some(ret_type) = ret_type {
170177
let type_ref = TypeRef::from_ast_opt(ret_type.type_ref());
171-
bindings.push((name![Output], type_ref))
178+
bindings.push(AssociatedTypeBinding {
179+
name: name![Output],
180+
type_ref: Some(type_ref),
181+
bounds: Vec::new(),
182+
});
172183
}
173184
if args.is_empty() && bindings.is_empty() {
174185
None

crates/ra_hir_def/src/type_ref.rs

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -163,8 +163,16 @@ impl TypeRef {
163163
let crate::path::GenericArg::Type(type_ref) = arg;
164164
go(type_ref, f);
165165
}
166-
for (_, type_ref) in &args_and_bindings.bindings {
167-
go(type_ref, f);
166+
for binding in &args_and_bindings.bindings {
167+
if let Some(type_ref) = &binding.type_ref {
168+
go(type_ref, f);
169+
}
170+
for bound in &binding.bounds {
171+
match bound {
172+
TypeBound::Path(path) => go_path(path, f),
173+
TypeBound::Error => (),
174+
}
175+
}
168176
}
169177
}
170178
}

crates/ra_hir_ty/src/lower.rs

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
use std::iter;
99
use std::sync::Arc;
1010

11+
use smallvec::SmallVec;
12+
1113
use hir_def::{
1214
adt::StructKind,
1315
builtin_type::BuiltinType,
@@ -596,21 +598,35 @@ fn assoc_type_bindings_from_type_bound<'a>(
596598
.into_iter()
597599
.flat_map(|segment| segment.args_and_bindings.into_iter())
598600
.flat_map(|args_and_bindings| args_and_bindings.bindings.iter())
599-
.map(move |(name, type_ref)| {
601+
.flat_map(move |binding| {
600602
let associated_ty = associated_type_by_name_including_super_traits(
601603
ctx.db.upcast(),
602604
trait_ref.trait_,
603-
&name,
605+
&binding.name,
604606
);
605607
let associated_ty = match associated_ty {
606-
None => return GenericPredicate::Error,
608+
None => return SmallVec::<[GenericPredicate; 1]>::new(),
607609
Some(t) => t,
608610
};
609611
let projection_ty =
610612
ProjectionTy { associated_ty, parameters: trait_ref.substs.clone() };
611-
let ty = Ty::from_hir(ctx, type_ref);
612-
let projection_predicate = ProjectionPredicate { projection_ty, ty };
613-
GenericPredicate::Projection(projection_predicate)
613+
let mut preds = SmallVec::with_capacity(
614+
binding.type_ref.as_ref().map_or(0, |_| 1) + binding.bounds.len(),
615+
);
616+
if let Some(type_ref) = &binding.type_ref {
617+
let ty = Ty::from_hir(ctx, type_ref);
618+
let projection_predicate =
619+
ProjectionPredicate { projection_ty: projection_ty.clone(), ty };
620+
preds.push(GenericPredicate::Projection(projection_predicate));
621+
}
622+
for bound in &binding.bounds {
623+
preds.extend(GenericPredicate::from_type_bound(
624+
ctx,
625+
bound,
626+
Ty::Projection(projection_ty.clone()),
627+
));
628+
}
629+
preds
614630
})
615631
}
616632

crates/ra_hir_ty/src/tests/traits.rs

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1923,6 +1923,53 @@ fn test<T, U>() where T: Trait<U::Item>, U: Trait<T::Item> {
19231923
assert_eq!(t, "{unknown}");
19241924
}
19251925

1926+
#[test]
1927+
fn inline_assoc_type_bounds_1() {
1928+
let t = type_at(
1929+
r#"
1930+
//- /main.rs
1931+
trait Iterator {
1932+
type Item;
1933+
}
1934+
trait OtherTrait<T> {
1935+
fn foo(&self) -> T;
1936+
}
1937+
1938+
// workaround for Chalk assoc type normalization problems
1939+
pub struct S<T>;
1940+
impl<T: Iterator> Iterator for S<T> {
1941+
type Item = <T as Iterator>::Item;
1942+
}
1943+
1944+
fn test<I: Iterator<Item: OtherTrait<u32>>>() {
1945+
let x: <S<I> as Iterator>::Item;
1946+
x.foo()<|>;
1947+
}
1948+
"#,
1949+
);
1950+
assert_eq!(t, "u32");
1951+
}
1952+
1953+
#[test]
1954+
fn inline_assoc_type_bounds_2() {
1955+
let t = type_at(
1956+
r#"
1957+
//- /main.rs
1958+
trait Iterator {
1959+
type Item;
1960+
}
1961+
1962+
fn test<I: Iterator<Item: Iterator<Item = u32>>>() {
1963+
let x: <<I as Iterator>::Item as Iterator>::Item;
1964+
x<|>;
1965+
}
1966+
"#,
1967+
);
1968+
// assert_eq!(t, "u32");
1969+
// doesn't currently work, Chalk #234
1970+
assert_eq!(t, "{unknown}");
1971+
}
1972+
19261973
#[test]
19271974
fn unify_impl_trait() {
19281975
assert_snapshot!(

0 commit comments

Comments
 (0)