<commit_before>use std::collections::BTreeMap;
use std::str::Split;

use clap::ArgMatches;
use toml::Value;

use libimagstore::store::EntryHeader;
use libimagutil::key_value_split::IntoKeyValue;

pub fn build_toml_header(matches: &ArgMatches, header: EntryHeader) -> EntryHeader {
    debug!("Building header from cli spec");
    if let Some(headerspecs) = matches.values_of("header") {
        let mut main = BTreeMap::new();
        for tpl in headerspecs.into_iter().filter_map(|hs| String::from(hs).into_kv()) {
            let (key, value) = tpl.into();
            debug!("Splitting: {:?}", key);
            let mut split = key.split(".");
            let current = split.next();
            if current.is_some() {
                insert_key_into(String::from(current.unwrap()), &mut split, value, &mut main);
            }
        }
    }
    header
}

fn insert_key_into(current: String,
                   rest_path: &mut Split<&str>,
                   value: String,
                   map: &mut BTreeMap<String, Value>) {
    let next = rest_path.next();

    if next.is_none() {
        map.insert(current, parse_value(value));
    } else {
        if map.contains_key(&current) {
            match map.get_mut(&current).unwrap() {
                &mut Value::Table(ref mut t) => {
                    insert_key_into(String::from(next.unwrap()), rest_path, value, t);
                },
                _ => unreachable!(),
            }
        } else {
            let mut submap = BTreeMap::new();
            insert_key_into(String::from(next.unwrap()), rest_path, value, &mut submap);
            map.insert(current, Value::Table(submap));
        }
    }
}

fn parse_value(value: String) -> Value {
    fn is_ary(v: &String) -> bool {
        v.chars().next() == Some('[') && v.chars().last() == Some(']') && v.len() >= 3
    }

    debug!("Building value out of: {:?}", value);
    if value == "true" {
        Value::Boolean(true)
    } else if value == "false" {
        Value::Boolean(false)
    } else if is_ary(&value) {
        let sub = &value[1..(value.len()-1)];
        Value::Array(sub.split(",").map(|v| parse_value(String::from(v))).collect())
    } else {
        Value::String(value)
    }
}

<commit_msg>Add store entry path builder helper<commit_after>use std::collections::BTreeMap;
use std::path::PathBuf;
use std::str::Split;

use clap::ArgMatches;
use toml::Value;

use libimagstore::store::EntryHeader;
use libimagrt::runtime::Runtime;
use libimagutil::key_value_split::IntoKeyValue;

pub fn build_entry_path(rt: &Runtime, path_elem: &str) -> PathBuf {
    debug!("Building path...");
    let mut path = rt.store().path().clone();

    if path_elem.chars().next() == Some('/') {
        path.push(&path_elem[1..path_elem.len()]);
    } else {
        path.push(path_elem);
    }

    path
}

pub fn build_toml_header(matches: &ArgMatches, header: EntryHeader) -> EntryHeader {
    debug!("Building header from cli spec");
    if let Some(headerspecs) = matches.values_of("header") {
        let mut main = BTreeMap::new();
        for tpl in headerspecs.into_iter().filter_map(|hs| String::from(hs).into_kv()) {
            let (key, value) = tpl.into();
            debug!("Splitting: {:?}", key);
            let mut split = key.split(".");
            let current = split.next();
            if current.is_some() {
                insert_key_into(String::from(current.unwrap()), &mut split, value, &mut main);
            }
        }
    }
    header
}

fn insert_key_into(current: String,
                   rest_path: &mut Split<&str>,
                   value: String,
                   map: &mut BTreeMap<String, Value>) {
    let next = rest_path.next();

    if next.is_none() {
        map.insert(current, parse_value(value));
    } else {
        if map.contains_key(&current) {
            match map.get_mut(&current).unwrap() {
                &mut Value::Table(ref mut t) => {
                    insert_key_into(String::from(next.unwrap()), rest_path, value, t);
                },
                _ => unreachable!(),
            }
        } else {
            let mut submap = BTreeMap::new();
            insert_key_into(String::from(next.unwrap()), rest_path, value, &mut submap);
            map.insert(current, Value::Table(submap));
        }
    }
}

fn parse_value(value: String) -> Value {
    fn is_ary(v: &String) -> bool {
        v.chars().next() == Some('[') && v.chars().last() == Some(']') && v.len() >= 3
    }

    debug!("Building value out of: {:?}", value);
    if value == "true" {
        Value::Boolean(true)
    } else if value == "false" {
        Value::Boolean(false)
    } else if is_ary(&value) {
        let sub = &value[1..(value.len()-1)];
        Value::Array(sub.split(",").map(|v| parse_value(String::from(v))).collect())
    } else {
        Value::String(value)
    }
}

<|endoftext|>


<commit_before><commit_msg>Only compile Sosemanuk tests in test builds<commit_after><|endoftext|>


<commit_before>use std::vec::Vec;
use std::io::BufReader;
use super::types::*;
use std::ptr::copy_nonoverlapping_memory;
use texture::Texture;
use gl;

pub struct Image {
    width: uint,
    height: uint,
    x_offset: int,
    y_offset: int,
    pixels: Vec<u16>,
}

macro_rules! io_try(
    ($e:expr) => (try!($e.map_err(|e| String::from_str(e.desc))))
)

impl Image {
    pub fn new(width: uint, height: uint) -> Image {
        Image { width: width,
                height: height,
                x_offset: 0,
                y_offset: 0,
                pixels: Vec::from_elem(width * height, 0xff00) }
    }

    pub fn new_from_header(header: &WadTextureHeader) -> Image {
        Image::new(header.width as uint, header.height as uint)
    }

    pub fn from_buffer(buffer: &[u8]) -> Image {
        let mut reader = BufReader::new(buffer);

        let width = reader.read_le_u16().unwrap() as uint;
        let height = reader.read_le_u16().unwrap() as uint;
        let x_offset = reader.read_le_i16().unwrap() as int;
        let y_offset = reader.read_le_i16().unwrap() as int;

        let mut pixels = Vec::from_elem(width * height, -1);
        // Sorry for the messy/unsafe code, but the array bounds checks in this
        // tight loop make it 6x slower.
        for i_column in range(0, width as int) { unsafe {
            // Each column is defined as a number of vertical `runs' which are
            // defined starting at `offset' in the buffer.
            let offset = reader.read_le_u32().unwrap() as int;
            let mut src_ptr = buffer.as_ptr().offset(offset);
            'this_column: loop {
                // The first byte contains the vertical coordinate of the run's
                // start.
                let row_start = *src_ptr as int; src_ptr = src_ptr.offset(1);

                // Pointer to the beginning of the run in `pixels'.
                let mut dest_ptr = pixels
                    .as_mut_ptr().offset(row_start * width as int + i_column);

                // The special value of 255 means this is the last run in the
                // column, so move on to the next one.
                if row_start == 255 { break 'this_column; }

                // The second byte is the length of this run. Skip an additional
                // byte which is ignored for some reason.
                let run_length = *src_ptr as int; src_ptr = src_ptr.offset(2);

                let src_end = src_ptr.offset(run_length);  // Ptr to end of run.
                while src_ptr < src_end {
                    // Copy one byte converting it into an opaque pixels (high
                    // bits are zero) and advance the pointers.
                    *dest_ptr = *src_ptr as u16;
                    dest_ptr = dest_ptr.offset(width as int);
                    src_ptr = src_ptr.offset(1);
                }
                // And another ignored byte after the run.
                src_ptr = src_ptr.offset(1);
            }
        }}
        let pixels = pixels;

        Image { width: width,
                height: height,
                x_offset: x_offset,
                y_offset: y_offset,
                pixels: pixels }
    }

    #[allow(unsigned_negate)]
    pub fn blit(&mut self, source: &Image, x_offset: int, y_offset: int,
                ignore_transparency: bool) {
        // Figure out the region in source which is not out of bounds when
        // copied into self.
        let y_start = if y_offset < 0 { -y_offset as uint } else { 0 };
        let x_start = if x_offset < 0 { -x_offset as uint } else { 0 };
        let y_end = if self.height as int > source.height as int + y_offset {
            source.height
        } else {
            self.height - y_offset as uint
        };
        let x_end = if self.width as int > source.width as int + x_offset {
            source.width
        } else {
            self.width - x_offset as uint
        };

        if ignore_transparency {
            // If we don't care about transparency we can memcpy row by row.
            let src_pitch = source.width as int;
            let dest_pitch = self.width as int;
            let copy_width = x_end - x_start;
            let copy_height = (y_end - y_start) as int;
            let (x_start, y_start) = (x_start as int, y_start as int);
            unsafe {
                let mut src_ptr = source.pixels.as_ptr().offset(
                    x_start + y_start * src_pitch);
                let mut dest_ptr = self.pixels.as_mut_ptr().offset(
                    x_start + x_offset + (y_start + y_offset) * dest_pitch);

                let src_end = src_ptr.offset(copy_height * src_pitch);
                while src_ptr < src_end {
                    copy_nonoverlapping_memory(dest_ptr, src_ptr, copy_width);
                    src_ptr = src_ptr.offset(src_pitch);
                    dest_ptr = dest_ptr.offset(dest_pitch);
                }
            }
        } else {
            // Only copy pixels whose high bits are not set.
            let dest_ptr = self.pixels.as_mut_ptr();
            let src_ptr = source.pixels.as_ptr();
            for src_y in range(y_start, y_end) {
                let dest_y = (src_y as int + y_offset) as uint;
                for src_x in range(x_start, x_end) {
                    let dest_x = (src_x as int + x_offset) as uint;

                    let (dest_x, dest_y) = (dest_x as uint, dest_y as uint);
                    let dest_index = (dest_x + dest_y * self.width) as int;
                    let src_index = (src_x + src_y * source.width) as int;

                    unsafe {
                        // `Blending' is a simple copy/no copy, but using bit
                        // ops we can avoid branching.
                        let src_pixel = *src_ptr.offset(src_index);
                        let dest_pixel = dest_ptr.offset(dest_index);
                        let blend = (-(src_pixel >> 15)) as u16;
                        *dest_pixel = (src_pixel & !blend) |
                                      (*dest_pixel & blend);
                    }
                }
            }
        }
    }

    pub fn to_texture(&self) -> Texture {
        let mut tex = Texture::new(gl::TEXTURE_2D);
        tex.bind(gl::TEXTURE0);
        tex.set_filters_nearest()
           .data_rg_u8(0, self.width, self.height, self.pixels[])
           .unbind(gl::TEXTURE0);
        tex
    }

    pub fn x_offset(&self) -> int { self.x_offset }
    pub fn y_offset(&self) -> int { self.y_offset }

    pub fn width(&self) -> uint { self.width }
    pub fn height(&self) -> uint { self.height }

    pub fn num_pixels(&self) -> uint { self.pixels.len() }

    pub fn get_pixels<'a>(&'a self) -> &'a [u16] { self.pixels[] }

}

<commit_msg>Explicit subtractions instead of unsigned negations.<commit_after>use std::vec::Vec;
use std::io::BufReader;
use super::types::*;
use std::ptr::copy_nonoverlapping_memory;
use texture::Texture;
use gl;

pub struct Image {
    width: uint,
    height: uint,
    x_offset: int,
    y_offset: int,
    pixels: Vec<u16>,
}

macro_rules! io_try(
    ($e:expr) => (try!($e.map_err(|e| String::from_str(e.desc))))
)

impl Image {
    pub fn new(width: uint, height: uint) -> Image {
        Image { width: width,
                height: height,
                x_offset: 0,
                y_offset: 0,
                pixels: Vec::from_elem(width * height, 0xff00) }
    }

    pub fn new_from_header(header: &WadTextureHeader) -> Image {
        Image::new(header.width as uint, header.height as uint)
    }

