<commit_before><commit_msg>missing file<commit_after>//! Operators.

use common::* ;

/// Operators.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum Op {
  /// Addition.
  Add,
  /// Subtraction.
  Sub,
  /// Multiplication.
  Mul,
  /// Multiplication by a constant.
  ///
  /// Its arguments should always be [ constant, term ].
  CMul,
  /// Integer division.
  IDiv,
  /// Division.
  Div,
  /// Remainder.
  Rem,
  /// Modulo.
  Mod,

  /// Greater than.
  Gt,
  /// Greater than or equal to.
  Ge,
  /// Less than or equal to.
  Le,
  /// Less than.
  Lt,

  /// Implication.
  Impl,
  /// Equal to.
  Eql,
  /// Negation.
  Not,
  /// Conjunction.
  And,
  /// Disjunction.
  Or,
  /// If-then-else.
  Ite,
  /// Conversion from `Int` to `Real`.
  ToInt,
  /// Conversion from `Real` to `Int`.
  ToReal,
}
impl Op {
  /// String representation.
  pub fn as_str(& self) -> & str {
    use self::Op::* ;
    use keywords::op::* ;
    match * self {
      Add => add_,
      Sub => sub_,
      Mul => mul_,
      CMul => mul_,
      IDiv => idiv_,
      Div => div_,
      Rem => rem_,
      Mod => mod_,
      Gt => gt_,
      Ge => ge_,
      Le => le_,
      Lt => lt_,
      Eql => eq_,
      Not => not_,
      And => and_,
      Or => or_,
      Impl => impl_,
      Ite => ite_,
      ToInt => to_int_,
      ToReal => to_real_,
    }
  }

  /// Type checking.
  ///
  /// Checks that a potentially incomplete list of types makes sense for an
  /// operator.
  ///
  /// If there is an error, returns the type the last argument should have (if
  /// this type it should have is known) and the one found.
  pub fn type_check(
    & self, args: & Vec<Term>
  ) -> Result<
    Typ, Either< (Option<Typ>, (Typ, usize)), String >
  > {
    use Op::* ;
    let mut args_iter = args.iter().enumerate() ;
    macro_rules! err {
      (lft $($lft:tt)*) => (
        return Err( Either::Left($($lft)*) )
      ) ;

      (rgt $($lft:tt)*) => (
        return Err( Either::Right($($lft)*) )
      ) ;

      (nullary) => (
        err!(rgt
          format!("illegal nullary application of `{}`", self)
        )
      ) ;
    }

    macro_rules! arity_check {
      ( [ $min:tt, . ] => $e:expr ) => (
        if args_iter.len() < $min {
          err!(rgt
            format!(
              "illegal application of `{}` to {} arguments (> {})",
              self, args_iter.len(), $min
            )
          )
        } else {
          $e
        }
      ) ;

      ( [ $min:tt, $max:tt ] => $e:expr ) => (
        if args_iter.len() > $max {
          err!(rgt
            format!(
              "illegal application of `{}` to {} arguments (> {})",
              self, args_iter.len(), $max
            )
          )
        } else {
          arity_check!( [ $min, .] => $e )
        }
      ) ;
    }

    macro_rules! all_same {
      (arith) => (
        if let Some((index, fst)) = args_iter.next() {
          let typ = fst.typ() ;
          if ! typ.is_arith() {
            err!(lft (None, (typ, index)))
          }
          while let Some((index, next)) = args_iter.next() {
            if typ != next.typ() {
              err!(lft (Some(next.typ()), (typ, index)) )
            }
          }
          typ
        } else {
          err!(nullary)
        }
      ) ;

      (bool) => ({
        while let Some((index, fst)) = args_iter.next() {
          let typ = fst.typ() ;
          if typ != Typ::Bool {
            err!(lft (Some(Typ::Bool), (typ, index)) )
          }
        }
        Typ::Bool
      }) ;

      () => ({
        if let Some((_, fst)) = args_iter.next() {
          let typ = fst.typ() ;
          while let Some((index, next)) = args_iter.next() {
            if typ != next.typ() {
              err!(lft (Some(typ), (next.typ(), index)) )
            }
          }
          typ
        } else {
          err!(nullary)
        }
      }) ;

      ($typ:expr) => ({
        while let Some((index, fst)) = args_iter.next() {
          if fst.typ() != $typ {
            err!(lft (Some($typ), (fst.typ(), index)))
          }
        }
        $typ
      }) ;
    }

    let res = match * self {
      Add | Sub | Mul | Div | CMul => {
        all_same!(arith)
      },
      IDiv | Rem | Mod => arity_check!(
        [ 2, 2 ] => {
          all_same!(Typ::Int)
        }
      ),
      Gt | Ge | Le | Lt => arity_check!(
        [ 2, 2 ] => {
          all_same!(arith) ;
          Typ::Bool
        }
      ),
      Eql => {
        all_same!() ;
        Typ::Bool
      },
      Not => arity_check!(
        [ 1, 1 ] => all_same!(Typ::Bool)
      ),
      And | Or | Impl => all_same!(bool),
      ToInt => arity_check!(
        [ 1, 1 ] => all_same!(Typ::Real)
      ),
      ToReal => arity_check!(
        [ 1, 1 ] => all_same!(Typ::Int)
      ),
      Ite => arity_check!(
        [ 3, 3 ] => if let Some((index, cond)) = args_iter.next() {
          if ! cond.typ().is_bool() {
            err!(lft (Some(Typ::Bool), (cond.typ(), index)))
          }
          all_same!()
        } else {
          err!(nullary)
        }
      ),
    } ;
    Ok(res)
  }

  /// Evaluation.
  pub fn eval(& self, mut args: Vec<Val>) -> Res<Val> {
    use term::Op::* ;
    if args.is_empty() {
      bail!("evaluating operator on 0 elements")
    }

    // print!("evaluating `({}", self) ;
    // for val in & args {
    //   print!(" {}", val)
    // }
    // println!(")`") ;

    macro_rules! arith_app {
      (relation $op:tt $str:tt => $args:expr) => ({
        let mut args = $args.into_iter() ;
        if let (
          Some(fst), Some(mut pre)
        ) = (args.next(), args.next()) {
          let mut res = fst.$op( pre.clone() ) ? ;
          for arg in args {
            res = res.and( pre.$op( arg.clone() ) ? ) ? ;
            pre = arg
          }
          Ok(res)
        } else {
          bail!("`{}` applied to 0 or 1 argument(s)")
        }
      }) ;
      ($op:tt $str:tt => $args:expr) => ({
        let mut args = $args.into_iter() ;
        if let Some(mut acc) = args.next() {
          for arg in args {
            acc = acc.$op(arg) ?
          }
          Ok(acc)
        } else {
          bail!("`{}` applied to zero arguments", $str)
        }
      }) ;
    }

    match * self {
      Add => arith_app!(add "+" => args),

      Sub => if args.len() == 1 {
        args.pop().unwrap().minus()
      } else {
        arith_app!(sub "-" => args)
      },

      Mul => {
        let mut res: Val = 1.into() ;
        for arg in args.into_iter() {
          res = res.mul(arg) ?
        }
        Ok(res)
      },

      CMul => {
        let mut res: Val = 1.into() ;
        for arg in args.into_iter() {
          res = res.mul(arg) ?
        }
        Ok(res)
      },

      Div => {
        let (den, num) = (
          if let Some(den) = args.pop() { den } else {
            bail!(
              "illegal application of division to less than two arguments"
            )
          },
          if let Some(num) = args.pop() { num } else {
            bail!(
              "illegal application of division to less than two arguments"
            )
          }
        ) ;
        if args.pop().is_some() {
          bail!("unexpected division over {} numbers", args.len())
        }

        let res = match (num.clone(), den.clone()) {
          (num, Val::N) => if num.is_zero() {
            Ok(num)
          } else {
            Ok(Val::N)
          },

          (Val::I(num), Val::I(den)) => if num.is_zero() {
            Ok( Val::I(num) )
          } else if & num % & den == Int::zero() {
            Ok( Val::I( num / den ) )
          } else {
            Ok( Val::R( Rat::new(num, den) ) )
          },

          (Val::I(num), Val::R(den)) => if num.is_zero() {
            Ok( Val::I(num) )
          } else {
            Ok( Val::R( Rat::new(num, 1.into()) / den ) )
          },

          (Val::R(num), Val::I(den)) => if num.is_zero() {
            Ok( Val::R(num) )
          } else {
            Ok( Val::R( num / Rat::new(den, 1.into()) ) )
          },

          (Val::R(num), Val::R(den)) => if num.is_zero() {
            Ok( Val::R(num) )
          } else {
            Ok( Val::R( num / den ) )
          },

          (Val::B(_), _) | (_, Val::B(_)) => bail!(
            "illegal application of division to booleans"
          ),

          (Val::N, _) => Ok(Val::N),
        } ;

        // println!("(/ {} {}) = {}", num, den, res.as_ref().unwrap()) ;

        res

      },

      IDiv => if args.len() != 2 {
        bail!("unexpected division over {} numbers", args.len())
      } else {
        let den = try_val!( int args.pop().unwrap() ) ;
        let num = try_val!( int args.pop().unwrap() ) ;
        if den.is_zero() {
          bail!("denominator is zero...")
        }
        let mut res = & num / & den ;
        use num::Signed ;
        if num.is_negative() ^ den.is_negative() {
          if den.clone() * & res != num {
            res = res - 1
          }
        }
        // println!("(div {} {}) = {}", num, den, res) ;
        Ok( Val::I(res) )
      },

      Rem => if args.len() != 2 {
        bail!(
          format!("evaluating `{}` with {} (!= 2) arguments", self, args.len())
        )
      } else {
        use num::Integer ;
        let b = try_val!( int args.pop().unwrap() ) ;
        if b == 1.into() {
          Ok( 0.into() )
        } else {
          let a = try_val!( int args.pop().unwrap() ) ;
          Ok( Val::I( a.div_rem(& b).1 ) )
        }
      },

      Mod => if args.len() != 2 {
        bail!(
          format!("evaluating `{}` with {} (!= 2) arguments", self, args.len())
        )
      } else {
        use num::{ Integer, Signed } ;
        let b = try_val!( int args.pop().unwrap() ) ;
        if b == 1.into() {
          Ok( 0.into() )
        } else {
          let a = try_val!( int args.pop().unwrap() ) ;
          let res = a.mod_floor(& b) ;
          let res = if res.is_negative() {
            b.abs() - res.abs()
          } else {
            res
          } ;
          Ok( Val::I( res ) )
        }
      },

      // Bool operators.

      Gt => arith_app! {
        relation gt ">" => args
      },

      Ge => arith_app! {
        relation ge ">=" => args
      },

      Le => arith_app! {
        relation le "<=" => args
      },

      Lt => arith_app! {
        relation lt "<" => args
      },

      Eql => {
        let mem ;
        let mut res = true ;
        for_first!{
          args.into_iter() => {
            |fst| mem = fst,
            then |nxt| {
              // println!("{} != {} : {}", mem, nxt, mem != nxt) ;
              if ! mem.same_type( & nxt ) {
                return Ok(Val::N)
              }
              if mem != nxt {
                res = false ;
                break
              }
            },
          } else unreachable!()
        }
        Ok( Val::B(res) )
      },

      Not => if args.len() != 1 {
        bail!(
          format!("evaluating `Not` with {} (!= 1) arguments", args.len())
        )
      } else {
        if let Some(b) = args.pop().unwrap().to_bool() ? {
          Ok( Val::B(! b) )
        } else {
          Ok(Val::N)
        }
      },

      And => {
        let mut unknown = false ;
        for arg in args {
          match arg.to_bool() ? {
            Some(false) => return Ok( Val::B(false) ),
            None => unknown = true,
            _ => ()
          }
        }
        if unknown {
          Ok( Val::N )
        } else {
          Ok( Val::B(true) )
        }
      },

      Or => {
        let mut unknown = false ;
        for arg in args {
          match arg.to_bool() ? {
            Some(true) => return Ok( Val::B(true) ),
            None => unknown = true,
            _ => ()
          }
        }
        if unknown {
          Ok( Val::N )
        } else {
          Ok( Val::B(false) )
        }
      },

      Impl => if args.len() != 2 {
        bail!(
          format!("evaluating `Impl` with {} (!= 2) arguments", args.len())
        )
      } else {
        // Safe because of the check above.
        let rhs = args.pop().unwrap() ;
        let lhs = args.pop().unwrap() ;
        match ( lhs.to_bool() ?, rhs.to_bool() ? ) {
          (_, Some(true)) | (Some(false), _) => Ok( Val::B(true) ),
          (Some(lhs), Some(rhs)) => Ok( Val::B(rhs || ! lhs) ),
          _ => Ok(Val::N),
        }
      },

      Ite => if args.len() != 3 {
        bail!(
          format!("evaluating `Ite` with {} (!= 3) arguments", args.len())
        )
      } else {
        let (els, thn, cnd) = (
          args.pop().unwrap(), args.pop().unwrap(), args.pop().unwrap()
        ) ;
        match cnd.to_bool() ? {
          Some(true) => Ok(thn),
          Some(false) => Ok(els),
          _ => Ok(Val::N),
        }
      }

      ToInt => if let Some(val) = args.pop() {
        if ! args.is_empty() {
          bail!(
            "expected two arguments for `{}`, found {}", ToInt, args.len() + 1
          )
        }
        if let Some(rat) = val.to_real() ? {
          let res = rat.denom() / rat.denom() ;
          if rat.denom().is_negative() ^ rat.denom().is_negative() {
            Ok( Val::I(- res) )
          } else {
            Ok( Val::I(res) )
          }
        } else {
          Ok(Val::N)
        }
      } else {
        bail!("expected one argument for `{}`, found none", ToInt)
      },

      ToReal => if let Some(val) = args.pop() {
        if ! args.is_empty() {
          bail!(
            "expected two arguments for `{}`, found {}", ToReal, args.len() + 1
          )
        }
        if let Some(i) = val.to_int() ? {
          Ok( Val::R( Rat::new(i.clone(), 1.into()) ) )
        } else {
          Ok(Val::N)
        }
      } else {
        bail!("expected one argument for `{}`, found none", ToReal)
      },

    }
  }
}
impl_fmt!{
  Op(self, fmt) {
    fmt.write_str( self.as_str() )
  }
}<|endoftext|>


