<commit_before>use bits;
use baseband::consts::SYNC_SYMBOLS;

use self::StatusCode::*;
use self::StreamSymbol::*;

/// Number of dibits output per status period, including the status symbol.
const DIBITS_PER_UPDATE: u32 = 70 / 2 + 1;

pub trait StatusSource {
    fn status(&mut self) -> StatusCode;
}

pub struct StatusInterleaver<T, S> where
    T: Iterator<Item = bits::Dibit>,
    S: StatusSource
{
    /// Source of dibits to interleave status symbols into.
    src: T,
    /// Source of status updates.
    status: S,
    /// Current dibit index in output stream.
    pos: u32,
}

impl<T, S> StatusInterleaver<T, S> where
    T: Iterator<Item = bits::Dibit>,
    S: StatusSource
{
    pub fn new(src: T, status: S) -> StatusInterleaver<T, S> {
        StatusInterleaver {
            status: status,
            src: src,
            pos: 0,
        }
    }
}

impl<T, S> Iterator for StatusInterleaver<T, S> where
    T: Iterator<Item = bits::Dibit>,
    S: StatusSource
{
    type Item = bits::Dibit;

    fn next(&mut self) -> Option<Self::Item> {
        self.pos += 1;
        self.pos %= DIBITS_PER_UPDATE;

        if self.pos == 0 {
            return Some(self.status.status().to_dibit());
        }

        match self.src.next() {
            Some(d) => Some(d),
            // If just after an update and no more source dibits, end the iteration.
            None if self.pos == 1 => None,
            // Pad until the next update.
            None => Some(bits::Dibit::new(0b00)),
        }
    }
}

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum StatusCode {
    /// Used by a repeater when the inbound channel is idle.
    InboundIdle,
    /// Used by a repeater when the inbound channel is busy.
    InboundBusy,
    /// Used when a subscriber is transmitting to a repeater.
    SubscriberRepeater,
    /// Used when a subscriber is transmitting directly to another subscriber.
    SubscriberDirect,
}

impl StatusCode {
    pub fn from_dibit(d: bits::Dibit) -> StatusCode {
        match d.bits() {
            0b01 => InboundBusy,
            0b00 => SubscriberDirect,
            0b10 => SubscriberRepeater,
            0b11 => InboundIdle,
            _ => unreachable!(),
        }
    }

    pub fn to_dibit(&self) -> bits::Dibit {
        bits::Dibit::new(match *self {
            InboundBusy => 0b01,
            SubscriberDirect => 0b00,
            SubscriberRepeater => 0b10,
            InboundIdle => 0b11,
        })
    }
}

/// A symbol in a transmitted P25 stream.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum StreamSymbol {
    /// Current symbol is a status code.
    Status(StatusCode),
    /// Current symbol is a data dibit.
    Data(bits::Dibit),
}

/// Deinterleave a P25 transmitted stream into status codes and data symbols.
#[derive(Copy, Clone)]
pub struct StatusDeinterleaver {
    pos: u32,
}

impl StatusDeinterleaver {
    pub fn new() -> StatusDeinterleaver {
        StatusDeinterleaver {
            pos: SYNC_SYMBOLS as u32,
        }
    }

    pub fn feed(&mut self, d: bits::Dibit) -> StreamSymbol {
        self.pos += 1;
        self.pos %= DIBITS_PER_UPDATE;

        if self.pos == 0 {
            Status(StatusCode::from_dibit(d))
        } else {
            Data(d)
        }
    }
}

#[cfg(test)]
mod test {
    use bits;
    use super::*;
    use std;

    #[test]
    fn test_interleave() {
        struct TestSource;
        impl StatusSource for TestSource {
            fn status(&mut self) -> StatusCode { StatusCode::InboundBusy }
        }

        let src = std::iter::repeat(bits::Dibit::new(0b10));
        let mut i = StatusInterleaver::new(src, TestSource);

        for _ in 0..35 {
            assert_eq!(i.next(), Some(bits::Dibit::new(0b10)));
        }

        assert_eq!(i.next(), Some(bits::Dibit::new(0b01)));

        for _ in 0..35 {
            assert_eq!(i.next(), Some(bits::Dibit::new(0b10)));
        }

        assert_eq!(i.next(), Some(bits::Dibit::new(0b01)));
    }

    #[test]
    fn test_deinterleave() {
        let mut d = StatusDeinterleaver::new();

        for _ in 0..11 {
            assert_eq!(d.feed(bits::Dibit::new(0)),
                StreamSymbol::Data(bits::Dibit::new(0)));
        }

        assert_eq!(d.feed(bits::Dibit::new(0)), StreamSymbol::Status(
                StatusCode::SubscriberDirect));

        for _ in 0..35 {
            assert_eq!(d.feed(bits::Dibit::new(0)),
                StreamSymbol::Data(bits::Dibit::new(0)));
        }

        assert_eq!(d.feed(bits::Dibit::new(0)), StreamSymbol::Status(
                StatusCode::SubscriberDirect));

        for _ in 0..35 {
            assert_eq!(d.feed(bits::Dibit::new(0)),
                StreamSymbol::Data(bits::Dibit::new(0)));
        }

        assert_eq!(d.feed(bits::Dibit::new(0)), StreamSymbol::Status(
                StatusCode::SubscriberDirect));
    }
}
<commit_msg>Add docs to status module<commit_after>//! Status symbol interleaving and deinterleaving.

use bits;
use baseband::consts::SYNC_SYMBOLS;

use self::StatusCode::*;
use self::StreamSymbol::*;

/// Number of dibits output per status period, including the status symbol.
const DIBITS_PER_UPDATE: u32 = 70 / 2 + 1;

/// A source of status symbols.
pub trait StatusSource {
    /// The current status.
    fn status(&mut self) -> StatusCode;
}

/// Interleaves status symbols into a stream of dibits.
pub struct StatusInterleaver<T, S> where
    T: Iterator<Item = bits::Dibit>,
    S: StatusSource
{
    /// Source of dibits to interleave status symbols into.
    src: T,
    /// Source of status updates.
    status: S,
    /// Current dibit index in output stream.
    pos: u32,
}

impl<T, S> StatusInterleaver<T, S> where
    T: Iterator<Item = bits::Dibit>,
    S: StatusSource
{
    pub fn new(src: T, status: S) -> StatusInterleaver<T, S> {
        StatusInterleaver {
            status: status,
            src: src,
            pos: 0,
        }
    }
}

impl<T, S> Iterator for StatusInterleaver<T, S> where
    T: Iterator<Item = bits::Dibit>,
    S: StatusSource
{
    type Item = bits::Dibit;

    fn next(&mut self) -> Option<Self::Item> {
        self.pos += 1;
        self.pos %= DIBITS_PER_UPDATE;

        if self.pos == 0 {
            return Some(self.status.status().to_dibit());
        }

        match self.src.next() {
            Some(d) => Some(d),
            // If just after an update and no more source dibits, end the iteration.
            None if self.pos == 1 => None,
            // Pad until the next update.
            None => Some(bits::Dibit::new(0b00)),
        }
    }
}

/// A P25 status symbol.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum StatusCode {
    /// Used by a repeater when the inbound channel is idle.
    InboundIdle,
    /// Used by a repeater when the inbound channel is busy.
    InboundBusy,
    /// Used when a subscriber is transmitting to a repeater.
    SubscriberRepeater,
    /// Used when a subscriber is transmitting directly to another subscriber.
    SubscriberDirect,
}

impl StatusCode {
    /// Parse a status code from the given dibit.
    pub fn from_dibit(d: bits::Dibit) -> StatusCode {
        match d.bits() {
            0b01 => InboundBusy,
            0b00 => SubscriberDirect,
            0b10 => SubscriberRepeater,
            0b11 => InboundIdle,
            _ => unreachable!(),
        }
    }

    /// Convert the current status code into a dibit.
    pub fn to_dibit(&self) -> bits::Dibit {
        bits::Dibit::new(match *self {
            InboundBusy => 0b01,
            SubscriberDirect => 0b00,
            SubscriberRepeater => 0b10,
            InboundIdle => 0b11,
        })
    }
}

/// A symbol in a transmitted P25 stream.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum StreamSymbol {
    /// Current symbol is a status code.
    Status(StatusCode),
    /// Current symbol is a data dibit.
    Data(bits::Dibit),
}

/// Deinterleave a P25 transmitted stream into status codes and data symbols.
#[derive(Copy, Clone)]
pub struct StatusDeinterleaver {
    /// Current dibit position in current status period.
    pos: u32,
}

impl StatusDeinterleaver {
    /// Create a new `StatusDeinterleaver` for deinterlacing immediately after the frame sync
    /// sequence.
    pub fn new() -> StatusDeinterleaver {
        StatusDeinterleaver {
            // Since stream deinterleaving is started after the frame sync, and the frame sync
            // symbols count towards the first status symbol period, start the counter with those
            // symbols taken into account.
            pos: SYNC_SYMBOLS as u32,
        }
    }

    /// Parse the given symbol as a status or data symbol.
    pub fn feed(&mut self, d: bits::Dibit) -> StreamSymbol {
        self.pos += 1;
        self.pos %= DIBITS_PER_UPDATE;

        if self.pos == 0 {
            Status(StatusCode::from_dibit(d))
        } else {
            Data(d)
        }
    }
}

#[cfg(test)]
mod test {
    use bits;
    use super::*;
    use std;