    pub fn from_buffer(buffer: &[u8]) -> Image {
        let mut reader = BufReader::new(buffer);

        let width = reader.read_le_u16().unwrap() as uint;
        let height = reader.read_le_u16().unwrap() as uint;
        let x_offset = reader.read_le_i16().unwrap() as int;
        let y_offset = reader.read_le_i16().unwrap() as int;

        let mut pixels = Vec::from_elem(width * height, -1);
        // Sorry for the messy/unsafe code, but the array bounds checks in this
        // tight loop make it 6x slower.
        for i_column in range(0, width as int) { unsafe {
            // Each column is defined as a number of vertical `runs' which are
            // defined starting at `offset' in the buffer.
            let offset = reader.read_le_u32().unwrap() as int;
            let mut src_ptr = buffer.as_ptr().offset(offset);
            'this_column: loop {
                // The first byte contains the vertical coordinate of the run's
                // start.
                let row_start = *src_ptr as int; src_ptr = src_ptr.offset(1);

                // Pointer to the beginning of the run in `pixels'.
                let mut dest_ptr = pixels
                    .as_mut_ptr().offset(row_start * width as int + i_column);

                // The special value of 255 means this is the last run in the
                // column, so move on to the next one.
                if row_start == 255 { break 'this_column; }

                // The second byte is the length of this run. Skip an additional
                // byte which is ignored for some reason.
                let run_length = *src_ptr as int; src_ptr = src_ptr.offset(2);

                let src_end = src_ptr.offset(run_length);  // Ptr to end of run.
                while src_ptr < src_end {
                    // Copy one byte converting it into an opaque pixels (high
                    // bits are zero) and advance the pointers.
                    *dest_ptr = *src_ptr as u16;
                    dest_ptr = dest_ptr.offset(width as int);
                    src_ptr = src_ptr.offset(1);
                }
                // And another ignored byte after the run.
                src_ptr = src_ptr.offset(1);
            }
        }}
        let pixels = pixels;

        Image { width: width,
                height: height,
                x_offset: x_offset,
                y_offset: y_offset,
                pixels: pixels }
    }

    pub fn blit(&mut self, source: &Image, x_offset: int, y_offset: int,
                ignore_transparency: bool) {
        // Figure out the region in source which is not out of bounds when
        // copied into self.
        let y_start = if y_offset < 0 { (-y_offset) as uint } else { 0 };
        let x_start = if x_offset < 0 { (-x_offset) as uint } else { 0 };
        let y_end = if self.height as int > source.height as int + y_offset {
            source.height
        } else {
            self.height - y_offset as uint
        };
        let x_end = if self.width as int > source.width as int + x_offset {
            source.width
        } else {
            self.width - x_offset as uint
        };

        if ignore_transparency {
            // If we don't care about transparency we can memcpy row by row.
            let src_pitch = source.width as int;
            let dest_pitch = self.width as int;
            let copy_width = x_end - x_start;
            let copy_height = (y_end - y_start) as int;
            let (x_start, y_start) = (x_start as int, y_start as int);
            unsafe {
                let mut src_ptr = source.pixels.as_ptr().offset(
                    x_start + y_start * src_pitch);
                let mut dest_ptr = self.pixels.as_mut_ptr().offset(
                    x_start + x_offset + (y_start + y_offset) * dest_pitch);

                let src_end = src_ptr.offset(copy_height * src_pitch);
                while src_ptr < src_end {
                    copy_nonoverlapping_memory(dest_ptr, src_ptr, copy_width);
                    src_ptr = src_ptr.offset(src_pitch);
                    dest_ptr = dest_ptr.offset(dest_pitch);
                }
            }
        } else {
            // Only copy pixels whose high bits are not set.
            let dest_ptr = self.pixels.as_mut_ptr();
            let src_ptr = source.pixels.as_ptr();
            for src_y in range(y_start, y_end) {
                let dest_y = (src_y as int + y_offset) as uint;
                for src_x in range(x_start, x_end) {
                    let dest_x = (src_x as int + x_offset) as uint;

                    let (dest_x, dest_y) = (dest_x as uint, dest_y as uint);
                    let dest_index = (dest_x + dest_y * self.width) as int;
                    let src_index = (src_x + src_y * source.width) as int;

                    unsafe {
                        // `Blending' is a simple copy/no copy, but using bit
                        // ops we can avoid branching.
                        let src_pixel = *src_ptr.offset(src_index);
                        let dest_pixel = dest_ptr.offset(dest_index);
                        let blend = (0 - (src_pixel >> 15)) as u16;
                        *dest_pixel = (src_pixel & !blend) |
                                      (*dest_pixel & blend);
                    }
                }
            }
        }
    }

    pub fn to_texture(&self) -> Texture {
        let mut tex = Texture::new(gl::TEXTURE_2D);
        tex.bind(gl::TEXTURE0);
        tex.set_filters_nearest()
           .data_rg_u8(0, self.width, self.height, self.pixels[])
           .unbind(gl::TEXTURE0);
        tex
    }

    pub fn x_offset(&self) -> int { self.x_offset }
    pub fn y_offset(&self) -> int { self.y_offset }

    pub fn width(&self) -> uint { self.width }
    pub fn height(&self) -> uint { self.height }

    pub fn num_pixels(&self) -> uint { self.pixels.len() }

    pub fn get_pixels<'a>(&'a self) -> &'a [u16] { self.pixels[] }

}

<|endoftext|>


<commit_before>use std::error::Error;
use std::{fmt, env};

use mir;
use ty::{FnSig, Ty, layout};

use super::{
    MemoryPointer, Lock, AccessKind
};

use rustc_const_math::ConstMathErr;
use syntax::codemap::Span;
use backtrace::Backtrace;

#[derive(Debug, Clone)]
pub struct EvalError<'tcx> {
    pub kind: EvalErrorKind<'tcx>,
    pub backtrace: Option<Backtrace>,
}

impl<'tcx> From<EvalErrorKind<'tcx>> for EvalError<'tcx> {
    fn from(kind: EvalErrorKind<'tcx>) -> Self {
        let backtrace = match env::var("RUST_BACKTRACE") {
            Ok(ref val) if !val.is_empty() => Some(Backtrace::new_unresolved()),
            _ => None
        };
        EvalError {
            kind,
            backtrace,
        }
    }
}

#[derive(Debug, Clone)]
pub enum EvalErrorKind<'tcx> {
    /// This variant is used by machines to signal their own errors that do not
    /// match an existing variant
    MachineError(String),
    FunctionPointerTyMismatch(FnSig<'tcx>, FnSig<'tcx>),
    NoMirFor(String),
    UnterminatedCString(MemoryPointer),
    DanglingPointerDeref,
    DoubleFree,
    InvalidMemoryAccess,
    InvalidFunctionPointer,
    InvalidBool,
    InvalidDiscriminant,
    PointerOutOfBounds {
        ptr: MemoryPointer,
        access: bool,
        allocation_size: u64,
    },
    InvalidNullPointerUsage,
    ReadPointerAsBytes,
    ReadBytesAsPointer,
    InvalidPointerMath,
    ReadUndefBytes,
    DeadLocal,
    InvalidBoolOp(mir::BinOp),
    Unimplemented(String),
    DerefFunctionPointer,
    ExecuteMemory,
    ArrayIndexOutOfBounds(Span, u64, u64),
    Math(Span, ConstMathErr),
    Intrinsic(String),
    OverflowingMath,
    InvalidChar(u128),
    ExecutionTimeLimitReached,
    StackFrameLimitReached,
    OutOfTls,
    TlsOutOfBounds,
    AbiViolation(String),
    AlignmentCheckFailed {
        required: u64,
        has: u64,
    },
    MemoryLockViolation {
        ptr: MemoryPointer,
        len: u64,
        frame: usize,
        access: AccessKind,
        lock: Lock,
    },
    MemoryAcquireConflict {
        ptr: MemoryPointer,
        len: u64,
        kind: AccessKind,
        lock: Lock,
    },
    InvalidMemoryLockRelease {
        ptr: MemoryPointer,
        len: u64,
        frame: usize,
        lock: Lock,
    },
    DeallocatedLockedMemory {
        ptr: MemoryPointer,
        lock: Lock,
    },
    ValidationFailure(String),
    CalledClosureAsFunction,
    VtableForArgumentlessMethod,
    ModifiedConstantMemory,
    AssumptionNotHeld,
    InlineAsm,
    TypeNotPrimitive(Ty<'tcx>),
    ReallocatedWrongMemoryKind(String, String),
    DeallocatedWrongMemoryKind(String, String),
    ReallocateNonBasePtr,
    DeallocateNonBasePtr,
    IncorrectAllocationInformation(u64, usize, u64, u64),
    Layout(layout::LayoutError<'tcx>),
    HeapAllocZeroBytes,
    HeapAllocNonPowerOfTwoAlignment(u64),
    Unreachable,
    Panic,
    ReadFromReturnPointer,
    PathNotFound(Vec<String>),
    UnimplementedTraitSelection,
    /// Abort in case type errors are reached
    TypeckError,
    /// Cannot compute this constant because it depends on another one
    /// which already produced an error
    ReferencedConstant,
}

pub type EvalResult<'tcx, T = ()> = Result<T, EvalError<'tcx>>;

impl<'tcx> Error for EvalError<'tcx> {
    fn description(&self) -> &str {
        use self::EvalErrorKind::*;
        match self.kind {
            MachineError(ref inner) => inner,
            FunctionPointerTyMismatch(..) =>
                "tried to call a function through a function pointer of a different type",
            InvalidMemoryAccess =>
                "tried to access memory through an invalid pointer",
            DanglingPointerDeref =>
                "dangling pointer was dereferenced",
            DoubleFree =>
                "tried to deallocate dangling pointer",
            InvalidFunctionPointer =>
                "tried to use a function pointer after offsetting it",
            InvalidBool =>
                "invalid boolean value read",
            InvalidDiscriminant =>
                "invalid enum discriminant value read",
            PointerOutOfBounds { .. } =>
                "pointer offset outside bounds of allocation",
            InvalidNullPointerUsage =>
                "invalid use of NULL pointer",
            MemoryLockViolation { .. } =>
                "memory access conflicts with lock",
            MemoryAcquireConflict { .. } =>
                "new memory lock conflicts with existing lock",
            ValidationFailure(..) =>
                "type validation failed",
            InvalidMemoryLockRelease { .. } =>
                "invalid attempt to release write lock",
            DeallocatedLockedMemory { .. } =>
                "tried to deallocate memory in conflict with a lock",
            ReadPointerAsBytes =>
                "a raw memory access tried to access part of a pointer value as raw bytes",
            ReadBytesAsPointer =>
                "a memory access tried to interpret some bytes as a pointer",
            InvalidPointerMath =>
                "attempted to do invalid arithmetic on pointers that would leak base addresses, e.g. comparing pointers into different allocations",
            ReadUndefBytes =>
                "attempted to read undefined bytes",
            DeadLocal =>
                "tried to access a dead local variable",
            InvalidBoolOp(_) =>
                "invalid boolean operation",
            Unimplemented(ref msg) => msg,
            DerefFunctionPointer =>
                "tried to dereference a function pointer",
            ExecuteMemory =>
                "tried to treat a memory pointer as a function pointer",
            ArrayIndexOutOfBounds(..) =>
                "array index out of bounds",
            Math(..) =>
                "mathematical operation failed",
            Intrinsic(..) =>
                "intrinsic failed",
            OverflowingMath =>
                "attempted to do overflowing math",
            NoMirFor(..) =>
                "mir not found",
            InvalidChar(..) =>
                "tried to interpret an invalid 32-bit value as a char",
            ExecutionTimeLimitReached =>
                "the expression was too complex to be evaluated or resulted in an infinite loop",
            StackFrameLimitReached =>
                "reached the configured maximum number of stack frames",
            OutOfTls =>
                "reached the maximum number of representable TLS keys",
            TlsOutOfBounds =>
                "accessed an invalid (unallocated) TLS key",
            AbiViolation(ref msg) => msg,
            AlignmentCheckFailed{..} =>
                "tried to execute a misaligned read or write",
            CalledClosureAsFunction =>
                "tried to call a closure through a function pointer",
            VtableForArgumentlessMethod =>
                "tried to call a vtable function without arguments",
            ModifiedConstantMemory =>
                "tried to modify constant memory",
            AssumptionNotHeld =>
                "`assume` argument was false",
            InlineAsm =>
                "miri does not support inline assembly",
            TypeNotPrimitive(_) =>
                "expected primitive type, got nonprimitive",
            ReallocatedWrongMemoryKind(_, _) =>
                "tried to reallocate memory from one kind to another",
            DeallocatedWrongMemoryKind(_, _) =>
                "tried to deallocate memory of the wrong kind",
            ReallocateNonBasePtr =>
                "tried to reallocate with a pointer not to the beginning of an existing object",
            DeallocateNonBasePtr =>
                "tried to deallocate with a pointer not to the beginning of an existing object",
            IncorrectAllocationInformation(..) =>
                "tried to deallocate or reallocate using incorrect alignment or size",
            Layout(_) =>
                "rustc layout computation failed",
            UnterminatedCString(_) =>
                "attempted to get length of a null terminated string, but no null found before end of allocation",
            HeapAllocZeroBytes =>
                "tried to re-, de- or allocate zero bytes on the heap",
            HeapAllocNonPowerOfTwoAlignment(_) =>
                "tried to re-, de-, or allocate heap memory with alignment that is not a power of two",
            Unreachable =>
                "entered unreachable code",
            Panic =>
                "the evaluated program panicked",
            ReadFromReturnPointer =>
                "tried to read from the return pointer",
            EvalErrorKind::PathNotFound(_) =>
                "a path could not be resolved, maybe the crate is not loaded",
            UnimplementedTraitSelection =>
                "there were unresolved type arguments during trait selection",
            TypeckError =>
                "encountered constants with type errors, stopping evaluation",
            ReferencedConstant =>
                "referenced constant has errors",
        }
    }
}

impl<'tcx> fmt::Display for EvalError<'tcx> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use self::EvalErrorKind::*;
        match self.kind {
            PointerOutOfBounds { ptr, access, allocation_size } => {
                write!(f, "{} at offset {}, outside bounds of allocation {} which has size {}",
                       if access { "memory access" } else { "pointer computed" },
                       ptr.offset, ptr.alloc_id, allocation_size)
            },
            MemoryLockViolation { ptr, len, frame, access, ref lock } => {
                write!(f, "{:?} access by frame {} at {:?}, size {}, is in conflict with lock {:?}",
                       access, frame, ptr, len, lock)
            }
            MemoryAcquireConflict { ptr, len, kind, ref lock } => {
                write!(f, "new {:?} lock at {:?}, size {}, is in conflict with lock {:?}",
                       kind, ptr, len, lock)
            }
            InvalidMemoryLockRelease { ptr, len, frame, ref lock } => {
                write!(f, "frame {} tried to release memory write lock at {:?}, size {}, but cannot release lock {:?}",
                       frame, ptr, len, lock)
            }
            DeallocatedLockedMemory { ptr, ref lock } => {
                write!(f, "tried to deallocate memory at {:?} in conflict with lock {:?}",
                       ptr, lock)
            }
            ValidationFailure(ref err) => {
                write!(f, "type validation failed: {}", err)
            }
            NoMirFor(ref func) => write!(f, "no mir for `{}`", func),
            FunctionPointerTyMismatch(sig, got) =>
                write!(f, "tried to call a function with sig {} through a function pointer of type {}", sig, got),
            ArrayIndexOutOfBounds(span, len, index) =>
                write!(f, "index out of bounds: the len is {} but the index is {} at {:?}", len, index, span),
            ReallocatedWrongMemoryKind(ref old, ref new) =>
                write!(f, "tried to reallocate memory from {} to {}", old, new),
            DeallocatedWrongMemoryKind(ref old, ref new) =>
                write!(f, "tried to deallocate {} memory but gave {} as the kind", old, new),
            Math(_, ref err) =>
                write!(f, "{}", err.description()),
            Intrinsic(ref err) =>
                write!(f, "{}", err),
            InvalidChar(c) =>
                write!(f, "tried to interpret an invalid 32-bit value as a char: {}", c),
            AlignmentCheckFailed { required, has } =>
               write!(f, "tried to access memory with alignment {}, but alignment {} is required",
                      has, required),
            TypeNotPrimitive(ty) =>
                write!(f, "expected primitive type, got {}", ty),
            Layout(ref err) =>
                write!(f, "rustc layout computation failed: {:?}", err),
            PathNotFound(ref path) =>
                write!(f, "Cannot find path {:?}", path),
            MachineError(ref inner) =>
                write!(f, "{}", inner),
            IncorrectAllocationInformation(size, size2, align, align2) =>
                write!(f, "incorrect alloc info: expected size {} and align {}, got size {} and align {}", size, align, size2, align2),
            _ => write!(f, "{}", self.description()),
        }
    }
}
<commit_msg>Only generate miri backtraces if explicitly requested<commit_after>use std::error::Error;
use std::{fmt, env};

