<commit_before>#[derive(PartialEq, Debug)]
pub enum Error {
    StackUnderflow,
}

pub struct Stack<T> {
    pub values: Vec<T>,
    pub register: Option<T>,
}

impl<T> Default for Stack<T>
where
    T: Clone,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<T> Stack<T>
where
    T: Clone,
{
    pub fn new() -> Self {
        Stack {
            values: Vec::new(),
            register: None,
        }
    }

    pub fn len(&self) -> usize {
        self.values.len()
    }

    pub fn is_empty(&self) -> bool {
        self.values.is_empty()
    }

    pub fn push(&mut self, val: T) {
        self.values.push(val);
    }

    pub fn pop(&mut self) -> Option<T> {
        self.values.pop()
    }

    pub fn switch_register(&mut self) -> Result<(), Error> {
        match self.register.take() {
            Some(val) => self.push(val),
            None => self.register = Some(self.pop().ok_or(Error::StackUnderflow)?),
        }

        Ok(())
    }

    pub fn dup(&mut self) -> Result<(), Error> {
        let v = self.values.last().ok_or(Error::StackUnderflow)?.clone();
        self.values.push(v);
        Ok(())
    }

    pub fn drop(&mut self) -> Result<(), Error> {
        match self.values.len() {
            0 => Err(Error::StackUnderflow),
            n => {
                self.values.truncate(n - 1);
                Ok(())
            }
        }
    }

    pub fn swap(&mut self) -> Result<(), Error> {
        match self.values.len() {
            0 | 1 => Err(Error::StackUnderflow),
            n => {
                self.values.swap(n - 2, n - 1);
                Ok(())
            }
        }
    }

    pub fn swap2(&mut self) -> Result<(), Error> {
        match self.values.len() {
            0...2 => Err(Error::StackUnderflow),
            n => {
                self.values.swap(n - 2, n - 1);
                self.values.swap(n - 3, n - 2);
                Ok(())
            }
        }
    }

    pub fn rshift(&mut self) {
        let e = self.values.pop();
        if let Some(e) = e {
            self.values.insert(0, e);
        }
    }

    pub fn lshift(&mut self) {
        match self.values.len() {
            0 | 1 => {}
            _ => {
                let v = self.values.remove(0);
                self.values.push(v);
            }
        }
    }
}

pub struct StackOfStacks<T> {
    pub initial_stack: Stack<T>,
    pub additional_stacks: Vec<Stack<T>>,
}

impl<T> Default for StackOfStacks<T>
where
    T: Clone,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<T> StackOfStacks<T>
where
    T: Clone,
{
    pub fn new() -> Self {
        StackOfStacks {
            initial_stack: Stack::new(),
            additional_stacks: vec![],
        }
    }

    pub fn push_stack(&mut self, moved_items: usize) -> Result<(), Error> {
        let vals = {
            let stack = self.top_mut();
            let n = stack
                .len()
                .checked_sub(moved_items)
                .ok_or(Error::StackUnderflow)?;
            stack.values.split_off(n)
        };

        self.additional_stacks.push(Stack {
            values: vals,
            register: None,
        });

        Ok(())
    }

    pub fn pop_stack(&mut self) {
        if let Some(stack) = self.additional_stacks.pop() {
            self.top_mut().values.extend(stack.values);
        } else {
            self.initial_stack.values.clear();
            self.initial_stack.register = None;
        }
    }

    pub fn top(&self) -> &Stack<T> {
        self.additional_stacks
            .last()
            .unwrap_or(&self.initial_stack)
    }

    pub fn top_mut(&mut self) -> &mut Stack<T> {
        self.additional_stacks
            .last_mut()
            .unwrap_or(&mut self.initial_stack)
    }
}

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

        #[test]
        fn new_works() {
            let stack = Stack::<isize>::new();

            assert!(stack.is_empty());
            assert_eq!(stack.register, None);
        }

        #[test]
        fn push_works() {
            let mut stack = Stack::new();
            stack.push(5);
            stack.push(42);
            stack.push(58);

            assert_eq!(stack.len(), 3);
            assert_eq!(stack.values, vec![5, 42, 58]);
        }

        #[test]
        fn pop_works() {
            let mut stack = Stack::<isize>::new();
            stack.push(5);

            assert_eq!(stack.pop(), Some(5));
        }

        #[test]
        fn pop_empty_stack_returns_none() {
            let mut stack = Stack::<isize>::new();
            assert_eq!(stack.pop(), None);
        }

        #[test]
        fn dup_works() {
            let mut stack = Stack::new();
            stack.push(5);
            stack.push(42);

            let res = stack.dup();

            assert!(res.is_ok());
            assert_eq!(stack.values, vec![5, 42, 42]);
        }

        #[test]
        fn dup_with_empty_stack_fails() {
            let mut stack = Stack::<isize>::new();

            let res = stack.dup();

            assert_eq!(res, Err(Error::StackUnderflow));
        }

        #[test]
        fn drop_works() {
            let mut stack = Stack::new();
            stack.push(5);
            stack.push(42);

            let res = stack.drop();

            assert!(res.is_ok());
            assert_eq!(stack.values, vec![5]);
        }

        #[test]
        fn drop_with_empty_stack_fails() {
            let mut stack = Stack::<isize>::new();

            let res = stack.drop();

            assert_eq!(res, Err(Error::StackUnderflow));
        }

        #[test]
        fn switch_register_works() {
            let mut stack = Stack::new();
            stack.push(5);
            stack.push(42);
            stack.push(58);

            let res = stack.switch_register();

            assert!(res.is_ok());
            assert_eq!(stack.register, Some(58));
            assert_eq!(stack.values, vec![5, 42]);

            let res2 = stack.switch_register();

            assert!(res2.is_ok());
            assert_eq!(stack.register, None);
            assert_eq!(stack.values, vec![5, 42, 58]);
        }

        #[test]
        fn switch_empty_register_on_empty_stack_fails() {
            let mut stack = Stack::<isize>::new();

            let res = stack.switch_register();

            assert_eq!(res, Err(Error::StackUnderflow));
        }

        #[test]
        fn swap_works() {
            let mut stack = Stack::new();
            stack.push(1);
            stack.push(2);
            stack.push(3);

            let res = stack.swap();

            assert!(res.is_ok());
            assert_eq!(stack.values, vec![1, 3, 2]);
        }

        #[test]
        fn swap_with_empty_stack_fails() {
            let mut stack = Stack::<isize>::new();

            let res = stack.swap();

            assert_eq!(res, Err(Error::StackUnderflow));
        }

        #[test]
        fn swap_with_one_element_fails() {
            let mut stack = Stack::new();
            stack.push(1);

            let res = stack.swap();

            assert_eq!(res, Err(Error::StackUnderflow));
        }

        #[test]
        fn swap2_works() {
            let mut stack = Stack::new();
            stack.push(1);
            stack.push(2);
            stack.push(3);
            stack.push(4);

            let res = stack.swap2();

            assert!(res.is_ok());
            assert_eq!(stack.values, vec![1, 4, 2, 3]);
        }

        #[test]
        fn swap2_with_empty_stack_fails() {
            let mut stack = Stack::<isize>::new();

            let res = stack.swap2();

            assert_eq!(res, Err(Error::StackUnderflow));
        }

        #[test]
        fn swap2_with_one_element_fails() {
            let mut stack = Stack::new();
            stack.push(1);

            let res = stack.swap2();

            assert_eq!(res, Err(Error::StackUnderflow));
        }

        #[test]
        fn swap2_with_two_elements_fails() {
            let mut stack = Stack::new();
            stack.push(1);
            stack.push(2);

            let res = stack.swap2();

            assert_eq!(res, Err(Error::StackUnderflow));
        }

        #[test]
        fn rshift_works() {
            let mut stack = Stack::new();
            stack.push(1);
            stack.push(2);
            stack.push(3);
            stack.push(4);

            stack.rshift();

            assert_eq!(stack.values, vec![4, 1, 2, 3]);
        }

        #[test]
        fn lshift_works() {
            let mut stack = Stack::new();
            stack.push(1);
            stack.push(2);
            stack.push(3);
            stack.push(4);

            stack.lshift();

            assert_eq!(stack.values, vec![2, 3, 4, 1]);
        }
    }

    mod stack_of_stacks {
        use super::super::*;

        #[test]
        fn new_works() {
            let s = StackOfStacks::<isize>::new();

            assert_eq!(s.additional_stacks.len(), 0);
            assert_eq!(s.initial_stack.len(), 0);
            assert_eq!(s.initial_stack.register, None);
        }

        #[test]
        fn push_stack_works() {
            let mut s = StackOfStacks::new();
            s.top_mut().push(5);
            s.top_mut().push(42);
            s.top_mut().push(58);

            let res = s.push_stack(2);

            assert!(res.is_ok());

            assert_eq!(s.additional_stacks.len(), 1);
            assert_eq!(s.initial_stack.values, vec![5]);
            assert_eq!(s.additional_stacks[0].values, vec![42, 58]);
            assert_eq!(s.additional_stacks[0].register, None);
        }

        #[test]
        fn push_stack_with_all_elements_works() {
            let mut s = StackOfStacks::new();
            s.top_mut().push(5);
            s.top_mut().push(42);
            s.top_mut().push(58);

            let res = s.push_stack(3);

            assert!(res.is_ok());

            assert_eq!(s.additional_stacks.len(), 1);
            assert_eq!(s.initial_stack.values, vec![0; 0]);
            assert_eq!(s.additional_stacks[0].values, vec![5, 42, 58]);
            assert_eq!(s.additional_stacks[0].register, None);
        }

        #[test]
        fn push_stack_with_zero_elements_works() {
            let mut s = StackOfStacks::new();
            s.top_mut().push(5);
            s.top_mut().push(42);
            s.top_mut().push(58);

            let res = s.push_stack(0);

            assert!(res.is_ok());

            assert_eq!(s.additional_stacks.len(), 1);
            assert_eq!(s.initial_stack.values, vec![5, 42, 58]);
            assert_eq!(s.additional_stacks[0].values, vec![0; 0]);
            assert_eq!(s.additional_stacks[0].register, None);
        }

        #[test]
        fn push_stack_with_too_many_values_fails() {
            let mut s = StackOfStacks::new();
            s.top_mut().push(5);
            s.top_mut().push(42);

            let res = s.push_stack(3);

            assert_eq!(res, Err(Error::StackUnderflow));
        }

        #[test]
        fn pop_stack_works() {
            let mut s = StackOfStacks::new();
            s.top_mut().push(5);
            s.top_mut().push(42);
            s.top_mut().push(58);

            let res = s.push_stack(2);

            assert!(res.is_ok());

            s.pop_stack();

            assert_eq!(s.additional_stacks.len(), 0);
            assert_eq!(s.initial_stack.values, vec![5, 42, 58]);
            assert_eq!(s.initial_stack.register, None);
        }

        #[test]
        fn pop_stack_with_base_register_works() {
            let mut s = StackOfStacks::new();
            s.top_mut().push(5);
            s.top_mut().push(42);
            s.top_mut().push(58);

            let _ = s.top_mut().switch_register().unwrap();
            let _ = s.push_stack(1).unwrap();

            s.pop_stack();

            assert_eq!(s.additional_stacks.len(), 0);
            assert_eq!(s.initial_stack.values, vec![5, 42]);
            assert_eq!(s.initial_stack.register, Some(58));
        }

        #[test]
        fn pop_stack_with_top_register_works() {
            let mut s = StackOfStacks::new();
            s.top_mut().push(5);
            s.top_mut().push(42);
            s.top_mut().push(58);

            let _ = s.push_stack(2).unwrap();
            let _ = s.top_mut().switch_register().unwrap();

            s.pop_stack();

            assert_eq!(s.additional_stacks.len(), 0);
            assert_eq!(s.initial_stack.values, vec![5, 42]);
            assert_eq!(s.initial_stack.register, None);
        }

        #[test]
        fn pop_initial_stack_makes_it_empty() {
            let mut s = StackOfStacks::new();
            s.top_mut().push(5);
            s.top_mut().push(42);
            s.top_mut().push(58);

            let _ = s.top_mut().switch_register().unwrap();

            s.pop_stack();

            assert_eq!(s.additional_stacks.len(), 0);
            assert_eq!(s.initial_stack.values, vec![0; 0]);
            assert_eq!(s.initial_stack.register, None);
        }
    }
}
<commit_msg>Simplify test module structure<commit_after>#[derive(PartialEq, Debug)]
pub enum Error {
    StackUnderflow,
}

