Skip to content

Commit f5079d0

Browse files
committed
Auto merge of rust-lang#134185 - compiler-errors:impl-trait-in-bindings, r=oli-obk
(Re-)Implement `impl_trait_in_bindings` This reimplements the `impl_trait_in_bindings` feature for local bindings. "`impl Trait` in bindings" serve as a form of *trait* ascription, where the type basically functions as an infer var but additionally registering the `impl Trait`'s trait bounds for the infer type. These trait bounds can be used to enforce that predicates hold, and can guide inference (e.g. for closure signature inference): ```rust let _: impl Fn(&u8) -> &u8 = |x| x; ``` They are implemented as an additional set of bounds that are registered when the type is lowered during typeck, and then these bounds are tied to a given `CanonicalUserTypeAscription` for borrowck. We enforce these `CanonicalUserTypeAscription` bounds during borrowck to make sure that the `impl Trait` types are sensitive to lifetimes: ```rust trait Static: 'static {} impl<T> Static for T where T: 'static {} let local = 1; let x: impl Static = &local; //~^ ERROR `local` does not live long enough ``` r? oli-obk cc rust-lang#63065 --- Why can't we just use TAIT inference or something? Well, TAITs in bodies have the problem that they cannot reference lifetimes local to a body. For example: ```rust type TAIT = impl Display; let local = 0; let x: TAIT = &local; //~^ ERROR `local` does not live long enough ``` That's because TAITs requires us to do *opaque type inference* which is pretty strict, since we need to remap all of the lifetimes of the hidden type to universal regions. This is simply not possible here. --- I consider this part of the "impl trait everywhere" experiment. I'm not certain if this needs yet another lang team experiment.
2 parents ed14192 + d714a22 commit f5079d0

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

53 files changed

+442
-52
lines changed

compiler/rustc_ast_lowering/src/block.rs

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
use rustc_ast::{Block, BlockCheckMode, Local, LocalKind, Stmt, StmtKind};
22
use rustc_hir as hir;
3+
use rustc_span::sym;
34
use smallvec::SmallVec;
45

56
use crate::{ImplTraitContext, ImplTraitPosition, LoweringContext};
@@ -82,11 +83,21 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
8283
(self.arena.alloc_from_iter(stmts), expr)
8384
}
8485