use mir;
use ty::{FnSig, Ty, layout};

use super::{
    MemoryPointer, Lock, AccessKind
};

use rustc_const_math::ConstMathErr;
use syntax::codemap::Span;
use backtrace::Backtrace;

#[derive(Debug, Clone)]
pub struct EvalError<'tcx> {
    pub kind: EvalErrorKind<'tcx>,
    pub backtrace: Option<Backtrace>,
}

impl<'tcx> From<EvalErrorKind<'tcx>> for EvalError<'tcx> {
    fn from(kind: EvalErrorKind<'tcx>) -> Self {
        let backtrace = match env::var("MIRI_BACKTRACE") {
            Ok(ref val) if !val.is_empty() => Some(Backtrace::new_unresolved()),
            _ => None
        };
        EvalError {
            kind,
            backtrace,
        }
    }
}

#[derive(Debug, Clone)]
pub enum EvalErrorKind<'tcx> {
    /// This variant is used by machines to signal their own errors that do not
    /// match an existing variant
    MachineError(String),
    FunctionPointerTyMismatch(FnSig<'tcx>, FnSig<'tcx>),
    NoMirFor(String),
    UnterminatedCString(MemoryPointer),
    DanglingPointerDeref,
    DoubleFree,
    InvalidMemoryAccess,
    InvalidFunctionPointer,
    InvalidBool,
    InvalidDiscriminant,
    PointerOutOfBounds {
        ptr: MemoryPointer,
        access: bool,
        allocation_size: u64,
    },
    InvalidNullPointerUsage,
    ReadPointerAsBytes,
    ReadBytesAsPointer,
    InvalidPointerMath,
    ReadUndefBytes,
    DeadLocal,
    InvalidBoolOp(mir::BinOp),
    Unimplemented(String),
    DerefFunctionPointer,
    ExecuteMemory,
    ArrayIndexOutOfBounds(Span, u64, u64),
    Math(Span, ConstMathErr),
    Intrinsic(String),
    OverflowingMath,
    InvalidChar(u128),
    ExecutionTimeLimitReached,
    StackFrameLimitReached,
    OutOfTls,
    TlsOutOfBounds,
    AbiViolation(String),
    AlignmentCheckFailed {
        required: u64,
        has: u64,
    },
    MemoryLockViolation {
        ptr: MemoryPointer,
        len: u64,
        frame: usize,
        access: AccessKind,
        lock: Lock,
    },
    MemoryAcquireConflict {
        ptr: MemoryPointer,
        len: u64,
        kind: AccessKind,
        lock: Lock,
    },
    InvalidMemoryLockRelease {
        ptr: MemoryPointer,
        len: u64,
        frame: usize,
        lock: Lock,
    },
    DeallocatedLockedMemory {
        ptr: MemoryPointer,
        lock: Lock,
    },
    ValidationFailure(String),
    CalledClosureAsFunction,
    VtableForArgumentlessMethod,
    ModifiedConstantMemory,
    AssumptionNotHeld,
    InlineAsm,
    TypeNotPrimitive(Ty<'tcx>),
    ReallocatedWrongMemoryKind(String, String),
    DeallocatedWrongMemoryKind(String, String),
    ReallocateNonBasePtr,
    DeallocateNonBasePtr,
    IncorrectAllocationInformation(u64, usize, u64, u64),
    Layout(layout::LayoutError<'tcx>),
    HeapAllocZeroBytes,
    HeapAllocNonPowerOfTwoAlignment(u64),
    Unreachable,
    Panic,
    ReadFromReturnPointer,
    PathNotFound(Vec<String>),
    UnimplementedTraitSelection,
    /// Abort in case type errors are reached
    TypeckError,
    /// Cannot compute this constant because it depends on another one
    /// which already produced an error
    ReferencedConstant,
}

pub type EvalResult<'tcx, T = ()> = Result<T, EvalError<'tcx>>;

impl<'tcx> Error for EvalError<'tcx> {
    fn description(&self) -> &str {
        use self::EvalErrorKind::*;
        match self.kind {
            MachineError(ref inner) => inner,
            FunctionPointerTyMismatch(..) =>
                "tried to call a function through a function pointer of a different type",
            InvalidMemoryAccess =>
                "tried to access memory through an invalid pointer",
            DanglingPointerDeref =>
                "dangling pointer was dereferenced",
            DoubleFree =>
                "tried to deallocate dangling pointer",
            InvalidFunctionPointer =>
                "tried to use a function pointer after offsetting it",
            InvalidBool =>
                "invalid boolean value read",
            InvalidDiscriminant =>
                "invalid enum discriminant value read",
            PointerOutOfBounds { .. } =>
                "pointer offset outside bounds of allocation",
            InvalidNullPointerUsage =>
                "invalid use of NULL pointer",
            MemoryLockViolation { .. } =>
                "memory access conflicts with lock",
            MemoryAcquireConflict { .. } =>
                "new memory lock conflicts with existing lock",
            ValidationFailure(..) =>
                "type validation failed",
            InvalidMemoryLockRelease { .. } =>
                "invalid attempt to release write lock",
            DeallocatedLockedMemory { .. } =>
                "tried to deallocate memory in conflict with a lock",
            ReadPointerAsBytes =>
                "a raw memory access tried to access part of a pointer value as raw bytes",
            ReadBytesAsPointer =>
                "a memory access tried to interpret some bytes as a pointer",
            InvalidPointerMath =>
                "attempted to do invalid arithmetic on pointers that would leak base addresses, e.g. comparing pointers into different allocations",
            ReadUndefBytes =>
                "attempted to read undefined bytes",
            DeadLocal =>
                "tried to access a dead local variable",
            InvalidBoolOp(_) =>
                "invalid boolean operation",
            Unimplemented(ref msg) => msg,
            DerefFunctionPointer =>
                "tried to dereference a function pointer",
            ExecuteMemory =>
                "tried to treat a memory pointer as a function pointer",
            ArrayIndexOutOfBounds(..) =>
                "array index out of bounds",
            Math(..) =>
                "mathematical operation failed",
            Intrinsic(..) =>
                "intrinsic failed",
            OverflowingMath =>
                "attempted to do overflowing math",
            NoMirFor(..) =>
                "mir not found",
            InvalidChar(..) =>
                "tried to interpret an invalid 32-bit value as a char",
            ExecutionTimeLimitReached =>
                "the expression was too complex to be evaluated or resulted in an infinite loop",
            StackFrameLimitReached =>
                "reached the configured maximum number of stack frames",
            OutOfTls =>
                "reached the maximum number of representable TLS keys",
            TlsOutOfBounds =>
                "accessed an invalid (unallocated) TLS key",
            AbiViolation(ref msg) => msg,
            AlignmentCheckFailed{..} =>
                "tried to execute a misaligned read or write",
            CalledClosureAsFunction =>
                "tried to call a closure through a function pointer",
            VtableForArgumentlessMethod =>
                "tried to call a vtable function without arguments",
            ModifiedConstantMemory =>
                "tried to modify constant memory",
            AssumptionNotHeld =>
                "`assume` argument was false",
            InlineAsm =>
                "miri does not support inline assembly",
            TypeNotPrimitive(_) =>
                "expected primitive type, got nonprimitive",
            ReallocatedWrongMemoryKind(_, _) =>
                "tried to reallocate memory from one kind to another",
            DeallocatedWrongMemoryKind(_, _) =>
                "tried to deallocate memory of the wrong kind",
            ReallocateNonBasePtr =>
                "tried to reallocate with a pointer not to the beginning of an existing object",
            DeallocateNonBasePtr =>
                "tried to deallocate with a pointer not to the beginning of an existing object",
            IncorrectAllocationInformation(..) =>
                "tried to deallocate or reallocate using incorrect alignment or size",
            Layout(_) =>
                "rustc layout computation failed",
            UnterminatedCString(_) =>
                "attempted to get length of a null terminated string, but no null found before end of allocation",
            HeapAllocZeroBytes =>
                "tried to re-, de- or allocate zero bytes on the heap",
            HeapAllocNonPowerOfTwoAlignment(_) =>
                "tried to re-, de-, or allocate heap memory with alignment that is not a power of two",
            Unreachable =>
                "entered unreachable code",
            Panic =>
                "the evaluated program panicked",
            ReadFromReturnPointer =>
                "tried to read from the return pointer",
            EvalErrorKind::PathNotFound(_) =>
                "a path could not be resolved, maybe the crate is not loaded",
            UnimplementedTraitSelection =>
                "there were unresolved type arguments during trait selection",
            TypeckError =>
                "encountered constants with type errors, stopping evaluation",
            ReferencedConstant =>
                "referenced constant has errors",
        }
    }
}

impl<'tcx> fmt::Display for EvalError<'tcx> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use self::EvalErrorKind::*;
        match self.kind {
            PointerOutOfBounds { ptr, access, allocation_size } => {
                write!(f, "{} at offset {}, outside bounds of allocation {} which has size {}",
                       if access { "memory access" } else { "pointer computed" },
                       ptr.offset, ptr.alloc_id, allocation_size)
            },
            MemoryLockViolation { ptr, len, frame, access, ref lock } => {
                write!(f, "{:?} access by frame {} at {:?}, size {}, is in conflict with lock {:?}",
                       access, frame, ptr, len, lock)
            }
            MemoryAcquireConflict { ptr, len, kind, ref lock } => {
                write!(f, "new {:?} lock at {:?}, size {}, is in conflict with lock {:?}",
                       kind, ptr, len, lock)
            }
            InvalidMemoryLockRelease { ptr, len, frame, ref lock } => {
                write!(f, "frame {} tried to release memory write lock at {:?}, size {}, but cannot release lock {:?}",
                       frame, ptr, len, lock)
            }
            DeallocatedLockedMemory { ptr, ref lock } => {
                write!(f, "tried to deallocate memory at {:?} in conflict with lock {:?}",
                       ptr, lock)
            }
            ValidationFailure(ref err) => {
                write!(f, "type validation failed: {}", err)
            }
            NoMirFor(ref func) => write!(f, "no mir for `{}`", func),
            FunctionPointerTyMismatch(sig, got) =>
                write!(f, "tried to call a function with sig {} through a function pointer of type {}", sig, got),
            ArrayIndexOutOfBounds(span, len, index) =>
                write!(f, "index out of bounds: the len is {} but the index is {} at {:?}", len, index, span),
            ReallocatedWrongMemoryKind(ref old, ref new) =>
                write!(f, "tried to reallocate memory from {} to {}", old, new),
            DeallocatedWrongMemoryKind(ref old, ref new) =>
                write!(f, "tried to deallocate {} memory but gave {} as the kind", old, new),
            Math(_, ref err) =>
                write!(f, "{}", err.description()),
            Intrinsic(ref err) =>
                write!(f, "{}", err),
            InvalidChar(c) =>
                write!(f, "tried to interpret an invalid 32-bit value as a char: {}", c),
            AlignmentCheckFailed { required, has } =>
               write!(f, "tried to access memory with alignment {}, but alignment {} is required",
                      has, required),
            TypeNotPrimitive(ty) =>
                write!(f, "expected primitive type, got {}", ty),
            Layout(ref err) =>
                write!(f, "rustc layout computation failed: {:?}", err),
            PathNotFound(ref path) =>
                write!(f, "Cannot find path {:?}", path),
            MachineError(ref inner) =>
                write!(f, "{}", inner),
            IncorrectAllocationInformation(size, size2, align, align2) =>
                write!(f, "incorrect alloc info: expected size {} and align {}, got size {} and align {}", size, align, size2, align2),
            _ => write!(f, "{}", self.description()),
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Encapsulate debug callback in its own type, including destruction, and explicitly order RendererVk destruction<commit_after><|endoftext|>


<commit_before><commit_msg>Implement basic mutex Replace spin-rs with a reentrant mutex that includes stats for monitoring contested or deadlocked locks. Physical cores can hold a mutex and then be interrupted and unable to access resources they already hold an exclusive lock on. Reentrant mutexes ensure lock owners can regain their access to their resources.<commit_after>/* diosix high-level hypervisor's mutex primitive
 *
 * Provide reentrant mutex locks for critical
 * data structures. this means when a physical
 * core holds a lock and then tries to lock it
 * again, this operation will succeed.
 *
 * this is so that if a core holds a lock
 * and is interrupted, it can regain access
 * to the locked data, use it, and release it.
 *
 * use lock() to acquire an exclusive lock
 * drop the lock to release it
 *
 * (c) Chris Williams, 2021.
 *
 * See LICENSE for usage and copying.
 */

use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use core::cell::UnsafeCell;
use core::ops::{Deref, DerefMut};

pub struct Mutex<T>
{
    acquired: AtomicBool,
    owner: AtomicUsize,
    lock_attempts: AtomicUsize,
    lock_count: AtomicUsize,
    release_count: AtomicUsize,
    regain_count: AtomicUsize,
    content: UnsafeCell<T>,
}

/* Mutex uses the same API as std's Mutex. Create a Mutex using new() and then
   call lock() to block until lock successfully acquired. Drop the lock to release
   it. Use try_lock() to make one attempt at acquiring the lock */

impl<T> Mutex<T>
{
    pub fn new(data: T) -> Mutex<T>
    {
        Mutex
        {
            acquired: AtomicBool::new(false),
            owner: AtomicUsize::new(0),
            lock_attempts: AtomicUsize::new(0),
            lock_count: AtomicUsize::new(0),
            release_count: AtomicUsize::new(0),
            regain_count: AtomicUsize::new(0),
            content: UnsafeCell::new(data),
        }
    }

    pub fn lock(&self) -> MutexGuard<'_, T>
    {
        /* id 0 is no owner, so shift up IDs by one */
        let id = super::pcore::PhysicalCore::get_id() + 1;

        /* spin trying to set acquired to true to obtain the mutex */
        loop
        {
            self.lock_attempts.fetch_add(1, Ordering::Relaxed);

            if self.acquired.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed) == Ok(false)
            {
                /* available locks should not have a non-zero owner */
                if self.owner.load(Ordering::SeqCst) != 0
                {
                    hvdebug!("BUG: Lock {:p} was available yet owned by {}", &self, self.owner.load(Ordering::SeqCst));
                }

                /* we've acquired the lock. store our ownership in it */
                self.owner.store(id, Ordering::SeqCst);
                self.lock_count.fetch_add(1, Ordering::Relaxed);
                break;
            }

            /* couldn't acquire lock.. but it's not ours, is it? */
            if self.owner.load(Ordering::SeqCst) == id
            {
                /* we own this lock -- ensure it remains locked for us */
                self.acquired.store(true, Ordering::SeqCst);
                self.regain_count.fetch_add(1, Ordering::Relaxed);
                break;
            }
        }

        MutexGuard { mutex: &self }
    }

    /* return true if the lock is held, or false if not */
    pub fn is_locked(&self) -> bool
    {
        self.acquired.load(Ordering::SeqCst)
    }

    /* release the lock */
    fn unlock(&self)
    {
        self.owner.store(0, Ordering::SeqCst);
        self.release_count.fetch_add(1, Ordering::Relaxed);
        self.acquired.store(false, Ordering::Release);
    }
}

/* pretty print a mutex's stats */
impl<T> core::fmt::Debug for Mutex<T>
{
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
    {
        write!(f, "{:p}: {} lock attempts, locked {}, released {}, regained lock {} times", &self,
            self.lock_attempts.load(Ordering::Relaxed),
            self.lock_count.load(Ordering::Relaxed),
            self.release_count.load(Ordering::Relaxed),
            self.regain_count.load(Ordering::Relaxed))
    }
}

pub struct MutexGuard<'a, T>
{
    mutex: &'a Mutex<T>,
}

impl<T> Deref for MutexGuard<'_, T>
{
    type Target = T;

    fn deref(&self) -> &Self::Target
    {
        unsafe { &*self.mutex.content.get() }
    }
}

impl<T> DerefMut for MutexGuard<'_, T>
{
    fn deref_mut(&mut self) -> &mut Self::Target
    {
        unsafe { &mut *self.mutex.content.get() }
    }
}

impl<T> Drop for MutexGuard<'_, T>
{
    fn drop(&mut self)
    {
        self.mutex.unlock()
    }
}

/* keep rustc happy */
unsafe impl<T> Send for Mutex<T> where T: Send {}
unsafe impl<T> Sync for Mutex<T> where T: Send {}
unsafe impl<T> Send for MutexGuard<'_, T> where T: Send {}
unsafe impl<T> Sync for MutexGuard<'_, T> where T: Send + Sync {}
<|endoftext|>


<commit_before><commit_msg>test: single-variant enum can't be dereferenced<commit_after>// Copyright 2014 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.

// Verify that single-variant enums cant be de-referenced
// Regression test for issue #9814

enum Foo { Bar(int) }

fn main() {
    let _ = *Bar(2); //~ ERROR type `Foo` cannot be dereferenced
}
<|endoftext|>


<commit_before><commit_msg>rearrange example<commit_after><|endoftext|>


<commit_before><commit_msg>chat: Better names for errors.<commit_after><|endoftext|>


<commit_before><commit_msg>Small change<commit_after><|endoftext|>


<commit_before><commit_msg>Collapse else-if block<commit_after><|endoftext|>


<commit_before><commit_msg>data inspection example<commit_after>extern crate parity_wasm;

use std::env;

fn main() {
    let args = env::args().collect::<Vec<_>>();
    if args.len() != 2 {
        println!("Usage: {} somefile.wasm", args[0]);
        return;
    }

    let module = parity_wasm::deserialize_file(&args[1]).expect("Failed to load module");

    let data_section = module.data_section().expect("no data section in module");

    println!("Data segments: {}", data_section.entries().len());

    let mut index = 0;
    for entry in data_section.entries() {
        println!("  Entry #{}", index);
        println!("    init: {}", entry.offset().code()[0]);
        println!("    size: {}", entry.value().len());
        index += 1;
    }
}<|endoftext|>


<commit_before><commit_msg>chg commenting main.rs to avoid build errors on TravisCI<commit_after><|endoftext|>


<commit_before><commit_msg>Move interrupt enabling until after memory init<commit_after><|endoftext|>


<commit_before><commit_msg>Remove unnecessary loop and return statements.<commit_after><|endoftext|>


<commit_before><commit_msg>Skeleton for problem 2415<commit_after>use std::cell::RefCell;
use std::rc::Rc;

// https://leetcode.com/problems/reverse-odd-levels-of-binary-tree/
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
    pub val: i32,
    pub left: Option<Rc<RefCell<TreeNode>>>,
    pub right: Option<Rc<RefCell<TreeNode>>>,
}

