Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP Generic associated types in trait paths #78978

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions compiler/rustc_ast/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1095,7 +1095,11 @@ impl Expr {
pub fn is_potential_trivial_const_param(&self) -> bool {
let this = if let ExprKind::Block(ref block, None) = self.kind {
if block.stmts.len() == 1 {
if let StmtKind::Expr(ref expr) = block.stmts[0].kind { expr } else { self }
if let StmtKind::Expr(ref expr) = block.stmts[0].kind {
expr
} else {
self
}
} else {
self
}
Expand Down Expand Up @@ -1833,6 +1837,7 @@ impl UintTy {
pub struct AssocTyConstraint {
pub id: NodeId,
pub ident: Ident,
pub gen_args: Vec<GenericArg>,
pub kind: AssocTyConstraintKind,
pub span: Span,
}
Expand Down Expand Up @@ -1938,7 +1943,11 @@ impl TyKind {
}

pub fn is_unit(&self) -> bool {
if let TyKind::Tup(ref tys) = *self { tys.is_empty() } else { false }
if let TyKind::Tup(ref tys) = *self {
tys.is_empty()
} else {
false
}
}
}

Expand Down
5 changes: 4 additions & 1 deletion compiler/rustc_ast/src/mut_visit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -444,11 +444,14 @@ pub fn noop_flat_map_arm<T: MutVisitor>(mut arm: Arm, vis: &mut T) -> SmallVec<[
}

pub fn noop_visit_ty_constraint<T: MutVisitor>(
AssocTyConstraint { id, ident, kind, span }: &mut AssocTyConstraint,
AssocTyConstraint { id, ident, gen_args, kind, span }: &mut AssocTyConstraint,
vis: &mut T,
) {
vis.visit_id(id);
vis.visit_ident(ident);
for arg in gen_args {
vis.visit_generic_arg(arg);
}
match kind {
AssocTyConstraintKind::Equality { ref mut ty } => {
vis.visit_ty(ty);
Expand Down
3 changes: 3 additions & 0 deletions compiler/rustc_ast/src/visit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -490,6 +490,9 @@ pub fn walk_assoc_ty_constraint<'a, V: Visitor<'a>>(
constraint: &'a AssocTyConstraint,
) {
visitor.visit_ident(constraint.ident);
for arg in &constraint.gen_args {
visitor.visit_generic_arg(arg);
}
match constraint.kind {
AssocTyConstraintKind::Equality { ref ty } => {
visitor.visit_ty(ty);
Expand Down
30 changes: 22 additions & 8 deletions compiler/rustc_ast_lowering/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1032,18 +1032,18 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
fn lower_assoc_ty_constraint(
&mut self,
constraint: &AssocTyConstraint,
itctx: ImplTraitContext<'_, 'hir>,
mut itctx: ImplTraitContext<'_, 'hir>,
) -> hir::TypeBinding<'hir> {
debug!("lower_assoc_ty_constraint(constraint={:?}, itctx={:?})", constraint, itctx);

let kind = match constraint.kind {
AssocTyConstraintKind::Equality { ref ty } => {
hir::TypeBindingKind::Equality { ty: self.lower_ty(ty, itctx) }
hir::TypeBindingKind::Equality { ty: self.lower_ty(ty, itctx.reborrow()) }
}
AssocTyConstraintKind::Bound { ref bounds } => {
let mut capturable_lifetimes;
// Piggy-back on the `impl Trait` context to figure out the correct behavior.
let (desugar_to_impl_trait, itctx) = match itctx {
let (desugar_to_impl_trait, mut itctx) = match itctx {
// We are in the return position:
//
// fn foo() -> impl Iterator<Item: Debug>
Expand All @@ -1052,7 +1052,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
//
// fn foo() -> impl Iterator<Item = impl Debug>
ImplTraitContext::ReturnPositionOpaqueTy { .. }
| ImplTraitContext::OtherOpaqueTy { .. } => (true, itctx),
| ImplTraitContext::OtherOpaqueTy { .. } => (true, itctx.reborrow()),

// We are in the argument position, but within a dyn type:
//
Expand All @@ -1061,7 +1061,9 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
// so desugar to
//
// fn foo(x: dyn Iterator<Item = impl Debug>)
ImplTraitContext::Universal(..) if self.is_in_dyn_type => (true, itctx),
ImplTraitContext::Universal(..) if self.is_in_dyn_type => {
(true, itctx.reborrow())
}

// In `type Foo = dyn Iterator<Item: Debug>` we desugar to
// `type Foo = dyn Iterator<Item = impl Debug>` but we have to override the
Expand All @@ -1087,7 +1089,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
// so we leave it as is and this gets expanded in astconv to a bound like
// `<T as Iterator>::Item: Debug` where `T` is the type parameter for the
// `impl Iterator`.
_ => (false, itctx),
_ => (false, itctx.reborrow()),
};

if desugar_to_impl_trait {
Expand All @@ -1113,24 +1115,36 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
span: constraint.span,
tokens: None,
},
itctx,
itctx.reborrow(),
);

hir::TypeBindingKind::Equality { ty }
})
} else {
// Desugar `AssocTy: Bounds` into a type binding where the
// later desugars into a trait predicate.
let bounds = self.lower_param_bounds(bounds, itctx);
let bounds = self.lower_param_bounds(bounds, itctx.reborrow());

hir::TypeBindingKind::Constraint { bounds }
}
}
};

debug!(
"lower_assoc_ty_constraint: generic args of AssocTyConstraint: {:?}",
constraint.gen_args
);
let args: &'hir mut [GenericArg<'hir>] = self.arena.alloc_from_iter(
constraint.gen_args.iter().map(|arg| self.lower_generic_arg(&arg, itctx.reborrow())),
);
debug!("lower_assoc_ty_constraint: lowered generic args: {:?}", args);
let bindings: &'hir mut [hir::TypeBinding<'hir>] = arena_vec![self;];
let gen_args = self.arena.alloc(hir::GenericArgs { args, bindings, parenthesized: false });

hir::TypeBinding {
hir_id: self.lower_node_id(constraint.id),
ident: constraint.ident,
gen_args,
kind,
span: constraint.span,
}
Expand Down
5 changes: 4 additions & 1 deletion compiler/rustc_ast_lowering/src/path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,9 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
) -> hir::TypeBinding<'hir> {
let ident = Ident::with_dummy_span(hir::FN_OUTPUT_NAME);
let kind = hir::TypeBindingKind::Equality { ty };
hir::TypeBinding { hir_id: self.next_id(), span, ident, kind }
let args = arena_vec![self;];
let bindings = arena_vec![self;];
let gen_args = self.arena.alloc(hir::GenericArgs { args, bindings, parenthesized: false });
hir::TypeBinding { hir_id: self.next_id(), gen_args, span, ident, kind }
}
}
27 changes: 26 additions & 1 deletion compiler/rustc_ast_passes/src/ast_validation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1350,6 +1350,29 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
}
}