    #[test]
    fn test_interleave() {
        struct TestSource;
        impl StatusSource for TestSource {
            fn status(&mut self) -> StatusCode { StatusCode::InboundBusy }
        }

        let src = std::iter::repeat(bits::Dibit::new(0b10));
        let mut i = StatusInterleaver::new(src, TestSource);

        for _ in 0..35 {
            assert_eq!(i.next(), Some(bits::Dibit::new(0b10)));
        }

        assert_eq!(i.next(), Some(bits::Dibit::new(0b01)));

        for _ in 0..35 {
            assert_eq!(i.next(), Some(bits::Dibit::new(0b10)));
        }

        assert_eq!(i.next(), Some(bits::Dibit::new(0b01)));
    }

    #[test]
    fn test_deinterleave() {
        let mut d = StatusDeinterleaver::new();

        for _ in 0..11 {
            assert_eq!(d.feed(bits::Dibit::new(0)),
                StreamSymbol::Data(bits::Dibit::new(0)));
        }

        assert_eq!(d.feed(bits::Dibit::new(0)), StreamSymbol::Status(
                StatusCode::SubscriberDirect));

        for _ in 0..35 {
            assert_eq!(d.feed(bits::Dibit::new(0)),
                StreamSymbol::Data(bits::Dibit::new(0)));
        }

        assert_eq!(d.feed(bits::Dibit::new(0)), StreamSymbol::Status(
                StatusCode::SubscriberDirect));

        for _ in 0..35 {
            assert_eq!(d.feed(bits::Dibit::new(0)),
                StreamSymbol::Data(bits::Dibit::new(0)));
        }

        assert_eq!(d.feed(bits::Dibit::new(0)), StreamSymbol::Status(
                StatusCode::SubscriberDirect));
    }
}
<|endoftext|>


<commit_before>// Copyright (c) 2015, The Radare Project. All rights reserved.
// See the COPYING file at the top-level directory of this distribution.
// Licensed under the BSD 3-Clause License:
// <http://opensource.org/licenses/BSD-3-Clause>
// This file may not be copied, modified, or distributed
// except according to those terms.

//! Contains the struct `SubRegisterFile` which extends `PhiPlacer`s
//! functionality by reads and writes to partial registers.

use std::cmp::Ordering;
use std::collections::HashMap;
use std::convert::From;

use r2api::structs::LRegInfo;

use middle::ssa::ssa_traits::ValueType;

#[derive(Clone, Debug, Default)]
pub struct RegInfo {
    pub name: String,
    pub type_info: Option<String>,
    pub alias_info: Option<String>,
    pub width: Option<usize>,
}

#[derive(Clone, Copy, Debug)]
pub struct SubRegister {
    pub base: usize,
    pub shift: usize,
    pub width: usize,
}

impl SubRegister {
    fn new(base: usize, shift: usize, width: usize) -> SubRegister {
        SubRegister {
            base: base,
            shift: shift,
            width: width,
        }
    }
}

/// A structure containing information about whole and partial registers of a platform.
/// Upon creation it builds a vector of `ValueType`s representing whole registers
/// to be added to a `PhiPlacer`.
///
/// It can then translate accesses to partial registers to accesses of whole registers.
/// Shifts and masks are added automatically.
#[derive(Clone, Debug)]
pub struct SubRegisterFile {
    /// `ValueType`s of whole registers ready to be added to a `PhiPlacer`.
    /// The index within `PhiPlacer` to the first register is needed
    /// as argument `base` to `read_register` and `write_register` later.
    pub whole_registers: Vec<ValueType>,
    /// Contains the respective names for the registers described in `whole_registers`
    pub whole_names: Vec<String>,
    named_registers: HashMap<String, SubRegister>,
    /// Contains the alias information for some registers.
    pub alias_info: HashMap<String, String>,
    /// Contains the type information for every registers.
    pub type_info: HashMap<String, String>,
}

impl SubRegisterFile {
    /// Creates a new SubRegisterFile based on a provided register profile.
    pub fn new(reg_info: &LRegInfo) -> SubRegisterFile {
        let mut aliases: HashMap<String, String> = HashMap::new();
        for reg in &reg_info.alias_info {
            aliases.insert(reg.reg.clone(), reg.role_str.clone());
        }

        let mut slices = HashMap::new();
        let mut events: Vec<SubRegister> = Vec::new();
        let mut types: HashMap<String, String> = HashMap::new();
        for (i, reg) in reg_info.reg_info.iter().enumerate() {
            types.insert(reg.name.clone(), reg.type_str.clone());
            if reg.type_str == "fpu" {
                continue;
            } // st7 from "fpu" overlaps with zf from "gpr" (r2 bug?)
            if reg.name.ends_with("flags") {
                continue;
            } // HARDCODED x86
            events.push(SubRegister::new(i, reg.offset, reg.size));
        }

        events.sort_by(|a, b| {
            let o = a.shift.cmp(&b.shift);
            if let Ordering::Equal = o {
                (b.width + b.shift).cmp(&(a.width + a.shift))
            } else {
                o
            }
        });

        let mut current = SubRegister::new(0, 0, 0);
        let mut whole: Vec<ValueType> = Vec::new();
        let mut names: Vec<String> = Vec::new();
        for &ev in &events {
            let name = &reg_info.reg_info[ev.base].name;
            let cur_until = current.shift + current.width;
            if ev.shift >= cur_until {
                current = ev;

                radeco_trace!("regfile_mappings|{} -> {}", whole.len(), &name);

                whole.push(From::from(current.width));
                names.push(name.clone());
            } else {
                let ev_until = ev.width + ev.shift;
                assert!(ev_until <= cur_until);
            }

            let subreg = SubRegister::new(whole.len() - 1, ev.shift - current.shift, ev.width);

            slices.insert(name.clone(), subreg);
        }

        SubRegisterFile {
            whole_registers: whole,
            named_registers: slices,
            whole_names: names,
            alias_info: aliases,
            type_info: types,
        }
    }

    // API for Sub Reigster.
    pub fn get_subregister(&self, name: &str) -> Option<SubRegister> {
        self.named_registers.get(name).cloned()
    }

    // API for whole register.

    // Get information by id.
    pub fn get_name(&self, id: usize) -> Option<String> {
        Some(self.whole_names[id].clone())
    }

    pub fn get_width(&self, id: usize) -> Option<usize> {
        if let Some(name) = self.get_name(id) {
            if let Some(subreg) = self.named_registers.get(&name) {
                Some(subreg.width)
            } else {
                None
            }
        } else {
            None
        }
    }

    pub fn get_reginfo(&self, id: usize) -> Option<RegInfo> {
        if let Some(name) = self.get_name(id) {
            Some(RegInfo {
                name: name.clone(),
                type_info: self.type_info.get(&name).cloned(),
                alias_info: self.alias_info.get(&name).cloned(),
                width: self.get_width(id),
            })
        } else {
            None
        }
    }

    // Get information by other way.
    pub fn get_name_by_alias(&self, alias: &String) -> Option<String> {
        for id in 0..self.whole_names.len() {
            if let Some(name) = self.get_name(id) {
                if self.alias_info.get(&name) == Some(alias) {
                    return Some(name);
                }
            }
        }
        None
    }

    pub fn get_reginfo_by_name(&self, name: &String) -> Option<RegInfo> {
        for id in 0..self.whole_names.len() {
            if Some(name) == self.get_name(id).as_ref() {
                return Some(RegInfo {
                            name: name.clone(),
                            type_info: self.type_info.get(name).cloned(),
                            alias_info: self.alias_info.get(name).cloned(),
                            width: self.get_width(id),
                });
            }
        }
        None
    }

    // Emit code for setting the specified register to the specified value.
    // Will automatically insert code for shifting and masking in case of subregisters.
    // This implies that it also tries to read the old value of the whole register.
    //
    // # Arguments
    // * `phiplacer` - A PhiPlacer that has already been informed of our variables.
    //                 It will also give us access to the SSA to modify
    // * `base`      - Index of the PhiPlacer variable that corresponds to our first register.
    // * `block`     - Reference to the basic block to which operations will be appended.
    // * `var`       - Name of the register to write as a string.
    // * `value`     - An SSA node whose value shall be assigned to the register.
    //                 As with most APIs in radeco, we will not check if the value is reachable
    //                 from the position where the caller is trying to insert these operations.

    //pub fn write_register<'a, T>(&self,
                                 //phip: &mut PhiPlacer<'a, T>,
                                 //base: usize,
                                 //block: T::ActionRef,
                                 //var: &String,
                                 //mut value: T::ValueRef,
                                 //addr: u64)
        //where T: 'a + SSAMod<BBInfo = BBInfo> + VerifiedAdd
    //{
        //let info = &self.named_registers[var];
        //let id = info.base + base;

        //let width = match phip.variable_types[id] {
            //ValueType::Integer { width } => width,
        //};

        //if info.width >= width as usize {
            //phip.write_variable(block, id, value);
            //return;
        //}

        //// Need to add a cast.
        //let vt = From::from(width);
        //let opcode = MOpcode::OpWiden(width as WidthSpec);

        //if phip.ssa.get_node_data(&value).ok().map_or(0, |nd| {
            //match nd.vt {
                //ValueType::Integer{width} => width,
            //}
        //}) < width {
            //value = phip.ssa.verified_add_op(block, opcode, vt, &[value], Some(addr));
        //}

        //let mut new_value;

        //if info.shift > 0 {
            //let shift_amount_node = phip.add_const(block, info.shift as u64);
            //new_value = phip.ssa.verified_add_op(block,
                                                 //MOpcode::OpLsl,
                                                 //vt,
                                                 //&[value, shift_amount_node],
                                                 //Some(addr));
            //value = new_value;
        //}

        //let fullval: u64 = !((!1u64) << (width - 1));
        //let maskval: u64 = ((!((!1u64) << (info.width - 1))) << info.shift) ^ fullval;