impl TreeNode {
    #[inline]
    pub fn new(val: i32) -> Self {
        TreeNode {
            val,
            left: None,
            right: None,
        }
    }
}

pub fn reverse_odd_levels(root: Option<Rc<RefCell<TreeNode>>>) -> Option<Rc<RefCell<TreeNode>>> {
    todo!()
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Initial db structure<commit_after>use rusqlite::Connection;

#[derive(Debug)]
pub struct Provider {
    id: i32,
    name: String,
}

fn table_create_provider(conn: &Connection) -> &Connection {
    conn.execute("CREATE TABLE PROVIDER (
                  id              INTEGER PRIMARY KEY ASC,
                  name            TEXT NOT NULL UNIQUE
                  )", &[]).unwrap();
    return conn;
}

#[derive(Debug)]
struct Job {
    id: i32,
    name: String,
    shell: String,
}

fn table_create_job(conn: &Connection)  -> &Connection {
    conn.execute("CREATE TABLE JOB (
                  id              INTEGER PRIMARY KEY ASC,
                  name            TEXT NOT NULL UNIQUE,
                  shell           TEXT NOT NULL
                  )", &[]).unwrap();
    return conn;
}

#[derive(Debug)]
struct JobProvide {
    id: i32,
    job: i32,
    provider: i32,
}

fn table_create_job_provide(conn: &Connection)  -> &Connection  {
    conn.execute("CREATE TABLE JOBPROVIDE (
                  id            INTEGER PRIMARY KEY ASC,
                  job           INTEGER,
                  provider      INTEGER,
                  FOREIGN KEY(job) REFERENCES JOB(id) ON UPDATE CASCADE
                  FOREIGN KEY(provider) REFERENCES PROVIDER(id) ON UPDATE CASCADE
                  )", &[]).unwrap();
    return conn;
}

#[derive(Debug)]
struct JobDepend {
    id: i32,
    job: i32,
    provider: i32,
    sq_order: i32,
}

fn table_create_job_depend(conn: &Connection)  -> &Connection  {
    conn.execute("CREATE TABLE JOBDEPEND (
                  id            INTEGER PRIMARY KEY ASC,
                  job           INTEGER NOT NULL,
                  provider      INTEGER NOT NULL,
                  sq_order      INTEGER NOT NULL UNIQUE,
                  FOREIGN KEY(job) REFERENCES JOB(id) ON UPDATE CASCADE
                  FOREIGN KEY(provider) REFERENCES PROVIDER(id) ON UPDATE CASCADE
                  )", &[]).unwrap();
    return conn;
}

#[derive(Debug)]
struct VariableName {
    id: i32,
    name: String,
}

fn table_create_variable_name(conn: &Connection)  -> &Connection  {
    conn.execute("CREATE TABLE VARIABLE_NAME (
                  id            INTEGER PRIMARY KEY ASC,
                  name      TEXT
                  )", &[]).unwrap();
    return conn;
}

#[derive(Debug)]
struct JobRequireVariable {
    id: i32,
    job: i32,
    variable_id: i32,
}

fn table_create_require_variable(conn: &Connection)  {
    conn.execute("CREATE TABLE require_variable (
                  id            INTEGER PRIMARY KEY ASC,
                  job           INTEGER,
                  variable_id   INTEGER
                  )", &[]).unwrap();
}

#[derive(Debug)]
struct VariablePair {
    id: i32,
    variable_id: i32,
    variable_value: String
}

fn table_create_variable_pair(conn: &Connection)  {
    conn.execute("CREATE TABLE VariablePair (
                  id            INTEGER PRIMARY KEY ASC,
                  variable_id   INTEGER,
                  variable_value  TEXT
                  )", &[]).unwrap();

}

#[derive(Debug)]
struct JobRequireVariablePair {
    id: i32,
    variable_pair: i32,
}

fn table_create_require_variable_pair(conn: &Connection)  -> &Connection  {
    conn.execute("CREATE TABLE VariableId (
                  id            INTEGER PRIMARY KEY ASC,
                  job           INTEGER,
                  variable_pair INTEGER
                  )", &[]).unwrap();
    return conn;
}

pub fn connect() -> Connection {
    let conn = Connection::open_in_memory().unwrap();
    conn.execute("PRAGMA foreign_keys = ON;", &[]).unwrap();
    return conn;
}

pub fn create_tables(conn: &Connection) -> &Connection  {
    let newcon = table_create_provider(&conn);
    let newcon2 = table_create_job(&newcon);
    table_create_job_depend(&conn);
    table_create_job_provide(&conn);
    table_create_variable_name(&conn);
    table_create_variable_pair(&conn);
    table_create_require_variable(&conn);
    table_create_require_variable_pair(&conn);
    return newcon2;
}

pub fn insert_provider(conn: &Connection, name: String) {

    let me = Provider {
        id: 0,
        name: name,
    };
    conn.execute("INSERT INTO PROVIDER (name)
                  VALUES (?1)",
                 &[&me.name]).unwrap();
}

pub fn insert_job(conn: &Connection, name: String, shell: String) {

    let me = Job {
        id: 0,
        name: name,
        shell: shell,
    };
    conn.execute("INSERT INTO JOB (name, shell)
                  VALUES (?1, ?2)",
                 &[&me.name, &me.shell]).unwrap();
}

pub fn insert_job_provide(conn: &Connection, job: i32, provider: i32) {

    let me = JobProvide {
        id: 0,
        job: job,
        provider: provider,
    };
    conn.execute("INSERT INTO JOBPROVIDE (job, provider)
                  VALUES (?1, ?2)",
                 &[&me.job, &me.provider]).unwrap();
}

pub fn insert_job_depend(conn: &Connection, job: i32, provider: i32, sq_order: i32) {

    let me = JobDepend {
        id: 0,
        job: job,
        provider: provider,
        sq_order: sq_order,
    };
    conn.execute("INSERT INTO JOBDEPEND (job, provider, sq_order)
                  VALUES (?1, ?2, ?3)",
                 &[&me.job, &me.provider, &me.sq_order]).unwrap();
}

pub fn provider_list(conn: &Connection) {
    let mut stmt = conn.prepare("SELECT id, name FROM PROVIDER").unwrap();
    let person_iter = stmt.query_map(&[], |row| {
        Provider {
            id: row.get(0),
            name: row.get(1)
        }
    }).unwrap();

    for person in person_iter {
        println!("Found provider {:?}", person.unwrap());
    }
}
<|endoftext|>


<commit_before><commit_msg>Add an idealistic test for optimize attribute<commit_after>// revisions: NO-OPT SIZE-OPT SPEED-OPT
// [NO-OPT]compile-flags: -Copt-level=0
// [SIZE-OPT]compile-flags: -Copt-level=s
// [SPEED-OPT]compile-flags: -Copt-level=3

#![feature(optimize_attribute)]
#![crate_type="rlib"]

// NO-OPT: Function Attrs:{{.*}}optnone
// NO-OPT-NOT: {{optsize|minsize}}
// NO-OPT-NEXT: @nothing
// NO-OPT: ret i32 %1
//
// SIZE-OPT: Function Attrs:{{.*}}optsize
// SIZE-OPT-NOT: {{minsize|optnone}}
// SIZE-OPT-NEXT: @nothing
// SIZE-OPT-NEXT: start
// SIZE-OPT-NEXT: ret i32 4
//
// SPEED-OPT: Function Attrs:
// SPEED-OPT-NOT: {{minsize|optnone|optsize}}
// SPEED-OPT-NEXT: @nothing
// SPEED-OPT-NEXT: start
// SPEED-OPT-NEXT: ret i32 4
#[no_mangle]
pub fn nothing() -> i32 {
    2 + 2
}

// CHECK: Function Attrs:{{.*}} minsize{{.*}}optsize
// CHECK-NEXT: @size
// CHECK-NEXT: start
// CHECK-NEXT: ret i32 4
#[optimize(size)]
#[no_mangle]
pub fn size() -> i32 {
    2 + 2
}

// CHECK: Function Attrs:
// CHECK-NOT: {{minsize|optsize|optnone}}
// CHECK-NEXT: @speed
// CHECK-NEXT: start
// CHECK-NEXT: ret i32 4
#[optimize(speed)]
#[no_mangle]
pub fn speed() -> i32 {
    2 + 2
}
<|endoftext|>


<commit_before><commit_msg>Improved (marginally) the error handling when a line cannot be completely read.<commit_after><|endoftext|>


<commit_before><commit_msg>test: Add a dvec indexing operator test, which serves as a test for #2615 (cross-crate operator overloading).<commit_after>fn main() {
    let x = dvec::dvec();
    x.push(1);
    io::println(fmt!("%d", x[0]));
}

