Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Clone implementations for managed and managed mutable types. #5750

Closed
wants to merge 54 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
54 commits
Select commit Hold shift + click to select a range
2b07f0f
field renaming
jbclements Mar 12, 2013
556143c
commenting parser
jbclements Mar 8, 2013
f2e47cd
change to parsing using tts
jbclements Mar 6, 2013
a20d1ad
Improve documentation for core::io.
steveklabnik Apr 1, 2013
1d658d9
Improve docs for Core::ReaderUtil.
steveklabnik Apr 2, 2013
948ff60
Typo fix. u8 -> i8
steveklabnik Apr 2, 2013
88e4b5d
install the librust{doc,pkg} host libraries
thestinger Apr 2, 2013
86d5ce5
remove trailing whitespace
steveklabnik Apr 3, 2013
a3e2d6e
Remove excess trailing whitespace.
steveklabnik Apr 3, 2013
e4edfa0
libstd: implement fileinput.
huonw Feb 23, 2013
1e28d8f
libstd: implement io::Reader for fileinput.
huonw Mar 25, 2013
f357a03
auto merge of #5685 : thestinger/rust/build, r=graydon
bors Apr 3, 2013
fea1380
libstd: make fileinput tests pass.
huonw Apr 3, 2013
cb16cd9
auto merge of #5673 : steveklabnik/rust/improve_io_docs, r=catamorphism
bors Apr 3, 2013
26d8b51
auto merge of #5674 : steveklabnik/rust/improve_reader_util_docs, r=c…
bors Apr 3, 2013
0cc9030
auto merge of #5202 : dbaupp/rust/std-fileinput, r=graydon
bors Apr 3, 2013
e2bffb7
Implement Clone for tuples
Apr 3, 2013
afd5cba
auto merge of #5692 : Aatch/rust/tuple-clone, r=thestinger
bors Apr 3, 2013
84e5033
Make bench/noise.rs more idiomatic and 20x faster
bstrie Apr 3, 2013
260d74d
auto merge of #5695 : bstrie/rust/noise, r=thestinger
bors Apr 3, 2013
44029a5
hashmap: rm linear namespace
thestinger Apr 3, 2013
cc148b5
rename Linear{Map,Set} => Hash{Map,Set}
thestinger Apr 3, 2013
c16919d
Removing mut fields from vec.rs, at_vec.rs, str.rs, unstable.rs, and …
Thiez Apr 2, 2013
397a478
Unstable didn't need transmute_mut after all.
Thiez Apr 3, 2013
c4d2b79
Add Clone derivation for std::net::url types.
metajack Apr 3, 2013
6153aae
auto merge of #5559 : jbclements/rust/change-to-tt-based-parsing, r=j…
bors Apr 3, 2013
d79b224
Add information about logging macros to the tutorial.
steveklabnik Apr 3, 2013
34b2336
Fix compiletest on windows
brson Apr 3, 2013
3044f5e
typo fix: na -> an
steveklabnik Apr 3, 2013
5b933ae
auto merge of #5696 : thestinger/rust/hashmap, r=sanxiyn
bors Apr 3, 2013
8dd5a70
Update tut. to not sound like I missed a section
brettcannon Apr 3, 2013
17ab718
auto merge of #5698 : Thiez/rust/de-mutfielding, r=pcwalton
bors Apr 3, 2013
84c296b
auto merge of #5701 : metajack/rust/net-url-clone, r=thestinger
bors Apr 3, 2013
a7f0bfb
One more typo: dubug -> debug
steveklabnik Apr 3, 2013
e2c7a4d
Simple typo fix
ajuckel Apr 4, 2013
783392f
auto merge of #5704 : brson/rust/compiletest, r=luqmana
bors Apr 4, 2013
f064048
Remove a android hack
ILyoan Apr 3, 2013
fac0d9d
Decides main name by target
ILyoan Apr 3, 2013
53232f7
Fix fileinput test fail
ILyoan Apr 4, 2013
af1baa3
auto merge of #5691 : ILyoan/rust/main_name, r=thestinger
bors Apr 4, 2013
aa899c9
auto merge of #5710 : ajuckel/rust/patch-1, r=luqmana
bors Apr 4, 2013
679b1dc
doc: Rewrite task tutorial intro
brson Apr 4, 2013
21de574
auto merge of #5703 : steveklabnik/rust/add_log_docs, r=thestinger
bors Apr 4, 2013
1dc330c
auto merge of #5707 : brettcannon/rust/patch-1, r=thestinger
bors Apr 4, 2013
b5d8224
auto merge of #5713 : brson/rust/tutorial2, r=thestinger
bors Apr 4, 2013
99b156e
mk: mips toolchain config
crabtw Mar 19, 2013
fdf48a7
rt: improve mips backend
crabtw Mar 19, 2013
4f1d8cb
fix mac build and comment on stack size check
crabtw Mar 29, 2013
cb91e91
Tutorial: rename variable to avoid confusion.
Apr 4, 2013
717ed51
auto merge of #5716 : dhardy/rust/master, r=thestinger
bors Apr 4, 2013
2c02aab
Add cell#with_mut_ref for handling mutable references to the content.
metajack Apr 4, 2013
c08fb75
auto merge of #5431 : crabtw/rust/mips-rt, r=brson
bors Apr 4, 2013
babe506
auto merge of #5722 : metajack/rust/cell-with-ref-mut, r=catamorphism
bors Apr 5, 2013
b22a060
Implement Clone for @ and @mut types.
metajack Apr 5, 2013
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 24 additions & 2 deletions doc/rust.md
Original file line number Diff line number Diff line change
Expand Up @@ -441,10 +441,10 @@ expression context, the final namespace qualifier is omitted.
Two examples of paths with type arguments:

~~~~
# use core::hashmap::linear::LinearMap;
# use core::hashmap::HashMap;
# fn f() {
# fn id<T:Copy>(t: T) -> T { t }
type t = LinearMap<int,~str>; // Type arguments used in a type expression
type t = HashMap<int,~str>; // Type arguments used in a type expression
let x = id::<int>(10); // Type arguments used in a call expression
# }
~~~~
Expand Down Expand Up @@ -3251,6 +3251,28 @@ of runtime logging modules follows.
* `::rt::backtrace` Log a backtrace on task failure
* `::rt::callback` Unused

#### Logging Expressions

Rust provides several macros to log information. Here's a simple Rust program
that demonstrates all four of them:

```rust
fn main() {
error!("This is an error log")
warn!("This is a warn log")
info!("this is an info log")
debug!("This is a debug log")
}
```

These four log levels correspond to levels 1-4, as controlled by `RUST_LOG`:

```bash
$ RUST_LOG=rust=3 ./rust
rust: ~"\"This is an error log\""
rust: ~"\"This is a warn log\""
rust: ~"\"this is an info log\""
```

# Appendix: Rationales and design tradeoffs

Expand Down
67 changes: 28 additions & 39 deletions doc/tutorial-tasks.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,74 +2,63 @@

# Introduction

The designers of Rust designed the language from the ground up to support pervasive
and safe concurrency through lightweight, memory-isolated tasks and
message passing.

Rust tasks are not the same as traditional threads: rather, they are more like
_green threads_. The Rust runtime system schedules tasks cooperatively onto a
small number of operating system threads. Because tasks are significantly
Rust provides safe concurrency through a combination
of lightweight, memory-isolated tasks and message passing.
This tutorial will describe the concurrency model in Rust, how it
relates to the Rust type system, and introduce
the fundamental library abstractions for constructing concurrent programs.

Rust tasks are not the same as traditional threads: rather,
they are considered _green threads_, lightweight units of execution that the Rust
runtime schedules cooperatively onto a small number of operating system threads.
On a multi-core system Rust tasks will be scheduled in parallel by default.
Because tasks are significantly
cheaper to create than traditional threads, Rust can create hundreds of
thousands of concurrent tasks on a typical 32-bit system.
In general, all Rust code executes inside a task, including the `main` function.