        //if maskval == 0 {
            //phip.write_variable(block, id, value);
            //return;
        //}

        //let mut ov = phip.read_variable(block, id);
        //let maskvalue_node = phip.add_const(block, maskval);
        //new_value = phip.ssa.verified_add_op(block,
                                             //MOpcode::OpAnd,
                                             //vt,
                                             //&[ov, maskvalue_node],
                                             //Some(addr));

        //ov = new_value;
        //new_value = phip.ssa.verified_add_op(block, MOpcode::OpOr, vt, &[value, ov], Some(addr));
        //value = new_value;
        //phip.write_variable(block, id, value);
    //}

    // Emit code for reading the current value of the specified register.
    //
    // # Arguments
    // * `phiplacer` - A PhiPlacer that has already been informed of our variables.
    //                 It will also give us access to the SSA to modify
    // * `base`      - Index of the PhiPlacer variable that corresponds to our first register.
    // * `block`     - Reference to the basic block to which operations will be appended.
    // * `var`       - Name of the register to read as a string.
    //
    // # Return value
    // A SSA node representing the value of the register as seen by the current end of `block`.
    // Unless prior basic blocks are marked as sealed in the PhiPlacer this will always return
    // a reference to a Phi node.
    // Either way, once nodes are sealed redundant Phi nodes are eliminated by PhiPlacer.

    //pub fn read_register<'a, T>(&self,
                                //phiplacer: &mut PhiPlacer<'a, T>,
                                //base: usize,
                                //block: T::ActionRef,
                                //var: &String,
                                //addr: u64)
                                //-> T::ValueRef
        //where T: SSAMod<BBInfo = BBInfo> + VerifiedAdd + 'a
    //{
        //let info = &self.named_registers[var];
        //let id = info.base + base;
        //let mut value = phiplacer.read_variable(block, id);

        //let width = match phiplacer.variable_types[id] {
            //ValueType::Integer { width } => width,
        //};

        //if info.shift > 0 {
            //let shift_amount_node = phiplacer.add_const(block, info.shift as u64);
            //let opcode = MOpcode::OpLsr;
            //let vtype = From::from(width);
            //let new_value = phiplacer.ssa.verified_add_op(block,
                                                          //opcode,
                                                          //vtype,
                                                          //&[value, shift_amount_node],
                                                          //Some(addr));
            //value = new_value;
        //}

        //if info.width < (width as usize) {
            //let opcode = MOpcode::OpNarrow(info.width as WidthSpec);
            //let vtype = From::from(info.width);
            //let new_value = phiplacer.ssa
                                     //.verified_add_op(block, opcode, vtype, &[value], Some(addr));
            //value = new_value;
        //}
        //value
    //}
}
<commit_msg>Remove RegInfo Struct<commit_after>// Copyright (c) 2015, The Radare Project. All rights reserved.
// See the COPYING file at the top-level directory of this distribution.
// Licensed under the BSD 3-Clause License:
// <http://opensource.org/licenses/BSD-3-Clause>
// This file may not be copied, modified, or distributed
// except according to those terms.

//! Contains the struct `SubRegisterFile` which extends `PhiPlacer`s
//! functionality by reads and writes to partial registers.

use std::cmp::Ordering;
use std::collections::HashMap;
use std::convert::From;

use r2api::structs::LRegInfo;

use middle::ssa::ssa_traits::ValueType;

#[derive(Clone, Copy, Debug)]
pub struct SubRegister {
    pub base: usize,
    pub shift: usize,
    pub width: usize,
}

impl SubRegister {
    fn new(base: usize, shift: usize, width: usize) -> SubRegister {
        SubRegister {
            base: base,
            shift: shift,
            width: width,
        }
    }
}

/// A structure containing information about whole and partial registers of a platform.
/// Upon creation it builds a vector of `ValueType`s representing whole registers
/// to be added to a `PhiPlacer`.
///
/// It can then translate accesses to partial registers to accesses of whole registers.
/// Shifts and masks are added automatically.
#[derive(Clone, Debug)]
pub struct SubRegisterFile {
    /// `ValueType`s of whole registers ready to be added to a `PhiPlacer`.
    /// The index within `PhiPlacer` to the first register is needed
    /// as argument `base` to `read_register` and `write_register` later.
    pub whole_registers: Vec<ValueType>,
    /// Contains the respective names for the registers described in `whole_registers`
    pub whole_names: Vec<String>,
    named_registers: HashMap<String, SubRegister>,
    /// Contains the alias information for some registers.
    pub alias_info: HashMap<String, String>,
    /// Contains the type information for every registers.
    pub type_info: HashMap<String, String>,
}

impl SubRegisterFile {
    /// Creates a new SubRegisterFile based on a provided register profile.
    pub fn new(reg_info: &LRegInfo) -> SubRegisterFile {
        let mut aliases: HashMap<String, String> = HashMap::new();
        for reg in &reg_info.alias_info {
            aliases.insert(reg.reg.clone(), reg.role_str.clone());
        }

        let mut slices = HashMap::new();
        let mut events: Vec<SubRegister> = Vec::new();
        let mut types: HashMap<String, String> = HashMap::new();
        for (i, reg) in reg_info.reg_info.iter().enumerate() {
            types.insert(reg.name.clone(), reg.type_str.clone());
            if reg.type_str == "fpu" {
                continue;
            } // st7 from "fpu" overlaps with zf from "gpr" (r2 bug?)
            if reg.name.ends_with("flags") {
                continue;
            } // HARDCODED x86
            events.push(SubRegister::new(i, reg.offset, reg.size));
        }

        events.sort_by(|a, b| {
            let o = a.shift.cmp(&b.shift);
            if let Ordering::Equal = o {
                (b.width + b.shift).cmp(&(a.width + a.shift))
            } else {
                o
            }
        });

        let mut current = SubRegister::new(0, 0, 0);
        let mut whole: Vec<ValueType> = Vec::new();
        let mut names: Vec<String> = Vec::new();
        for &ev in &events {
            let name = &reg_info.reg_info[ev.base].name;
            let cur_until = current.shift + current.width;
            if ev.shift >= cur_until {
                current = ev;

                radeco_trace!("regfile_mappings|{} -> {}", whole.len(), &name);

                whole.push(From::from(current.width));
                names.push(name.clone());
            } else {
                let ev_until = ev.width + ev.shift;
                assert!(ev_until <= cur_until);
            }

            let subreg = SubRegister::new(whole.len() - 1, ev.shift - current.shift, ev.width);

            slices.insert(name.clone(), subreg);
        }

        SubRegisterFile {
            whole_registers: whole,
            named_registers: slices,
            whole_names: names,
            alias_info: aliases,
            type_info: types,
        }
    }

    // API for Sub Reigster.
    pub fn get_subregister(&self, name: &str) -> Option<SubRegister> {
        self.named_registers.get(name).cloned()
    }

    // API for whole register.

    // Get information by id.
    pub fn get_name(&self, id: usize) -> Option<String> {
        Some(self.whole_names[id].clone())
    }

    pub fn get_width(&self, id: usize) -> Option<usize> {
        if let Some(name) = self.get_name(id) {
            if let Some(subreg) = self.named_registers.get(&name) {
                Some(subreg.width)
            } else {
                None
            }
        } else {
            None
        }
    }

    // Get information by other way.
    pub fn get_name_by_alias(&self, alias: &String) -> Option<String> {
        for id in 0..self.whole_names.len() {
            if let Some(name) = self.get_name(id) {
                if self.alias_info.get(&name) == Some(alias) {
                    return Some(name);
                }
            }
        }
        None
    }

    // Emit code for setting the specified register to the specified value.
    // Will automatically insert code for shifting and masking in case of subregisters.
    // This implies that it also tries to read the old value of the whole register.
    //
    // # Arguments
    // * `phiplacer` - A PhiPlacer that has already been informed of our variables.
    //                 It will also give us access to the SSA to modify
    // * `base`      - Index of the PhiPlacer variable that corresponds to our first register.
    // * `block`     - Reference to the basic block to which operations will be appended.
    // * `var`       - Name of the register to write as a string.
    // * `value`     - An SSA node whose value shall be assigned to the register.
    //                 As with most APIs in radeco, we will not check if the value is reachable
    //                 from the position where the caller is trying to insert these operations.

    //pub fn write_register<'a, T>(&self,
                                 //phip: &mut PhiPlacer<'a, T>,
                                 //base: usize,
                                 //block: T::ActionRef,
                                 //var: &String,
                                 //mut value: T::ValueRef,
                                 //addr: u64)
        //where T: 'a + SSAMod<BBInfo = BBInfo> + VerifiedAdd
    //{
        //let info = &self.named_registers[var];
        //let id = info.base + base;

        //let width = match phip.variable_types[id] {
            //ValueType::Integer { width } => width,
        //};

        //if info.width >= width as usize {
            //phip.write_variable(block, id, value);
            //return;
        //}

        //// Need to add a cast.
        //let vt = From::from(width);
        //let opcode = MOpcode::OpWiden(width as WidthSpec);

        //if phip.ssa.get_node_data(&value).ok().map_or(0, |nd| {
            //match nd.vt {
                //ValueType::Integer{width} => width,
            //}
        //}) < width {
            //value = phip.ssa.verified_add_op(block, opcode, vt, &[value], Some(addr));
        //}

        //let mut new_value;

        //if info.shift > 0 {
            //let shift_amount_node = phip.add_const(block, info.shift as u64);
            //new_value = phip.ssa.verified_add_op(block,
                                                 //MOpcode::OpLsl,
                                                 //vt,
                                                 //&[value, shift_amount_node],
                                                 //Some(addr));
            //value = new_value;
        //}