86+
/// Return an `ImplTraitContext` that allows impl trait in bindings if
87+
/// the feature gate is enabled, or issues a feature error if it is not.
88+
fn impl_trait_in_bindings_ctxt(&self, position: ImplTraitPosition) -> ImplTraitContext {
89+
if self.tcx.features().impl_trait_in_bindings() {
90+
ImplTraitContext::InBinding
91+
} else {
92+
ImplTraitContext::FeatureGated(position, sym::impl_trait_in_bindings)
93+
}
94+
}
95+
8596
fn lower_local(&mut self, l: &Local) -> &'hir hir::LetStmt<'hir> {
86-
let ty = l
87-
.ty
88-
.as_ref()
89-
.map(|t| self.lower_ty(t, ImplTraitContext::Disallowed(ImplTraitPosition::Variable)));
97+
// Let statements are allowed to have impl trait in bindings.
98+
let ty = l.ty.as_ref().map(|t| {
99+
self.lower_ty(t, self.impl_trait_in_bindings_ctxt(ImplTraitPosition::Variable))
100+
});
90101
let init = l.kind.init().map(|init| self.lower_expr(init));
91102
let hir_id = self.lower_node_id(l.id);
92103
let pat = self.lower_pat(&l.pat);

compiler/rustc_ast_lowering/src/lib.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -260,6 +260,13 @@ enum ImplTraitContext {
260260
/// equivalent to a new opaque type like `type T = impl Debug; fn foo() -> T`.
261261
///
262262
OpaqueTy { origin: hir::OpaqueTyOrigin<LocalDefId> },
263+
264+
/// Treat `impl Trait` as a "trait ascription", which is like a type
265+
/// variable but that also enforces that a set of trait goals hold.
266+
///
267+
/// This is useful to guide inference for unnameable types.
268+
InBinding,
269+
263270
/// `impl Trait` is unstably accepted in this position.
264271
FeatureGated(ImplTraitPosition, Symbol),
265272
/// `impl Trait` is not accepted in this position.
@@ -1327,6 +1334,9 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
13271334
}
13281335
path
13291336
}
1337+
ImplTraitContext::InBinding => {
1338+
hir::TyKind::TraitAscription(self.lower_param_bounds(bounds, itctx))
1339+
}
13301340
ImplTraitContext::FeatureGated(position, feature) => {
13311341
let guar = self
13321342
.tcx

compiler/rustc_borrowck/src/type_check/canonical.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -275,7 +275,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
275275
user_ty: ty::UserType<'tcx>,
276276
span: Span,
277277
) {
278-
let ty::UserType::Ty(user_ty) = user_ty else { bug!() };
278+
let ty::UserTypeKind::Ty(user_ty) = user_ty.kind else { bug!() };
279279

280280
// A fast path for a common case with closure input/output types.
281281
if let ty::Infer(_) = user_ty.kind() {

compiler/rustc_borrowck/src/type_check/input_output.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
110110
) {
111111
self.ascribe_user_type_skip_wf(
112112
arg_decl.ty,
113-
ty::UserType::Ty(user_ty),
113+
ty::UserType::new(ty::UserTypeKind::Ty(user_ty)),
114114
arg_decl.source_info.span,
115115
);
116116
}
@@ -119,7 +119,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
119119
let output_decl = &body.local_decls[RETURN_PLACE];
120120
self.ascribe_user_type_skip_wf(
121121
output_decl.ty,
122-
ty::UserType::Ty(user_provided_sig.output()),
122+
ty::UserType::new(ty::UserTypeKind::Ty(user_provided_sig.output())),
123123
output_decl.source_info.span,
124124
);
125125
}