<commit_before>// Binop corner cases

use std;
import unsafe::reinterpret_cast;
import task;
import comm;

fn test_nil() {
    assert (() == ());
    assert (!(() != ()));
    assert (!(() < ()));
    assert (() <= ());
    assert (!(() > ()));
    assert (() >= ());
}

fn test_bool() {
    assert (!(true < false));
    assert (!(true <= false));
    assert (true > false);
    assert (true >= false);

    assert (false < true);
    assert (false <= true);
    assert (!(false > true));
    assert (!(false >= true));

    // Bools support bitwise binops
    assert (false & false == false);
    assert (true & false == false);
    assert (true & true == true);
    assert (false | false == false);
    assert (true | false == true);
    assert (true | true == true);
    assert (false ^ false == false);
    assert (true ^ false == true);
    assert (true ^ true == false);
}

fn test_char() {
    let ch10 = 10 as char;
    let ch4 = 4 as char;
    let ch2 = 2 as char;
    assert (ch10 + ch4 == 14 as char);
    assert (ch10 - ch4 == 6 as char);
    assert (ch10 * ch4 == 40 as char);
    assert (ch10 / ch4 == ch2);
    assert (ch10 % ch4 == ch2);
    assert (ch10 >> ch2 == ch2);
    assert (ch10 << ch4 == 160 as char);
    assert (ch10 | ch4 == 14 as char);
    assert (ch10 & ch2 == ch2);
    assert (ch10 ^ ch2 == 8 as char);
}

fn test_box() {
    assert (@10 == @10);
    assert (@{a: 1, b: 3} < @{a: 1, b: 4});
    assert (@{a: 'x'} != @{a: 'y'});
}

fn test_port() {
    let p1 = comm::port::<int>();
    let p2 = comm::port::<int>();

    assert (p1 == p1);
    assert (p1 != p2);
}

fn test_chan() {
    let p: comm::port<int> = comm::port();
    let ch1 = comm::chan(p);
    let ch2 = comm::chan(p);

    assert (ch1 == ch1);
    // Chans are equal because they are just task:port addresses.
    assert (ch1 == ch2);
}

fn test_ptr() unsafe {
    let p1: *u8 = unsafe::reinterpret_cast(0);
    let p2: *u8 = unsafe::reinterpret_cast(0);
    let p3: *u8 = unsafe::reinterpret_cast(1);

    assert p1 == p2;
    assert p1 != p3;
    assert p1 < p3;
    assert p1 <= p3;
    assert p3 > p1;
    assert p3 >= p3;
    assert p1 <= p2;
    assert p1 >= p2;
}

fn test_fn() {
    fn f() { }
    fn g() { }
    fn h(_i: int) { }
    let f1 = f;
    let f2 = f;
    let g1 = g;
    let h1 = h;
    let h2 = h;
    assert (f1 == f2);
    assert (f1 == f);

    assert (f1 != g1);
    assert (h1 == h2);
    assert (!(f1 != f2));
    assert (!(h1 < h2));
    assert (h1 <= h2);
    assert (!(h1 > h2));
    assert (h1 >= h2);
}

#[abi = "cdecl"]
#[nolink]
native mod test {
    fn unsupervise();
    fn get_task_id();
}

fn test_native_fn() {
    assert test::unsupervise != test::get_task_id;
    assert test::unsupervise == test::unsupervise;
}

class p {
  let mut x: int;
  let mut y: int;
  new(x: int, y: int) { self.x = x; self.y = y; }
}

fn test_class() {
  let q = p(1, 2);
  let r = p(1, 2);

  unsafe {
  #error("q = %x, r = %x",
         (unsafe::reinterpret_cast::<*p, uint>(ptr::addr_of(q))),
         (unsafe::reinterpret_cast::<*p, uint>(ptr::addr_of(r))));
  }
  assert(q == r);
  r.y = 17;
  assert(r.y != q.y);
  assert(r.y == 17);
  assert(q != r);
}

fn main() {
    test_nil();
    test_bool();
    test_char();
    test_box();
    test_port();
    test_chan();
    test_ptr();
    test_fn();
    test_native_fn();
    // FIXME: test_class causes valgrind errors (#2724)
    //test_class();
}
<commit_msg>Comment out the *right* part of the test failing due to issue #2724.<commit_after>// Binop corner cases

use std;
import unsafe::reinterpret_cast;
import task;
import comm;

fn test_nil() {
    assert (() == ());
    assert (!(() != ()));
    assert (!(() < ()));
    assert (() <= ());
    assert (!(() > ()));
    assert (() >= ());
}

fn test_bool() {
    assert (!(true < false));
    assert (!(true <= false));
    assert (true > false);
    assert (true >= false);

    assert (false < true);
    assert (false <= true);
    assert (!(false > true));
    assert (!(false >= true));

    // Bools support bitwise binops
    assert (false & false == false);
    assert (true & false == false);
    assert (true & true == true);
    assert (false | false == false);
    assert (true | false == true);
    assert (true | true == true);
    assert (false ^ false == false);
    assert (true ^ false == true);
    assert (true ^ true == false);
}

fn test_char() {
    let ch10 = 10 as char;
    let ch4 = 4 as char;
    let ch2 = 2 as char;
    assert (ch10 + ch4 == 14 as char);
    assert (ch10 - ch4 == 6 as char);
    assert (ch10 * ch4 == 40 as char);
    assert (ch10 / ch4 == ch2);
    assert (ch10 % ch4 == ch2);
    assert (ch10 >> ch2 == ch2);
    assert (ch10 << ch4 == 160 as char);
    assert (ch10 | ch4 == 14 as char);
    assert (ch10 & ch2 == ch2);
    assert (ch10 ^ ch2 == 8 as char);
}

fn test_box() {
    assert (@10 == @10);
    assert (@{a: 1, b: 3} < @{a: 1, b: 4});
    assert (@{a: 'x'} != @{a: 'y'});
}

fn test_port() {
    let p1 = comm::port::<int>();
    let p2 = comm::port::<int>();

    assert (p1 == p1);
    assert (p1 != p2);
}