        //let fullval: u64 = !((!1u64) << (width - 1));
        //let maskval: u64 = ((!((!1u64) << (info.width - 1))) << info.shift) ^ fullval;

        //if maskval == 0 {
            //phip.write_variable(block, id, value);
            //return;
        //}

        //let mut ov = phip.read_variable(block, id);
        //let maskvalue_node = phip.add_const(block, maskval);
        //new_value = phip.ssa.verified_add_op(block,
                                             //MOpcode::OpAnd,
                                             //vt,
                                             //&[ov, maskvalue_node],
                                             //Some(addr));

        //ov = new_value;
        //new_value = phip.ssa.verified_add_op(block, MOpcode::OpOr, vt, &[value, ov], Some(addr));
        //value = new_value;
        //phip.write_variable(block, id, value);
    //}

    // Emit code for reading the current value of the specified register.
    //
    // # Arguments
    // * `phiplacer` - A PhiPlacer that has already been informed of our variables.
    //                 It will also give us access to the SSA to modify
    // * `base`      - Index of the PhiPlacer variable that corresponds to our first register.
    // * `block`     - Reference to the basic block to which operations will be appended.
    // * `var`       - Name of the register to read as a string.
    //
    // # Return value
    // A SSA node representing the value of the register as seen by the current end of `block`.
    // Unless prior basic blocks are marked as sealed in the PhiPlacer this will always return
    // a reference to a Phi node.
    // Either way, once nodes are sealed redundant Phi nodes are eliminated by PhiPlacer.

    //pub fn read_register<'a, T>(&self,
                                //phiplacer: &mut PhiPlacer<'a, T>,
                                //base: usize,
                                //block: T::ActionRef,
                                //var: &String,
                                //addr: u64)
                                //-> T::ValueRef
        //where T: SSAMod<BBInfo = BBInfo> + VerifiedAdd + 'a
    //{
        //let info = &self.named_registers[var];
        //let id = info.base + base;
        //let mut value = phiplacer.read_variable(block, id);

        //let width = match phiplacer.variable_types[id] {
            //ValueType::Integer { width } => width,
        //};

        //if info.shift > 0 {
            //let shift_amount_node = phiplacer.add_const(block, info.shift as u64);
            //let opcode = MOpcode::OpLsr;
            //let vtype = From::from(width);
            //let new_value = phiplacer.ssa.verified_add_op(block,
                                                          //opcode,
                                                          //vtype,
                                                          //&[value, shift_amount_node],
                                                          //Some(addr));
            //value = new_value;
        //}

        //if info.width < (width as usize) {
            //let opcode = MOpcode::OpNarrow(info.width as WidthSpec);
            //let vtype = From::from(info.width);
            //let new_value = phiplacer.ssa
                                     //.verified_add_op(block, opcode, vtype, &[value], Some(addr));
            //value = new_value;
        //}
        //value
    //}
}
<|endoftext|>


<commit_before>use super::utils::types::{ Sha256Digest, Bitfield };
use super::rlp::{ RlpStream, Encodable };

pub struct PartialCrosslinkRecord {
    pub shard_id: u16,
    pub shard_block_hash: Sha256Digest,
    pub voter_bitfield: Bitfield
}

impl PartialCrosslinkRecord {
    pub fn new_for_shard(shard_id: u16,
               shard_block_hash: Sha256Digest) -> PartialCrosslinkRecord {
        PartialCrosslinkRecord {
            shard_id: shard_id,
            shard_block_hash: shard_block_hash,
            voter_bitfield: Vec::new()
        }
    }
}

/*
 * RLP Encoding
 */
impl Encodable for PartialCrosslinkRecord {
    fn rlp_append(&self, s: &mut RlpStream) {
        s.append(&self.shard_id);
        s.append(&self.shard_block_hash);
        s.append(&self.voter_bitfield);
    }
}

#[cfg(test)]
mod tests {
    use super::super::rlp;
    use super::*;

    #[test]
    fn test_new_for_shard() {
        let id = 1;
        let hash = Sha256Digest::random();
        let p = PartialCrosslinkRecord::new_for_shard(id, hash);
        assert_eq!(p.shard_id, id);
        assert_eq!(p.shard_block_hash, hash);
    }

    #[test]
    fn test_serialization() {
        let p = PartialCrosslinkRecord {
            shard_id: 1,
            shard_block_hash: Sha256Digest::zero(),
            voter_bitfield: Vec::new()
        };
        let e = rlp::encode(&p);
        println!("{:?}", e);
        assert_eq!(e.len(), 35);
        assert_eq!(e[0], 1);
        assert_eq!(e[1], 160);
        assert_eq!(e[2..34], [0; 32]);
        assert_eq!(e[34], 128);
    }
}
<commit_msg>Remove println<commit_after>use super::utils::types::{ Sha256Digest, Bitfield };
use super::rlp::{ RlpStream, Encodable };

pub struct PartialCrosslinkRecord {
    pub shard_id: u16,
    pub shard_block_hash: Sha256Digest,
    pub voter_bitfield: Bitfield
}

impl PartialCrosslinkRecord {
    pub fn new_for_shard(shard_id: u16,
               shard_block_hash: Sha256Digest) -> PartialCrosslinkRecord {
        PartialCrosslinkRecord {
            shard_id: shard_id,
            shard_block_hash: shard_block_hash,
            voter_bitfield: Vec::new()
        }
    }
}

/*
 * RLP Encoding
 */
impl Encodable for PartialCrosslinkRecord {
    fn rlp_append(&self, s: &mut RlpStream) {
        s.append(&self.shard_id);
        s.append(&self.shard_block_hash);
        s.append(&self.voter_bitfield);
    }
}

#[cfg(test)]
mod tests {
    use super::super::rlp;
    use super::*;

    #[test]
    fn test_new_for_shard() {
        let id = 1;
        let hash = Sha256Digest::random();
        let p = PartialCrosslinkRecord::new_for_shard(id, hash);
        assert_eq!(p.shard_id, id);
        assert_eq!(p.shard_block_hash, hash);
    }

    #[test]
    fn test_serialization() {
        let p = PartialCrosslinkRecord {
            shard_id: 1,
            shard_block_hash: Sha256Digest::zero(),
            voter_bitfield: Vec::new()
        };
        let e = rlp::encode(&p);
        assert_eq!(e.len(), 35);
        assert_eq!(e[0], 1);
        assert_eq!(e[1], 160);
        assert_eq!(e[2..34], [0; 32]);
        assert_eq!(e[34], 128);
    }
}
<|endoftext|>


<commit_before>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// Code that generates a test runner to run all the tests in a crate

use driver::session;
use front::config;

use std::cell::RefCell;
use std::vec;
use syntax::ast_util::*;
use syntax::attr::AttrMetaMethods;
use syntax::attr;
use syntax::codemap::{dummy_sp, Span, ExpnInfo, NameAndSpan, MacroAttribute};
use syntax::codemap;
use syntax::ext::base::ExtCtxt;
use syntax::fold::ast_fold;
use syntax::fold;
use syntax::opt_vec;
use syntax::print::pprust;
use syntax::{ast, ast_util};
use syntax::util::small_vector::SmallVector;

struct Test {
    span: Span,
    path: ~[ast::Ident],
    bench: bool,
    ignore: bool,
    should_fail: bool
}

struct TestCtxt {
    sess: session::Session,
    path: RefCell<~[ast::Ident]>,
    ext_cx: @ExtCtxt,
    testfns: RefCell<~[Test]>,
    is_extra: bool,
    config: ast::CrateConfig,
}

// Traverse the crate, collecting all the test functions, eliding any
// existing main functions, and synthesizing a main test harness
pub fn modify_for_testing(sess: session::Session,
                          crate: ast::Crate) -> ast::Crate {
    // We generate the test harness when building in the 'test'
    // configuration, either with the '--test' or '--cfg test'
    // command line options.
    let should_test = attr::contains_name(crate.config, "test");

    if should_test {
        generate_test_harness(sess, crate)
    } else {
        strip_test_functions(crate)
    }
}

struct TestHarnessGenerator {
    cx: @mut TestCtxt,
}

impl fold::ast_fold for TestHarnessGenerator {
    fn fold_crate(&self, c: ast::Crate) -> ast::Crate {
        let folded = fold::noop_fold_crate(c, self);

        // Add a special __test module to the crate that will contain code
        // generated for the test harness
        ast::Crate {
            module: add_test_module(self.cx, &folded.module),
            .. folded
        }
    }

    fn fold_item(&self, i: @ast::item) -> SmallVector<@ast::item> {
        {
            let mut path = self.cx.path.borrow_mut();
            path.get().push(i.ident);
        }
        debug!("current path: {}",
               ast_util::path_name_i(self.cx.path.get()));

        if is_test_fn(self.cx, i) || is_bench_fn(i) {
            match i.node {
                ast::item_fn(_, purity, _, _, _)
                    if purity == ast::unsafe_fn => {
                    let sess = self.cx.sess;
                    sess.span_fatal(i.span,
                                    "unsafe functions cannot be used for \
                                     tests");
                }
                _ => {
                    debug!("this is a test function");
                    let test = Test {
                        span: i.span,
                        path: self.cx.path.get(),
                        bench: is_bench_fn(i),
                        ignore: is_ignored(self.cx, i),
                        should_fail: should_fail(i)
                    };
                    {
                        let mut testfns = self.cx.testfns.borrow_mut();
                        testfns.get().push(test);
                    }
                    // debug!("have {} test/bench functions",
                    //        cx.testfns.len());
                }
            }
        }

        let res = fold::noop_fold_item(i, self);
        {
            let mut path = self.cx.path.borrow_mut();
            path.get().pop();
        }
        res
    }