<|endoftext|>


<commit_before>#[doc = "Prunes branches of the tree that are not exported"];

import rustc::syntax::ast;
import rustc::syntax::ast_util;
import rustc::middle::ast_map;

export mk_pass;

fn mk_pass() -> pass {
    run
}

fn run(srv: astsrv::srv, doc: doc::cratedoc) -> doc::cratedoc {
    let fold = fold::fold({
        fold_mod: fold_mod
        with *fold::default_seq_fold(srv)
    });
    fold.fold_crate(fold, doc)
}

fn fold_mod(fold: fold::fold<astsrv::srv>, doc: doc::moddoc) -> doc::moddoc {
    let doc = fold::default_seq_fold_mod(fold, doc);
    ~{
        items: exported_items(fold.ctxt, doc),
        mods: doc::modlist(exported_mods(fold.ctxt, doc)),
        fns: doc::fnlist(exported_fns(fold.ctxt, doc)),
        consts: doc::constlist(exported_consts(fold.ctxt, doc))
        with *doc
    }
}

fn exported_items(srv: astsrv::srv, doc: doc::moddoc) -> [doc::itemtag] {
    exported_things(
        srv, doc,
        exported_items_from_crate,
        exported_items_from_mod
    )
}

fn exported_mods(srv: astsrv::srv, doc: doc::moddoc) -> [doc::moddoc] {
    exported_things(
        srv, doc,
        exported_mods_from_crate,
        exported_mods_from_mod
    )
}

fn exported_fns(srv: astsrv::srv, doc: doc::moddoc) -> [doc::fndoc] {
    exported_things(
        srv, doc,
        exported_fns_from_crate,
        exported_fns_from_mod
    )
}

fn exported_consts(srv: astsrv::srv, doc: doc::moddoc) -> [doc::constdoc] {
    exported_things(
        srv, doc,
        exported_consts_from_crate,
        exported_consts_from_mod
    )
}

fn exported_things<T>(
    srv: astsrv::srv,
    doc: doc::moddoc,
    from_crate: fn(astsrv::srv, doc::moddoc) -> [T],
    from_mod: fn(astsrv::srv, doc::moddoc) -> [T]
) -> [T] {
    if doc.id == ast::crate_node_id {
        from_crate(srv, doc)
    } else {
        from_mod(srv, doc)
    }
}

fn exported_items_from_crate(
    srv: astsrv::srv,
    doc: doc::moddoc
) -> [doc::itemtag] {
    exported_items_from(srv, doc, is_exported_from_crate)
}

fn exported_items_from_mod(
    srv: astsrv::srv,
    doc: doc::moddoc
) -> [doc::itemtag] {
    exported_items_from(srv, doc, bind is_exported_from_mod(_, doc.id, _))
}

fn exported_mods_from_crate(
    srv: astsrv::srv,
    doc: doc::moddoc
) -> [doc::moddoc] {
    exported_mods_from(srv, doc, is_exported_from_crate)
}

fn exported_mods_from_mod(
    srv: astsrv::srv,
    doc: doc::moddoc
) -> [doc::moddoc] {
    exported_mods_from(srv, doc, bind is_exported_from_mod(_, doc.id, _))
}

fn exported_fns_from_crate(
    srv: astsrv::srv,
    doc: doc::moddoc
) -> [doc::fndoc] {
    exported_fns_from(srv, doc, is_exported_from_crate)
}

fn exported_fns_from_mod(
    srv: astsrv::srv,
    doc: doc::moddoc
) -> [doc::fndoc] {
    exported_fns_from(srv, doc, bind is_exported_from_mod(_, doc.id, _))
}

fn exported_consts_from_crate(
    srv: astsrv::srv,
    doc: doc::moddoc
) -> [doc::constdoc] {
    exported_consts_from(srv, doc, is_exported_from_crate)
}

fn exported_consts_from_mod(
    srv: astsrv::srv,
    doc: doc::moddoc
) -> [doc::constdoc] {
    exported_consts_from(srv, doc, bind is_exported_from_mod(_, doc.id, _))
}