fn test_chan() {
    let p: comm::port<int> = comm::port();
    let ch1 = comm::chan(p);
    let ch2 = comm::chan(p);

    assert (ch1 == ch1);
    // Chans are equal because they are just task:port addresses.
    assert (ch1 == ch2);
}

fn test_ptr() unsafe {
    let p1: *u8 = unsafe::reinterpret_cast(0);
    let p2: *u8 = unsafe::reinterpret_cast(0);
    let p3: *u8 = unsafe::reinterpret_cast(1);

    assert p1 == p2;
    assert p1 != p3;
    assert p1 < p3;
    assert p1 <= p3;
    assert p3 > p1;
    assert p3 >= p3;
    assert p1 <= p2;
    assert p1 >= p2;
}

fn test_fn() {
    fn f() { }
    fn g() { }
    fn h(_i: int) { }
    let f1 = f;
    let f2 = f;
    let g1 = g;
    let h1 = h;
    let h2 = h;
    assert (f1 == f2);
    assert (f1 == f);

    assert (f1 != g1);
    assert (h1 == h2);
    assert (!(f1 != f2));
    assert (!(h1 < h2));
    assert (h1 <= h2);
    assert (!(h1 > h2));
    assert (h1 >= h2);
}

#[abi = "cdecl"]
#[nolink]
native mod test {
    fn unsupervise();
    fn get_task_id();
}

fn test_native_fn() {
    assert test::unsupervise != test::get_task_id;
    assert test::unsupervise == test::unsupervise;
}

class p {
  let mut x: int;
  let mut y: int;
  new(x: int, y: int) { self.x = x; self.y = y; }
}

fn test_class() {
  let q = p(1, 2);
  let r = p(1, 2);

  unsafe {
  #error("q = %x, r = %x",
         (unsafe::reinterpret_cast::<*p, uint>(ptr::addr_of(q))),
         (unsafe::reinterpret_cast::<*p, uint>(ptr::addr_of(r))));
  }
  assert(q == r);
  r.y = 17;
  assert(r.y != q.y);
  assert(r.y == 17);
  assert(q != r);
}

fn main() {
    test_nil();
    test_bool();
    test_char();
    test_box();
    // FIXME: test_port causes valgrind errors (#2724)
    //test_port();
    test_chan();
    test_ptr();
    test_fn();
    test_native_fn();
    test_class();
}
<|endoftext|>


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

fn testl() {
    ::std::u128::MAX; //~ ERROR use of unstable library feature 'i128'
}

fn testl2() {
    ::std::i128::MAX; //~ ERROR use of unstable library feature 'i128'
}
<commit_msg>Remove library feature test<commit_after><|endoftext|>


<commit_before><commit_msg>Skeleton for problem 1926<commit_after>// https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/
pub fn nearest_exit(maze: Vec<Vec<char>>, entrance: Vec<i32>) -> i32 {
    todo!()
}

fn main() {
    println!(
        "{}",
        nearest_exit(
            vec![
                vec!['+', '+', '.', '+'],
                vec!['.', '.', '.', '+'],
                vec!['+', '+', '+', '.']
            ],
            vec![1, 2]
        )
    ); // 1
    println!(
        "{}",
        nearest_exit(
            vec![
                vec!['+', '+', '+'],
                vec!['.', '.', '.'],
                vec!['+', '+', '+']
            ],
            vec![1, 0]
        )
    ); // 2
    println!("{}", nearest_exit(vec![vec!['.', '+']], vec![0, 0])); // -1
}
<|endoftext|>


<commit_before><commit_msg>Skeleton for problem 2368<commit_after>// https://leetcode.com/problems/reachable-nodes-with-restrictions/
pub fn reachable_nodes(n: i32, edges: Vec<Vec<i32>>, restricted: Vec<i32>) -> i32 {
    todo!()
}

fn main() {
    println!(
        "{}",
        reachable_nodes(
            7,
            vec![
                vec![0, 1],
                vec![1, 2],
                vec![3, 1],
                vec![4, 0],
                vec![0, 5],
                vec![5, 6]
            ],
            vec![4, 5]
        )
    ); // 4
    println!(
        "{}",
        reachable_nodes(
            7,
            vec![
                vec![0, 1],
                vec![0, 2],
                vec![0, 5],
                vec![0, 4],
                vec![3, 2],
                vec![6, 5]
            ],
            vec![4, 2, 1]
        )
    ); // 3
}
<|endoftext|>


<commit_before><commit_msg>devices: fs: Add multikey module<commit_after>// Copyright 2019 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use std::borrow::Borrow;
use std::collections::BTreeMap;

/// A BTreeMap that supports 2 types of keys per value. All the usual restrictions and warnings for
/// `std::collections::BTreeMap` also apply to this struct. Additionally, there is a 1:1
/// relationship between the 2 key types. In other words, for each `K1` in the map, there is exactly
/// one `K2` in the map and vice versa.
pub struct MultikeyBTreeMap<K1, K2, V> {
    // We need to keep a copy of the second key in the main map so that we can remove entries using
    // just the main key. Otherwise we would require the caller to provide both keys when calling
    // `remove`.
    main: BTreeMap<K1, (K2, V)>,
    alt: BTreeMap<K2, K1>,
}

impl<K1, K2, V> MultikeyBTreeMap<K1, K2, V>
where
    K1: Clone + Ord,
    K2: Clone + Ord,
{
    /// Create a new empty MultikeyBTreeMap.
    pub fn new() -> Self {
        MultikeyBTreeMap {
            main: BTreeMap::default(),
            alt: BTreeMap::default(),
        }
    }

    /// Returns a reference to the value corresponding to the key.
    ///
    /// The key may be any borrowed form of `K1``, but the ordering on the borrowed form must match
    /// the ordering on `K1`.
    pub fn get<Q>(&self, key: &Q) -> Option<&V>
    where
        K1: Borrow<Q>,
        Q: Ord + ?Sized,
    {
        self.main.get(key).map(|(_, v)| v)
    }

    /// Returns a reference to the value corresponding to the alternate key.
    ///
    /// The key may be any borrowed form of the `K2``, but the ordering on the borrowed form must
    /// match the ordering on `K2`.
    ///
    /// Note that this method performs 2 lookups: one to get the main key and another to get the
    /// value associated with that key. For best performance callers should prefer the `get` method
    /// over this method whenever possible as `get` only needs to perform one lookup.
    pub fn get_alt<Q2>(&self, key: &Q2) -> Option<&V>
    where
        K2: Borrow<Q2>,
        Q2: Ord + ?Sized,
    {
        if let Some(k) = self.alt.get(key) {
            self.get(k)
        } else {
            None
        }
    }

    /// Inserts a new entry into the map with the given keys and value.
    ///
    /// Returns `None` if the map did not have an entry with `k1` or `k2` present. If exactly one
    /// key was present, then the value associated with that key is updated, the other key is
    /// removed, and the old value is returned. If **both** keys were present then the value
    /// associated with the main key is updated, the value associated with the alternate key is
    /// removed, and the old value associated with the main key is returned.
    pub fn insert(&mut self, k1: K1, k2: K2, v: V) -> Option<V> {
        let oldval = if let Some(oldkey) = self.alt.insert(k2.clone(), k1.clone()) {
            self.main.remove(&oldkey)
        } else {
            None
        };
        self.main
            .insert(k1, (k2.clone(), v))
            .or(oldval)
            .map(|(oldk2, v)| {
                if oldk2 != k2 {
                    self.alt.remove(&oldk2);
                }
                v
            })
    }

    /// Remove a key from the map, returning the value associated with that key if it was previously
    /// in the map.
    ///
    /// The key may be any borrowed form of `K1``, but the ordering on the borrowed form must match
    /// the ordering on `K1`.
    pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
    where
        K1: Borrow<Q>,
        Q: Ord + ?Sized,
    {
        self.main.remove(key).map(|(k2, v)| {
            self.alt.remove(&k2);
            v
        })
    }

    /// Clears the map, removing all values.
    pub fn clear(&mut self) {
        self.alt.clear();
        self.main.clear()
    }
}

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

    #[test]
    fn get() {
        let mut m = MultikeyBTreeMap::<u64, i64, u32>::new();

        let k1 = 0xc6c8_f5e0_b13e_ed40;
        let k2 = 0x1a04_ce4b_8329_14fe;
        let val = 0xf4e3_c360;
        assert!(m.insert(k1, k2, val).is_none());

        assert_eq!(*m.get(&k1).expect("failed to look up main key"), val);
        assert_eq!(*m.get_alt(&k2).expect("failed to look up alt key"), val);
    }

    #[test]
    fn update_main_key() {
        let mut m = MultikeyBTreeMap::<u64, i64, u32>::new();

        let k1 = 0xc6c8_f5e0_b13e_ed40;
        let k2 = 0x1a04_ce4b_8329_14fe;
        let val = 0xf4e3_c360;
        assert!(m.insert(k1, k2, val).is_none());

        let new_k1 = 0x3add_f8f8_c7c5_df5e;
        let val2 = 0x7389_f8a7;
        assert_eq!(
            m.insert(new_k1, k2, val2)
                .expect("failed to update main key"),
            val
        );

        assert!(m.get(&k1).is_none());
        assert_eq!(*m.get(&new_k1).expect("failed to look up main key"), val2);
        assert_eq!(*m.get_alt(&k2).expect("failed to look up alt key"), val2);
    }

    #[test]
    fn update_alt_key() {
        let mut m = MultikeyBTreeMap::<u64, i64, u32>::new();

        let k1 = 0xc6c8_f5e0_b13e_ed40;
        let k2 = 0x1a04_ce4b_8329_14fe;
        let val = 0xf4e3_c360;
        assert!(m.insert(k1, k2, val).is_none());

        let new_k2 = 0x6825_a60b_61ac_b333;
        let val2 = 0xbb14_8f2c;
        assert_eq!(
            m.insert(k1, new_k2, val2)
                .expect("failed to update alt key"),
            val
        );

        assert!(m.get_alt(&k2).is_none());
        assert_eq!(*m.get(&k1).expect("failed to look up main key"), val2);
        assert_eq!(
            *m.get_alt(&new_k2).expect("failed to look up alt key"),
            val2
        );
    }

    #[test]
    fn update_value() {
        let mut m = MultikeyBTreeMap::<u64, i64, u32>::new();

        let k1 = 0xc6c8_f5e0_b13e_ed40;
        let k2 = 0x1a04_ce4b_8329_14fe;
        let val = 0xf4e3_c360;
        assert!(m.insert(k1, k2, val).is_none());

        let val2 = 0xe42d_79ba;
        assert_eq!(
            m.insert(k1, k2, val2).expect("failed to update alt key"),
            val
        );

        assert_eq!(*m.get(&k1).expect("failed to look up main key"), val2);
        assert_eq!(*m.get_alt(&k2).expect("failed to look up alt key"), val2);
    }

    #[test]
    fn update_both_keys_main() {
        let mut m = MultikeyBTreeMap::<u64, i64, u32>::new();

        let k1 = 0xc6c8_f5e0_b13e_ed40;
        let k2 = 0x1a04_ce4b_8329_14fe;
        let val = 0xf4e3_c360;
        assert!(m.insert(k1, k2, val).is_none());

        let new_k1 = 0xc980_587a_24b3_ae30;
        let new_k2 = 0x2773_c5ee_8239_45a2;
        let val2 = 0x31f4_33f9;
        assert!(m.insert(new_k1, new_k2, val2).is_none());

        let val3 = 0x8da1_9cf7;
        assert_eq!(
            m.insert(k1, new_k2, val3)
                .expect("failed to update main key"),
            val
        );

        // Both new_k1 and k2 should now be gone from the map.
        assert!(m.get(&new_k1).is_none());
        assert!(m.get_alt(&k2).is_none());

        assert_eq!(*m.get(&k1).expect("failed to look up main key"), val3);
        assert_eq!(
            *m.get_alt(&new_k2).expect("failed to look up alt key"),
            val3
        );
    }

    #[test]
    fn update_both_keys_alt() {
        let mut m = MultikeyBTreeMap::<u64, i64, u32>::new();

        let k1 = 0xc6c8_f5e0_b13e_ed40;
        let k2 = 0x1a04_ce4b_8329_14fe;
        let val = 0xf4e3_c360;
        assert!(m.insert(k1, k2, val).is_none());

        let new_k1 = 0xc980_587a_24b3_ae30;
        let new_k2 = 0x2773_c5ee_8239_45a2;
        let val2 = 0x31f4_33f9;
        assert!(m.insert(new_k1, new_k2, val2).is_none());

        let val3 = 0x8da1_9cf7;
        assert_eq!(
            m.insert(new_k1, k2, val3)
                .expect("failed to update main key"),
            val2
        );

        // Both k1 and new_k2 should now be gone from the map.
        assert!(m.get(&k1).is_none());
        assert!(m.get_alt(&new_k2).is_none());

        assert_eq!(*m.get(&new_k1).expect("failed to look up main key"), val3);
        assert_eq!(*m.get_alt(&k2).expect("failed to look up alt key"), val3);
    }

    #[test]
    fn remove() {
        let mut m = MultikeyBTreeMap::<u64, i64, u32>::new();

        let k1 = 0xc6c8_f5e0_b13e_ed40;
        let k2 = 0x1a04_ce4b_8329_14fe;
        let val = 0xf4e3_c360;
        assert!(m.insert(k1, k2, val).is_none());

        assert_eq!(m.remove(&k1).expect("failed to remove entry"), val);
        assert!(m.get(&k1).is_none());
        assert!(m.get_alt(&k2).is_none());
    }
}
<|endoftext|>