    fn fold_mod(&self, m: &ast::_mod) -> ast::_mod {
        // Remove any #[main] from the AST so it doesn't clash with
        // the one we're going to add. Only if compiling an executable.

        fn nomain(cx: @mut TestCtxt, item: @ast::item) -> @ast::item {
            if !*cx.sess.building_library {
                @ast::item {
                    attrs: item.attrs.iter().filter_map(|attr| {
                        if "main" != attr.name() {
                            Some(*attr)
                        } else {
                            None
                        }
                    }).collect(),
                    .. (*item).clone()
                }
            } else {
                item
            }
        }

        let mod_nomain = ast::_mod {
            view_items: m.view_items.clone(),
            items: m.items.iter().map(|i| nomain(self.cx, *i)).collect(),
        };

        fold::noop_fold_mod(&mod_nomain, self)
    }
}

fn generate_test_harness(sess: session::Session, crate: ast::Crate)
                         -> ast::Crate {
    let cx: @mut TestCtxt = @mut TestCtxt {
        sess: sess,
        ext_cx: ExtCtxt::new(sess.parse_sess, sess.opts.cfg.clone()),
        path: RefCell::new(~[]),
        testfns: RefCell::new(~[]),
        is_extra: is_extra(&crate),
        config: crate.config.clone(),
    };

    let ext_cx = cx.ext_cx;
    ext_cx.bt_push(ExpnInfo {
        call_site: dummy_sp(),
        callee: NameAndSpan {
            name: @"test",
            format: MacroAttribute,
            span: None
        }
    });

    let fold = TestHarnessGenerator {
        cx: cx
    };
    let res = fold.fold_crate(crate);
    ext_cx.bt_pop();
    return res;
}

fn strip_test_functions(crate: ast::Crate) -> ast::Crate {
    // When not compiling with --test we should not compile the
    // #[test] functions
    config::strip_items(crate, |attrs| {
        !attr::contains_name(attrs, "test") &&
        !attr::contains_name(attrs, "bench")
    })
}

fn is_test_fn(cx: @mut TestCtxt, i: @ast::item) -> bool {
    let has_test_attr = attr::contains_name(i.attrs, "test");

    fn has_test_signature(i: @ast::item) -> bool {
        match &i.node {
          &ast::item_fn(ref decl, _, _, ref generics, _) => {
            let no_output = match decl.output.node {
                ast::ty_nil => true,
                _ => false
            };
            decl.inputs.is_empty()
                && no_output
                && !generics.is_parameterized()
          }
          _ => false
        }
    }

    if has_test_attr && !has_test_signature(i) {
        let sess = cx.sess;
        sess.span_err(
            i.span,
            "functions used as tests must have signature fn() -> ()."
        );
    }

    return has_test_attr && has_test_signature(i);
}

fn is_bench_fn(i: @ast::item) -> bool {
    let has_bench_attr = attr::contains_name(i.attrs, "bench");

    fn has_test_signature(i: @ast::item) -> bool {
        match i.node {
            ast::item_fn(ref decl, _, _, ref generics, _) => {
                let input_cnt = decl.inputs.len();
                let no_output = match decl.output.node {
                    ast::ty_nil => true,
                    _ => false
                };
                let tparm_cnt = generics.ty_params.len();
                // NB: inadequate check, but we're running
                // well before resolve, can't get too deep.
                input_cnt == 1u
                    && no_output && tparm_cnt == 0u
            }
          _ => false
        }
    }

    return has_bench_attr && has_test_signature(i);
}

fn is_ignored(cx: @mut TestCtxt, i: @ast::item) -> bool {
    i.attrs.iter().any(|attr| {
        // check ignore(cfg(foo, bar))
        "ignore" == attr.name() && match attr.meta_item_list() {
            Some(ref cfgs) => attr::test_cfg(cx.config, cfgs.iter().map(|x| *x)),
            None => true
        }
    })
}

fn should_fail(i: @ast::item) -> bool {
    attr::contains_name(i.attrs, "should_fail")
}

fn add_test_module(cx: &TestCtxt, m: &ast::_mod) -> ast::_mod {
    let testmod = mk_test_module(cx);
    ast::_mod {
        items: vec::append_one(m.items.clone(), testmod),
        ..(*m).clone()
    }
}

/*

We're going to be building a module that looks more or less like:

mod __test {
  #[!resolve_unexported]
  extern mod extra (name = "extra", vers = "...");
  fn main() {
    #[main];
    extra::test::test_main_static(::os::args(), tests)
  }

  static tests : &'static [extra::test::TestDescAndFn] = &[
    ... the list of tests in the crate ...
  ];
}

*/

fn mk_std(cx: &TestCtxt) -> ast::view_item {
    let id_extra = cx.sess.ident_of("extra");
    let vi = if cx.is_extra {
        ast::view_item_use(
            ~[@nospan(ast::view_path_simple(id_extra,
                                            path_node(~[id_extra]),
                                            ast::DUMMY_NODE_ID))])
    } else {
        let mi = attr::mk_name_value_item_str(@"vers", @"0.9-pre");
        ast::view_item_extern_mod(id_extra, None, ~[mi], ast::DUMMY_NODE_ID)
    };
    ast::view_item {
        node: vi,
        attrs: ~[],
        vis: ast::public,
        span: dummy_sp()
    }
}

fn mk_test_module(cx: &TestCtxt) -> @ast::item {

    // Link to extra
    let view_items = ~[mk_std(cx)];

    // A constant vector of test descriptors.
    let tests = mk_tests(cx);

    // The synthesized main function which will call the console test runner
    // with our list of tests
    let mainfn = (quote_item!(cx.ext_cx,
        pub fn main() {
            #[main];
            extra::test::test_main_static(::std::os::args(), TESTS);
        }
    )).unwrap();

    let testmod = ast::_mod {
        view_items: view_items,
        items: ~[mainfn, tests],
    };
    let item_ = ast::item_mod(testmod);

    // This attribute tells resolve to let us call unexported functions
    let resolve_unexported_attr =
        attr::mk_attr(attr::mk_word_item(@"!resolve_unexported"));

    let item = ast::item {
        ident: cx.sess.ident_of("__test"),
        attrs: ~[resolve_unexported_attr],
        id: ast::DUMMY_NODE_ID,
        node: item_,
        vis: ast::public,
        span: dummy_sp(),
     };

    debug!("Synthetic test module:\n{}\n",
           pprust::item_to_str(&item, cx.sess.intr()));

    return @item;
}

fn nospan<T>(t: T) -> codemap::Spanned<T> {
    codemap::Spanned { node: t, span: dummy_sp() }
}

fn path_node(ids: ~[ast::Ident]) -> ast::Path {
    ast::Path {
        span: dummy_sp(),
        global: false,
        segments: ids.move_iter().map(|identifier| ast::PathSegment {
            identifier: identifier,
            lifetimes: opt_vec::Empty,
            types: opt_vec::Empty,
        }).collect()
    }
}

fn path_node_global(ids: ~[ast::Ident]) -> ast::Path {
    ast::Path {
        span: dummy_sp(),
        global: true,
        segments: ids.move_iter().map(|identifier| ast::PathSegment {
            identifier: identifier,
            lifetimes: opt_vec::Empty,
            types: opt_vec::Empty,
        }).collect()
    }
}

fn mk_tests(cx: &TestCtxt) -> @ast::item {
    // The vector of test_descs for this crate
    let test_descs = mk_test_descs(cx);

    (quote_item!(cx.ext_cx,
        pub static TESTS : &'static [self::extra::test::TestDescAndFn] =
            $test_descs
        ;
    )).unwrap()
}

fn is_extra(crate: &ast::Crate) -> bool {
    match attr::find_pkgid(crate.attrs) {
        Some(ref s) if "extra" == s.name => true,
        _ => false
    }
}

fn mk_test_descs(cx: &TestCtxt) -> @ast::Expr {
    let mut descs = ~[];
    {
        let testfns = cx.testfns.borrow();
        debug!("building test vector from {} tests", testfns.get().len());
        for test in testfns.get().iter() {
            descs.push(mk_test_desc_and_fn_rec(cx, test));
        }
    }

    let inner_expr = @ast::Expr {
        id: ast::DUMMY_NODE_ID,
        node: ast::ExprVec(descs, ast::MutImmutable),
        span: dummy_sp(),
    };

    @ast::Expr {
        id: ast::DUMMY_NODE_ID,
        node: ast::ExprVstore(inner_expr, ast::ExprVstoreSlice),
        span: dummy_sp(),
    }
}