pub struct Stack<T> {
    pub values: Vec<T>,
    pub register: Option<T>,
}

impl<T> Default for Stack<T>
where
    T: Clone,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<T> Stack<T>
where
    T: Clone,
{
    pub fn new() -> Self {
        Stack {
            values: Vec::new(),
            register: None,
        }
    }

    pub fn len(&self) -> usize {
        self.values.len()
    }

    pub fn is_empty(&self) -> bool {
        self.values.is_empty()
    }

    pub fn push(&mut self, val: T) {
        self.values.push(val);
    }

    pub fn pop(&mut self) -> Option<T> {
        self.values.pop()
    }

    pub fn switch_register(&mut self) -> Result<(), Error> {
        match self.register.take() {
            Some(val) => self.push(val),
            None => self.register = Some(self.pop().ok_or(Error::StackUnderflow)?),
        }

        Ok(())
    }

    pub fn dup(&mut self) -> Result<(), Error> {
        let v = self.values.last().ok_or(Error::StackUnderflow)?.clone();
        self.values.push(v);
        Ok(())
    }

    pub fn drop(&mut self) -> Result<(), Error> {
        match self.values.len() {
            0 => Err(Error::StackUnderflow),
            n => {
                self.values.truncate(n - 1);
                Ok(())
            }
        }
    }

    pub fn swap(&mut self) -> Result<(), Error> {
        match self.values.len() {
            0 | 1 => Err(Error::StackUnderflow),
            n => {
                self.values.swap(n - 2, n - 1);
                Ok(())
            }
        }
    }

    pub fn swap2(&mut self) -> Result<(), Error> {
        match self.values.len() {
            0...2 => Err(Error::StackUnderflow),
            n => {
                self.values.swap(n - 2, n - 1);
                self.values.swap(n - 3, n - 2);
                Ok(())
            }
        }
    }

    pub fn rshift(&mut self) {
        let e = self.values.pop();
        if let Some(e) = e {
            self.values.insert(0, e);
        }
    }

    pub fn lshift(&mut self) {
        match self.values.len() {
            0 | 1 => {}
            _ => {
                let v = self.values.remove(0);
                self.values.push(v);
            }
        }
    }
}

pub struct StackOfStacks<T> {
    pub initial_stack: Stack<T>,
    pub additional_stacks: Vec<Stack<T>>,
}

impl<T> Default for StackOfStacks<T>
where
    T: Clone,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<T> StackOfStacks<T>
where
    T: Clone,
{
    pub fn new() -> Self {
        StackOfStacks {
            initial_stack: Stack::new(),
            additional_stacks: vec![],
        }
    }

    pub fn push_stack(&mut self, moved_items: usize) -> Result<(), Error> {
        let vals = {
            let stack = self.top_mut();
            let n = stack
                .len()
                .checked_sub(moved_items)
                .ok_or(Error::StackUnderflow)?;
            stack.values.split_off(n)
        };

        self.additional_stacks.push(Stack {
            values: vals,
            register: None,
        });

        Ok(())
    }

    pub fn pop_stack(&mut self) {
        if let Some(stack) = self.additional_stacks.pop() {
            self.top_mut().values.extend(stack.values);
        } else {
            self.initial_stack.values.clear();
            self.initial_stack.register = None;
        }
    }

    pub fn top(&self) -> &Stack<T> {
        self.additional_stacks.last().unwrap_or(&self.initial_stack)
    }

    pub fn top_mut(&mut self) -> &mut Stack<T> {
        self.additional_stacks
            .last_mut()
            .unwrap_or(&mut self.initial_stack)
    }
}

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

    #[test]
    fn new_works() {
        let stack = Stack::<isize>::new();

        assert!(stack.is_empty());
        assert_eq!(stack.register, None);
    }

    #[test]
    fn push_works() {
        let mut stack = Stack::new();
        stack.push(5);
        stack.push(42);
        stack.push(58);

        assert_eq!(stack.len(), 3);
        assert_eq!(stack.values, vec![5, 42, 58]);
    }

    #[test]
    fn pop_works() {
        let mut stack = Stack::<isize>::new();
        stack.push(5);

        assert_eq!(stack.pop(), Some(5));
    }

    #[test]
    fn pop_empty_stack_returns_none() {
        let mut stack = Stack::<isize>::new();
        assert_eq!(stack.pop(), None);
    }

    #[test]
    fn dup_works() {
        let mut stack = Stack::new();
        stack.push(5);
        stack.push(42);

        let res = stack.dup();

        assert!(res.is_ok());
        assert_eq!(stack.values, vec![5, 42, 42]);
    }

    #[test]
    fn dup_with_empty_stack_fails() {
        let mut stack = Stack::<isize>::new();

        let res = stack.dup();

        assert_eq!(res, Err(Error::StackUnderflow));
    }

    #[test]
    fn drop_works() {
        let mut stack = Stack::new();
        stack.push(5);
        stack.push(42);

        let res = stack.drop();

        assert!(res.is_ok());
        assert_eq!(stack.values, vec![5]);
    }

    #[test]
    fn drop_with_empty_stack_fails() {
        let mut stack = Stack::<isize>::new();

        let res = stack.drop();

        assert_eq!(res, Err(Error::StackUnderflow));
    }

    #[test]
    fn switch_register_works() {
        let mut stack = Stack::new();
        stack.push(5);
        stack.push(42);
        stack.push(58);

        let res = stack.switch_register();

        assert!(res.is_ok());
        assert_eq!(stack.register, Some(58));
        assert_eq!(stack.values, vec![5, 42]);

        let res2 = stack.switch_register();

        assert!(res2.is_ok());
        assert_eq!(stack.register, None);
        assert_eq!(stack.values, vec![5, 42, 58]);
    }

    #[test]
    fn switch_empty_register_on_empty_stack_fails() {
        let mut stack = Stack::<isize>::new();

        let res = stack.switch_register();

        assert_eq!(res, Err(Error::StackUnderflow));
    }

    #[test]
    fn swap_works() {
        let mut stack = Stack::new();
        stack.push(1);
        stack.push(2);
        stack.push(3);

        let res = stack.swap();

        assert!(res.is_ok());
        assert_eq!(stack.values, vec![1, 3, 2]);
    }

    #[test]
    fn swap_with_empty_stack_fails() {
        let mut stack = Stack::<isize>::new();

        let res = stack.swap();

        assert_eq!(res, Err(Error::StackUnderflow));
    }

    #[test]
    fn swap_with_one_element_fails() {
        let mut stack = Stack::new();
        stack.push(1);

        let res = stack.swap();

        assert_eq!(res, Err(Error::StackUnderflow));
    }

    #[test]
    fn swap2_works() {
        let mut stack = Stack::new();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);

        let res = stack.swap2();

        assert!(res.is_ok());
        assert_eq!(stack.values, vec![1, 4, 2, 3]);
    }

    #[test]
    fn swap2_with_empty_stack_fails() {
        let mut stack = Stack::<isize>::new();

        let res = stack.swap2();

        assert_eq!(res, Err(Error::StackUnderflow));
    }

    #[test]
    fn swap2_with_one_element_fails() {
        let mut stack = Stack::new();
        stack.push(1);

        let res = stack.swap2();

        assert_eq!(res, Err(Error::StackUnderflow));
    }

    #[test]
    fn swap2_with_two_elements_fails() {
        let mut stack = Stack::new();
        stack.push(1);
        stack.push(2);

        let res = stack.swap2();

        assert_eq!(res, Err(Error::StackUnderflow));
    }

    #[test]
    fn rshift_works() {
        let mut stack = Stack::new();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);

        stack.rshift();

        assert_eq!(stack.values, vec![4, 1, 2, 3]);
    }

    #[test]
    fn lshift_works() {
        let mut stack = Stack::new();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);

        stack.lshift();

        assert_eq!(stack.values, vec![2, 3, 4, 1]);
    }
}

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

    #[test]
    fn new_works() {
        let s = StackOfStacks::<isize>::new();

        assert_eq!(s.additional_stacks.len(), 0);
        assert_eq!(s.initial_stack.len(), 0);
        assert_eq!(s.initial_stack.register, None);
    }

    #[test]
    fn push_stack_works() {
        let mut s = StackOfStacks::new();
        s.top_mut().push(5);
        s.top_mut().push(42);
        s.top_mut().push(58);

        let res = s.push_stack(2);

        assert!(res.is_ok());

        assert_eq!(s.additional_stacks.len(), 1);
        assert_eq!(s.initial_stack.values, vec![5]);
        assert_eq!(s.additional_stacks[0].values, vec![42, 58]);
        assert_eq!(s.additional_stacks[0].register, None);
    }

    #[test]
    fn push_stack_with_all_elements_works() {
        let mut s = StackOfStacks::new();
        s.top_mut().push(5);
        s.top_mut().push(42);
        s.top_mut().push(58);

        let res = s.push_stack(3);

        assert!(res.is_ok());

        assert_eq!(s.additional_stacks.len(), 1);
        assert_eq!(s.initial_stack.values, vec![0; 0]);
        assert_eq!(s.additional_stacks[0].values, vec![5, 42, 58]);
        assert_eq!(s.additional_stacks[0].register, None);
    }

    #[test]
    fn push_stack_with_zero_elements_works() {
        let mut s = StackOfStacks::new();
        s.top_mut().push(5);
        s.top_mut().push(42);
        s.top_mut().push(58);

        let res = s.push_stack(0);

        assert!(res.is_ok());

        assert_eq!(s.additional_stacks.len(), 1);
        assert_eq!(s.initial_stack.values, vec![5, 42, 58]);
        assert_eq!(s.additional_stacks[0].values, vec![0; 0]);
        assert_eq!(s.additional_stacks[0].register, None);
    }

    #[test]
    fn push_stack_with_too_many_values_fails() {
        let mut s = StackOfStacks::new();
        s.top_mut().push(5);
        s.top_mut().push(42);

        let res = s.push_stack(3);

        assert_eq!(res, Err(Error::StackUnderflow));
    }

    #[test]
    fn pop_stack_works() {
        let mut s = StackOfStacks::new();
        s.top_mut().push(5);
        s.top_mut().push(42);
        s.top_mut().push(58);

        let res = s.push_stack(2);

        assert!(res.is_ok());

        s.pop_stack();

        assert_eq!(s.additional_stacks.len(), 0);
        assert_eq!(s.initial_stack.values, vec![5, 42, 58]);
        assert_eq!(s.initial_stack.register, None);
    }

    #[test]
    fn pop_stack_with_base_register_works() {
        let mut s = StackOfStacks::new();
        s.top_mut().push(5);
        s.top_mut().push(42);
        s.top_mut().push(58);

        let _ = s.top_mut().switch_register().unwrap();
        let _ = s.push_stack(1).unwrap();

        s.pop_stack();

        assert_eq!(s.additional_stacks.len(), 0);
        assert_eq!(s.initial_stack.values, vec![5, 42]);
        assert_eq!(s.initial_stack.register, Some(58));
    }

    #[test]
    fn pop_stack_with_top_register_works() {
        let mut s = StackOfStacks::new();
        s.top_mut().push(5);
        s.top_mut().push(42);
        s.top_mut().push(58);

        let _ = s.push_stack(2).unwrap();
        let _ = s.top_mut().switch_register().unwrap();

        s.pop_stack();

        assert_eq!(s.additional_stacks.len(), 0);
        assert_eq!(s.initial_stack.values, vec![5, 42]);
        assert_eq!(s.initial_stack.register, None);
    }

    #[test]
    fn pop_initial_stack_makes_it_empty() {
        let mut s = StackOfStacks::new();
        s.top_mut().push(5);
        s.top_mut().push(42);
        s.top_mut().push(58);

        let _ = s.top_mut().switch_register().unwrap();

        s.pop_stack();

        assert_eq!(s.additional_stacks.len(), 0);
        assert_eq!(s.initial_stack.values, vec![0; 0]);
        assert_eq!(s.initial_stack.register, None);
    }
}
<|endoftext|>