compiler/rustc_borrowck/src/type_check/mod.rs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ use rustc_middle::ty::visit::TypeVisitableExt;
3131
use rustc_middle::ty::{
3232
self, Binder, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, CoroutineArgsExt,
3333
Dynamic, GenericArgsRef, OpaqueHiddenType, OpaqueTypeKey, RegionVid, Ty, TyCtxt, UserArgs,
34-
UserType, UserTypeAnnotationIndex,
34+
UserTypeAnnotationIndex,
3535
};
3636
use rustc_middle::{bug, span_bug};
3737
use rustc_mir_dataflow::ResultsCursor;
@@ -370,7 +370,10 @@ impl<'a, 'b, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'tcx> {
370370
} else {
371371
self.cx.ascribe_user_type(
372372
constant.const_.ty(),
373-
UserType::TypeOf(uv.def, UserArgs { args: uv.args, user_self_ty: None }),
373+
ty::UserType::new(ty::UserTypeKind::TypeOf(uv.def, UserArgs {
374+
args: uv.args,
375+
user_self_ty: None,
376+
})),
374377
locations.span(self.cx.body),
375378
);
376379
}
@@ -991,9 +994,10 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
991994
for user_annotation in self.user_type_annotations {
992995
let CanonicalUserTypeAnnotation { span, ref user_ty, inferred_ty } = *user_annotation;
993996
let annotation = self.instantiate_canonical(span, user_ty);
994-
if let ty::UserType::TypeOf(def, args) = annotation
997+
if let ty::UserTypeKind::TypeOf(def, args) = annotation.kind
995998
&& let DefKind::InlineConst = tcx.def_kind(def)
996999
{
1000+
assert!(annotation.bounds.is_empty());
9971001
self.check_inline_const(inferred_ty, def.expect_local(), args, span);
9981002
} else {
9991003
self.ascribe_user_type(inferred_ty, annotation, span);

compiler/rustc_feature/src/removed.rs

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -126,9 +126,6 @@ declare_features! (
126126
better implied higher-ranked implied bounds support"
127127
)
128128
),
129-
/// Allows `impl Trait` in bindings (`let`, `const`, `static`).
130-
(removed, impl_trait_in_bindings, "1.55.0", Some(63065),
131-
Some("the implementation was not maintainable, the feature may get reintroduced once the current refactorings are done")),
132129
(removed, import_shadowing, "1.0.0", None, None),
133130
/// Allows in-band quantification of lifetime bindings (e.g., `fn foo(x: &'a u8) -> &'a u8`).
134131
(removed, in_band_lifetimes, "1.23.0", Some(44524),

compiler/rustc_feature/src/unstable.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -517,6 +517,8 @@ declare_features! (
517517
(unstable, if_let_guard, "1.47.0", Some(51114)),
518518
/// Allows `impl Trait` to be used inside associated types (RFC 2515).
519519
(unstable, impl_trait_in_assoc_type, "1.70.0", Some(63063)),
520+
/// Allows `impl Trait` in bindings (`let`).
521+
(unstable, impl_trait_in_bindings, "1.64.0", Some(63065)),
520522
/// Allows `impl Trait` as output type in `Fn` traits in return position of functions.
521523
(unstable, impl_trait_in_fn_trait_return, "1.64.0", Some(99697)),
522524
/// Allows associated types in inherent impls.

compiler/rustc_hir/src/hir.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2906,6 +2906,8 @@ pub enum TyKind<'hir> {
29062906
Path(QPath<'hir>),
29072907
/// An opaque type definition itself. This is only used for `impl Trait`.
29082908
OpaqueDef(&'hir OpaqueTy<'hir>),
2909+
/// A trait ascription type, which is `impl Trait` within a local binding.
2910+
TraitAscription(GenericBounds<'hir>),
29092911
/// A trait object type `Bound1 + Bound2 + Bound3`
29102912
/// where `Bound` is a trait or a lifetime.
29112913
TraitObject(&'hir [PolyTraitRef<'hir>], &'hir Lifetime, TraitObjectSyntax),

compiler/rustc_hir/src/intravisit.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -900,6 +900,9 @@ pub fn walk_ty<'v, V: Visitor<'v>>(visitor: &mut V, typ: &'v Ty<'v>) -> V::Resul
900900
TyKind::OpaqueDef(opaque) => {
901901
try_visit!(visitor.visit_opaque_ty(opaque));
902902
}
903+
TyKind::TraitAscription(bounds) => {
904+
walk_list!(visitor, visit_param_bound, bounds);
905+
}
903906
TyKind::Array(ref ty, ref length) => {
904907
try_visit!(visitor.visit_ty(ty));
905908
try_visit!(visitor.visit_const_arg(length));

compiler/rustc_hir_analysis/src/collect.rs

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ use rustc_errors::{
2929
use rustc_hir::def::DefKind;
3030
use rustc_hir::def_id::{DefId, LocalDefId};
3131
use rustc_hir::intravisit::{self, Visitor, walk_generics};
32-
use rustc_hir::{self as hir, GenericParamKind, Node};
32+
use rustc_hir::{self as hir, GenericParamKind, HirId, Node};
3333
use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
3434
use rustc_infer::traits::ObligationCause;
3535
use rustc_middle::hir::nested_filter;
@@ -437,6 +437,15 @@ impl<'tcx> HirTyLowerer<'tcx> for ItemCtxt<'tcx> {
437437
ty::Const::new_error_with_message(self.tcx(), span, "bad placeholder constant")
438438
}
439439

440+
fn register_trait_ascription_bounds(
441+
&self,
442+
_: Vec<(ty::Clause<'tcx>, Span)>,
443+
_: HirId,
444+
span: Span,
445+
) {
446+
self.dcx().span_delayed_bug(span, "trait ascription type not allowed here");
447+
}
448+
440449
fn probe_ty_param_bounds(
441450
&self,
442451
span: Span,

0 commit comments

Comments
 (0)