fn exported_items_from(
    srv: astsrv::srv,
    doc: doc::moddoc,
    is_exported: fn(astsrv::srv, str) -> bool
) -> [doc::itemtag] {
    vec::filter_map(doc.items) { |itemtag|
        let name = alt itemtag {
          doc::enumtag(~{name, _}) { name }
          doc::restag(~{name, _}) { "FIXME" }
        };
        let itemtag = alt itemtag {
          doc::enumtag(enumdoc) {
            // Also need to check variant exportedness
            doc::enumtag(~{
                variants: exported_variants_from(srv, enumdoc, is_exported)
                with *enumdoc
            })
          }
          _ { itemtag }
        };
        if is_exported(srv, name) {
            some(itemtag)
        } else {
            none
        }
    }
}

fn exported_fns_from(
    srv: astsrv::srv,
    doc: doc::moddoc,
    is_exported: fn(astsrv::srv, str) -> bool
) -> [doc::fndoc] {
    vec::filter_map(*doc.fns) { |doc|
        if is_exported(srv, doc.name) {
            some(doc)
        } else {
            none
        }
    }
}

fn exported_mods_from(
    srv: astsrv::srv,
    doc: doc::moddoc,
    is_exported: fn(astsrv::srv, str) -> bool
) -> [doc::moddoc] {
    vec::filter_map(*doc.mods) { |doc|
        if is_exported(srv, doc.name) {
            some(doc)
        } else {
            none
        }
    }
}

fn exported_consts_from(
    srv: astsrv::srv,
    doc: doc::moddoc,
    is_exported: fn(astsrv::srv, str) -> bool
) -> [doc::constdoc] {
    vec::filter_map(*doc.consts) { |doc|
        if is_exported(srv, doc.name) {
            some(doc)
        } else {
            none
        }
    }
}

fn exported_variants_from(
    srv: astsrv::srv,
    doc: doc::enumdoc,
    is_exported: fn(astsrv::srv, str) -> bool
) -> [doc::variantdoc] {
    vec::filter_map(doc.variants) { |doc|
        if is_exported(srv, doc.name) {
            some(doc)
        } else {
            none
        }
    }
}

fn is_exported_from_mod(
    srv: astsrv::srv,
    mod_id: doc::ast_id,
    item_name: str
) -> bool {
    astsrv::exec(srv) {|ctxt|
        alt ctxt.ast_map.get(mod_id) {
          ast_map::node_item(item) {
            alt item.node {
              ast::item_mod(m) {
                ast_util::is_exported(item_name, m)
              }
            }
          }
        }
    }
}

fn is_exported_from_crate(
    srv: astsrv::srv,
    item_name: str
) -> bool {
    astsrv::exec(srv) {|ctxt|
        ast_util::is_exported(item_name, ctxt.ast.node.module)
    }
}

#[test]
fn should_prune_unexported_fns() {
    let source = "mod b { export a; fn a() { } fn b() { } }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = run(srv, doc);
    assert vec::len(*doc.topmod.mods[0].fns) == 1u;
}

#[test]
fn should_prune_unexported_fns_from_top_mod() {
    let source = "export a; fn a() { } fn b() { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = run(srv, doc);
    assert vec::len(*doc.topmod.fns) == 1u;
}

#[test]
fn should_prune_unexported_modules() {
    let source = "mod a { export a; mod a { } mod b { } }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = run(srv, doc);
    assert vec::len(*doc.topmod.mods[0].mods) == 1u;
}

#[test]
fn should_prune_unexported_modules_from_top_mod() {
    let source = "export a; mod a { } mod b { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = run(srv, doc);
    assert vec::len(*doc.topmod.mods) == 1u;
}

#[test]
fn should_prune_unexported_consts() {
    let source = "mod a { export a; \
                  const a: bool = true; \
                  const b: bool = true; }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = run(srv, doc);
    assert vec::len(*doc.topmod.mods[0].consts) == 1u;
}

#[test]
fn should_prune_unexported_consts_from_top_mod() {
    let source = "export a; const a: bool = true; const b: bool = true;";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = run(srv, doc);
    assert vec::len(*doc.topmod.consts) == 1u;
}

#[test]
fn should_prune_unexported_enums_from_top_mod() {
    let source = "export a; mod a { } enum b { c }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = run(srv, doc);
    assert vec::len(doc.topmod.enums()) == 0u;
}

#[test]
fn should_prune_unexported_enums() {
    let source = "mod a { export a; mod a { } enum b { c } }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = run(srv, doc);
    assert vec::len(doc.topmod.mods[0].enums()) == 0u;
}

#[test]
fn should_prune_unexported_variants_from_top_mod() {
    let source = "export b::{}; enum b { c }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = run(srv, doc);
    assert vec::len(doc.topmod.enums()[0].variants) == 0u;
}

#[test]
fn should_prune_unexported_variants() {
    let source = "mod a { export b::{}; enum b { c } }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = run(srv, doc);
    assert vec::len(doc.topmod.mods[0].enums()[0].variants) == 0u;
}
<commit_msg>rustdoc: Add test that unexported resources are pruned<commit_after>#[doc = "Prunes branches of the tree that are not exported"];

import rustc::syntax::ast;
import rustc::syntax::ast_util;
import rustc::middle::ast_map;

export mk_pass;

fn mk_pass() -> pass {
    run
}

fn run(srv: astsrv::srv, doc: doc::cratedoc) -> doc::cratedoc {
    let fold = fold::fold({
        fold_mod: fold_mod
        with *fold::default_seq_fold(srv)
    });
    fold.fold_crate(fold, doc)
}

fn fold_mod(fold: fold::fold<astsrv::srv>, doc: doc::moddoc) -> doc::moddoc {
    let doc = fold::default_seq_fold_mod(fold, doc);
    ~{
        items: exported_items(fold.ctxt, doc),
        mods: doc::modlist(exported_mods(fold.ctxt, doc)),
        fns: doc::fnlist(exported_fns(fold.ctxt, doc)),
        consts: doc::constlist(exported_consts(fold.ctxt, doc))
        with *doc
    }
}

fn exported_items(srv: astsrv::srv, doc: doc::moddoc) -> [doc::itemtag] {
    exported_things(
        srv, doc,
        exported_items_from_crate,
        exported_items_from_mod
    )
}

fn exported_mods(srv: astsrv::srv, doc: doc::moddoc) -> [doc::moddoc] {
    exported_things(
        srv, doc,
        exported_mods_from_crate,
        exported_mods_from_mod
    )
}

fn exported_fns(srv: astsrv::srv, doc: doc::moddoc) -> [doc::fndoc] {
    exported_things(
        srv, doc,
        exported_fns_from_crate,
        exported_fns_from_mod
    )
}

fn exported_consts(srv: astsrv::srv, doc: doc::moddoc) -> [doc::constdoc] {
    exported_things(
        srv, doc,
        exported_consts_from_crate,
        exported_consts_from_mod
    )
}

fn exported_things<T>(
    srv: astsrv::srv,
    doc: doc::moddoc,
    from_crate: fn(astsrv::srv, doc::moddoc) -> [T],
    from_mod: fn(astsrv::srv, doc::moddoc) -> [T]
) -> [T] {
    if doc.id == ast::crate_node_id {
        from_crate(srv, doc)
    } else {
        from_mod(srv, doc)
    }
}

fn exported_items_from_crate(
    srv: astsrv::srv,
    doc: doc::moddoc
) -> [doc::itemtag] {
    exported_items_from(srv, doc, is_exported_from_crate)
}

fn exported_items_from_mod(
    srv: astsrv::srv,
    doc: doc::moddoc
) -> [doc::itemtag] {
    exported_items_from(srv, doc, bind is_exported_from_mod(_, doc.id, _))
}

fn exported_mods_from_crate(
    srv: astsrv::srv,
    doc: doc::moddoc
) -> [doc::moddoc] {
    exported_mods_from(srv, doc, is_exported_from_crate)
}

fn exported_mods_from_mod(
    srv: astsrv::srv,
    doc: doc::moddoc
) -> [doc::moddoc] {
    exported_mods_from(srv, doc, bind is_exported_from_mod(_, doc.id, _))
}

fn exported_fns_from_crate(
    srv: astsrv::srv,
    doc: doc::moddoc
) -> [doc::fndoc] {
    exported_fns_from(srv, doc, is_exported_from_crate)
}

fn exported_fns_from_mod(
    srv: astsrv::srv,
    doc: doc::moddoc
) -> [doc::fndoc] {
    exported_fns_from(srv, doc, bind is_exported_from_mod(_, doc.id, _))
}

fn exported_consts_from_crate(
    srv: astsrv::srv,
    doc: doc::moddoc
) -> [doc::constdoc] {
    exported_consts_from(srv, doc, is_exported_from_crate)
}

fn exported_consts_from_mod(
    srv: astsrv::srv,
    doc: doc::moddoc
) -> [doc::constdoc] {
    exported_consts_from(srv, doc, bind is_exported_from_mod(_, doc.id, _))
}

fn exported_items_from(
    srv: astsrv::srv,
    doc: doc::moddoc,
    is_exported: fn(astsrv::srv, str) -> bool
) -> [doc::itemtag] {
    vec::filter_map(doc.items) { |itemtag|
        let name = alt itemtag {
          doc::enumtag(~{name, _}) { name }
          doc::restag(~{name, _}) { name }
        };
        let itemtag = alt itemtag {
          doc::enumtag(enumdoc) {
            // Also need to check variant exportedness
            doc::enumtag(~{
                variants: exported_variants_from(srv, enumdoc, is_exported)
                with *enumdoc
            })
          }
          _ { itemtag }
        };
        if is_exported(srv, name) {
            some(itemtag)
        } else {
            none
        }
    }
}

fn exported_fns_from(
    srv: astsrv::srv,
    doc: doc::moddoc,
    is_exported: fn(astsrv::srv, str) -> bool
) -> [doc::fndoc] {
    vec::filter_map(*doc.fns) { |doc|
        if is_exported(srv, doc.name) {
            some(doc)
        } else {
            none
        }
    }
}

fn exported_mods_from(
    srv: astsrv::srv,
    doc: doc::moddoc,
    is_exported: fn(astsrv::srv, str) -> bool
) -> [doc::moddoc] {
    vec::filter_map(*doc.mods) { |doc|
        if is_exported(srv, doc.name) {
            some(doc)
        } else {
            none
        }
    }
}

fn exported_consts_from(
    srv: astsrv::srv,
    doc: doc::moddoc,
    is_exported: fn(astsrv::srv, str) -> bool
) -> [doc::constdoc] {
    vec::filter_map(*doc.consts) { |doc|
        if is_exported(srv, doc.name) {
            some(doc)
        } else {
            none
        }
    }
}

fn exported_variants_from(
    srv: astsrv::srv,
    doc: doc::enumdoc,
    is_exported: fn(astsrv::srv, str) -> bool
) -> [doc::variantdoc] {
    vec::filter_map(doc.variants) { |doc|
        if is_exported(srv, doc.name) {
            some(doc)
        } else {
            none
        }
    }
}

fn is_exported_from_mod(
    srv: astsrv::srv,
    mod_id: doc::ast_id,
    item_name: str
) -> bool {
    astsrv::exec(srv) {|ctxt|
        alt ctxt.ast_map.get(mod_id) {
          ast_map::node_item(item) {
            alt item.node {
              ast::item_mod(m) {
                ast_util::is_exported(item_name, m)
              }
            }
          }
        }
    }
}

fn is_exported_from_crate(
    srv: astsrv::srv,
    item_name: str
) -> bool {
    astsrv::exec(srv) {|ctxt|
        ast_util::is_exported(item_name, ctxt.ast.node.module)
    }
}

#[test]
fn should_prune_unexported_fns() {
    let source = "mod b { export a; fn a() { } fn b() { } }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = run(srv, doc);
    assert vec::len(*doc.topmod.mods[0].fns) == 1u;
}