fn mk_test_desc_and_fn_rec(cx: &TestCtxt, test: &Test) -> @ast::Expr {
    let span = test.span;
    let path = test.path.clone();

    debug!("encoding {}", ast_util::path_name_i(path));

    let name_lit: ast::lit =
        nospan(ast::lit_str(ast_util::path_name_i(path).to_managed(), ast::CookedStr));

    let name_expr = @ast::Expr {
          id: ast::DUMMY_NODE_ID,
          node: ast::ExprLit(@name_lit),
          span: span
    };

    let fn_path = path_node_global(path);

    let fn_expr = @ast::Expr {
        id: ast::DUMMY_NODE_ID,
        node: ast::ExprPath(fn_path),
        span: span,
    };

    let t_expr = if test.bench {
        quote_expr!(cx.ext_cx, self::extra::test::StaticBenchFn($fn_expr) )
    } else {
        quote_expr!(cx.ext_cx, self::extra::test::StaticTestFn($fn_expr) )
    };

    let ignore_expr = if test.ignore {
        quote_expr!(cx.ext_cx, true )
    } else {
        quote_expr!(cx.ext_cx, false )
    };

    let fail_expr = if test.should_fail {
        quote_expr!(cx.ext_cx, true )
    } else {
        quote_expr!(cx.ext_cx, false )
    };

    let e = quote_expr!(cx.ext_cx,
        self::extra::test::TestDescAndFn {
            desc: self::extra::test::TestDesc {
                name: self::extra::test::StaticTestName($name_expr),
                ignore: $ignore_expr,
                should_fail: $fail_expr
            },
            testfn: $t_expr,
        }
    );
    e
}
<commit_msg>librustc: De-`@mut` the test context<commit_after>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// Code that generates a test runner to run all the tests in a crate

use driver::session;
use front::config;

use std::cell::RefCell;
use std::vec;
use syntax::ast_util::*;
use syntax::attr::AttrMetaMethods;
use syntax::attr;
use syntax::codemap::{dummy_sp, Span, ExpnInfo, NameAndSpan, MacroAttribute};
use syntax::codemap;
use syntax::ext::base::ExtCtxt;
use syntax::fold::ast_fold;
use syntax::fold;
use syntax::opt_vec;
use syntax::print::pprust;
use syntax::{ast, ast_util};
use syntax::util::small_vector::SmallVector;

struct Test {
    span: Span,
    path: ~[ast::Ident],
    bench: bool,
    ignore: bool,
    should_fail: bool
}

struct TestCtxt {
    sess: session::Session,
    path: RefCell<~[ast::Ident]>,
    ext_cx: @ExtCtxt,
    testfns: RefCell<~[Test]>,
    is_extra: bool,
    config: ast::CrateConfig,
}

// Traverse the crate, collecting all the test functions, eliding any
// existing main functions, and synthesizing a main test harness
pub fn modify_for_testing(sess: session::Session,
                          crate: ast::Crate) -> ast::Crate {
    // We generate the test harness when building in the 'test'
    // configuration, either with the '--test' or '--cfg test'
    // command line options.
    let should_test = attr::contains_name(crate.config, "test");

    if should_test {
        generate_test_harness(sess, crate)
    } else {
        strip_test_functions(crate)
    }
}

struct TestHarnessGenerator {
    cx: @TestCtxt,
}

impl fold::ast_fold for TestHarnessGenerator {
    fn fold_crate(&self, c: ast::Crate) -> ast::Crate {
        let folded = fold::noop_fold_crate(c, self);

        // Add a special __test module to the crate that will contain code
        // generated for the test harness
        ast::Crate {
            module: add_test_module(self.cx, &folded.module),
            .. folded
        }
    }

    fn fold_item(&self, i: @ast::item) -> SmallVector<@ast::item> {
        {
            let mut path = self.cx.path.borrow_mut();
            path.get().push(i.ident);
        }
        debug!("current path: {}",
               ast_util::path_name_i(self.cx.path.get()));

        if is_test_fn(self.cx, i) || is_bench_fn(i) {
            match i.node {
                ast::item_fn(_, purity, _, _, _)
                    if purity == ast::unsafe_fn => {
                    let sess = self.cx.sess;
                    sess.span_fatal(i.span,
                                    "unsafe functions cannot be used for \
                                     tests");
                }
                _ => {
                    debug!("this is a test function");
                    let test = Test {
                        span: i.span,
                        path: self.cx.path.get(),
                        bench: is_bench_fn(i),
                        ignore: is_ignored(self.cx, i),
                        should_fail: should_fail(i)
                    };
                    {
                        let mut testfns = self.cx.testfns.borrow_mut();
                        testfns.get().push(test);
                    }
                    // debug!("have {} test/bench functions",
                    //        cx.testfns.len());
                }
            }
        }

        let res = fold::noop_fold_item(i, self);
        {
            let mut path = self.cx.path.borrow_mut();
            path.get().pop();
        }
        res
    }

    fn fold_mod(&self, m: &ast::_mod) -> ast::_mod {
        // Remove any #[main] from the AST so it doesn't clash with
        // the one we're going to add. Only if compiling an executable.

        fn nomain(cx: @TestCtxt, item: @ast::item) -> @ast::item {
            if !*cx.sess.building_library {
                @ast::item {
                    attrs: item.attrs.iter().filter_map(|attr| {
                        if "main" != attr.name() {
                            Some(*attr)
                        } else {
                            None
                        }
                    }).collect(),
                    .. (*item).clone()
                }
            } else {
                item
            }
        }

        let mod_nomain = ast::_mod {
            view_items: m.view_items.clone(),
            items: m.items.iter().map(|i| nomain(self.cx, *i)).collect(),
        };

        fold::noop_fold_mod(&mod_nomain, self)
    }
}

fn generate_test_harness(sess: session::Session, crate: ast::Crate)
                         -> ast::Crate {
    let cx: @TestCtxt = @TestCtxt {
        sess: sess,
        ext_cx: ExtCtxt::new(sess.parse_sess, sess.opts.cfg.clone()),
        path: RefCell::new(~[]),
        testfns: RefCell::new(~[]),
        is_extra: is_extra(&crate),
        config: crate.config.clone(),
    };

    let ext_cx = cx.ext_cx;
    ext_cx.bt_push(ExpnInfo {
        call_site: dummy_sp(),
        callee: NameAndSpan {
            name: @"test",
            format: MacroAttribute,
            span: None
        }
    });

    let fold = TestHarnessGenerator {
        cx: cx
    };
    let res = fold.fold_crate(crate);
    ext_cx.bt_pop();
    return res;
}

fn strip_test_functions(crate: ast::Crate) -> ast::Crate {
    // When not compiling with --test we should not compile the
    // #[test] functions
    config::strip_items(crate, |attrs| {
        !attr::contains_name(attrs, "test") &&
        !attr::contains_name(attrs, "bench")
    })
}

fn is_test_fn(cx: @TestCtxt, i: @ast::item) -> bool {
    let has_test_attr = attr::contains_name(i.attrs, "test");

    fn has_test_signature(i: @ast::item) -> bool {
        match &i.node {
          &ast::item_fn(ref decl, _, _, ref generics, _) => {
            let no_output = match decl.output.node {
                ast::ty_nil => true,
                _ => false
            };
            decl.inputs.is_empty()
                && no_output
                && !generics.is_parameterized()
          }
          _ => false
        }
    }

    if has_test_attr && !has_test_signature(i) {
        let sess = cx.sess;
        sess.span_err(
            i.span,
            "functions used as tests must have signature fn() -> ()."
        );
    }

    return has_test_attr && has_test_signature(i);
}

fn is_bench_fn(i: @ast::item) -> bool {
    let has_bench_attr = attr::contains_name(i.attrs, "bench");

    fn has_test_signature(i: @ast::item) -> bool {
        match i.node {
            ast::item_fn(ref decl, _, _, ref generics, _) => {
                let input_cnt = decl.inputs.len();
                let no_output = match decl.output.node {
                    ast::ty_nil => true,
                    _ => false
                };
                let tparm_cnt = generics.ty_params.len();
                // NB: inadequate check, but we're running
                // well before resolve, can't get too deep.
                input_cnt == 1u
                    && no_output && tparm_cnt == 0u
            }
          _ => false
        }
    }

    return has_bench_attr && has_test_signature(i);
}

fn is_ignored(cx: @TestCtxt, i: @ast::item) -> bool {
    i.attrs.iter().any(|attr| {
        // check ignore(cfg(foo, bar))
        "ignore" == attr.name() && match attr.meta_item_list() {
            Some(ref cfgs) => attr::test_cfg(cx.config, cfgs.iter().map(|x| *x)),
            None => true
        }
    })
}

fn should_fail(i: @ast::item) -> bool {
    attr::contains_name(i.attrs, "should_fail")
}

fn add_test_module(cx: &TestCtxt, m: &ast::_mod) -> ast::_mod {
    let testmod = mk_test_module(cx);
    ast::_mod {
        items: vec::append_one(m.items.clone(), testmod),
        ..(*m).clone()
    }
}

/*

We're going to be building a module that looks more or less like:

mod __test {
  #[!resolve_unexported]
  extern mod extra (name = "extra", vers = "...");
  fn main() {
    #[main];
    extra::test::test_main_static(::os::args(), tests)
  }

  static tests : &'static [extra::test::TestDescAndFn] = &[
    ... the list of tests in the crate ...
  ];
}

*/

fn mk_std(cx: &TestCtxt) -> ast::view_item {
    let id_extra = cx.sess.ident_of("extra");
    let vi = if cx.is_extra {
        ast::view_item_use(
            ~[@nospan(ast::view_path_simple(id_extra,
                                            path_node(~[id_extra]),
                                            ast::DUMMY_NODE_ID))])
    } else {
        let mi = attr::mk_name_value_item_str(@"vers", @"0.9-pre");
        ast::view_item_extern_mod(id_extra, None, ~[mi], ast::DUMMY_NODE_ID)
    };
    ast::view_item {
        node: vi,
        attrs: ~[],
        vis: ast::public,
        span: dummy_sp()
    }
}