<commit_before>
//! A different way of thinking about states.
//!
//! All objects are stored in a state.

use HashMap = collections::HashMap;

pub type UpdateFunction<T, D> = fn (obj: &mut T, delta: &D);

/// Keeps track of the current state of objects.
/// Also keeps an update function per state.
/// This is because otherwise all states require same logic.
pub struct StateMachine<Object, Delta> {
    current: State<CurrentState<Object>>,
    states: State<State<Object>>,
    update_functions: State<UpdateFunction<Object, Delta>>
}

impl<T, D> StateMachine<T, D> {
    /// Adds a new state.
    pub fn add_state(
            &mut self,
            state_id: uint,
            state: State<T>,
            update: Option<UpdateFunction<T, D>>
    ) {
        self.states.objects.insert(state_id, state);
        match update {
            None => {},
            Some(fun) => { self.update_functions.objects.insert(state_id, fun); }
        }
    }

    /// Returns the current value of object by looking up in correct state.
    #[inline(always)]
    pub fn val<'a>(&'a self, obj: uint) -> &'a T {
        let &CurrentState{ state: state } = self.current.objects.get(&obj);
        self.states.objects.get(&state).objects.get(&obj)
    }
}

/// Stores the current state of an object.
struct CurrentState<Object> {
    state: uint,
}

/// Contains objects.
pub struct State<Object> {
    objects: HashMap<uint, Object>,
}

impl<T> State<T> {
    /// Moves an object from one state to another.
    pub fn move_to(&mut self, to: &mut State<T>, obj: uint) {
        let pop = self.objects.pop(&obj);
        match pop {
            None => {},
            Some(val) => { to.objects.insert(obj, val); }
        }
    }
}

/// Updates on delta information.
///
/// For any type implementing this trait,
/// there is a `State<T>` and `StateMachine<T>`
/// which also implements this trait.
pub trait UpdateDelta<D> {
    /// Updates all the objects with delta information.
    fn update(&mut self, delta: &D);
}

impl<T: UpdateDelta<D>, D>
UpdateDelta<D> for State<T> {
    fn update(&mut self, delta: &D) {
        for (_, obj) in self.objects.mut_iter() {
            obj.update(delta);
        }
    }
}

impl<T: UpdateDelta<D>, D>
UpdateDelta<D> for StateMachine<T, D> {
    fn update(&mut self, delta: &D) {
        for (id_state, state) in self.states.objects.mut_iter() {
            match self.update_functions.objects.find(id_state) {
                    None => {},
                    Some(fun) => {
                        for (_, obj) in state.objects.mut_iter() {
                            (*fun)(obj, delta);
                        }
                    }
            }
        }
    }
}

<commit_msg>Add object to StateMachine<commit_after>
//! A different way of thinking about states.
//!
//! All objects are stored in a state.

use HashMap = collections::HashMap;

pub type UpdateFunction<T, D> = fn (obj: &mut T, delta: &D);

/// Keeps track of the current state of objects.
/// Also keeps an update function per state.
/// This is because otherwise all states require same logic.
pub struct StateMachine<Object, Delta> {
    current: State<CurrentState<Object>>,
    states: State<State<Object>>,
    update_functions: State<UpdateFunction<Object, Delta>>
}

impl<T, D> StateMachine<T, D> {
    /// Adds a new state.
    pub fn add_state(
            &mut self,
            state_id: uint,
            state: State<T>,
            update: Option<UpdateFunction<T, D>>
    ) {
        self.states.objects.insert(state_id, state);
        match update {
            None => {},
            Some(fun) => { self.update_functions.objects.insert(state_id, fun); }
        }
    }

    /// Adds a new object.
    pub fn add_object(
            &mut self,
            state_id: uint,
            obj_id: uint,
            obj: T) {
        self.current.objects.insert(obj_id, CurrentState { state: state_id });
        self.states.objects.get_mut(&state_id).objects.insert(obj_id, obj);
    }

    /// Returns the current value of object by looking up in correct state.
    #[inline(always)]
    pub fn val<'a>(&'a self, obj: uint) -> &'a T {
        let &CurrentState{ state: state } = self.current.objects.get(&obj);
        self.states.objects.get(&state).objects.get(&obj)
    }
}

/// Stores the current state of an object.
struct CurrentState<Object> {
    state: uint,
}

/// Contains objects.
pub struct State<Object> {
    objects: HashMap<uint, Object>,
}

impl<T> State<T> {
    /// Moves an object from one state to another.
    pub fn move_to(&mut self, to: &mut State<T>, obj: uint) {
        let pop = self.objects.pop(&obj);
        match pop {
            None => {},
            Some(val) => { to.objects.insert(obj, val); }
        }
    }
}

/// Updates on delta information.
///
/// For any type implementing this trait,
/// there is a `State<T>` and `StateMachine<T>`
/// which also implements this trait.
pub trait UpdateDelta<D> {
    /// Updates all the objects with delta information.
    fn update(&mut self, delta: &D);
}

impl<T: UpdateDelta<D>, D>
UpdateDelta<D> for State<T> {
    fn update(&mut self, delta: &D) {
        for (_, obj) in self.objects.mut_iter() {
            obj.update(delta);
        }
    }
}

impl<T: UpdateDelta<D>, D>
UpdateDelta<D> for StateMachine<T, D> {
    fn update(&mut self, delta: &D) {
        for (id_state, state) in self.states.objects.mut_iter() {
            match self.update_functions.objects.find(id_state) {
                    None => {},
                    Some(fun) => {
                        for (_, obj) in state.objects.mut_iter() {
                            (*fun)(obj, delta);
                        }
                    }
            }
        }
    }
}

<|endoftext|>


<commit_before>//! Data structures that can be shared between the server and the client.
//!
//! All these structures should be serializable, so that they can be
//! transferred from the server to the client over the network.
use std::convert::Into;
use std::fmt;
use std::collections::HashMap;

/// A unit identifier.
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Copy, Clone, Hash)]
pub struct UnitId(pub u32);

impl Into<UnitId> for u32 {
    fn into(self) -> UnitId {
        UnitId(self)
    }
}

impl fmt::Display for UnitId {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        self.0.fmt(f)
    }
}

/// A client/player identifier.
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Copy, Clone)]
pub struct ClientId(pub u32);

impl Into<ClientId> for u32 {
    fn into(self) -> ClientId {
        ClientId(self)
    }
}

impl fmt::Display for ClientId {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        self.0.fmt(f)
    }
}

/// The state of a single unit
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub struct Unit {
    /// The unit identifier
    pub id: UnitId,

    /// X/Y position in the world in m
    pub position: [f64; 2],

    /// Angle of the unit in radiant
    pub angle: f64,

    /// Direction and speed of the movement. The angle of the movement may be different then the
    /// angle of the unit. The unit is m per milli second.
    pub speed_vector: [f64; 2],

    /// Health of the unit
    pub health: u64,
}

impl Unit {
    pub fn new<T: Into<UnitId>>(id: T, position: [f64; 2]) -> Unit {
        println!("Create unit at {:?}", position);
        Unit {
            id: id.into(),
            position: position,
            angle: 0.0f64,
            speed_vector: [0.0f64, 0.0f64],
            health: 100_0000,
        }
    }

    pub fn update(&mut self, dt_ms: f64) {
        self.position[0] += self.speed_vector[0] * dt_ms;
        self.position[1] += self.speed_vector[1] * dt_ms;
    }
}

/// A player has an ID and consists of 0..N `Unit`s
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub struct Player {
    pub id: ClientId,
    pub units: Vec<Unit>,
}

impl Player {
    pub fn new<T: Into<ClientId>>(id: T) -> Player {
        Player {
            id: id.into(),
            units: vec![],
        }
    }
}

/// Data related to the current game.
///
/// This needs to be transferred to the client every time the game state
/// changes.
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub struct GameState {
    /// List of players
    pub players: Vec<Player>,
}

impl GameState {
    pub fn new() -> GameState {
        GameState{ players: vec![] }
    }

    pub fn update_targets(&mut self, unit_targets: &HashMap<UnitId, [f64; 2]>) {
        for player in self.players.iter_mut() {
            for unit in player.units.iter_mut() {
                if let Some(target) = unit_targets.get(&unit.id) {
                    let speed = 0.0001;
                    unit.speed_vector = [(target[0]-unit.position[0])*speed, (target[1]-unit.position[1])*speed];
                } else {
                    unit.speed_vector = [0.0,0.0];
                }
            }
        }
    }

    pub fn update(&mut self, dt: f64) {
        for player in self.players.iter_mut() {
            for unit in player.units.iter_mut() {
                unit.update(dt);
            }
        }
    }
}

/// Data related to the entire world, like width and height.
///
/// This needs to be transferred to the client only once, on connecting.
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub struct WorldState {
    /// Width of the world in m
    pub x: f64,
    /// Height of the world in m
    pub y: f64,
}