#[test]
fn should_prune_unexported_fns_from_top_mod() {
    let source = "export a; fn a() { } fn b() { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = run(srv, doc);
    assert vec::len(*doc.topmod.fns) == 1u;
}

#[test]
fn should_prune_unexported_modules() {
    let source = "mod a { export a; mod a { } mod b { } }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = run(srv, doc);
    assert vec::len(*doc.topmod.mods[0].mods) == 1u;
}

#[test]
fn should_prune_unexported_modules_from_top_mod() {
    let source = "export a; mod a { } mod b { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = run(srv, doc);
    assert vec::len(*doc.topmod.mods) == 1u;
}

#[test]
fn should_prune_unexported_consts() {
    let source = "mod a { export a; \
                  const a: bool = true; \
                  const b: bool = true; }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = run(srv, doc);
    assert vec::len(*doc.topmod.mods[0].consts) == 1u;
}

#[test]
fn should_prune_unexported_consts_from_top_mod() {
    let source = "export a; const a: bool = true; const b: bool = true;";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = run(srv, doc);
    assert vec::len(*doc.topmod.consts) == 1u;
}

#[test]
fn should_prune_unexported_enums_from_top_mod() {
    let source = "export a; mod a { } enum b { c }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = run(srv, doc);
    assert vec::len(doc.topmod.enums()) == 0u;
}

#[test]
fn should_prune_unexported_enums() {
    let source = "mod a { export a; mod a { } enum b { c } }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = run(srv, doc);
    assert vec::len(doc.topmod.mods[0].enums()) == 0u;
}

#[test]
fn should_prune_unexported_variants_from_top_mod() {
    let source = "export b::{}; enum b { c }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = run(srv, doc);
    assert vec::len(doc.topmod.enums()[0].variants) == 0u;
}

#[test]
fn should_prune_unexported_variants() {
    let source = "mod a { export b::{}; enum b { c } }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = run(srv, doc);
    assert vec::len(doc.topmod.mods[0].enums()[0].variants) == 0u;
}

#[test]
fn should_prune_unexported_resources_from_top_mod() {
    let source = "export a; mod a { } resource r(a: bool) { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = run(srv, doc);
    assert vec::is_empty(doc.topmod.resources());
}

#[test]
fn should_prune_unexported_resources() {
    let source = "mod a { export a; mod a { } resource r(a: bool) { } }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = run(srv, doc);
    assert vec::is_empty(doc.topmod.mods[0].resources());
}
<|endoftext|>


<commit_before><commit_msg>Reuse tile textures when appropriate<commit_after><|endoftext|>


<commit_before>// Copyright 2014 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.

// error-pattern: too big for the current architecture

#[cfg(target_word_size = "64")]
fn main() {
    let n = 0u;
    let a = box [&n,..0xF000000000000000u];
    println!("{}", a[0xFFFFFFu]);
}

#[cfg(target_word_size = "32")]
fn main() {
    let n = 0u;
    let a = box [&n,..0xFFFFFFFFu];
    println!("{}", a[0xFFFFFFu]);
}
<commit_msg>trailing whitespace<commit_after>// Copyright 2014 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.

// error-pattern: too big for the current architecture

#[cfg(target_word_size = "64")]
fn main() {
    let n = 0u;
    let a = box [&n,..0xF000000000000000u];
    println!("{}", a[0xFFFFFFu]);
}

#[cfg(target_word_size = "32")]
fn main() {
    let n = 0u;
    let a = box [&n,..0xFFFFFFFFu];
    println!("{}", a[0xFFFFFFu]);
}
<|endoftext|>


<commit_before><commit_msg>Auto merge of #28337 - apasel422:tests, r=alexcrichton<commit_after>// Copyright 2015 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.

trait Tr {}
type Huh<T> where T: Tr = isize; //~ ERROR type parameter `T` is unused
fn main() {}
<|endoftext|>


<commit_before>#[abi = "rust-intrinsic"]
extern mod rusti {
    fn sqrtf32(x: f32) -> f32;
    fn sqrtf64(x: f64) -> f64;
    fn powif32(a: f32, x: i32) -> f32;
    fn powif64(a: f64, x: i32) -> f64;
    fn sinf32(x: f32) -> f32;
    fn sinf64(x: f64) -> f64;
    fn cosf32(x: f32) -> f32;
    fn cosf64(x: f64) -> f64;
    fn powf32(a: f32, x: f32) -> f32;
    fn powf64(a: f64, x: f64) -> f64;
    fn expf32(x: f32) -> f32;
    fn expf64(x: f64) -> f64;
    fn exp2f32(x: f32) -> f32;
    fn exp2f64(x: f64) -> f64;
    fn logf32(x: f32) -> f32;
    fn logf64(x: f64) -> f64;
    fn log10f32(x: f32) -> f32;
    fn log10f64(x: f64) -> f64;
    fn log2f32(x: f32) -> f32;
    fn log2f64(x: f64) -> f64;
    fn fmaf32(a: f32, b: f32, c: f32) -> f32;
    fn fmaf64(a: f64, b: f64, c: f64) -> f64;
    fn fabsf32(x: f32) -> f32;
    fn fabsf64(x: f64) -> f64;
    fn floorf32(x: f32) -> f32;
    fn floorf64(x: f64) -> f64;
    fn ceilf32(x: f32) -> f32;
    fn ceilf64(x: f64) -> f64;
    fn truncf32(x: f32) -> f32;
    fn truncf64(x: f64) -> f64;
}

fn main() {

    use rusti::*;

    assert(sqrtf32(64f32) == 8f32);
    assert(sqrtf64(64f64) == 8f64);

    assert(powif32(25f32, -2i32) == 0.0016f32);
    assert(powif64(23.2f64, 2i32) == 538.24f64);

    assert(sinf32(0f32) == 0f32);
    assert(sinf64(f64::consts::pi / 2f64) == 1f64);

    assert(cosf32(0f32) == 1f32);
    assert(cosf64(f64::consts::pi * 2f64) == 1f64);

    assert(powf32(25f32, -2f32) == 0.0016f32);
    assert(powf64(400f64, 0.5f64) == 20f64);

    assert(expf32(1f32) == f32::consts::e);
    assert(expf64(1f64) == f64::consts::e);

    assert(exp2f32(10f32) == 1024f32);
    assert(exp2f64(50f64) == 1125899906842624f64);

    assert(logf32(f32::consts::e) == 1f32);
    assert(logf64(1f64) == 0f64);

    assert(log10f32(10f32) == 1f32);
    assert(log10f64(f64::consts::e) == f64::consts::log10_e);

    assert(log2f32(8f32) == 3f32);
    assert(log2f64(f64::consts::e) == f64::consts::log2_e);

    assert(fmaf32(1.0f32, 2.0f32, 5.0f32) == 7.0f32);
    assert(fmaf64(0.0f64, -2.0f64, f64::consts::e) == f64::consts::e);

    assert(fabsf32(-1.0f32) == 1.0f32);
    assert(fabsf64(34.2f64) == 34.2f64);

    assert(floorf32(3.8f32) == 3.0f32);
    assert(floorf64(-1.1f64) == -2.0f64);

    // Causes linker error
    // undefined reference to llvm.ceil.f32/64
    //assert(ceilf32(-2.3f32) == -2.0f32);
    //assert(ceilf64(3.8f64) == 4.0f64);

    // Causes linker error
    // undefined reference to llvm.trunc.f32/64
    //assert(truncf32(0.1f32) == 0.0f32);
    //assert(truncf64(-0.1f64) == 0.0f64);

}
<commit_msg>test: Fix float imprecision error on intrinsics-math<commit_after>#[abi = "rust-intrinsic"]
extern mod rusti {
    fn sqrtf32(x: f32) -> f32;
    fn sqrtf64(x: f64) -> f64;
    fn powif32(a: f32, x: i32) -> f32;
    fn powif64(a: f64, x: i32) -> f64;
    fn sinf32(x: f32) -> f32;
    fn sinf64(x: f64) -> f64;
    fn cosf32(x: f32) -> f32;
    fn cosf64(x: f64) -> f64;
    fn powf32(a: f32, x: f32) -> f32;
    fn powf64(a: f64, x: f64) -> f64;
    fn expf32(x: f32) -> f32;
    fn expf64(x: f64) -> f64;
    fn exp2f32(x: f32) -> f32;
    fn exp2f64(x: f64) -> f64;
    fn logf32(x: f32) -> f32;
    fn logf64(x: f64) -> f64;
    fn log10f32(x: f32) -> f32;
    fn log10f64(x: f64) -> f64;
    fn log2f32(x: f32) -> f32;
    fn log2f64(x: f64) -> f64;
    fn fmaf32(a: f32, b: f32, c: f32) -> f32;
    fn fmaf64(a: f64, b: f64, c: f64) -> f64;
    fn fabsf32(x: f32) -> f32;
    fn fabsf64(x: f64) -> f64;
    fn floorf32(x: f32) -> f32;
    fn floorf64(x: f64) -> f64;
    fn ceilf32(x: f32) -> f32;
    fn ceilf64(x: f64) -> f64;
    fn truncf32(x: f32) -> f32;
    fn truncf64(x: f64) -> f64;
}

fn main() {

    use rusti::*;

    assert(sqrtf32(64f32) == 8f32);
    assert(sqrtf64(64f64) == 8f64);

    assert(powif32(25f32, -2i32) == 0.0016f32);
    assert(powif64(23.2f64, 2i32) == 538.24f64);

    assert(sinf32(0f32) == 0f32);
    assert(sinf64(f64::consts::pi / 2f64) == 1f64);

    assert(cosf32(0f32) == 1f32);
    assert(cosf64(f64::consts::pi * 2f64) == 1f64);

    assert(powf32(25f32, -2f32) == 0.0016f32);
    assert(powf64(400f64, 0.5f64) == 20f64);

    assert(expf32(1f32) == f32::consts::e);
    assert(expf64(1f64) == f64::consts::e);

    assert(exp2f32(10f32) == 1024f32);
    assert(exp2f64(50f64) == 1125899906842624f64);

    assert(fabsf32(logf32(f32::consts::e) - 1f32) < 0.000001f32);
    assert(logf64(1f64) == 0f64);

    assert(log10f32(10f32) == 1f32);
    assert(log10f64(f64::consts::e) == f64::consts::log10_e);

    assert(log2f32(8f32) == 3f32);
    assert(log2f64(f64::consts::e) == f64::consts::log2_e);

    assert(fmaf32(1.0f32, 2.0f32, 5.0f32) == 7.0f32);
    assert(fmaf64(0.0f64, -2.0f64, f64::consts::e) == f64::consts::e);

    assert(fabsf32(-1.0f32) == 1.0f32);
    assert(fabsf64(34.2f64) == 34.2f64);

    assert(floorf32(3.8f32) == 3.0f32);
    assert(floorf64(-1.1f64) == -2.0f64);

    // Causes linker error
    // undefined reference to llvm.ceil.f32/64
    //assert(ceilf32(-2.3f32) == -2.0f32);
    //assert(ceilf64(3.8f64) == 4.0f64);

    // Causes linker error
    // undefined reference to llvm.trunc.f32/64
    //assert(truncf32(0.1f32) == 0.0f32);
    //assert(truncf64(-0.1f64) == 0.0f64);

}
<|endoftext|>


<commit_before><commit_msg>Add slop example<commit_after>extern crate clap;

use clap::{App, Arg};

/// myprog -f -p=bob -- sloppy slop slop
fn main() {

    let matches = App::new("myprog")
        .arg(Arg::with_name("eff")
            .short("f"))
        .arg(Arg::with_name("pea")
             .short("p")
             .takes_value(true))
        .arg(Arg::with_name("slop")
             .multiple(true))
        .get_matches();

    println!("-f used: {:?}", matches.is_present("eff"));
    println!("-p's value: {:?}", matches.value_of("pea"));
    println!("'slops' values: {:?}", matches.values_of("slop").map(|vals| vals.collect::<Vec<_>>()));

    // Continued program logic goes here...
}
<|endoftext|>