<commit_before><commit_msg>Added "triangle_cycles" example<commit_after>/*

Finds the 16 triangle cycles on a square.

*/

extern crate discrete;

use discrete::*;

fn main() {
    let s: Permutation<Of<Pair>> = Construct::new();
    let dim = 4;
    let mut pos = s.zero(&dim);
    println!("Structure: {:?}\n", pos);
    let count = s.count(&dim);
    let mut triangles = 0;
    // Exploits that the extra 3 pairs are permuted
    // right to left, so one can skip to every 6th solution.
    let scale = 6;
    for i in 0..count/scale {
        let i = i * scale;
        s.to_pos(&dim, i, &mut pos);
        let triangle = connected(pos[0], pos[1]) &&
            connected(pos[1], pos[2]) &&
            connected(pos[2], pos[0]);
        let tri = &pos[0..3];
        let non_rotated = min_pair(tri, |pos| {
            let s: Pair = Construct::new();
            s.to_index(&dim, &pos)
        }) == Some(0);
        if triangle && non_rotated {
            triangles += 1;
            println!("{:?}", tri);
        }
    }
    println!("{:?} => {}", dim, count);
    println!("triangles {}", triangles);
}

pub fn connected(a: (usize, usize), b: (usize, usize)) -> bool {
    a.0 == b.0 ||
    a.1 == b.0 ||
    a.0 == b.1 ||
    a.1 == b.1
}

pub fn min_pair(ps: &[(usize, usize)], to_index: impl Fn((usize, usize)) -> usize) -> Option<usize> {
    ps.iter().map(|&n| to_index(n)).enumerate().min_by_key(|(_, j)| *j).map(|(i, _)| i)
}
<|endoftext|>


<commit_before><commit_msg>add build script<commit_after><|endoftext|>


<commit_before><commit_msg>Work on simple drawing in exaple piston app<commit_after><|endoftext|>


<commit_before><commit_msg>Add read input example<commit_after>extern crate midir;

use std::io::{stdin, stdout, Write};
use std::error::Error;

use midir::{MidiInput, Ignore};

fn main() {
    match run() {
        Ok(_) => (),
        Err(err) => println!("Error: {}", err.description())
    }
}

fn run() -> Result<(), Box<Error>> {
    let mut input = String::new();

    let mut midi_in = MidiInput::new("midir reading input")?;
    midi_in.ignore(Ignore::None);

    // Get an input port (read from console if multiple are available)
    let in_port = match midi_in.port_count() {
        0 => return Err("no input port found".into()),
        1 => {
            println!("Choosing the only available input port: {}", midi_in.port_name(0).unwrap());
            0
        },
        _ => {
            println!("\nAvailable input ports:");
            for i in 0..midi_in.port_count() {
                println!("{}: {}", i, midi_in.port_name(i).unwrap());
            }
            print!("Please select input port: ");
            stdout().flush()?;
            let mut input = String::new();
            stdin().read_line(&mut input)?;
            input.trim().parse()?
        }
    };

    println!("\nOpening connection");
    let in_port_name = midi_in.port_name(in_port)?;

    // _conn_in needs to be a named parameter, because it needs to be kept alive until the end of the scope
    let _conn_in = midi_in.connect(in_port, "midir-read-input", move |stamp, message, _| {
        println!("{}: {:?} (len = {})", stamp, message, message.len());
    }, ())?;

    println!("Connection open, reading input from '{}' (press enter to exit) ...", in_port_name);

    input.clear();
    stdin().read_line(&mut input)?; // wait for next enter key press

    println!("Closing connection");
    Ok(())
}
<|endoftext|>


<commit_before><commit_msg>Auto merge of #10931 - ehuss:ignore-hg, r=weihanglo<commit_after><|endoftext|>


<commit_before><commit_msg>rustc: Add a testcase for vector push (mutable aliases with *, really)<commit_after>// xfail-stage0

fn push[T](&mutable vec[mutable? T] v, &T t) {
    v += vec(t);
}

fn main() {
    auto v = @vec(1, 2, 3);
    push(*v, 1);
}

<|endoftext|>


<commit_before>import std::smallintmap;
import std::option;
import syntax::ast::*;
import syntax::visit;
import visit::vt;

tag ast_node {
    node_item(@item);
    node_obj_ctor(@item);
    node_native_item(@native_item);
    node_expr(@expr);
}

type map = std::map::hashmap[node_id, ast_node];

fn map_crate(c: &crate) -> map {
    // FIXME: This is using an adapter to convert the smallintmap
    // interface to the hashmap interface. It would be better to just
    // convert everything to use the smallintmap.
    let map = new_smallintmap_int_adapter[ast_node]();

    let v_map =
        @{visit_item: bind map_item(map, _, _, _),
          visit_native_item: bind map_native_item(map, _, _, _),
          visit_expr: bind map_expr(map, _, _, _)
             with *visit::default_visitor[()]()};
    visit::visit_crate(c, (), visit::mk_vt(v_map));
    ret map;
}

fn map_item(map: &map, i: &@item, e: &(), v: &vt[()]) {
    map.insert(i.id, node_item(i));
    alt i.node {
      item_obj(_, _, ctor_id) { map.insert(ctor_id, node_obj_ctor(i)); }
      _ { }
    }
    visit::visit_item(i, e, v);
}

fn map_native_item(map: &map, i: &@native_item, e: &(), v: &vt[()]) {
    map.insert(i.id, node_native_item(i));
    visit::visit_native_item(i, e, v);
}

fn map_expr(map: &map, ex: &@expr, e: &(), v: &vt[()]) {
    map.insert(ex.id, node_expr(ex));
    visit::visit_expr(ex, e, v);
}

fn new_smallintmap_int_adapter[@V]() -> std::map::hashmap[int, V] {
    let key_idx = fn (key: &int) -> uint { key as uint };
    let idx_key = fn (idx: &uint) -> int { idx as int };
    ret new_smallintmap_adapter(key_idx, idx_key);
}

// This creates an object with the hashmap interface backed
// by the smallintmap type, because I don't want to go through
// the entire codebase adapting all the callsites to the different
// interface.
// FIXME: hashmap and smallintmap should support the same interface.
fn new_smallintmap_adapter[@K,
                           @V](key_idx: fn(&K) -> uint ,
                               idx_key: fn(&uint) -> K ) ->
   std::map::hashmap[K, V] {

    obj adapter[@K,
                @V](map: smallintmap::smallintmap[V],
                    key_idx: fn(&K) -> uint ,
                    idx_key: fn(&uint) -> K ) {

        fn size() -> uint { fail }

        fn insert(key: &K, value: &V) -> bool {
            let exists = smallintmap::contains_key(map, key_idx(key));
            smallintmap::insert(map, key_idx(key), value);
            ret !exists;
        }

        fn contains_key(key: &K) -> bool {
            ret smallintmap::contains_key(map, key_idx(key));
        }

        fn get(key: &K) -> V { ret smallintmap::get(map, key_idx(key)); }

        fn find(key: &K) -> option::t[V] {
            ret smallintmap::find(map, key_idx(key));
        }

        fn remove(key: &K) -> option::t[V] { fail }

        fn rehash() { fail }

        iter items() -> @{key: K, val: V} {
            let idx = 0u;
            for item: option::t[V]  in map.v {
                alt item {
                  option::some(elt) {
                    let value = elt;
                    let key = idx_key(idx);
                    put @{key: key, val: value};
                  }
                  option::none. { }
                }
                idx += 1u;
            }
        }
        iter keys() -> K {
            for each p: @{key: K, val: V}  in self.items() { put p.key; }
        }
    }

    let map = smallintmap::mk[V]();
    ret adapter(map, key_idx, idx_key);
}

// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
<commit_msg>Add ast_map::node_span function<commit_after>import std::smallintmap;
import std::option;
import syntax::ast::*;
import syntax::visit;
import syntax::codemap;
import visit::vt;

tag ast_node {
    node_item(@item);
    node_obj_ctor(@item);
    node_native_item(@native_item);
    node_expr(@expr);
}

type map = std::map::hashmap[node_id, ast_node];

fn map_crate(c: &crate) -> map {
    // FIXME: This is using an adapter to convert the smallintmap
    // interface to the hashmap interface. It would be better to just
    // convert everything to use the smallintmap.
    let map = new_smallintmap_int_adapter[ast_node]();

    let v_map =
        @{visit_item: bind map_item(map, _, _, _),
          visit_native_item: bind map_native_item(map, _, _, _),
          visit_expr: bind map_expr(map, _, _, _)
             with *visit::default_visitor[()]()};
    visit::visit_crate(c, (), visit::mk_vt(v_map));
    ret map;
}

fn map_item(map: &map, i: &@item, e: &(), v: &vt[()]) {
    map.insert(i.id, node_item(i));
    alt i.node {
      item_obj(_, _, ctor_id) { map.insert(ctor_id, node_obj_ctor(i)); }
      _ { }
    }
    visit::visit_item(i, e, v);
}

fn map_native_item(map: &map, i: &@native_item, e: &(), v: &vt[()]) {
    map.insert(i.id, node_native_item(i));
    visit::visit_native_item(i, e, v);
}

fn map_expr(map: &map, ex: &@expr, e: &(), v: &vt[()]) {
    map.insert(ex.id, node_expr(ex));
    visit::visit_expr(ex, e, v);
}

fn new_smallintmap_int_adapter[@V]() -> std::map::hashmap[int, V] {
    let key_idx = fn (key: &int) -> uint { key as uint };
    let idx_key = fn (idx: &uint) -> int { idx as int };
    ret new_smallintmap_adapter(key_idx, idx_key);
}

// This creates an object with the hashmap interface backed
// by the smallintmap type, because I don't want to go through
// the entire codebase adapting all the callsites to the different
// interface.
// FIXME: hashmap and smallintmap should support the same interface.
fn new_smallintmap_adapter[@K,
                           @V](key_idx: fn(&K) -> uint ,
                               idx_key: fn(&uint) -> K ) ->
   std::map::hashmap[K, V] {

    obj adapter[@K,
                @V](map: smallintmap::smallintmap[V],
                    key_idx: fn(&K) -> uint ,
                    idx_key: fn(&uint) -> K ) {

        fn size() -> uint { fail }

        fn insert(key: &K, value: &V) -> bool {
            let exists = smallintmap::contains_key(map, key_idx(key));
            smallintmap::insert(map, key_idx(key), value);
            ret !exists;
        }

        fn contains_key(key: &K) -> bool {
            ret smallintmap::contains_key(map, key_idx(key));
        }

        fn get(key: &K) -> V { ret smallintmap::get(map, key_idx(key)); }

        fn find(key: &K) -> option::t[V] {
            ret smallintmap::find(map, key_idx(key));
        }

        fn remove(key: &K) -> option::t[V] { fail }

        fn rehash() { fail }

        iter items() -> @{key: K, val: V} {
            let idx = 0u;
            for item: option::t[V]  in map.v {
                alt item {
                  option::some(elt) {
                    let value = elt;
                    let key = idx_key(idx);
                    put @{key: key, val: value};
                  }
                  option::none. { }
                }
                idx += 1u;
            }
        }
        iter keys() -> K {
            for each p: @{key: K, val: V}  in self.items() { put p.key; }
        }
    }

    let map = smallintmap::mk[V]();
    ret adapter(map, key_idx, idx_key);
}

fn node_span(node: &ast_node) -> codemap::span {
    alt node {
      node_item(item) { item.span }
      node_obj_ctor(item) { item.span }
      node_native_item(nitem) { nitem.span }
      node_expr(expr) { expr.span }
    }
}

#[cfg(test)]
mod test {
    #[test]
    fn test_node_span_item() {
        let expected: codemap::span = {lo: 20u, hi: 30u};
        let node = node_item(@{ident: "test",
                               attrs: ~[],
                               id: 0,
                               node: item_mod({view_items: ~[],
                                               items: ~[]}),
                               span: expected});
        assert node_span(node) == expected;
    }

    #[test]
    fn test_node_span_obj_ctor() {
        let expected: codemap::span = {lo: 20u, hi: 30u};
        let node = node_obj_ctor(@{ident: "test",
                                   attrs: ~[],
                                   id: 0,
                                   node: item_mod({view_items: ~[],
                                                   items: ~[]}),
                                   span: expected});
        assert node_span(node) == expected;
    }

    #[test]
    fn test_node_span_native_item() {
        let expected: codemap::span = {lo: 20u, hi: 30u};
        let node = node_native_item(@{ident: "test",
                                      attrs: ~[],
                                      node: native_item_ty,
                                      id: 0,
                                      span: expected});
        assert node_span(node) == expected;
    }

    #[test]
    fn test_node_span_expr() {
        let expected: codemap::span = {lo: 20u, hi: 30u};
        let node = node_expr(@{id: 0,
                               node: expr_break,
                               span: expected});
        assert node_span(node) == expected;
    }
}

// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
<|endoftext|>


<commit_before>import run::spawn_process;
import io::writer_util;
import libc::{c_int, pid_t};

import pipes::chan;

export run;

#[cfg(target_os = "win32")]
fn target_env(lib_path: ~str, prog: ~str) -> ~[(~str,~str)] {

    let mut env = os::env();

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

    env = do vec::map(env) |pair| {
        let (k,v) = pair;
        if k == ~"PATH" { (~"PATH", v + ~";" + lib_path + ~";" + aux_path) }
        else { (k,v) }
    };
    if str::ends_with(prog, ~"rustc.exe") {
        vec::push(env, (~"RUST_THREADS", ~"1"));
    }
    return env;
}

#[cfg(target_os = "linux")]
#[cfg(target_os = "macos")]
#[cfg(target_os = "freebsd")]
fn target_env(_lib_path: ~str, _prog: ~str) -> ~[(~str,~str)] {
    ~[]
}

// FIXME (#2659): This code is duplicated in core::run::program_output
fn run(lib_path: ~str,
       prog: ~str,
       args: ~[~str],
       env: ~[(~str, ~str)],
       input: option<~str>) -> {status: int, out: ~str, err: ~str} {

    let pipe_in = os::pipe();
    let pipe_out = os::pipe();
    let pipe_err = os::pipe();
    let pid = spawn_process(prog, args,
                            some(env + target_env(lib_path, prog)),
                            none, pipe_in.in, pipe_out.out, pipe_err.out);

    os::close(pipe_in.in);
    os::close(pipe_out.out);
    os::close(pipe_err.out);
    if pid == -1i32 {
        os::close(pipe_in.out);
        os::close(pipe_out.in);
        os::close(pipe_err.in);
        fail;
    }

    writeclose(pipe_in.out, input);
    let p = pipes::port_set();
    let ch = p.chan();
    do task::spawn_sched(task::single_threaded) {
        let errput = readclose(pipe_err.in);
        ch.send((2, errput));
    }
    let ch = p.chan();
    do task::spawn_sched(task::single_threaded) {
        let output = readclose(pipe_out.in);
        ch.send((1, output));
    }
    let status = run::waitpid(pid);
    let mut errs = ~"";
    let mut outs = ~"";
    let mut count = 2;
    while count > 0 {
        match p.recv() {
          (1, s) => {
            outs = s;
          }
          (2, s) => {
            errs = s;
          }
          _ => { fail }
        };
        count -= 1;
    };
    return {status: status, out: outs, err: errs};
}

fn writeclose(fd: c_int, s: option<~str>) {
    if option::is_some(s) {
        let writer = io::fd_writer(fd, false);
        writer.write_str(option::get(s));
    }

    os::close(fd);
}

fn readclose(fd: c_int) -> ~str {
    // Copied from run::program_output
    let file = os::fdopen(fd);
    let reader = io::FILE_reader(file, false);
    let mut buf = ~"";
    while !reader.eof() {
        let bytes = reader.read_bytes(4096u);
        buf += str::from_bytes(bytes);
    }
    os::fclose(file);
    return buf;
}
<commit_msg>Fix compiletest breakage<commit_after>import run::spawn_process;
import io::writer_util;
import libc::{c_int, pid_t};

import pipes::chan;

export run;

#[cfg(target_os = "win32")]
fn target_env(lib_path: ~str, prog: ~str) -> ~[(~str,~str)] {

    let mut env = os::env();

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

    env = do vec::map(env) |pair| {
        let (k,v) = pair;
        if k == ~"PATH" { (~"PATH", v + ~";" + lib_path + ~";" + aux_path) }
        else { (k,v) }
    };
    if str::ends_with(prog, ~"rustc.exe") {
        vec::push(env, (~"RUST_THREADS", ~"1"));
    }
    return env;
}

#[cfg(target_os = "linux")]
#[cfg(target_os = "macos")]
#[cfg(target_os = "freebsd")]
fn target_env(_lib_path: ~str, _prog: ~str) -> ~[(~str,~str)] {
    ~[]
}