impl WorldState {
    pub fn new(x: f64, y: f64) -> WorldState {
        WorldState {
            x: x,
            y: y,
        }
    }
}
<commit_msg>state: Export UNIT_SIZE<commit_after>//! Data structures that can be shared between the server and the client.
//!
//! All these structures should be serializable, so that they can be
//! transferred from the server to the client over the network.
use std::convert::Into;
use std::fmt;
use std::collections::HashMap;

/// A unit identifier.
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Copy, Clone, Hash)]
pub struct UnitId(pub u32);

impl Into<UnitId> for u32 {
    fn into(self) -> UnitId {
        UnitId(self)
    }
}

impl fmt::Display for UnitId {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        self.0.fmt(f)
    }
}

/// A client/player identifier.
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Copy, Clone)]
pub struct ClientId(pub u32);

impl Into<ClientId> for u32 {
    fn into(self) -> ClientId {
        ClientId(self)
    }
}

impl fmt::Display for ClientId {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        self.0.fmt(f)
    }
}

pub const UNIT_SIZE: f64 = 50.0;

/// The state of a single unit
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub struct Unit {
    /// The unit identifier
    pub id: UnitId,

    /// X/Y position in the world in m
    pub position: [f64; 2],

    /// Angle of the unit in radiant
    pub angle: f64,

    /// Direction and speed of the movement. The angle of the movement may be different then the
    /// angle of the unit. The unit is m per milli second.
    pub speed_vector: [f64; 2],

    /// Health of the unit
    pub health: u64,
}

impl Unit {
    pub fn new<T: Into<UnitId>>(id: T, position: [f64; 2]) -> Unit {
        println!("Create unit at {:?}", position);
        Unit {
            id: id.into(),
            position: position,
            angle: 0.0f64,
            speed_vector: [0.0f64, 0.0f64],
            health: 100_0000,
        }
    }

    pub fn update(&mut self, dt_ms: f64) {
        self.position[0] += self.speed_vector[0] * dt_ms;
        self.position[1] += self.speed_vector[1] * dt_ms;
    }
}

/// A player has an ID and consists of 0..N `Unit`s
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub struct Player {
    pub id: ClientId,
    pub units: Vec<Unit>,
}

impl Player {
    pub fn new<T: Into<ClientId>>(id: T) -> Player {
        Player {
            id: id.into(),
            units: vec![],
        }
    }
}

/// Data related to the current game.
///
/// This needs to be transferred to the client every time the game state
/// changes.
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub struct GameState {
    /// List of players
    pub players: Vec<Player>,
}

impl GameState {
    pub fn new() -> GameState {
        GameState{ players: vec![] }
    }

    pub fn update_targets(&mut self, unit_targets: &HashMap<UnitId, [f64; 2]>) {
        for player in self.players.iter_mut() {
            for unit in player.units.iter_mut() {
                if let Some(target) = unit_targets.get(&unit.id) {
                    let speed = 0.0001;
                    unit.speed_vector = [(target[0]-unit.position[0])*speed, (target[1]-unit.position[1])*speed];
                } else {
                    unit.speed_vector = [0.0,0.0];
                }
            }
        }
    }

    pub fn update(&mut self, dt: f64) {
        for player in self.players.iter_mut() {
            for unit in player.units.iter_mut() {
                unit.update(dt);
            }
        }
    }
}

/// Data related to the entire world, like width and height.
///
/// This needs to be transferred to the client only once, on connecting.
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub struct WorldState {
    /// Width of the world in m
    pub x: f64,
    /// Height of the world in m
    pub y: f64,
}

impl WorldState {
    pub fn new(x: f64, y: f64) -> WorldState {
        WorldState {
            x: x,
            y: y,
        }
    }
}
<|endoftext|>


<commit_before>// Copyright 2014 Michael Yang. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

//! Matrix operations.

use attribute::{
    Order,
};

pub mod ll;
pub mod ops;

/// Methods that allow a type to be used in BLAS functions as a matrix.
pub trait Matrix<T> {
    /// The leading dimension of the matrix. Defaults to `cols`.
    fn lead_dim(&self) -> i32 { self.cols() }
    /// The order of the matrix. Defaults to `RowMajor`.
    fn order(&self) -> Order { Order::RowMajor }
    /// Returns the number of rows.
    fn rows(&self) -> i32;
    /// Returns the number of columns.
    fn cols(&self) -> i32;
    /// An unsafe pointer to a contiguous block of memory.
    unsafe fn as_ptr(&self) -> *const T;
    /// An unsafe pointer to a contiguous block of memory.
    unsafe fn as_mut_ptr(&mut self) -> *mut T;
}

pub trait BandMatrix<T>: Matrix<T> {
    fn sub_diagonals(&self) -> i32;
    fn sup_diagonals(&self) -> i32;
}

#[cfg(test)]
mod test_struct {
    use matrix::Matrix;

    impl<T> Matrix<T> for (i32, i32, Vec<T>) {
        fn rows(&self) -> i32 {
            self.0
        }

        fn cols(&self) -> i32 {
            self.1
        }

        #[inline]
        unsafe fn as_ptr(&self) -> *const T {
            self.2[..].as_ptr()
        }

        #[inline]
        unsafe fn as_mut_ptr(&mut self) -> *mut T {
            (&mut self.2[..]).as_mut_ptr()
        }
    }
}
<commit_msg>Determine lead_dim for Matrix by matching on Order.<commit_after>// Copyright 2014 Michael Yang. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

//! Matrix operations.

use attribute::{
    Order,
};

pub mod ll;
pub mod ops;

/// Methods that allow a type to be used in BLAS functions as a matrix.
pub trait Matrix<T> {
    /// The leading dimension of the matrix. Defaults to `cols` for `RowMajor`
    /// order and 'rows' for `ColMajor` order.
    fn lead_dim(&self) -> i32 {
        match self.order() {
            Order::RowMajor => self.cols(),
            Order::ColMajor => self.rows(),
        }
    }
    /// The order of the matrix. Defaults to `RowMajor`.
    fn order(&self) -> Order { Order::RowMajor }
    /// Returns the number of rows.
    fn rows(&self) -> i32;
    /// Returns the number of columns.
    fn cols(&self) -> i32;
    /// An unsafe pointer to a contiguous block of memory.
    unsafe fn as_ptr(&self) -> *const T;
    /// An unsafe pointer to a contiguous block of memory.
    unsafe fn as_mut_ptr(&mut self) -> *mut T;
}

pub trait BandMatrix<T>: Matrix<T> {
    fn sub_diagonals(&self) -> i32;
    fn sup_diagonals(&self) -> i32;
}

#[cfg(test)]
mod test_struct {
    use matrix::Matrix;

    impl<T> Matrix<T> for (i32, i32, Vec<T>) {
        fn rows(&self) -> i32 {
            self.0
        }

        fn cols(&self) -> i32 {
            self.1
        }

        #[inline]
        unsafe fn as_ptr(&self) -> *const T {
            self.2[..].as_ptr()
        }

        #[inline]
        unsafe fn as_mut_ptr(&mut self) -> *mut T {
            (&mut self.2[..]).as_mut_ptr()
        }
    }
}
<|endoftext|>


<commit_before>// Copyright (c) 2016 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

extern crate libc;

use std;
use std::ffi::{CString, OsString};
use hcore::os::ffi::OsStrExt;
use std::path::{Path, PathBuf};
use std::ptr;

use common;
use common::ui::{Status, UI};
use hcore;
use hcore::fs::cache_artifact_path;
use hcore::package::{PackageIdent, PackageInstall};
use hcore::url::default_depot_url;

use {PRODUCT, VERSION};
use error::{Error, Result};

#[allow(dead_code)] // Currently only used on Linux platforms
const MAX_RETRIES: u8 = 4;

/// Makes an `execv(3)` system call to become a new program.
///
/// Note that if successful, this function will not return.
///
/// # Failures
///
/// * Command and/or command arguments cannot be converted into `CString`
pub fn exec_command(command: PathBuf, args: Vec<OsString>) -> Result<()> {
    // A massive thanks to the `exec` crate which pointed to the correct invocation
    // behavior--namely to pass null-terminated string pointers.
    //
    // Source: https://github.com/faradayio/exec-rs/blob/master/src/lib.rs

    debug!("Calling execv: ({:?}) {:?}", command.display(), &args);
    let prog_cstring = try!(CString::new(command.as_os_str().as_bytes()));
    let arg_cstrings = try!(args.into_iter()
        .map(|arg| CString::new(arg.as_os_str().as_bytes()))
        .collect::<std::result::Result<Vec<_>, _>>());
    let mut arg_charptrs: Vec<_> = arg_cstrings.iter()
        .map(|arg| arg.as_bytes_with_nul().as_ptr() as *const i8)
        .collect();
    arg_charptrs.insert(0,
                        prog_cstring.clone().as_bytes_with_nul().as_ptr() as *const i8);
    arg_charptrs.push(ptr::null());

    unsafe {
        libc::execv(prog_cstring.as_bytes_with_nul().as_ptr() as *const i8,
                    arg_charptrs.as_mut_ptr());
    }
    Ok(())
}

/// Returns the absolute path to the given command from the given package identifier.
///
/// If the package is not locally installed, the package will be installed before recomputing.
/// There are a maximum number of times a re-installation will be attempted before returning an
/// error.
///
/// # Failures
///
/// * If the package is installed but the command cannot be found in the package
/// * If an error occurs when loading the local package from disk
/// * If the maximum number of installation retries has been exceeded
#[allow(dead_code)] // Currently only used on Linux platforms
pub fn command_from_pkg(ui: &mut UI,
                        command: &str,
                        ident: &PackageIdent,
                        cache_key_path: &Path,
                        retry: u8)
                        -> Result<PathBuf> {
    if retry > MAX_RETRIES {
        return Err(Error::ExecCommandNotFound(command.to_string()));
    }

    let fs_root_path = Path::new("/");
    match PackageInstall::load(ident, None) {
        Ok(pi) => {
            match try!(find_command_in_pkg(&command, &pi, fs_root_path)) {
                Some(cmd) => Ok(cmd),
                None => return Err(Error::ExecCommandNotFound(command.to_string())),
            }
        }
        Err(hcore::Error::PackageNotFound(_)) => {
            try!(ui.status(Status::Missing, format!("package for {}", &ident)));
            try!(common::command::package::install::start(ui,
                                                          &default_depot_url(),
                                                          &ident.to_string(),
                                                          PRODUCT,
                                                          VERSION,
                                                          fs_root_path,
                                                          &cache_artifact_path(None),
                                                          cache_key_path));
            command_from_pkg(ui, &command, &ident, &cache_key_path, retry + 1)
        }
        Err(e) => return Err(Error::from(e)),
    }
}

/// Returns the absolute path to the given command from a given package installation.
///
/// If the command is not found, then `None` is returned.
///
/// # Failures
///
/// * The path entries metadata cannot be loaded
pub fn find_command_in_pkg(command: &str,
                           pkg_install: &PackageInstall,
                           fs_root_path: &Path)
                           -> Result<Option<PathBuf>> {
    for path in try!(pkg_install.paths()) {
        let candidate = fs_root_path.join(try!(path.strip_prefix("/"))).join(command);
        if candidate.is_file() {
            return Ok(Some(path.join(command)));
        }
    }
    Ok(None)
}
<commit_msg>replacing execv in exec.rs with std::process::Command<commit_after>// Copyright (c) 2016 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

