From d63b8e003dd4c6bf7c99e1978816e0fd1c9202cf Mon Sep 17 00:00:00 2001 From: "Felix S. Klock II" Date: Tue, 27 Jan 2015 01:22:12 +0100 Subject: [PATCH 01/10] rebase of prototype Placer protocol atop master. --- src/liballoc/boxed.rs | 94 +++++++++++++-- src/liballoc/lib.rs | 7 ++ src/libcore/ops.rs | 43 +++++++ src/libcore/ptr.rs | 2 +- src/librustc/middle/expr_use_visitor.rs | 5 + src/libsyntax/ext/expand.rs | 149 ++++++++++++++++++++++++ 6 files changed, 291 insertions(+), 9 deletions(-) diff --git a/src/liballoc/boxed.rs b/src/liballoc/boxed.rs index c4abedf3fe89a..2c276c7875fb6 100644 --- a/src/liballoc/boxed.rs +++ b/src/liballoc/boxed.rs @@ -45,6 +45,8 @@ #![stable] +use heap; + use core::any::Any; use core::clone::Clone; use core::cmp::{PartialEq, PartialOrd, Eq, Ord, Ordering}; @@ -53,10 +55,11 @@ use core::error::{Error, FromError}; use core::fmt; use core::hash::{self, Hash}; use core::iter::Iterator; -use core::marker::Sized; +use core::marker::{Copy, Sized}; use core::mem; -use core::ops::{Deref, DerefMut}; +use core::ops::{Deref, DerefMut, Drop, Placer, PlacementAgent}; use core::option::Option; +use core::ptr::PtrExt; use core::ptr::Unique; use core::raw::TraitObject; use core::result::Result::{Ok, Err}; @@ -78,14 +81,90 @@ use core::result::Result; /// ``` #[lang = "exchange_heap"] #[unstable = "may be renamed; uncertain about custom allocator design"] -pub static HEAP: () = (); +pub const HEAP: ExchangeHeapSingleton = + ExchangeHeapSingleton { _force_singleton: () }; + +/// This the singleton type used solely for `boxed::HEAP`. +pub struct ExchangeHeapSingleton { _force_singleton: () } +impl Copy for ExchangeHeapSingleton { } /// A pointer type for heap allocation. /// /// See the [module-level documentation](../../std/boxed/index.html) for more. #[lang = "owned_box"] #[stable] -pub struct Box(Unique); +pub struct Box(Unique); + +/// `IntermediateBox` represents uninitialized backing storage for `Box`. +/// +/// FIXME (pnkfelix): Ideally we would just reuse `Box` instead of +/// introducing a separate `IntermediateBox`; but then you hit +/// issues when you e.g. attempt to destructure an instance of `Box`, +/// since it is a lang item and so it gets special handling by the +/// compiler. Easier just to make this parallel type for now. +/// +/// FIXME (pnkfelix): Currently the `box` protocol only supports +/// creating instances of sized types. This IntermediateBox is +/// designed to be forward-compatible with a future protocol that +/// supports creating instances of unsized types; that is why the type +/// parameter has the `?Sized` generalization marker, and is also why +/// this carries an explicit size. However, it probably does not need +/// to carry the explicit alignment; that is just a work-around for +/// the fact that the `align_of` intrinsic currently requires the +/// input type to be Sized (which I do not think is strictly +/// necessary). +#[experimental = "placement box design is still being worked out."] +pub struct IntermediateBox{ + ptr: *mut u8, + size: uint, + align: uint, +} + +impl PlacementAgent for IntermediateBox { + type Owner = Box; + + fn pointer(&mut self) -> *mut T { self.ptr as *mut T } + + unsafe fn finalize(self) -> Box { + let p = self.ptr as *mut T; + mem::forget(self); + mem::transmute(p) + } +} + +impl Placer for ExchangeHeapSingleton { + type Interim = IntermediateBox; + + fn make_place(self) -> IntermediateBox { + let size = mem::size_of::(); + let align = mem::align_of::(); + + let p = if size == 0 { + heap::EMPTY as *mut u8 + } else { + let p = unsafe { + heap::allocate(size, align) + }; + if p.is_null() { + panic!("Box make_place allocation failure."); + } + p + }; + + IntermediateBox { ptr: p, size: size, align: align } + } +} + +#[unsafe_destructor] +impl Drop for IntermediateBox { + fn drop(&mut self) { + if self.size > 0 { + unsafe { + heap::deallocate(self.ptr, self.size, self.align) + } + } + } +} impl Box { /// Allocates memory on the heap and then moves `x` into it. @@ -104,13 +183,13 @@ impl Box { #[stable] impl Default for Box { #[stable] - fn default() -> Box { box Default::default() } + fn default() -> Box { box (HEAP) Default::default() } } #[stable] impl Default for Box<[T]> { #[stable] - fn default() -> Box<[T]> { box [] } + fn default() -> Box<[T]> { box (HEAP) [] } } #[stable] @@ -124,8 +203,7 @@ impl Clone for Box { /// let y = x.clone(); /// ``` #[inline] - fn clone(&self) -> Box { box {(**self).clone()} } - + fn clone(&self) -> Box { box (HEAP) {(**self).clone()} } /// Copies `source`'s contents into `self` without creating a new allocation. /// /// # Examples diff --git a/src/liballoc/lib.rs b/src/liballoc/lib.rs index 231ef6e7e74da..577ab5d013d5e 100644 --- a/src/liballoc/lib.rs +++ b/src/liballoc/lib.rs @@ -91,9 +91,14 @@ pub mod heap; // Primitive types using the heaps above +// Need to conditionally define the mod from `boxed.rs` to avoid +// duplicating the lang-items when building in test cfg; but also need +// to allow code to have `use boxed::HEAP;` declaration. #[cfg(not(test))] pub mod boxed; #[cfg(test)] +mod boxed { pub use std::boxed::HEAP; } +#[cfg(test)] mod boxed_test; pub mod arc; pub mod rc; @@ -127,5 +132,7 @@ pub fn fixme_14344_be_sure_to_link_to_collections() {} #[doc(hidden)] mod std { pub use core::fmt; + pub use core::ops; pub use core::option; + pub use core::ptr; } diff --git a/src/libcore/ops.rs b/src/libcore/ops.rs index 372596cdd44ec..44638e21dd876 100644 --- a/src/libcore/ops.rs +++ b/src/libcore/ops.rs @@ -1148,3 +1148,46 @@ impl FnOnce for F self.call_mut(args) } } + +/// Interface to user-implementations of `box () `. +/// +/// `box (P) V` effectively expands into: +/// `{ let b = P.make_place(); +/// let raw_place = b.pointer(); +/// let v = V; +/// unsafe { ptr::write(raw_place, v); b.finalize() } +/// }` +/// +/// An instance of `Interim` is transient mutable value; an instance +/// of `Placer` may *also* be some transient mutable value, but the +/// placer could also be an immutable constant that implements `Copy`. +pub trait Placer { + type Interim: PlacementAgent; + /// Allocates a place for the data to live, returning an + /// intermediate agent to negotiate build-up or tear-down. + fn make_place(self) -> Self::Interim; +} + +/// Helper trait for expansion of `box (P) V`. +/// +/// A placement agent can be thought of as a special representation +/// for a hypothetical `&uninit` reference (which Rust cannot +/// currently express directly). That is, it represents a pointer to +/// uninitialized storage. +/// +/// The client is responsible for two steps: First, initializing the +/// payload (it can access its address via the `pointer()` +/// method). Second, converting the agent to an instance of the owning +/// pointer, via the `finalize()` method. +/// +/// See also `Placer`. +pub trait PlacementAgent { + type Owner; + + /// Returns a pointer to the offset in the place where the data lives. + fn pointer(&mut self) -> *mut Data; + + /// Converts this intermediate agent into owning pointer for the data, + /// forgetting self in the process. + unsafe fn finalize(self) -> Self::Owner; +} diff --git a/src/libcore/ptr.rs b/src/libcore/ptr.rs index 0b89467d63b83..01c60f06108f1 100644 --- a/src/libcore/ptr.rs +++ b/src/libcore/ptr.rs @@ -514,7 +514,7 @@ impl PartialOrd for *mut T { /// Useful for building abstractions like `Vec` or `Box`, which /// internally use raw pointers to manage the memory that they own. #[unstable = "recently added to this module"] -pub struct Unique(pub *mut T); +pub struct Unique(pub *mut T); /// `Unique` pointers are `Send` if `T` is `Send` because the data they /// reference is unaliased. Note that this aliasing invariant is diff --git a/src/librustc/middle/expr_use_visitor.rs b/src/librustc/middle/expr_use_visitor.rs index 70a7b4f13cc83..fb55e946dc4c2 100644 --- a/src/librustc/middle/expr_use_visitor.rs +++ b/src/librustc/middle/expr_use_visitor.rs @@ -621,6 +621,11 @@ impl<'d,'t,'tcx,TYPER:mc::Typer<'tcx>> ExprUseVisitor<'d,'t,'tcx,TYPER> { None => {} } self.consume_expr(&**base); + if place.is_some() { + self.tcx().sess.span_bug( + expr.span, + "box with explicit place remains after expansion"); + } } ast::ExprMac(..) => { diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index 629991799e73d..1aca34ac9ad10 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -58,6 +58,7 @@ pub fn expand_type(t: P, pub fn expand_expr(e: P, fld: &mut MacroExpander) -> P { e.and_then(|ast::Expr {id, node, span}| match node { + // expr_mac should really be expr_ext or something; it's the // entry-point for all syntax extensions. ast::ExprMac(mac) => { @@ -82,6 +83,154 @@ pub fn expand_expr(e: P, fld: &mut MacroExpander) -> P { }) } + // FIXME (pnkfelix): The code below is designed to handle + // *both* `box ` and `box () `, but for + // now the desugaring will only apply to the latter. + // + // The motivation is mostly to make it easier to land without + // having to update many tests that are not expecting to deal + // with the desugared form in terms of (1.) error messages and + // (2.) the dependencies on `::std::ops::placer`. + // + // To re-enable the more general code paths, just change the + // `Some(place)` in this binding to `maybe_place`, and revise + // the `let maybe_place = ...` to call `fld.fold_expr(place)` + // directly. + + // Desugar ExprBox: `box () ` + ast::ExprBox(Some(place), value_expr) => { + let value_span = value_expr.span; + let place_span = place.span; + + let maybe_place : Option> = Some(fld.fold_expr(place)); + let value_expr = fld.fold_expr(value_expr); + + // Desugar `box () ` to something + // analogous to: + // + // { + // let place /* : impl Placer */ = ; + // let agent = place.make_place(); + // let raw_place = agent.pointer(); + // let value = + // unsafe { + // ptr::write(raw_place, value); + // agent.finalize() + // } + // } + + let place_ident = token::gensym_ident("place"); + let agent_ident = token::gensym_ident("agent"); + let value_ident = token::gensym_ident("value"); + let p_ptr_ident = token::gensym_ident("p_ptr"); + + let place = fld.cx.expr_ident(span, place_ident); + let agent = fld.cx.expr_ident(span, agent_ident); + let value = fld.cx.expr_ident(span, value_ident); + let p_ptr = fld.cx.expr_ident(span, p_ptr_ident); + + fn mk_path_for_idents(span: Span, + idents: &[&'static str]) -> ast::Path { + let segments : Vec = + idents.iter().map(|s| { + ast::PathSegment { + identifier: token::str_to_ident(*s), + parameters: ast::PathParameters::none(), + } + }).collect(); + ast::Path { + span: span, global: true, segments: segments, + } + } + + // NOTE: clients using `box ` short-hand need to + // either use `libstd` or must make their own local + // + // ``` + // mod std { mod boxed { pub use ... as HEAP; } + // mod ops { mod placer { ... } } + // mod ptr { pub use ... as write; } } + // ``` + // + // as appropriate. + + let boxed_heap = |:| -> ast::Path { + let idents = ["std", "boxed", "HEAP"]; + mk_path_for_idents(place_span, &idents[]) + }; + + let placer_make_place = |:| -> ast::Path { + let idents = ["std", "ops", "Placer", "make_place"]; + mk_path_for_idents(place_span, &idents[]) + }; + + let placer_pointer = |:| -> ast::Path { + let idents = ["std", "ops", "PlacementAgent", "pointer"]; + mk_path_for_idents(place_span, &idents[]) + }; + + let placer_finalize = |:| -> ast::Path { + let idents = ["std", "ops", "PlacementAgent", "finalize"]; + mk_path_for_idents(place_span, &idents[]) + }; + + let ptr_write = |:| -> ast::Path { + let idents = ["std", "ptr", "write"]; + mk_path_for_idents(place_span, &idents[]) + }; + + let make_call = |&: f: ast::Path, args: Vec>| -> P { + fld.cx.expr_call(span, fld.cx.expr_path(f), args) + }; + + let stmt_let = |&: span, bind, expr| fld.cx.stmt_let(span, false, bind, expr); + let stmt_let_mut = |: span, bind, expr| fld.cx.stmt_let(span, true, bind, expr); + + fld.cx.expr_block(fld.cx.block_all( + span, + vec![ + // let place = ; // default of ::std::boxed::HEAP + stmt_let(place_span, + place_ident, + match maybe_place { + Some(place_expr) => place_expr, + None => fld.cx.expr_path(boxed_heap()), + }), + + // let mut agent = Placer::make_place(place); + stmt_let_mut(place_span, agent_ident, + make_call(placer_make_place(), vec![place])), + + // let p_ptr = PlacementAgent::pointer(&mut agent); + stmt_let(place_span, + p_ptr_ident, + make_call(placer_pointer(), + vec![fld.cx.expr_mut_addr_of(place_span, + agent.clone())])), + + // let value = ; + stmt_let(value_span, value_ident, value_expr) + + ], + + // unsafe { ptr::write(p_ptr, value); PlacementAgent::finalize(agent) } + { + let call_ptr_write = + StmtSemi(make_call(ptr_write(), vec![p_ptr, value]), + ast::DUMMY_NODE_ID); + let call_ptr_write = + codemap::respan(value_span, call_ptr_write); + + Some(fld.cx.expr_block(P(ast::Block { + stmts: vec![P(call_ptr_write)], + expr: Some(make_call(placer_finalize(), vec![agent])), + id: ast::DUMMY_NODE_ID, + rules: ast::UnsafeBlock(ast::CompilerGenerated), + span: span, + }))) + })) + } + ast::ExprWhile(cond, body, opt_ident) => { let cond = fld.fold_expr(cond); let (body, opt_ident) = expand_loop_block(body, opt_ident, fld); From b8c332a3b004fdafab3c197863b875b9d222084f Mon Sep 17 00:00:00 2001 From: "Felix S. Klock II" Date: Tue, 27 Jan 2015 11:33:38 +0100 Subject: [PATCH 02/10] parser: switch from `box () ` form to `in () `. Note that `box ` itself remains unchanged. --- src/libsyntax/parse/parser.rs | 71 +++++++++++++++++++---------------- 1 file changed, 39 insertions(+), 32 deletions(-) diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index eab24574bb195..2b0eddd194f85 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -2774,46 +2774,53 @@ impl<'a> Parser<'a> { ex = ExprAddrOf(m, e); } token::Ident(_, _) => { - if !self.token.is_keyword(keywords::Box) { + if !self.token.is_keyword(keywords::Box) && + !self.token.is_keyword(keywords::In) { return self.parse_dot_or_call_expr(); } let lo = self.span.lo; + let is_in = self.token.is_keyword(keywords::In); self.bump(); - // Check for a place: `box(PLACE) EXPR`. - if self.eat(&token::OpenDelim(token::Paren)) { - // Support `box() EXPR` as the default. - if !self.eat(&token::CloseDelim(token::Paren)) { - let place = self.parse_expr(); - self.expect(&token::CloseDelim(token::Paren)); - // Give a suggestion to use `box()` when a parenthesised expression is used - if !self.token.can_begin_expr() { - let span = self.span; - let this_token_to_string = self.this_token_to_string(); - self.span_err(span, - &format!("expected expression, found `{}`", - this_token_to_string)[]); - let box_span = mk_sp(lo, self.last_span.hi); - self.span_help(box_span, - "perhaps you meant `box() (foo)` instead?"); - self.abort_if_errors(); - } - let subexpression = self.parse_prefix_expr(); - hi = subexpression.span.hi; - ex = ExprBox(Some(place), subexpression); - return self.mk_expr(lo, hi, ex); - } + if (!is_in && self.eat(&token::OpenDelim(token::Paren))) || + (is_in && { self.expect(&token::OpenDelim(token::Paren)); true }) { + let place = self.parse_expr(); + self.expect(&token::CloseDelim(token::Paren)); + // Give a suggestion to use `box` when a parenthesised expression is used + if !self.token.can_begin_expr() { + let span = self.span; + let this_token_to_string = self.this_token_to_string(); + self.span_err(span, + &format!("expected expression, found `{}`", + this_token_to_string)[]); + let box_span = mk_sp(lo, self.last_span.hi); + self.span_help(box_span, + "perhaps you meant `box (foo)` instead?"); + self.abort_if_errors(); + } + if !is_in { + let box_span = mk_sp(lo, self.last_span.hi); + self.span_warn( + box_span, + "deprecated syntax; use the `in` keyword now \ + (e.g. change `box () ` to \ + `in () `)"); + } + let subexpression = self.parse_prefix_expr(); + hi = subexpression.span.hi; + ex = ExprBox(Some(place), subexpression); + return self.mk_expr(lo, hi, ex); + } else { + // Otherwise, we use the unique pointer default. + let subexpression = self.parse_prefix_expr(); + hi = subexpression.span.hi; + // FIXME (pnkfelix): After working out kinks with box + // desugaring, should be `ExprBox(None, subexpression)` + // instead. + ex = self.mk_unary(UnUniq, subexpression); } - - // Otherwise, we use the unique pointer default. - let subexpression = self.parse_prefix_expr(); - hi = subexpression.span.hi; - // FIXME (pnkfelix): After working out kinks with box - // desugaring, should be `ExprBox(None, subexpression)` - // instead. - ex = self.mk_unary(UnUniq, subexpression); } _ => return self.parse_dot_or_call_expr() } From 8954197fe72c6eca1b6e5dec48b3c16d6194485a Mon Sep 17 00:00:00 2001 From: "Felix S. Klock II" Date: Wed, 4 Feb 2015 18:51:22 +0100 Subject: [PATCH 03/10] IN PROGRESS prototype code for unstable overloaded-box and placement-in. --- src/liballoc/boxed.rs | 66 ++++++---- src/libcore/ops.rs | 134 +++++++++++++++----- src/libsyntax/ext/expand.rs | 225 ++++++++++++++++++++++------------ src/libsyntax/parse/parser.rs | 21 ++-- 4 files changed, 295 insertions(+), 151 deletions(-) diff --git a/src/liballoc/boxed.rs b/src/liballoc/boxed.rs index 2c276c7875fb6..1e226c0321cbd 100644 --- a/src/liballoc/boxed.rs +++ b/src/liballoc/boxed.rs @@ -57,7 +57,8 @@ use core::hash::{self, Hash}; use core::iter::Iterator; use core::marker::{Copy, Sized}; use core::mem; -use core::ops::{Deref, DerefMut, Drop, Placer, PlacementAgent}; +use core::ops::{Deref, DerefMut, Drop}; +use core::ops::{Placer, Boxed, Place, InPlace}; use core::option::Option; use core::ptr::PtrExt; use core::ptr::Unique; @@ -120,38 +121,51 @@ pub struct IntermediateBox{ align: uint, } -impl PlacementAgent for IntermediateBox { - type Owner = Box; - +impl Place for IntermediateBox { fn pointer(&mut self) -> *mut T { self.ptr as *mut T } +} - unsafe fn finalize(self) -> Box { - let p = self.ptr as *mut T; - mem::forget(self); - mem::transmute(p) - } +unsafe fn finalize(b: IntermediateBox) -> Box { + let p = b.ptr as *mut T; + mem::forget(b); + mem::transmute(p) } -impl Placer for ExchangeHeapSingleton { - type Interim = IntermediateBox; - - fn make_place(self) -> IntermediateBox { - let size = mem::size_of::(); - let align = mem::align_of::(); +fn make_place() -> IntermediateBox { + let size = mem::size_of::(); + let align = mem::align_of::(); - let p = if size == 0 { - heap::EMPTY as *mut u8 - } else { - let p = unsafe { - heap::allocate(size, align) - }; - if p.is_null() { - panic!("Box make_place allocation failure."); - } - p + let p = if size == 0 { + heap::EMPTY as *mut u8 + } else { + let p = unsafe { + heap::allocate(size, align) }; + if p.is_null() { + panic!("Box make_place allocation failure."); + } + p + }; - IntermediateBox { ptr: p, size: size, align: align } + IntermediateBox { ptr: p, size: size, align: align } +} + +impl InPlace for IntermediateBox { + type Owner = Box; + unsafe fn finalize(self) -> Box { finalize(self) } +} + +impl Boxed for Box { + type Data = T; + type Place = IntermediateBox; + unsafe fn finalize(b: IntermediateBox) -> Box { finalize(b) } +} + +impl Placer for ExchangeHeapSingleton { + type Place = IntermediateBox; + + fn make_place(self) -> IntermediateBox { + make_place() } } diff --git a/src/libcore/ops.rs b/src/libcore/ops.rs index 44638e21dd876..0bb02a2afebe7 100644 --- a/src/libcore/ops.rs +++ b/src/libcore/ops.rs @@ -1149,45 +1149,113 @@ impl FnOnce for F } } -/// Interface to user-implementations of `box () `. -/// -/// `box (P) V` effectively expands into: -/// `{ let b = P.make_place(); -/// let raw_place = b.pointer(); -/// let v = V; -/// unsafe { ptr::write(raw_place, v); b.finalize() } -/// }` -/// -/// An instance of `Interim` is transient mutable value; an instance -/// of `Placer` may *also* be some transient mutable value, but the -/// placer could also be an immutable constant that implements `Copy`. -pub trait Placer { - type Interim: PlacementAgent; - /// Allocates a place for the data to live, returning an - /// intermediate agent to negotiate build-up or tear-down. - fn make_place(self) -> Self::Interim; +/// Both `in (PLACE) EXPR` and `box EXPR` desugar into expressions +/// that allocate an intermediate "place" that holds uninitialized +/// state. The desugaring evaluates EXPR, and writes the result at +/// the address returned by the `pointer` method of this trait. +/// +/// A `Place` can be thought of as a special representation for a +/// hypothetical `&uninit` reference (which Rust cannot currently +/// express directly). That is, it represents a pointer to +/// uninitialized storage. +/// +/// The client is responsible for two steps: First, initializing the +/// payload (it can access its address via `pointer`). Second, +/// converting the agent to an instance of the owning pointer, via the +/// appropriate `finalize` method (see the `InPlace`. +/// +/// If evaluating EXPR fails, then the destructor for the +/// implementation of Place to clean up any intermediate state +/// (e.g. deallocate box storage, pop a stack, etc). +pub trait Place { + /// Returns the address where the input value will be written. + /// Note that the data at this address is generally uninitialized, + /// and thus one should use `ptr::write` for initializing it. + fn pointer(&mut self) -> *mut Data; } -/// Helper trait for expansion of `box (P) V`. +/// Interface to implementations of `in (PLACE) EXPR`. /// -/// A placement agent can be thought of as a special representation -/// for a hypothetical `&uninit` reference (which Rust cannot -/// currently express directly). That is, it represents a pointer to -/// uninitialized storage. +/// `in (PLACE) EXPR` effectively desugars into: /// -/// The client is responsible for two steps: First, initializing the -/// payload (it can access its address via the `pointer()` -/// method). Second, converting the agent to an instance of the owning -/// pointer, via the `finalize()` method. +/// ``` +/// let p = PLACE; +/// let mut place = Placer::make_place(p); +/// let raw_place = Place::pointer(&mut place); +/// let value = EXPR; +/// unsafe { +/// std::ptr::write(raw_place, value); +/// InPlace::finalize(place) +/// } +/// ``` /// -/// See also `Placer`. -pub trait PlacementAgent { - type Owner; +/// The type of `in (PLACE) EXPR` is derived from the type of `PLACE`; +/// if the type of `PLACE` is `P`, then the final type of the whole +/// expression is `P::Place::Owner` (see the `InPlace` and `Boxed` +/// traits). +/// +/// Values for types implementing this trait usually are transient +/// intermediate values (e.g. the return value of `Vec::emplace_back`) +/// or `Copy`, since the `make_place` method takes `self` by value. +pub trait Placer { + /// `Place` is the intermedate agent guarding the + /// uninitialized state for `Data`. + type Place: InPlace; - /// Returns a pointer to the offset in the place where the data lives. - fn pointer(&mut self) -> *mut Data; + /// Creates a fresh place from `self`. + fn make_place(self) -> Self::Place; +} + +/// Specialization of `Place` trait supporting `in (PLACE) EXPR`. +pub trait InPlace: Place { + /// `Owner` is the type of the end value of `in (PLACE) EXPR` + /// + /// Note that when `in (PLACE) EXPR` is solely used for + /// side-effecting an existing data-structure, + /// e.g. `Vec::emplace_back`, then `Owner` need not carry any + /// information at all (e.g. it can be the unit type `()` in that + /// case). + type Owner; - /// Converts this intermediate agent into owning pointer for the data, - /// forgetting self in the process. + /// Converts self into the final value, shifting + /// deallocation/cleanup responsibilities (if any remain), over to + /// the returned instance of `Owner` and forgetting self. unsafe fn finalize(self) -> Self::Owner; } + +/// Core trait for the `box EXPR` form. +/// +/// `box EXPR` effectively desugars into: +/// +/// ``` +/// let mut place = BoxPlace::make_place(); +/// let raw_place = Place::pointer(&mut place); +/// let value = $value; +/// unsafe { +/// ::std::ptr::write(raw_place, value); +/// Boxed::finalize(place) +/// } +/// ``` +/// +/// The type of `box EXPR` is supplied from its surrounding +/// context; in the above expansion, the result type `T` is used +/// to determine which implementation of `Boxed` to use, and that +/// `` in turn dictates determines which +/// implementation of `BoxPlace` to use, namely: +/// `<::Place as BoxPlace>`. +pub trait Boxed { + /// The kind of data that is stored in this kind of box. + type Data; /* (`Data` unused b/c cannot yet express below bound.) */ + type Place; /* should be bounded by BoxPlace */ + + /// Converts filled place into final owning value, shifting + /// deallocation/cleanup responsibilities (if any remain), over to + /// returned instance of `Self` and forgetting `filled`. + unsafe fn finalize(filled: Self::Place) -> Self; +} + +/// Specialization of `Place` trait supporting `box EXPR`. +pub trait BoxPlace : Place { + /// Creates a globally fresh place. + fn make_place() -> Self; +} diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index 1aca34ac9ad10..9ad70927e24b4 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -57,6 +57,7 @@ pub fn expand_type(t: P, } pub fn expand_expr(e: P, fld: &mut MacroExpander) -> P { + let expr_span = e.span; e.and_then(|ast::Expr {id, node, span}| match node { // expr_mac should really be expr_ext or something; it's the @@ -83,48 +84,31 @@ pub fn expand_expr(e: P, fld: &mut MacroExpander) -> P { }) } - // FIXME (pnkfelix): The code below is designed to handle - // *both* `box ` and `box () `, but for - // now the desugaring will only apply to the latter. - // - // The motivation is mostly to make it easier to land without - // having to update many tests that are not expecting to deal - // with the desugared form in terms of (1.) error messages and - // (2.) the dependencies on `::std::ops::placer`. - // - // To re-enable the more general code paths, just change the - // `Some(place)` in this binding to `maybe_place`, and revise - // the `let maybe_place = ...` to call `fld.fold_expr(place)` - // directly. - - // Desugar ExprBox: `box () ` - ast::ExprBox(Some(place), value_expr) => { + // Desugar ExprBox: `in (PLACE) EXPR` + ast::ExprBox(Some(placer), value_expr) => { + // to: + // + // let p = PLACE; + // let mut place = Placer::make_place(p); + // let raw_place = InPlace::pointer(&mut place); + // let value = EXPR; + // unsafe { + // std::ptr::write(raw_place, value); + // InPlace::finalize(place) + // } + let value_span = value_expr.span; - let place_span = place.span; + let placer_span = placer.span; - let maybe_place : Option> = Some(fld.fold_expr(place)); + let placer_expr = fld.fold_expr(placer); let value_expr = fld.fold_expr(value_expr); - // Desugar `box () ` to something - // analogous to: - // - // { - // let place /* : impl Placer */ = ; - // let agent = place.make_place(); - // let raw_place = agent.pointer(); - // let value = - // unsafe { - // ptr::write(raw_place, value); - // agent.finalize() - // } - // } - - let place_ident = token::gensym_ident("place"); - let agent_ident = token::gensym_ident("agent"); + let placer_ident = token::gensym_ident("placer"); + let agent_ident = token::gensym_ident("place"); let value_ident = token::gensym_ident("value"); let p_ptr_ident = token::gensym_ident("p_ptr"); - let place = fld.cx.expr_ident(span, place_ident); + let placer = fld.cx.expr_ident(span, placer_ident); let agent = fld.cx.expr_ident(span, agent_ident); let value = fld.cx.expr_ident(span, value_ident); let p_ptr = fld.cx.expr_ident(span, p_ptr_ident); @@ -143,77 +127,156 @@ pub fn expand_expr(e: P, fld: &mut MacroExpander) -> P { } } - // NOTE: clients using `box ` short-hand need to - // either use `libstd` or must make their own local - // - // ``` - // mod std { mod boxed { pub use ... as HEAP; } - // mod ops { mod placer { ... } } - // mod ptr { pub use ... as write; } } - // ``` - // - // as appropriate. - - let boxed_heap = |:| -> ast::Path { - let idents = ["std", "boxed", "HEAP"]; - mk_path_for_idents(place_span, &idents[]) - }; - let placer_make_place = |:| -> ast::Path { let idents = ["std", "ops", "Placer", "make_place"]; - mk_path_for_idents(place_span, &idents[]) + mk_path_for_idents(placer_span, &idents[]) }; - let placer_pointer = |:| -> ast::Path { - let idents = ["std", "ops", "PlacementAgent", "pointer"]; - mk_path_for_idents(place_span, &idents[]) + let place_pointer = |:| -> ast::Path { + let idents = ["std", "ops", "Place", "pointer"]; + mk_path_for_idents(placer_span, &idents[]) }; - let placer_finalize = |:| -> ast::Path { - let idents = ["std", "ops", "PlacementAgent", "finalize"]; - mk_path_for_idents(place_span, &idents[]) + let place_finalize = |:| -> ast::Path { + let idents = ["std", "ops", "InPlace", "finalize"]; + mk_path_for_idents(placer_span, &idents[]) }; let ptr_write = |:| -> ast::Path { let idents = ["std", "ptr", "write"]; - mk_path_for_idents(place_span, &idents[]) + mk_path_for_idents(placer_span, &idents[]) }; let make_call = |&: f: ast::Path, args: Vec>| -> P { fld.cx.expr_call(span, fld.cx.expr_path(f), args) }; - let stmt_let = |&: span, bind, expr| fld.cx.stmt_let(span, false, bind, expr); - let stmt_let_mut = |: span, bind, expr| fld.cx.stmt_let(span, true, bind, expr); + let stmt_let = |&: bind, expr| fld.cx.stmt_let(placer_span, false, bind, expr); + let stmt_let_mut = |: bind, expr| fld.cx.stmt_let(placer_span, true, bind, expr); fld.cx.expr_block(fld.cx.block_all( span, vec![ - // let place = ; // default of ::std::boxed::HEAP - stmt_let(place_span, - place_ident, - match maybe_place { - Some(place_expr) => place_expr, - None => fld.cx.expr_path(boxed_heap()), - }), - - // let mut agent = Placer::make_place(place); - stmt_let_mut(place_span, agent_ident, - make_call(placer_make_place(), vec![place])), - - // let p_ptr = PlacementAgent::pointer(&mut agent); - stmt_let(place_span, - p_ptr_ident, - make_call(placer_pointer(), - vec![fld.cx.expr_mut_addr_of(place_span, + // let placer = ; + stmt_let(placer_ident, placer_expr), + + // let mut place = Placer::make_place(placer); + stmt_let_mut(agent_ident, + make_call(placer_make_place(), vec![placer])), + + // let p_ptr = Place::pointer(&mut place); + stmt_let(p_ptr_ident, + make_call(place_pointer(), + vec![fld.cx.expr_mut_addr_of(placer_span, agent.clone())])), // let value = ; - stmt_let(value_span, value_ident, value_expr) + fld.cx.stmt_let(value_span, false, value_ident, value_expr) + + ], + + // unsafe { ptr::write(p_ptr, value); InPlace::finalize(place) } + { + let call_ptr_write = + StmtSemi(make_call(ptr_write(), vec![p_ptr, value]), + ast::DUMMY_NODE_ID); + let call_ptr_write = + codemap::respan(value_span, call_ptr_write); + + Some(fld.cx.expr_block(P(ast::Block { + stmts: vec![P(call_ptr_write)], + expr: Some(make_call(place_finalize(), vec![agent])), + id: ast::DUMMY_NODE_ID, + rules: ast::UnsafeBlock(ast::CompilerGenerated), + span: span, + }))) + })) + } + + // Desugar ExprBox: `box EXPR` + ast::ExprBox(None, value_expr) => { + // to: + // + // let mut place = BoxPlace::make_place(); + // let raw_place = Place::pointer(&mut place); + // let value = $value; + // unsafe { + // ::std::ptr::write(raw_place, value); + // Boxed::finalize(place) + // } + + let value_span = value_expr.span; + + let value_expr = fld.fold_expr(value_expr); + + let agent_ident = token::gensym_ident("place"); + let value_ident = token::gensym_ident("value"); + let p_ptr_ident = token::gensym_ident("p_ptr"); + + let agent = fld.cx.expr_ident(span, agent_ident); + let value = fld.cx.expr_ident(span, value_ident); + let p_ptr = fld.cx.expr_ident(span, p_ptr_ident); + + fn mk_path_for_idents(span: Span, + idents: &[&'static str]) -> ast::Path { + let segments : Vec = + idents.iter().map(|s| { + ast::PathSegment { + identifier: token::str_to_ident(*s), + parameters: ast::PathParameters::none(), + } + }).collect(); + ast::Path { + span: span, global: true, segments: segments, + } + } + + let make_place = |:| -> ast::Path { + let idents = ["std", "ops", "BoxPlace", "make_place"]; + mk_path_for_idents(expr_span, &idents[]) + }; + + let place_pointer = |:| -> ast::Path { + let idents = ["std", "ops", "Place", "pointer"]; + mk_path_for_idents(expr_span, &idents[]) + }; + + let boxed_finalize = |:| -> ast::Path { + let idents = ["std", "ops", "Boxed", "finalize"]; + mk_path_for_idents(expr_span, &idents[]) + }; + + let ptr_write = |:| -> ast::Path { + let idents = ["std", "ptr", "write"]; + mk_path_for_idents(expr_span, &idents[]) + }; + + let make_call = |&: f: ast::Path, args: Vec>| -> P { + fld.cx.expr_call(span, fld.cx.expr_path(f), args) + }; + + let stmt_let = |&: bind, expr| fld.cx.stmt_let(expr_span, false, bind, expr); + let stmt_let_mut = |: bind, expr| fld.cx.stmt_let(expr_span, true, bind, expr); + + fld.cx.expr_block(fld.cx.block_all( + span, + vec![ + // let mut place = BoxPlace::make_place(); + stmt_let_mut(agent_ident, make_call(make_place(), vec![])), + + // let p_ptr = Place::pointer(&mut place); + stmt_let( + p_ptr_ident, make_call( + place_pointer(), + vec![fld.cx.expr_mut_addr_of(expr_span, + agent.clone())])), + + // let value = ; + fld.cx.stmt_let(value_span, false, value_ident, value_expr) ], - // unsafe { ptr::write(p_ptr, value); PlacementAgent::finalize(agent) } + // unsafe { ptr::write(p_ptr, value); Boxed::finalize(place) } { let call_ptr_write = StmtSemi(make_call(ptr_write(), vec![p_ptr, value]), @@ -223,7 +286,7 @@ pub fn expand_expr(e: P, fld: &mut MacroExpander) -> P { Some(fld.cx.expr_block(P(ast::Block { stmts: vec![P(call_ptr_write)], - expr: Some(make_call(placer_finalize(), vec![agent])), + expr: Some(make_call(boxed_finalize(), vec![agent])), id: ast::DUMMY_NODE_ID, rules: ast::UnsafeBlock(ast::CompilerGenerated), span: span, diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 2b0eddd194f85..87b59e157a837 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -56,7 +56,7 @@ use ast::{TupleVariantKind, Ty, Ty_, TypeBinding}; use ast::{TyFixedLengthVec, TyBareFn}; use ast::{TyTypeof, TyInfer, TypeMethod}; use ast::{TyParam, TyParamBound, TyParen, TyPath, TyPolyTraitRef, TyPtr, TyQPath}; -use ast::{TyRptr, TyTup, TyU32, TyVec, UnUniq}; +use ast::{TyRptr, TyTup, TyU32, TyVec}; use ast::{TypeImplItem, TypeTraitItem, Typedef, ClosureKind}; use ast::{UnnamedField, UnsafeBlock}; use ast::{ViewPath, ViewPathGlob, ViewPathList, ViewPathSimple}; @@ -2801,12 +2801,14 @@ impl<'a> Parser<'a> { self.abort_if_errors(); } if !is_in { - let box_span = mk_sp(lo, self.last_span.hi); - self.span_warn( - box_span, - "deprecated syntax; use the `in` keyword now \ - (e.g. change `box () ` to \ - `in () `)"); + // SNAP 9006c3c + // Enable this warning after snapshot + // let box_span = mk_sp(lo, self.last_span.hi); + // self.span_warn( + // box_span, + // "deprecated syntax; use the `in` keyword now \ + // (e.g. change `box () ` to \ + // `in () `)"); } let subexpression = self.parse_prefix_expr(); hi = subexpression.span.hi; @@ -2816,10 +2818,7 @@ impl<'a> Parser<'a> { // Otherwise, we use the unique pointer default. let subexpression = self.parse_prefix_expr(); hi = subexpression.span.hi; - // FIXME (pnkfelix): After working out kinks with box - // desugaring, should be `ExprBox(None, subexpression)` - // instead. - ex = self.mk_unary(UnUniq, subexpression); + ex = ExprBox(None, subexpression); } } _ => return self.parse_dot_or_call_expr() From 8774c4581b7494e97a43fde7a865e54289fa6628 Mon Sep 17 00:00:00 2001 From: "Felix S. Klock II" Date: Fri, 6 Feb 2015 15:11:09 +0100 Subject: [PATCH 04/10] Add `BoxPlace` impl for the intermediate box value. --- src/liballoc/boxed.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/liballoc/boxed.rs b/src/liballoc/boxed.rs index 1e226c0321cbd..2ac509e668d6a 100644 --- a/src/liballoc/boxed.rs +++ b/src/liballoc/boxed.rs @@ -58,7 +58,7 @@ use core::iter::Iterator; use core::marker::{Copy, Sized}; use core::mem; use core::ops::{Deref, DerefMut, Drop}; -use core::ops::{Placer, Boxed, Place, InPlace}; +use core::ops::{Placer, Boxed, Place, InPlace, BoxPlace}; use core::option::Option; use core::ptr::PtrExt; use core::ptr::Unique; @@ -150,6 +150,10 @@ fn make_place() -> IntermediateBox { IntermediateBox { ptr: p, size: size, align: align } } +impl BoxPlace for IntermediateBox { + fn make_place() -> IntermediateBox { make_place() } +} + impl InPlace for IntermediateBox { type Owner = Box; unsafe fn finalize(self) -> Box { finalize(self) } From a0e98b423d8852d99d21306528c9c0b21a5c6f69 Mon Sep 17 00:00:00 2001 From: "Felix S. Klock II" Date: Fri, 6 Feb 2015 15:23:48 +0100 Subject: [PATCH 05/10] Fallout from changes to box protocol in libstd and related crates. --- src/liballoc/arc.rs | 3 ++- src/liballoc/rc.rs | 6 +++++- src/libcollections/lib.rs | 2 ++ src/liblog/lib.rs | 7 ++++--- src/libstd/io/net/ip.rs | 4 ++-- src/libstd/io/stdio.rs | 8 +++++--- src/libstd/io/timer.rs | 5 +++-- src/libstd/lib.rs | 1 + src/libstd/rt/unwind.rs | 8 +++++--- src/libstd/sync/mpsc/mpsc_queue.rs | 11 +++++++---- src/libstd/sync/mpsc/spsc_queue.rs | 11 +++++++---- src/libstd/sys/common/helper_thread.rs | 5 ++++- src/libstd/sys/unix/thread.rs | 6 ++++-- src/libstd/thunk.rs | 3 ++- 14 files changed, 53 insertions(+), 27 deletions(-) diff --git a/src/liballoc/arc.rs b/src/liballoc/arc.rs index 5f8cd6baf9a74..464870999d944 100644 --- a/src/liballoc/arc.rs +++ b/src/liballoc/arc.rs @@ -81,6 +81,7 @@ use core::nonzero::NonZero; use core::ops::Deref; use core::ptr; use core::hash::{Hash, Hasher}; +use boxed::Box; use heap::deallocate; /// An atomically reference counted wrapper for shared state. @@ -160,7 +161,7 @@ impl Arc { pub fn new(data: T) -> Arc { // Start the weak pointer count as 1 which is the weak pointer that's // held by all the strong pointers (kinda), see std/rc.rs for more info - let x = box ArcInner { + let x : Box<_> = box ArcInner { strong: atomic::AtomicUsize::new(1), weak: atomic::AtomicUsize::new(1), data: data, diff --git a/src/liballoc/rc.rs b/src/liballoc/rc.rs index 5e82c4f1adea9..76034c1e64961 100644 --- a/src/liballoc/rc.rs +++ b/src/liballoc/rc.rs @@ -161,6 +161,7 @@ use core::ptr::{self, PtrExt}; use core::result::Result; use core::result::Result::{Ok, Err}; +use boxed::HEAP; use heap::deallocate; struct RcBox { @@ -202,7 +203,10 @@ impl Rc { // there is an implicit weak pointer owned by all the strong pointers, which // ensures that the weak destructor never frees the allocation while the strong // destructor is running, even if the weak pointer is stored inside the strong one. - _ptr: NonZero::new(transmute(box RcBox { + // + // SNAP 9006c3c + // Change `box (HEAP)` to `in (HEAP)` after snapshot. + _ptr: NonZero::new(transmute(box (HEAP) RcBox { value: value, strong: Cell::new(1), weak: Cell::new(1) diff --git a/src/libcollections/lib.rs b/src/libcollections/lib.rs index 6a182add00064..5d626028a3c50 100644 --- a/src/libcollections/lib.rs +++ b/src/libcollections/lib.rs @@ -106,6 +106,8 @@ mod std { pub use core::cmp; // derive(Eq, Ord, etc.) pub use core::marker; // derive(Copy) pub use core::hash; // derive(Hash) + pub use core::ops; // necessary for box + pub use core::ptr; // necessary for box } #[cfg(test)] diff --git a/src/liblog/lib.rs b/src/liblog/lib.rs index e7c5bc35f761a..b7ae5cf2b9dd5 100644 --- a/src/liblog/lib.rs +++ b/src/liblog/lib.rs @@ -172,6 +172,7 @@ #![allow(unstable)] #![deny(missing_docs)] +use std::boxed::HEAP; use std::cell::RefCell; use std::fmt; use std::io::LineBufferedWriter; @@ -294,7 +295,7 @@ pub fn log(level: u32, loc: &'static LogLocation, args: fmt::Arguments) { let mut logger = LOCAL_LOGGER.with(|s| { s.borrow_mut().take() }).unwrap_or_else(|| { - box DefaultLogger { handle: io::stderr() } as Box + box (HEAP) DefaultLogger { handle: io::stderr() } as Box }); logger.log(&LogRecord { level: LogLevel(level), @@ -416,12 +417,12 @@ fn init() { assert!(FILTER.is_null()); match filter { - Some(f) => FILTER = mem::transmute(box f), + Some(f) => FILTER = mem::transmute(box (HEAP) f), None => {} } assert!(DIRECTIVES.is_null()); - DIRECTIVES = mem::transmute(box directives); + DIRECTIVES = mem::transmute(box (HEAP) directives); // Schedule the cleanup for the globals for when the runtime exits. rt::at_exit(move |:| { diff --git a/src/libstd/io/net/ip.rs b/src/libstd/io/net/ip.rs index e4622781ae7ea..f4c6dd71c06fe 100644 --- a/src/libstd/io/net/ip.rs +++ b/src/libstd/io/net/ip.rs @@ -325,7 +325,7 @@ impl<'a> Parser<'a> { fn read_ip_addr(&mut self) -> Option { let ipv4_addr = |&mut: p: &mut Parser| p.read_ipv4_addr(); let ipv6_addr = |&mut: p: &mut Parser| p.read_ipv6_addr(); - self.read_or(&mut [box ipv4_addr, box ipv6_addr]) + self.read_or(&mut [Box::new(ipv4_addr), Box::new(ipv6_addr)]) } fn read_socket_addr(&mut self) -> Option { @@ -338,7 +338,7 @@ impl<'a> Parser<'a> { p.read_seq_3::(open_br, ip_addr, clos_br) .map(|t| match t { (_, ip, _) => ip }) }; - p.read_or(&mut [box ipv4_p, box ipv6_p]) + p.read_or(&mut [Box::new(ipv4_p), Box::new(ipv6_p)]) }; let colon = |&: p: &mut Parser| p.read_given_char(':'); let port = |&: p: &mut Parser| p.read_number(10, 5, 0x10000).map(|n| n as u16); diff --git a/src/libstd/io/stdio.rs b/src/libstd/io/stdio.rs index a5664b9f01377..d9d99781c4342 100644 --- a/src/libstd/io/stdio.rs +++ b/src/libstd/io/stdio.rs @@ -27,7 +27,7 @@ use self::StdSource::*; -use boxed::Box; +use boxed::{Box, HEAP}; use cell::RefCell; use clone::Clone; use failure::LOCAL_STDERR; @@ -234,7 +234,7 @@ pub fn stdin() -> StdinReader { let stdin = StdinReader { inner: Arc::new(Mutex::new(RaceBox(stdin))) }; - STDIN = mem::transmute(box stdin); + STDIN = mem::transmute(box (HEAP) stdin); // Make sure to free it at exit rt::at_exit(|| { @@ -341,7 +341,9 @@ fn with_task_stdout(f: F) where F: FnOnce(&mut Writer) -> IoResult<()> { let mut my_stdout = LOCAL_STDOUT.with(|slot| { slot.borrow_mut().take() }).unwrap_or_else(|| { - box stdout() as Box + // SNAP 9006c3c + // Change `Box::new(..)` to `in (HEAP) ..` after snapshot. + box (HEAP) stdout() as Box }); let result = f(&mut *my_stdout); let mut var = Some(my_stdout); diff --git a/src/libstd/io/timer.rs b/src/libstd/io/timer.rs index 68ae7d0ff2083..76fa575e8c780 100644 --- a/src/libstd/io/timer.rs +++ b/src/libstd/io/timer.rs @@ -15,6 +15,7 @@ // FIXME: These functions take Durations but only pass ms to the backend impls. +use boxed::{HEAP}; use sync::mpsc::{Receiver, Sender, channel}; use time::Duration; use io::IoResult; @@ -143,7 +144,7 @@ impl Timer { let (tx, rx) = channel(); // Short-circuit the timer backend for 0 duration if in_ms_u64(duration) != 0 { - self.inner.oneshot(in_ms_u64(duration), box TimerCallback { tx: tx }); + self.inner.oneshot(in_ms_u64(duration), box (HEAP) TimerCallback { tx: tx }); } else { tx.send(()).unwrap(); } @@ -204,7 +205,7 @@ impl Timer { // not clear what use a 0ms period is anyway... let ms = if ms == 0 { 1 } else { ms }; let (tx, rx) = channel(); - self.inner.period(ms, box TimerCallback { tx: tx }); + self.inner.period(ms, box (HEAP) TimerCallback { tx: tx }); return rx } } diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs index 9bfc15f14389f..08184503489d7 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -292,6 +292,7 @@ mod std { pub use thread_local; // used for thread_local! pub use marker; // used for tls! pub use ops; // used for bitflags! + pub use ptr; // necessary for box // The test runner calls ::std::os::args() but really wants realstd #[cfg(test)] pub use realstd::os as os; diff --git a/src/libstd/rt/unwind.rs b/src/libstd/rt/unwind.rs index b313a5312bcfa..29c78f51bc492 100644 --- a/src/libstd/rt/unwind.rs +++ b/src/libstd/rt/unwind.rs @@ -60,6 +60,7 @@ use prelude::v1::*; use any::Any; +use boxed::HEAP; use cell::Cell; use cmp; use failure; @@ -164,7 +165,7 @@ fn rust_panic(cause: Box) -> ! { rtdebug!("begin_unwind()"); unsafe { - let exception = box Exception { + let exception = box (HEAP) Exception { uwe: uw::_Unwind_Exception { exception_class: rust_exception_class(), exception_cleanup: exception_cleanup, @@ -502,7 +503,7 @@ pub fn begin_unwind_fmt(msg: fmt::Arguments, file_line: &(&'static str, uint)) - let mut s = String::new(); let _ = write!(&mut s, "{}", msg); - begin_unwind_inner(box s, file_line) + begin_unwind_inner(Box::new(s), file_line) } /// This is the entry point of unwinding for panic!() and assert!(). @@ -516,7 +517,8 @@ pub fn begin_unwind(msg: M, file_line: &(&'static str, uint)) -> // panicking. // see below for why we do the `Any` coercion here. - begin_unwind_inner(box msg, file_line) + let msg: Box = box msg; + begin_unwind_inner(msg, file_line) } /// The core of the unwinding. diff --git a/src/libstd/sync/mpsc/mpsc_queue.rs b/src/libstd/sync/mpsc/mpsc_queue.rs index ea81ed30a9c60..40c43ff997955 100644 --- a/src/libstd/sync/mpsc/mpsc_queue.rs +++ b/src/libstd/sync/mpsc/mpsc_queue.rs @@ -44,7 +44,7 @@ pub use self::PopResult::*; use core::prelude::*; -use alloc::boxed::Box; +use alloc::boxed::{Box, HEAP}; use core::mem; use core::ptr; use core::cell::UnsafeCell; @@ -82,7 +82,9 @@ unsafe impl Sync for Queue { } impl Node { unsafe fn new(v: Option) -> *mut Node { - mem::transmute(box Node { + // SNAP 9006c3c + // Change `box (HEAP)` to `in (HEAP) ..` after snapshot. + mem::transmute(box (HEAP) Node { next: AtomicPtr::new(ptr::null_mut()), value: v, }) @@ -161,12 +163,13 @@ mod tests { use super::{Queue, Data, Empty, Inconsistent}; use sync::Arc; use thread::Thread; + use alloc::boxed::{HEAP}; #[test] fn test_full() { let q = Queue::new(); - q.push(box 1i); - q.push(box 2i); + q.push(box (HEAP) 1i); + q.push(box (HEAP) 2i); } #[test] diff --git a/src/libstd/sync/mpsc/spsc_queue.rs b/src/libstd/sync/mpsc/spsc_queue.rs index 8cd88cedf6b7d..1033190b9231f 100644 --- a/src/libstd/sync/mpsc/spsc_queue.rs +++ b/src/libstd/sync/mpsc/spsc_queue.rs @@ -37,7 +37,7 @@ use core::prelude::*; -use alloc::boxed::Box; +use alloc::boxed::{Box, HEAP}; use core::mem; use core::ptr; use core::cell::UnsafeCell; @@ -81,7 +81,9 @@ unsafe impl Sync for Queue { } impl Node { fn new() -> *mut Node { unsafe { - mem::transmute(box Node { + // SNAP 9006c3c + // Change `box (HEAP)` to `in (HEAP) ..` after snapshot. + mem::transmute(box (HEAP) Node { value: None, next: AtomicPtr::new(ptr::null_mut::>()), }) @@ -244,6 +246,7 @@ impl Drop for Queue { mod test { use prelude::v1::*; + use alloc::boxed::{HEAP}; use sync::Arc; use super::Queue; use thread::Thread; @@ -290,8 +293,8 @@ mod test { fn drop_full() { unsafe { let q = Queue::new(0); - q.push(box 1i); - q.push(box 2i); + q.push(box (HEAP) 1i); + q.push(box (HEAP) 2i); } } diff --git a/src/libstd/sys/common/helper_thread.rs b/src/libstd/sys/common/helper_thread.rs index 6f6179a436e91..1be5bd7a166d0 100644 --- a/src/libstd/sys/common/helper_thread.rs +++ b/src/libstd/sys/common/helper_thread.rs @@ -22,6 +22,7 @@ use prelude::v1::*; +use boxed::{HEAP}; use cell::UnsafeCell; use mem; use ptr; @@ -88,7 +89,9 @@ impl Helper { let _guard = self.lock.lock().unwrap(); if !*self.initialized.get() { let (tx, rx) = channel(); - *self.chan.get() = mem::transmute(box tx); + // SNAP 9006c3c + // Change `box (HEAP)` to `in (HEAP) ..` after snapshot. + *self.chan.get() = mem::transmute(box (HEAP) tx); let (receive, send) = helper_signal::new(); *self.signal.get() = send as uint; diff --git a/src/libstd/sys/unix/thread.rs b/src/libstd/sys/unix/thread.rs index ac51b68795fbe..9d9d7b11a8c03 100644 --- a/src/libstd/sys/unix/thread.rs +++ b/src/libstd/sys/unix/thread.rs @@ -10,7 +10,7 @@ use core::prelude::*; -use boxed::Box; +use boxed::{Box, HEAP}; use cmp; use mem; use ptr; @@ -194,7 +194,9 @@ pub unsafe fn create(stack: uint, p: Thunk) -> rust_thread { }, }; - let arg: *mut libc::c_void = mem::transmute(box p); // must box since sizeof(p)=2*uint + // SNAP 9006c3c + // Change `box (HEAP)` to `in (HEAP)` after snapshot. + let arg: *mut libc::c_void = mem::transmute(box (HEAP) p); // must box since sizeof(p)=2*uint let ret = pthread_create(&mut native, &attr, thread_start, arg); assert_eq!(pthread_attr_destroy(&mut attr), 0); diff --git a/src/libstd/thunk.rs b/src/libstd/thunk.rs index 1830a4df54aab..2e52667bc97dd 100644 --- a/src/libstd/thunk.rs +++ b/src/libstd/thunk.rs @@ -31,8 +31,9 @@ impl Thunk { pub fn with_arg(func: F) -> Thunk where F : FnOnce(A) -> R, F : Send { + let func: Box<_> = box func; Thunk { - invoke: box func + invoke: func } } From 58184172273dc1b0d768ea7a4f9c5ccbaff38832 Mon Sep 17 00:00:00 2001 From: "Felix S. Klock II" Date: Fri, 6 Feb 2015 15:25:19 +0100 Subject: [PATCH 06/10] fallout from box protocol changes in rustc related crates. --- src/librustc/lint/context.rs | 6 +++--- src/librustc/middle/const_eval.rs | 4 ++-- src/librustc/middle/dataflow.rs | 2 +- src/librustc/plugin/registry.rs | 2 +- src/librustc_driver/driver.rs | 2 +- src/librustc_driver/lib.rs | 8 ++++---- src/librustc_driver/pretty.rs | 4 ++-- src/librustc_llvm/lib.rs | 4 ++-- src/librustc_trans/back/write.rs | 2 +- src/librustc_trans/save/mod.rs | 2 +- src/librustc_trans/trans/base.rs | 2 +- src/librustc_trans/trans/cleanup.rs | 20 ++++++++++---------- src/librustc_trans/trans/inline.rs | 2 +- src/libsyntax/diagnostic.rs | 6 +++--- src/libsyntax/ext/base.rs | 18 +++++++++--------- src/libsyntax/ext/deriving/clone.rs | 4 ++-- src/libsyntax/ext/deriving/cmp/eq.rs | 8 ++++---- src/libsyntax/ext/deriving/cmp/ord.rs | 18 +++++++++--------- src/libsyntax/ext/deriving/cmp/totaleq.rs | 6 +++--- src/libsyntax/ext/deriving/cmp/totalord.rs | 8 ++++---- src/libsyntax/ext/deriving/decodable.rs | 4 ++-- src/libsyntax/ext/deriving/default.rs | 4 ++-- src/libsyntax/ext/deriving/encodable.rs | 4 ++-- src/libsyntax/ext/deriving/hash.rs | 4 ++-- src/libsyntax/ext/deriving/primitive.rs | 8 ++++---- src/libsyntax/ext/deriving/rand.rs | 4 ++-- src/libsyntax/ext/deriving/show.rs | 4 ++-- src/libsyntax/ext/expand.rs | 2 +- src/libsyntax/ext/source_util.rs | 2 +- src/libsyntax/ext/tt/macro_parser.rs | 2 +- src/libsyntax/ext/tt/macro_rules.rs | 10 +++++----- src/libsyntax/owned_slice.rs | 2 +- src/libsyntax/parse/mod.rs | 6 +++--- src/libsyntax/print/pprust.rs | 2 +- 34 files changed, 93 insertions(+), 93 deletions(-) diff --git a/src/librustc/lint/context.rs b/src/librustc/lint/context.rs index d871461dd8a1a..f9812bfbbaddb 100644 --- a/src/librustc/lint/context.rs +++ b/src/librustc/lint/context.rs @@ -171,7 +171,7 @@ impl LintStore { macro_rules! add_builtin { ($sess:ident, $($name:ident),*,) => ( {$( - self.register_pass($sess, false, box builtin::$name as LintPassObject); + self.register_pass($sess, false, Box::new(builtin::$name) as LintPassObject); )*} ) } @@ -179,7 +179,7 @@ impl LintStore { macro_rules! add_builtin_with_new { ($sess:ident, $($name:ident),*,) => ( {$( - self.register_pass($sess, false, box builtin::$name::new() as LintPassObject); + self.register_pass($sess, false, Box::new(builtin::$name::new()) as LintPassObject); )*} ) } @@ -231,7 +231,7 @@ impl LintStore { UNUSED_UNSAFE, PATH_STATEMENTS); // We have one lint pass defined in this module. - self.register_pass(sess, false, box GatherNodeLevels as LintPassObject); + self.register_pass(sess, false, Box::new(GatherNodeLevels) as LintPassObject); // Insert temporary renamings for a one-time deprecation self.register_renamed("raw_pointer_deriving", "raw_pointer_derive"); diff --git a/src/librustc/middle/const_eval.rs b/src/librustc/middle/const_eval.rs index c2533c1a9c688..ded069dc9944f 100644 --- a/src/librustc/middle/const_eval.rs +++ b/src/librustc/middle/const_eval.rs @@ -132,7 +132,7 @@ fn lookup_variant_by_id<'a>(tcx: &'a ty::ctxt, None => {} } let expr_id = match csearch::maybe_get_item_ast(tcx, enum_def, - box |a, b, c, d| astencode::decode_inlined_item(a, b, c, d)) { + Box::new( |a, b, c, d| astencode::decode_inlined_item(a, b, c, d))) { csearch::found(&ast::IIItem(ref item)) => match item.node { ast::ItemEnum(ast::EnumDef { ref variants }, _) => { // NOTE this doesn't do the right thing, it compares inlined @@ -172,7 +172,7 @@ pub fn lookup_const_by_id<'a>(tcx: &'a ty::ctxt, def_id: ast::DefId) None => {} } let expr_id = match csearch::maybe_get_item_ast(tcx, def_id, - box |a, b, c, d| astencode::decode_inlined_item(a, b, c, d)) { + Box::new( |a, b, c, d| astencode::decode_inlined_item(a, b, c, d))) { csearch::found(&ast::IIItem(ref item)) => match item.node { ast::ItemConst(_, ref const_expr) => Some(const_expr.id), _ => None diff --git a/src/librustc/middle/dataflow.rs b/src/librustc/middle/dataflow.rs index a172786981031..59f1993011148 100644 --- a/src/librustc/middle/dataflow.rs +++ b/src/librustc/middle/dataflow.rs @@ -457,7 +457,7 @@ impl<'a, 'tcx, O:DataFlowOperator+Clone+'static> DataFlowContext<'a, 'tcx, O> { debug!("Dataflow result for {}:", self.analysis_name); debug!("{}", { - self.pretty_print_to(box io::stderr(), blk).unwrap(); + self.pretty_print_to(Box::new(io::stderr()), blk).unwrap(); "" }); } diff --git a/src/librustc/plugin/registry.rs b/src/librustc/plugin/registry.rs index f6fb1c2d41928..8c831c93f3340 100644 --- a/src/librustc/plugin/registry.rs +++ b/src/librustc/plugin/registry.rs @@ -96,7 +96,7 @@ impl<'a> Registry<'a> { /// It builds for you a `NormalTT` that calls `expander`, /// and also takes care of interning the macro's name. pub fn register_macro(&mut self, name: &str, expander: MacroExpanderFn) { - self.register_syntax_extension(token::intern(name), NormalTT(box expander, None)); + self.register_syntax_extension(token::intern(name), NormalTT(Box::new(expander), None)); } /// Register a compiler lint pass. diff --git a/src/librustc_driver/driver.rs b/src/librustc_driver/driver.rs index 3fac5ba9674c3..2a4404ac2b29f 100644 --- a/src/librustc_driver/driver.rs +++ b/src/librustc_driver/driver.rs @@ -213,7 +213,7 @@ impl<'a> PhaseController<'a> { pub fn basic() -> PhaseController<'a> { PhaseController { stop: false, - callback: box |&: _| {}, + callback: Box::new(|&: _| {}), } } } diff --git a/src/librustc_driver/lib.rs b/src/librustc_driver/lib.rs index 0e940b85bd84d..952639ea880cc 100644 --- a/src/librustc_driver/lib.rs +++ b/src/librustc_driver/lib.rs @@ -224,13 +224,13 @@ fn build_controller<'a>(sess: &Session) -> CompileController<'a> { } if sess.opts.debugging_opts.save_analysis { - control.after_analysis.callback = box |state| { + control.after_analysis.callback = Box::new(|state| { time(state.session.time_passes(), "save analysis", state.krate.unwrap(), |krate| save::process_crate(state.session, krate, state.analysis.unwrap(), state.out_dir)); - }; + }); control.make_glob_map = resolve::MakeGlobMap::Yes; } @@ -614,7 +614,7 @@ pub fn monitor(f: F) { cfg = cfg.stack_size(STACK_SIZE); } - match cfg.scoped(move || { std::io::stdio::set_stderr(box w); f() }).join() { + match cfg.scoped(move || { std::io::stdio::set_stderr(Box::new(w)); f() }).join() { Ok(()) => { /* fallthrough */ } Err(value) => { // Thread panicked without emitting a fatal diagnostic @@ -656,7 +656,7 @@ pub fn monitor(f: F) { // Panic so the process returns a failure code, but don't pollute the // output with some unnecessary panic messages, we've already // printed everything that we needed to. - io::stdio::set_stderr(box io::util::NullWriter); + io::stdio::set_stderr(Box::new(io::util::NullWriter)); panic!(); } } diff --git a/src/librustc_driver/pretty.rs b/src/librustc_driver/pretty.rs index 582e10323248c..4c71fec4e399a 100644 --- a/src/librustc_driver/pretty.rs +++ b/src/librustc_driver/pretty.rs @@ -548,11 +548,11 @@ pub fn pretty_print_input(sess: Session, let mut rdr = MemReader::new(src); let out = match ofile { - None => box io::stdout() as Box, + None => Box::new(io::stdout()) as Box, Some(p) => { let r = io::File::create(&p); match r { - Ok(w) => box w as Box, + Ok(w) => Box::new(w) as Box, Err(e) => panic!("print-print failed to open {} due to {}", p.display(), e), } diff --git a/src/librustc_llvm/lib.rs b/src/librustc_llvm/lib.rs index 8c651cf839b74..b734490e2a0ab 100644 --- a/src/librustc_llvm/lib.rs +++ b/src/librustc_llvm/lib.rs @@ -246,12 +246,12 @@ impl AttrBuilder { } pub fn arg<'a, T: AttrHelper + 'static>(&'a mut self, idx: uint, a: T) -> &'a mut AttrBuilder { - self.attrs.push((idx, box a as Box)); + self.attrs.push((idx, Box::new(a) as Box)); self } pub fn ret<'a, T: AttrHelper + 'static>(&'a mut self, a: T) -> &'a mut AttrBuilder { - self.attrs.push((ReturnIndex as uint, box a as Box)); + self.attrs.push((ReturnIndex as uint, Box::new(a) as Box)); self } diff --git a/src/librustc_trans/back/write.rs b/src/librustc_trans/back/write.rs index 5e48ce384be51..ae30e7172abdb 100644 --- a/src/librustc_trans/back/write.rs +++ b/src/librustc_trans/back/write.rs @@ -911,7 +911,7 @@ fn run_work_multithreaded(sess: &Session, futures.push(rx); thread::Builder::new().name(format!("codegen-{}", i)).spawn(move |:| { - let diag_handler = mk_handler(box diag_emitter); + let diag_handler = mk_handler(Box::new(diag_emitter)); // Must construct cgcx inside the proc because it has non-Send // fields. diff --git a/src/librustc_trans/save/mod.rs b/src/librustc_trans/save/mod.rs index 71ca6a4db03d3..aa2f9cdb7d14c 100644 --- a/src/librustc_trans/save/mod.rs +++ b/src/librustc_trans/save/mod.rs @@ -1548,7 +1548,7 @@ pub fn process_crate(sess: &Session, out_name.push_str(".csv"); root_path.push(out_name); let output_file = match File::create(&root_path) { - Ok(f) => box f, + Ok(f) => Box::new(f), Err(e) => { let disp = root_path.display(); sess.fatal(&format!("Could not open {}: {}", disp, e)[]); diff --git a/src/librustc_trans/trans/base.rs b/src/librustc_trans/trans/base.rs index 230a4c5d4272e..f9ea38936962c 100644 --- a/src/librustc_trans/trans/base.rs +++ b/src/librustc_trans/trans/base.rs @@ -2962,7 +2962,7 @@ pub fn write_metadata(cx: &SharedCrateContext, krate: &ast::Crate) -> Vec { } let encode_inlined_item: encoder::EncodeInlinedItem = - box |ecx, rbml_w, ii| astencode::encode_inlined_item(ecx, rbml_w, ii); + Box::new( |ecx, rbml_w, ii| astencode::encode_inlined_item(ecx, rbml_w, ii)); let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item); let metadata = encoder::encode_metadata(encode_parms, krate); diff --git a/src/librustc_trans/trans/cleanup.rs b/src/librustc_trans/trans/cleanup.rs index a25f4f778ab7a..40d882ab44378 100644 --- a/src/librustc_trans/trans/cleanup.rs +++ b/src/librustc_trans/trans/cleanup.rs @@ -262,9 +262,9 @@ impl<'blk, 'tcx> CleanupMethods<'blk, 'tcx> for FunctionContext<'blk, 'tcx> { fn schedule_lifetime_end(&self, cleanup_scope: ScopeId, val: ValueRef) { - let drop = box LifetimeEnd { + let drop = Box::new(LifetimeEnd { ptr: val, - }; + }); debug!("schedule_lifetime_end({:?}, val={})", cleanup_scope, @@ -279,13 +279,13 @@ impl<'blk, 'tcx> CleanupMethods<'blk, 'tcx> for FunctionContext<'blk, 'tcx> { val: ValueRef, ty: Ty<'tcx>) { if !common::type_needs_drop(self.ccx.tcx(), ty) { return; } - let drop = box DropValue { + let drop = Box::new(DropValue { is_immediate: false, must_unwind: common::type_needs_unwind_cleanup(self.ccx, ty), val: val, ty: ty, zero: false - }; + }); debug!("schedule_drop_mem({:?}, val={}, ty={})", cleanup_scope, @@ -301,13 +301,13 @@ impl<'blk, 'tcx> CleanupMethods<'blk, 'tcx> for FunctionContext<'blk, 'tcx> { val: ValueRef, ty: Ty<'tcx>) { if !common::type_needs_drop(self.ccx.tcx(), ty) { return; } - let drop = box DropValue { + let drop = Box::new(DropValue { is_immediate: false, must_unwind: common::type_needs_unwind_cleanup(self.ccx, ty), val: val, ty: ty, zero: true - }; + }); debug!("schedule_drop_and_zero_mem({:?}, val={}, ty={}, zero={})", cleanup_scope, @@ -325,13 +325,13 @@ impl<'blk, 'tcx> CleanupMethods<'blk, 'tcx> for FunctionContext<'blk, 'tcx> { ty: Ty<'tcx>) { if !common::type_needs_drop(self.ccx.tcx(), ty) { return; } - let drop = box DropValue { + let drop = Box::new(DropValue { is_immediate: true, must_unwind: common::type_needs_unwind_cleanup(self.ccx, ty), val: val, ty: ty, zero: false - }; + }); debug!("schedule_drop_immediate({:?}, val={}, ty={:?})", cleanup_scope, @@ -347,7 +347,7 @@ impl<'blk, 'tcx> CleanupMethods<'blk, 'tcx> for FunctionContext<'blk, 'tcx> { val: ValueRef, heap: Heap, content_ty: Ty<'tcx>) { - let drop = box FreeValue { ptr: val, heap: heap, content_ty: content_ty }; + let drop = Box::new(FreeValue { ptr: val, heap: heap, content_ty: content_ty }); debug!("schedule_free_value({:?}, val={}, heap={:?})", cleanup_scope, @@ -364,7 +364,7 @@ impl<'blk, 'tcx> CleanupMethods<'blk, 'tcx> for FunctionContext<'blk, 'tcx> { size: ValueRef, align: ValueRef, heap: Heap) { - let drop = box FreeSlice { ptr: val, size: size, align: align, heap: heap }; + let drop = Box::new(FreeSlice { ptr: val, size: size, align: align, heap: heap }); debug!("schedule_free_slice({:?}, val={}, heap={:?})", cleanup_scope, diff --git a/src/librustc_trans/trans/inline.rs b/src/librustc_trans/trans/inline.rs index dd1cfc5ad6d82..fb2d4ea49fb54 100644 --- a/src/librustc_trans/trans/inline.rs +++ b/src/librustc_trans/trans/inline.rs @@ -40,7 +40,7 @@ fn instantiate_inline(ccx: &CrateContext, fn_id: ast::DefId) let csearch_result = csearch::maybe_get_item_ast( ccx.tcx(), fn_id, - box |a,b,c,d| astencode::decode_inlined_item(a, b, c, d)); + Box::new( |a,b,c,d| astencode::decode_inlined_item(a, b, c, d))); let inline_def = match csearch_result { csearch::not_found => { diff --git a/src/libsyntax/diagnostic.rs b/src/libsyntax/diagnostic.rs index 0c7f6befc4e3e..81ba90d8960de 100644 --- a/src/libsyntax/diagnostic.rs +++ b/src/libsyntax/diagnostic.rs @@ -219,7 +219,7 @@ pub fn mk_span_handler(handler: Handler, cm: codemap::CodeMap) -> SpanHandler { pub fn default_handler(color_config: ColorConfig, registry: Option) -> Handler { - mk_handler(box EmitterWriter::stderr(color_config, registry)) + mk_handler(Box::new(EmitterWriter::stderr(color_config, registry))) } pub fn mk_handler(e: Box) -> Handler { @@ -347,11 +347,11 @@ impl EmitterWriter { if use_color { let dst = match term::stderr() { Some(t) => Terminal(t), - None => Raw(box stderr), + None => Raw(Box::new(stderr)), }; EmitterWriter { dst: dst, registry: registry } } else { - EmitterWriter { dst: Raw(box stderr), registry: registry } + EmitterWriter { dst: Raw(Box::new(stderr)), registry: registry } } } diff --git a/src/libsyntax/ext/base.rs b/src/libsyntax/ext/base.rs index ef8010927dccc..3934337f99b25 100644 --- a/src/libsyntax/ext/base.rs +++ b/src/libsyntax/ext/base.rs @@ -265,7 +265,7 @@ pub struct MacExpr { } impl MacExpr { pub fn new(e: P) -> Box { - box MacExpr { e: e } as Box + Box::new(MacExpr { e: e }) as Box } } impl MacResult for MacExpr { @@ -289,7 +289,7 @@ pub struct MacPat { } impl MacPat { pub fn new(p: P) -> Box { - box MacPat { p: p } as Box + Box::new(MacPat { p: p }) as Box } } impl MacResult for MacPat { @@ -304,7 +304,7 @@ pub struct MacItems { impl MacItems { pub fn new>>(it: I) -> Box { - box MacItems { items: it.collect() } as Box + Box::new(MacItems { items: it.collect() }) as Box } } @@ -328,7 +328,7 @@ impl DummyResult { /// Use this as a return value after hitting any errors and /// calling `span_err`. pub fn any(sp: Span) -> Box { - box DummyResult { expr_only: false, span: sp } as Box + Box::new(DummyResult { expr_only: false, span: sp }) as Box } /// Create a default MacResult that can only be an expression. @@ -337,7 +337,7 @@ impl DummyResult { /// if an error is encountered internally, the user will receive /// an error that they also used it in the wrong place. pub fn expr(sp: Span) -> Box { - box DummyResult { expr_only: true, span: sp } as Box + Box::new(DummyResult { expr_only: true, span: sp }) as Box } /// A plain dummy expression. @@ -442,7 +442,7 @@ impl BlockInfo { fn initial_syntax_expander_table(ecfg: &expand::ExpansionConfig) -> SyntaxEnv { // utility function to simplify creating NormalTT syntax extensions fn builtin_normal_expander(f: MacroExpanderFn) -> SyntaxExtension { - NormalTT(box f, None) + NormalTT(Box::new(f), None) } let mut syntax_expanders = SyntaxEnv::new(); @@ -466,9 +466,9 @@ fn initial_syntax_expander_table(ecfg: &expand::ExpansionConfig) -> SyntaxEnv { builtin_normal_expander( ext::log_syntax::expand_syntax_ext)); syntax_expanders.insert(intern("derive"), - Decorator(box ext::deriving::expand_meta_derive)); + Decorator(Box::new(ext::deriving::expand_meta_derive))); syntax_expanders.insert(intern("deriving"), - Decorator(box ext::deriving::expand_deprecated_deriving)); + Decorator(Box::new(ext::deriving::expand_deprecated_deriving))); if ecfg.enable_quotes { // Quasi-quoting expanders @@ -529,7 +529,7 @@ fn initial_syntax_expander_table(ecfg: &expand::ExpansionConfig) -> SyntaxEnv { builtin_normal_expander( ext::cfg::expand_cfg)); syntax_expanders.insert(intern("cfg_attr"), - Modifier(box ext::cfg_attr::expand)); + Modifier(Box::new(ext::cfg_attr::expand))); syntax_expanders.insert(intern("trace_macros"), builtin_normal_expander( ext::trace_macros::expand_trace_macros)); diff --git a/src/libsyntax/ext/deriving/clone.rs b/src/libsyntax/ext/deriving/clone.rs index 6498e8d2d587a..16ede8ed3c22a 100644 --- a/src/libsyntax/ext/deriving/clone.rs +++ b/src/libsyntax/ext/deriving/clone.rs @@ -40,9 +40,9 @@ pub fn expand_deriving_clone(cx: &mut ExtCtxt, args: Vec::new(), ret_ty: Self, attributes: attrs, - combine_substructure: combine_substructure(box |c, s, sub| { + combine_substructure: combine_substructure(Box::new( |c, s, sub| { cs_clone("Clone", c, s, sub) - }), + })), } ) }; diff --git a/src/libsyntax/ext/deriving/cmp/eq.rs b/src/libsyntax/ext/deriving/cmp/eq.rs index c550c26c74572..48bb13abd9ba6 100644 --- a/src/libsyntax/ext/deriving/cmp/eq.rs +++ b/src/libsyntax/ext/deriving/cmp/eq.rs @@ -40,7 +40,7 @@ pub fn expand_deriving_eq(cx: &mut ExtCtxt, cx.expr_binary(span, ast::BiAnd, subexpr, eq) }, cx.expr_bool(span, true), - box |cx, span, _, _| cx.expr_bool(span, false), + Box::new( |cx, span, _, _| cx.expr_bool(span, false)), cx, span, substr) } fn cs_ne(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> P { @@ -57,7 +57,7 @@ pub fn expand_deriving_eq(cx: &mut ExtCtxt, cx.expr_binary(span, ast::BiOr, subexpr, eq) }, cx.expr_bool(span, false), - box |cx, span, _, _| cx.expr_bool(span, true), + Box::new( |cx, span, _, _| cx.expr_bool(span, true)), cx, span, substr) } @@ -72,9 +72,9 @@ pub fn expand_deriving_eq(cx: &mut ExtCtxt, args: vec!(borrowed_self()), ret_ty: Literal(Path::new(vec!("bool"))), attributes: attrs, - combine_substructure: combine_substructure(box |a, b, c| { + combine_substructure: combine_substructure(Box::new( |a, b, c| { $f(a, b, c) - }) + })) } } } } diff --git a/src/libsyntax/ext/deriving/cmp/ord.rs b/src/libsyntax/ext/deriving/cmp/ord.rs index 9f1850145b6c5..5ce9b322e115f 100644 --- a/src/libsyntax/ext/deriving/cmp/ord.rs +++ b/src/libsyntax/ext/deriving/cmp/ord.rs @@ -38,9 +38,9 @@ pub fn expand_deriving_ord(cx: &mut ExtCtxt, args: vec!(borrowed_self()), ret_ty: Literal(Path::new(vec!("bool"))), attributes: attrs, - combine_substructure: combine_substructure(box |cx, span, substr| { + combine_substructure: combine_substructure(Box::new( |cx, span, substr| { cs_op($op, $equal, cx, span, substr) - }) + })) } } } } @@ -48,7 +48,7 @@ pub fn expand_deriving_ord(cx: &mut ExtCtxt, let ordering_ty = Literal(Path::new(vec!["std", "cmp", "Ordering"])); let ret_ty = Literal(Path::new_(vec!["std", "option", "Option"], None, - vec![box ordering_ty], + vec![Box::new(ordering_ty)], true)); let inline = cx.meta_word(span, InternedString::new("inline")); @@ -61,9 +61,9 @@ pub fn expand_deriving_ord(cx: &mut ExtCtxt, args: vec![borrowed_self()], ret_ty: ret_ty, attributes: attrs, - combine_substructure: combine_substructure(box |cx, span, substr| { + combine_substructure: combine_substructure(Box::new( |cx, span, substr| { cs_partial_cmp(cx, span, substr) - }) + })) }; let trait_def = TraitDef { @@ -174,13 +174,13 @@ pub fn cs_partial_cmp(cx: &mut ExtCtxt, span: Span, cx.expr_block(cx.block(span, vec!(assign), Some(if_))) }, equals_expr.clone(), - box |cx, span, (self_args, tag_tuple), _non_self_args| { + Box::new( |cx, span, (self_args, tag_tuple), _non_self_args| { if self_args.len() != 2 { cx.span_bug(span, "not exactly 2 arguments in `derive(PartialOrd)`") } else { some_ordering_collapsed(cx, span, PartialCmpOp, tag_tuple) } - }, + }), cx, span, substr) } @@ -222,7 +222,7 @@ fn cs_op(less: bool, equal: bool, cx: &mut ExtCtxt, cx.expr_binary(span, ast::BiOr, cmp, and) }, cx.expr_bool(span, equal), - box |cx, span, (self_args, tag_tuple), _non_self_args| { + Box::new( |cx, span, (self_args, tag_tuple), _non_self_args| { if self_args.len() != 2 { cx.span_bug(span, "not exactly 2 arguments in `derive(PartialOrd)`") } else { @@ -232,6 +232,6 @@ fn cs_op(less: bool, equal: bool, cx: &mut ExtCtxt, }; some_ordering_collapsed(cx, span, op, tag_tuple) } - }, + }), cx, span, substr) } diff --git a/src/libsyntax/ext/deriving/cmp/totaleq.rs b/src/libsyntax/ext/deriving/cmp/totaleq.rs index 9a2af6a3e0bee..c4ec092eee225 100644 --- a/src/libsyntax/ext/deriving/cmp/totaleq.rs +++ b/src/libsyntax/ext/deriving/cmp/totaleq.rs @@ -32,7 +32,7 @@ pub fn expand_deriving_totaleq(cx: &mut ExtCtxt, let block = cx.block(span, stmts, None); cx.expr_block(block) }, - box |cx, sp, _, _| cx.span_bug(sp, "non matching enums in derive(Eq)?"), + Box::new( |cx, sp, _, _| cx.span_bug(sp, "non matching enums in derive(Eq)?")), cx, span, substr) @@ -57,9 +57,9 @@ pub fn expand_deriving_totaleq(cx: &mut ExtCtxt, args: vec!(), ret_ty: nil_ty(), attributes: attrs, - combine_substructure: combine_substructure(box |a, b, c| { + combine_substructure: combine_substructure(Box::new( |a, b, c| { cs_total_eq_assert(a, b, c) - }) + })) } ) }; diff --git a/src/libsyntax/ext/deriving/cmp/totalord.rs b/src/libsyntax/ext/deriving/cmp/totalord.rs index 29d327142a6cf..0613bf8ddf509 100644 --- a/src/libsyntax/ext/deriving/cmp/totalord.rs +++ b/src/libsyntax/ext/deriving/cmp/totalord.rs @@ -41,9 +41,9 @@ pub fn expand_deriving_totalord(cx: &mut ExtCtxt, args: vec!(borrowed_self()), ret_ty: Literal(Path::new(vec!("std", "cmp", "Ordering"))), attributes: attrs, - combine_substructure: combine_substructure(box |a, b, c| { + combine_substructure: combine_substructure(Box::new( |a, b, c| { cs_cmp(a, b, c) - }), + })), } ) }; @@ -130,12 +130,12 @@ pub fn cs_cmp(cx: &mut ExtCtxt, span: Span, cx.expr_block(cx.block(span, vec!(assign), Some(if_))) }, cx.expr_path(equals_path.clone()), - box |cx, span, (self_args, tag_tuple), _non_self_args| { + Box::new( |cx, span, (self_args, tag_tuple), _non_self_args| { if self_args.len() != 2 { cx.span_bug(span, "not exactly 2 arguments in `derives(Ord)`") } else { ordering_collapsed(cx, span, tag_tuple) } - }, + }), cx, span, substr) } diff --git a/src/libsyntax/ext/deriving/decodable.rs b/src/libsyntax/ext/deriving/decodable.rs index e458bd58e8b6a..2f4f5c79c04e1 100644 --- a/src/libsyntax/ext/deriving/decodable.rs +++ b/src/libsyntax/ext/deriving/decodable.rs @@ -76,9 +76,9 @@ fn expand_deriving_decodable_imp(cx: &mut ExtCtxt, true )), attributes: Vec::new(), - combine_substructure: combine_substructure(box |a, b, c| { + combine_substructure: combine_substructure(Box::new( |a, b, c| { decodable_substructure(a, b, c, krate) - }), + })), }) }; diff --git a/src/libsyntax/ext/deriving/default.rs b/src/libsyntax/ext/deriving/default.rs index f8fdd8575bd67..b15bc14814b71 100644 --- a/src/libsyntax/ext/deriving/default.rs +++ b/src/libsyntax/ext/deriving/default.rs @@ -40,9 +40,9 @@ pub fn expand_deriving_default(cx: &mut ExtCtxt, args: Vec::new(), ret_ty: Self, attributes: attrs, - combine_substructure: combine_substructure(box |a, b, c| { + combine_substructure: combine_substructure(Box::new( |a, b, c| { default_substructure(a, b, c) - }) + })) }) }; trait_def.expand(cx, mitem, item, push) diff --git a/src/libsyntax/ext/deriving/encodable.rs b/src/libsyntax/ext/deriving/encodable.rs index 4c78a7b6a0cfe..c6192d2df81f2 100644 --- a/src/libsyntax/ext/deriving/encodable.rs +++ b/src/libsyntax/ext/deriving/encodable.rs @@ -152,9 +152,9 @@ fn expand_deriving_encodable_imp(cx: &mut ExtCtxt, true )), attributes: Vec::new(), - combine_substructure: combine_substructure(box |a, b, c| { + combine_substructure: combine_substructure(Box::new( |a, b, c| { encodable_substructure(a, b, c) - }), + })), }) }; diff --git a/src/libsyntax/ext/deriving/hash.rs b/src/libsyntax/ext/deriving/hash.rs index 8dac864c2ae3b..f7030d7e57f2b 100644 --- a/src/libsyntax/ext/deriving/hash.rs +++ b/src/libsyntax/ext/deriving/hash.rs @@ -50,9 +50,9 @@ pub fn expand_deriving_hash(cx: &mut ExtCtxt, args: vec!(Ptr(box Literal(args), Borrowed(None, MutMutable))), ret_ty: nil_ty(), attributes: attrs, - combine_substructure: combine_substructure(box |a, b, c| { + combine_substructure: combine_substructure(Box::new( |a, b, c| { hash_substructure(a, b, c) - }) + })) } ) }; diff --git a/src/libsyntax/ext/deriving/primitive.rs b/src/libsyntax/ext/deriving/primitive.rs index c45fe1ceb2049..68ed6f73bf3d2 100644 --- a/src/libsyntax/ext/deriving/primitive.rs +++ b/src/libsyntax/ext/deriving/primitive.rs @@ -46,9 +46,9 @@ pub fn expand_deriving_from_primitive(cx: &mut ExtCtxt, true)), // #[inline] liable to cause code-bloat attributes: attrs.clone(), - combine_substructure: combine_substructure(box |c, s, sub| { + combine_substructure: combine_substructure(Box::new( |c, s, sub| { cs_from("i64", c, s, sub) - }), + })), }, MethodDef { name: "from_u64", @@ -62,9 +62,9 @@ pub fn expand_deriving_from_primitive(cx: &mut ExtCtxt, true)), // #[inline] liable to cause code-bloat attributes: attrs, - combine_substructure: combine_substructure(box |c, s, sub| { + combine_substructure: combine_substructure(Box::new( |c, s, sub| { cs_from("u64", c, s, sub) - }), + })), }) }; diff --git a/src/libsyntax/ext/deriving/rand.rs b/src/libsyntax/ext/deriving/rand.rs index bb902d7059c87..af9ae3b19c15f 100644 --- a/src/libsyntax/ext/deriving/rand.rs +++ b/src/libsyntax/ext/deriving/rand.rs @@ -45,9 +45,9 @@ pub fn expand_deriving_rand(cx: &mut ExtCtxt, ), ret_ty: Self, attributes: Vec::new(), - combine_substructure: combine_substructure(box |a, b, c| { + combine_substructure: combine_substructure(Box::new( |a, b, c| { rand_substructure(a, b, c) - }) + })) } ) }; diff --git a/src/libsyntax/ext/deriving/show.rs b/src/libsyntax/ext/deriving/show.rs index f5b5d4dda199c..0840ca36c8717 100644 --- a/src/libsyntax/ext/deriving/show.rs +++ b/src/libsyntax/ext/deriving/show.rs @@ -46,9 +46,9 @@ pub fn expand_deriving_show(cx: &mut ExtCtxt, args: vec!(fmtr), ret_ty: Literal(Path::new(vec!("std", "fmt", "Result"))), attributes: Vec::new(), - combine_substructure: combine_substructure(box |a, b, c| { + combine_substructure: combine_substructure(Box::new( |a, b, c| { show_substructure(a, b, c) - }) + })) } ) }; diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index 9ad70927e24b4..e2091fc235240 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -1212,7 +1212,7 @@ fn expand_annotatable(a: Annotatable, // but that double-mut-borrows fld let mut items: SmallVector> = SmallVector::zero(); dec.expand(fld.cx, attr.span, &*attr.node.value, &**it, - box |&mut: item| items.push(item)); + Box::new( |&mut: item| items.push(item))); decorator_items.extend(items.into_iter() .flat_map(|item| expand_item(item, fld).into_iter())); diff --git a/src/libsyntax/ext/source_util.rs b/src/libsyntax/ext/source_util.rs index a74adbf408515..4ac5c98136f09 100644 --- a/src/libsyntax/ext/source_util.rs +++ b/src/libsyntax/ext/source_util.rs @@ -121,7 +121,7 @@ pub fn expand_include<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree } } - box ExpandResult { p: p } + Box::new(ExpandResult { p: p }) } // include_str! : read the given file, insert it as a literal string expr diff --git a/src/libsyntax/ext/tt/macro_parser.rs b/src/libsyntax/ext/tt/macro_parser.rs index d115f2ed62082..79774d4367238 100644 --- a/src/libsyntax/ext/tt/macro_parser.rs +++ b/src/libsyntax/ext/tt/macro_parser.rs @@ -479,7 +479,7 @@ pub fn parse(sess: &ParseSess, } rdr.next_token(); } else /* bb_eis.len() == 1 */ { - let mut rust_parser = Parser::new(sess, cfg.clone(), box rdr.clone()); + let mut rust_parser = Parser::new(sess, cfg.clone(), Box::new(rdr.clone())); let mut ei = bb_eis.pop().unwrap(); match ei.top_elts.get_tt(ei.idx) { diff --git a/src/libsyntax/ext/tt/macro_rules.rs b/src/libsyntax/ext/tt/macro_rules.rs index 8350e0222ef89..f28cad9cdb183 100644 --- a/src/libsyntax/ext/tt/macro_rules.rs +++ b/src/libsyntax/ext/tt/macro_rules.rs @@ -181,13 +181,13 @@ fn generic_extension<'cx>(cx: &'cx ExtCtxt, Some(named_matches), imported_from, rhs); - let mut p = Parser::new(cx.parse_sess(), cx.cfg(), box trncbr); + let mut p = Parser::new(cx.parse_sess(), cx.cfg(), Box::new(trncbr)); p.check_unknown_macro_variable(); // Let the context choose how to interpret the result. // Weird, but useful for X-macros. - return box ParserAnyMacro { + return Box::new(ParserAnyMacro { parser: RefCell::new(p), - } as Box + }) as Box } Failure(sp, ref msg) => if sp.lo >= best_fail_spot.lo { best_fail_spot = sp; @@ -268,12 +268,12 @@ pub fn compile<'cx>(cx: &'cx mut ExtCtxt, _ => cx.span_bug(def.span, "wrong-structured rhs") }; - let exp = box MacroRulesMacroExpander { + let exp = Box::new(MacroRulesMacroExpander { name: def.ident, imported_from: def.imported_from, lhses: lhses, rhses: rhses, - }; + }); NormalTT(exp, Some(def.span)) } diff --git a/src/libsyntax/owned_slice.rs b/src/libsyntax/owned_slice.rs index 872354024e93c..542e7624c6579 100644 --- a/src/libsyntax/owned_slice.rs +++ b/src/libsyntax/owned_slice.rs @@ -30,7 +30,7 @@ impl fmt::Debug for OwnedSlice { impl OwnedSlice { pub fn empty() -> OwnedSlice { - OwnedSlice { data: box [] } + OwnedSlice { data: Box::new([]) } } #[inline(never)] diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index 8cb7ee5b33746..64399c86a8f2b 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -286,7 +286,7 @@ pub fn filemap_to_tts(sess: &ParseSess, filemap: Rc) // parsing tt's probably shouldn't require a parser at all. let cfg = Vec::new(); let srdr = lexer::StringReader::new(&sess.span_diagnostic, filemap); - let mut p1 = Parser::new(sess, cfg, box srdr); + let mut p1 = Parser::new(sess, cfg, Box::new(srdr)); p1.parse_all_token_trees() } @@ -295,7 +295,7 @@ pub fn tts_to_parser<'a>(sess: &'a ParseSess, tts: Vec, cfg: ast::CrateConfig) -> Parser<'a> { let trdr = lexer::new_tt_reader(&sess.span_diagnostic, None, None, tts); - let mut p = Parser::new(sess, cfg, box trdr); + let mut p = Parser::new(sess, cfg, Box::new(trdr)); p.check_unknown_macro_variable(); p } @@ -358,7 +358,7 @@ pub mod with_hygiene { use super::lexer::make_reader_with_embedded_idents as make_reader; let cfg = Vec::new(); let srdr = make_reader(&sess.span_diagnostic, filemap); - let mut p1 = Parser::new(sess, cfg, box srdr); + let mut p1 = Parser::new(sess, cfg, Box::new(srdr)); p1.parse_all_token_trees() } } diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index d06ac50920e04..f4d30484ac2e7 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -169,7 +169,7 @@ pub fn to_string(f: F) -> String where F: FnOnce(&mut State) -> IoResult<()>, { use std::raw::TraitObject; - let mut s = rust_printer(box Vec::new()); + let mut s = rust_printer(Box::new(Vec::new())); f(&mut s).unwrap(); eof(&mut s.s).unwrap(); let wr = unsafe { From 8dfb3c50114708d84c0a8fdc8f87be22f05fbfd5 Mon Sep 17 00:00:00 2001 From: "Felix S. Klock II" Date: Fri, 6 Feb 2015 15:25:38 +0100 Subject: [PATCH 07/10] fallout from box protocol changes in libterm crate. --- src/libterm/lib.rs | 13 +++++++------ src/libterm/terminfo/mod.rs | 5 +++-- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/src/libterm/lib.rs b/src/libterm/lib.rs index 027c5a1a70832..88fb005a2aca2 100644 --- a/src/libterm/lib.rs +++ b/src/libterm/lib.rs @@ -61,6 +61,7 @@ pub use terminfo::TerminfoTerminal; #[cfg(windows)] pub use win::WinConsole; +use std::boxed::HEAP; use std::io::IoResult; pub mod terminfo; @@ -91,7 +92,7 @@ impl Writer for WriterWrapper { /// opened. pub fn stdout() -> Option + Send>> { TerminfoTerminal::new(WriterWrapper { - wrapped: box std::io::stdout() as Box, + wrapped: box (HEAP) std::io::stdout() as Box, }) } @@ -100,14 +101,14 @@ pub fn stdout() -> Option + Send>> { /// opened. pub fn stdout() -> Option + Send>> { let ti = TerminfoTerminal::new(WriterWrapper { - wrapped: box std::io::stdout() as Box, + wrapped: box (HEAP) std::io::stdout() as Box, }); match ti { Some(t) => Some(t), None => { WinConsole::new(WriterWrapper { - wrapped: box std::io::stdout() as Box, + wrapped: box (HEAP) std::io::stdout() as Box, }) } } @@ -118,7 +119,7 @@ pub fn stdout() -> Option + Send>> { /// opened. pub fn stderr() -> Option + Send>> { TerminfoTerminal::new(WriterWrapper { - wrapped: box std::io::stderr() as Box, + wrapped: box (HEAP) std::io::stderr() as Box, }) } @@ -127,14 +128,14 @@ pub fn stderr() -> Option + Send>> { /// opened. pub fn stderr() -> Option + Send>> { let ti = TerminfoTerminal::new(WriterWrapper { - wrapped: box std::io::stderr() as Box, + wrapped: box (HEAP) std::io::stderr() as Box, }); match ti { Some(t) => Some(t), None => { WinConsole::new(WriterWrapper { - wrapped: box std::io::stderr() as Box, + wrapped: box (HEAP) std::io::stderr() as Box, }) } } diff --git a/src/libterm/terminfo/mod.rs b/src/libterm/terminfo/mod.rs index 2ef0bca3785cb..56027ba169a34 100644 --- a/src/libterm/terminfo/mod.rs +++ b/src/libterm/terminfo/mod.rs @@ -10,6 +10,7 @@ //! Terminfo database interface. +use std::boxed::HEAP; use std::collections::HashMap; use std::io::IoResult; use std::os; @@ -186,7 +187,7 @@ impl TerminfoTerminal { "mintty.exe" == s }) { // msys terminal - return Some(box TerminfoTerminal {out: out, + return Some(box (HEAP) TerminfoTerminal {out: out, ti: msys_terminfo(), num_colors: 8} as Box+Send>); } @@ -207,7 +208,7 @@ impl TerminfoTerminal { inf.numbers.get("colors").map_or(0, |&n| n) } else { 0 }; - return Some(box TerminfoTerminal {out: out, + return Some(box (HEAP) TerminfoTerminal {out: out, ti: inf, num_colors: nc} as Box+Send>); } From 99497053d72d5c5fc7769f591ed9c668abb513f1 Mon Sep 17 00:00:00 2001 From: "Felix S. Klock II" Date: Fri, 6 Feb 2015 15:25:54 +0100 Subject: [PATCH 08/10] fallout from box protocol changes in libtest crate. --- src/libtest/lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/libtest/lib.rs b/src/libtest/lib.rs index 793483754eebf..10a969afbdfd5 100644 --- a/src/libtest/lib.rs +++ b/src/libtest/lib.rs @@ -886,8 +886,8 @@ pub fn run_test(opts: &TestOpts, if nocapture { drop((stdout, stderr)); } else { - cfg = cfg.stdout(box stdout as Box); - cfg = cfg.stderr(box stderr as Box); + cfg = cfg.stdout(Box::new(stdout) as Box); + cfg = cfg.stderr(Box::new(stderr) as Box); } let result_guard = cfg.scoped(move || { testfn.invoke(()) }); From 1aac55a3663795fc7b1ecd9858a2adf6a529d8a1 Mon Sep 17 00:00:00 2001 From: "Felix S. Klock II" Date: Fri, 6 Feb 2015 15:26:04 +0100 Subject: [PATCH 09/10] fallout from box protocol changes in librustdoc crate. --- src/librustdoc/test.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/librustdoc/test.rs b/src/librustdoc/test.rs index 7f1bd9e6d5965..2763ee0a13595 100644 --- a/src/librustdoc/test.rs +++ b/src/librustdoc/test.rs @@ -147,7 +147,7 @@ fn runtest(test: &str, cratename: &str, libs: SearchPaths, let (tx, rx) = channel(); let w1 = io::ChanWriter::new(tx); let w2 = w1.clone(); - let old = io::stdio::set_stderr(box w1); + let old = io::stdio::set_stderr(Box::new(w1)); Thread::spawn(move |:| { let mut p = io::ChanReader::new(rx); let mut err = match old { @@ -156,15 +156,15 @@ fn runtest(test: &str, cratename: &str, libs: SearchPaths, let old: Box = old; old } - None => box io::stderr() as Box, + None => Box::new(io::stderr()) as Box, }; io::util::copy(&mut p, &mut err).unwrap(); }); - let emitter = diagnostic::EmitterWriter::new(box w2, None); + let emitter = diagnostic::EmitterWriter::new(Box::new(w2), None); // Compile the code let codemap = CodeMap::new(); - let diagnostic_handler = diagnostic::mk_handler(box emitter); + let diagnostic_handler = diagnostic::mk_handler(Box::new(emitter)); let span_diagnostic_handler = diagnostic::mk_span_handler(diagnostic_handler, codemap); From 74191c8bef0f4152e5e1c33311283034a062c7bc Mon Sep 17 00:00:00 2001 From: "Felix S. Klock II" Date: Fri, 6 Feb 2015 15:26:29 +0100 Subject: [PATCH 10/10] fallout from box protocol changes in `rustbook`. --- src/rustbook/build.rs | 6 +++--- src/rustbook/error.rs | 2 +- src/rustbook/help.rs | 2 +- src/rustbook/serve.rs | 2 +- src/rustbook/term.rs | 2 +- src/rustbook/test.rs | 8 ++++---- 6 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/rustbook/build.rs b/src/rustbook/build.rs index 93601c0f61bf4..0eef57bca88d1 100644 --- a/src/rustbook/build.rs +++ b/src/rustbook/build.rs @@ -28,7 +28,7 @@ struct Build; pub fn parse_cmd(name: &str) -> Option> { if name == "build" { - Some(box Build as Box) + Some(Box::new(Build) as Box) } else { None } @@ -134,7 +134,7 @@ fn render(book: &Book, tgt: &Path) -> CliResult<()> { if output_result != 0 { let message = format!("Could not execute `rustdoc` with {:?}: {}", rustdoc_args, output_result); - return Err(box message as Box); + return Err(Box::new(message) as Box); } } @@ -181,7 +181,7 @@ impl Subcommand for Build { term.err(&format!("error: {}", err)[]); } - Err(box format!("{} errors occurred", n) as Box) + Err(Box::new(format!("{} errors occurred", n)) as Box) } } } diff --git a/src/rustbook/error.rs b/src/rustbook/error.rs index 7d5e7efcc9459..a5ce5828806e7 100644 --- a/src/rustbook/error.rs +++ b/src/rustbook/error.rs @@ -40,7 +40,7 @@ impl Show for Box { impl FromError for Box { fn from_err(err: E) -> Box { - box err as Box + Box::new(err) as Box } } diff --git a/src/rustbook/help.rs b/src/rustbook/help.rs index 7fd8214f7311a..a6537b623c108 100644 --- a/src/rustbook/help.rs +++ b/src/rustbook/help.rs @@ -19,7 +19,7 @@ struct Help; pub fn parse_cmd(name: &str) -> Option> { match name { - "help" | "--help" | "-h" | "-?" => Some(box Help as Box), + "help" | "--help" | "-h" | "-?" => Some(Box::new(Help) as Box), _ => None } } diff --git a/src/rustbook/serve.rs b/src/rustbook/serve.rs index 808527dcef95e..b8fc902dc7f32 100644 --- a/src/rustbook/serve.rs +++ b/src/rustbook/serve.rs @@ -19,7 +19,7 @@ struct Serve; pub fn parse_cmd(name: &str) -> Option> { if name == "serve" { - Some(box Serve as Box) + Some(Box::new(Serve) as Box) } else { None } diff --git a/src/rustbook/term.rs b/src/rustbook/term.rs index 471e22ce7c1f1..bbf0c7660e69d 100644 --- a/src/rustbook/term.rs +++ b/src/rustbook/term.rs @@ -21,7 +21,7 @@ pub struct Term { impl Term { pub fn new() -> Term { Term { - err: box stdio::stderr() as Box, + err: Box::new(stdio::stderr()) as Box, } } diff --git a/src/rustbook/test.rs b/src/rustbook/test.rs index f2bf92585f7ea..68ca0db5b29b8 100644 --- a/src/rustbook/test.rs +++ b/src/rustbook/test.rs @@ -23,7 +23,7 @@ struct Test; pub fn parse_cmd(name: &str) -> Option> { if name == "test" { - Some(box Test as Box) + Some(Box::new(Test) as Box) } else { None } @@ -52,13 +52,13 @@ impl Subcommand for Test { term.err(&format!("{}\n{}", String::from_utf8_lossy(&output.output[]), String::from_utf8_lossy(&output.error[]))[]); - return Err(box "Some tests failed." as Box); + return Err(Box::new("Some tests failed.") as Box); } } Err(e) => { let message = format!("Could not execute `rustdoc`: {}", e); - return Err(box message as Box); + return Err(Box::new(message) as Box); } } } @@ -67,7 +67,7 @@ impl Subcommand for Test { for err in errors.into_iter() { term.err(&err[]); } - return Err(box "There was an error." as Box); + return Err(Box::new("There was an error.") as Box); } } Ok(()) // lol