Skip to content

Commit 686ec28

Browse files
committed
Auto merge of #42527 - qnighy:unsized-tuple-coercions, r=arielb1
Unsized tuple coercions Part of #18469. Fixes #32702. #37685 and #34451 might also be related. This PR does the following: - Introduce explicit `Sized` constraints on tuple initializers, similar to that of record-struct initializers. Not much relevant to the main contribution but I noticed this when making tests for unsized tuple coercions. - Implement `(.., T): Unsize<(.., U)>` where `T: Unsize<U>`. - Assume `(.., T)` is MaybeUnsizedUnivariant. - Modify `src/librustc/ty/util.rs` and `src/librustc_trans/glue.rs` so that tuples and structs are uniformly traversed when translating.
2 parents d0e0f53 + 94862c6 commit 686ec28

26 files changed

+707
-19
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# `unsized_tuple_coercion`
2+
3+
The tracking issue for this feature is: [#42877]
4+
5+
[#42877]: https://github.com/rust-lang/rust/issues/42877
6+
7+
------------------------
8+
9+
This is a part of [RFC0401]. According to the RFC, there should be an implementation like this:
10+
11+
```rust
12+
impl<..., T, U: ?Sized> Unsized<(..., U)> for (..., T) where T: Unsized<U> {}
13+
```
14+
15+
This implementation is currently gated behind `#[feature(unsized_tuple_coercion)]` to avoid insta-stability. Therefore you can use it like this:
16+
17+
```rust
18+
#![feature(unsized_tuple_coercion)]
19+
20+
fn main() {
21+
let x : ([i32; 3], [i32; 3]) = ([1, 2, 3], [4, 5, 6]);
22+
let y : &([i32; 3], [i32]) = &x;
23+
assert_eq!(y.1[0], 4);
24+
}
25+
```
26+
27+
[RFC0401]: https://github.com/rust-lang/rfcs/blob/master/text/0401-coercions.md

src/librustc/traits/error_reporting.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -1060,7 +1060,7 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
10601060
err.note("slice and array elements must have `Sized` type");
10611061
}
10621062
ObligationCauseCode::TupleElem => {
1063-
err.note("tuple elements must have `Sized` type");
1063+
err.note("only the last element of a tuple may have a dynamically sized type");
10641064
}
10651065
ObligationCauseCode::ProjectionWf(data) => {
10661066
err.note(&format!("required so that the projection `{}` is well-formed",
@@ -1097,6 +1097,9 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
10971097
ObligationCauseCode::AssignmentLhsSized => {
10981098
err.note("the left-hand-side of an assignment must have a statically known size");
10991099
}
1100+
ObligationCauseCode::TupleInitializerSized => {
1101+
err.note("tuples must have a statically known size to be initialized");
1102+
}
11001103
ObligationCauseCode::StructInitializerSized => {
11011104
err.note("structs must have a statically known size to be initialized");
11021105
}

src/librustc/traits/mod.rs

+2
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,8 @@ pub enum ObligationCauseCode<'tcx> {
121121
// Various cases where expressions must be sized/copy/etc:
122122
/// L = X implies that L is Sized
123123
AssignmentLhsSized,
124+
/// (x1, .., xn) must be Sized
125+
TupleInitializerSized,
124126
/// S { ... } must be Sized
125127
StructInitializerSized,
126128
/// Type of each variable must be Sized

src/librustc/traits/select.rs

+38-2
Original file line numberDiff line numberDiff line change
@@ -1651,6 +1651,11 @@ impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> {
16511651
def_id_a == def_id_b
16521652
}
16531653

1654+
// (.., T) -> (.., U).
1655+
(&ty::TyTuple(tys_a, _), &ty::TyTuple(tys_b, _)) => {
1656+
tys_a.len() == tys_b.len()
1657+
}
1658+
16541659
_ => false
16551660
};
16561661

@@ -2591,8 +2596,8 @@ impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> {
25912596
let inner_source = field.subst(tcx, substs_a);
25922597
let inner_target = field.subst(tcx, substs_b);
25932598

2594-
// Check that the source structure with the target's
2595-
// type parameters is a subtype of the target.
2599+
// Check that the source struct with the target's
2600+
// unsized parameters is equal to the target.
25962601
let params = substs_a.iter().enumerate().map(|(i, &k)| {
25972602
if ty_params.contains(i) {
25982603
Kind::from(substs_b.type_at(i))
@@ -2617,6 +2622,37 @@ impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> {
26172622
&[inner_target]));
26182623
}
26192624

2625+
// (.., T) -> (.., U).
2626+
(&ty::TyTuple(tys_a, _), &ty::TyTuple(tys_b, _)) => {
2627+
assert_eq!(tys_a.len(), tys_b.len());
2628+
2629+
// The last field of the tuple has to exist.
2630+
let (a_last, a_mid) = if let Some(x) = tys_a.split_last() {
2631+
x
2632+
} else {
2633+
return Err(Unimplemented);
2634+
};
2635+
let b_last = tys_b.last().unwrap();
2636+
2637+
// Check that the source tuple with the target's
2638+
// last element is equal to the target.
2639+
let new_tuple = tcx.mk_tup(a_mid.iter().chain(Some(b_last)), false);
2640+
let InferOk { obligations, .. } =
2641+
self.infcx.at(&obligation.cause, obligation.param_env)
2642+
.eq(target, new_tuple)
2643+
.map_err(|_| Unimplemented)?;
2644+
self.inferred_obligations.extend(obligations);
2645+
2646+
// Construct the nested T: Unsize<U> predicate.
2647+
nested.push(tcx.predicate_for_trait_def(
2648+
obligation.param_env,
2649+
obligation.cause.clone(),
2650+
obligation.predicate.def_id(),
2651+
obligation.recursion_depth + 1,
2652+
a_last,
2653+
&[b_last]));
2654+
}
2655+
26202656
_ => bug!()
26212657
};
26222658

src/librustc/traits/structural_impls.rs

+3
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,7 @@ impl<'a, 'tcx> Lift<'tcx> for traits::ObligationCauseCode<'a> {
189189
tcx.lift(&ty).map(super::ObjectCastObligation)
190190
}
191191
super::AssignmentLhsSized => Some(super::AssignmentLhsSized),
192+
super::TupleInitializerSized => Some(super::TupleInitializerSized),
192193
super::StructInitializerSized => Some(super::StructInitializerSized),
193194
super::VariableType(id) => Some(super::VariableType(id)),
194195
super::ReturnType(id) => Some(super::ReturnType(id)),
@@ -476,6 +477,7 @@ impl<'tcx> TypeFoldable<'tcx> for traits::ObligationCauseCode<'tcx> {
476477
super::TupleElem |
477478
super::ItemObligation(_) |
478479
super::AssignmentLhsSized |
480+
super::TupleInitializerSized |
479481
super::StructInitializerSized |
480482
super::VariableType(_) |
481483
super::ReturnType(_) |
@@ -523,6 +525,7 @@ impl<'tcx> TypeFoldable<'tcx> for traits::ObligationCauseCode<'tcx> {
523525
super::TupleElem |
524526
super::ItemObligation(_) |
525527
super::AssignmentLhsSized |
528+
super::TupleInitializerSized |
526529
super::StructInitializerSized |
527530
super::VariableType(_) |
528531
super::ReturnType(_) |

src/librustc/ty/layout.rs

+7-3
Original file line numberDiff line numberDiff line change
@@ -1220,12 +1220,16 @@ impl<'a, 'tcx> Layout {
12201220
}
12211221

12221222
ty::TyTuple(tys, _) => {
1223-
// FIXME(camlorn): if we ever allow unsized tuples, this needs to be checked.
1224-
// See the univariant case below to learn how.
1223+
let kind = if tys.len() == 0 {
1224+
StructKind::AlwaysSizedUnivariant
1225+
} else {
1226+
StructKind::MaybeUnsizedUnivariant
1227+
};
1228+
12251229
let st = Struct::new(dl,
12261230
&tys.iter().map(|ty| ty.layout(tcx, param_env))
12271231
.collect::<Result<Vec<_>, _>>()?,
1228-
&ReprOptions::default(), StructKind::AlwaysSizedUnivariant, ty)?;
1232+
&ReprOptions::default(), kind, ty)?;
12291233
Univariant { variant: st, non_zero: false }
12301234
}
12311235

src/librustc/ty/util.rs

+20-9
Original file line numberDiff line numberDiff line change
@@ -317,15 +317,26 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
317317
target: Ty<'tcx>)
318318
-> (Ty<'tcx>, Ty<'tcx>) {
319319
let (mut a, mut b) = (source, target);
320-
while let (&TyAdt(a_def, a_substs), &TyAdt(b_def, b_substs)) = (&a.sty, &b.sty) {
321-
if a_def != b_def || !a_def.is_struct() {
322-
break;
323-
}
324-
match a_def.struct_variant().fields.last() {
325-
Some(f) => {
326-
a = f.ty(self, a_substs);
327-
b = f.ty(self, b_substs);
328-
}
320+
loop {
321+
match (&a.sty, &b.sty) {
322+
(&TyAdt(a_def, a_substs), &TyAdt(b_def, b_substs))
323+
if a_def == b_def && a_def.is_struct() => {
324+
if let Some(f) = a_def.struct_variant().fields.last() {
325+
a = f.ty(self, a_substs);
326+
b = f.ty(self, b_substs);
327+
} else {
328+
break;
329+
}
330+
},
331+
(&TyTuple(a_tys, _), &TyTuple(b_tys, _))
332+
if a_tys.len() == b_tys.len() => {
333+
if let Some(a_last) = a_tys.last() {
334+
a = a_last;
335+
b = b_tys.last().unwrap();
336+
} else {
337+
break;
338+
}
339+
},
329340
_ => break,
330341
}
331342
}

src/librustc_trans/glue.rs

+9-3
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ pub fn size_and_align_of_dst<'a, 'tcx>(bcx: &Builder<'a, 'tcx>, t: Ty<'tcx>, inf
7676
}
7777
assert!(!info.is_null());
7878
match t.sty {
79-
ty::TyAdt(def, substs) => {
79+
ty::TyAdt(..) | ty::TyTuple(..) => {
8080
let ccx = bcx.ccx;
8181
// First get the size of all statically known fields.
8282
// Don't use size_of because it also rounds up to alignment, which we
@@ -101,8 +101,14 @@ pub fn size_and_align_of_dst<'a, 'tcx>(bcx: &Builder<'a, 'tcx>, t: Ty<'tcx>, inf
101101

102102
// Recurse to get the size of the dynamically sized field (must be
103103
// the last field).
104-
let last_field = def.struct_variant().fields.last().unwrap();
105-
let field_ty = monomorphize::field_ty(bcx.tcx(), substs, last_field);
104+
let field_ty = match t.sty {
105+
ty::TyAdt(def, substs) => {
106+
let last_field = def.struct_variant().fields.last().unwrap();
107+
monomorphize::field_ty(bcx.tcx(), substs, last_field)
108+
},
109+
ty::TyTuple(tys, _) => tys.last().unwrap(),
110+
_ => unreachable!(),
111+
};
106112
let (unsized_size, unsized_align) = size_and_align_of_dst(bcx, field_ty, info);
107113

108114
// FIXME (#26403, #27023): We should be adding padding

src/librustc_typeck/check/coercion.rs

+20-1
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ use rustc::ty::relate::RelateResult;
7676
use rustc::ty::subst::Subst;
7777
use errors::DiagnosticBuilder;
7878
use syntax::abi;
79+
use syntax::feature_gate;
7980
use syntax::ptr::P;
8081
use syntax_pos;
8182

@@ -520,14 +521,24 @@ impl<'f, 'gcx, 'tcx> Coerce<'f, 'gcx, 'tcx> {
520521
coerce_source,
521522
&[coerce_target]));
522523

524+
let mut has_unsized_tuple_coercion = false;
525+
523526
// Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid
524527
// emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where
525528
// inference might unify those two inner type variables later.
526529
let traits = [coerce_unsized_did, unsize_did];
527530
while let Some(obligation) = queue.pop_front() {
528531
debug!("coerce_unsized resolve step: {:?}", obligation);
529532
let trait_ref = match obligation.predicate {
530-
ty::Predicate::Trait(ref tr) if traits.contains(&tr.def_id()) => tr.clone(),
533+
ty::Predicate::Trait(ref tr) if traits.contains(&tr.def_id()) => {
534+
if unsize_did == tr.def_id() {
535+
if let ty::TyTuple(..) = tr.0.input_types().nth(1).unwrap().sty {
536+
debug!("coerce_unsized: found unsized tuple coercion");
537+
has_unsized_tuple_coercion = true;
538+
}
539+
}
540+
tr.clone()
541+
}
531542
_ => {
532543
coercion.obligations.push(obligation);
533544
continue;
@@ -557,6 +568,14 @@ impl<'f, 'gcx, 'tcx> Coerce<'f, 'gcx, 'tcx> {
557568
}
558569
}
559570

571+
if has_unsized_tuple_coercion && !self.tcx.sess.features.borrow().unsized_tuple_coercion {
572+
feature_gate::emit_feature_err(&self.tcx.sess.parse_sess,
573+
"unsized_tuple_coercion",
574+
self.cause.span,
575+
feature_gate::GateIssue::Language,
576+
feature_gate::EXPLAIN_UNSIZED_TUPLE_COERCION);
577+
}
578+
560579
Ok(coercion)
561580
}
562581

src/librustc_typeck/check/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -3854,6 +3854,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
38543854
if tuple.references_error() {
38553855
tcx.types.err
38563856
} else {
3857+
self.require_type_is_sized(tuple, expr.span, traits::TupleInitializerSized);
38573858
tuple
38583859
}
38593860
}

src/libsyntax/feature_gate.rs

+6
Original file line numberDiff line numberDiff line change
@@ -357,6 +357,9 @@ declare_features! (
357357

358358
// Allows a test to fail without failing the whole suite
359359
(active, allow_fail, "1.19.0", Some(42219)),
360+
361+
// Allows unsized tuple coercion.
362+
(active, unsized_tuple_coercion, "1.20.0", Some(42877)),
360363
);
361364

362365
declare_features! (
@@ -1041,6 +1044,9 @@ pub const EXPLAIN_VIS_MATCHER: &'static str =
10411044
pub const EXPLAIN_PLACEMENT_IN: &'static str =
10421045
"placement-in expression syntax is experimental and subject to change.";
10431046

1047+
pub const EXPLAIN_UNSIZED_TUPLE_COERCION: &'static str =
1048+
"Unsized tuple coercion is not stable enough for use and is subject to change";
1049+
10441050
struct PostExpansionVisitor<'a> {
10451051
context: &'a Context<'a>,
10461052
}
+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
// Forbid assignment into a dynamically sized type.
12+
13+
#![feature(unsized_tuple_coercion)]
14+
15+
type Fat<T: ?Sized> = (isize, &'static str, T);
16+
//~^ WARNING trait bounds are not (yet) enforced
17+
18+
#[derive(PartialEq,Eq)]
19+
struct Bar;
20+
21+
#[derive(PartialEq,Eq)]
22+
struct Bar1 {
23+
f: isize
24+
}
25+
26+
trait ToBar {
27+
fn to_bar(&self) -> Bar;
28+
fn to_val(&self) -> isize;
29+
}
30+
31+
impl ToBar for Bar1 {
32+
fn to_bar(&self) -> Bar {
33+
Bar
34+
}
35+
fn to_val(&self) -> isize {
36+
self.f
37+
}
38+
}
39+
40+
pub fn main() {
41+
// Assignment.
42+
let f5: &mut Fat<ToBar> = &mut (5, "some str", Bar1 {f :42});
43+
let z: Box<ToBar> = Box::new(Bar1 {f: 36});
44+
f5.2 = Bar1 {f: 36};
45+
//~^ ERROR mismatched types
46+
//~| expected type `ToBar`
47+
//~| found type `Bar1`
48+
//~| expected trait ToBar, found struct `Bar1`
49+
//~| ERROR `ToBar: std::marker::Sized` is not satisfied
50+
}

src/test/compile-fail/dst-bad-coerce1.rs

+14
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010

1111
// Attempt to change the type as well as unsizing.
1212

13+
#![feature(unsized_tuple_coercion)]
14+
1315
struct Fat<T: ?Sized> {
1416
ptr: T
1517
}
@@ -29,4 +31,16 @@ pub fn main() {
2931
let f2: &Fat<Foo> = &f1;
3032
let f3: &Fat<Bar> = f2;
3133
//~^ ERROR `Foo: Bar` is not satisfied
34+
35+
// Tuple with a vec of isize.
36+
let f1 = ([1, 2, 3],);
37+
let f2: &([isize; 3],) = &f1;
38+
let f3: &([usize],) = f2;
39+
//~^ ERROR mismatched types
40+
41+
// Tuple with a trait.
42+
let f1 = (Foo,);
43+
let f2: &(Foo,) = &f1;
44+
let f3: &(Bar,) = f2;
45+
//~^ ERROR `Foo: Bar` is not satisfied
3246
}

src/test/compile-fail/dst-bad-coerce2.rs

+10
Original file line numberDiff line numberDiff line change
@@ -28,4 +28,14 @@ pub fn main() {
2828
let f1 = Fat { ptr: Foo };
2929
let f2: &Fat<Foo> = &f1;
3030
let f3: &mut Fat<Bar> = f2; //~ ERROR mismatched types
31+
32+
// Tuple with a vec of ints.
33+
let f1 = ([1, 2, 3],);
34+
let f2: &([isize; 3],) = &f1;
35+
let f3: &mut ([isize],) = f2; //~ ERROR mismatched types
36+
37+
// Tuple with a trait.
38+
let f1 = (Foo,);
39+
let f2: &(Foo,) = &f1;
40+
let f3: &mut (Bar,) = f2; //~ ERROR mismatched types
3141
}

0 commit comments

Comments
 (0)