extern crate libc;

use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::process::{Command, exit};

use common;
use common::ui::{Status, UI};
use hcore;
use hcore::fs::cache_artifact_path;
use hcore::package::{PackageIdent, PackageInstall};
use hcore::url::default_depot_url;

use {PRODUCT, VERSION};
use error::{Error, Result};

#[allow(dead_code)] // Currently only used on Linux platforms
const MAX_RETRIES: u8 = 4;

/// Makes an `std::process::Command` call.
///
/// # Failures
///
/// * Command and/or command arguments cannot be converted into `CString`
pub fn exec_command(command: PathBuf, args: Vec<OsString>) -> Result<()> {
    debug!("Calling std::process::Command: ({:?}) {:?}", command.display(), &args);
    let mut command = Command::new(command);

    for arg in &args {
        command.arg(arg);
    }
    let status = command.status().expect(&(format!("{:?} failed to start.", &command)));
    // Let's bubble back up the error codes from the command we shell'd out to
    exit(status.code().unwrap())
}

/// Returns the absolute path to the given command from the given package identifier.
///
/// If the package is not locally installed, the package will be installed before recomputing.
/// There are a maximum number of times a re-installation will be attempted before returning an
/// error.
///
/// # Failures
///
/// * If the package is installed but the command cannot be found in the package
/// * If an error occurs when loading the local package from disk
/// * If the maximum number of installation retries has been exceeded
#[allow(dead_code)] // Currently only used on Linux platforms
pub fn command_from_pkg(ui: &mut UI,
                        command: &str,
                        ident: &PackageIdent,
                        cache_key_path: &Path,
                        retry: u8)
                        -> Result<PathBuf> {
    if retry > MAX_RETRIES {
        return Err(Error::ExecCommandNotFound(command.to_string()));
    }

    let fs_root_path = Path::new("/");
    match PackageInstall::load(ident, None) {
        Ok(pi) => {
            match try!(find_command_in_pkg(&command, &pi, fs_root_path)) {
                Some(cmd) => Ok(cmd),
                None => return Err(Error::ExecCommandNotFound(command.to_string())),
            }
        }
        Err(hcore::Error::PackageNotFound(_)) => {
            try!(ui.status(Status::Missing, format!("package for {}", &ident)));
            try!(common::command::package::install::start(ui,
                                                          &default_depot_url(),
                                                          &ident.to_string(),
                                                          PRODUCT,
                                                          VERSION,
                                                          fs_root_path,
                                                          &cache_artifact_path(None),
                                                          cache_key_path));
            command_from_pkg(ui, &command, &ident, &cache_key_path, retry + 1)
        }
        Err(e) => return Err(Error::from(e)),
    }
}

/// Returns the absolute path to the given command from a given package installation.
///
/// If the command is not found, then `None` is returned.
///
/// # Failures
///
/// * The path entries metadata cannot be loaded
pub fn find_command_in_pkg(command: &str,
                           pkg_install: &PackageInstall,
                           fs_root_path: &Path)
                           -> Result<Option<PathBuf>> {
    for path in try!(pkg_install.paths()) {
        let candidate = fs_root_path.join(try!(path.strip_prefix("/"))).join(command);
        if candidate.is_file() {
            return Ok(Some(path.join(command)));
        }
    }
    Ok(None)
}
<|endoftext|>


<commit_before>// Copyright 2015-2016 Benjamin Fry <benjaminfry@me.com>
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://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;
use std::{thread, time};
use std::fs::File;
use std::net::SocketAddr;
use std::net::{IpAddr, Ipv4Addr};
#[cfg(not(target_os = "linux"))]
use std::net::Ipv6Addr;
use std::io::{Read, Write};
use std::sync::Arc;
use std::sync::atomic;

use futures::Stream;
use native_tls;
use native_tls::{Certificate, TlsAcceptor};
use tokio_core::reactor::Core;

use {TlsStream, TlsStreamBuilder};

// this fails on linux for some reason. It appears that a buffer somewhere is dirty
//  and subsequent reads of a mesage buffer reads the wrong length. It works for 2 iterations
//  but not 3?
// #[cfg(not(target_os = "linux"))]
#[test]
fn test_tls_client_stream_ipv4() {
    tls_client_stream_test(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), false)
}

// FIXME: mtls is disabled at the moment, it causes a hang on Linux, and is currently not supported on macOS
#[cfg(feature = "mtls")]
#[test]
#[cfg(not(target_os = "macos"))] // ignored until Travis-CI fixes IPv6
fn test_tls_client_stream_ipv4_mtls() {
    tls_client_stream_test(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), true)
}

#[test]
#[cfg(not(target_os = "linux"))] // ignored until Travis-CI fixes IPv6
fn test_tls_client_stream_ipv6() {
    tls_client_stream_test(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), false)
}

const TEST_BYTES: &'static [u8; 8] = b"DEADBEEF";
const TEST_BYTES_LEN: usize = 8;

fn read_file(path: &str) -> Vec<u8> {
    let mut bytes = vec![];

    let mut file = File::open(path).expect(&format!("failed to open file: {}", path));
    file.read_to_end(&mut bytes)
        .expect(&format!("failed to read file: {}", path));
    bytes
}

#[allow(unused_mut)]
fn tls_client_stream_test(server_addr: IpAddr, mtls: bool) {
    let succeeded = Arc::new(atomic::AtomicBool::new(false));
    let succeeded_clone = succeeded.clone();
    thread::Builder::new()
        .name("thread_killer".to_string())
        .spawn(move || {
            let succeeded = succeeded_clone.clone();
            for _ in 0..15 {
                thread::sleep(time::Duration::from_secs(1));
                if succeeded.load(atomic::Ordering::Relaxed) {
                    return;
                }
            }

            panic!("timeout");
        })
        .unwrap();

    let root_cert_der = read_file("../tests/ca.der");

    // Generate X509 certificate
    let subject_name = "ns.example.com";
    let server_pkcs12_der = read_file("../tests/cert.p12");

    // TODO: need a timeout on listen
    let server = std::net::TcpListener::bind(SocketAddr::new(server_addr, 0)).unwrap();
    let server_addr = server.local_addr().unwrap();

    let send_recv_times = 4;

    let server_handle = thread::Builder::new().name("test_tls_client_stream:server".to_string()).spawn(move || {
    let pkcs12 = native_tls::Pkcs12::from_der(&server_pkcs12_der, "mypass").expect("Pkcs12::from_der");
    let mut tls = TlsAcceptor::builder(pkcs12).expect("build with pkcs12 failed");

    // #[cfg(target_os = "linux")]
    // {
    //   let mut openssl_builder = tls.builder_mut();
    //   let mut openssl_ctx_builder = openssl_builder.builder_mut();

    //   let mut mode = openssl::ssl::SslVerifyMode::empty();

    //   // FIXME: mtls tests hang on Linux...
    //   if mtls {
    //     //   mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;

    //     // let mut store = X509StoreBuilder::new().unwrap();
    //     // let root_ca = X509::from_der(&root_cert_der_copy).unwrap();
    //     // store.add_cert(root_ca).unwrap();
    //     // openssl_ctx_builder.set_verify_cert_store(store.build()).unwrap();
    //   } else {
    //     mode.insert(SSL_VERIFY_NONE);
    //   }

    //   openssl_ctx_builder.set_verify(mode);
    // }

    // FIXME: add CA on macOS

    let tls = tls.build().expect("tls build failed");

    // server_barrier.wait();
    let (socket, _) = server.accept().expect("tcp accept failed");
    socket.set_read_timeout(Some(std::time::Duration::from_secs(5))).unwrap(); // should recieve something within 5 seconds...
    socket.set_write_timeout(Some(std::time::Duration::from_secs(5))).unwrap(); // should recieve something within 5 seconds...

    let mut socket = tls.accept(socket).expect("tls accept failed");

    for _ in 0..send_recv_times {
      // wait for some bytes...
      let mut len_bytes = [0_u8; 2];
      socket.read_exact(&mut len_bytes).expect("SERVER: receive failed");
      let length = (len_bytes[0] as u16) << 8 & 0xFF00 | len_bytes[1] as u16 & 0x00FF;
      assert_eq!(length as usize, TEST_BYTES_LEN);

      let mut buffer = [0_u8; TEST_BYTES_LEN];
      socket.read_exact(&mut buffer).unwrap();

      // println!("read bytes iter: {}", i);
      assert_eq!(&buffer, TEST_BYTES);

      // bounce them right back...
      socket.write_all(&len_bytes).expect("SERVER: send length failed");
      socket.write_all(&buffer).expect("SERVER: send buffer failed");
      // println!("wrote bytes iter: {}", i);
      std::thread::yield_now();
    }
  }).unwrap();

    // let the server go first
    std::thread::yield_now();

    // setup the client, which is going to run on the testing thread...
    let mut io_loop = Core::new().unwrap();

    // the tests should run within 5 seconds... right?
    // TODO: add timeout here, so that test never hangs...
    // let timeout = Timeout::new(Duration::from_secs(5), &io_loop.handle());

    let trust_chain = Certificate::from_der(&root_cert_der).unwrap();

    // barrier.wait();
    let mut builder = ::tls_stream::tls_builder();
    builder.add_ca(trust_chain);

    // fix MTLS
    // if mtls {
    //     config_mtls(&root_pkey, &root_name, &root_cert, &mut builder);
    // }

    let (stream, sender) = builder.build(server_addr, subject_name.to_string(), io_loop.handle());

    // TODO: there is a race failure here... a race with the server thread most likely...
    let mut stream = io_loop
        .run(stream)
        .ok()
        .expect("run failed to get stream");

    for _ in 0..send_recv_times {
        // test once
        sender
            .send((TEST_BYTES.to_vec(), server_addr))
            .expect("send failed");
        let (buffer, stream_tmp) = io_loop
            .run(stream.into_future())
            .ok()
            .expect("future iteration run failed");
        stream = stream_tmp;
        let (buffer, _) = buffer.expect("no buffer received");
        assert_eq!(&buffer, TEST_BYTES);
    }

    succeeded.store(true, std::sync::atomic::Ordering::Relaxed);
    server_handle.join().expect("server thread failed");
}

// TODO: fix MTLS
// #[allow(unused_variables)]
// fn config_mtls(root_pkey: &PKey,
//                root_name: &X509Name,
//                root_cert: &X509,
//                builder: &mut TlsStreamBuilder) {
//     // signed by the same root cert
//     let client_name = "resolv.example.com";
//     let (_ /*client_pkey*/, _ /*client_cert*/, client_identity) =
//         cert(client_name, root_pkey, root_name, root_cert);
//     let client_identity =
//         native_tls::Pkcs12::from_der(&client_identity.to_der().unwrap(), "mypass").unwrap();

//     #[cfg(feature = "mtls")]
//     builder.identity(client_identity);
// }
<commit_msg>fix renaming issue<commit_after>// Copyright 2015-2016 Benjamin Fry <benjaminfry@me.com>
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://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;
use std::{thread, time};
use std::fs::File;
use std::net::SocketAddr;
use std::net::{IpAddr, Ipv4Addr};
#[cfg(not(target_os = "linux"))]
use std::net::Ipv6Addr;
use std::io::{Read, Write};
use std::sync::Arc;
use std::sync::atomic;

