Skip to content

Commit f7964ae

Browse files
committed
Implement Copy/Clone for closures
1 parent 01c65cb commit f7964ae

File tree

10 files changed

+212
-18
lines changed

10 files changed

+212
-18
lines changed

src/librustc/traits/select.rs

+22-7
Original file line numberDiff line numberDiff line change
@@ -1340,7 +1340,7 @@ impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> {
13401340
self.assemble_candidates_from_impls(obligation, &mut candidates)?;
13411341

13421342
// For other types, we'll use the builtin rules.
1343-
let copy_conditions = self.copy_conditions(obligation);
1343+
let copy_conditions = self.copy_clone_conditions(obligation);
13441344
self.assemble_builtin_bound_candidates(copy_conditions, &mut candidates)?;
13451345
} else if lang_items.sized_trait() == Some(def_id) {
13461346
// Sized is never implementable by end-users, it is
@@ -1355,7 +1355,7 @@ impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> {
13551355
// Same builtin conditions as `Copy`, i.e. every type which has builtin support
13561356
// for `Copy` also has builtin support for `Clone`, + tuples and arrays of `Clone`
13571357
// types have builtin support for `Clone`.
1358-
let clone_conditions = self.copy_conditions(obligation);
1358+
let clone_conditions = self.copy_clone_conditions(obligation);
13591359
self.assemble_builtin_bound_candidates(clone_conditions, &mut candidates)?;
13601360
}
13611361

@@ -2050,7 +2050,7 @@ impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> {
20502050
}
20512051
}
20522052