fn mk_test_module(cx: &TestCtxt) -> @ast::item {

    // Link to extra
    let view_items = ~[mk_std(cx)];

    // A constant vector of test descriptors.
    let tests = mk_tests(cx);

    // The synthesized main function which will call the console test runner
    // with our list of tests
    let mainfn = (quote_item!(cx.ext_cx,
        pub fn main() {
            #[main];
            extra::test::test_main_static(::std::os::args(), TESTS);
        }
    )).unwrap();

    let testmod = ast::_mod {
        view_items: view_items,
        items: ~[mainfn, tests],
    };
    let item_ = ast::item_mod(testmod);

    // This attribute tells resolve to let us call unexported functions
    let resolve_unexported_attr =
        attr::mk_attr(attr::mk_word_item(@"!resolve_unexported"));

    let item = ast::item {
        ident: cx.sess.ident_of("__test"),
        attrs: ~[resolve_unexported_attr],
        id: ast::DUMMY_NODE_ID,
        node: item_,
        vis: ast::public,
        span: dummy_sp(),
     };

    debug!("Synthetic test module:\n{}\n",
           pprust::item_to_str(&item, cx.sess.intr()));

    return @item;
}

fn nospan<T>(t: T) -> codemap::Spanned<T> {
    codemap::Spanned { node: t, span: dummy_sp() }
}

fn path_node(ids: ~[ast::Ident]) -> ast::Path {
    ast::Path {
        span: dummy_sp(),
        global: false,
        segments: ids.move_iter().map(|identifier| ast::PathSegment {
            identifier: identifier,
            lifetimes: opt_vec::Empty,
            types: opt_vec::Empty,
        }).collect()
    }
}

fn path_node_global(ids: ~[ast::Ident]) -> ast::Path {
    ast::Path {
        span: dummy_sp(),
        global: true,
        segments: ids.move_iter().map(|identifier| ast::PathSegment {
            identifier: identifier,
            lifetimes: opt_vec::Empty,
            types: opt_vec::Empty,
        }).collect()
    }
}

fn mk_tests(cx: &TestCtxt) -> @ast::item {
    // The vector of test_descs for this crate
    let test_descs = mk_test_descs(cx);

    (quote_item!(cx.ext_cx,
        pub static TESTS : &'static [self::extra::test::TestDescAndFn] =
            $test_descs
        ;
    )).unwrap()
}

fn is_extra(crate: &ast::Crate) -> bool {
    match attr::find_pkgid(crate.attrs) {
        Some(ref s) if "extra" == s.name => true,
        _ => false
    }
}

fn mk_test_descs(cx: &TestCtxt) -> @ast::Expr {
    let mut descs = ~[];
    {
        let testfns = cx.testfns.borrow();
        debug!("building test vector from {} tests", testfns.get().len());
        for test in testfns.get().iter() {
            descs.push(mk_test_desc_and_fn_rec(cx, test));
        }
    }

    let inner_expr = @ast::Expr {
        id: ast::DUMMY_NODE_ID,
        node: ast::ExprVec(descs, ast::MutImmutable),
        span: dummy_sp(),
    };

    @ast::Expr {
        id: ast::DUMMY_NODE_ID,
        node: ast::ExprVstore(inner_expr, ast::ExprVstoreSlice),
        span: dummy_sp(),
    }
}

fn mk_test_desc_and_fn_rec(cx: &TestCtxt, test: &Test) -> @ast::Expr {
    let span = test.span;
    let path = test.path.clone();

    debug!("encoding {}", ast_util::path_name_i(path));

    let name_lit: ast::lit =
        nospan(ast::lit_str(ast_util::path_name_i(path).to_managed(), ast::CookedStr));

    let name_expr = @ast::Expr {
          id: ast::DUMMY_NODE_ID,
          node: ast::ExprLit(@name_lit),
          span: span
    };

    let fn_path = path_node_global(path);

    let fn_expr = @ast::Expr {
        id: ast::DUMMY_NODE_ID,
        node: ast::ExprPath(fn_path),
        span: span,
    };

    let t_expr = if test.bench {
        quote_expr!(cx.ext_cx, self::extra::test::StaticBenchFn($fn_expr) )
    } else {
        quote_expr!(cx.ext_cx, self::extra::test::StaticTestFn($fn_expr) )
    };

    let ignore_expr = if test.ignore {
        quote_expr!(cx.ext_cx, true )
    } else {
        quote_expr!(cx.ext_cx, false )
    };

    let fail_expr = if test.should_fail {
        quote_expr!(cx.ext_cx, true )
    } else {
        quote_expr!(cx.ext_cx, false )
    };

    let e = quote_expr!(cx.ext_cx,
        self::extra::test::TestDescAndFn {
            desc: self::extra::test::TestDesc {
                name: self::extra::test::StaticTestName($name_expr),
                ignore: $ignore_expr,
                should_fail: $fail_expr
            },
            testfn: $t_expr,
        }
    );
    e
}
<|endoftext|>


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

use std::collections::HashSet;
use std::env;
use std::io;
use std::path::{Path, PathBuf};
use syntax::ast;

pub struct RPathConfig<'a> {
    pub used_crates: Vec<(ast::CrateNum, Option<PathBuf>)>,
    pub out_filename: PathBuf,
    pub is_like_osx: bool,
    pub has_rpath: bool,
    pub get_install_prefix_lib_path: &'a mut FnMut() -> PathBuf,
    pub realpath: &'a mut FnMut(&Path) -> io::Result<PathBuf>,
}

pub fn get_rpath_flags(config: &mut RPathConfig) -> Vec<String> {
    // No rpath on windows
    if !config.has_rpath {
        return Vec::new();
    }

    let mut flags = Vec::new();

    debug!("preparing the RPATH!");

    let libs = config.used_crates.clone();
    let libs = libs.into_iter().filter_map(|(_, l)| l).collect::<Vec<_>>();
    let rpaths = get_rpaths(config, &libs[..]);
    flags.push_all(&rpaths_to_flags(&rpaths[..]));
    flags
}

fn rpaths_to_flags(rpaths: &[String]) -> Vec<String> {
    let mut ret = Vec::new();
    for rpath in rpaths {
        ret.push(format!("-Wl,-rpath,{}", &(*rpath)));
    }
    return ret;
}

fn get_rpaths(config: &mut RPathConfig, libs: &[PathBuf]) -> Vec<String> {
    debug!("output: {:?}", config.out_filename.display());
    debug!("libs:");
    for libpath in libs {
        debug!("    {:?}", libpath.display());
    }

    // Use relative paths to the libraries. Binaries can be moved
    // as long as they maintain the relative relationship to the
    // crates they depend on.
    let rel_rpaths = get_rpaths_relative_to_output(config, libs);

    // And a final backup rpath to the global library location.
    let fallback_rpaths = vec!(get_install_prefix_rpath(config));

    fn log_rpaths(desc: &str, rpaths: &[String]) {
        debug!("{} rpaths:", desc);
        for rpath in rpaths {
            debug!("    {}", *rpath);
        }
    }

    log_rpaths("relative", &rel_rpaths[..]);
    log_rpaths("fallback", &fallback_rpaths[..]);

    let mut rpaths = rel_rpaths;
    rpaths.push_all(&fallback_rpaths[..]);

    // Remove duplicates
    let rpaths = minimize_rpaths(&rpaths[..]);
    return rpaths;
}

fn get_rpaths_relative_to_output(config: &mut RPathConfig,
                                 libs: &[PathBuf]) -> Vec<String> {
    libs.iter().map(|a| get_rpath_relative_to_output(config, a)).collect()
}

fn get_rpath_relative_to_output(config: &mut RPathConfig, lib: &Path) -> String {
    // Mac doesn't appear to support $ORIGIN
    let prefix = if config.is_like_osx {
        "@loader_path"
    } else {
        "$ORIGIN"
    };

    let cwd = env::current_dir().unwrap();
    let mut lib = (config.realpath)(&cwd.join(lib)).unwrap();
    lib.pop();
    let mut output = (config.realpath)(&cwd.join(&config.out_filename)).unwrap();
    output.pop();
    let relative = relativize(&lib, &output);
    // FIXME (#9639): This needs to handle non-utf8 paths
    format!("{}/{}", prefix,
            relative.to_str().expect("non-utf8 component in path"))
}

fn relativize(path: &Path, rel: &Path) -> PathBuf {
    let mut res = PathBuf::new("");
    let mut cur = rel;
    while !path.starts_with(cur) {
        res.push("..");
        match cur.parent() {
            Some(p) => cur = p,
            None => panic!("can't create relative paths across filesystems"),
        }
    }
    match path.relative_from(cur) {
        Some(s) => { res.push(s); res }
        None => panic!("couldn't create relative path from {:?} to {:?}",
                       rel, path),
    }

}

fn get_install_prefix_rpath(config: &mut RPathConfig) -> String {
    let path = (config.get_install_prefix_lib_path)();
    let path = env::current_dir().unwrap().join(&path);
    // FIXME (#9639): This needs to handle non-utf8 paths
    path.to_str().expect("non-utf8 component in rpath").to_string()
}

fn minimize_rpaths(rpaths: &[String]) -> Vec<String> {
    let mut set = HashSet::new();
    let mut minimized = Vec::new();
    for rpath in rpaths {
        if set.insert(&rpath[..]) {
            minimized.push(rpath.clone());
        }
    }
    minimized
}

#[cfg(all(unix, test))]
mod test {
    use super::{RPathConfig};
    use super::{minimize_rpaths, rpaths_to_flags, get_rpath_relative_to_output};
    use std::path::{Path, PathBuf};

    #[test]
    fn test_rpaths_to_flags() {
        let flags = rpaths_to_flags(&[
            "path1".to_string(),
            "path2".to_string()
        ]);
        assert_eq!(flags,
                   ["-Wl,-rpath,path1",
                    "-Wl,-rpath,path2"]);
    }