use futures::Stream;
use native_tls;
use native_tls::{Certificate, TlsAcceptor};
use tokio_core::reactor::Core;

use {TlsStream, TlsStreamBuilder};

// this fails on linux for some reason. It appears that a buffer somewhere is dirty
//  and subsequent reads of a mesage buffer reads the wrong length. It works for 2 iterations
//  but not 3?
// #[cfg(not(target_os = "linux"))]
#[test]
fn test_tls_client_stream_ipv4() {
    tls_client_stream_test(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), false)
}

// FIXME: mtls is disabled at the moment, it causes a hang on Linux, and is currently not supported on macOS
#[cfg(feature = "mtls")]
#[test]
#[cfg(not(target_os = "macos"))] // ignored until Travis-CI fixes IPv6
fn test_tls_client_stream_ipv4_mtls() {
    tls_client_stream_test(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), true)
}

#[test]
#[cfg(not(target_os = "linux"))] // ignored until Travis-CI fixes IPv6
fn test_tls_client_stream_ipv6() {
    tls_client_stream_test(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), false)
}

const TEST_BYTES: &'static [u8; 8] = b"DEADBEEF";
const TEST_BYTES_LEN: usize = 8;

fn read_file(path: &str) -> Vec<u8> {
    let mut bytes = vec![];

    let mut file = File::open(path).expect(&format!("failed to open file: {}", path));
    file.read_to_end(&mut bytes)
        .expect(&format!("failed to read file: {}", path));
    bytes
}

#[allow(unused_mut)]
fn tls_client_stream_test(server_addr: IpAddr, mtls: bool) {
    let succeeded = Arc::new(atomic::AtomicBool::new(false));
    let succeeded_clone = succeeded.clone();
    thread::Builder::new()
        .name("thread_killer".to_string())
        .spawn(move || {
            let succeeded = succeeded_clone.clone();
            for _ in 0..15 {
                thread::sleep(time::Duration::from_secs(1));
                if succeeded.load(atomic::Ordering::Relaxed) {
                    return;
                }
            }

            panic!("timeout");
        })
        .unwrap();

    let root_cert_der = read_file("../tests/ca.der");

    // Generate X509 certificate
    let subject_name = "ns.example.com";
    let server_pkcs12_der = read_file("../tests/cert.p12");

    // TODO: need a timeout on listen
    let server = std::net::TcpListener::bind(SocketAddr::new(server_addr, 0)).unwrap();
    let server_addr = server.local_addr().unwrap();

    let send_recv_times = 4;

    let server_handle = thread::Builder::new().name("test_tls_client_stream:server".to_string()).spawn(move || {
    let pkcs12 = native_tls::Pkcs12::from_der(&server_pkcs12_der, "mypass").expect("Pkcs12::from_der");
    let mut tls = TlsAcceptor::builder(pkcs12).expect("build with pkcs12 failed");

    // #[cfg(target_os = "linux")]
    // {
    //   let mut openssl_builder = tls.builder_mut();
    //   let mut openssl_ctx_builder = openssl_builder.builder_mut();

    //   let mut mode = openssl::ssl::SslVerifyMode::empty();

    //   // FIXME: mtls tests hang on Linux...
    //   if mtls {
    //     //   mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;

    //     // let mut store = X509StoreBuilder::new().unwrap();
    //     // let root_ca = X509::from_der(&root_cert_der_copy).unwrap();
    //     // store.add_cert(root_ca).unwrap();
    //     // openssl_ctx_builder.set_verify_cert_store(store.build()).unwrap();
    //   } else {
    //     mode.insert(SSL_VERIFY_NONE);
    //   }

    //   openssl_ctx_builder.set_verify(mode);
    // }

    // FIXME: add CA on macOS

    let tls = tls.build().expect("tls build failed");

    // server_barrier.wait();
    let (socket, _) = server.accept().expect("tcp accept failed");
    socket.set_read_timeout(Some(std::time::Duration::from_secs(5))).unwrap(); // should recieve something within 5 seconds...
    socket.set_write_timeout(Some(std::time::Duration::from_secs(5))).unwrap(); // should recieve something within 5 seconds...

    let mut socket = tls.accept(socket).expect("tls accept failed");

    for _ in 0..send_recv_times {
      // wait for some bytes...
      let mut len_bytes = [0_u8; 2];
      socket.read_exact(&mut len_bytes).expect("SERVER: receive failed");
      let length = (len_bytes[0] as u16) << 8 & 0xFF00 | len_bytes[1] as u16 & 0x00FF;
      assert_eq!(length as usize, TEST_BYTES_LEN);

      let mut buffer = [0_u8; TEST_BYTES_LEN];
      socket.read_exact(&mut buffer).unwrap();

      // println!("read bytes iter: {}", i);
      assert_eq!(&buffer, TEST_BYTES);

      // bounce them right back...
      socket.write_all(&len_bytes).expect("SERVER: send length failed");
      socket.write_all(&buffer).expect("SERVER: send buffer failed");
      // println!("wrote bytes iter: {}", i);
      std::thread::yield_now();
    }
  }).unwrap();

    // let the server go first
    std::thread::yield_now();

    // setup the client, which is going to run on the testing thread...
    let mut io_loop = Core::new().unwrap();

    // the tests should run within 5 seconds... right?
    // TODO: add timeout here, so that test never hangs...
    // let timeout = Timeout::new(Duration::from_secs(5), &io_loop.handle());

    let trust_chain = Certificate::from_der(&root_cert_der).unwrap();

    // barrier.wait();
    let mut builder = TlsStreamBuilder::new();
    builder.add_ca(trust_chain);

    // fix MTLS
    // if mtls {
    //     config_mtls(&root_pkey, &root_name, &root_cert, &mut builder);
    // }

    let (stream, sender) = builder.build(server_addr, subject_name.to_string(), io_loop.handle());

    // TODO: there is a race failure here... a race with the server thread most likely...
    let mut stream = io_loop
        .run(stream)
        .ok()
        .expect("run failed to get stream");

    for _ in 0..send_recv_times {
        // test once
        sender
            .send((TEST_BYTES.to_vec(), server_addr))
            .expect("send failed");
        let (buffer, stream_tmp) = io_loop
            .run(stream.into_future())
            .ok()
            .expect("future iteration run failed");
        stream = stream_tmp;
        let (buffer, _) = buffer.expect("no buffer received");
        assert_eq!(&buffer, TEST_BYTES);
    }

    succeeded.store(true, std::sync::atomic::Ordering::Relaxed);
    server_handle.join().expect("server thread failed");
}

// TODO: fix MTLS
// #[allow(unused_variables)]
// fn config_mtls(root_pkey: &PKey,
//                root_name: &X509Name,
//                root_cert: &X509,
//                builder: &mut TlsStreamBuilder) {
//     // signed by the same root cert
//     let client_name = "resolv.example.com";
//     let (_ /*client_pkey*/, _ /*client_cert*/, client_identity) =
//         cert(client_name, root_pkey, root_name, root_cert);
//     let client_identity =
//         native_tls::Pkcs12::from_der(&client_identity.to_der().unwrap(), "mypass").unwrap();

//     #[cfg(feature = "mtls")]
//     builder.identity(client_identity);
// }
<|endoftext|>


<commit_before>// Copyright 2018 Syn Developers
//
// 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.

//! Parsing interface for parsing a token stream into a syntax tree node.
//!
//! Parsing in Syn is built on parser functions that take in a [`Cursor`] and
//! produce a [`PResult<T>`] where `T` is some syntax tree node. `Cursor` is a
//! cheaply copyable cursor over a range of tokens in a token stream, and
//! `PResult` is a result that packages together a parsed syntax tree node `T`
//! with a stream of remaining unparsed tokens after `T` represented as another
//! `Cursor`, or a [`ParseError`] if parsing failed.
//!
//! [`Cursor`]: ../buffer/index.html
//! [`PResult<T>`]: type.PResult.html
//! [`ParseError`]: struct.ParseError.html
//!
//! This `Cursor`- and `PResult`-based interface is convenient for parser
//! combinators and parser implementations, but not necessarily when you just
//! have some tokens that you want to parse. For that we expose the following
//! two entry points.
//!
//! ## The `syn::parse*` functions
//!
//! The [`syn::parse`], [`syn::parse2`], and [`syn::parse_str`] functions serve
//! as an entry point for parsing syntax tree nodes that can be parsed in an
//! obvious default way. These functions can return any syntax tree node that
//! implements the [`Synom`] trait, which includes most types in Syn.
//!
//! [`syn::parse`]: ../fn.parse.html
//! [`syn::parse2`]: ../fn.parse2.html
//! [`syn::parse_str`]: ../fn.parse_str.html
//! [`Synom`]: trait.Synom.html
//!
//! ```
//! use syn::Type;
//!
//! # fn run_parser() -> Result<(), syn::synom::ParseError> {
//! let t: Type = syn::parse_str("std::collections::HashMap<String, Value>")?;
//! #     Ok(())
//! # }
//! #
//! # fn main() {
//! #     run_parser().unwrap();
//! # }
//! ```
//!
//! The [`parse_quote!`] macro also uses this approach.
//!
//! [`parse_quote!`]: ../macro.parse_quote.html
//!
//! ## The `Parser` trait
//!
//! Some types can be parsed in several ways depending on context. For example
//! an [`Attribute`] can be either "outer" like `#[...]` or "inner" like
//! `#![...]` and parsing the wrong one would be a bug. Similarly [`Punctuated`]
//! may or may not allow trailing punctuation, and parsing it the wrong way
//! would either reject valid input or accept invalid input.
//!
//! [`Attribute`]: ../struct.Attribute.html
//! [`Punctuated`]: ../punctuated/index.html
//!
//! The `Synom` trait is not implemented in these cases because there is no good
//! behavior to consider the default.
//!
//! ```ignore
//! // Can't parse `Punctuated` without knowing whether trailing punctuation
//! // should be allowed in this context.
//! let path: Punctuated<PathSegment, Token![::]> = syn::parse(tokens)?;
//! ```
//!
//! In these cases the types provide a choice of parser functions rather than a
//! single `Synom` implementation, and those parser functions can be invoked
//! through the [`Parser`] trait.
//!
//! [`Parser`]: trait.Parser.html
//!
//! ```
//! # #[macro_use]
//! # extern crate syn;
//! #
//! # extern crate proc_macro2;
//! # use proc_macro2::TokenStream;
//! #
//! use syn::synom::Parser;
//! use syn::punctuated::Punctuated;
//! use syn::{PathSegment, Expr, Attribute};
//!
//! # fn run_parsers() -> Result<(), syn::synom::ParseError> {
//! #     let tokens = TokenStream::new().into();
//! // Parse a nonempty sequence of path segments separated by `::` punctuation
//! // with no trailing punctuation.
//! let parser = Punctuated::<PathSegment, Token![::]>::parse_separated_nonempty;
//! let path = parser.parse(tokens)?;
//!
//! #     let tokens = TokenStream::new().into();
//! // Parse a possibly empty sequence of expressions terminated by commas with
//! // an optional trailing punctuation.
//! let parser = Punctuated::<Expr, Token![,]>::parse_terminated;
//! let args = parser.parse(tokens)?;
//!
//! #     let tokens = TokenStream::new().into();
//! // Parse zero or more outer attributes but not inner attributes.
//! named!(outer_attrs -> Vec<Attribute>, many0!(Attribute::parse_outer));
//! let attrs = outer_attrs.parse(tokens)?;
//! #
//! #     Ok(())
//! # }
//! #
//! # fn main() {}
//! ```
//!
//! # Implementing a parser function
//!
//! Parser functions are usually implemented using the [`nom`]-style parser
//! combinator macros provided by Syn, but may also be implemented without
//! macros be using the low-level [`Cursor`] API directly.
//!
//! [`nom`]: https://github.com/Geal/nom
//!
//! The following parser combinator macros are available and a `Synom` parsing
//! example is provided for each one.
//!
//! - [`alt!`](../macro.alt.html)
//! - [`braces!`](../macro.braces.html)
//! - [`brackets!`](../macro.brackets.html)
//! - [`call!`](../macro.call.html)
//! - [`cond!`](../macro.cond.html)
//! - [`cond_reduce!`](../macro.cond_reduce.html)
//! - [`custom_keyword!`](../macro.custom_keyword.html)
//! - [`do_parse!`](../macro.do_parse.html)
//! - [`epsilon!`](../macro.epsilon.html)
//! - [`input_end!`](../macro.input_end.html)
//! - [`keyword!`](../macro.keyword.html)
//! - [`many0!`](../macro.many0.html)
//! - [`map!`](../macro.map.html)
//! - [`not!`](../macro.not.html)
//! - [`option!`](../macro.option.html)
//! - [`parens!`](../macro.parens.html)
//! - [`punct!`](../macro.punct.html)
//! - [`reject!`](../macro.reject.html)
//! - [`switch!`](../macro.switch.html)
//! - [`syn!`](../macro.syn.html)
//! - [`tuple!`](../macro.tuple.html)
//! - [`value!`](../macro.value.html)
//!
//! *This module is available if Syn is built with the `"parsing"` feature.*