// FIXME (#2659): This code is duplicated in core::run::program_output
fn run(lib_path: ~str,
       prog: ~str,
       args: ~[~str],
       env: ~[(~str, ~str)],
       input: option<~str>) -> {status: int, out: ~str, err: ~str} {

    let pipe_in = os::pipe();
    let pipe_out = os::pipe();
    let pipe_err = os::pipe();
    let pid = spawn_process(prog, args,
                            &some(env + target_env(lib_path, prog)),
                            &none, pipe_in.in, pipe_out.out, pipe_err.out);

    os::close(pipe_in.in);
    os::close(pipe_out.out);
    os::close(pipe_err.out);
    if pid == -1i32 {
        os::close(pipe_in.out);
        os::close(pipe_out.in);
        os::close(pipe_err.in);
        fail;
    }

    writeclose(pipe_in.out, input);
    let p = pipes::port_set();
    let ch = p.chan();
    do task::spawn_sched(task::single_threaded) {
        let errput = readclose(pipe_err.in);
        ch.send((2, errput));
    }
    let ch = p.chan();
    do task::spawn_sched(task::single_threaded) {
        let output = readclose(pipe_out.in);
        ch.send((1, output));
    }
    let status = run::waitpid(pid);
    let mut errs = ~"";
    let mut outs = ~"";
    let mut count = 2;
    while count > 0 {
        match p.recv() {
          (1, s) => {
            outs = s;
          }
          (2, s) => {
            errs = s;
          }
          _ => { fail }
        };
        count -= 1;
    };
    return {status: status, out: outs, err: errs};
}

fn writeclose(fd: c_int, s: option<~str>) {
    if option::is_some(s) {
        let writer = io::fd_writer(fd, false);
        writer.write_str(option::get(s));
    }

    os::close(fd);
}

fn readclose(fd: c_int) -> ~str {
    // Copied from run::program_output
    let file = os::fdopen(fd);
    let reader = io::FILE_reader(file, false);
    let mut buf = ~"";
    while !reader.eof() {
        let bytes = reader.read_bytes(4096u);
        buf += str::from_bytes(bytes);
    }
    os::fclose(file);
    return buf;
}
<|endoftext|>


<commit_before><commit_msg>don't assert when maxImageCount cap is 0<commit_after><|endoftext|>


<commit_before><commit_msg>Add an option on fence creation to select signalled or not, use it to avoid conditionally waiting on the submission-completed fence<commit_after><|endoftext|>


<commit_before><commit_msg>Clear the frame to green for Vulkan to aid debugging, and select VK_PRESENT_MODE_IMMEDIATE_KHR in preference<commit_after><|endoftext|>


<commit_before><commit_msg>Review the sizes specified when creating the descriptor set pool<commit_after><|endoftext|>


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

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

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

use syntax::ast_util::*;
use syntax::attr;
use syntax::codemap::{dummy_sp, span, ExpandedFrom, CallInfo, NameAndSpan};
use syntax::codemap;
use syntax::ext::base::{mk_ctxt, ext_ctxt};
use syntax::fold;
use syntax::print::pprust;
use syntax::{ast, ast_util};

type node_id_gen = @fn() -> ast::node_id;

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

struct TestCtxt {
    sess: session::Session,
    crate: @ast::crate,
    path: ~[ast::ident],
    ext_cx: @ext_ctxt,
    testfns: ~[Test]
}

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

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

fn generate_test_harness(sess: session::Session,
                         crate: @ast::crate)
                      -> @ast::crate {
    let cx: @mut TestCtxt = @mut TestCtxt {
        sess: sess,
        crate: crate,
        ext_cx: mk_ctxt(sess.parse_sess, copy sess.opts.cfg),
        path: ~[],
        testfns: ~[]
    };

    cx.ext_cx.bt_push(ExpandedFrom(CallInfo {
        call_site: dummy_sp(),
        callee: NameAndSpan {
            name: ~"test",
            span: None
        }
    }));

    let precursor = @fold::AstFoldFns {
        fold_crate: fold::wrap(|a,b| fold_crate(cx, a, b) ),
        fold_item: |a,b| fold_item(cx, a, b),
        fold_mod: |a,b| fold_mod(cx, a, b),.. *fold::default_ast_fold()};

    let fold = fold::make_fold(precursor);
    let res = @fold.fold_crate(&*crate);
    cx.ext_cx.bt_pop();
    return res;
}

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

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

    fn nomain(cx: @mut TestCtxt, item: @ast::item) -> @ast::item {
        if !*cx.sess.building_library {
            @ast::item{attrs: item.attrs.filtered(|attr| {
                               *attr::get_attr_name(attr) != ~"main"
                           }),.. copy *item}
        } else { item }
    }

    let mod_nomain = ast::_mod {
        view_items: /*bad*/copy m.view_items,
        items: vec::map(m.items, |i| nomain(cx, *i)),
    };

    fold::noop_fold_mod(&mod_nomain, fld)
}

fn fold_crate(cx: @mut TestCtxt,
              c: &ast::crate_,
              fld: @fold::ast_fold)
           -> ast::crate_ {
    let folded = fold::noop_fold_crate(c, fld);

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

fn fold_item(cx: @mut TestCtxt, i: @ast::item, fld: @fold::ast_fold)
          -> Option<@ast::item> {
    cx.path.push(i.ident);
    debug!("current path: %s",
           ast_util::path_name_i(copy cx.path, cx.sess.parse_sess.interner));

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

    let res = fold::noop_fold_item(i, fld);
    cx.path.pop();
    return res;
}

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

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

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

fn is_bench_fn(i: @ast::item) -> bool {
    let has_bench_attr =
        vec::len(attr::find_attrs_by_name(i.attrs, ~"bench")) > 0u;

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

    return has_bench_attr && has_test_signature(i);
}

fn is_ignored(cx: @mut TestCtxt, i: @ast::item) -> bool {
    let ignoreattrs = attr::find_attrs_by_name(i.attrs, "ignore");
    let ignoreitems = attr::attr_metas(ignoreattrs);
    return if !ignoreitems.is_empty() {
        let cfg_metas =
            vec::concat(
                vec::filter_map(ignoreitems,
                                |i| attr::get_meta_item_list(i)));
        config::metas_in_cfg(/*bad*/copy cx.crate.node.config, cfg_metas)
    } else {
        false
    }
}

fn should_fail(i: @ast::item) -> bool {
    vec::len(attr::find_attrs_by_name(i.attrs, ~"should_fail")) > 0u
}

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

/*

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

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

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

*/

fn mk_std(cx: &TestCtxt) -> @ast::view_item {
    let vers = ast::lit_str(@~"0.7-pre");
    let vers = nospan(vers);
    let mi = ast::meta_name_value(@~"vers", vers);
    let mi = nospan(mi);
    let id_std = cx.sess.ident_of(~"std");
    let vi = if is_std(cx) {
        ast::view_item_use(
            ~[@nospan(ast::view_path_simple(id_std,
                                            path_node(~[id_std]),
                                            cx.sess.next_node_id()))])
    } else {
        ast::view_item_extern_mod(id_std, ~[@mi],
                           cx.sess.next_node_id())
    };
    let vi = ast::view_item {
        node: vi,
        attrs: ~[],
        vis: ast::public,
        span: dummy_sp()
    };
    return @vi;
}

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

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

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

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

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

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

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

    debug!("Synthetic test module:\n%s\n",
           pprust::item_to_str(@copy item, cx.sess.intr()));

    return @item;
}

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

fn path_node(ids: ~[ast::ident]) -> @ast::Path {
    @ast::Path { span: dummy_sp(),
                global: false,
                idents: ids,
                rp: None,
                types: ~[] }
}

fn path_node_global(ids: ~[ast::ident]) -> @ast::Path {
    @ast::Path { span: dummy_sp(),
                 global: true,
                 idents: ids,
                 rp: None,
                 types: ~[] }
}

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

    let ext_cx = cx.ext_cx;

    // The vector of test_descs for this crate
    let test_descs = mk_test_descs(cx);

    (quote_item!(
        pub static tests : &'static [self::std::test::TestDescAndFn] =
            $test_descs
        ;
    )).get()
}

fn is_std(cx: &TestCtxt) -> bool {
    let is_std = {
        let items = attr::find_linkage_metas(cx.crate.node.attrs);
        match attr::last_meta_item_value_str_by_name(items, ~"name") {
          Some(@~"std") => true,
          _ => false
        }
    };
    return is_std;
}

fn mk_test_descs(cx: &TestCtxt) -> @ast::expr {
    debug!("building test vector from %u tests", cx.testfns.len());
    let mut descs = ~[];
    for cx.testfns.each |test| {
        descs.push(mk_test_desc_and_fn_rec(cx, test));
    }

    let sess = cx.sess;
    let inner_expr = @ast::expr {
        id: sess.next_node_id(),
        callee_id: sess.next_node_id(),
        node: ast::expr_vec(descs, ast::m_imm),
        span: dummy_sp(),
    };

    @ast::expr {
        id: sess.next_node_id(),
        callee_id: sess.next_node_id(),
        node: ast::expr_vstore(inner_expr, ast::expr_vstore_slice),
        span: dummy_sp(),
    }
}