    #[test]
    fn test_minimize1() {
        let res = minimize_rpaths(&[
            "rpath1".to_string(),
            "rpath2".to_string(),
            "rpath1".to_string()
        ]);
        assert!(res == [
            "rpath1",
            "rpath2",
        ]);
    }

    #[test]
    fn test_minimize2() {
        let res = minimize_rpaths(&[
            "1a".to_string(),
            "2".to_string(),
            "2".to_string(),
            "1a".to_string(),
            "4a".to_string(),
            "1a".to_string(),
            "2".to_string(),
            "3".to_string(),
            "4a".to_string(),
            "3".to_string()
        ]);
        assert!(res == [
            "1a",
            "2",
            "4a",
            "3",
        ]);
    }

    #[test]
    fn test_rpath_relative() {
        if cfg!(target_os = "macos") {
            let config = &mut RPathConfig {
                used_crates: Vec::new(),
                has_rpath: true,
                is_like_osx: true,
                out_filename: PathBuf::new("bin/rustc"),
                get_install_prefix_lib_path: &mut || panic!(),
                realpath: &mut |p| Ok(p.to_path_buf()),
            };
            let res = get_rpath_relative_to_output(config,
                                                   Path::new("lib/libstd.so"));
            assert_eq!(res, "@loader_path/../lib");
        } else {
            let config = &mut RPathConfig {
                used_crates: Vec::new(),
                out_filename: PathBuf::new("bin/rustc"),
                get_install_prefix_lib_path: &mut || panic!(),
                has_rpath: true,
                is_like_osx: false,
                realpath: &mut |p| Ok(p.to_path_buf()),
            };
            let res = get_rpath_relative_to_output(config,
                                                   Path::new("lib/libstd.so"));
            assert_eq!(res, "$ORIGIN/../lib");
        }
    }
}
<commit_msg>Fix regression in -C rpath that causes failures with symlinks<commit_after>// Copyright 2012-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.

use std::collections::HashSet;
use std::env;
use std::io;
use std::path::{Path, PathBuf};
use syntax::ast;

pub struct RPathConfig<'a> {
    pub used_crates: Vec<(ast::CrateNum, Option<PathBuf>)>,
    pub out_filename: PathBuf,
    pub is_like_osx: bool,
    pub has_rpath: bool,
    pub get_install_prefix_lib_path: &'a mut FnMut() -> PathBuf,
    pub realpath: &'a mut FnMut(&Path) -> io::Result<PathBuf>,
}

pub fn get_rpath_flags(config: &mut RPathConfig) -> Vec<String> {
    // No rpath on windows
    if !config.has_rpath {
        return Vec::new();
    }

    let mut flags = Vec::new();

    debug!("preparing the RPATH!");

    let libs = config.used_crates.clone();
    let libs = libs.into_iter().filter_map(|(_, l)| l).collect::<Vec<_>>();
    let rpaths = get_rpaths(config, &libs[..]);
    flags.push_all(&rpaths_to_flags(&rpaths[..]));
    flags
}

fn rpaths_to_flags(rpaths: &[String]) -> Vec<String> {
    let mut ret = Vec::new();
    for rpath in rpaths {
        ret.push(format!("-Wl,-rpath,{}", &(*rpath)));
    }
    return ret;
}

fn get_rpaths(config: &mut RPathConfig, libs: &[PathBuf]) -> Vec<String> {
    debug!("output: {:?}", config.out_filename.display());
    debug!("libs:");
    for libpath in libs {
        debug!("    {:?}", libpath.display());
    }

    // Use relative paths to the libraries. Binaries can be moved
    // as long as they maintain the relative relationship to the
    // crates they depend on.
    let rel_rpaths = get_rpaths_relative_to_output(config, libs);

    // And a final backup rpath to the global library location.
    let fallback_rpaths = vec!(get_install_prefix_rpath(config));

    fn log_rpaths(desc: &str, rpaths: &[String]) {
        debug!("{} rpaths:", desc);
        for rpath in rpaths {
            debug!("    {}", *rpath);
        }
    }

    log_rpaths("relative", &rel_rpaths[..]);
    log_rpaths("fallback", &fallback_rpaths[..]);

    let mut rpaths = rel_rpaths;
    rpaths.push_all(&fallback_rpaths[..]);

    // Remove duplicates
    let rpaths = minimize_rpaths(&rpaths[..]);
    return rpaths;
}

fn get_rpaths_relative_to_output(config: &mut RPathConfig,
                                 libs: &[PathBuf]) -> Vec<String> {
    libs.iter().map(|a| get_rpath_relative_to_output(config, a)).collect()
}

fn get_rpath_relative_to_output(config: &mut RPathConfig, lib: &Path) -> String {
    // Mac doesn't appear to support $ORIGIN
    let prefix = if config.is_like_osx {
        "@loader_path"
    } else {
        "$ORIGIN"
    };

    let cwd = env::current_dir().unwrap();
    let mut lib = (config.realpath)(&cwd.join(lib)).unwrap();
    lib.pop();
    let mut output = (config.realpath)(&cwd.join(&config.out_filename)).unwrap();
    output.pop();
    let relative = path_relative_from(&lib, &output)
        .expect(&format!("couldn't create relative path from {:?} to {:?}", output, lib));
    // FIXME (#9639): This needs to handle non-utf8 paths
    format!("{}/{}", prefix,
            relative.to_str().expect("non-utf8 component in path"))
}

// This routine is adapted from the *old* Path's `path_relative_from`
// function, which works differently from the new `relative_from` function.
// In particular, this handles the case on unix where both paths are
// absolute but with only the root as the common directory.
fn path_relative_from(path: &Path, base: &Path) -> Option<PathBuf> {
    use std::path::Component;

    if path.is_absolute() != base.is_absolute() {
        if path.is_absolute() {
            Some(PathBuf::new(path))
        } else {
            None
        }
    } else {
        let mut ita = path.components();
        let mut itb = base.components();
        let mut comps: Vec<Component> = vec![];
        loop {
            match (ita.next(), itb.next()) {
                (None, None) => break,
                (Some(a), None) => {
                    comps.push(a);
                    comps.extend(ita.by_ref());
                    break;
                }
                (None, _) => comps.push(Component::ParentDir),
                (Some(a), Some(b)) if comps.is_empty() && a == b => (),
                (Some(a), Some(b)) if b == Component::CurDir => comps.push(a),
                (Some(_), Some(b)) if b == Component::ParentDir => return None,
                (Some(a), Some(_)) => {
                    comps.push(Component::ParentDir);
                    for _ in itb {
                        comps.push(Component::ParentDir);
                    }
                    comps.push(a);
                    comps.extend(ita.by_ref());
                    break;
                }
            }
        }
        Some(comps.iter().map(|c| c.as_os_str()).collect())
    }
}

fn get_install_prefix_rpath(config: &mut RPathConfig) -> String {
    let path = (config.get_install_prefix_lib_path)();
    let path = env::current_dir().unwrap().join(&path);
    // FIXME (#9639): This needs to handle non-utf8 paths
    path.to_str().expect("non-utf8 component in rpath").to_string()
}

fn minimize_rpaths(rpaths: &[String]) -> Vec<String> {
    let mut set = HashSet::new();
    let mut minimized = Vec::new();
    for rpath in rpaths {
        if set.insert(&rpath[..]) {
            minimized.push(rpath.clone());
        }
    }
    minimized
}

#[cfg(all(unix, test))]
mod test {
    use super::{RPathConfig};
    use super::{minimize_rpaths, rpaths_to_flags, get_rpath_relative_to_output};
    use std::path::{Path, PathBuf};

    #[test]
    fn test_rpaths_to_flags() {
        let flags = rpaths_to_flags(&[
            "path1".to_string(),
            "path2".to_string()
        ]);
        assert_eq!(flags,
                   ["-Wl,-rpath,path1",
                    "-Wl,-rpath,path2"]);
    }

    #[test]
    fn test_minimize1() {
        let res = minimize_rpaths(&[
            "rpath1".to_string(),
            "rpath2".to_string(),
            "rpath1".to_string()
        ]);
        assert!(res == [
            "rpath1",
            "rpath2",
        ]);
    }

    #[test]
    fn test_minimize2() {
        let res = minimize_rpaths(&[
            "1a".to_string(),
            "2".to_string(),
            "2".to_string(),
            "1a".to_string(),
            "4a".to_string(),
            "1a".to_string(),
            "2".to_string(),
            "3".to_string(),
            "4a".to_string(),
            "3".to_string()
        ]);
        assert!(res == [
            "1a",
            "2",
            "4a",
            "3",
        ]);
    }

    #[test]
    fn test_rpath_relative() {
        if cfg!(target_os = "macos") {
            let config = &mut RPathConfig {
                used_crates: Vec::new(),
                has_rpath: true,
                is_like_osx: true,
                out_filename: PathBuf::new("bin/rustc"),
                get_install_prefix_lib_path: &mut || panic!(),
                realpath: &mut |p| Ok(p.to_path_buf()),
            };
            let res = get_rpath_relative_to_output(config,
                                                   Path::new("lib/libstd.so"));
            assert_eq!(res, "@loader_path/../lib");
        } else {
            let config = &mut RPathConfig {
                used_crates: Vec::new(),
                out_filename: PathBuf::new("bin/rustc"),
                get_install_prefix_lib_path: &mut || panic!(),
                has_rpath: true,
                is_like_osx: false,
                realpath: &mut |p| Ok(p.to_path_buf()),
            };
            let res = get_rpath_relative_to_output(config,
                                                   Path::new("lib/libstd.so"));
            assert_eq!(res, "$ORIGIN/../lib");
        }
    }
}
<|endoftext|>