#[cfg(feature = "proc-macro")]
use proc_macro;
use proc_macro2;

use error::parse_error;
pub use error::{PResult, ParseError};

use buffer::{Cursor, TokenBuffer};

/// Parsing interface implemented by all types that can be parsed in a default
/// way from a token stream.
///
/// Refer to the [module documentation] for details about parsing in Syn.
///
/// [module documentation]: index.html
///
/// *This trait is available if Syn is built with the `"parsing"` feature.*
pub trait Synom: Sized {
    fn parse(input: Cursor) -> PResult<Self>;

    /// A short name of the type being parsed.
    ///
    /// The description should only be used for a simple name.  It should not
    /// contain newlines or sentence-ending punctuation, to facilitate embedding in
    /// larger user-facing strings.  Syn will use this description when building
    /// error messages about parse failures.
    ///
    /// # Examples
    ///
    /// ```
    /// # use syn::buffer::Cursor;
    /// # use syn::synom::{Synom, PResult};
    /// #
    /// struct ExprMacro {
    ///     // ...
    /// }
    ///
    /// impl Synom for ExprMacro {
    /// #   fn parse(input: Cursor) -> PResult<Self> { unimplemented!() }
    ///     // fn parse(...) -> ... { ... }
    ///
    ///     fn description() -> Option<&'static str> {
    ///         // Will result in messages like
    ///         //
    ///         //     "failed to parse macro invocation expression: $reason"
    ///         Some("macro invocation expression")
    ///     }
    /// }
    /// ```
    fn description() -> Option<&'static str> {
        None
    }
}

impl Synom for proc_macro2::TokenStream {
    fn parse(input: Cursor) -> PResult<Self> {
        Ok((input.token_stream(), Cursor::empty()))
    }

    fn description() -> Option<&'static str> {
        Some("arbitrary token stream")
    }
}

impl Synom for proc_macro2::Ident {
    fn parse(input: Cursor) -> PResult<Self> {
        let (term, rest) = match input.ident() {
            Some(term) => term,
            _ => return parse_error(),
        };
        match &term.to_string()[..] {
			"_"
			// From https://doc.rust-lang.org/grammar.html#keywords
			| "abstract" | "alignof" | "as" | "become" | "box" | "break" | "const"
			| "continue" | "crate" | "do" | "else" | "enum" | "extern" | "false" | "final"
			| "fn" | "for" | "if" | "impl" | "in" | "let" | "loop" | "macro" | "match"
			| "mod" | "move" | "mut" | "offsetof" | "override" | "priv" | "proc" | "pub"
			| "pure" | "ref" | "return" | "Self" | "self" | "sizeof" | "static" | "struct"
			| "super" | "trait" | "true" | "type" | "typeof" | "unsafe" | "unsized" | "use"
			| "virtual" | "where" | "while" | "yield" => return parse_error(),
			_ => {}
		}

        Ok((term, rest))
    }

    fn description() -> Option<&'static str> {
        Some("identifier")
    }
}

/// Parser that can parse Rust tokens into a particular syntax tree node.
///
/// Refer to the [module documentation] for details about parsing in Syn.
///
/// [module documentation]: index.html
///
/// *This trait is available if Syn is built with the `"parsing"` feature.*
pub trait Parser: Sized {
    type Output;

    /// Parse a proc-macro2 token stream into the chosen syntax tree node.
    fn parse2(self, tokens: proc_macro2::TokenStream) -> Result<Self::Output, ParseError>;

    /// Parse tokens of source code into the chosen syntax tree node.
    ///
    /// *This method is available if Syn is built with both the `"parsing"` and
    /// `"proc-macro"` features.*
    #[cfg(feature = "proc-macro")]
    fn parse(self, tokens: proc_macro::TokenStream) -> Result<Self::Output, ParseError> {
        self.parse2(tokens.into())
    }

    /// Parse a string of Rust code into the chosen syntax tree node.
    ///
    /// # Hygiene
    ///
    /// Every span in the resulting syntax tree will be set to resolve at the
    /// macro call site.
    fn parse_str(self, s: &str) -> Result<Self::Output, ParseError> {
        match s.parse() {
            Ok(tts) => self.parse2(tts),
            Err(_) => Err(ParseError::new("error while lexing input string")),
        }
    }
}

impl<F, T> Parser for F
where
    F: FnOnce(Cursor) -> PResult<T>,
{
    type Output = T;

    fn parse2(self, tokens: proc_macro2::TokenStream) -> Result<T, ParseError> {
        let buf = TokenBuffer::new2(tokens);
        let (t, rest) = self(buf.begin())?;
        if rest.eof() {
            Ok(t)
        } else if rest == buf.begin() {
            // parsed nothing
            Err(ParseError::new("failed to parse anything"))
        } else {
            Err(ParseError::new("failed to parse all tokens"))
        }
    }
}

/// Extension traits that are made available within the `call!` parser.
///
/// *This module is available if Syn is built with the `"parsing"` feature.*
pub mod ext {
    use super::*;
    use proc_macro2::Ident;

    /// Additional parsing methods for `Ident`.
    ///
    /// This trait is sealed and cannot be implemented for types outside of Syn.
    ///
    /// *This trait is available if Syn is built with the `"parsing"` feature.*
    pub trait IdentExt: Sized + private::Sealed {
        /// Parses any identifier including keywords.
        ///
        /// This is useful when parsing a DSL which allows Rust keywords as
        /// identifiers.
        ///
        /// ```rust
        /// #[macro_use]
        /// extern crate syn;
        ///
        /// use syn::Ident;
        ///
        /// // Parses input that looks like `name = NAME` where `NAME` can be
        /// // any identifier.
        /// //
        /// // Examples:
        /// //
        /// //     name = anything
        /// //     name = impl
        /// named!(parse_dsl -> Ident, do_parse!(
        ///     custom_keyword!(name) >>
        ///     punct!(=) >>
        ///     name: call!(Ident::parse_any) >>
        ///     (name)
        /// ));
        /// #
        /// # fn main() {}
        /// ```
        fn parse_any(input: Cursor) -> PResult<Self>;
    }

    impl IdentExt for Ident {
        fn parse_any(input: Cursor) -> PResult<Self> {
            input.ident().map_or_else(parse_error, Ok)
        }
    }

    mod private {
        use proc_macro2::Ident;

        pub trait Sealed {}

        impl Sealed for Ident {}
    }
}
<commit_msg>Synom for some proc_macro2 types<commit_after>// Copyright 2018 Syn Developers
//
// 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.