fn mk_test_desc_and_fn_rec(cx: &TestCtxt, test: &Test) -> @ast::expr {
    let span = test.span;
    let path = /*bad*/copy test.path;

    let ext_cx = cx.ext_cx;

    debug!("encoding %s", ast_util::path_name_i(path,
                                                cx.sess.parse_sess.interner));

    let name_lit: ast::lit =
        nospan(ast::lit_str(@ast_util::path_name_i(
            path,
            cx.sess.parse_sess.interner)));

    let name_expr = @ast::expr {
          id: cx.sess.next_node_id(),
          callee_id: cx.sess.next_node_id(),
          node: ast::expr_lit(@name_lit),
          span: span
    };

    let fn_path = path_node_global(path);

    let fn_expr = @ast::expr {
        id: cx.sess.next_node_id(),
        callee_id: cx.sess.next_node_id(),
        node: ast::expr_path(fn_path),
        span: span,
    };

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

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

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

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

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

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

use syntax::ast_util::*;
use syntax::attr;
use syntax::codemap::{dummy_sp, span, ExpandedFrom, CallInfo, NameAndSpan};
use syntax::codemap;
use syntax::ext::base::{mk_ctxt, ext_ctxt};
use syntax::fold;
use syntax::print::pprust;
use syntax::{ast, ast_util};

type node_id_gen = @fn() -> ast::node_id;

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

struct TestCtxt {
    sess: session::Session,
    crate: @ast::crate,
    path: ~[ast::ident],
    ext_cx: @ext_ctxt,
    testfns: ~[Test]
}

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

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

fn generate_test_harness(sess: session::Session,
                         crate: @ast::crate)
                      -> @ast::crate {
    let cx: @mut TestCtxt = @mut TestCtxt {
        sess: sess,
        crate: crate,
        ext_cx: mk_ctxt(sess.parse_sess, copy sess.opts.cfg),
        path: ~[],
        testfns: ~[]
    };

    cx.ext_cx.bt_push(ExpandedFrom(CallInfo {
        call_site: dummy_sp(),
        callee: NameAndSpan {
            name: ~"test",
            span: None
        }
    }));

    let precursor = @fold::AstFoldFns {
        fold_crate: fold::wrap(|a,b| fold_crate(cx, a, b) ),
        fold_item: |a,b| fold_item(cx, a, b),
        fold_mod: |a,b| fold_mod(cx, a, b),.. *fold::default_ast_fold()};

    let fold = fold::make_fold(precursor);
    let res = @fold.fold_crate(&*crate);
    cx.ext_cx.bt_pop();
    return res;
}

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

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

    fn nomain(cx: @mut TestCtxt, item: @ast::item) -> @ast::item {
        if !*cx.sess.building_library {
            @ast::item{attrs: item.attrs.filtered(|attr| {
                               *attr::get_attr_name(attr) != ~"main"
                           }),.. copy *item}
        } else { item }
    }

    let mod_nomain = ast::_mod {
        view_items: /*bad*/copy m.view_items,
        items: vec::map(m.items, |i| nomain(cx, *i)),
    };

    fold::noop_fold_mod(&mod_nomain, fld)
}

fn fold_crate(cx: @mut TestCtxt,
              c: &ast::crate_,
              fld: @fold::ast_fold)
           -> ast::crate_ {
    let folded = fold::noop_fold_crate(c, fld);

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

fn fold_item(cx: @mut TestCtxt, i: @ast::item, fld: @fold::ast_fold)
          -> Option<@ast::item> {
    cx.path.push(i.ident);
    debug!("current path: %s",
           ast_util::path_name_i(copy cx.path, cx.sess.parse_sess.interner));

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

    let res = fold::noop_fold_item(i, fld);
    cx.path.pop();
    return res;
}

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

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

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

fn is_bench_fn(i: @ast::item) -> bool {
    let has_bench_attr =
        vec::len(attr::find_attrs_by_name(i.attrs, ~"bench")) > 0u;

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

    return has_bench_attr && has_test_signature(i);
}

fn is_ignored(cx: @mut TestCtxt, i: @ast::item) -> bool {
    let ignoreattrs = attr::find_attrs_by_name(i.attrs, "ignore");
    let ignoreitems = attr::attr_metas(ignoreattrs);
    return if !ignoreitems.is_empty() {
        let cfg_metas =
            vec::concat(
                vec::filter_map(ignoreitems,
                                |i| attr::get_meta_item_list(i)));
        config::metas_in_cfg(/*bad*/copy cx.crate.node.config, cfg_metas)
    } else {
        false
    }
}

fn should_fail(i: @ast::item) -> bool {
    vec::len(attr::find_attrs_by_name(i.attrs, ~"should_fail")) > 0u
}

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

/*

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

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

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

*/

fn mk_std(cx: &TestCtxt) -> @ast::view_item {
    let vers = ast::lit_str(@~"0.7-pre");
    let vers = nospan(vers);
    let mi = ast::meta_name_value(@~"vers", vers);
    let mi = nospan(mi);
    let id_std = cx.sess.ident_of(~"std");
    let vi = if is_std(cx) {
        ast::view_item_use(
            ~[@nospan(ast::view_path_simple(id_std,
                                            path_node(~[id_std]),
                                            cx.sess.next_node_id()))])
    } else {
        ast::view_item_extern_mod(id_std, ~[@mi],
                           cx.sess.next_node_id())
    };
    let vi = ast::view_item {
        node: vi,
        attrs: ~[],
        vis: ast::public,
        span: dummy_sp()
    };
    return @vi;
}

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

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

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

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

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

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

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

    debug!("Synthetic test module:\n%s\n",
           pprust::item_to_str(@copy item, cx.sess.intr()));

    return @item;
}

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

fn path_node(ids: ~[ast::ident]) -> @ast::Path {
    @ast::Path { span: dummy_sp(),
                global: false,
                idents: ids,
                rp: None,
                types: ~[] }
}

fn path_node_global(ids: ~[ast::ident]) -> @ast::Path {
    @ast::Path { span: dummy_sp(),
                 global: true,
                 idents: ids,
                 rp: None,
                 types: ~[] }
}

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

    let ext_cx = cx.ext_cx;

    // The vector of test_descs for this crate
    let test_descs = mk_test_descs(cx);

    (quote_item!(
        pub static tests : &'static [self::std::test::TestDescAndFn] =
            $test_descs
        ;
    )).get()
}

fn is_std(cx: &TestCtxt) -> bool {
    let is_std = {
        let items = attr::find_linkage_metas(cx.crate.node.attrs);
        match attr::last_meta_item_value_str_by_name(items, ~"name") {
          Some(@~"std") => true,
          _ => false
        }
    };
    return is_std;
}

fn mk_test_descs(cx: &TestCtxt) -> @ast::expr {
    debug!("building test vector from %u tests", cx.testfns.len());
    let mut descs = ~[];
    for cx.testfns.each |test| {
        descs.push(mk_test_desc_and_fn_rec(cx, test));
    }

    let sess = cx.sess;
    let inner_expr = @ast::expr {
        id: sess.next_node_id(),
        callee_id: sess.next_node_id(),
        node: ast::expr_vec(descs, ast::m_imm),
        span: dummy_sp(),
    };

    @ast::expr {
        id: sess.next_node_id(),
        callee_id: sess.next_node_id(),
        node: ast::expr_vstore(inner_expr, ast::expr_vstore_slice),
        span: dummy_sp(),
    }
}