<commit_before><commit_msg>Add regression test for ICE in constant blocks<commit_after>// Copyright 2016 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.
#![feature(const_fn)]

const bad : u32 = {
    {
        5; //~ ERROR: blocks in constants are limited to items and tail expressions
        0
    }
};

const bad_two : u32 = {
    {
        invalid();
        //~^ ERROR: blocks in constants are limited to items and tail expressions
        //~^^ ERROR: calls in constants are limited to constant functions, struct and enum
        0
    }
};

const bad_three : u32 = {
    {
        valid();
        //~^ ERROR: blocks in constants are limited to items and tail expressions
        0
    }
};

static bad_four : u32 = {
    {
        5; //~ ERROR: blocks in statics are limited to items and tail expressions
        0
    }
};

static bad_five : u32 = {
    {
        invalid();
        //~^ ERROR: blocks in statics are limited to items and tail expressions
        //~^^ ERROR: calls in statics are limited to constant functions, struct and enum
        0
    }
};

static bad_six : u32 = {
    {
        valid();
        //~^ ERROR: blocks in statics are limited to items and tail expressions
        0
    }
};

static mut bad_seven : u32 = {
    {
        5; //~ ERROR: blocks in statics are limited to items and tail expressions
        0
    }
};

static mut bad_eight : u32 = {
    {
        invalid();
        //~^ ERROR: blocks in statics are limited to items and tail expressions
        //~^^ ERROR: calls in statics are limited to constant functions, struct and enum
        0
    }
};

static mut bad_nine : u32 = {
    {
        valid();
        //~^ ERROR: blocks in statics are limited to items and tail expressions
        0
    }
};

fn invalid() {}
const fn valid() {}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>lifetime issue solved by moving the memory out of removed stack frame<commit_after><|endoftext|>


<commit_before><commit_msg>Include event loop example<commit_after>extern crate asynchronous;

use asynchronous::{Promise, EventLoop};

#[derive(Debug)]
enum Event {
    Hello(String),
    Goodbye(u32)
}

fn function_test() {
    let event_loop_a = EventLoop::on(move |event| {
        match event {
            Event::Hello(t) => {
                println!("Hello {}", t);
                None
            },
            Event::Goodbye(v) => {
                println!("Farewell {}", v);
                Some(Event::Goodbye(v))
            },
        }
    }).finish_in_ms(50);

    let event_loop_b = EventLoop::new();

    let e_l = event_loop_a.clone();
    let promise = Promise::<_,()>::new(move || {
        &e_l.emit(Event::Hello("Inside Promise".to_string()));
        Ok(e_l)
    }).success(|e_l| {
        &e_l.emit(Event::Goodbye(1));
        Ok(e_l)
    });

    &event_loop_a.emit(Event::Hello("World".to_string()));
    &event_loop_b.emit("TestA");
    let x = std::sync::Arc::new(std::sync::Mutex::new(0));
    event_loop_b.emit_until(move || {
        let mut lock_x = x.lock().unwrap(); *lock_x += 1;
        if *lock_x <= 3 { Some("TestB") } else { None }
    });
    &event_loop_a.emit(Event::Goodbye(2));
    let _ = promise.sync();
    &event_loop_a.emit(Event::Goodbye(3));
    println!("Result 4: {:?}", event_loop_a.emit(Event::Goodbye(4)));
    let event_loop_a = event_loop_a.finish();
    println!("Result 5: {:?}", event_loop_a.emit(Event::Goodbye(5)));
    &event_loop_b.emit("TestC");
    println!("Result 6: {:?}", event_loop_a.emit(Event::Goodbye(6)));

    &event_loop_a.to_promise().then(|res| {
        let lock = res.lock().unwrap();
        println!("Event Loop a: {:?} ", *lock);
        event_loop_b.finish().to_promise().sync()
    }, |error| {
        println!("Error in loop a: {:?}", error);
        Err(())
    }).success(|res| {
        let lock = res.lock().unwrap();
        println!("Event Loop b: {:?} ", *lock);
        Ok(())
    }).sync();

}

fn main () {
    function_test();
}<|endoftext|>


<commit_before><commit_msg>Add regression test for #21177<commit_after>// Copyright 2015 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.

trait Trait {
    type A;
    type B;
}

fn foo<T: Trait<A = T::B>>() { }
//~^ ERROR: unsupported cyclic reference between types/traits detected

fn main() { }
<|endoftext|>


<commit_before><commit_msg>Add test for #27433<commit_after>// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <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.

fn main() {
    let foo = 42u32;
    const FOO : u32 = foo;
                   //~^ ERROR attempt to use a non-constant value in a constant
}
<|endoftext|>


<commit_before><commit_msg>Rollup merge of #47704 - dsprenkels:issue-44415, r=alexcrichton<commit_after>// Copyright 2018 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.

#![feature(const_fn)]
#![feature(core_intrinsics)]

use std::intrinsics;

struct Foo {
    bytes: [u8; unsafe { intrinsics::size_of::<Foo>() }],
    //~^ ERROR unsupported cyclic reference between types/traits detected
    x: usize,
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Add test for issue 18060.<commit_after>// Copyright 2016 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.

// Regression test for #18060: match arms were matching in the wrong order.

fn main() {
    assert_eq!(2, match (1, 3) { (0, 2...5) => 1, (1, 3) => 2, (_, 2...5) => 3, (_, _) => 4 });
    assert_eq!(2, match (1, 3) {                  (1, 3) => 2, (_, 2...5) => 3, (_, _) => 4 });
    assert_eq!(2, match (1, 7) { (0, 2...5) => 1, (1, 7) => 2, (_, 2...5) => 3, (_, _) => 4 });
}
<|endoftext|>


<commit_before><commit_msg>Managed boxes<commit_after>fn main() {
  let x: @int = @10;
  println((*x).to_str());
}

<|endoftext|>


<commit_before><commit_msg>an empy message<commit_after><|endoftext|>


<commit_before><commit_msg> removed filter for testing<commit_after><|endoftext|>


<commit_before><commit_msg>nbertagnolli's rust solution to subset sum problem<commit_after>/// This File takes in a list of integers separated by commas and determines if the sum
/// of two integers in the list is zero.  The full problem description  can be found
/// here https://redd.it/68oda5
///
/// Author: Nicolas Bertagnolli
/// Date: 2017-05-07

// Import necessary libraries
use std::io;
use std::collections::HashMap;

fn main() {
    println!("Enter a list and we will see if two numbers add to 0");

    // Create a holder for the raw input
    let mut raw_input = String::new();

    // Read from standard in
    io::stdin()
        .read_line(&mut raw_input)
        .expect("Failed to read line");

    // print out the input that was entered
    println!("You entered:  {}", raw_input);

    // Create a hashmap of the integer values
    let int_map = string_to_map(raw_input);

    // print out whether or not two elements add to 0
    let answer = sum_to_zero(int_map);
    println!("{}", answer);
}

/// Converts a string of integers to a hashmap
///
/// # Args
/// s: String of the form 1,2,3,... to be converted to a hashmap
///
/// # Returns
/// HashMap<int32, int32> that maps an integer to itself
fn string_to_map(s: String) -> HashMap<i32, i32> {

    // split the input string based on ,
    let split = s.split(',');

    // initialize a hashmap to store the integers.
    let mut map = HashMap::new();

    for string in split {
        println!("{}", string);

        // convert each string element to an integer
        let s2: i32 = string
            .trim()
            .parse()
            .expect("Wanted a number");

        // Add each integer to the map
        map.insert(s2, s2);
    }

    return map;
}

/// Checks to see if there is a pair of values that sum to 0 in a given map
///
/// If two elements sum to zero then both a and -a are present in the map
/// so all we need to do is check if there exists a such that -a is also
/// present.  This is O(n) since the HashMap is o(1) access and we only
/// need to check every element.
///
/// # Args:
/// map: A hash map of integers to integers
///
/// # Returns
/// Boolean value true if there exists a pair of elements that sum to 0
///     false otherwise
fn sum_to_zero(map: HashMap<i32, i32>) -> bool {
    for (int1, int2) in &map {
        let temp = -1 * int2;
        match map.get(&temp) {
            Some(review) => return true,
            None =>  continue
        }
    }
    return false;
}
<|endoftext|>


<commit_before><commit_msg>test unchecked_rem<commit_after>#![feature(core_intrinsics)]

use std::intrinsics::*;

//error-pattern: Division by 0 in unchecked_rem

fn main() {
    unsafe {
        let _n = unchecked_rem(3u32, 0);
    }
}
<|endoftext|>


<commit_before><commit_msg>Reorder the device creation to just before swapchain creation<commit_after><|endoftext|>


<commit_before><commit_msg>Fix #558 Closes #558<commit_after><|endoftext|>


<commit_before>#[doc="A new implementation of communication.

This should be implementing almost entirely in Rust, and hopefully
avoid needing a single global lock."]

import arc::methods;
import dvec::dvec;
import dvec::{extensions};

export port;
export chan;
export send, recv;
export methods;

type raw_port<T: send> = arc::exclusive<dvec<T>>;

enum port<T: send> {
    port_(raw_port<T>)
}
enum chan<T: send> {
    chan_(raw_port<T>)
}

fn port<T: send>() -> port<T> {
    port_(arc::exclusive(dvec()))
}

fn chan<T: send>(p: port<T>) -> chan<T> {
    chan_((*p).clone())
}

fn send<T: send>(c: chan<T>, -x: T) {
    let mut x <- some(x);
    (*c).with {|cond, data|
        let mut xx = none;
        xx <-> x;
        alt xx {
          some(y) {
            let mut x <- y;
            (*data).push(x);
            cond.signal();
          }
          none { fail }
        };
    }
}

fn recv<T: send>(p: port<T>) -> T {
    (*p).with {|cond, data|
        if (*data).len() == 0u {
            cond.wait();
        }
        assert (*data).len() > 0u;
        (*data).shift()
    }
}

impl methods<T: send> for chan<T> {
    fn send(-x: T) {
        send(self, x)
    }

    fn clone() -> chan<T> {
        chan_((*self).clone())
    }
}

impl methods<T: send> for port<T> {
    fn recv() -> T {
        recv(self)
    }

    fn chan() -> chan<T> {
        chan(self)
    }
}

#[cfg(test)]
mod test {
    #[test]
    fn newport_simple() {
        let p = port();
        let c = chan(p);

        c.send(42);
        assert p.recv() == 42;
    }
}
<commit_msg>Fixing illegal moves.<commit_after>#[doc="A new implementation of communication.

This should be implementing almost entirely in Rust, and hopefully
avoid needing a single global lock."]

import arc::methods;
import dvec::dvec;
import dvec::{extensions};

export port;
export chan;
export send, recv;
export methods;

type raw_port<T: send> = arc::exclusive<dvec<T>>;

enum port<T: send> {
    port_(raw_port<T>)
}
enum chan<T: send> {
    chan_(raw_port<T>)
}

fn port<T: send>() -> port<T> {
    port_(arc::exclusive(dvec()))
}

fn chan<T: send>(p: port<T>) -> chan<T> {
    chan_((*p).clone())
}

fn send<T: send>(c: chan<T>, -x: T) {
    let mut x <- some(x);
    (*c).with {|cond, data|
        let mut xx = none;
        xx <-> x;
        (*data).push(option::unwrap(xx));
        cond.signal();
    }
}

fn recv<T: send>(p: port<T>) -> T {
    (*p).with {|cond, data|
        if (*data).len() == 0u {
            cond.wait();
        }
        assert (*data).len() > 0u;
        (*data).shift()
    }
}

impl methods<T: send> for chan<T> {
    fn send(-x: T) {
        send(self, x)
    }

    fn clone() -> chan<T> {
        chan_((*self).clone())
    }
}

impl methods<T: send> for port<T> {
    fn recv() -> T {
        recv(self)
    }

    fn chan() -> chan<T> {
        chan(self)
    }
}

#[cfg(test)]
mod test {
    #[test]
    fn newport_simple() {
        let p = port();
        let c = chan(p);

        c.send(42);
        assert p.recv() == 42;
    }
}
<|endoftext|>