diff --git a/src/librustc/traits/select.rs b/src/librustc/traits/select.rs index f5f69ad0a7c..e8a6c5a0347 100644 --- a/src/librustc/traits/select.rs +++ b/src/librustc/traits/select.rs @@ -1340,7 +1340,7 @@ impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> { self.assemble_candidates_from_impls(obligation, &mut candidates)?; // For other types, we'll use the builtin rules. - let copy_conditions = self.copy_conditions(obligation); + let copy_conditions = self.copy_clone_conditions(obligation); self.assemble_builtin_bound_candidates(copy_conditions, &mut candidates)?; } else if lang_items.sized_trait() == Some(def_id) { // Sized is never implementable by end-users, it is @@ -1355,7 +1355,7 @@ impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> { // Same builtin conditions as `Copy`, i.e. every type which has builtin support // for `Copy` also has builtin support for `Clone`, + tuples and arrays of `Clone` // types have builtin support for `Clone`. - let clone_conditions = self.copy_conditions(obligation); + let clone_conditions = self.copy_clone_conditions(obligation); self.assemble_builtin_bound_candidates(clone_conditions, &mut candidates)?; } @@ -2050,7 +2050,7 @@ impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> { } } - fn copy_conditions(&mut self, obligation: &TraitObligation<'tcx>) + fn copy_clone_conditions(&mut self, obligation: &TraitObligation<'tcx>) -> BuiltinImplConditions<'tcx> { // NOTE: binder moved to (*) @@ -2068,8 +2068,7 @@ impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> { Where(ty::Binder(Vec::new())) } - ty::TyDynamic(..) | ty::TyStr | ty::TySlice(..) | - ty::TyClosure(..) | ty::TyGenerator(..) | + ty::TyDynamic(..) | ty::TyStr | ty::TySlice(..) | ty::TyGenerator(..) | ty::TyRef(_, ty::TypeAndMut { ty: _, mutbl: hir::MutMutable }) => { Never } @@ -2084,6 +2083,22 @@ impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> { Where(ty::Binder(tys.to_vec())) } + ty::TyClosure(def_id, substs) => { + let trait_id = obligation.predicate.def_id(); + let copy_closures = + Some(trait_id) == self.tcx().lang_items().copy_trait() && + self.tcx().sess.features.borrow().copy_closures; + let clone_closures = + Some(trait_id) == self.tcx().lang_items().clone_trait() && + self.tcx().sess.features.borrow().clone_closures; + + if copy_closures || clone_closures { + Where(ty::Binder(substs.upvar_tys(def_id, self.tcx()).collect())) + } else { + Never + } + } + ty::TyAdt(..) | ty::TyProjection(..) | ty::TyParam(..) | ty::TyAnon(..) => { // Fallback to whatever user-defined impls exist in this case. None @@ -2370,10 +2385,10 @@ impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> { self.sized_conditions(obligation) } _ if Some(trait_def) == lang_items.copy_trait() => { - self.copy_conditions(obligation) + self.copy_clone_conditions(obligation) } _ if Some(trait_def) == lang_items.clone_trait() => { - self.copy_conditions(obligation) + self.copy_clone_conditions(obligation) } _ => bug!("unexpected builtin trait {:?}", trait_def) }; diff --git a/src/librustc/ty/instance.rs b/src/librustc/ty/instance.rs index d9c6843fad7..871a23863ac 100644 --- a/src/librustc/ty/instance.rs +++ b/src/librustc/ty/instance.rs @@ -38,7 +38,7 @@ pub enum InstanceDef<'tcx> { /// drop_in_place::; None for empty drop glue. DropGlue(DefId, Option>), - /// Builtin method implementation, e.g. `Clone::clone`. + ///`::clone` shim. CloneShim(DefId, Ty<'tcx>), } diff --git a/src/librustc_mir/shim.rs b/src/librustc_mir/shim.rs index 3c9d95ca215..31480457723 100644 --- a/src/librustc_mir/shim.rs +++ b/src/librustc_mir/shim.rs @@ -296,9 +296,15 @@ fn build_clone_shim<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, let len = len.val.to_const_int().unwrap().to_u64().unwrap(); builder.array_shim(ty, len) } - ty::TyTuple(tys, _) => builder.tuple_shim(tys), + ty::TyClosure(def_id, substs) => { + builder.tuple_like_shim( + &substs.upvar_tys(def_id, tcx).collect::>(), + AggregateKind::Closure(def_id, substs) + ) + } + ty::TyTuple(tys, _) => builder.tuple_like_shim(&**tys, AggregateKind::Tuple), _ => { - bug!("clone shim for `{:?}` which is not `Copy` and is not an aggregate", self_ty); + bug!("clone shim for `{:?}` which is not `Copy` and is not an aggregate", self_ty) } }; @@ -613,7 +619,12 @@ impl<'a, 'tcx> CloneShimBuilder<'a, 'tcx> { self.block(vec![], TerminatorKind::Resume, true); } - fn tuple_shim(&mut self, tys: &ty::Slice>) { + fn tuple_like_shim(&mut self, tys: &[ty::Ty<'tcx>], kind: AggregateKind<'tcx>) { + match kind { + AggregateKind::Tuple | AggregateKind::Closure(..) => (), + _ => bug!("only tuples and closures are accepted"), + }; + let rcvr = Lvalue::Local(Local::new(1+0)).deref(); let mut returns = Vec::new(); @@ -646,17 +657,17 @@ impl<'a, 'tcx> CloneShimBuilder<'a, 'tcx> { } } - // `return (returns[0], returns[1], ..., returns[tys.len() - 1]);` + // `return kind(returns[0], returns[1], ..., returns[tys.len() - 1]);` let ret_statement = self.make_statement( StatementKind::Assign( Lvalue::Local(RETURN_POINTER), Rvalue::Aggregate( - box AggregateKind::Tuple, + box kind, returns.into_iter().map(Operand::Consume).collect() ) ) ); - self.block(vec![ret_statement], TerminatorKind::Return, false); + self.block(vec![ret_statement], TerminatorKind::Return, false); } } diff --git a/src/libsyntax/feature_gate.rs b/src/libsyntax/feature_gate.rs index ae0dd872963..6560943a932 100644 --- a/src/libsyntax/feature_gate.rs +++ b/src/libsyntax/feature_gate.rs @@ -385,6 +385,10 @@ declare_features! ( // allow '|' at beginning of match arms (RFC 1925) (active, match_beginning_vert, "1.21.0", Some(44101)), + + // Copy/Clone closures (RFC 2132) + (active, clone_closures, "1.22.0", Some(44490)), + (active, copy_closures, "1.22.0", Some(44490)), ); declare_features! ( @@ -1573,7 +1577,7 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute]) -> Features { let mut features = Features::new(); - let mut feature_checker = MutexFeatureChecker::default(); + let mut feature_checker = FeatureChecker::default(); for attr in krate_attrs { if !attr.check_name("feature") { @@ -1622,14 +1626,16 @@ pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute]) -> F features } -// A collector for mutually-exclusive features and their flag spans +/// A collector for mutually exclusive and interdependent features and their flag spans. #[derive(Default)] -struct MutexFeatureChecker { +struct FeatureChecker { proc_macro: Option, custom_attribute: Option, + copy_closures: Option, + clone_closures: Option, } -impl MutexFeatureChecker { +impl FeatureChecker { // If this method turns out to be a hotspot due to branching, // the branching can be eliminated by modifying `set!()` to set these spans // only for the features that need to be checked for mutual exclusion. @@ -1642,6 +1648,14 @@ impl MutexFeatureChecker { if features.custom_attribute { self.custom_attribute = self.custom_attribute.or(Some(span)); } + + if features.copy_closures { + self.copy_closures = self.copy_closures.or(Some(span)); + } + + if features.clone_closures { + self.clone_closures = self.clone_closures.or(Some(span)); + } } fn check(self, handler: &Handler) { @@ -1653,6 +1667,15 @@ impl MutexFeatureChecker { panic!(FatalError); } + + if let (Some(span), None) = (self.copy_closures, self.clone_closures) { + handler.struct_span_err(span, "`#![feature(copy_closures)]` can only be used with \ + `#![feature(clone_closures)]`") + .span_note(span, "`#![feature(copy_closures)]` declared here") + .emit(); + + panic!(FatalError); + } } } diff --git a/src/test/compile-fail/feature-gate-clone-closures.rs b/src/test/compile-fail/feature-gate-clone-closures.rs new file mode 100644 index 00000000000..a15153ea7bf --- /dev/null +++ b/src/test/compile-fail/feature-gate-clone-closures.rs @@ -0,0 +1,21 @@ +// Copyright 2017 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#[derive(Clone)] +struct S(i32); + +fn main() { + let a = S(5); + let hello = move || { + println!("Hello {}", a.0); + }; + + let hello = hello.clone(); //~ ERROR no method named `clone` found for type +} diff --git a/src/test/compile-fail/feature-gate-copy-closures.rs b/src/test/compile-fail/feature-gate-copy-closures.rs new file mode 100644 index 00000000000..b11b09eb9fd --- /dev/null +++ b/src/test/compile-fail/feature-gate-copy-closures.rs @@ -0,0 +1,19 @@ +// Copyright 2017 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +fn main() { + let a = 5; + let hello = || { + println!("Hello {}", a); + }; + + let b = hello; + let c = hello; //~ ERROR use of moved value: `hello` [E0382] +} diff --git a/src/test/compile-fail/not-clone-closure.rs b/src/test/compile-fail/not-clone-closure.rs new file mode 100644 index 00000000000..2a30dc4fdd4 --- /dev/null +++ b/src/test/compile-fail/not-clone-closure.rs @@ -0,0 +1,24 @@ +// Copyright 2017 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// Check that closures do not implement `Clone` if their environment is not `Clone`. + +#![feature(clone_closures)] + +struct S(i32); + +fn main() { + let a = S(5); + let hello = move || { + println!("Hello {}", a.0); + }; + + let hello = hello.clone(); //~ ERROR the trait bound `S: std::clone::Clone` is not satisfied +} diff --git a/src/test/compile-fail/not-copy-closure.rs b/src/test/compile-fail/not-copy-closure.rs new file mode 100644 index 00000000000..271e6d5fc90 --- /dev/null +++ b/src/test/compile-fail/not-copy-closure.rs @@ -0,0 +1,24 @@ +// Copyright 2017 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// Check that closures do not implement `Copy` if their environment is not `Copy`. + +#![feature(copy_closures)] +#![feature(clone_closures)] + +fn main() { + let mut a = 5; + let hello = || { + a += 1; + }; + + let b = hello; + let c = hello; //~ ERROR use of moved value: `hello` [E0382] +} diff --git a/src/test/run-pass/clone-closure.rs b/src/test/run-pass/clone-closure.rs new file mode 100644 index 00000000000..7f554c77fc4 --- /dev/null +++ b/src/test/run-pass/clone-closure.rs @@ -0,0 +1,29 @@ +// Copyright 2017 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// Check that closures implement `Clone`. + +#![feature(clone_closures)] + +#[derive(Clone)] +struct S(i32); + +fn main() { + let mut a = S(5); + let mut hello = move || { + a.0 += 1; + println!("Hello {}", a.0); + a.0 + }; + + let mut hello2 = hello.clone(); + assert_eq!(6, hello2()); + assert_eq!(6, hello()); +} diff --git a/src/test/run-pass/copy-closure.rs b/src/test/run-pass/copy-closure.rs new file mode 100644 index 00000000000..309c83ebd99 --- /dev/null +++ b/src/test/run-pass/copy-closure.rs @@ -0,0 +1,28 @@ +// Copyright 2017 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// Check that closures implement `Copy`. + +#![feature(copy_closures)] +#![feature(clone_closures)] + +fn call T>(f: F) -> T { f() } + +fn main() { + let a = 5; + let hello = || { + println!("Hello {}", a); + a + }; + + assert_eq!(5, call(hello.clone())); + assert_eq!(5, call(hello)); + assert_eq!(5, call(hello)); +}