fn mk_test_desc_and_fn_rec(cx: &TestCtxt, test: &Test) -> @ast::expr {
    let span = test.span;
    let path = /*bad*/copy test.path;

    let ext_cx = cx.ext_cx;

    debug!("encoding %s", ast_util::path_name_i(path,
                                                cx.sess.parse_sess.interner));

    let name_lit: ast::lit =
        nospan(ast::lit_str(@ast_util::path_name_i(
            path,
            cx.sess.parse_sess.interner)));

    let name_expr = @ast::expr {
          id: cx.sess.next_node_id(),
          callee_id: cx.sess.next_node_id(),
          node: ast::expr_lit(@name_lit),
          span: span
    };

    let fn_path = path_node_global(path);

    let fn_expr = @ast::expr {
        id: cx.sess.next_node_id(),
        callee_id: cx.sess.next_node_id(),
        node: ast::expr_path(fn_path),
        span: span,
    };

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

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

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

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


<commit_before><commit_msg>Massive x86_64 platform_init cleanup<commit_after><|endoftext|>


<commit_before>use redox::*;

use super::{XdrOps, XdrResult};

pub struct MemOps {
    pos: usize,
    buffer: Vec<u8>,
}

impl XdrOps for MemOps {
    fn get_long(&mut self) -> XdrResult<usize> {
        Ok(0)
    }

    fn put_long(&mut self, l: usize) -> XdrResult<()> {
        Ok(())
    }

    fn get_i32(&mut self) -> XdrResult<i32> {
        Ok(0)
    }

    fn put_i32(&mut self, i: i32) -> XdrResult<()> {
        Ok(())
    }

    fn get_bytes(&mut self, bytes: &mut [u8]) -> XdrResult<()> {
        Ok(())
    }

    fn put_bytes(&mut self, bytes: &[u8]) -> XdrResult<()> {
        Ok(())
    }

    fn get_pos(&self) -> usize {
        self.pos
    }

    fn set_pos(&mut self, offset: usize) -> XdrResult<()> {
        Ok(())
    }

    fn destroy(&mut self) {
    }
}
<commit_msg>MemOps::get_long<commit_after>use core::mem;

use redox::*;

use super::{XdrOps, XdrError, XdrResult};

pub struct MemOps {
    pos: usize,
    buffer: Vec<u8>,
}

impl XdrOps for MemOps {
    fn get_long(&mut self) -> XdrResult<usize> {
        if self.buffer.len()-self.pos < 4 {
            Err(XdrError)
        } else {
            let d: &usize = unsafe { mem::transmute(&self.buffer[self.pos]) };
            self.pos += 4;
            Ok(*d)
        }
    }

    fn put_long(&mut self, l: usize) -> XdrResult<()> {
        Ok(())
    }

    fn get_i32(&mut self) -> XdrResult<i32> {
        Ok(0)
    }

    fn put_i32(&mut self, i: i32) -> XdrResult<()> {
        Ok(())
    }

    fn get_bytes(&mut self, bytes: &mut [u8]) -> XdrResult<()> {
        Ok(())
    }

    fn put_bytes(&mut self, bytes: &[u8]) -> XdrResult<()> {
        Ok(())
    }

    fn get_pos(&self) -> usize {
        self.pos
    }

    fn set_pos(&mut self, offset: usize) -> XdrResult<()> {
        Ok(())
    }

    fn destroy(&mut self) {
    }
}
<|endoftext|>


<commit_before><commit_msg>euler 3<commit_after>// The prime factors of 13195 are 5, 7, 13 and 29.
// What is the largest prime factor of the number 600851475143 ?

fn factors(number: u64) -> Vec<u64> {
	let mut n = 1;
	let mut factors = Vec::new();

	while n * n <= number {
		if number % n == 0 { factors.push(n) }
		n += 1;
	}

	factors.push(number);

	factors
}

fn is_prime(number: u64) -> bool {
	factors(number).len() == 2
}

fn main() {
	println!("{}", factors(600851475143).iter().filter(|&f| is_prime(*f)).last().unwrap());
}<|endoftext|>


<commit_before>extern crate ws;
extern crate clap;
extern crate serde;
extern crate serde_json;

use serde_json::Value;
use serde_json::value::Map;

use clap::{App, Arg};

struct BenchHandler {
    ws: ws::Sender,
    count: u32
}

impl ws::Handler for BenchHandler {
    fn on_message(&mut self, msg: ws::Message) -> ws::Result<()> {
        if let Some((Some(msg_type), payload)) = msg.into_text().ok()
            .map(|v| v.as_str().to_owned())
            .and_then(|body: String| serde_json::from_str(body.as_str()).ok())
            .and_then(|j: Value| j.as_object().map(move |obj: &Map<String, Value>| {
                let t = obj.get("type").and_then(|t| t.as_str()).map(|s| s.to_owned());
                let p: Value = obj.get("payload").unwrap_or(&Value::Null).clone();
                (t, p)
            })) {
                match msg_type.as_ref() {
                    "echo" => {
                        try!(self.ws.send(format!("{}", payload)));
                    },
                    "broadcast" => {
                        try!(self.ws.broadcast(format!("{}", payload)));
                        try!(self.ws.send(format!("{{\"type\": \"broadcastResult\", \"listenCount\": {}, \"payload\": {}}}", self.count, payload)))
                    },
                    _ => {}
                };
            };
        Ok(())
    }

    fn on_open(&mut self, _: ws::Handshake) -> ws::Result<()> {
        self.count += 1;
        println!("Connection Open! {}", self.count);
        Ok(())
    }

    fn on_close(&mut self,_: ws::CloseCode, _: &str) {
        self.count -= 1;
        println!("Connection Closed! {}", self.count);
    }
}

fn main() {
    let matches = App::new("rust-ws-server")
        .version("1.0")
        .arg(Arg::with_name("address")
                    .short("a")
                    .long("address")
                    .required(true)
                    .takes_value(true)
                    .default_value("127.0.0.1"))
        .arg(Arg::with_name("port")
            .short("p")
            .long("port")
            .required(true)
            .takes_value(true)
            .default_value("3000"))
        .get_matches();
    if let (Some(address), Some(port)) = (matches.value_of("address"), matches.value_of("port")) {
        if let Err(error) = ws::listen(format!("{}:{}", address, port).as_str(), |out| {
            BenchHandler { ws: out, count: 0 }
        }) {
            println!("Failed to create WebSocket due to {:?}", error);
        }
    } else {
        println!("{}", matches.usage());
    }
}
<commit_msg>Increase max connections and change broadcast and echo output to be JSON.<commit_after>extern crate ws;
extern crate clap;
extern crate serde;
extern crate serde_json;

use serde_json::Value;
use serde_json::value::Map;

use clap::{App, Arg};

struct BenchHandler {
    ws: ws::Sender,
    count: u32
}

impl ws::Handler for BenchHandler {
    fn on_message(&mut self, msg: ws::Message) -> ws::Result<()> {
        if let Ok(body) = msg.into_text() {
            if let Some((Some(msg_type), payload)) = serde_json::from_str(body.as_str()).ok()
                .and_then(|j: Value| j.as_object().map(move |obj: &Map<String, Value>| {
                    let t = obj.get("type").and_then(|t| t.as_str()).map(|s| s.to_owned());
                    let p: Value = obj.get("payload").unwrap_or(&Value::Null).clone();
                    (t, p)
                })) {
                match msg_type.as_ref() {
                    "echo" => {
                        try!(self.ws.send(body.as_str()));
                    },
                    "broadcast" => {
                        try!(self.ws.broadcast(body.as_str()));
                        try!(self.ws.send(format!("{{\"type\": \"broadcastResult\", \"listenCount\": {}, \"payload\": {}}}", self.count, payload)))
                    },
                    _ => {}
                };
            };
        }
        Ok(())
    }

    fn on_open(&mut self, _: ws::Handshake) -> ws::Result<()> {
        self.count += 1;
        println!("Connection Open! {}", self.count);
        Ok(())
    }

    fn on_close(&mut self,_: ws::CloseCode, _: &str) {
        self.count -= 1;
        println!("Connection Closed! {}", self.count);
    }
}

fn main() {
    let matches = App::new("rust-ws-server")
        .version("1.0")
        .arg(Arg::with_name("address")
                    .short("a")
                    .long("address")
                    .required(true)
                    .takes_value(true)
                    .default_value("127.0.0.1"))
        .arg(Arg::with_name("port")
            .short("p")
            .long("port")
            .required(true)
            .takes_value(true)
            .default_value("3000"))
        .get_matches();
    if let (Some(address), Some(port)) = (matches.value_of("address"), matches.value_of("port")) {
        ws::Builder::new().with_settings(ws::Settings {
            max_connections: 500_000,
            ..ws::Settings::default()
        }).build(|out| {
            BenchHandler { ws: out, count: 0 }
        }).unwrap().listen(format!("{}:{}", address, port).as_str()).unwrap();
    } else {
        println!("{}", matches.usage());
    }
}
<|endoftext|>


<commit_before>// Regression test for issue #2783

fn foo(f: fn()) { f() }

fn main() {
    "" || 42; //! ERROR binary operation || cannot be applied to type `str`
    foo || {}; //! ERROR binary operation || cannot be applied to type `extern fn(fn())`
    //!^ NOTE did you forget the 'do' keyword for the call?
}
<commit_msg>Update compile-fail/missing-do for new error-comment syntax<commit_after>// Regression test for issue #2783

fn foo(f: fn()) { f() }

fn main() {
    "" || 42; //~ ERROR binary operation || cannot be applied to type `str`
    foo || {}; //~ ERROR binary operation || cannot be applied to type `extern fn(fn())`
    //~^ NOTE did you forget the 'do' keyword for the call?
}
<|endoftext|>


<commit_before><commit_msg>Add solution to problem 39<commit_after>#[macro_use] extern crate libeuler;

/// If p is the perimeter of a right angle triangle with integral length sides, {a,b,c}, there are
/// exactly three solutions for p = 120.
///
/// {20,48,52}, {24,45,51}, {30,40,50}
///
/// For which value of p ≤ 1000, is the number of solutions maximised?
fn main() {
    solutions! {
        sol naive {
            let mut max = 0;
            let mut maxval = 0;
            for i in 0..1000 {
                let triangles = get_triangles(i);
                if triangles.len() > max {
                    max = triangles.len();
                    maxval = i;
                }
            }

            maxval
        }
    }
}

#[derive(Debug)]
struct Triangle {
    one: i64,
    two: i64,
    three: i64
}

fn get_triangles(p: i64) -> Vec<Triangle> {
    let mut retval = Vec::new();

    for one in 1..p {
        for two in one..p {
            let three = p - one - two;
            if three as f64 == (one.pow(2) as f64 + two.pow(2) as f64).sqrt() {
                retval.push(Triangle {
                    one: one,
                    two: two,
                    three: three
                });
            }
        }
    }

    retval
}
<|endoftext|>


<commit_before><commit_msg>Format code.<commit_after><|endoftext|>


<commit_before><commit_msg>Start playing with rust<commit_after>fn main() {
  println!("Hello world!");
}
<|endoftext|>


<commit_before>use std::num::ParseIntError;
use std::result;

// Define a generic alias for a `Result` with the error type `ParseIntError`.
type AliasedResult<T> = result::Result<T, ParseIntError>;

// Use the above alias to refer to our specific `Result` type.
fn double_number(number_str: &str) -> AliasedResult<i32> {
    number_str.parse::<i32>().map(|n| 2 * n)
}

// Here, the alias again allows us to save some space.
fn print(result: AliasedResult<i32>) {
    match result {
        Ok(n)  => println!("n is {}", n),
        Err(e) => println!("Error: {}", e),
    }
}

fn main() {
    print(double_number("10"));
    print(double_number("t"));
}
<commit_msg>Removed unneeded usage of std::result.<commit_after>use std::num::ParseIntError;

// Define a generic alias for a `Result` with the error type `ParseIntError`.
type AliasedResult<T> = Result<T, ParseIntError>;

// Use the above alias to refer to our specific `Result` type.
fn double_number(number_str: &str) -> AliasedResult<i32> {
    number_str.parse::<i32>().map(|n| 2 * n)
}

// Here, the alias again allows us to save some space.
fn print(result: AliasedResult<i32>) {
    match result {
        Ok(n)  => println!("n is {}", n),
        Err(e) => println!("Error: {}", e),
    }
}

fn main() {
    print(double_number("10"));
    print(double_number("t"));
}
<|endoftext|>


<commit_before><commit_msg>map or<commit_after><|endoftext|>


<commit_before><commit_msg>Add a REPL example<commit_after>extern crate hlua;

use hlua::AnyLuaValue;

use std::io::prelude::*;
use std::io::{stdin, stdout};

fn main() {
    let mut lua = hlua::Lua::new();
    lua.openlibs();

    let stdin = stdin();
    loop {
        print!("> ");
        stdout().flush().unwrap();

        let mut line = String::new();
        stdin.read_line(&mut line).unwrap();

        match lua.execute::<AnyLuaValue>(&line) {
            Ok(value) => println!("{:?}", value),
            Err(e) => println!("error: {:?}", e),
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Solve Area of a Circle in rust<commit_after>use std::io;

fn main() {
    let mut input_n = String::new();

    if let Err(_e) = io::stdin().read_line(&mut input_n){}

    let n: f64 = input_n.trim().parse().unwrap();

    println!("A={:.4}", n * n * 3.14159);
}
<|endoftext|>


<commit_before><commit_msg>[cli] Fix compilation error.<commit_after>pub mod wallet;
<|endoftext|>


<commit_before><commit_msg>Fix failing build on travis-ci<commit_after><|endoftext|>


<commit_before>pub struct Point {
    x: f32,
    y: f32,
    z: f32,
}

pub struct Triangle {
    p1: Point,
    p2: Point,
    p3: Point,
}
<commit_msg>Added Points.<commit_after>pub struct Point {
    x: f32,
    y: f32,
    z: f32,
}

impl Point {
    pub fn make_2d(&self) -> FlatPoint {
        FlatPoint {
            x: self.x / self.z,
            y: self.y / self.z,
        }
    }
}

pub struct FlatPoint {
    x: f32,
    y: f32,
}

pub struct Triangle {
    p1: Point,
    p2: Point,
    p3: Point,
    uv_p1: FlatPoint,
    uv_p2: FlatPoint,
    uv_p3: FlatPoint,
}
<|endoftext|>