2053-
fn copy_conditions(&mut self, obligation: &TraitObligation<'tcx>)
2053+
fn copy_clone_conditions(&mut self, obligation: &TraitObligation<'tcx>)
20542054
-> BuiltinImplConditions<'tcx>
20552055
{
20562056
// NOTE: binder moved to (*)
@@ -2068,8 +2068,7 @@ impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> {
20682068
Where(ty::Binder(Vec::new()))
20692069
}
20702070

2071-
ty::TyDynamic(..) | ty::TyStr | ty::TySlice(..) |
2072-
ty::TyClosure(..) | ty::TyGenerator(..) |
2071+
ty::TyDynamic(..) | ty::TyStr | ty::TySlice(..) | ty::TyGenerator(..) |
20732072
ty::TyRef(_, ty::TypeAndMut { ty: _, mutbl: hir::MutMutable }) => {
20742073
Never
20752074
}
@@ -2084,6 +2083,22 @@ impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> {
20842083
Where(ty::Binder(tys.to_vec()))
20852084
}
20862085

2086+
ty::TyClosure(def_id, substs) => {
2087+
let trait_id = obligation.predicate.def_id();
2088+
let copy_closures =
2089+
Some(trait_id) == self.tcx().lang_items().copy_trait() &&
2090+
self.tcx().sess.features.borrow().copy_closures;
2091+
let clone_closures =
2092+
Some(trait_id) == self.tcx().lang_items().clone_trait() &&
2093+
self.tcx().sess.features.borrow().clone_closures;
2094+
2095+
if copy_closures || clone_closures {
2096+
Where(ty::Binder(substs.upvar_tys(def_id, self.tcx()).collect()))
2097+
} else {
2098+
Never
2099+
}
2100+
}
2101+
20872102
ty::TyAdt(..) | ty::TyProjection(..) | ty::TyParam(..) | ty::TyAnon(..) => {
20882103
// Fallback to whatever user-defined impls exist in this case.
20892104
None
@@ -2370,10 +2385,10 @@ impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> {
23702385
self.sized_conditions(obligation)
23712386
}
23722387
_ if Some(trait_def) == lang_items.copy_trait() => {
2373-
self.copy_conditions(obligation)
2388+
self.copy_clone_conditions(obligation)
23742389
}
23752390
_ if Some(trait_def) == lang_items.clone_trait() => {
2376-
self.copy_conditions(obligation)
2391+
self.copy_clone_conditions(obligation)
23772392
}
23782393
_ => bug!("unexpected builtin trait {:?}", trait_def)
23792394
};

src/librustc/ty/instance.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ pub enum InstanceDef<'tcx> {
3838
/// drop_in_place::<T>; None for empty drop glue.
3939
DropGlue(DefId, Option<Ty<'tcx>>),
4040

41-
/// Builtin method implementation, e.g. `Clone::clone`.
41+
///`<T as Clone>::clone` shim.
4242
CloneShim(DefId, Ty<'tcx>),
4343
}
4444

src/librustc_mir/shim.rs

+17-6
Original file line numberDiff line numberDiff line change
@@ -296,9 +296,15 @@ fn build_clone_shim<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
296296
let len = len.val.to_const_int().unwrap().to_u64().unwrap();
297297
builder.array_shim(ty, len)
298298
}
299-
ty::TyTuple(tys, _) => builder.tuple_shim(tys),
299+
ty::TyClosure(def_id, substs) => {
300+
builder.tuple_like_shim(
301+
&substs.upvar_tys(def_id, tcx).collect::<Vec<_>>(),
302+
AggregateKind::Closure(def_id, substs)
303+
)
304+
}
305+
ty::TyTuple(tys, _) => builder.tuple_like_shim(&**tys, AggregateKind::Tuple),
300306
_ => {
301-
bug!("clone shim for `{:?}` which is not `Copy` and is not an aggregate", self_ty);
307+
bug!("clone shim for `{:?}` which is not `Copy` and is not an aggregate", self_ty)
302308
}
303309
};
304310

@@ -613,7 +619,12 @@ impl<'a, 'tcx> CloneShimBuilder<'a, 'tcx> {
613619
self.block(vec![], TerminatorKind::Resume, true);
614620
}
615621

616-
fn tuple_shim(&mut self, tys: &ty::Slice<Ty<'tcx>>) {
622+
fn tuple_like_shim(&mut self, tys: &[ty::Ty<'tcx>], kind: AggregateKind<'tcx>) {
623+
match kind {
624+
AggregateKind::Tuple | AggregateKind::Closure(..) => (),
625+
_ => bug!("only tuples and closures are accepted"),
626+
};
627+
617628
let rcvr = Lvalue::Local(Local::new(1+0)).deref();
618629

619630
let mut returns = Vec::new();
@@ -646,17 +657,17 @@ impl<'a, 'tcx> CloneShimBuilder<'a, 'tcx> {
646657
}
647658
}
648659

649-
// `return (returns[0], returns[1], ..., returns[tys.len() - 1]);`
660+
// `return kind(returns[0], returns[1], ..., returns[tys.len() - 1]);`
650661
let ret_statement = self.make_statement(
651662
StatementKind::Assign(
652663
Lvalue::Local(RETURN_POINTER),
653664
Rvalue::Aggregate(
654-
box AggregateKind::Tuple,
665+
box kind,
655666
returns.into_iter().map(Operand::Consume).collect()
656667
)
657668
)
658669
);
659-
self.block(vec![ret_statement], TerminatorKind::Return, false);
670+
self.block(vec![ret_statement], TerminatorKind::Return, false);
660671
}
661672
}
662673

src/libsyntax/feature_gate.rs

+27-4
Original file line numberDiff line numberDiff line change
@@ -385,6 +385,10 @@ declare_features! (
385385

386386
// allow '|' at beginning of match arms (RFC 1925)
387387
(active, match_beginning_vert, "1.21.0", Some(44101)),
388+
389+
// Copy/Clone closures (RFC 2132)
390+
(active, clone_closures, "1.22.0", Some(44490)),
391+
(active, copy_closures, "1.22.0", Some(44490)),
388392
);
389393

390394
declare_features! (
@@ -1573,7 +1577,7 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
15731577
pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute]) -> Features {
15741578
let mut features = Features::new();
15751579

1576-
let mut feature_checker = MutexFeatureChecker::default();
1580+
let mut feature_checker = FeatureChecker::default();
15771581

15781582
for attr in krate_attrs {
15791583
if !attr.check_name("feature") {
@@ -1622,14 +1626,16 @@ pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute]) -> F
16221626
features
16231627
}
16241628

1625-
// A collector for mutually-exclusive features and their flag spans
1629+
/// A collector for mutually exclusive and interdependent features and their flag spans.
16261630
#[derive(Default)]
1627-
struct MutexFeatureChecker {
1631+
struct FeatureChecker {
16281632
proc_macro: Option<Span>,
16291633
custom_attribute: Option<Span>,
1634+
copy_closures: Option<Span>,
1635+
clone_closures: Option<Span>,
16301636
}
16311637

1632-
impl MutexFeatureChecker {
1638+
impl FeatureChecker {
16331639
// If this method turns out to be a hotspot due to branching,
16341640
// the branching can be eliminated by modifying `set!()` to set these spans
16351641
// only for the features that need to be checked for mutual exclusion.
@@ -1642,6 +1648,14 @@ impl MutexFeatureChecker {
16421648
if features.custom_attribute {
16431649
self.custom_attribute = self.custom_attribute.or(Some(span));
16441650
}
1651+
1652+
if features.copy_closures {
1653+
self.copy_closures = self.copy_closures.or(Some(span));
1654+
}
1655+
1656+
if features.clone_closures {
1657+
self.clone_closures = self.clone_closures.or(Some(span));
1658+
}
16451659
}
16461660

16471661
fn check(self, handler: &Handler) {
@@ -1653,6 +1667,15 @@ impl MutexFeatureChecker {
16531667

16541668
panic!(FatalError);
16551669
}
1670+
1671+
if let (Some(span), None) = (self.copy_closures, self.clone_closures) {
1672+
handler.struct_span_err(span, "`#![feature(copy_closures)]` can only be used with \
1673+
`#![feature(clone_closures)]`")
1674+
.span_note(span, "`#![feature(copy_closures)]` declared here")
1675+
.emit();
1676+
1677+
panic!(FatalError);
1678+
}
16561679
}
16571680
}
16581681

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// Copyright 2017 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+
#[derive(Clone)]
12+
struct S(i32);
13+
14+
fn main() {
15+
let a = S(5);
16+
let hello = move || {
17+
println!("Hello {}", a.0);
18+
};
19+
20+
let hello = hello.clone(); //~ ERROR no method named `clone` found for type
21+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// Copyright 2017 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+
fn main() {
12+
let a = 5;
13+
let hello = || {
14+
println!("Hello {}", a);
15+
};
16+
17+
let b = hello;
18+
let c = hello; //~ ERROR use of moved value: `hello` [E0382]
19+
}
+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// Copyright 2017 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+
// Check that closures do not implement `Clone` if their environment is not `Clone`.
12+
13+
#![feature(clone_closures)]
14+
15+
struct S(i32);
16+
17+
fn main() {
18+
let a = S(5);
19+
let hello = move || {
20+
println!("Hello {}", a.0);
21+
};
22+
23+
let hello = hello.clone(); //~ ERROR the trait bound `S: std::clone::Clone` is not satisfied
24+
}
+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// Copyright 2017 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+
// Check that closures do not implement `Copy` if their environment is not `Copy`.
12+
13+
#![feature(copy_closures)]
14+
#![feature(clone_closures)]
15+
16+
fn main() {
17+
let mut a = 5;
18+
let hello = || {
19+
a += 1;
20+
};
21+
22+
let b = hello;
23+
let c = hello; //~ ERROR use of moved value: `hello` [E0382]
24+
}

src/test/run-pass/clone-closure.rs

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// Copyright 2017 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+
// Check that closures implement `Clone`.
12+
13+
#![feature(clone_closures)]
14+
15+
#[derive(Clone)]
16+
struct S(i32);
17+
18+
fn main() {
19+
let mut a = S(5);
20+
let mut hello = move || {
21+
a.0 += 1;
22+
println!("Hello {}", a.0);
23+
a.0
24+
};
25+
26+
let mut hello2 = hello.clone();
27+
assert_eq!(6, hello2());
28+
assert_eq!(6, hello());
29+
}

src/test/run-pass/copy-closure.rs

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Copyright 2017 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+
// Check that closures implement `Copy`.
12+
13+
#![feature(copy_closures)]
14+
#![feature(clone_closures)]
15+
16+
fn call<T, F: FnOnce() -> T>(f: F) -> T { f() }
17+
18+
fn main() {
19+
let a = 5;
20+
let hello = || {
21+
println!("Hello {}", a);
22+
a
23+
};
24+
25+
assert_eq!(5, call(hello.clone()));
26+
assert_eq!(5, call(hello));
27+
assert_eq!(5, call(hello));
28+
}

0 commit comments

Comments
 (0)