In order to make efficient use of memory Rust tasks have dynamically sized stacks.
A task begins its life with a small
amount of stack space (currently in the low thousands of bytes, depending on
platform), and acquires more stack as needed.
Unlike in languages such as C, a Rust task cannot accidentally write to
memory beyond the end of the stack, causing crashes or worse.

Tasks provide failure isolation and recovery. When an exception occurs in Rust
code (as a result of an explicit call to `fail!()`, an assertion failure, or
another invalid operation), the runtime system destroys the entire
Tasks provide failure isolation and recovery. When a fatal error occurs in Rust
code as a result of an explicit call to `fail!()`, an assertion failure, or
another invalid operation, the runtime system destroys the entire
task. Unlike in languages such as Java and C++, there is no way to `catch` an
exception. Instead, tasks may monitor each other for failure.

Rust tasks have dynamically sized stacks. A task begins its life with a small
amount of stack space (currently in the low thousands of bytes, depending on
platform), and acquires more stack as needed. Unlike in languages such as C, a
Rust task cannot run off the end of the stack. However, tasks do have a stack
budget. If a Rust task exceeds its stack budget, then it will fail safely:
with a checked exception.

Tasks use Rust's type system to provide strong memory safety guarantees. In
particular, the type system guarantees that tasks cannot share mutable state
with each other. Tasks communicate with each other by transferring _owned_
data through the global _exchange heap_.

This tutorial explains the basics of tasks and communication in Rust,
explores some typical patterns in concurrent Rust code, and finally
discusses some of the more unusual synchronization types in the standard
library.

> ***Warning:*** This tutorial is incomplete

## A note about the libraries

While Rust's type system provides the building blocks needed for safe
and efficient tasks, all of the task functionality itself is implemented
in the core and standard libraries, which are still under development
and do not always present a consistent interface.

In particular, there are currently two independent modules that provide a
message passing interface to Rust code: `core::comm` and `core::pipes`.
`core::comm` is an older, less efficient system that is being phased out in
favor of `pipes`. At some point, we will remove the existing `core::comm` API
and move the user-facing portions of `core::pipes` to `core::comm`. In this
tutorial, we discuss `pipes` and ignore the `comm` API.
and do not always present a consistent or complete interface.

For your reference, these are the standard modules involved in Rust
concurrency at this writing.

* [`core::task`] - All code relating to tasks and task scheduling
* [`core::comm`] - The deprecated message passing API
* [`core::pipes`] - The new message passing infrastructure and API
* [`std::comm`] - Higher level messaging types based on `core::pipes`
* [`core::comm`] - The message passing interface
* [`core::pipes`] - The underlying messaging infrastructure
* [`std::comm`] - Additional messaging types based on `core::pipes`
* [`std::sync`] - More exotic synchronization tools, including locks
* [`std::arc`] - The ARC (atomic reference counted) type, for safely sharing
immutable data
* [`std::par`] - Some basic tools for implementing parallel algorithms
* [`std::arc`] - The ARC (atomically reference counted) type,
for safely sharing immutable data

[`core::task`]: core/task.html
[`core::comm`]: core/comm.html
[`core::pipes`]: core/pipes.html
[`std::comm`]: std/comm.html
[`std::sync`]: std/sync.html
[`std::arc`]: std/arc.html
[`std::par`]: std/par.html

# Basics

Expand Down
10 changes: 5 additions & 5 deletions doc/tutorial.md
Original file line number Diff line number Diff line change
Expand Up @@ -495,7 +495,7 @@ omitted.

A powerful application of pattern matching is *destructuring*:
matching in order to bind names to the contents of data
types. Remember that `(float, float)` is a tuple of two floats:
types. Assuming that `(float, float)` is a tuple of two floats:

~~~~
fn angle(vector: (float, float)) -> float {
Expand Down Expand Up @@ -988,7 +988,7 @@ custom destructors.

# Boxes

Many modern languages represent values as as pointers to heap memory by
Many modern languages represent values as pointers to heap memory by
default. In contrast, Rust, like C and C++, represents such types directly.
Another way to say this is that aggregate data in Rust are *unboxed*. This
means that if you `let x = Point { x: 1f, y: 1f };`, you are creating a struct
Expand Down Expand Up @@ -1191,7 +1191,7 @@ they are frozen:
let x = @mut 5;
let y = x;
{
let y = &*y; // the managed box is now frozen
let z = &*y; // the managed box is now frozen
// modifying it through x or y will cause a task failure
}
// the box is now unfrozen again
Expand Down Expand Up @@ -1888,8 +1888,8 @@ illegal to copy and pass by value.
Generic `type`, `struct`, and `enum` declarations follow the same pattern:

~~~~
# use core::hashmap::linear::LinearMap;
type Set<T> = LinearMap<T, ()>;
# use core::hashmap::HashMap;
type Set<T> = HashMap<T, ()>;

struct Stack<T> {
elements: ~[T]
Expand Down
2 changes: 2 additions & 0 deletions mk/install.mk
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,8 @@ install-host: $(CSREQ$(ISTAGE)_T_$(CFG_BUILD_TRIPLE)_H_$(CFG_BUILD_TRIPLE))
$(Q)$(call INSTALL_LIB,$(HL),$(PHL),$(LIBSYNTAX_GLOB_$(CFG_BUILD_TRIPLE)))
$(Q)$(call INSTALL_LIB,$(HL),$(PHL),$(LIBRUSTI_GLOB_$(CFG_BUILD_TRIPLE)))
$(Q)$(call INSTALL_LIB,$(HL),$(PHL),$(LIBRUST_GLOB_$(CFG_BUILD_TRIPLE)))
$(Q)$(call INSTALL_LIB,$(HL),$(PHL),$(LIBRUSTPKG_GLOB_$(CFG_BUILD_TRIPLE)))
$(Q)$(call INSTALL_LIB,$(HL),$(PHL),$(LIBRUSTDOC_GLOB_$(CFG_BUILD_TRIPLE)))
$(Q)$(call INSTALL,$(HL),$(PHL),$(CFG_RUNTIME_$(CFG_BUILD_TRIPLE)))
$(Q)$(call INSTALL,$(HL),$(PHL),$(CFG_RUSTLLVM_$(CFG_BUILD_TRIPLE)))
$(Q)$(call INSTALL,$(S)/man, \
Expand Down
25 changes: 25 additions & 0 deletions mk/platform.mk
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,31 @@ CFG_RUN_arm-linux-androideabi=
CFG_RUN_TARG_arm-linux-androideabi=
RUSTC_FLAGS_arm-linux-androideabi :=--android-cross-path=$(CFG_ANDROID_CROSS_PATH)

# mips-unknown-linux-gnu configuration
CC_mips-unknown-linux-gnu=mips-linux-gnu-gcc
CXX_mips-unknown-linux-gnu=mips-linux-gnu-g++
CPP_mips-unknown-linux-gnu=mips-linux-gnu-gcc -E
AR_mips-unknown-linux-gnu=mips-linux-gnu-ar
CFG_LIB_NAME_mips-unknown-linux-gnu=lib$(1).so
CFG_LIB_GLOB_mips-unknown-linux-gnu=lib$(1)-*.so
CFG_LIB_DSYM_GLOB_mips-unknown-linux-gnu=lib$(1)-*.dylib.dSYM
CFG_GCCISH_CFLAGS_mips-unknown-linux-gnu := -Wall -g -fPIC -mips32r2 -msoft-float -mabi=32
CFG_GCCISH_CXXFLAGS_mips-unknown-linux-gnu := -fno-rtti
CFG_GCCISH_LINK_FLAGS_mips-unknown-linux-gnu := -shared -fPIC -g -mips32r2 -msoft-float -mabi=32
CFG_GCCISH_DEF_FLAG_mips-unknown-linux-gnu := -Wl,--export-dynamic,--dynamic-list=
CFG_GCCISH_PRE_LIB_FLAGS_mips-unknown-linux-gnu := -Wl,-whole-archive
CFG_GCCISH_POST_LIB_FLAGS_mips-unknown-linux-gnu := -Wl,-no-whole-archive -Wl,-znoexecstack
CFG_DEF_SUFFIX_mips-unknown-linux-gnu := .linux.def
CFG_INSTALL_NAME_mips-unknown-linux-gnu =
CFG_LIBUV_LINK_FLAGS_mips-unknown-linux-gnu =
CFG_EXE_SUFFIX_mips-unknown-linux-gnu :=
CFG_WINDOWSY_mips-unknown-linux-gnu :=
CFG_UNIXY_mips-unknown-linux-gnu := 1
CFG_PATH_MUNGE_mips-unknown-linux-gnu := true
CFG_LDPATH_mips-unknown-linux-gnu :=
CFG_RUN_mips-unknown-linux-gnu=
CFG_RUN_TARG_mips-unknown-linux-gnu=

# i686-pc-mingw32 configuration
CC_i686-pc-mingw32=$(CC)
CXX_i686-pc-mingw32=$(CXX)
Expand Down
5 changes: 5 additions & 0 deletions mk/rt.mk
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
LIBUV_FLAGS_i386 = -m32 -fPIC
LIBUV_FLAGS_x86_64 = -m64 -fPIC
LIBUV_FLAGS_arm = -fPIC -DANDROID -std=gnu99
LIBUV_FLAGS_mips = -fPIC -mips32r2 -msoft-float -mabi=32

# when we're doing a snapshot build, we intentionally degrade as many
# features in libuv and the runtime as possible, to ease portability.
Expand Down Expand Up @@ -180,6 +181,10 @@ else
$$(LIBUV_LIB_$(1)): $$(LIBUV_DEPS)
$$(Q)$$(MAKE) -C $$(S)src/libuv/ \
CFLAGS="$$(LIBUV_FLAGS_$$(HOST_$(1))) $$(SNAP_DEFINES)" \
LDFLAGS="$$(LIBUV_FLAGS_$$(HOST_$(1)))" \
CC="$$(CC_$(1))" \
CXX="$$(CXX_$(1))" \
AR="$$(AR_$(1))" \
builddir_name="$$(CFG_BUILD_DIR)/rt/$(1)/libuv" \
V=$$(VERBOSE)
endif
Expand Down
2 changes: 1 addition & 1 deletion src/compiletest/procsrv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ fn target_env(lib_path: ~str, prog: ~str) -> ~[(~str,~str)] {

// Make sure we include the aux directory in the path
assert!(prog.ends_with(~".exe"));
let aux_path = prog.slice(0u, prog.len() - 4u) + ~".libaux";
let aux_path = prog.slice(0u, prog.len() - 4u).to_owned() + ~".libaux";

env = do vec::map(env) |pair| {
let (k,v) = *pair;
Expand Down
4 changes: 2 additions & 2 deletions src/libcore/at_vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ pub mod raw {
*/
#[inline(always)]
pub unsafe fn set_len<T>(v: @[T], new_len: uint) {
let repr: **VecRepr = ::cast::reinterpret_cast(&addr_of(&v));
let repr: **mut VecRepr = ::cast::reinterpret_cast(&addr_of(&v));
(**repr).unboxed.fill = new_len * sys::size_of::<T>();
}

Expand All @@ -226,7 +226,7 @@ pub mod raw {

#[inline(always)] // really pretty please
pub unsafe fn push_fast<T>(v: &mut @[T], initval: T) {
let repr: **VecRepr = ::cast::reinterpret_cast(&v);
let repr: **mut VecRepr = ::cast::reinterpret_cast(&v);
let fill = (**repr).unboxed.fill;
(**repr).unboxed.fill += sys::size_of::<T>();
let p = addr_of(&((**repr).unboxed.data));
Expand Down
38 changes: 31 additions & 7 deletions src/libcore/cell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

//! A mutable, nullable memory location

use cast::transmute;
use cast::transmute_mut;
use prelude::*;

/*
Expand All @@ -20,16 +20,12 @@ Similar to a mutable option type, but friendlier.
*/

pub struct Cell<T> {
mut value: Option<T>
value: Option<T>
}

impl<T:cmp::Eq> cmp::Eq for Cell<T> {
fn eq(&self, other: &Cell<T>) -> bool {
unsafe {
let frozen_self: &Option<T> = transmute(&mut self.value);
let frozen_other: &Option<T> = transmute(&mut other.value);
frozen_self == frozen_other
}
(self.value) == (other.value)
}
fn ne(&self, other: &Cell<T>) -> bool { !self.eq(other) }
}
Expand All @@ -46,6 +42,7 @@ pub fn empty_cell<T>() -> Cell<T> {
pub impl<T> Cell<T> {
/// Yields the value, failing if the cell is empty.
fn take(&self) -> T {
let mut self = unsafe { transmute_mut(self) };
if self.is_empty() {
fail!(~"attempt to take an empty cell");
}
Expand All @@ -57,6 +54,7 @@ pub impl<T> Cell<T> {

/// Returns the value, failing if the cell is full.
fn put_back(&self, value: T) {
let mut self = unsafe { transmute_mut(self) };
if !self.is_empty() {
fail!(~"attempt to put a value back into a full cell");
}
Expand All @@ -75,6 +73,14 @@ pub impl<T> Cell<T> {
self.put_back(v);
r
}

// Calls a closure with a mutable reference to the value.
fn with_mut_ref<R>(&self, op: &fn(v: &mut T) -> R) -> R {
let mut v = self.take();
let r = op(&mut v);
self.put_back(v);
r
}
}

#[test]
Expand Down Expand Up @@ -103,3 +109,21 @@ fn test_put_back_non_empty() {
let value_cell = Cell(~10);
value_cell.put_back(~20);
}

#[test]
fn test_with_ref() {
let good = 6;
let c = Cell(~[1, 2, 3, 4, 5, 6]);
let l = do c.with_ref() |v| { v.len() };
assert!(l == good);
}

#[test]
fn test_with_mut_ref() {
let good = ~[1, 2, 3];
let mut v = ~[1, 2];
let c = Cell(v);
do c.with_mut_ref() |v| { v.push(3); }
let v = c.take();
assert!(v == good);
}
10 changes: 10 additions & 0 deletions src/libcore/clone.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,16 @@ impl<T:Clone> Clone for ~T {
fn clone(&self) -> ~T { ~(**self).clone() }
}

impl<T:Clone> Clone for @T {
#[inline(always)]
fn clone(&self) -> @T { @(**self).clone() }
}

impl<T:Clone> Clone for @mut T {
#[inline(always)]
fn clone(&self) -> @mut T { @mut (**self).clone() }
}

macro_rules! clone_impl(
($t:ty) => {
impl Clone for $t {
Expand Down
4 changes: 2 additions & 2 deletions src/libcore/gc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ use io;
use libc::{size_t, uintptr_t};
use option::{None, Option, Some};
use ptr;
use hashmap::linear::LinearSet;
use hashmap::HashSet;
use stackwalk;
use sys;

Expand Down Expand Up @@ -344,7 +344,7 @@ pub fn cleanup_stack_for_failure() {
ptr::null()
};

let mut roots = LinearSet::new();
let mut roots = HashSet::new();
for walk_gc_roots(need_cleanup, sentinel) |root, tydesc| {
// Track roots to avoid double frees.
if roots.contains(&*root) {
Expand Down
Loading