fn get_generic_args_from_path_segment(path_segment: &PathSegment) -> Vec<GenericArg> {
let mut generic_args: Vec<GenericArg> = vec![];
if let Some(ref args) = path_segment.args {
match &**args {
GenericArgs::AngleBracketed(ref angle_args) => {
for arg in &angle_args.args {
match arg {
AngleBracketedArg::Arg(gen_arg) => match gen_arg {
GenericArg::Lifetime(_) | GenericArg::Type(_) => {
generic_args.push((*gen_arg).clone())
}
_ => {}
},
_ => {}
}
}
}
_ => {}
}
}
generic_args
}

/// When encountering an equality constraint in a `where` clause, emit an error. If the code seems
/// like it's setting an associated type, provide an appropriate suggestion.
fn deny_equality_constraints(
Expand All @@ -1372,16 +1395,18 @@ fn deny_equality_constraints(
if param.ident == *ident {
let param = ident;
match &full_path.segments[qself.position..] {
[PathSegment { ident, .. }] => {
[path @ PathSegment { ident, .. }] => {
// Make a new `Path` from `foo::Bar` to `Foo<Bar = RhsTy>`.
let mut assoc_path = full_path.clone();
// Remove `Bar` from `Foo::Bar`.
assoc_path.segments.pop();
let len = assoc_path.segments.len() - 1;
let generic_args = get_generic_args_from_path_segment(&path);
// Build `<Bar = RhsTy>`.
let arg = AngleBracketedArg::Constraint(AssocTyConstraint {
id: rustc_ast::node_id::DUMMY_NODE_ID,
ident: *ident,
gen_args: generic_args,
kind: AssocTyConstraintKind::Equality {
ty: predicate.rhs_ty.clone(),
},
Expand Down
7 changes: 7 additions & 0 deletions compiler/rustc_ast_pretty/src/pprust/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -937,6 +937,13 @@ impl<'a> State<'a> {

pub fn print_assoc_constraint(&mut self, constraint: &ast::AssocTyConstraint) {
self.print_ident(constraint.ident);
if constraint.gen_args.len() > 0 {
self.s.word("<");
for arg in &constraint.gen_args {
self.print_generic_arg(arg);
}
self.s.word(">");
}
self.s.space();
match &constraint.kind {
ast::AssocTyConstraintKind::Equality { ty } => {
Expand Down
7 changes: 6 additions & 1 deletion compiler/rustc_hir/src/hir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -497,7 +497,11 @@ pub struct WhereClause<'hir> {

impl WhereClause<'_> {
pub fn span(&self) -> Option<Span> {
if self.predicates.is_empty() { None } else { Some(self.span) }
if self.predicates.is_empty() {
None
} else {
Some(self.span)
}
petrochenkov marked this conversation as resolved.
Show resolved Hide resolved
}

/// The `WhereClause` under normal circumstances points at either the predicates or the empty
Expand Down Expand Up @@ -1940,6 +1944,7 @@ pub struct TypeBinding<'hir> {
pub hir_id: HirId,
#[stable_hasher(project(name))]
pub ident: Ident,
pub gen_args: &'hir GenericArgs<'hir>,
pub kind: TypeBindingKind<'hir>,
pub span: Span,
}
Expand Down
2 changes: 2 additions & 0 deletions compiler/rustc_hir/src/intravisit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -758,6 +758,8 @@ pub fn walk_assoc_type_binding<'v, V: Visitor<'v>>(
) {
visitor.visit_id(type_binding.hir_id);
visitor.visit_ident(type_binding.ident);
// FIXME: Pass the correct span for the generic arguments here
visitor.visit_generic_args(type_binding.span, type_binding.gen_args);
match type_binding.kind {
TypeBindingKind::Equality { ref ty } => {
visitor.visit_ty(ty);
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_hir_pretty/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1801,6 +1801,7 @@ impl<'a> State<'a> {
for binding in generic_args.bindings.iter() {
start_or_comma(self);
self.print_ident(binding.ident);
self.print_generic_args(binding.gen_args, false, false);
self.s.space();
match generic_args.bindings[0].kind {
hir::TypeBindingKind::Equality { ref ty } => {
Expand Down
Loading