//! Parsing interface for parsing a token stream into a syntax tree node.
//!
//! Parsing in Syn is built on parser functions that take in a [`Cursor`] and
//! produce a [`PResult<T>`] where `T` is some syntax tree node. `Cursor` is a
//! cheaply copyable cursor over a range of tokens in a token stream, and
//! `PResult` is a result that packages together a parsed syntax tree node `T`
//! with a stream of remaining unparsed tokens after `T` represented as another
//! `Cursor`, or a [`ParseError`] if parsing failed.
//!
//! [`Cursor`]: ../buffer/index.html
//! [`PResult<T>`]: type.PResult.html
//! [`ParseError`]: struct.ParseError.html
//!
//! This `Cursor`- and `PResult`-based interface is convenient for parser
//! combinators and parser implementations, but not necessarily when you just
//! have some tokens that you want to parse. For that we expose the following
//! two entry points.
//!
//! ## The `syn::parse*` functions
//!
//! The [`syn::parse`], [`syn::parse2`], and [`syn::parse_str`] functions serve
//! as an entry point for parsing syntax tree nodes that can be parsed in an
//! obvious default way. These functions can return any syntax tree node that
//! implements the [`Synom`] trait, which includes most types in Syn.
//!
//! [`syn::parse`]: ../fn.parse.html
//! [`syn::parse2`]: ../fn.parse2.html
//! [`syn::parse_str`]: ../fn.parse_str.html
//! [`Synom`]: trait.Synom.html
//!
//! ```
//! use syn::Type;
//!
//! # fn run_parser() -> Result<(), syn::synom::ParseError> {
//! let t: Type = syn::parse_str("std::collections::HashMap<String, Value>")?;
//! #     Ok(())
//! # }
//! #
//! # fn main() {
//! #     run_parser().unwrap();
//! # }
//! ```
//!
//! The [`parse_quote!`] macro also uses this approach.
//!
//! [`parse_quote!`]: ../macro.parse_quote.html
//!
//! ## The `Parser` trait
//!
//! Some types can be parsed in several ways depending on context. For example
//! an [`Attribute`] can be either "outer" like `#[...]` or "inner" like
//! `#![...]` and parsing the wrong one would be a bug. Similarly [`Punctuated`]
//! may or may not allow trailing punctuation, and parsing it the wrong way
//! would either reject valid input or accept invalid input.
//!
//! [`Attribute`]: ../struct.Attribute.html
//! [`Punctuated`]: ../punctuated/index.html
//!
//! The `Synom` trait is not implemented in these cases because there is no good
//! behavior to consider the default.
//!
//! ```ignore
//! // Can't parse `Punctuated` without knowing whether trailing punctuation
//! // should be allowed in this context.
//! let path: Punctuated<PathSegment, Token![::]> = syn::parse(tokens)?;
//! ```
//!
//! In these cases the types provide a choice of parser functions rather than a
//! single `Synom` implementation, and those parser functions can be invoked
//! through the [`Parser`] trait.
//!
//! [`Parser`]: trait.Parser.html
//!
//! ```
//! # #[macro_use]
//! # extern crate syn;
//! #
//! # extern crate proc_macro2;
//! # use proc_macro2::TokenStream;
//! #
//! use syn::synom::Parser;
//! use syn::punctuated::Punctuated;
//! use syn::{PathSegment, Expr, Attribute};
//!
//! # fn run_parsers() -> Result<(), syn::synom::ParseError> {
//! #     let tokens = TokenStream::new().into();
//! // Parse a nonempty sequence of path segments separated by `::` punctuation
//! // with no trailing punctuation.
//! let parser = Punctuated::<PathSegment, Token![::]>::parse_separated_nonempty;
//! let path = parser.parse(tokens)?;
//!
//! #     let tokens = TokenStream::new().into();
//! // Parse a possibly empty sequence of expressions terminated by commas with
//! // an optional trailing punctuation.
//! let parser = Punctuated::<Expr, Token![,]>::parse_terminated;
//! let args = parser.parse(tokens)?;
//!
//! #     let tokens = TokenStream::new().into();
//! // Parse zero or more outer attributes but not inner attributes.
//! named!(outer_attrs -> Vec<Attribute>, many0!(Attribute::parse_outer));
//! let attrs = outer_attrs.parse(tokens)?;
//! #
//! #     Ok(())
//! # }
//! #
//! # fn main() {}
//! ```
//!
//! # Implementing a parser function
//!
//! Parser functions are usually implemented using the [`nom`]-style parser
//! combinator macros provided by Syn, but may also be implemented without
//! macros be using the low-level [`Cursor`] API directly.
//!
//! [`nom`]: https://github.com/Geal/nom
//!
//! The following parser combinator macros are available and a `Synom` parsing
//! example is provided for each one.
//!
//! - [`alt!`](../macro.alt.html)
//! - [`braces!`](../macro.braces.html)
//! - [`brackets!`](../macro.brackets.html)
//! - [`call!`](../macro.call.html)
//! - [`cond!`](../macro.cond.html)
//! - [`cond_reduce!`](../macro.cond_reduce.html)
//! - [`custom_keyword!`](../macro.custom_keyword.html)
//! - [`do_parse!`](../macro.do_parse.html)
//! - [`epsilon!`](../macro.epsilon.html)
//! - [`input_end!`](../macro.input_end.html)
//! - [`keyword!`](../macro.keyword.html)
//! - [`many0!`](../macro.many0.html)
//! - [`map!`](../macro.map.html)
//! - [`not!`](../macro.not.html)
//! - [`option!`](../macro.option.html)
//! - [`parens!`](../macro.parens.html)
//! - [`punct!`](../macro.punct.html)
//! - [`reject!`](../macro.reject.html)
//! - [`switch!`](../macro.switch.html)
//! - [`syn!`](../macro.syn.html)
//! - [`tuple!`](../macro.tuple.html)
//! - [`value!`](../macro.value.html)
//!
//! *This module is available if Syn is built with the `"parsing"` feature.*

#[cfg(feature = "proc-macro")]
use proc_macro;
use proc_macro2::{self, Delimiter, Group, Literal, Punct, TokenTree};

use error::parse_error;
pub use error::{PResult, ParseError};

use buffer::{Cursor, TokenBuffer};

/// Parsing interface implemented by all types that can be parsed in a default
/// way from a token stream.
///
/// Refer to the [module documentation] for details about parsing in Syn.
///
/// [module documentation]: index.html
///
/// *This trait is available if Syn is built with the `"parsing"` feature.*
pub trait Synom: Sized {
    fn parse(input: Cursor) -> PResult<Self>;

    /// A short name of the type being parsed.
    ///
    /// The description should only be used for a simple name.  It should not
    /// contain newlines or sentence-ending punctuation, to facilitate embedding in
    /// larger user-facing strings.  Syn will use this description when building
    /// error messages about parse failures.
    ///
    /// # Examples
    ///
    /// ```
    /// # use syn::buffer::Cursor;
    /// # use syn::synom::{Synom, PResult};
    /// #
    /// struct ExprMacro {
    ///     // ...
    /// }
    ///
    /// impl Synom for ExprMacro {
    /// #   fn parse(input: Cursor) -> PResult<Self> { unimplemented!() }
    ///     // fn parse(...) -> ... { ... }
    ///
    ///     fn description() -> Option<&'static str> {
    ///         // Will result in messages like
    ///         //
    ///         //     "failed to parse macro invocation expression: $reason"
    ///         Some("macro invocation expression")
    ///     }
    /// }
    /// ```
    fn description() -> Option<&'static str> {
        None
    }
}

impl Synom for proc_macro2::TokenStream {
    fn parse(input: Cursor) -> PResult<Self> {
        Ok((input.token_stream(), Cursor::empty()))
    }

    fn description() -> Option<&'static str> {
        Some("arbitrary token stream")
    }
}

impl Synom for TokenTree {
    fn parse(input: Cursor) -> PResult<Self> {
        match input.token_tree() {
            Some((tt, rest)) => Ok((tt, rest)),
            None => parse_error(),
        }
    }

    fn description() -> Option<&'static str> {
        Some("token tree")
    }
}

impl Synom for Group {
    fn parse(input: Cursor) -> PResult<Self> {
        for delim in &[Delimiter::Parenthesis, Delimiter::Brace, Delimiter::Bracket] {
            match input.group(*delim) {
                Some((inside, span, rest)) => {
                    let mut group = Group::new(*delim, inside.token_stream());
                    group.set_span(span);
                    return Ok((group, rest));
                }
                None => {}
            }
        }
        parse_error()
    }

    fn description() -> Option<&'static str> {
        Some("group token")
    }
}

impl Synom for proc_macro2::Ident {
    fn parse(input: Cursor) -> PResult<Self> {
        let (term, rest) = match input.ident() {
            Some(term) => term,
            _ => return parse_error(),
        };
        match &term.to_string()[..] {
			"_"
			// From https://doc.rust-lang.org/grammar.html#keywords
			| "abstract" | "alignof" | "as" | "become" | "box" | "break" | "const"
			| "continue" | "crate" | "do" | "else" | "enum" | "extern" | "false" | "final"
			| "fn" | "for" | "if" | "impl" | "in" | "let" | "loop" | "macro" | "match"
			| "mod" | "move" | "mut" | "offsetof" | "override" | "priv" | "proc" | "pub"
			| "pure" | "ref" | "return" | "Self" | "self" | "sizeof" | "static" | "struct"
			| "super" | "trait" | "true" | "type" | "typeof" | "unsafe" | "unsized" | "use"
			| "virtual" | "where" | "while" | "yield" => return parse_error(),
			_ => {}
		}

        Ok((term, rest))
    }

    fn description() -> Option<&'static str> {
        Some("identifier")
    }
}

impl Synom for Punct {
    fn parse(input: Cursor) -> PResult<Self> {
        match input.punct() {
            Some((punct, rest)) => Ok((punct, rest)),
            None => parse_error(),
        }
    }

    fn description() -> Option<&'static str> {
        Some("punctuation token")
    }
}

impl Synom for Literal {
    fn parse(input: Cursor) -> PResult<Self> {
        match input.literal() {
            Some((literal, rest)) => Ok((literal, rest)),
            None => parse_error(),
        }
    }

    fn description() -> Option<&'static str> {
        Some("literal token")
    }
}

/// Parser that can parse Rust tokens into a particular syntax tree node.
///
/// Refer to the [module documentation] for details about parsing in Syn.
///
/// [module documentation]: index.html
///
/// *This trait is available if Syn is built with the `"parsing"` feature.*
pub trait Parser: Sized {
    type Output;

    /// Parse a proc-macro2 token stream into the chosen syntax tree node.
    fn parse2(self, tokens: proc_macro2::TokenStream) -> Result<Self::Output, ParseError>;

    /// Parse tokens of source code into the chosen syntax tree node.
    ///
    /// *This method is available if Syn is built with both the `"parsing"` and
    /// `"proc-macro"` features.*
    #[cfg(feature = "proc-macro")]
    fn parse(self, tokens: proc_macro::TokenStream) -> Result<Self::Output, ParseError> {
        self.parse2(tokens.into())
    }

    /// Parse a string of Rust code into the chosen syntax tree node.
    ///
    /// # Hygiene
    ///
    /// Every span in the resulting syntax tree will be set to resolve at the
    /// macro call site.
    fn parse_str(self, s: &str) -> Result<Self::Output, ParseError> {
        match s.parse() {
            Ok(tts) => self.parse2(tts),
            Err(_) => Err(ParseError::new("error while lexing input string")),
        }
    }
}

impl<F, T> Parser for F
where
    F: FnOnce(Cursor) -> PResult<T>,
{
    type Output = T;

    fn parse2(self, tokens: proc_macro2::TokenStream) -> Result<T, ParseError> {
        let buf = TokenBuffer::new2(tokens);
        let (t, rest) = self(buf.begin())?;
        if rest.eof() {
            Ok(t)
        } else if rest == buf.begin() {
            // parsed nothing
            Err(ParseError::new("failed to parse anything"))
        } else {
            Err(ParseError::new("failed to parse all tokens"))
        }
    }
}

/// Extension traits that are made available within the `call!` parser.
///
/// *This module is available if Syn is built with the `"parsing"` feature.*
pub mod ext {
    use super::*;
    use proc_macro2::Ident;

    /// Additional parsing methods for `Ident`.
    ///
    /// This trait is sealed and cannot be implemented for types outside of Syn.
    ///
    /// *This trait is available if Syn is built with the `"parsing"` feature.*
    pub trait IdentExt: Sized + private::Sealed {
        /// Parses any identifier including keywords.
        ///
        /// This is useful when parsing a DSL which allows Rust keywords as
        /// identifiers.
        ///
        /// ```rust
        /// #[macro_use]
        /// extern crate syn;
        ///
        /// use syn::Ident;
        ///
        /// // Parses input that looks like `name = NAME` where `NAME` can be
        /// // any identifier.
        /// //
        /// // Examples:
        /// //
        /// //     name = anything
        /// //     name = impl
        /// named!(parse_dsl -> Ident, do_parse!(
        ///     custom_keyword!(name) >>
        ///     punct!(=) >>
        ///     name: call!(Ident::parse_any) >>
        ///     (name)
        /// ));
        /// #
        /// # fn main() {}
        /// ```
        fn parse_any(input: Cursor) -> PResult<Self>;
    }

    impl IdentExt for Ident {
        fn parse_any(input: Cursor) -> PResult<Self> {
            input.ident().map_or_else(parse_error, Ok)
        }
    }

    mod private {
        use proc_macro2::Ident;

        pub trait Sealed {}

        impl Sealed for Ident {}
    }
}
<|endoftext|>