1
Fork 0

libsyntax: Remove fn() unsafe { ... }. r=graydon

This commit is contained in:
Patrick Walton 2013-01-23 11:43:58 -08:00
parent 1d1b81143b
commit 54b2cad8b3
59 changed files with 2807 additions and 2425 deletions

View file

@ -33,7 +33,8 @@ fn load_errors(testfile: &Path) -> ~[expected_error] {
return error_patterns;
}
fn parse_expected(line_num: uint, line: ~str) -> ~[expected_error] unsafe {
fn parse_expected(line_num: uint, line: ~str) -> ~[expected_error] {
unsafe {
let error_tag = ~"//~";
let mut idx;
match str::find_str(line, error_tag) {
@ -64,3 +65,4 @@ fn parse_expected(line_num: uint, line: ~str) -> ~[expected_error] unsafe {
return ~[{line: line_num - adjust_line, kind: kind, msg: msg}];
}
}

View file

@ -146,7 +146,8 @@ fn parse_name_directive(line: ~str, directive: ~str) -> bool {
}
fn parse_name_value_directive(line: ~str,
directive: ~str) -> Option<~str> unsafe {
directive: ~str) -> Option<~str> {
unsafe {
let keycolon = directive + ~":";
match str::find_str(line, keycolon) {
Some(colon) => {
@ -158,3 +159,4 @@ fn parse_name_value_directive(line: ~str,
None => None
}
}
}

View file

@ -1135,7 +1135,8 @@ fn get_temp_workdir(c: &Cargo) -> Path {
}
}
fn cmd_install(c: &Cargo) unsafe {
fn cmd_install(c: &Cargo) {
unsafe {
let wd = get_temp_workdir(c);
if vec::len(c.opts.free) == 2u {
@ -1158,6 +1159,7 @@ fn cmd_install(c: &Cargo) unsafe {
install_query(c, &wd, query);
}
}
fn sync(c: &Cargo) {
for c.sources.each_key |k| {

View file

@ -122,7 +122,8 @@ pub fn listen<T: Owned, U>(f: fn(Chan<T>) -> U) -> U {
struct PortPtr<T:Owned> {
po: *rust_port,
drop unsafe {
drop {
unsafe {
do task::unkillable {
// Once the port is detached it's guaranteed not to receive further
// messages
@ -143,6 +144,7 @@ struct PortPtr<T:Owned> {
}
}
}
}
fn PortPtr<T: Owned>(po: *rust_port) -> PortPtr<T> {
PortPtr {
@ -209,7 +211,7 @@ pub fn send<T: Owned>(ch: Chan<T>, data: T) {
let Chan_(p) = ch;
let data_ptr = ptr::addr_of(&data) as *();
let res = rustrt::rust_port_id_send(p, data_ptr);
if res != 0 unsafe {
if res != 0 {
// Data sent successfully
cast::forget(move data);
}

View file

@ -86,8 +86,10 @@ pub fn fill_charp_buf(f: fn(*mut c_char, size_t) -> bool)
-> Option<~str> {
let buf = vec::cast_to_mut(vec::from_elem(tmpbuf_sz, 0u8 as c_char));
do vec::as_mut_buf(buf) |b, sz| {
if f(b, sz as size_t) unsafe {
if f(b, sz as size_t) {
unsafe {
Some(str::raw::from_buf(b as *u8))
}
} else {
None
}

View file

@ -193,10 +193,12 @@ impl PacketHeader {
reinterpret_cast(&self.buffer)
}
fn set_buffer<T: Owned>(b: ~Buffer<T>) unsafe {
fn set_buffer<T: Owned>(b: ~Buffer<T>) {
unsafe {
self.buffer = reinterpret_cast(&b);
}
}
}
#[doc(hidden)]
pub type Packet<T: Owned> = {
@ -356,7 +358,8 @@ pub unsafe fn get_buffer<T: Owned>(p: *PacketHeader) -> ~Buffer<T> {
struct BufferResource<T: Owned> {
buffer: ~Buffer<T>,
drop unsafe {
drop {
unsafe {
let b = move_it!(self.buffer);
//let p = ptr::addr_of(*b);
//error!("drop %?", p);
@ -372,6 +375,7 @@ struct BufferResource<T: Owned> {
}
}
}
}
fn BufferResource<T: Owned>(b: ~Buffer<T>) -> BufferResource<T> {
//let p = ptr::addr_of(*b);
@ -641,8 +645,9 @@ fn wait_many<T: Selectable>(pkts: &[T]) -> uint {
let mut data_avail = false;
let mut ready_packet = pkts.len();
for pkts.eachi |i, p| unsafe {
let p = unsafe { &*p.header() };
for pkts.eachi |i, p| {
unsafe {
let p = &*p.header();
let old = p.mark_blocked(this);
match old {
Full | Terminated => {
@ -655,6 +660,7 @@ fn wait_many<T: Selectable>(pkts: &[T]) -> uint {
Empty => ()
}
}
}
while !data_avail {
debug!("sleeping on %? packets", pkts.len());
@ -1072,7 +1078,8 @@ impl<T: Owned> Port<T>: GenericPort<T> {
}
impl<T: Owned> Port<T>: Peekable<T> {
pure fn peek() -> bool unsafe {
pure fn peek() -> bool {
unsafe {
let mut endp = None;
endp <-> self.endp;
let peek = match &endp {
@ -1083,15 +1090,18 @@ impl<T: Owned> Port<T>: Peekable<T> {
peek
}
}
}
impl<T: Owned> Port<T>: Selectable {
pure fn header() -> *PacketHeader unsafe {
pure fn header() -> *PacketHeader {
unsafe {
match self.endp {
Some(ref endp) => endp.header(),
None => fail ~"peeking empty stream"
}
}
}
}
/// Treat many ports as one.
pub struct PortSet<T: Owned> {

View file

@ -64,7 +64,8 @@ pub unsafe fn run_in_bare_thread(f: ~fn()) {
let (port, chan) = pipes::stream();
// FIXME #4525: Unfortunate that this creates an extra scheduler but it's
// necessary since rust_raw_thread_join_delete is blocking
do task::spawn_sched(task::SingleThreaded) unsafe {
do task::spawn_sched(task::SingleThreaded) {
unsafe {
let closure: &fn() = || {
f()
};
@ -72,16 +73,19 @@ pub unsafe fn run_in_bare_thread(f: ~fn()) {
rustrt::rust_raw_thread_join_delete(thread);
chan.send(());
}
}
port.recv();
}
#[test]
fn test_run_in_bare_thread() unsafe {
fn test_run_in_bare_thread() {
unsafe {
let i = 100;
do run_in_bare_thread {
assert i == 100;
}
}
}
#[allow(non_camel_case_types)] // runtime type
type rust_port_id = uint;
@ -273,10 +277,12 @@ pub unsafe fn weaken_task(f: fn(oldcomm::Port<()>)) {
struct Unweaken {
ch: oldcomm::Chan<()>,
drop unsafe {
drop {
unsafe {
rustrt::rust_task_unweaken(cast::reinterpret_cast(&self.ch));
}
}
}
fn Unweaken(ch: oldcomm::Chan<()>) -> Unweaken {
Unweaken {
@ -359,7 +365,8 @@ struct ArcData<T> {
struct ArcDestruct<T> {
mut data: *libc::c_void,
drop unsafe {
drop {
unsafe {
if self.data.is_null() {
return; // Happens when destructing an unwrapper's handle.
}
@ -368,10 +375,11 @@ struct ArcDestruct<T> {
let new_count = rusti::atomic_xsub(&mut data.count, 1) - 1;
assert new_count >= 0;
if new_count == 0 {
// Were we really last, or should we hand off to an unwrapper?
// It's safe to not xchg because the unwrapper will set the
// unwrap lock *before* dropping his/her reference. In effect,
// being here means we're the only *awake* task with the data.
// Were we really last, or should we hand off to an
// unwrapper? It's safe to not xchg because the unwrapper
// will set the unwrap lock *before* dropping his/her
// reference. In effect, being here means we're the only
// *awake* task with the data.
if data.unwrapper != 0 {
let p: UnwrapProto =
cast::reinterpret_cast(&data.unwrapper);
@ -394,6 +402,7 @@ struct ArcDestruct<T> {
}
}
}
}
fn ArcDestruct<T>(data: *libc::c_void) -> ArcDestruct<T> {
ArcDestruct {
@ -406,14 +415,16 @@ pub unsafe fn unwrap_shared_mutable_state<T: Owned>(rc: SharedMutableState<T>)
struct DeathThroes<T> {
mut ptr: Option<~ArcData<T>>,
mut response: Option<pipes::ChanOne<bool>>,
drop unsafe {
drop {
unsafe {
let response = option::swap_unwrap(&mut self.response);
// In case we get killed early, we need to tell the person who
// tried to wake us whether they should hand-off the data to us.
// tried to wake us whether they should hand-off the data to
// us.
if task::failing() {
pipes::send_one(move response, false);
// Either this swap_unwrap or the one below (at "Got here")
// ought to run.
// Either this swap_unwrap or the one below (at "Got
// here") ought to run.
cast::forget(option::swap_unwrap(&mut self.ptr));
} else {
assert self.ptr.is_none();
@ -421,6 +432,7 @@ pub unsafe fn unwrap_shared_mutable_state<T: Owned>(rc: SharedMutableState<T>)
}
}
}
}
do task::unkillable {
let ptr: ~ArcData<T> = cast::reinterpret_cast(&rc.data);

View file

@ -165,9 +165,11 @@ pub pure fn to_mut_unsafe_ptr<T>(thing: &mut T) -> *mut T {
(I couldn't think of a cutesy name for this one.)
*/
#[inline(always)]
pub pure fn to_uint<T>(thing: &T) -> uint unsafe {
pub pure fn to_uint<T>(thing: &T) -> uint {
unsafe {
cast::reinterpret_cast(&thing)
}
}
/// Determine if two borrowed pointers point to the same thing.
#[inline(always)]
@ -215,11 +217,13 @@ impl<T> *mut T: Ptr<T> {
#[cfg(notest)]
impl<T> *const T : Eq {
#[inline(always)]
pure fn eq(&self, other: &*const T) -> bool unsafe {
pure fn eq(&self, other: &*const T) -> bool {
unsafe {
let a: uint = cast::reinterpret_cast(&(*self));
let b: uint = cast::reinterpret_cast(&(*other));
return a == b;
}
}
#[inline(always)]
pure fn ne(&self, other: &*const T) -> bool { !(*self).eq(other) }
}
@ -228,30 +232,38 @@ impl<T> *const T : Eq {
#[cfg(notest)]
impl<T> *const T : Ord {
#[inline(always)]
pure fn lt(&self, other: &*const T) -> bool unsafe {
pure fn lt(&self, other: &*const T) -> bool {
unsafe {
let a: uint = cast::reinterpret_cast(&(*self));
let b: uint = cast::reinterpret_cast(&(*other));
return a < b;
}
}
#[inline(always)]
pure fn le(&self, other: &*const T) -> bool unsafe {
pure fn le(&self, other: &*const T) -> bool {
unsafe {
let a: uint = cast::reinterpret_cast(&(*self));
let b: uint = cast::reinterpret_cast(&(*other));
return a <= b;
}
}
#[inline(always)]
pure fn ge(&self, other: &*const T) -> bool unsafe {
pure fn ge(&self, other: &*const T) -> bool {
unsafe {
let a: uint = cast::reinterpret_cast(&(*self));
let b: uint = cast::reinterpret_cast(&(*other));
return a >= b;
}
}
#[inline(always)]
pure fn gt(&self, other: &*const T) -> bool unsafe {
pure fn gt(&self, other: &*const T) -> bool {
unsafe {
let a: uint = cast::reinterpret_cast(&(*self));
let b: uint = cast::reinterpret_cast(&(*other));
return a > b;
}
}
}
// Equality for region pointers
#[cfg(notest)]

View file

@ -366,11 +366,13 @@ Section: Transforming strings
*
* The result vector is not null-terminated.
*/
pub pure fn to_bytes(s: &str) -> ~[u8] unsafe {
pub pure fn to_bytes(s: &str) -> ~[u8] {
unsafe {
let mut v: ~[u8] = ::cast::transmute(from_slice(s));
vec::raw::set_len(&mut v, len(s));
v
}
}
/// Work with the string as a byte slice, not including trailing null.
#[inline(always)]
@ -454,8 +456,10 @@ pure fn split_char_inner(s: &str, sep: char, count: uint, allow_empty: bool)
let mut i = 0u, start = 0u;
while i < l && done < count {
if s[i] == b {
if allow_empty || start < i unsafe {
result.push(unsafe { raw::slice_bytes(s, start, i) });
if allow_empty || start < i {
unsafe {
result.push(raw::slice_bytes(s, start, i));
}
}
start = i + 1u;
done += 1u;
@ -497,16 +501,20 @@ pure fn split_inner(s: &str, sepfn: fn(cc: char) -> bool, count: uint,
while i < l && done < count {
let CharRange {ch, next} = char_range_at(s, i);
if sepfn(ch) {
if allow_empty || start < i unsafe {
result.push(unsafe { raw::slice_bytes(s, start, i)});
if allow_empty || start < i {
unsafe {
result.push(raw::slice_bytes(s, start, i));
}
}
start = next;
done += 1u;
}
i = next;
}
if allow_empty || start < l unsafe {
result.push(unsafe { raw::slice_bytes(s, start, l) });
if allow_empty || start < l {
unsafe {
result.push(raw::slice_bytes(s, start, l));
}
}
result
}
@ -1490,11 +1498,13 @@ pub pure fn to_utf16(s: &str) -> ~[u16] {
// Arithmetic with u32 literals is easier on the eyes than chars.
let mut ch = cch as u32;
if (ch & 0xFFFF_u32) == ch unsafe {
// The BMP falls through (assuming non-surrogate, as it should)
unsafe {
if (ch & 0xFFFF_u32) == ch {
// The BMP falls through (assuming non-surrogate, as it
// should)
assert ch <= 0xD7FF_u32 || ch >= 0xE000_u32;
u.push(ch as u16)
} else unsafe {
} else {
// Supplementary planes break into surrogates.
assert ch >= 0x1_0000_u32 && ch <= 0x10_FFFF_u32;
ch -= 0x1_0000_u32;
@ -1503,6 +1513,7 @@ pub pure fn to_utf16(s: &str) -> ~[u16] {
u.push_all(~[w1, w2])
}
}
}
u
}

View file

@ -213,7 +213,8 @@ pub mod tests {
}
#[test]
pub fn synthesize_closure() unsafe {
pub fn synthesize_closure() {
unsafe {
let x = 10;
let f: fn(int) -> int = |y| x + y;
@ -233,6 +234,7 @@ pub mod tests {
assert new_f(20) == 30;
}
}
}
// Local Variables:
// mode: rust;

View file

@ -86,40 +86,50 @@ pub unsafe fn local_data_modify<T: Durable>(
}
#[test]
fn test_tls_multitask() unsafe {
fn test_tls_multitask() {
unsafe {
fn my_key(_x: @~str) { }
local_data_set(my_key, @~"parent data");
do task::spawn unsafe {
assert local_data_get(my_key).is_none(); // TLS shouldn't carry over.
do task::spawn {
unsafe {
// TLS shouldn't carry over.
assert local_data_get(my_key).is_none();
local_data_set(my_key, @~"child data");
assert *(local_data_get(my_key).get()) == ~"child data";
// should be cleaned up for us
}
}
// Must work multiple times
assert *(local_data_get(my_key).get()) == ~"parent data";
assert *(local_data_get(my_key).get()) == ~"parent data";
assert *(local_data_get(my_key).get()) == ~"parent data";
}
}
#[test]
fn test_tls_overwrite() unsafe {
fn test_tls_overwrite() {
unsafe {
fn my_key(_x: @~str) { }
local_data_set(my_key, @~"first data");
local_data_set(my_key, @~"next data"); // Shouldn't leak.
assert *(local_data_get(my_key).get()) == ~"next data";
}
}
#[test]
fn test_tls_pop() unsafe {
fn test_tls_pop() {
unsafe {
fn my_key(_x: @~str) { }
local_data_set(my_key, @~"weasel");
assert *(local_data_pop(my_key).get()) == ~"weasel";
// Pop must remove the data from the map.
assert local_data_pop(my_key).is_none();
}
}
#[test]
fn test_tls_modify() unsafe {
fn test_tls_modify() {
unsafe {
fn my_key(_x: @~str) { }
local_data_modify(my_key, |data| {
match data {
@ -136,62 +146,77 @@ fn test_tls_modify() unsafe {
});
assert *(local_data_pop(my_key).get()) == ~"next data";
}
}
#[test]
fn test_tls_crust_automorestack_memorial_bug() unsafe {
// This might result in a stack-canary clobber if the runtime fails to set
// sp_limit to 0 when calling the cleanup extern - it might automatically
// jump over to the rust stack, which causes next_c_sp to get recorded as
// Something within a rust stack segment. Then a subsequent upcall (esp.
// for logging, think vsnprintf) would run on a stack smaller than 1 MB.
fn test_tls_crust_automorestack_memorial_bug() {
unsafe {
// This might result in a stack-canary clobber if the runtime fails to
// set sp_limit to 0 when calling the cleanup extern - it might
// automatically jump over to the rust stack, which causes next_c_sp
// to get recorded as something within a rust stack segment. Then a
// subsequent upcall (esp. for logging, think vsnprintf) would run on
// a stack smaller than 1 MB.
fn my_key(_x: @~str) { }
do task::spawn {
unsafe { local_data_set(my_key, @~"hax"); }
}
}
}
#[test]
fn test_tls_multiple_types() unsafe {
fn test_tls_multiple_types() {
unsafe {
fn str_key(_x: @~str) { }
fn box_key(_x: @@()) { }
fn int_key(_x: @int) { }
do task::spawn unsafe {
do task::spawn {
unsafe {
local_data_set(str_key, @~"string data");
local_data_set(box_key, @@());
local_data_set(int_key, @42);
}
}
}
}
#[test]
fn test_tls_overwrite_multiple_types() {
fn str_key(_x: @~str) { }
fn box_key(_x: @@()) { }
fn int_key(_x: @int) { }
do task::spawn unsafe {
do task::spawn {
unsafe {
local_data_set(str_key, @~"string data");
local_data_set(int_key, @42);
// This could cause a segfault if overwriting-destruction is done with
// the crazy polymorphic transmute rather than the provided finaliser.
// This could cause a segfault if overwriting-destruction is done
// with the crazy polymorphic transmute rather than the provided
// finaliser.
local_data_set(int_key, @31337);
}
}
}
#[test]
#[should_fail]
#[ignore(cfg(windows))]
fn test_tls_cleanup_on_failure() unsafe {
fn test_tls_cleanup_on_failure() {
unsafe {
fn str_key(_x: @~str) { }
fn box_key(_x: @@()) { }
fn int_key(_x: @int) { }
local_data_set(str_key, @~"parent data");
local_data_set(box_key, @@());
do task::spawn unsafe { // spawn_linked
do task::spawn {
unsafe { // spawn_linked
local_data_set(str_key, @~"string data");
local_data_set(box_key, @@());
local_data_set(int_key, @42);
fail;
}
}
// Not quite nondeterministic.
local_data_set(int_key, @31337);
fail;
}
}

View file

@ -29,11 +29,13 @@ pub trait LocalData { }
impl<T: Durable> @T: LocalData { }
impl LocalData: Eq {
pure fn eq(&self, other: &@LocalData) -> bool unsafe {
pure fn eq(&self, other: &@LocalData) -> bool {
unsafe {
let ptr_a: (uint, uint) = cast::reinterpret_cast(&(*self));
let ptr_b: (uint, uint) = cast::reinterpret_cast(other);
return ptr_a == ptr_b;
}
}
pure fn ne(&self, other: &@LocalData) -> bool { !(*self).eq(other) }
}
@ -43,12 +45,15 @@ type TaskLocalElement = (*libc::c_void, *libc::c_void, LocalData);
// Has to be a pointer at outermost layer; the foreign call returns void *.
type TaskLocalMap = @dvec::DVec<Option<TaskLocalElement>>;
extern fn cleanup_task_local_map(map_ptr: *libc::c_void) unsafe {
extern fn cleanup_task_local_map(map_ptr: *libc::c_void) {
unsafe {
assert !map_ptr.is_null();
// Get and keep the single reference that was created at the beginning.
// Get and keep the single reference that was created at the
// beginning.
let _map: TaskLocalMap = cast::reinterpret_cast(&map_ptr);
// All local_data will be destroyed along with the map.
}
}
// Gets the map from the runtime. Lazily initialises if not done so already.
unsafe fn get_task_local_map(task: *rust_task) -> TaskLocalMap {

View file

@ -114,19 +114,23 @@ impl<A: ToStr Copy, B: ToStr Copy, C: ToStr Copy> (A, B, C): ToStr {
impl<A: ToStr> ~[A]: ToStr {
#[inline(always)]
pure fn to_str() -> ~str unsafe {
pure fn to_str() -> ~str {
unsafe {
// Bleh -- not really unsafe
// push_str and push_char
let mut acc = ~"[", first = true;
for vec::each(self) |elt| unsafe {
for vec::each(self) |elt| {
unsafe {
if first { first = false; }
else { str::push_str(&mut acc, ~", "); }
str::push_str(&mut acc, elt.to_str());
}
}
str::push_char(&mut acc, ']');
move acc
}
}
}
impl<A: ToStr> @A: ToStr {
#[inline(always)]

View file

@ -450,8 +450,8 @@ pub pure fn partitioned<T: Copy>(v: &[T], f: fn(&T) -> bool) -> (~[T], ~[T]) {
// Mutators
/// Removes the first element from a vector and return it
pub fn shift<T>(v: &mut ~[T]) -> T unsafe {
pub fn shift<T>(v: &mut ~[T]) -> T {
unsafe {
assert v.is_not_empty();
if v.len() == 1 { return v.pop() }
@ -496,6 +496,7 @@ pub fn shift<T>(v: &mut ~[T]) -> T unsafe {
return work_elt;
}
}
/// Prepend an element to the vector
pub fn unshift<T>(v: &mut ~[T], x: T) {
@ -532,7 +533,8 @@ pub fn remove<T>(v: &mut ~[T], i: uint) -> T {
v.pop()
}
pub fn consume<T>(v: ~[T], f: fn(uint, v: T)) unsafe {
pub fn consume<T>(v: ~[T], f: fn(uint, v: T)) {
unsafe {
let mut v = v; // FIXME(#3488)
do as_mut_buf(v) |p, ln| {
@ -550,6 +552,7 @@ pub fn consume<T>(v: ~[T], f: fn(uint, v: T)) unsafe {
raw::set_len(&mut v, 0);
}
}
pub fn consume_mut<T>(v: ~[mut T], f: fn(uint, v: T)) {
consume(vec::cast_from_mut(v), f)
@ -666,19 +669,21 @@ pub fn truncate<T>(v: &mut ~[T], newlen: uint) {
* Remove consecutive repeated elements from a vector; if the vector is
* sorted, this removes all duplicates.
*/
pub fn dedup<T: Eq>(v: &mut ~[T]) unsafe {
pub fn dedup<T: Eq>(v: &mut ~[T]) {
unsafe {
if v.len() < 1 { return; }
let mut last_written = 0, next_to_read = 1;
do as_const_buf(*v) |p, ln| {
// We have a mutable reference to v, so we can make arbitrary changes.
// (cf. push and pop)
// We have a mutable reference to v, so we can make arbitrary
// changes. (cf. push and pop)
let p = p as *mut T;
// last_written < next_to_read <= ln
while next_to_read < ln {
// last_written < next_to_read < ln
if *ptr::mut_offset(p, next_to_read) ==
*ptr::mut_offset(p, last_written) {
// FIXME #4204 Should be rusti::uninit() - don't need to zero
// FIXME #4204 Should be rusti::uninit() - don't need to
// zero
let mut dropped = rusti::init();
dropped <-> *ptr::mut_offset(p, next_to_read);
} else {
@ -697,6 +702,7 @@ pub fn dedup<T: Eq>(v: &mut ~[T]) unsafe {
// last_written < next_to_read == ln
raw::set_len(v, last_written + 1);
}
}
// Appending
@ -1215,7 +1221,9 @@ pub pure fn zip_slice<T: Copy, U: Copy>(v: &[const T], u: &[const U])
let sz = len(v);
let mut i = 0u;
assert sz == len(u);
while i < sz unsafe { zipped.push((v[i], u[i])); i += 1u; }
while i < sz {
unsafe { zipped.push((v[i], u[i])); i += 1u; }
}
zipped
}
@ -1454,10 +1462,12 @@ pub pure fn windowed<TT: Copy>(nn: uint, xx: &[TT]) -> ~[~[TT]] {
assert 1u <= nn;
for vec::eachi (xx) |ii, _x| {
let len = vec::len(xx);
if ii+nn <= len unsafe {
if ii+nn <= len {
unsafe {
ww.push(vec::slice(xx, ii, ii+nn));
}
}
}
ww
}
@ -3909,11 +3919,13 @@ mod tests {
#[test]
#[should_fail]
#[ignore(cfg(windows))]
fn test_copy_memory_oob() unsafe {
fn test_copy_memory_oob() {
unsafe {
let a = [mut 1, 2, 3, 4];
let b = [1, 2, 3, 4, 5];
raw::copy_memory(a, b, 5);
}
}
}

View file

@ -59,7 +59,8 @@ impl output_type : cmp::Eq {
pure fn ne(&self, other: &output_type) -> bool { !(*self).eq(other) }
}
pub fn llvm_err(sess: Session, +msg: ~str) -> ! unsafe {
pub fn llvm_err(sess: Session, +msg: ~str) -> ! {
unsafe {
let cstr = llvm::LLVMRustGetLastError();
if cstr == ptr::null() {
sess.fatal(msg);
@ -67,6 +68,7 @@ pub fn llvm_err(sess: Session, +msg: ~str) -> ! unsafe {
sess.fatal(msg + ~": " + str::raw::from_c_str(cstr));
}
}
}
pub fn WriteOutputFile(sess: Session,
PM: lib::llvm::PassManagerRef, M: ModuleRef,
@ -121,7 +123,8 @@ pub mod jit {
pm: PassManagerRef,
m: ModuleRef,
opt: c_int,
stacks: bool) unsafe {
stacks: bool) {
unsafe {
let manager = llvm::LLVMRustPrepareJIT(rusti::morestack_addr());
// We need to tell JIT where to resolve all linked
@ -168,6 +171,7 @@ pub mod jit {
}
}
}
}
mod write {
#[legacy_exports];
@ -576,9 +580,11 @@ fn build_link_meta(sess: Session, c: &ast::crate, output: &Path,
return {name: name, vers: vers, extras_hash: extras_hash};
}
fn truncated_hash_result(symbol_hasher: &hash::State) -> ~str unsafe {
fn truncated_hash_result(symbol_hasher: &hash::State) -> ~str {
unsafe {
symbol_hasher.result_str()
}
}
// This calculates STH for a symbol, as defined above

View file

@ -1386,7 +1386,7 @@ fn float_width(llt: TypeRef) -> uint {
}
}
fn fn_ty_param_tys(fn_ty: TypeRef) -> ~[TypeRef] unsafe {
fn fn_ty_param_tys(fn_ty: TypeRef) -> ~[TypeRef] {
unsafe {
let args = vec::from_elem(llvm::LLVMCountParamTypes(fn_ty) as uint,
0 as TypeRef);

View file

@ -201,7 +201,8 @@ fn metadata_matches(extern_metas: ~[@ast::meta_item],
}
fn get_metadata_section(os: os,
filename: &Path) -> Option<@~[u8]> unsafe {
filename: &Path) -> Option<@~[u8]> {
unsafe {
let mb = str::as_c_str(filename.to_str(), |buf| {
llvm::LLVMRustCreateMemoryBufferWithContentsOfFile(buf)
});
@ -247,6 +248,7 @@ fn get_metadata_section(os: os,
}
return option::None::<@~[u8]>;
}
}
fn meta_section_name(os: os) -> ~str {
match os {

View file

@ -2255,14 +2255,16 @@ fn create_main_wrapper(ccx: @crate_ctxt, sp: span, main_llfn: ValueRef) {
val_ty(crate_map)], ccx.int_type);
let start = decl_cdecl_fn(ccx.llmod, ~"rust_start", start_ty);
let args = if ccx.sess.building_library unsafe {
let args = unsafe {
if ccx.sess.building_library {
~[rust_main,
llvm::LLVMConstInt(T_i32(), 0u as c_ulonglong, False),
llvm::LLVMConstInt(T_i32(), 0u as c_ulonglong, False),
crate_map]
} else unsafe {
} else {
~[rust_main, llvm::LLVMGetParam(llfn, 0 as c_uint),
llvm::LLVMGetParam(llfn, 1 as c_uint), crate_map]
}
};
let result = unsafe {

View file

@ -176,10 +176,12 @@ fn IndirectBr(cx: block, Addr: ValueRef, NumDests: uint) {
// This is a really awful way to get a zero-length c-string, but better (and a
// lot more efficient) than doing str::as_c_str("", ...) every time.
fn noname() -> *libc::c_char unsafe {
fn noname() -> *libc::c_char {
unsafe {
const cnull: uint = 0u;
return cast::reinterpret_cast(&ptr::addr_of(&cnull));
}
}
fn Invoke(cx: block, Fn: ValueRef, Args: ~[ValueRef],
Then: BasicBlockRef, Catch: BasicBlockRef) {

View file

@ -660,7 +660,7 @@ fn val_str(tn: type_names, v: ValueRef) -> @str {
}
// Returns the nth element of the given LLVM structure type.
fn struct_elt(llstructty: TypeRef, n: uint) -> TypeRef unsafe {
fn struct_elt(llstructty: TypeRef, n: uint) -> TypeRef {
unsafe {
let elt_count = llvm::LLVMCountStructElementTypes(llstructty) as uint;
assert (n < elt_count);
@ -832,11 +832,13 @@ fn T_size_t(targ_cfg: @session::config) -> TypeRef {
return T_int(targ_cfg);
}
fn T_fn(inputs: ~[TypeRef], output: TypeRef) -> TypeRef unsafe {
fn T_fn(inputs: ~[TypeRef], output: TypeRef) -> TypeRef {
unsafe {
return llvm::LLVMFunctionType(output, to_ptr(inputs),
inputs.len() as c_uint,
False);
}
}
fn T_fn_pair(cx: @crate_ctxt, tfn: TypeRef) -> TypeRef {
return T_struct(~[T_ptr(tfn), T_opaque_cbox_ptr(cx)]);
@ -854,7 +856,7 @@ fn T_root(t: TypeRef, addrspace: addrspace) -> TypeRef {
}
}
fn T_struct(elts: ~[TypeRef]) -> TypeRef unsafe {
fn T_struct(elts: ~[TypeRef]) -> TypeRef {
unsafe {
return llvm::LLVMStructType(to_ptr(elts),
elts.len() as c_uint,
@ -869,7 +871,7 @@ fn T_named_struct(name: ~str) -> TypeRef {
}
}
fn set_struct_body(t: TypeRef, elts: ~[TypeRef]) unsafe {
fn set_struct_body(t: TypeRef, elts: ~[TypeRef]) {
unsafe {
llvm::LLVMStructSetBody(t,
to_ptr(elts),
@ -908,7 +910,7 @@ fn T_task(targ_cfg: @session::config) -> TypeRef {
return t;
}
fn T_tydesc_field(cx: @crate_ctxt, field: uint) -> TypeRef unsafe {
fn T_tydesc_field(cx: @crate_ctxt, field: uint) -> TypeRef {
// Bit of a kludge: pick the fn typeref out of the tydesc..
unsafe {
@ -1188,7 +1190,7 @@ fn C_postr(s: ~str) -> ValueRef {
}
}
fn C_zero_byte_arr(size: uint) -> ValueRef unsafe {
fn C_zero_byte_arr(size: uint) -> ValueRef {
unsafe {
let mut i = 0u;
let mut elts: ~[ValueRef] = ~[];
@ -1215,14 +1217,14 @@ fn C_named_struct(T: TypeRef, elts: &[ValueRef]) -> ValueRef {
}
}
fn C_array(ty: TypeRef, elts: ~[ValueRef]) -> ValueRef unsafe {
fn C_array(ty: TypeRef, elts: ~[ValueRef]) -> ValueRef {
unsafe {
return llvm::LLVMConstArray(ty, vec::raw::to_ptr(elts),
elts.len() as c_uint);
}
}
fn C_bytes(bytes: ~[u8]) -> ValueRef unsafe {
fn C_bytes(bytes: ~[u8]) -> ValueRef {
unsafe {
return llvm::LLVMConstString(
cast::reinterpret_cast(&vec::raw::to_ptr(bytes)),
@ -1230,7 +1232,7 @@ fn C_bytes(bytes: ~[u8]) -> ValueRef unsafe {
}
}
fn C_bytes_plus_null(bytes: ~[u8]) -> ValueRef unsafe {
fn C_bytes_plus_null(bytes: ~[u8]) -> ValueRef {
unsafe {
return llvm::LLVMConstString(
cast::reinterpret_cast(&vec::raw::to_ptr(bytes)),

View file

@ -86,7 +86,7 @@ fn lli64(val: int) -> ValueRef {
fn lli1(bval: bool) -> ValueRef {
C_bool(bval)
}
fn llmdnode(elems: ~[ValueRef]) -> ValueRef unsafe {
fn llmdnode(elems: ~[ValueRef]) -> ValueRef {
unsafe {
llvm::LLVMMDNode(vec::raw::to_ptr(elems),
vec::len(elems) as libc::c_uint)
@ -95,9 +95,11 @@ fn llmdnode(elems: ~[ValueRef]) -> ValueRef unsafe {
fn llunused() -> ValueRef {
lli32(0x0)
}
fn llnull() -> ValueRef unsafe {
fn llnull() -> ValueRef {
unsafe {
cast::reinterpret_cast(&ptr::null::<ValueRef>())
}
}
fn add_named_metadata(cx: @crate_ctxt, name: ~str, val: ValueRef) {
str::as_c_str(name, |sbuf| {
@ -154,12 +156,15 @@ enum debug_metadata {
retval_metadata(@metadata<retval_md>),
}
fn cast_safely<T: Copy, U>(val: T) -> U unsafe {
fn cast_safely<T: Copy, U>(val: T) -> U {
unsafe {
let val2 = val;
return cast::transmute(move val2);
}
}
fn md_from_metadata<T>(val: debug_metadata) -> T unsafe {
fn md_from_metadata<T>(val: debug_metadata) -> T {
unsafe {
match val {
file_metadata(md) => cast_safely(md),
compile_unit_metadata(md) => cast_safely(md),
@ -171,9 +176,11 @@ fn md_from_metadata<T>(val: debug_metadata) -> T unsafe {
retval_metadata(md) => cast_safely(md)
}
}
}
fn cached_metadata<T: Copy>(cache: metadata_cache, mdtag: int,
eq: fn(md: T) -> bool) -> Option<T> unsafe {
eq: fn(md: T) -> bool) -> Option<T> {
unsafe {
if cache.contains_key(mdtag) {
let items = cache.get(mdtag);
for items.each |item| {
@ -185,9 +192,10 @@ fn cached_metadata<T: Copy>(cache: metadata_cache, mdtag: int,
}
return option::None;
}
}
fn create_compile_unit(cx: @crate_ctxt)
-> @metadata<compile_unit_md> unsafe {
fn create_compile_unit(cx: @crate_ctxt) -> @metadata<compile_unit_md> {
unsafe {
let cache = get_cache(cx);
let crate_name = /*bad*/copy (/*bad*/copy cx.dbg_cx).get().crate_file;
let tg = CompileUnitTag;
@ -197,8 +205,8 @@ fn create_compile_unit(cx: @crate_ctxt)
option::None => ()
}
let (_, work_dir) = get_file_path_and_dir(cx.sess.working_dir.to_str(),
crate_name);
let (_, work_dir) = get_file_path_and_dir(
cx.sess.working_dir.to_str(), crate_name);
let unit_metadata = ~[lltag(tg),
llunused(),
lli32(DW_LANG_RUST),
@ -217,6 +225,7 @@ fn create_compile_unit(cx: @crate_ctxt)
return mdval;
}
}
fn get_cache(cx: @crate_ctxt) -> metadata_cache {
(/*bad*/copy cx.dbg_cx).get().llmetadata
@ -646,7 +655,8 @@ fn create_var(type_tag: int, context: ValueRef, +name: ~str, file: ValueRef,
}
fn create_local_var(bcx: block, local: @ast::local)
-> @metadata<local_var_md> unsafe {
-> @metadata<local_var_md> {
unsafe {
let cx = bcx.ccx();
let cache = get_cache(cx);
let tg = AutoVariableTag;
@ -669,8 +679,8 @@ fn create_local_var(bcx: block, local: @ast::local)
None => create_function(bcx.fcx).node,
Some(_) => create_block(bcx).node
};
let mdnode = create_var(tg, context, cx.sess.str_of(name), filemd.node,
loc.line as int, tymd.node);
let mdnode = create_var(tg, context, cx.sess.str_of(name),
filemd.node, loc.line as int, tymd.node);
let mdval = @{node: mdnode, data: {id: local.node.id}};
update_cache(cache, AutoVariableTag, local_var_metadata(mdval));
@ -693,9 +703,11 @@ fn create_local_var(bcx: block, local: @ast::local)
declargs);
return mdval;
}
}
fn create_arg(bcx: block, arg: ast::arg, sp: span)
-> Option<@metadata<argument_md>> unsafe {
-> Option<@metadata<argument_md>> {
unsafe {
let fcx = bcx.fcx, cx = fcx.ccx;
let cache = get_cache(cx);
let tg = ArgVariableTag;
@ -728,7 +740,8 @@ fn create_arg(bcx: block, arg: ast::arg, sp: span)
local_mem(v) | local_imm(v) => v,
};
let declargs = ~[llmdnode(~[llptr]), mdnode];
trans::build::Call(bcx, cx.intrinsics.get(~"llvm.dbg.declare"),
trans::build::Call(bcx,
cx.intrinsics.get(~"llvm.dbg.declare"),
declargs);
return Some(mdval);
}
@ -737,6 +750,7 @@ fn create_arg(bcx: block, arg: ast::arg, sp: span)
}
}
}
}
fn update_source_pos(cx: block, s: span) {
if !cx.sess().opts.debuginfo {

View file

@ -498,12 +498,14 @@ type t_box = @{sty: sty,
enum t_opaque {}
type t = *t_opaque;
pure fn get(t: t) -> t_box unsafe {
pure fn get(t: t) -> t_box {
unsafe {
let t2 = cast::reinterpret_cast::<t, t_box>(&t);
let t3 = t2;
cast::forget(move t2);
t3
}
}
pure fn tbox_has_flag(tb: t_box, flag: tbox_flag) -> bool {
(tb.flags & (flag as uint)) != 0u

View file

@ -141,10 +141,12 @@ impl BigBitv {
let w0 = self.storage[i] & mask;
let w1 = b.storage[i] & mask;
let w = op(w0, w1) & mask;
if w0 != w unsafe {
if w0 != w {
unsafe {
changed = true;
self.storage[i] = w;
}
}
true
}
changed

View file

@ -219,7 +219,8 @@ pub type Result = result::Result<Matches, Fail_>;
* `opt_str`, etc. to interrogate results. Returns `err(Fail_)` on failure.
* Use <fail_str> to get an error message.
*/
pub fn getopts(args: &[~str], opts: &[Opt]) -> Result unsafe {
pub fn getopts(args: &[~str], opts: &[Opt]) -> Result {
unsafe {
let n_opts = opts.len();
fn f(_x: uint) -> ~[Optval] { return ~[]; }
let vals = vec::cast_to_mut(vec::from_fn(n_opts, f));
@ -256,11 +257,11 @@ pub fn getopts(args: &[~str], opts: &[Opt]) -> Result unsafe {
let range = str::char_range_at(cur, j);
let opt = Short(range.ch);
/* In a series of potential options (eg. -aheJ), if we see
one which takes an argument, we assume all subsequent
characters make up the argument. This allows options
such as -L/usr/local/lib/foo to be interpreted
correctly
/* In a series of potential options (eg. -aheJ), if we
see one which takes an argument, we assume all
subsequent characters make up the argument. This
allows options such as -L/usr/local/lib/foo to be
interpreted correctly
*/
match find_opt(opts, opt) {
@ -340,6 +341,7 @@ pub fn getopts(args: &[~str], opts: &[Opt]) -> Result unsafe {
vals: vec::cast_from_mut(move vals),
free: free});
}
}
fn opt_vals(mm: &Matches, nm: &str) -> ~[Optval] {
return match find_opt(mm.opts, mkname(nm)) {

View file

@ -337,10 +337,12 @@ pub fn to_writer(wr: io::Writer, json: &Json) {
}
/// Encodes a json value into a string
pub pure fn to_str(json: &Json) -> ~str unsafe {
pub pure fn to_str(json: &Json) -> ~str {
unsafe {
// ugh, should be safe
io::with_str_writer(|wr| to_writer(wr, json))
}
}
/// Encodes a json value into a io::writer
pub fn to_pretty_writer(wr: io::Writer, json: &Json) {

View file

@ -435,11 +435,13 @@ pub mod chained {
}
impl<K:Eq IterBytes Hash Copy ToStr, V: ToStr Copy> T<K, V>: ToStr {
pure fn to_str() -> ~str unsafe {
pure fn to_str() -> ~str {
unsafe {
// Meh -- this should be safe
do io::with_str_writer |wr| { self.to_writer(wr) }
}
}
}
impl<K:Eq IterBytes Hash Copy, V: Copy> T<K, V>: ops::Index<K, V> {
pure fn index(&self, k: K) -> V {

View file

@ -117,7 +117,8 @@ enum IpGetAddrErr {
pub fn get_addr(node: &str, iotask: iotask)
-> result::Result<~[IpAddr], IpGetAddrErr> {
do oldcomm::listen |output_ch| {
do str::as_buf(node) |node_ptr, len| unsafe {
do str::as_buf(node) |node_ptr, len| {
unsafe {
log(debug, fmt!("slice len %?", len));
let handle = create_uv_getaddrinfo_t();
let handle_ptr = ptr::addr_of(&handle);
@ -125,7 +126,8 @@ pub fn get_addr(node: &str, iotask: iotask)
output_ch: output_ch
};
let handle_data_ptr = ptr::addr_of(&handle_data);
do interact(iotask) |loop_ptr| unsafe {
do interact(iotask) |loop_ptr| {
unsafe {
let result = uv_getaddrinfo(
loop_ptr,
handle_ptr,
@ -141,11 +143,13 @@ pub fn get_addr(node: &str, iotask: iotask)
output_ch.send(result::Err(GetAddrUnknownError));
}
}
}
};
output_ch.recv()
}
}
}
}
pub mod v4 {
use net::ip::{IpAddr, Ipv4, Ipv6, ParseAddrErr};
@ -300,7 +304,8 @@ type GetAddrData = {
};
extern fn get_addr_cb(handle: *uv_getaddrinfo_t, status: libc::c_int,
res: *addrinfo) unsafe {
res: *addrinfo) {
unsafe {
log(debug, ~"in get_addr_cb");
let handle_data = get_data_for_req(handle) as
*GetAddrData;
@ -357,6 +362,7 @@ extern fn get_addr_cb(handle: *uv_getaddrinfo_t, status: libc::c_int,
}
log(debug, ~"leaving get_addr_cb");
}
}
#[cfg(test)]
mod test {

View file

@ -143,7 +143,8 @@ pub enum TcpConnectErrData {
*/
pub fn connect(input_ip: ip::IpAddr, port: uint,
iotask: IoTask)
-> result::Result<TcpSocket, TcpConnectErrData> unsafe {
-> result::Result<TcpSocket, TcpConnectErrData> {
unsafe {
let result_po = oldcomm::Port::<ConnAttempt>();
let closed_signal_po = oldcomm::Port::<()>();
let conn_data = {
@ -172,7 +173,8 @@ pub fn connect(input_ip: ip::IpAddr, port: uint,
// we can send into the interact cb to be handled in libuv..
log(debug, fmt!("stream_handle_ptr outside interact %?",
stream_handle_ptr));
do iotask::interact(iotask) |move input_ip, loop_ptr| unsafe {
do iotask::interact(iotask) |move input_ip, loop_ptr| {
unsafe {
log(debug, ~"in interact cb for tcp client connect..");
log(debug, fmt!("stream_handle_ptr in interact %?",
stream_handle_ptr));
@ -232,7 +234,8 @@ pub fn connect(input_ip: ip::IpAddr, port: uint,
ConnFailure(err_data.to_tcp_err()));
uv::ll::set_data_for_uv_handle(stream_handle_ptr,
conn_data_ptr);
uv::ll::close(stream_handle_ptr, stream_error_close_cb);
uv::ll::close(stream_handle_ptr,
stream_error_close_cb);
}
}
}
@ -243,6 +246,7 @@ pub fn connect(input_ip: ip::IpAddr, port: uint,
ConnFailure(err_data.to_tcp_err()));
}
}
}
};
match oldcomm::recv(result_po) {
ConnSuccess => {
@ -263,6 +267,7 @@ pub fn connect(input_ip: ip::IpAddr, port: uint,
}
}
}
}
/**
* Write binary data to a tcp stream; Blocks until operation completes
@ -279,10 +284,12 @@ pub fn connect(input_ip: ip::IpAddr, port: uint,
* `tcp_err_data` value as the `err` variant
*/
pub fn write(sock: &TcpSocket, raw_write_data: ~[u8])
-> result::Result<(), TcpErrData> unsafe {
-> result::Result<(), TcpErrData> {
unsafe {
let socket_data_ptr = ptr::addr_of(&(*(sock.socket_data)));
write_common_impl(socket_data_ptr, raw_write_data)
}
}
/**
* Write binary data to tcp stream; Returns a `future::future` value
@ -316,13 +323,15 @@ pub fn write(sock: &TcpSocket, raw_write_data: ~[u8])
* value as the `err` variant
*/
pub fn write_future(sock: &TcpSocket, raw_write_data: ~[u8])
-> future::Future<result::Result<(), TcpErrData>> unsafe {
-> future::Future<result::Result<(), TcpErrData>> {
unsafe {
let socket_data_ptr = ptr::addr_of(&(*(sock.socket_data)));
do future_spawn {
let data_copy = copy(raw_write_data);
write_common_impl(socket_data_ptr, data_copy)
}
}
}
/**
* Begin reading binary data from an open TCP connection; used with
@ -341,10 +350,12 @@ pub fn write_future(sock: &TcpSocket, raw_write_data: ~[u8])
*/
pub fn read_start(sock: &TcpSocket)
-> result::Result<oldcomm::Port<
result::Result<~[u8], TcpErrData>>, TcpErrData> unsafe {
result::Result<~[u8], TcpErrData>>, TcpErrData> {
unsafe {
let socket_data = ptr::addr_of(&(*(sock.socket_data)));
read_start_common_impl(socket_data)
}
}
/**
* Stop reading from an open TCP connection; used with `read_start`
@ -355,11 +366,14 @@ pub fn read_start(sock: &TcpSocket)
*/
pub fn read_stop(sock: &TcpSocket,
read_port: oldcomm::Port<result::Result<~[u8], TcpErrData>>) ->
result::Result<(), TcpErrData> unsafe {
log(debug, fmt!("taking the read_port out of commission %?", read_port));
result::Result<(), TcpErrData> {
unsafe {
log(debug,
fmt!("taking the read_port out of commission %?", read_port));
let socket_data = ptr::addr_of(&(*sock.socket_data));
read_stop_common_impl(socket_data)
}
}
/**
* Reads a single chunk of data from `tcp_socket`; block until data/error
@ -489,8 +503,8 @@ fn read_future(sock: &TcpSocket, timeout_msecs: uint)
* as the `err` variant of a `result`.
*/
pub fn accept(new_conn: TcpNewConnection)
-> result::Result<TcpSocket, TcpErrData> unsafe {
-> result::Result<TcpSocket, TcpErrData> {
unsafe {
match new_conn {
NewTcpConn(server_handle_ptr) => {
let server_data_ptr = uv::ll::get_data_for_uv_handle(
@ -558,6 +572,7 @@ pub fn accept(new_conn: TcpNewConnection)
}
}
}
}
/**
* Bind to a given IP/port and listen for new connections
@ -592,24 +607,30 @@ pub fn listen(host_ip: ip::IpAddr, port: uint, backlog: uint,
on_establish_cb: fn~(oldcomm::Chan<Option<TcpErrData>>),
new_connect_cb: fn~(TcpNewConnection,
oldcomm::Chan<Option<TcpErrData>>))
-> result::Result<(), TcpListenErrData> unsafe {
-> result::Result<(), TcpListenErrData> {
unsafe {
do listen_common(move host_ip, port, backlog, iotask,
move on_establish_cb)
// on_connect_cb
|move new_connect_cb, handle| unsafe {
let server_data_ptr = uv::ll::get_data_for_uv_handle(handle)
|move new_connect_cb, handle| {
unsafe {
let server_data_ptr =
uv::ll::get_data_for_uv_handle(handle)
as *TcpListenFcData;
let new_conn = NewTcpConn(handle);
let kill_ch = (*server_data_ptr).kill_ch;
new_connect_cb(new_conn, kill_ch);
}
}
}
}
fn listen_common(host_ip: ip::IpAddr, port: uint, backlog: uint,
iotask: IoTask,
on_establish_cb: fn~(oldcomm::Chan<Option<TcpErrData>>),
on_connect_cb: fn~(*uv::ll::uv_tcp_t))
-> result::Result<(), TcpListenErrData> unsafe {
-> result::Result<(), TcpListenErrData> {
unsafe {
let stream_closed_po = oldcomm::Port::<()>();
let kill_po = oldcomm::Port::<Option<TcpErrData>>();
let kill_ch = oldcomm::Chan(&kill_po);
@ -637,7 +658,8 @@ fn listen_common(host_ip: ip::IpAddr, port: uint, backlog: uint,
// tcp::connect (because the iotask::interact cb isn't
// nested within a core::comm::listen block)
let loc_ip = copy(host_ip);
do iotask::interact(iotask) |move loc_ip, loop_ptr| unsafe {
do iotask::interact(iotask) |move loc_ip, loop_ptr| {
unsafe {
match uv::ll::tcp_init(loop_ptr, server_stream_ptr) {
0i32 => {
uv::ll::set_data_for_uv_handle(
@ -647,13 +669,15 @@ fn listen_common(host_ip: ip::IpAddr, port: uint, backlog: uint,
let bind_result = match loc_ip {
ip::Ipv4(ref addr) => {
log(debug, fmt!("addr: %?", addr));
let in_addr = uv::ll::ip4_addr(addr_str, port as int);
let in_addr = uv::ll::ip4_addr(addr_str,
port as int);
uv::ll::tcp_bind(server_stream_ptr,
ptr::addr_of(&in_addr))
}
ip::Ipv6(ref addr) => {
log(debug, fmt!("addr: %?", addr));
let in_addr = uv::ll::ip6_addr(addr_str, port as int);
let in_addr = uv::ll::ip6_addr(addr_str,
port as int);
uv::ll::tcp_bind6(server_stream_ptr,
ptr::addr_of(&in_addr))
}
@ -666,14 +690,16 @@ fn listen_common(host_ip: ip::IpAddr, port: uint, backlog: uint,
0i32 => oldcomm::send(setup_ch, None),
_ => {
log(debug, ~"failure to uv_listen()");
let err_data = uv::ll::get_last_err_data(loop_ptr);
let err_data = uv::ll::get_last_err_data(
loop_ptr);
oldcomm::send(setup_ch, Some(err_data));
}
}
}
_ => {
log(debug, ~"failure to uv_tcp_bind");
let err_data = uv::ll::get_last_err_data(loop_ptr);
let err_data = uv::ll::get_last_err_data(
loop_ptr);
oldcomm::send(setup_ch, Some(err_data));
}
}
@ -685,15 +711,19 @@ fn listen_common(host_ip: ip::IpAddr, port: uint, backlog: uint,
}
}
};
}
setup_ch.recv()
};
match setup_result {
Some(ref err_data) => {
do iotask::interact(iotask) |loop_ptr| unsafe {
log(debug, fmt!("tcp::listen post-kill recv hl interact %?",
do iotask::interact(iotask) |loop_ptr| {
unsafe {
log(debug,
fmt!("tcp::listen post-kill recv hl interact %?",
loop_ptr));
(*server_data_ptr).active = false;
uv::ll::close(server_stream_ptr, tcp_lfc_close_cb);
}
};
stream_closed_po.recv();
match err_data.err_name {
@ -716,11 +746,14 @@ fn listen_common(host_ip: ip::IpAddr, port: uint, backlog: uint,
None => {
on_establish_cb(kill_ch);
let kill_result = oldcomm::recv(kill_po);
do iotask::interact(iotask) |loop_ptr| unsafe {
log(debug, fmt!("tcp::listen post-kill recv hl interact %?",
do iotask::interact(iotask) |loop_ptr| {
unsafe {
log(debug,
fmt!("tcp::listen post-kill recv hl interact %?",
loop_ptr));
(*server_data_ptr).active = false;
uv::ll::close(server_stream_ptr, tcp_lfc_close_cb);
}
};
stream_closed_po.recv();
match kill_result {
@ -734,6 +767,7 @@ fn listen_common(host_ip: ip::IpAddr, port: uint, backlog: uint,
}
}
}
}
/**
* Convert a `net::tcp::tcp_socket` to a `net::tcp::tcp_socket_buf`.
@ -859,17 +893,22 @@ impl TcpSocketBuf: io::Reader {
/// Implementation of `io::reader` trait for a buffered `net::tcp::tcp_socket`
impl TcpSocketBuf: io::Writer {
pub fn write(&self, data: &[const u8]) unsafe {
pub fn write(&self, data: &[const u8]) {
unsafe {
let socket_data_ptr =
ptr::addr_of(&(*((*(self.data)).sock).socket_data));
let w_result = write_common_impl(socket_data_ptr,
vec::slice(data, 0, vec::len(data)));
vec::slice(data,
0,
vec::len(data)));
if w_result.is_err() {
let err_data = w_result.get_err();
log(debug, fmt!("ERROR sock_buf as io::writer.writer err: %? %?",
log(debug,
fmt!("ERROR sock_buf as io::writer.writer err: %? %?",
err_data.err_name, err_data.err_msg));
}
}
}
fn seek(&self, dist: int, seek: io::SeekStyle) {
log(debug, fmt!("tcp_socket_buf seek stub %? %?", dist, seek));
// noop
@ -887,7 +926,8 @@ impl TcpSocketBuf: io::Writer {
// INTERNAL API
fn tear_down_socket_data(socket_data: @TcpSocketData) unsafe {
fn tear_down_socket_data(socket_data: @TcpSocketData) {
unsafe {
let closed_po = oldcomm::Port::<()>();
let closed_ch = oldcomm::Chan(&closed_po);
let close_data = {
@ -895,12 +935,15 @@ fn tear_down_socket_data(socket_data: @TcpSocketData) unsafe {
};
let close_data_ptr = ptr::addr_of(&close_data);
let stream_handle_ptr = (*socket_data).stream_handle_ptr;
do iotask::interact((*socket_data).iotask) |loop_ptr| unsafe {
log(debug, fmt!("interact dtor for tcp_socket stream %? loop %?",
do iotask::interact((*socket_data).iotask) |loop_ptr| {
unsafe {
log(debug,
fmt!("interact dtor for tcp_socket stream %? loop %?",
stream_handle_ptr, loop_ptr));
uv::ll::set_data_for_uv_handle(stream_handle_ptr,
close_data_ptr);
uv::ll::close(stream_handle_ptr, tcp_socket_dtor_close_cb);
}
};
oldcomm::recv(closed_po);
//the line below will most likely crash
@ -909,10 +952,12 @@ fn tear_down_socket_data(socket_data: @TcpSocketData) unsafe {
as *libc::c_void);
log(debug, ~"exiting dtor for tcp_socket");
}
}
// shared implementation for tcp::read
fn read_common_impl(socket_data: *TcpSocketData, timeout_msecs: uint)
-> result::Result<~[u8],TcpErrData> unsafe {
-> result::Result<~[u8],TcpErrData> {
unsafe {
use timer;
log(debug, ~"starting tcp::read");
@ -949,16 +994,20 @@ fn read_common_impl(socket_data: *TcpSocketData, timeout_msecs: uint)
}
}
}
}
// shared impl for read_stop
fn read_stop_common_impl(socket_data: *TcpSocketData) ->
result::Result<(), TcpErrData> unsafe {
result::Result<(), TcpErrData> {
unsafe {
let stream_handle_ptr = (*socket_data).stream_handle_ptr;
let stop_po = oldcomm::Port::<Option<TcpErrData>>();
let stop_ch = oldcomm::Chan(&stop_po);
do iotask::interact((*socket_data).iotask) |loop_ptr| unsafe {
do iotask::interact((*socket_data).iotask) |loop_ptr| {
unsafe {
log(debug, ~"in interact cb for tcp::read_stop");
match uv::ll::read_stop(stream_handle_ptr as *uv::ll::uv_stream_t) {
match uv::ll::read_stop(stream_handle_ptr as
*uv::ll::uv_stream_t) {
0i32 => {
log(debug, ~"successfully called uv_read_stop");
oldcomm::send(stop_ch, None);
@ -969,24 +1018,30 @@ fn read_stop_common_impl(socket_data: *TcpSocketData) ->
oldcomm::send(stop_ch, Some(err_data.to_tcp_err()));
}
}
}
};
match oldcomm::recv(stop_po) {
Some(ref err_data) => result::Err(err_data.to_tcp_err()),
None => result::Ok(())
}
}
}
// shared impl for read_start
fn read_start_common_impl(socket_data: *TcpSocketData)
-> result::Result<oldcomm::Port<
result::Result<~[u8], TcpErrData>>, TcpErrData> unsafe {
result::Result<~[u8], TcpErrData>>, TcpErrData> {
unsafe {
let stream_handle_ptr = (*socket_data).stream_handle_ptr;
let start_po = oldcomm::Port::<Option<uv::ll::uv_err_data>>();
let start_ch = oldcomm::Chan(&start_po);
log(debug, ~"in tcp::read_start before interact loop");
do iotask::interact((*socket_data).iotask) |loop_ptr| unsafe {
log(debug, fmt!("in tcp::read_start interact cb %?", loop_ptr));
match uv::ll::read_start(stream_handle_ptr as *uv::ll::uv_stream_t,
do iotask::interact((*socket_data).iotask) |loop_ptr| {
unsafe {
log(debug,
fmt!("in tcp::read_start interact cb %?", loop_ptr));
match uv::ll::read_start(stream_handle_ptr as
*uv::ll::uv_stream_t,
on_alloc_cb,
on_tcp_read_cb) {
0i32 => {
@ -999,19 +1054,22 @@ fn read_start_common_impl(socket_data: *TcpSocketData)
oldcomm::send(start_ch, Some(err_data));
}
}
}
};
match oldcomm::recv(start_po) {
Some(ref err_data) => result::Err(err_data.to_tcp_err()),
None => result::Ok((*socket_data).reader_po)
}
}
}
// helper to convert a "class" vector of [u8] to a *[uv::ll::uv_buf_t]
// shared implementation used by write and write_future
fn write_common_impl(socket_data_ptr: *TcpSocketData,
raw_write_data: ~[u8])
-> result::Result<(), TcpErrData> unsafe {
-> result::Result<(), TcpErrData> {
unsafe {
let write_req_ptr = ptr::addr_of(&((*socket_data_ptr).write_req));
let stream_handle_ptr =
(*socket_data_ptr).stream_handle_ptr;
@ -1024,8 +1082,10 @@ fn write_common_impl(socket_data_ptr: *TcpSocketData,
result_ch: oldcomm::Chan(&result_po)
};
let write_data_ptr = ptr::addr_of(&write_data);
do iotask::interact((*socket_data_ptr).iotask) |loop_ptr| unsafe {
log(debug, fmt!("in interact cb for tcp::write %?", loop_ptr));
do iotask::interact((*socket_data_ptr).iotask) |loop_ptr| {
unsafe {
log(debug, fmt!("in interact cb for tcp::write %?",
loop_ptr));
match uv::ll::write(write_req_ptr,
stream_handle_ptr,
write_buf_vec_ptr,
@ -1041,6 +1101,7 @@ fn write_common_impl(socket_data_ptr: *TcpSocketData,
TcpWriteError(err_data.to_tcp_err()));
}
}
}
};
// FIXME (#2656): Instead of passing unsafe pointers to local data,
// and waiting here for the write to complete, we should transfer
@ -1051,6 +1112,7 @@ fn write_common_impl(socket_data_ptr: *TcpSocketData,
TcpWriteError(ref err_data) => result::Err(err_data.to_tcp_err())
}
}
}
enum TcpNewConnection {
NewTcpConn(*uv::ll::uv_tcp_t)
@ -1066,14 +1128,17 @@ type TcpListenFcData = {
mut active: bool
};
extern fn tcp_lfc_close_cb(handle: *uv::ll::uv_tcp_t) unsafe {
extern fn tcp_lfc_close_cb(handle: *uv::ll::uv_tcp_t) {
unsafe {
let server_data_ptr = uv::ll::get_data_for_uv_handle(
handle) as *TcpListenFcData;
oldcomm::send((*server_data_ptr).stream_closed_ch, ());
}
}
extern fn tcp_lfc_on_connection_cb(handle: *uv::ll::uv_tcp_t,
status: libc::c_int) unsafe {
status: libc::c_int) {
unsafe {
let server_data_ptr = uv::ll::get_data_for_uv_handle(handle)
as *TcpListenFcData;
let kill_ch = (*server_data_ptr).kill_ch;
@ -1090,11 +1155,14 @@ extern fn tcp_lfc_on_connection_cb(handle: *uv::ll::uv_tcp_t,
}
}
}
}
fn malloc_uv_tcp_t() -> *uv::ll::uv_tcp_t unsafe {
fn malloc_uv_tcp_t() -> *uv::ll::uv_tcp_t {
unsafe {
rustrt::rust_uv_current_kernel_malloc(
rustrt::rust_uv_helper_uv_tcp_t_size()) as *uv::ll::uv_tcp_t
}
}
enum TcpConnectResult {
TcpConnected(TcpSocket),
@ -1129,7 +1197,8 @@ impl uv::ll::uv_err_data: ToTcpErr {
extern fn on_tcp_read_cb(stream: *uv::ll::uv_stream_t,
nread: libc::ssize_t,
++buf: uv::ll::uv_buf_t) unsafe {
++buf: uv::ll::uv_buf_t) {
unsafe {
log(debug, fmt!("entering on_tcp_read_cb stream: %? nread: %?",
stream, nread));
let loop_ptr = uv::ll::get_loop_for_uv_handle(stream);
@ -1159,10 +1228,12 @@ extern fn on_tcp_read_cb(stream: *uv::ll::uv_stream_t,
uv::ll::free_base_of_buf(buf);
log(debug, ~"exiting on_tcp_read_cb");
}
}
extern fn on_alloc_cb(handle: *libc::c_void,
suggested_size: size_t)
-> uv::ll::uv_buf_t unsafe {
-> uv::ll::uv_buf_t {
unsafe {
log(debug, ~"tcp read on_alloc_cb!");
let char_ptr = uv::ll::malloc_buf_base_of(suggested_size);
log(debug, fmt!("tcp read on_alloc_cb h: %? char_ptr: %u sugsize: %u",
@ -1171,21 +1242,25 @@ extern fn on_alloc_cb(handle: *libc::c_void,
suggested_size as uint));
uv::ll::buf_init(char_ptr, suggested_size as uint)
}
}
type TcpSocketCloseData = {
closed_ch: oldcomm::Chan<()>
};
extern fn tcp_socket_dtor_close_cb(handle: *uv::ll::uv_tcp_t) unsafe {
extern fn tcp_socket_dtor_close_cb(handle: *uv::ll::uv_tcp_t) {
unsafe {
let data = uv::ll::get_data_for_uv_handle(handle)
as *TcpSocketCloseData;
let closed_ch = (*data).closed_ch;
oldcomm::send(closed_ch, ());
log(debug, ~"tcp_socket_dtor_close_cb exiting..");
}
}
extern fn tcp_write_complete_cb(write_req: *uv::ll::uv_write_t,
status: libc::c_int) unsafe {
status: libc::c_int) {
unsafe {
let write_data_ptr = uv::ll::get_data_for_req(write_req)
as *WriteReqData;
if status == 0i32 {
@ -1201,6 +1276,7 @@ extern fn tcp_write_complete_cb(write_req: *uv::ll::uv_write_t,
TcpWriteError(err_data));
}
}
}
type WriteReqData = {
result_ch: oldcomm::Chan<TcpWriteResult>
@ -1211,19 +1287,24 @@ type ConnectReqData = {
closed_signal_ch: oldcomm::Chan<()>
};
extern fn stream_error_close_cb(handle: *uv::ll::uv_tcp_t) unsafe {
extern fn stream_error_close_cb(handle: *uv::ll::uv_tcp_t) {
unsafe {
let data = uv::ll::get_data_for_uv_handle(handle) as
*ConnectReqData;
oldcomm::send((*data).closed_signal_ch, ());
log(debug, fmt!("exiting steam_error_close_cb for %?", handle));
}
}
extern fn tcp_connect_close_cb(handle: *uv::ll::uv_tcp_t) unsafe {
extern fn tcp_connect_close_cb(handle: *uv::ll::uv_tcp_t) {
unsafe {
log(debug, fmt!("closed client tcp handle %?", handle));
}
}
extern fn tcp_connect_on_connect_cb(connect_req_ptr: *uv::ll::uv_connect_t,
status: libc::c_int) unsafe {
status: libc::c_int) {
unsafe {
let conn_data_ptr = (uv::ll::get_data_for_req(connect_req_ptr)
as *ConnectReqData);
let result_ch = (*conn_data_ptr).result_ch;
@ -1249,6 +1330,7 @@ extern fn tcp_connect_on_connect_cb(connect_req_ptr: *uv::ll::uv_connect_t,
}
log(debug, ~"leaving tcp_connect_on_connect_cb");
}
}
enum ConnAttempt {
ConnSuccess,
@ -1298,26 +1380,36 @@ pub mod test {
use net::tcp::test::*;
#[test]
fn test_gl_tcp_server_and_client_ipv4() unsafe {
fn test_gl_tcp_server_and_client_ipv4() {
unsafe {
use net::tcp::test::tcp_ipv4_server_and_client_test::*;
impl_gl_tcp_ipv4_server_and_client();
}
}
#[test]
fn test_gl_tcp_get_peer_addr() unsafe {
fn test_gl_tcp_get_peer_addr() {
unsafe {
impl_gl_tcp_ipv4_get_peer_addr();
}
}
#[test]
fn test_gl_tcp_ipv4_client_error_connection_refused() unsafe {
fn test_gl_tcp_ipv4_client_error_connection_refused() {
unsafe {
impl_gl_tcp_ipv4_client_error_connection_refused();
}
#[test]
fn test_gl_tcp_server_address_in_use() unsafe {
impl_gl_tcp_ipv4_server_address_in_use();
}
#[test]
fn test_gl_tcp_server_access_denied() unsafe {
fn test_gl_tcp_server_address_in_use() {
unsafe {
impl_gl_tcp_ipv4_server_address_in_use();
}
}
#[test]
fn test_gl_tcp_server_access_denied() {
unsafe {
impl_gl_tcp_ipv4_server_access_denied();
}
}
// Strange failure on Windows. --pcwalton
#[test]
#[ignore(cfg(target_os = "win32"))]
@ -1336,30 +1428,40 @@ pub mod test {
#[test]
#[ignore(cfg(target_os = "linux"))]
fn test_gl_tcp_server_and_client_ipv4() unsafe {
fn test_gl_tcp_server_and_client_ipv4() {
unsafe {
impl_gl_tcp_ipv4_server_and_client();
}
}
#[test]
#[ignore(cfg(target_os = "linux"))]
fn test_gl_tcp_get_peer_addr() unsafe {
fn test_gl_tcp_get_peer_addr() {
unsafe {
impl_gl_tcp_ipv4_get_peer_addr();
}
#[test]
#[ignore(cfg(target_os = "linux"))]
fn test_gl_tcp_ipv4_client_error_connection_refused() unsafe {
impl_gl_tcp_ipv4_client_error_connection_refused();
}
#[test]
#[ignore(cfg(target_os = "linux"))]
fn test_gl_tcp_server_address_in_use() unsafe {
fn test_gl_tcp_ipv4_client_error_connection_refused() {
unsafe {
impl_gl_tcp_ipv4_client_error_connection_refused();
}
}
#[test]
#[ignore(cfg(target_os = "linux"))]
fn test_gl_tcp_server_address_in_use() {
unsafe {
impl_gl_tcp_ipv4_server_address_in_use();
}
}
#[test]
#[ignore(cfg(target_os = "linux"))]
#[ignore(cfg(windows), reason = "deadlocking bots")]
fn test_gl_tcp_server_access_denied() unsafe {
fn test_gl_tcp_server_access_denied() {
unsafe {
impl_gl_tcp_ipv4_server_access_denied();
}
}
#[test]
#[ignore(cfg(target_os = "linux"))]
#[ignore(cfg(target_os = "win32"))]

View file

@ -361,7 +361,8 @@ pure fn query_from_str(rawquery: &str) -> Query {
return query;
}
pub pure fn query_to_str(query: &Query) -> ~str unsafe {
pub pure fn query_to_str(query: &Query) -> ~str {
unsafe {
// FIXME(#3722): unsafe only because decode_inner does (string) IO
let mut strvec = ~[];
for query.each |kv| {
@ -376,6 +377,7 @@ pub pure fn query_to_str(query: &Query) -> ~str unsafe {
}
return str::connect(strvec, ~"&");
}
}
// returns the scheme and the rest of the url, or a parsing error
pub pure fn get_scheme(rawurl: &str) -> Result<(~str, ~str), ~str> {

View file

@ -131,7 +131,8 @@ impl <T: Ord> PriorityQueue<T> {
// vector over the junk element. This reduces the constant factor
// compared to using swaps, which involves twice as many moves.
priv fn siftup(&mut self, start: uint, pos: uint) unsafe {
priv fn siftup(&mut self, start: uint, pos: uint) {
unsafe {
let mut pos = pos;
let new = move *addr_of(&self.data[pos]);
@ -147,8 +148,10 @@ impl <T: Ord> PriorityQueue<T> {
}
rusti::move_val_init(&mut self.data[pos], move new);
}
}
priv fn siftdown_range(&mut self, pos: uint, end: uint) unsafe {
priv fn siftdown_range(&mut self, pos: uint, end: uint) {
unsafe {
let mut pos = pos;
let start = pos;
let new = move *addr_of(&self.data[pos]);
@ -164,9 +167,11 @@ impl <T: Ord> PriorityQueue<T> {
pos = child;
child = 2 * pos + 1;
}
rusti::move_val_init(&mut self.data[pos], move new);
self.siftup(start, pos);
}
}
priv fn siftdown(&mut self, pos: uint) {
self.siftdown_range(pos, self.len());

View file

@ -55,24 +55,29 @@ pub unsafe fn load_history(file: ~str) -> bool {
/// Print out a prompt and then wait for input and return it
pub unsafe fn read(prompt: ~str) -> Option<~str> {
do str::as_c_str(prompt) |buf| unsafe {
do str::as_c_str(prompt) |buf| {
unsafe {
let line = rustrt::linenoise(buf);
if line.is_null() { None }
else { Some(str::raw::from_c_str(line)) }
}
}
}
pub type CompletionCb = fn~(~str, fn(~str));
fn complete_key(_v: @CompletionCb) {}
/// Bind to the main completion callback
pub unsafe fn complete(cb: CompletionCb) unsafe {
pub unsafe fn complete(cb: CompletionCb) {
unsafe {
task::local_data::local_data_set(complete_key, @(move cb));
extern fn callback(line: *c_char, completions: *()) unsafe {
let cb = copy *task::local_data::local_data_get(complete_key).get();
extern fn callback(line: *c_char, completions: *()) {
unsafe {
let cb = copy *task::local_data::local_data_get(complete_key)
.get();
do cb(str::raw::from_c_str(line)) |suggestion| {
do str::as_c_str(suggestion) |buf| {
@ -80,6 +85,8 @@ pub unsafe fn complete(cb: CompletionCb) unsafe {
}
}
}
}
rustrt::linenoiseSetCompletionCallback(callback);
}
}

View file

@ -831,8 +831,9 @@ pub mod node {
return forest[0];
}
pub fn serialize_node(node: @Node) -> ~str unsafe {
let mut buf = vec::cast_to_mut(vec::from_elem(byte_len(node), 0u8));
pub fn serialize_node(node: @Node) -> ~str {
unsafe {
let mut buf = vec::cast_to_mut(vec::from_elem(byte_len(node), 0));
let mut offset = 0u;//Current position in the buffer
let it = leaf_iterator::start(node);
loop {
@ -854,6 +855,7 @@ pub mod node {
}
return cast::transmute(move buf);
}
}
/**
* Replace a subtree by a single leaf with the same contents.
@ -862,7 +864,8 @@ pub mod node {
*
* This function executes in linear time.
*/
pub fn flatten(node: @Node) -> @Node unsafe {
pub fn flatten(node: @Node) -> @Node {
unsafe {
match (*node) {
Leaf(_) => return node,
Concat(ref x) => {
@ -875,6 +878,7 @@ pub mod node {
}
}
}
}
/**
* Balance a node.
@ -1284,7 +1288,8 @@ mod tests {
node::Empty => return ~"",
node::Content(x) => {
let str = @mut ~"";
fn aux(str: @mut ~str, node: @node::Node) unsafe {
fn aux(str: @mut ~str, node: @node::Node) {
unsafe {
match (*node) {
node::Leaf(x) => {
*str += str::slice(
@ -1297,6 +1302,7 @@ mod tests {
}
}
}
}
aux(str, x);
return *str
}

View file

@ -282,7 +282,8 @@ mod tests {
use core::vec;
#[test]
fn test() unsafe {
fn test() {
unsafe {
type Test = {input: ~str, output: ~[u8]};
fn a_million_letter_a() -> ~str {
@ -375,6 +376,7 @@ mod tests {
sh.reset();
}
}
}
}

View file

@ -49,7 +49,8 @@ pub fn delayed_send<T: Owned>(iotask: IoTask,
let timer_done_ch_ptr = ptr::addr_of(&timer_done_ch);
let timer = uv::ll::timer_t();
let timer_ptr = ptr::addr_of(&timer);
do iotask::interact(iotask) |loop_ptr| unsafe {
do iotask::interact(iotask) |loop_ptr| {
unsafe {
let init_result = uv::ll::timer_init(loop_ptr, timer_ptr);
if (init_result == 0i32) {
let start_result = uv::ll::timer_start(
@ -58,16 +59,17 @@ pub fn delayed_send<T: Owned>(iotask: IoTask,
uv::ll::set_data_for_uv_handle(
timer_ptr,
timer_done_ch_ptr as *libc::c_void);
}
else {
let error_msg = uv::ll::get_last_err_info(loop_ptr);
} else {
let error_msg = uv::ll::get_last_err_info(
loop_ptr);
fail ~"timer::delayed_send() start failed: " +
error_msg;
}
}
else {
} else {
let error_msg = uv::ll::get_last_err_info(loop_ptr);
fail ~"timer::delayed_send() init failed: "+error_msg;
fail ~"timer::delayed_send() init failed: " +
error_msg;
}
}
};
// delayed_send_cb has been processed by libuv
@ -138,28 +140,32 @@ pub fn recv_timeout<T: Copy Owned>(iotask: IoTask,
// INTERNAL API
extern fn delayed_send_cb(handle: *uv::ll::uv_timer_t,
status: libc::c_int) unsafe {
log(debug, fmt!("delayed_send_cb handle %? status %?", handle, status));
status: libc::c_int) {
unsafe {
log(debug,
fmt!("delayed_send_cb handle %? status %?", handle, status));
let timer_done_ch =
*(uv::ll::get_data_for_uv_handle(handle) as *oldcomm::Chan<()>);
let stop_result = uv::ll::timer_stop(handle);
if (stop_result == 0i32) {
oldcomm::send(timer_done_ch, ());
uv::ll::close(handle, delayed_send_close_cb);
}
else {
} else {
let loop_ptr = uv::ll::get_loop_for_uv_handle(handle);
let error_msg = uv::ll::get_last_err_info(loop_ptr);
fail ~"timer::sleep() init failed: "+error_msg;
}
}
}
extern fn delayed_send_close_cb(handle: *uv::ll::uv_timer_t) unsafe {
extern fn delayed_send_close_cb(handle: *uv::ll::uv_timer_t) {
unsafe {
log(debug, fmt!("delayed_send_close_cb handle %?", handle));
let timer_done_ch =
*(uv::ll::get_data_for_uv_handle(handle) as *oldcomm::Chan<()>);
oldcomm::send(timer_done_ch, ());
}
}
#[cfg(test)]
mod test {

View file

@ -51,7 +51,8 @@ impl <K: Eq Ord, V: Eq> TreeMap<K, V>: Eq {
} else {
let mut x = self.iter();
let mut y = other.iter();
for self.len().times unsafe { // unsafe as a purity workaround
for self.len().times {
unsafe { // unsafe as a purity workaround
// ICE: x.next() != y.next()
let (x1, x2) = x.next().unwrap();
@ -61,6 +62,7 @@ impl <K: Eq Ord, V: Eq> TreeMap<K, V>: Eq {
return false
}
}
}
true
}
}

View file

@ -47,9 +47,10 @@ pub fn get() -> IoTask {
}
#[doc(hidden)]
fn get_monitor_task_gl() -> IoTask unsafe {
let monitor_loop_chan_ptr = rustrt::rust_uv_get_kernel_global_chan_ptr();
fn get_monitor_task_gl() -> IoTask {
unsafe {
let monitor_loop_chan_ptr =
rustrt::rust_uv_get_kernel_global_chan_ptr();
debug!("ENTERING global_loop::get() loop chan: %?",
monitor_loop_chan_ptr);
@ -63,7 +64,8 @@ fn get_monitor_task_gl() -> IoTask unsafe {
task::task().sched_mode
(task::SingleThreaded)
.unlinked()
}) |msg_po| unsafe {
}) |msg_po| {
unsafe {
debug!("global monitor task starting");
// As a weak task the runtime will notify us when to exit
@ -89,6 +91,7 @@ fn get_monitor_task_gl() -> IoTask unsafe {
debug!("global monitor task is leaving weakend state");
};
debug!("global monitor task exiting");
}
};
// once we have a chan to the monitor loop, we ask it for
@ -98,6 +101,7 @@ fn get_monitor_task_gl() -> IoTask unsafe {
fetch_ch.recv()
}
}
}
fn spawn_loop() -> IoTask {
let builder = do task::task().add_wrapper |task_body| {
@ -135,29 +139,37 @@ mod test {
use core::ptr;
use core::task;
extern fn simple_timer_close_cb(timer_ptr: *ll::uv_timer_t) unsafe {
extern fn simple_timer_close_cb(timer_ptr: *ll::uv_timer_t) {
unsafe {
let exit_ch_ptr = ll::get_data_for_uv_handle(
timer_ptr as *libc::c_void) as *oldcomm::Chan<bool>;
let exit_ch = *exit_ch_ptr;
oldcomm::send(exit_ch, true);
log(debug, fmt!("EXIT_CH_PTR simple_timer_close_cb exit_ch_ptr: %?",
log(debug,
fmt!("EXIT_CH_PTR simple_timer_close_cb exit_ch_ptr: %?",
exit_ch_ptr));
}
}
extern fn simple_timer_cb(timer_ptr: *ll::uv_timer_t,
_status: libc::c_int) unsafe {
_status: libc::c_int) {
unsafe {
log(debug, ~"in simple timer cb");
ll::timer_stop(timer_ptr);
let hl_loop = get_gl();
do iotask::interact(hl_loop) |_loop_ptr| unsafe {
do iotask::interact(hl_loop) |_loop_ptr| {
unsafe {
log(debug, ~"closing timer");
ll::close(timer_ptr, simple_timer_close_cb);
log(debug, ~"about to deref exit_ch_ptr");
log(debug, ~"after msg sent on deref'd exit_ch");
}
};
log(debug, ~"exiting simple timer cb");
}
}
fn impl_uv_hl_simple_timer(iotask: IoTask) unsafe {
fn impl_uv_hl_simple_timer(iotask: IoTask) {
unsafe {
let exit_po = oldcomm::Port::<bool>();
let exit_ch = oldcomm::Chan(&exit_po);
let exit_ch_ptr = ptr::addr_of(&exit_ch);
@ -165,31 +177,35 @@ mod test {
exit_ch_ptr));
let timer_handle = ll::timer_t();
let timer_ptr = ptr::addr_of(&timer_handle);
do iotask::interact(iotask) |loop_ptr| unsafe {
do iotask::interact(iotask) |loop_ptr| {
unsafe {
log(debug, ~"user code inside interact loop!!!");
let init_status = ll::timer_init(loop_ptr, timer_ptr);
if(init_status == 0i32) {
ll::set_data_for_uv_handle(
timer_ptr as *libc::c_void,
exit_ch_ptr as *libc::c_void);
let start_status = ll::timer_start(timer_ptr, simple_timer_cb,
1u, 0u);
if(start_status == 0i32) {
}
else {
let start_status = ll::timer_start(timer_ptr,
simple_timer_cb,
1u,
0u);
if start_status != 0 {
fail ~"failure on ll::timer_start()";
}
}
else {
} else {
fail ~"failure on ll::timer_init()";
}
}
};
oldcomm::recv(exit_po);
log(debug, ~"global_loop timer test: msg recv on exit_po, done..");
log(debug,
~"global_loop timer test: msg recv on exit_po, done..");
}
}
#[test]
fn test_gl_uv_global_loop_high_level_global_timer() unsafe {
fn test_gl_uv_global_loop_high_level_global_timer() {
unsafe {
let hl_loop = get_gl();
let exit_po = oldcomm::Port::<()>();
let exit_ch = oldcomm::Chan(&exit_po);
@ -200,12 +216,14 @@ mod test {
impl_uv_hl_simple_timer(hl_loop);
oldcomm::recv(exit_po);
}
}
// keeping this test ignored until some kind of stress-test-harness
// is set up for the build bots
#[test]
#[ignore]
fn test_stress_gl_uv_global_loop_high_level_global_timer() unsafe {
fn test_stress_gl_uv_global_loop_high_level_global_timer() {
unsafe {
let hl_loop = get_gl();
let exit_po = oldcomm::Port::<()>();
let exit_ch = oldcomm::Chan(&exit_po);
@ -219,7 +237,9 @@ mod test {
for iter::repeat(cycles) {
oldcomm::recv(exit_po);
};
log(debug, ~"test_stress_gl_uv_global_loop_high_level_global_timer"+
log(debug,
~"test_stress_gl_uv_global_loop_high_level_global_timer"+
~" exiting sucessfully!");
}
}
}

View file

@ -83,9 +83,11 @@ pub unsafe fn interact(iotask: IoTask,
* async handle and do a sanity check to make sure that all other handles are
* closed, causing a failure otherwise.
*/
pub fn exit(iotask: IoTask) unsafe {
pub fn exit(iotask: IoTask) {
unsafe {
send_msg(iotask, TeardownLoop);
}
}
// INTERNAL API
@ -96,8 +98,8 @@ enum IoTaskMsg {
}
/// Run the loop and begin handling messages
fn run_loop(iotask_ch: Chan<IoTask>) unsafe {
fn run_loop(iotask_ch: Chan<IoTask>) {
unsafe {
let loop_ptr = ll::loop_new();
// set up the special async handle we'll use to allow multi-task
@ -129,6 +131,7 @@ fn run_loop(iotask_ch: Chan<IoTask>) unsafe {
log(debug, ~"uv loop ended");
ll::loop_delete(loop_ptr);
}
}
// data that lives for the lifetime of the high-evel oo
type IoTaskLoopData = {
@ -136,21 +139,23 @@ type IoTaskLoopData = {
msg_po: Port<IoTaskMsg>
};
fn send_msg(iotask: IoTask,
msg: IoTaskMsg) unsafe {
fn send_msg(iotask: IoTask, msg: IoTaskMsg) {
unsafe {
iotask.op_chan.send(move msg);
ll::async_send(iotask.async_handle);
}
}
/// Dispatch all pending messages
extern fn wake_up_cb(async_handle: *ll::uv_async_t,
status: int) unsafe {
status: int) {
unsafe {
log(debug, fmt!("wake_up_cb extern.. handle: %? status: %?",
async_handle, status));
let loop_ptr = ll::get_loop_for_uv_handle(async_handle);
let data = ll::get_data_for_uv_handle(async_handle) as *IoTaskLoopData;
let data = ll::get_data_for_uv_handle(async_handle)
as *IoTaskLoopData;
let msg_po = (*data).msg_po;
while msg_po.peek() {
@ -160,20 +165,26 @@ extern fn wake_up_cb(async_handle: *ll::uv_async_t,
}
}
}
}
fn begin_teardown(data: *IoTaskLoopData) unsafe {
fn begin_teardown(data: *IoTaskLoopData) {
unsafe {
log(debug, ~"iotask begin_teardown() called, close async_handle");
let async_handle = (*data).async_handle;
ll::close(async_handle as *c_void, tear_down_close_cb);
}
}
extern fn tear_down_close_cb(handle: *ll::uv_async_t) unsafe {
extern fn tear_down_close_cb(handle: *ll::uv_async_t) {
unsafe {
let loop_ptr = ll::get_loop_for_uv_handle(handle);
let loop_refs = ll::loop_refcount(loop_ptr);
log(debug, fmt!("tear_down_close_cb called, closing handle at %? refs %?",
log(debug,
fmt!("tear_down_close_cb called, closing handle at %? refs %?",
handle, loop_refs));
assert loop_refs == 1i32;
}
}
#[cfg(test)]
mod test {
@ -188,22 +199,27 @@ mod test {
use core::ptr;
use core::task;
extern fn async_close_cb(handle: *ll::uv_async_t) unsafe {
extern fn async_close_cb(handle: *ll::uv_async_t) {
unsafe {
log(debug, fmt!("async_close_cb handle %?", handle));
let exit_ch = (*(ll::get_data_for_uv_handle(handle)
as *AhData)).exit_ch;
oldcomm::send(exit_ch, ());
}
extern fn async_handle_cb(handle: *ll::uv_async_t, status: libc::c_int)
}
extern fn async_handle_cb(handle: *ll::uv_async_t, status: libc::c_int) {
unsafe {
log(debug, fmt!("async_handle_cb handle %? status %?",handle,status));
log(debug,
fmt!("async_handle_cb handle %? status %?",handle,status));
ll::close(handle, async_close_cb);
}
}
type AhData = {
iotask: IoTask,
exit_ch: oldcomm::Chan<()>
};
fn impl_uv_iotask_async(iotask: IoTask) unsafe {
fn impl_uv_iotask_async(iotask: IoTask) {
unsafe {
let async_handle = ll::async_t();
let ah_ptr = ptr::addr_of(&async_handle);
let exit_po = oldcomm::Port::<()>();
@ -213,13 +229,17 @@ mod test {
exit_ch: exit_ch
};
let ah_data_ptr = ptr::addr_of(&ah_data);
do interact(iotask) |loop_ptr| unsafe {
do interact(iotask) |loop_ptr| {
unsafe {
ll::async_init(loop_ptr, ah_ptr, async_handle_cb);
ll::set_data_for_uv_handle(ah_ptr, ah_data_ptr as *libc::c_void);
ll::set_data_for_uv_handle(ah_ptr,
ah_data_ptr as *libc::c_void);
ll::async_send(ah_ptr);
}
};
oldcomm::recv(exit_po);
}
}
// this fn documents the bear minimum neccesary to roll your own
// high_level_loop
@ -233,9 +253,11 @@ mod test {
return oldcomm::recv(iotask_port);
}
extern fn lifetime_handle_close(handle: *libc::c_void) unsafe {
extern fn lifetime_handle_close(handle: *libc::c_void) {
unsafe {
log(debug, fmt!("lifetime_handle_close ptr %?", handle));
}
}
extern fn lifetime_async_callback(handle: *libc::c_void,
status: libc::c_int) {
@ -244,17 +266,18 @@ mod test {
}
#[test]
fn test_uv_iotask_async() unsafe {
fn test_uv_iotask_async() {
unsafe {
let exit_po = oldcomm::Port::<()>();
let exit_ch = oldcomm::Chan(&exit_po);
let iotask = spawn_test_loop(exit_ch);
// using this handle to manage the lifetime of the high_level_loop,
// as it will exit the first time one of the impl_uv_hl_async() is
// cleaned up with no one ref'd handles on the loop (Which can happen
// under race-condition type situations.. this ensures that the loop
// lives until, at least, all of the impl_uv_hl_async() runs have been
// called, at least.
// using this handle to manage the lifetime of the
// high_level_loop, as it will exit the first time one of the
// impl_uv_hl_async() is cleaned up with no one ref'd handles on
// the loop (Which can happen under race-condition type
// situations.. this ensures that the loop lives until, at least,
// all of the impl_uv_hl_async() runs have been called, at least.
let work_exit_po = oldcomm::Port::<()>();
let work_exit_ch = oldcomm::Chan(&work_exit_po);
for iter::repeat(7u) {
@ -272,3 +295,4 @@ mod test {
log(debug, ~"after recv on exit_po.. exiting..");
}
}
}

View file

@ -1103,7 +1103,8 @@ pub mod test {
extern fn on_alloc_cb(handle: *libc::c_void,
suggested_size: libc::size_t)
-> uv_buf_t unsafe {
-> uv_buf_t {
unsafe {
log(debug, ~"on_alloc_cb!");
let char_ptr = malloc_buf_base_of(suggested_size);
log(debug, fmt!("on_alloc_cb h: %? char_ptr: %u sugsize: %u",
@ -1112,10 +1113,12 @@ pub mod test {
suggested_size as uint));
return buf_init(char_ptr, suggested_size as uint);
}
}
extern fn on_read_cb(stream: *uv_stream_t,
nread: libc::ssize_t,
++buf: uv_buf_t) unsafe {
++buf: uv_buf_t) {
unsafe {
let nread = nread as int;
log(debug, fmt!("CLIENT entering on_read_cb nred: %d",
nread));
@ -1146,21 +1149,28 @@ pub mod test {
free_base_of_buf(buf);
log(debug, ~"CLIENT exiting on_read_cb");
}
}
extern fn on_write_complete_cb(write_req: *uv_write_t,
status: libc::c_int) unsafe {
log(debug, fmt!("CLIENT beginning on_write_complete_cb status: %d",
status: libc::c_int) {
unsafe {
log(debug,
fmt!("CLIENT beginning on_write_complete_cb status: %d",
status as int));
let stream = get_stream_handle_from_write_req(write_req);
log(debug, fmt!("CLIENT on_write_complete_cb: tcp:%d write_handle:%d",
log(debug,
fmt!("CLIENT on_write_complete_cb: tcp:%d write_handle:%d",
stream as int, write_req as int));
let result = read_start(stream, on_alloc_cb, on_read_cb);
log(debug, fmt!("CLIENT ending on_write_complete_cb .. status: %d",
log(debug,
fmt!("CLIENT ending on_write_complete_cb .. status: %d",
result as int));
}
}
extern fn on_connect_cb(connect_req_ptr: *uv_connect_t,
status: libc::c_int) unsafe {
status: libc::c_int) {
unsafe {
log(debug, fmt!("beginning on_connect_cb .. status: %d",
status as int));
let stream =
@ -1189,9 +1199,11 @@ pub mod test {
}
log(debug, ~"finishing on_connect_cb");
}
}
fn impl_uv_tcp_request(ip: &str, port: int, req_str: &str,
client_chan: *oldcomm::Chan<~str>) unsafe {
client_chan: *oldcomm::Chan<~str>) {
unsafe {
let test_loop = loop_new();
let tcp_handle = tcp_t();
let tcp_handle_ptr = ptr::addr_of(&tcp_handle);
@ -1261,15 +1273,17 @@ pub mod test {
assert false;
}
loop_delete(test_loop);
}
}
extern fn server_after_close_cb(handle: *libc::c_void) unsafe {
log(debug, fmt!("SERVER server stream closed, should exit.. h: %?",
extern fn server_after_close_cb(handle: *libc::c_void) {
unsafe {
log(debug, fmt!("SERVER server stream closed, should exit. h: %?",
handle));
}
}
extern fn client_stream_after_close_cb(handle: *libc::c_void)
extern fn client_stream_after_close_cb(handle: *libc::c_void) {
unsafe {
log(debug,
~"SERVER: closed client stream, now closing server stream");
@ -1279,18 +1293,22 @@ pub mod test {
close((*client_data).server as *libc::c_void,
server_after_close_cb);
}
}
extern fn after_server_resp_write(req: *uv_write_t) unsafe {
extern fn after_server_resp_write(req: *uv_write_t) {
unsafe {
let client_stream_ptr =
get_stream_handle_from_write_req(req);
log(debug, ~"SERVER: resp sent... closing client stream");
close(client_stream_ptr as *libc::c_void,
client_stream_after_close_cb)
}
}
extern fn on_server_read_cb(client_stream_ptr: *uv_stream_t,
nread: libc::ssize_t,
++buf: uv_buf_t) unsafe {
++buf: uv_buf_t) {
unsafe {
let nread = nread as int;
if (nread > 0) {
// we have data
@ -1348,10 +1366,12 @@ pub mod test {
free_base_of_buf(buf);
log(debug, ~"SERVER exiting on_read_cb");
}
}
extern fn server_connection_cb(server_stream_ptr:
*uv_stream_t,
status: libc::c_int) unsafe {
status: libc::c_int) {
unsafe {
log(debug, ~"client connecting!");
let test_loop = get_loop_for_uv_handle(
server_stream_ptr as *libc::c_void);
@ -1402,6 +1422,7 @@ pub mod test {
assert false;
}
}
}
type tcp_server_data = {
client: *uv_tcp_t,
@ -1422,7 +1443,8 @@ pub mod test {
}
extern fn continue_async_cb(async_handle: *uv_async_t,
status: libc::c_int) unsafe {
status: libc::c_int) {
unsafe {
// once we're in the body of this callback,
// the tcp server's loop is set up, so we
// can continue on to let the tcp client
@ -1434,13 +1456,15 @@ pub mod test {
oldcomm::send(continue_chan, should_continue);
close(async_handle as *libc::c_void, async_close_cb);
}
}
fn impl_uv_tcp_server(server_ip: &str,
server_port: int,
+kill_server_msg: ~str,
+server_resp_msg: ~str,
server_chan: *oldcomm::Chan<~str>,
continue_chan: *oldcomm::Chan<bool>) unsafe {
continue_chan: *oldcomm::Chan<bool>) {
unsafe {
let test_loop = loop_new();
let tcp_server = tcp_t();
let tcp_server_ptr = ptr::addr_of(&tcp_server);
@ -1536,10 +1560,12 @@ pub mod test {
}
loop_delete(test_loop);
}
}
// this is the impl for a test that is (maybe) ran on a
// per-platform/arch basis below
fn impl_uv_tcp_server_and_request() unsafe {
fn impl_uv_tcp_server_and_request() {
unsafe {
let bind_ip = ~"0.0.0.0";
let request_ip = ~"127.0.0.1";
let port = 8886;
@ -1579,6 +1605,7 @@ pub mod test {
assert str::contains(msg_from_client, kill_server_msg);
assert str::contains(msg_from_server, server_resp_msg);
}
}
// FIXME don't run on fbsd or linux 32 bit(#2064)
#[cfg(target_os="win32")]
@ -1590,21 +1617,25 @@ pub mod test {
pub mod impl64 {
use uv_ll::test::*;
#[test]
pub fn test_uv_ll_tcp_server_and_request() unsafe {
pub fn test_uv_ll_tcp_server_and_request() {
unsafe {
impl_uv_tcp_server_and_request();
}
}
}
#[cfg(target_arch="x86")]
#[cfg(target_arch="arm")]
pub mod impl32 {
use uv_ll::test::*;
#[test]
#[ignore(cfg(target_os = "linux"))]
pub fn test_uv_ll_tcp_server_and_request() unsafe {
pub fn test_uv_ll_tcp_server_and_request() {
unsafe {
impl_uv_tcp_server_and_request();
}
}
}
}
// struct size tests
#[test]

View file

@ -208,7 +208,8 @@ pub impl FileMap {
self.lines.push(pos);
}
pub fn get_line(&self, line: int) -> ~str unsafe {
pub fn get_line(&self, line: int) -> ~str {
unsafe {
let begin: BytePos = self.lines[line] - self.start_pos;
let begin = begin.to_uint();
let end = match str::find_char_from(*self.src, '\n', begin) {
@ -217,6 +218,7 @@ pub impl FileMap {
};
str::slice(*self.src, begin, end)
}
}
pub fn record_multibyte_char(&self, pos: BytePos, bytes: uint) {
assert bytes >=2 && bytes <= 4;

View file

@ -157,12 +157,14 @@ fn byte_offset(rdr: string_reader) -> BytePos {
(rdr.pos - rdr.filemap.start_pos)
}
fn get_str_from(rdr: string_reader, start: BytePos) -> ~str unsafe {
fn get_str_from(rdr: string_reader, start: BytePos) -> ~str {
unsafe {
// I'm pretty skeptical about this subtraction. What if there's a
// multi-byte character before the mark?
return str::slice(*rdr.src, start.to_uint() - 1u,
byte_offset(rdr).to_uint() - 1u);
}
}
fn bump(rdr: string_reader) {
rdr.last_pos = rdr.pos;

View file

@ -44,7 +44,8 @@ pub enum ObsoleteSyntax {
ObsoletePrivSection,
ObsoleteModeInFnType,
ObsoleteMoveInit,
ObsoleteBinaryMove
ObsoleteBinaryMove,
ObsoleteUnsafeBlock
}
impl ObsoleteSyntax : cmp::Eq {
@ -118,6 +119,10 @@ impl Parser {
ObsoleteBinaryMove => (
"binary move",
"Write `foo = move bar` instead"
),
ObsoleteUnsafeBlock => (
"non-standalone unsafe block",
"use an inner `unsafe { ... }` block instead"
)
};

View file

@ -69,6 +69,7 @@ use parse::obsolete::{ObsoleteLet, ObsoleteFieldTerminator};
use parse::obsolete::{ObsoleteMoveInit, ObsoleteBinaryMove};
use parse::obsolete::{ObsoleteStructCtor, ObsoleteWith, ObsoleteClassMethod};
use parse::obsolete::{ObsoleteSyntax, ObsoleteLowerCaseKindBounds};
use parse::obsolete::{ObsoleteUnsafeBlock};
use parse::prec::{as_prec, token_to_binop};
use parse::token::{can_begin_expr, is_ident, is_ident_or_path};
use parse::token::{is_plain_ident, INTERPOLATED, special_idents};
@ -2336,12 +2337,13 @@ impl Parser {
}
let lo = self.span.lo;
let us = self.eat_keyword(~"unsafe");
if self.eat_keyword(~"unsafe") {
self.obsolete(copy self.span, ObsoleteUnsafeBlock);
}
self.expect(token::LBRACE);
let {inner: move inner, next: move next} =
maybe_parse_inner_attrs_and_next(self, parse_attrs);
let blk_check_mode = if us { unsafe_blk } else { default_blk };
return (inner, self.parse_block_tail_(lo, blk_check_mode, next));
return (inner, self.parse_block_tail_(lo, default_blk, next));
}
fn parse_block_no_value() -> blk {

View file

@ -21,17 +21,21 @@ fn recurse() {
struct r {
recursed: *mut bool,
drop unsafe {
drop {
unsafe {
if !*(self.recursed) {
*(self.recursed) = true;
recurse();
}
}
}
}
fn r(recursed: *mut bool) -> r unsafe {
fn r(recursed: *mut bool) -> r {
unsafe {
r { recursed: recursed }
}
}
fn main() {
let mut recursed = false;

View file

@ -32,7 +32,8 @@ fn r(v: *int) -> r {
}
}
fn main() unsafe {
fn main() {
unsafe {
let i1 = ~0;
let i1p = cast::reinterpret_cast(&i1);
cast::forget(move i1);
@ -40,3 +41,4 @@ fn main() unsafe {
failfn();
log(error, x);
}
}

View file

@ -62,7 +62,8 @@ fn test_box() {
assert (@10 == @10);
}
fn test_ptr() unsafe {
fn test_ptr() {
unsafe {
let p1: *u8 = ::core::cast::reinterpret_cast(&0);
let p2: *u8 = ::core::cast::reinterpret_cast(&0);
let p3: *u8 = ::core::cast::reinterpret_cast(&1);
@ -76,6 +77,7 @@ fn test_ptr() unsafe {
assert p1 <= p2;
assert p1 >= p2;
}
}
#[abi = "cdecl"]
#[nolink]

View file

@ -19,11 +19,13 @@ extern mod libc {
fn my_strlen(str: *u8) -> uint;
}
fn strlen(str: ~str) -> uint unsafe {
fn strlen(str: ~str) -> uint {
unsafe {
// C string is terminated with a zero
let bytes = str::to_bytes(str) + ~[0u8];
return libc::my_strlen(vec::raw::to_ptr(bytes));
}
}
fn main() {
let len = strlen(~"Rust");

View file

@ -14,9 +14,11 @@ use core::cast;
use core::libc::{c_double, c_int};
use core::f64::*;
fn to_c_int(v: &mut int) -> &mut c_int unsafe {
fn to_c_int(v: &mut int) -> &mut c_int {
unsafe {
cast::reinterpret_cast(&v)
}
}
fn lgamma(n: c_double, value: &mut int) -> c_double {
return m::lgamma(n, to_c_int(value));

View file

@ -34,7 +34,8 @@ pub mod pipes {
mut payload: Option<T>
};
pub fn packet<T: Owned>() -> *packet<T> unsafe {
pub fn packet<T: Owned>() -> *packet<T> {
unsafe {
let p: *packet<T> = cast::transmute(~{
mut state: empty,
mut blocked_task: None::<task::Task>,
@ -42,6 +43,7 @@ pub mod pipes {
});
p
}
}
#[abi = "rust-intrinsic"]
mod rusti {
@ -218,7 +220,8 @@ pub mod pingpong {
pub enum ping = ::pipes::send_packet<pong>;
pub enum pong = ::pipes::send_packet<ping>;
pub fn liberate_ping(-p: ping) -> ::pipes::send_packet<pong> unsafe {
pub fn liberate_ping(-p: ping) -> ::pipes::send_packet<pong> {
unsafe {
let addr : *::pipes::send_packet<pong> = match &p {
&ping(ref x) => { cast::transmute(ptr::addr_of(x)) }
};
@ -226,8 +229,10 @@ pub mod pingpong {
cast::forget(move p);
move liberated_value
}
}
pub fn liberate_pong(-p: pong) -> ::pipes::send_packet<ping> unsafe {
pub fn liberate_pong(-p: pong) -> ::pipes::send_packet<ping> {
unsafe {
let addr : *::pipes::send_packet<ping> = match &p {
&pong(ref x) => { cast::transmute(ptr::addr_of(x)) }
};
@ -235,6 +240,7 @@ pub mod pingpong {
cast::forget(move p);
move liberated_value
}
}
pub fn init() -> (client::ping, server::ping) {
::pipes::entangle()

View file

@ -14,6 +14,8 @@
extern mod issue_2723_a;
use issue_2723_a::*;
fn main() unsafe {
fn main() {
unsafe {
f(~[2]);
}
}

View file

@ -1,19 +0,0 @@
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Tests that "loop unsafe" isn't misparsed.
fn main() {
loop unsafe {
io::println("Hello world!");
return ();
}
}

View file

@ -23,10 +23,12 @@ type ccx = {
x: int
};
fn alloc(_bcx : &arena) -> &bcx unsafe {
fn alloc(_bcx : &arena) -> &bcx {
unsafe {
return cast::reinterpret_cast(
&libc::malloc(sys::size_of::<bcx/&blk>() as libc::size_t));
}
}
fn h(bcx : &bcx) -> &bcx {
return alloc(bcx.fcx.arena);

View file

@ -26,18 +26,21 @@ impl r : Drop {
}
}
fn r(v: *int) -> r unsafe {
fn r(v: *int) -> r {
unsafe {
r {
v: v
}
}
}
enum t = {
mut next: Option<@t>,
r: r
};
fn main() unsafe {
fn main() {
unsafe {
let i1 = ~0;
let i1p = cast::reinterpret_cast(&i1);
cast::forget(move i1);
@ -75,3 +78,4 @@ fn main() unsafe {
x1.next = Some(x2);
x2.next = Some(x1);
}
}

View file

@ -39,7 +39,8 @@ enum t = {
r: r
};
fn main() unsafe {
fn main() {
unsafe {
let i1 = ~0xA;
let i1p = cast::reinterpret_cast(&i1);
cast::forget(move i1);
@ -61,3 +62,4 @@ fn main() unsafe {
x1.next = Some(x2);
x2.next = Some(x1);
}
}

View file

@ -33,20 +33,23 @@ impl r : Drop {
}
}
fn r(v: u, w: int, _x: *int) -> r unsafe {
fn r(v: u, w: int, _x: *int) -> r {
unsafe {
r {
v: v,
w: w,
x: cast::reinterpret_cast(&0)
}
}
}
enum t = {
mut next: Option<@t>,
r: r
};
fn main() unsafe {
fn main() {
unsafe {
let i1 = ~0xA;
let i1p = cast::reinterpret_cast(&i1);
cast::forget(move i1);
@ -68,3 +71,4 @@ fn main() unsafe {
x1.next = Some(x2);
x2.next = Some(x1);
}
}

View file

@ -24,7 +24,8 @@ extern mod rustrt {
fn start_task(id: task_id, f: closure);
}
fn main() unsafe {
fn main() {
unsafe {
let po = oldcomm::Port();
let ch = oldcomm::Chan(&po);
let parent_sched_id = rustrt::rust_get_sched_id();
@ -46,3 +47,4 @@ fn main() unsafe {
cast::forget(move f);
oldcomm::recv(po);
}
}

View file

@ -37,7 +37,7 @@ fn main() {
test_color(orange, 4, ~"orange");
}
fn test_color(color: color, val: int, name: ~str) unsafe {
fn test_color(color: color, val: int, name: ~str) {
//assert unsafe::reinterpret_cast(color) == val;
assert color as int == val;
assert color as float == val as float;

View file

@ -13,6 +13,10 @@
// in that type gets resolved.
extern mod std;
fn null<T>() -> *T unsafe { cast::reinterpret_cast(&0) }
fn null<T>() -> *T {
unsafe {
cast::reinterpret_cast(&0)
}
}
fn main() { null::<int>(); }

View file

@ -8,7 +8,8 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn main() unsafe {
fn main() {
unsafe {
let i = ~@1;
let j = ~@2;
let rc1 = sys::refcount(*i);
@ -17,3 +18,4 @@ fn main() unsafe {
error!("rc1: %u rc2: %u", rc1, rc2);
assert rc1 + 1u == rc2;
}
}

View file

@ -20,9 +20,5 @@ fn g() {
}
}
fn h() unsafe {
f();
}
fn main() {
}