<commit_before>#![feature(box_patterns)]

use std::error::Error;
use std::fs::File;

extern crate csv;
use csv::{Reader, StringRecords};

/// The data types supported by this database. Currently just u64 and string but others
/// will be added later, including complex types
#[derive(Debug,Clone)]
enum DataType {
    UnsignedLong,
    String
}

/// Definition of a column in a relation (data set).
#[derive(Debug,Clone)]
struct ColumnMeta {
    name: String,
    data_type: DataType,
    nullable: bool
}

/// Definition of a relation (data set) consisting of one or more columns.
#[derive(Debug,Clone)]
struct TupleType {
    columns: Vec<ColumnMeta>
}

/// Value holder for all supported data types
#[derive(Debug,Clone,PartialEq,PartialOrd)]
enum Value {
    UnsignedLong(u64),
    String(String),
    Boolean(bool)
}

/// A tuple represents one row within a relation and is implemented as a trait to allow for
/// specific implementations for different data sources
trait Tuple {
    fn get_value(&self, index: usize) -> Result<Value, Box<std::error::Error>>;
}

/// A simple tuple implementation for testing and initial prototyping
#[derive(Debug)]
struct SimpleTuple {
    values: Vec<Value>
}

impl Tuple for SimpleTuple {

    fn get_value(&self, index: usize) -> Result<Value, Box<std::error::Error>> {
        Ok(self.values[index].clone())
    }

}

#[derive(Debug)]
enum Operator {
    Eq,
    NotEq,
    Lt,
    LtEq,
    Gt,
    GtEq,
}

#[derive(Debug)]
enum Expr {
    /// index into a value within the tuple
    TupleValue(usize),
    /// literal value
    Literal(Value),
    /// binary expression e.g. "age > 21"
    BinaryExpr { left: Box<Expr>, op: Operator, right: Box<Expr> },
}

/// Query plan
#[derive(Debug)]
enum PlanNode {
    TableScan { schema: String, table: String },
    Filter { expr: Expr, input: Box<PlanNode> },
    Project { expr: Vec<Expr>, input: Box<PlanNode> }
}

fn evaluate(tuple: &Tuple, tt: &TupleType, expr: &Expr) -> Result<Value, Box<std::error::Error>> {

    match expr {
        &Expr::BinaryExpr { box ref left, ref op, box ref right } => {
            //TODO: remove use of unwrap() here
            let left_value = evaluate(tuple, tt, left).unwrap();
            let right_value = evaluate(tuple, tt, right).unwrap();
            match op {
                &Operator::Eq => Ok(Value::Boolean(left_value == right_value)),
                &Operator::NotEq => Ok(Value::Boolean(left_value != right_value)),
                &Operator::Lt => Ok(Value::Boolean(left_value < right_value)),
                &Operator::LtEq => Ok(Value::Boolean(left_value <= right_value)),
                &Operator::Gt => Ok(Value::Boolean(left_value > right_value)),
                &Operator::GtEq => Ok(Value::Boolean(left_value >= right_value)),
            }
        },
        &Expr::TupleValue(index) => tuple.get_value(index),
        &Expr::Literal(ref value) => Ok(value.clone()),
    }

}

trait TupleConsumer {
    fn process(&self, tuple: &Tuple);
}

struct DebugConsumer {
}

impl TupleConsumer for DebugConsumer {
    fn process(&self, tuple: &Tuple) {
        //println!("Tuple: {:?}", tuple);
    }
}

struct FilterConsumer {
    tuple_type: TupleType,
    filter_expr: Expr
}

impl TupleConsumer for FilterConsumer {
    fn process(&self, tuple: &Tuple) {
        let x = evaluate(tuple, &self.tuple_type, &self.filter_expr);
        println!("Filter expr evaluates to {:?}", x);
    }
}

trait Relation {
    fn scan(&mut self, &TupleConsumer);
}

struct CsvRelation {
    filename: String,
    tuple_type: TupleType,
    reader: csv::Reader<File>,
    //records: Option<csv::StringRecords<'a, File>>
}

impl CsvRelation {
    fn open(filename: String, tuple_type: TupleType) -> Self {
        let mut rdr = csv::Reader::from_file(&filename).unwrap();
        CsvRelation {
            filename: filename,
            tuple_type: tuple_type,
            reader: rdr,
            //      records: None,
        }
    }

    //    fn init(&self) {
    //        self.records = Some(self.reader.records());
    //    }
}

impl Relation for CsvRelation {

    fn scan(&mut self, consumer: &TupleConsumer) {
        // iterate over data
        let mut records = self.reader.records();
        while let Some(row) = records.next() {
            let data : Vec<String> = row.unwrap();

            // for now, do an expensive translation of strings to the specific tuple type for
            // every single column
            let mut converted : Vec<Value> = vec![];
            for i in 0..data.len() {
                converted.push(match self.tuple_type.columns[i].data_type {
                    DataType::UnsignedLong => Value::UnsignedLong(data[i].parse::<u64>().unwrap()),
                    DataType::String => Value::String(data[i].clone()),
                });
            }
            let tuple = SimpleTuple { values: converted };

            consumer.process(&tuple);

        }

    }

}

fn main() {

    // define schema for data source (csv file)
    let tt = TupleType {
        columns: vec![
            ColumnMeta { name: String::from("id"), data_type: DataType::UnsignedLong, nullable: false },
            ColumnMeta { name: String::from("name"), data_type: DataType::String, nullable: false }
        ]
    };

    // open csv file
    let mut csv = CsvRelation::open(String::from("people.csv"), tt.clone());

    // create simple filter expression for "id = 2"
    let filter_expr = Expr::BinaryExpr {
        left: Box::new(Expr::TupleValue(0)),
        op: Operator::Eq,
        right: Box::new(Expr::Literal(Value::UnsignedLong(2)))
    };

    let filter_consumer = FilterConsumer { tuple_type: tt.clone(), filter_expr: filter_expr };

    csv.scan(&filter_consumer);
}
<commit_msg>experimenting with simple consumer chaining<commit_after>#![feature(box_patterns)]

use std::error::Error;
use std::fs::File;

extern crate csv;
use csv::{Reader, StringRecords};

/// The data types supported by this database. Currently just u64 and string but others
/// will be added later, including complex types
#[derive(Debug,Clone)]
enum DataType {
    UnsignedLong,
    String
}

/// Definition of a column in a relation (data set).
#[derive(Debug,Clone)]
struct ColumnMeta {
    name: String,
    data_type: DataType,
    nullable: bool
}

/// Definition of a relation (data set) consisting of one or more columns.
#[derive(Debug,Clone)]
struct TupleType {
    columns: Vec<ColumnMeta>
}

/// Value holder for all supported data types
#[derive(Debug,Clone,PartialEq,PartialOrd)]
enum Value {
    UnsignedLong(u64),
    String(String),
    Boolean(bool)
}

/// A tuple represents one row within a relation and is implemented as a trait to allow for
/// specific implementations for different data sources
trait Tuple {
    fn get_value(&self, index: usize) -> Result<Value, Box<std::error::Error>>;
}

/// A simple tuple implementation for testing and initial prototyping
#[derive(Debug)]
struct SimpleTuple {
    values: Vec<Value>
}

impl Tuple for SimpleTuple {

    fn get_value(&self, index: usize) -> Result<Value, Box<std::error::Error>> {
        Ok(self.values[index].clone())
    }

}

fn print_tuple(tuple_type: &TupleType, tuple: &Tuple) {
    for i in 0..tuple_type.columns.len() {
        print!("{:?}", tuple.get_value(i));
    }
    println!();
}

#[derive(Debug)]
enum Operator {
    Eq,
    NotEq,
    Lt,
    LtEq,
    Gt,
    GtEq,
}

#[derive(Debug)]
enum Expr {
    /// index into a value within the tuple
    TupleValue(usize),
    /// literal value
    Literal(Value),
    /// binary expression e.g. "age > 21"
    BinaryExpr { left: Box<Expr>, op: Operator, right: Box<Expr> },
}

/// Query plan
#[derive(Debug)]
enum PlanNode {
    TableScan { schema: String, table: String },
    Filter { expr: Expr, input: Box<PlanNode> },
    Project { expr: Vec<Expr>, input: Box<PlanNode> }
}

fn evaluate(tuple: &Tuple, tt: &TupleType, expr: &Expr) -> Result<Value, Box<std::error::Error>> {

    match expr {
        &Expr::BinaryExpr { box ref left, ref op, box ref right } => {
            //TODO: remove use of unwrap() here
            let left_value = evaluate(tuple, tt, left).unwrap();
            let right_value = evaluate(tuple, tt, right).unwrap();
            match op {
                &Operator::Eq => Ok(Value::Boolean(left_value == right_value)),
                &Operator::NotEq => Ok(Value::Boolean(left_value != right_value)),
                &Operator::Lt => Ok(Value::Boolean(left_value < right_value)),
                &Operator::LtEq => Ok(Value::Boolean(left_value <= right_value)),
                &Operator::Gt => Ok(Value::Boolean(left_value > right_value)),
                &Operator::GtEq => Ok(Value::Boolean(left_value >= right_value)),
            }
        },
        &Expr::TupleValue(index) => tuple.get_value(index),
        &Expr::Literal(ref value) => Ok(value.clone()),
    }

}

trait TupleConsumer {
    fn process(&self, tuple: &Tuple);
}

struct DebugConsumer {
    tuple_type: TupleType,
}

impl TupleConsumer for DebugConsumer {
    fn process(&self, tuple: &Tuple) {
        print_tuple(&self.tuple_type, tuple);
    }
}

struct FilterConsumer<'a> {
    tuple_type: TupleType,
    filter_expr: Expr,
    next_consumer: Option<&'a TupleConsumer>
}

impl<'a> TupleConsumer for FilterConsumer<'a> {
    fn process(&self, tuple: &Tuple) {
        let x = evaluate(tuple, &self.tuple_type, &self.filter_expr);
        println!("Filter expr evaluates to {:?}", x);

        match x {
            Ok(v) => match v {
                Value::Boolean(b) => {
                    if (b) {
                        match self.next_consumer {
                            Some(c) => c.process(tuple),
                            None => {}
                        }
                    }
                },
                _ => {}
            },
            _ => {}
        }

    }
}

trait Relation {
    fn scan(&mut self, &TupleConsumer);
}

struct CsvRelation {
    filename: String,
    tuple_type: TupleType,
    reader: csv::Reader<File>,
}

impl CsvRelation {
    fn open(filename: String, tuple_type: TupleType) -> Self {
        let rdr = csv::Reader::from_file(&filename).unwrap();
        CsvRelation {
            filename: filename,
            tuple_type: tuple_type,
            reader: rdr,
        }
    }
}

impl Relation for CsvRelation {

    fn scan(&mut self, consumer: &TupleConsumer) {
        // iterate over data
        let mut records = self.reader.records();
        while let Some(row) = records.next() {
            let data : Vec<String> = row.unwrap();

            // for now, do an expensive translation of strings to the specific tuple type for
            // every single column
            let mut converted : Vec<Value> = vec![];
            for i in 0..data.len() {
                converted.push(match self.tuple_type.columns[i].data_type {
                    DataType::UnsignedLong => Value::UnsignedLong(data[i].parse::<u64>().unwrap()),
                    DataType::String => Value::String(data[i].clone()),
                });
            }
            let tuple = SimpleTuple { values: converted };

            consumer.process(&tuple);

        }

    }

}

fn main() {

    // define schema for data source (csv file)
    let tt = TupleType {
        columns: vec![
            ColumnMeta { name: String::from("id"), data_type: DataType::UnsignedLong, nullable: false },
            ColumnMeta { name: String::from("name"), data_type: DataType::String, nullable: false }
        ]
    };

    // open csv file
    let mut csv = CsvRelation::open(String::from("people.csv"), tt.clone());

    // create simple filter expression for "id = 2"
    let filter_expr = Expr::BinaryExpr {
        left: Box::new(Expr::TupleValue(0)),
        op: Operator::Eq,
        right: Box::new(Expr::Literal(Value::UnsignedLong(2)))
    };

    let debug_consumer = DebugConsumer { tuple_type: tt.clone() };

    let filter_consumer = FilterConsumer {
        tuple_type: tt.clone(),
        filter_expr: filter_expr,
        next_consumer: Some(&debug_consumer)
    };

    csv.scan(&filter_consumer);
}
<|endoftext|>


<commit_before><commit_msg>Added files via upload<commit_after>// use util::{run_example, read_url};

use std::{};
use util::{run_example};

fn t(file: &str) {
 let  a= file;
  println!("hello: {:}", a);
    run_example()

}

#[test] fn non_macro() { t("hello_world") }

<|endoftext|>


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

use core::prelude::*;

use ast;
use ast::{meta_item, item, expr};
use codemap::span;
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use ext::deriving::generic::*;

pub fn expand_deriving_ord(cx: @ExtCtxt,
                           span: span,
                           mitem: @meta_item,
                           in_items: ~[@item]) -> ~[@item] {
    macro_rules! md (
        ($name:expr, $func:expr, $op:expr) => {
            MethodDef {
                name: $name,
                generics: LifetimeBounds::empty(),
                explicit_self: borrowed_explicit_self(),
                args: ~[borrowed_self()],
                ret_ty: Literal(Path::new(~["bool"])),
                const_nonmatching: false,
                combine_substructure: |cx, span, substr| $func($op, cx, span, substr)
            }
        }
    );

    let trait_def = TraitDef {
        path: Path::new(~["std", "cmp", "Ord"]),
        additional_bounds: ~[],
        generics: LifetimeBounds::empty(),
        methods: ~[
            md!("lt", cs_strict, true),
            md!("le", cs_nonstrict, true), // inverse operation
            md!("gt", cs_strict, false),
            md!("ge", cs_nonstrict, false)
        ]
    };
    trait_def.expand(cx, span, mitem, in_items)
}

/// Strict inequality.
fn cs_strict(less: bool, cx: @ExtCtxt, span: span, substr: &Substructure) -> @expr {
    let op = if less {ast::lt} else {ast::gt};
    cs_fold(
        false, // need foldr,
        |cx, span, subexpr, self_f, other_fs| {
            /*
            build up a series of chain ||'s and &&'s from the inside
            out (hence foldr) to get lexical ordering, i.e. for op ==
            `ast::lt`

            ```
            self.f1 < other.f1 || (!(other.f1 < self.f1) &&
                (self.f2 < other.f2 || (!(other.f2 < self.f2) &&
                    (false)
                ))
            )
            ```

            The optimiser should remove the redundancy. We explicitly
            get use the binops to avoid auto-deref derefencing too many
            layers of pointers, if the type includes pointers.
            */
            let other_f = match other_fs {
                [o_f] => o_f,
                _ => cx.span_bug(span, "Not exactly 2 arguments in `deriving(Ord)`")
            };

            let cmp = cx.expr_binary(span, op,
                                     cx.expr_deref(span, self_f),
                                     cx.expr_deref(span, other_f));

            let not_cmp = cx.expr_binary(span, op,
                                         cx.expr_deref(span, other_f),
                                         cx.expr_deref(span, self_f));
            let not_cmp = cx.expr_unary(span, ast::not, not_cmp);

            let and = cx.expr_binary(span, ast::and,
                                     not_cmp, subexpr);
            cx.expr_binary(span, ast::or, cmp, and)
        },
        cx.expr_bool(span, false),
        |cx, span, args, _| {
            // nonmatching enums, order by the order the variants are
            // written
            match args {
                [(self_var, _, _),
                 (other_var, _, _)] =>
                    cx.expr_bool(span,
                                 if less {
                                     self_var < other_var
                                 } else {
                                     self_var > other_var
                                 }),
                _ => cx.span_bug(span, "Not exactly 2 arguments in `deriving(Ord)`")
            }
        },
        cx, span, substr)
}

fn cs_nonstrict(less: bool, cx: @ExtCtxt, span: span, substr: &Substructure) -> @expr {
    // Example: ge becomes !(*self < *other), le becomes !(*self > *other)

    let inverse_op = if less {ast::gt} else {ast::lt};
    match substr.self_args {
        [self_, other] => {
            let inverse_cmp = cx.expr_binary(span, inverse_op,
                                             cx.expr_deref(span, self_),
                                             cx.expr_deref(span, other));

            cx.expr_unary(span, ast::not, inverse_cmp)
        }
        _ => cx.span_bug(span, "Not exactly 2 arguments in `deriving(Ord)`")
    }
}
<commit_msg>syntax: correct the modifications to deriving(Ord) so that it works.<commit_after>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use core::prelude::*;

use ast;
use ast::{meta_item, item, expr};
use codemap::span;
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use ext::deriving::generic::*;

pub fn expand_deriving_ord(cx: @ExtCtxt,
                           span: span,
                           mitem: @meta_item,
                           in_items: ~[@item]) -> ~[@item] {
    macro_rules! md (
        ($name:expr, $op:expr, $equal:expr) => {
            MethodDef {
                name: $name,
                generics: LifetimeBounds::empty(),
                explicit_self: borrowed_explicit_self(),
                args: ~[borrowed_self()],
                ret_ty: Literal(Path::new(~["bool"])),
                const_nonmatching: false,
                combine_substructure: |cx, span, substr| cs_op($op, $equal, cx, span, substr)
            }
        }
    );

    let trait_def = TraitDef {
        path: Path::new(~["std", "cmp", "Ord"]),
        additional_bounds: ~[],
        generics: LifetimeBounds::empty(),
        methods: ~[
            md!("lt", true, false),
            md!("le", true, true),
            md!("gt", false, false),
            md!("ge", false, true)
        ]
    };
    trait_def.expand(cx, span, mitem, in_items)
}

/// Strict inequality.
fn cs_op(less: bool, equal: bool, cx: @ExtCtxt, span: span, substr: &Substructure) -> @expr {
    let op = if less {ast::lt} else {ast::gt};
    cs_fold(
        false, // need foldr,
        |cx, span, subexpr, self_f, other_fs| {
            /*
            build up a series of chain ||'s and &&'s from the inside
            out (hence foldr) to get lexical ordering, i.e. for op ==
            `ast::lt`

            ```
            self.f1 < other.f1 || (!(other.f1 < self.f1) &&
                (self.f2 < other.f2 || (!(other.f2 < self.f2) &&
                    (false)
                ))
            )
            ```

            The optimiser should remove the redundancy. We explicitly
            get use the binops to avoid auto-deref derefencing too many
            layers of pointers, if the type includes pointers.
            */
            let other_f = match other_fs {
                [o_f] => o_f,
                _ => cx.span_bug(span, "Not exactly 2 arguments in `deriving(Ord)`")
            };

            let cmp = cx.expr_binary(span, op,
                                     cx.expr_deref(span, self_f),
                                     cx.expr_deref(span, other_f));

            let not_cmp = cx.expr_unary(span, ast::not,
                                        cx.expr_binary(span, op,
                                                       cx.expr_deref(span, other_f),
                                                       cx.expr_deref(span, self_f)));

            let and = cx.expr_binary(span, ast::and, not_cmp, subexpr);
            cx.expr_binary(span, ast::or, cmp, and)
        },
        cx.expr_bool(span, equal),
        |cx, span, args, _| {
            // nonmatching enums, order by the order the variants are
            // written
            match args {
                [(self_var, _, _),
                 (other_var, _, _)] =>
                    cx.expr_bool(span,
                                 if less {
                                     self_var < other_var
                                 } else {
                                     self_var > other_var
                                 }),
                _ => cx.span_bug(span, "Not exactly 2 arguments in `deriving(Ord)`")
            }
        },
        cx, span, substr)
}
<|endoftext|>


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

use driver::session::NoDebugInfo;
use driver::session::Session;
use lib::llvm::{ContextRef, ModuleRef, ValueRef};
use lib::llvm::{llvm, TargetData, TypeNames};
use lib::llvm::mk_target_data;
use metadata::common::LinkMeta;
use middle::astencode;
use middle::resolve;
use middle::trans::adt;
use middle::trans::base;
use middle::trans::builder::Builder;
use middle::trans::common::{C_i32, C_null};
use middle::trans::common::{mono_id,ExternMap,tydesc_info,BuilderRef_res,Stats};
use middle::trans::debuginfo;
use middle::trans::type_::Type;
use middle::ty;
use util::sha2::Sha256;
use util::nodemap::{NodeMap, NodeSet, DefIdMap};

use std::cell::{Cell, RefCell};
use std::c_str::ToCStr;
use std::libc::c_uint;
use std::ptr;
use collections::{HashMap, HashSet};
use syntax::ast;
use syntax::parse::token::InternedString;

pub struct CrateContext {
    pub llmod: ModuleRef,
    pub llcx: ContextRef,
    pub metadata_llmod: ModuleRef,
    pub td: TargetData,
    pub tn: TypeNames,
    pub externs: RefCell<ExternMap>,
    pub intrinsics: HashMap<&'static str, ValueRef>,
    pub item_vals: RefCell<NodeMap<ValueRef>>,
    pub exp_map2: resolve::ExportMap2,
    pub reachable: NodeSet,
    pub item_symbols: RefCell<NodeMap<~str>>,
    pub link_meta: LinkMeta,
    pub drop_glues: RefCell<HashMap<ty::t, ValueRef>>,
    pub tydescs: RefCell<HashMap<ty::t, @tydesc_info>>,
    /// Set when running emit_tydescs to enforce that no more tydescs are
    /// created.
    pub finished_tydescs: Cell<bool>,
    /// Track mapping of external ids to local items imported for inlining
    pub external: RefCell<DefIdMap<Option<ast::NodeId>>>,
    /// Backwards version of the `external` map (inlined items to where they
    /// came from)
    pub external_srcs: RefCell<NodeMap<ast::DefId>>,
    /// A set of static items which cannot be inlined into other crates. This
    /// will pevent in IIItem() structures from being encoded into the metadata
    /// that is generated
    pub non_inlineable_statics: RefCell<NodeSet>,
    /// Cache instances of monomorphized functions
    pub monomorphized: RefCell<HashMap<mono_id, ValueRef>>,
    pub monomorphizing: RefCell<DefIdMap<uint>>,
    /// Cache generated vtables
    pub vtables: RefCell<HashMap<(ty::t, mono_id), ValueRef>>,
    /// Cache of constant strings,
    pub const_cstr_cache: RefCell<HashMap<InternedString, ValueRef>>,

    /// Reverse-direction for const ptrs cast from globals.
    /// Key is an int, cast from a ValueRef holding a *T,
    /// Val is a ValueRef holding a *[T].
    ///
    /// Needed because LLVM loses pointer->pointee association
    /// when we ptrcast, and we have to ptrcast during translation
    /// of a [T] const because we form a slice, a [*T,int] pair, not
    /// a pointer to an LLVM array type.
    pub const_globals: RefCell<HashMap<int, ValueRef>>,

    /// Cache of emitted const values
    pub const_values: RefCell<NodeMap<ValueRef>>,

    /// Cache of external const values
    pub extern_const_values: RefCell<DefIdMap<ValueRef>>,

    pub impl_method_cache: RefCell<HashMap<(ast::DefId, ast::Name), ast::DefId>>,

    /// Cache of closure wrappers for bare fn's.
    pub closure_bare_wrapper_cache: RefCell<HashMap<ValueRef, ValueRef>>,

    pub lltypes: RefCell<HashMap<ty::t, Type>>,
    pub llsizingtypes: RefCell<HashMap<ty::t, Type>>,
    pub adt_reprs: RefCell<HashMap<ty::t, @adt::Repr>>,
    pub symbol_hasher: RefCell<Sha256>,
    pub type_hashcodes: RefCell<HashMap<ty::t, ~str>>,
    pub all_llvm_symbols: RefCell<HashSet<~str>>,
    pub tcx: ty::ctxt,
    pub maps: astencode::Maps,
    pub stats: @Stats,
    pub int_type: Type,
    pub opaque_vec_type: Type,
    pub builder: BuilderRef_res,
    /// Set when at least one function uses GC. Needed so that
    /// decl_gc_metadata knows whether to link to the module metadata, which
    /// is not emitted by LLVM's GC pass when no functions use GC.
    pub uses_gc: bool,
    pub dbg_cx: Option<debuginfo::CrateDebugContext>,
}

impl CrateContext {
    pub fn new(name: &str,
               tcx: ty::ctxt,
               emap2: resolve::ExportMap2,
               maps: astencode::Maps,
               symbol_hasher: Sha256,
               link_meta: LinkMeta,
               reachable: NodeSet)
               -> CrateContext {
        unsafe {
            let llcx = llvm::LLVMContextCreate();
            let llmod = name.with_c_str(|buf| {
                llvm::LLVMModuleCreateWithNameInContext(buf, llcx)
            });
            let metadata_llmod = format!("{}_metadata", name).with_c_str(|buf| {
                llvm::LLVMModuleCreateWithNameInContext(buf, llcx)
            });
            tcx.sess.targ_cfg.target_strs.data_layout.with_c_str(|buf| {
                llvm::LLVMSetDataLayout(llmod, buf);
                llvm::LLVMSetDataLayout(metadata_llmod, buf);
            });
            tcx.sess.targ_cfg.target_strs.target_triple.with_c_str(|buf| {
                llvm::LLVMRustSetNormalizedTarget(llmod, buf);
                llvm::LLVMRustSetNormalizedTarget(metadata_llmod, buf);
            });

            let td = mk_target_data(tcx.sess.targ_cfg.target_strs.data_layout);

            let dbg_cx = if tcx.sess.opts.debuginfo != NoDebugInfo {
                Some(debuginfo::CrateDebugContext::new(llmod))
            } else {
                None
            };

            let mut ccx = CrateContext {
                llmod: llmod,
                llcx: llcx,
                metadata_llmod: metadata_llmod,
                td: td,
                tn: TypeNames::new(),
                externs: RefCell::new(HashMap::new()),
                intrinsics: HashMap::new(),
                item_vals: RefCell::new(NodeMap::new()),
                exp_map2: emap2,
                reachable: reachable,
                item_symbols: RefCell::new(NodeMap::new()),
                link_meta: link_meta,
                drop_glues: RefCell::new(HashMap::new()),
                tydescs: RefCell::new(HashMap::new()),
                finished_tydescs: Cell::new(false),
                external: RefCell::new(DefIdMap::new()),
                external_srcs: RefCell::new(NodeMap::new()),
                non_inlineable_statics: RefCell::new(NodeSet::new()),
                monomorphized: RefCell::new(HashMap::new()),
                monomorphizing: RefCell::new(DefIdMap::new()),
                vtables: RefCell::new(HashMap::new()),
                const_cstr_cache: RefCell::new(HashMap::new()),
                const_globals: RefCell::new(HashMap::new()),
                const_values: RefCell::new(NodeMap::new()),
                extern_const_values: RefCell::new(DefIdMap::new()),
                impl_method_cache: RefCell::new(HashMap::new()),
                closure_bare_wrapper_cache: RefCell::new(HashMap::new()),
                lltypes: RefCell::new(HashMap::new()),
                llsizingtypes: RefCell::new(HashMap::new()),
                adt_reprs: RefCell::new(HashMap::new()),
                symbol_hasher: RefCell::new(symbol_hasher),
                type_hashcodes: RefCell::new(HashMap::new()),
                all_llvm_symbols: RefCell::new(HashSet::new()),
                tcx: tcx,
                maps: maps,
                stats: @Stats {
                    n_static_tydescs: Cell::new(0u),
                    n_glues_created: Cell::new(0u),
                    n_null_glues: Cell::new(0u),
                    n_real_glues: Cell::new(0u),
                    n_fns: Cell::new(0u),
                    n_monos: Cell::new(0u),
                    n_inlines: Cell::new(0u),
                    n_closures: Cell::new(0u),
                    n_llvm_insns: Cell::new(0u),
                    llvm_insns: RefCell::new(HashMap::new()),
                    fn_stats: RefCell::new(Vec::new()),
                },
                int_type: Type::from_ref(ptr::null()),
                opaque_vec_type: Type::from_ref(ptr::null()),
                builder: BuilderRef_res(llvm::LLVMCreateBuilderInContext(llcx)),
                uses_gc: false,
                dbg_cx: dbg_cx,
            };

            ccx.int_type = Type::int(&ccx);
            ccx.opaque_vec_type = Type::opaque_vec(&ccx);

            ccx.tn.associate_type("tydesc", &Type::tydesc(&ccx));

            let mut str_slice_ty = Type::named_struct(&ccx, "str_slice");
            str_slice_ty.set_struct_body([Type::i8p(&ccx), ccx.int_type], false);
            ccx.tn.associate_type("str_slice", &str_slice_ty);

            base::declare_intrinsics(&mut ccx);

            if ccx.sess().count_llvm_insns() {
                base::init_insn_ctxt()
            }

            ccx
        }
    }

    pub fn tcx<'a>(&'a self) -> &'a ty::ctxt {
        &self.tcx
    }

    pub fn sess<'a>(&'a self) -> &'a Session {
        &self.tcx.sess
    }

    pub fn builder<'a>(&'a self) -> Builder<'a> {
        Builder::new(self)
    }

    pub fn const_inbounds_gepi(&self,
                               pointer: ValueRef,
                               indices: &[uint]) -> ValueRef {
        debug!("const_inbounds_gepi: pointer={} indices={:?}",
               self.tn.val_to_str(pointer), indices);
        let v: Vec<ValueRef> =
            indices.iter().map(|i| C_i32(self, *i as i32)).collect();
        unsafe {
            llvm::LLVMConstInBoundsGEP(pointer,
                                       v.as_ptr(),
                                       indices.len() as c_uint)
        }
    }

    pub fn offsetof_gep(&self,
                        llptr_ty: Type,
                        indices: &[uint]) -> ValueRef {
        /*!
         * Returns the offset of applying the given GEP indices
         * to an instance of `llptr_ty`. Similar to `offsetof` in C,
         * except that `llptr_ty` must be a pointer type.
         */

        unsafe {
            let null = C_null(llptr_ty);
            llvm::LLVMConstPtrToInt(self.const_inbounds_gepi(null, indices),
                                    self.int_type.to_ref())
        }
    }

    pub fn tydesc_type(&self) -> Type {
        self.tn.find_type("tydesc").unwrap()
    }
}
<commit_msg>middle: trans: context: remove dead code<commit_after>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use driver::session::NoDebugInfo;
use driver::session::Session;
use lib::llvm::{ContextRef, ModuleRef, ValueRef};
use lib::llvm::{llvm, TargetData, TypeNames};
use lib::llvm::mk_target_data;
use metadata::common::LinkMeta;
use middle::astencode;
use middle::resolve;
use middle::trans::adt;
use middle::trans::base;
use middle::trans::builder::Builder;
use middle::trans::common::{mono_id,ExternMap,tydesc_info,BuilderRef_res,Stats};
use middle::trans::debuginfo;
use middle::trans::type_::Type;
use middle::ty;
use util::sha2::Sha256;
use util::nodemap::{NodeMap, NodeSet, DefIdMap};

use std::cell::{Cell, RefCell};
use std::c_str::ToCStr;
use std::ptr;
use collections::{HashMap, HashSet};
use syntax::ast;
use syntax::parse::token::InternedString;

pub struct CrateContext {
    pub llmod: ModuleRef,
    pub llcx: ContextRef,
    pub metadata_llmod: ModuleRef,
    pub td: TargetData,
    pub tn: TypeNames,
    pub externs: RefCell<ExternMap>,
    pub intrinsics: HashMap<&'static str, ValueRef>,
    pub item_vals: RefCell<NodeMap<ValueRef>>,
    pub exp_map2: resolve::ExportMap2,
    pub reachable: NodeSet,
    pub item_symbols: RefCell<NodeMap<~str>>,
    pub link_meta: LinkMeta,
    pub drop_glues: RefCell<HashMap<ty::t, ValueRef>>,
    pub tydescs: RefCell<HashMap<ty::t, @tydesc_info>>,
    /// Set when running emit_tydescs to enforce that no more tydescs are
    /// created.
    pub finished_tydescs: Cell<bool>,
    /// Track mapping of external ids to local items imported for inlining
    pub external: RefCell<DefIdMap<Option<ast::NodeId>>>,
    /// Backwards version of the `external` map (inlined items to where they
    /// came from)
    pub external_srcs: RefCell<NodeMap<ast::DefId>>,
    /// A set of static items which cannot be inlined into other crates. This
    /// will pevent in IIItem() structures from being encoded into the metadata
    /// that is generated
    pub non_inlineable_statics: RefCell<NodeSet>,
    /// Cache instances of monomorphized functions
    pub monomorphized: RefCell<HashMap<mono_id, ValueRef>>,
    pub monomorphizing: RefCell<DefIdMap<uint>>,
    /// Cache generated vtables
    pub vtables: RefCell<HashMap<(ty::t, mono_id), ValueRef>>,
    /// Cache of constant strings,
    pub const_cstr_cache: RefCell<HashMap<InternedString, ValueRef>>,

    /// Reverse-direction for const ptrs cast from globals.
    /// Key is an int, cast from a ValueRef holding a *T,
    /// Val is a ValueRef holding a *[T].
    ///
    /// Needed because LLVM loses pointer->pointee association
    /// when we ptrcast, and we have to ptrcast during translation
    /// of a [T] const because we form a slice, a [*T,int] pair, not
    /// a pointer to an LLVM array type.
    pub const_globals: RefCell<HashMap<int, ValueRef>>,

    /// Cache of emitted const values
    pub const_values: RefCell<NodeMap<ValueRef>>,

    /// Cache of external const values
    pub extern_const_values: RefCell<DefIdMap<ValueRef>>,

    pub impl_method_cache: RefCell<HashMap<(ast::DefId, ast::Name), ast::DefId>>,

    /// Cache of closure wrappers for bare fn's.
    pub closure_bare_wrapper_cache: RefCell<HashMap<ValueRef, ValueRef>>,

    pub lltypes: RefCell<HashMap<ty::t, Type>>,
    pub llsizingtypes: RefCell<HashMap<ty::t, Type>>,
    pub adt_reprs: RefCell<HashMap<ty::t, @adt::Repr>>,
    pub symbol_hasher: RefCell<Sha256>,
    pub type_hashcodes: RefCell<HashMap<ty::t, ~str>>,
    pub all_llvm_symbols: RefCell<HashSet<~str>>,
    pub tcx: ty::ctxt,
    pub maps: astencode::Maps,
    pub stats: @Stats,
    pub int_type: Type,
    pub opaque_vec_type: Type,
    pub builder: BuilderRef_res,
    /// Set when at least one function uses GC. Needed so that
    /// decl_gc_metadata knows whether to link to the module metadata, which
    /// is not emitted by LLVM's GC pass when no functions use GC.
    pub uses_gc: bool,
    pub dbg_cx: Option<debuginfo::CrateDebugContext>,
}

impl CrateContext {
    pub fn new(name: &str,
               tcx: ty::ctxt,
               emap2: resolve::ExportMap2,
               maps: astencode::Maps,
               symbol_hasher: Sha256,
               link_meta: LinkMeta,
               reachable: NodeSet)
               -> CrateContext {
        unsafe {
            let llcx = llvm::LLVMContextCreate();
            let llmod = name.with_c_str(|buf| {
                llvm::LLVMModuleCreateWithNameInContext(buf, llcx)
            });
            let metadata_llmod = format!("{}_metadata", name).with_c_str(|buf| {
                llvm::LLVMModuleCreateWithNameInContext(buf, llcx)
            });
            tcx.sess.targ_cfg.target_strs.data_layout.with_c_str(|buf| {
                llvm::LLVMSetDataLayout(llmod, buf);
                llvm::LLVMSetDataLayout(metadata_llmod, buf);
            });
            tcx.sess.targ_cfg.target_strs.target_triple.with_c_str(|buf| {
                llvm::LLVMRustSetNormalizedTarget(llmod, buf);
                llvm::LLVMRustSetNormalizedTarget(metadata_llmod, buf);
            });

            let td = mk_target_data(tcx.sess.targ_cfg.target_strs.data_layout);

            let dbg_cx = if tcx.sess.opts.debuginfo != NoDebugInfo {
                Some(debuginfo::CrateDebugContext::new(llmod))
            } else {
                None
            };

            let mut ccx = CrateContext {
                llmod: llmod,
                llcx: llcx,
                metadata_llmod: metadata_llmod,
                td: td,
                tn: TypeNames::new(),
                externs: RefCell::new(HashMap::new()),
                intrinsics: HashMap::new(),
                item_vals: RefCell::new(NodeMap::new()),
                exp_map2: emap2,
                reachable: reachable,
                item_symbols: RefCell::new(NodeMap::new()),
                link_meta: link_meta,
                drop_glues: RefCell::new(HashMap::new()),
                tydescs: RefCell::new(HashMap::new()),
                finished_tydescs: Cell::new(false),
                external: RefCell::new(DefIdMap::new()),
                external_srcs: RefCell::new(NodeMap::new()),
                non_inlineable_statics: RefCell::new(NodeSet::new()),
                monomorphized: RefCell::new(HashMap::new()),
                monomorphizing: RefCell::new(DefIdMap::new()),
                vtables: RefCell::new(HashMap::new()),
                const_cstr_cache: RefCell::new(HashMap::new()),
                const_globals: RefCell::new(HashMap::new()),
                const_values: RefCell::new(NodeMap::new()),
                extern_const_values: RefCell::new(DefIdMap::new()),
                impl_method_cache: RefCell::new(HashMap::new()),
                closure_bare_wrapper_cache: RefCell::new(HashMap::new()),
                lltypes: RefCell::new(HashMap::new()),
                llsizingtypes: RefCell::new(HashMap::new()),
                adt_reprs: RefCell::new(HashMap::new()),
                symbol_hasher: RefCell::new(symbol_hasher),
                type_hashcodes: RefCell::new(HashMap::new()),
                all_llvm_symbols: RefCell::new(HashSet::new()),
                tcx: tcx,
                maps: maps,
                stats: @Stats {
                    n_static_tydescs: Cell::new(0u),
                    n_glues_created: Cell::new(0u),
                    n_null_glues: Cell::new(0u),
                    n_real_glues: Cell::new(0u),
                    n_fns: Cell::new(0u),
                    n_monos: Cell::new(0u),
                    n_inlines: Cell::new(0u),
                    n_closures: Cell::new(0u),
                    n_llvm_insns: Cell::new(0u),
                    llvm_insns: RefCell::new(HashMap::new()),
                    fn_stats: RefCell::new(Vec::new()),
                },
                int_type: Type::from_ref(ptr::null()),
                opaque_vec_type: Type::from_ref(ptr::null()),
                builder: BuilderRef_res(llvm::LLVMCreateBuilderInContext(llcx)),
                uses_gc: false,
                dbg_cx: dbg_cx,
            };

            ccx.int_type = Type::int(&ccx);
            ccx.opaque_vec_type = Type::opaque_vec(&ccx);

            ccx.tn.associate_type("tydesc", &Type::tydesc(&ccx));

            let mut str_slice_ty = Type::named_struct(&ccx, "str_slice");
            str_slice_ty.set_struct_body([Type::i8p(&ccx), ccx.int_type], false);
            ccx.tn.associate_type("str_slice", &str_slice_ty);

            base::declare_intrinsics(&mut ccx);

            if ccx.sess().count_llvm_insns() {
                base::init_insn_ctxt()
            }

            ccx
        }
    }

    pub fn tcx<'a>(&'a self) -> &'a ty::ctxt {
        &self.tcx
    }

    pub fn sess<'a>(&'a self) -> &'a Session {
        &self.tcx.sess
    }

    pub fn builder<'a>(&'a self) -> Builder<'a> {
        Builder::new(self)
    }

    pub fn tydesc_type(&self) -> Type {
        self.tn.find_type("tydesc").unwrap()
    }
}
<|endoftext|>


<commit_before><commit_msg>Simplify Day 22 solution a bit<commit_after><|endoftext|>


<commit_before>pub use super::{Command, CommandType, CommandGroup};

use std::collections::HashMap;
use std::default::Default;
use std::sync::Arc;
use ::client::Context;
use ::model::{Message, Permissions};

pub struct CreateCommand(pub Command);

impl CreateCommand {
    /// Adds a ratelimit bucket.
    pub fn bucket(mut self, bucket: &str) -> Self {
        self.0.bucket = Some(bucket.to_owned());

        self
    }

    /// Adds an alias, allowing users to use the command under a different name.
    pub fn known_as(mut self, name: &str) -> Self {
        self.0.aliases.push(name.to_owned());

        self
    }

    /// Adds multiple aliases.
    pub fn batch_known_as(mut self, names: Vec<&str>) -> Self {
        for n in names {
            self.0.aliases.push(n.to_owned());
        }

        self
    }

    /// Adds a "check" to a command, which checks whether or not the command's
    /// function should be called.
    ///
    /// # Examples
    ///
    /// Ensure that the user who created a message, calling a "ping" command,
    /// is the owner.
    ///
    /// ```rust,no_run
    /// use serenity::client::{Client, Context};
    /// use serenity::model::Message;
    /// use std::env;
    ///
    /// let mut client = Client::login_bot(&env::var("DISCORD_TOKEN").unwrap());
    ///
    /// client.with_framework(|f| f
    ///     .configure(|c| c.prefix("~"))
    ///     .command("ping", |c| c
    ///         .check(owner_check)
    ///         .desc("Replies to a ping with a pong")
    ///         .exec(ping)));
    ///
    /// fn ping(context: &mut Context, _message: &Message, _args: Vec<String>) -> Result<(), String> {
    ///     let _ = context.say("Pong!");
    ///
    ///     Ok(())
    /// }
    ///
    /// fn owner_check(_context: &mut Context, message: &Message) -> bool {
    ///     // replace with your user ID
    ///     message.author.id == 7
    /// }
    /// ```
    pub fn check<F>(mut self, check: F) -> Self
        where F: Fn(&mut Context, &Message) -> bool + Send + Sync + 'static {
        self.0.checks.push(Box::new(check));

        self
    }

    /// Description, used by other commands.
    pub fn desc(mut self, desc: &str) -> Self {
        self.0.desc = Some(desc.to_owned());

        self
    }

    /// Whether command can be used only privately or not.
    pub fn dm_only(mut self, dm_only: bool) -> Self {
        self.0.dm_only = dm_only;

        self
    }

    /// Example arguments, used by other commands.
    pub fn example(mut self, example: &str) -> Self {
        self.0.example = Some(example.to_owned());

        self
    }

    /// A function that can be called when a command is received.
    /// You can return Err(string) if there's an error.
    ///
    /// See [`exec_str`] if you _only_ need to return a string on command use.
    ///
    /// [`exec_str`]: #method.exec_str
    pub fn exec<F>(mut self, func: F) -> Self
        where F: Fn(&mut Context, &Message, Vec<String>) -> Result<(), String> + Send + Sync + 'static {
        self.0.exec = CommandType::Basic(Box::new(func));

        self
    }

    /// Sets a function that's called when a command is called that can access
    /// the internal HashMap of usages, used specifically for creating a help
    /// command.
    ///
    /// You can return Err(string) if there's an error.
    pub fn exec_help<F>(mut self, f: F) -> Self
        where F: Fn(&mut Context, &Message, HashMap<String, Arc<CommandGroup>>, Vec<String>) -> Result<(), String> + Send + Sync + 'static {
        self.0.exec = CommandType::WithCommands(Box::new(f));

        self
    }

    /// Sets a string to be sent in the channel of context on command. This can
    /// be useful for an `about`, `invite`, `ping`, etc. command.
    ///
    /// # Examples
    ///
    /// Create a command named "ping" that returns "Pong!":
    ///
    /// ```rust,ignore
    /// client.with_framework(|f| f
    ///     .command("ping", |c| c.exec_str("Pong!")));
    /// ```
    pub fn exec_str(mut self, content: &str) -> Self {
        self.0.exec = CommandType::StringResponse(content.to_owned());

        self
    }

    /// Whether command can be used only in guilds or not.
    pub fn guild_only(mut self, guild_only: bool) -> Self {
        self.0.guild_only = guild_only;

        self
    }

    /// Whether command should be displayed in help list or not, used by other commands.
    pub fn help_available(mut self, help_available: bool) -> Self {
        self.0.help_available = help_available;

        self
    }

    /// Maximum amount of arguments that can be passed.
    pub fn max_args(mut self, max_args: i32) -> Self {
        self.0.max_args = Some(max_args);

        self
    }

    /// Minumum amount of arguments that should be passed.
    pub fn min_args(mut self, min_args: i32) -> Self {
        self.0.min_args = Some(min_args);

        self
    }

    /// Whether command can be used only privately or not.
    pub fn owners_only(mut self, owners_only: bool) -> Self {
        self.0.owners_only = owners_only;

        self
    }

    /// The permissions that a user must have in the contextual channel in order
    /// for the command to be processed.
    pub fn required_permissions(mut self, permissions: Permissions) -> Self {
        self.0.required_permissions = permissions;

        self
    }

    /// Command usage schema, used by other commands.
    pub fn usage(mut self, usage: &str) -> Self {
        self.0.usage = Some(usage.to_owned());

        self
    }

    /// Whether or not arguments should be parsed using the quotation parser.
    ///
    /// Enabling this will parse `~command "this is arg 1" "this is arg 2"` as
    /// two arguments: `this is arg 1` and `this is arg 2`.
    ///
    /// Disabling this will parse `~command "this is arg 1" "this is arg 2"` as
    /// eight arguments: `"this`, `is`, `arg`, `1"`, `"this`, `is`, `arg`, `2"`.
    ///
    /// Refer to [`utils::parse_quotes`] for information on the parser.
    ///
    /// [`utils::parse_quotes`]: ../../utils/fn.parse_quotes.html
    pub fn use_quotes(mut self, use_quotes: bool) -> Self {
        self.0.use_quotes = use_quotes;

        self
    }
}

impl Default for Command {
    fn default() -> Command {
        Command {
            aliases: Vec::new(),
            checks: Vec::default(),
            exec: CommandType::Basic(Box::new(|_, _, _| Ok(()))),
            desc: None,
            usage: None,
            example: None,
            use_quotes: false,
            min_args: None,
            bucket: None,
            max_args: None,
            required_permissions: Permissions::empty(),
            dm_only: false,
            guild_only: false,
            help_available: true,
            owners_only: false,
        }
    }
}
<commit_msg>hashmap of usages<commit_after>pub use super::{Command, CommandType, CommandGroup};

use std::collections::HashMap;
use std::default::Default;
use std::sync::Arc;
use ::client::Context;
use ::model::{Message, Permissions};

pub struct CreateCommand(pub Command);

impl CreateCommand {
    /// Adds a ratelimit bucket.
    pub fn bucket(mut self, bucket: &str) -> Self {
        self.0.bucket = Some(bucket.to_owned());

        self
    }

    /// Adds an alias, allowing users to use the command under a different name.
    pub fn known_as(mut self, name: &str) -> Self {
        self.0.aliases.push(name.to_owned());

        self
    }

    /// Adds multiple aliases.
    pub fn batch_known_as(mut self, names: Vec<&str>) -> Self {
        for n in names {
            self.0.aliases.push(n.to_owned());
        }

        self
    }

    /// Adds a "check" to a command, which checks whether or not the command's
    /// function should be called.
    ///
    /// # Examples
    ///
    /// Ensure that the user who created a message, calling a "ping" command,
    /// is the owner.
    ///
    /// ```rust,no_run
    /// use serenity::client::{Client, Context};
    /// use serenity::model::Message;
    /// use std::env;
    ///
    /// let mut client = Client::login_bot(&env::var("DISCORD_TOKEN").unwrap());
    ///
    /// client.with_framework(|f| f
    ///     .configure(|c| c.prefix("~"))
    ///     .command("ping", |c| c
    ///         .check(owner_check)
    ///         .desc("Replies to a ping with a pong")
    ///         .exec(ping)));
    ///
    /// fn ping(context: &mut Context, _message: &Message, _args: Vec<String>) -> Result<(), String> {
    ///     let _ = context.say("Pong!");
    ///
    ///     Ok(())
    /// }
    ///
    /// fn owner_check(_context: &mut Context, message: &Message) -> bool {
    ///     // replace with your user ID
    ///     message.author.id == 7
    /// }
    /// ```
    pub fn check<F>(mut self, check: F) -> Self
        where F: Fn(&mut Context, &Message) -> bool + Send + Sync + 'static {
        self.0.checks.push(Box::new(check));

        self
    }

    /// Description, used by other commands.
    pub fn desc(mut self, desc: &str) -> Self {
        self.0.desc = Some(desc.to_owned());

        self
    }

    /// Whether command can be used only privately or not.
    pub fn dm_only(mut self, dm_only: bool) -> Self {
        self.0.dm_only = dm_only;

        self
    }

    /// Example arguments, used by other commands.
    pub fn example(mut self, example: &str) -> Self {
        self.0.example = Some(example.to_owned());

        self
    }

    /// A function that can be called when a command is received.
    /// You can return Err(string) if there's an error.
    ///
    /// See [`exec_str`] if you _only_ need to return a string on command use.
    ///
    /// [`exec_str`]: #method.exec_str
    pub fn exec<F>(mut self, func: F) -> Self
        where F: Fn(&mut Context, &Message, Vec<String>) -> Result<(), String> + Send + Sync + 'static {
        self.0.exec = CommandType::Basic(Box::new(func));

        self
    }

    /// Sets a function that's called when a command is called that can access
    /// the internal HashMap of commands, used specifically for creating a help
    /// command.
    ///
    /// You can return Err(string) if there's an error.
    pub fn exec_help<F>(mut self, f: F) -> Self
        where F: Fn(&mut Context, &Message, HashMap<String, Arc<CommandGroup>>, Vec<String>) -> Result<(), String> + Send + Sync + 'static {
        self.0.exec = CommandType::WithCommands(Box::new(f));

        self
    }

    /// Sets a string to be sent in the channel of context on command. This can
    /// be useful for an `about`, `invite`, `ping`, etc. command.
    ///
    /// # Examples
    ///
    /// Create a command named "ping" that returns "Pong!":
    ///
    /// ```rust,ignore
    /// client.with_framework(|f| f
    ///     .command("ping", |c| c.exec_str("Pong!")));
    /// ```
    pub fn exec_str(mut self, content: &str) -> Self {
        self.0.exec = CommandType::StringResponse(content.to_owned());

        self
    }

    /// Whether command can be used only in guilds or not.
    pub fn guild_only(mut self, guild_only: bool) -> Self {
        self.0.guild_only = guild_only;

        self
    }

    /// Whether command should be displayed in help list or not, used by other commands.
    pub fn help_available(mut self, help_available: bool) -> Self {
        self.0.help_available = help_available;

        self
    }

    /// Maximum amount of arguments that can be passed.
    pub fn max_args(mut self, max_args: i32) -> Self {
        self.0.max_args = Some(max_args);

        self
    }

    /// Minumum amount of arguments that should be passed.
    pub fn min_args(mut self, min_args: i32) -> Self {
        self.0.min_args = Some(min_args);

        self
    }

    /// Whether command can be used only privately or not.
    pub fn owners_only(mut self, owners_only: bool) -> Self {
        self.0.owners_only = owners_only;

        self
    }

    /// The permissions that a user must have in the contextual channel in order
    /// for the command to be processed.
    pub fn required_permissions(mut self, permissions: Permissions) -> Self {
        self.0.required_permissions = permissions;

        self
    }

    /// Command usage schema, used by other commands.
    pub fn usage(mut self, usage: &str) -> Self {
        self.0.usage = Some(usage.to_owned());

        self
    }

    /// Whether or not arguments should be parsed using the quotation parser.
    ///
    /// Enabling this will parse `~command "this is arg 1" "this is arg 2"` as
    /// two arguments: `this is arg 1` and `this is arg 2`.
    ///
    /// Disabling this will parse `~command "this is arg 1" "this is arg 2"` as
    /// eight arguments: `"this`, `is`, `arg`, `1"`, `"this`, `is`, `arg`, `2"`.
    ///
    /// Refer to [`utils::parse_quotes`] for information on the parser.
    ///
    /// [`utils::parse_quotes`]: ../../utils/fn.parse_quotes.html
    pub fn use_quotes(mut self, use_quotes: bool) -> Self {
        self.0.use_quotes = use_quotes;

        self
    }
}

impl Default for Command {
    fn default() -> Command {
        Command {
            aliases: Vec::new(),
            checks: Vec::default(),
            exec: CommandType::Basic(Box::new(|_, _, _| Ok(()))),
            desc: None,
            usage: None,
            example: None,
            use_quotes: false,
            min_args: None,
            bucket: None,
            max_args: None,
            required_permissions: Permissions::empty(),
            dm_only: false,
            guild_only: false,
            help_available: true,
            owners_only: false,
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Auto merge of #276 - lvillani:eq-hash-traits, r=SimonSapin<commit_after><|endoftext|>


<commit_before>//  based on:
//  http://shootout.alioth.debian.org/
//   u64q/program.php?test=mandelbrot&lang=python3&id=2
//
//  takes 2 optional numeric args: square image size and yield frequency
//  in the shootout, they use 16000 as image size
//  yield frequency doesn't seem to have much effect
//
//  writes pbm image to stdout

use std;
import std::io::writer_util;

type cmplx = {re: f64, im: f64};
type line = {i: uint, b: [u8]};

impl arith for cmplx {
    fn *(x: cmplx) -> cmplx {
        {re: self.re*x.re - self.im*x.im, im: self.re*x.im + self.im*x.re}
    }

    fn +(x: cmplx) -> cmplx {
        {re: self.re + x.re, im: self.im + x.im}
    }
}

pure fn cabs(x: cmplx) -> f64
{
    x.re*x.re + x.im*x.im
}

fn mb(x: cmplx) -> bool
{
    let z = {re: 0., im: 0.};
    let i = 0;
    let in = true;
    while i < 50 {
        z = z*z + x;
        if cabs(z) >= 4. {
            in = false;
            break;
        }
        i += 1;
    }
    in
}

fn fillbyte(x: cmplx, incr: f64) -> u8 {
    let rv = 0_u8;
    let i = 0_u8;
    while i < 8_u8 {
        let z = {re: x.re + (i as f64)*incr, im: x.im};
        if mb(z) {
            rv += 1_u8 << (7_u8 - i);
        }
        i += 1_u8;
    }
    rv
}

fn chanmb(i: uint, size: uint, ch: comm::chan<line>) -> ()
{
    let crv = [];
    let incr = 2./(size as f64);
    let y = incr*(i as f64) - 1.;
    let xincr = 8.*incr;
    uint::range(0_u, size/8_u) {
        |j|
        let x = {re: xincr*(j as f64) - 1.5, im: y};
        crv += [fillbyte(x, incr)];
    };
    comm::send(ch, {i:i, b:crv});
}

fn writer(writech: comm::chan<comm::chan<line>>, size: uint)
{
    let p: comm::port<line> = comm::port();
    let ch = comm::chan(p);
    comm::send(writech, ch);
    let cout = std::io::stdout();
    cout.write_line("P4");
    cout.write_line(#fmt("%u %u", size, size));
    let lines = std::map::new_uint_hash();
    let done = 0_u;
    let i = 0_u;
    while i < size {
        let aline = comm::recv(p);
        if aline.i == done {
            #debug("W %u", aline.i);
            cout.write(aline.b);
            done += 1_u;
            let prev = done;
            while prev <= i {
                if lines.contains_key(prev) {
                    #debug("WS %u", prev);
                    cout.write(lines.get(prev));
                    done += 1_u;
                    lines.remove(prev);
                    prev += 1_u;
                }
                else {
                    break
                }
            };
        }
        else {
            #debug("S %u", aline.i);
            lines.insert(aline.i, aline.b);
        };
        i += 1_u;
    }
}

fn main(argv: [str])
{
    let size = if vec::len(argv) < 2_u {
        80u
    }
    else {
        uint::from_str(argv[1])
    };
    let yieldevery = if vec::len(argv) < 3_u {
        10_u
    }
    else {
        uint::from_str(argv[2])
    };
    let writep = comm::port();
    let writech = comm::chan(writep);
    task::spawn {
        || writer(writech, size);
    };
    let ch = comm::recv(writep);
    uint::range(0_u, size) {
        |j| task::spawn {
            || chanmb(j, size, ch);
        };
        if j % yieldevery == 0_u {
            #debug("Y %u", j);
            task::yield();
        };
    };
}
<commit_msg>add third arg for output path, default to no output<commit_after>//  based on:
//  http://shootout.alioth.debian.org/
//   u64q/program.php?test=mandelbrot&lang=python3&id=2
//
//  takes 3 optional args:
//   square image size, defaults to 80_u
//   yield frequency, defaults to 10_u (yield every 10 spawns)
//   output path, default is "" (no output), "-" means stdout
//
//  in the shootout, they use 16000 as image size
//  yield frequency doesn't seem to have much effect
//
//  writes pbm image to output path

use std;
import std::io::writer_util;

type cmplx = {re: f64, im: f64};
type line = {i: uint, b: [u8]};

impl arith for cmplx {
    fn *(x: cmplx) -> cmplx {
        {re: self.re*x.re - self.im*x.im, im: self.re*x.im + self.im*x.re}
    }

    fn +(x: cmplx) -> cmplx {
        {re: self.re + x.re, im: self.im + x.im}
    }
}

pure fn cabs(x: cmplx) -> f64
{
    x.re*x.re + x.im*x.im
}

fn mb(x: cmplx) -> bool
{
    let z = {re: 0., im: 0.};
    let i = 0;
    let in = true;
    while i < 50 {
        z = z*z + x;
        if cabs(z) >= 4. {
            in = false;
            break;
        }
        i += 1;
    }
    in
}

fn fillbyte(x: cmplx, incr: f64) -> u8 {
    let rv = 0_u8;
    let i = 0_u8;
    while i < 8_u8 {
        let z = {re: x.re + (i as f64)*incr, im: x.im};
        if mb(z) {
            rv += 1_u8 << (7_u8 - i);
        }
        i += 1_u8;
    }
    rv
}

fn chanmb(i: uint, size: uint, ch: comm::chan<line>) -> ()
{
    let crv = [];
    let incr = 2./(size as f64);
    let y = incr*(i as f64) - 1.;
    let xincr = 8.*incr;
    uint::range(0_u, size/8_u) {
        |j|
        let x = {re: xincr*(j as f64) - 1.5, im: y};
        crv += [fillbyte(x, incr)];
    };
    comm::send(ch, {i:i, b:crv});
}

type devnull = {dn: int};

impl of std::io::writer for devnull {
    fn write(_b: [const u8]) {}
    fn seek(_i: int, _s: std::io::seek_style) {}
    fn tell() -> uint {0_u}
    fn flush() -> int {0}
}

fn writer(path: str, writech: comm::chan<comm::chan<line>>, size: uint)
{
    let p: comm::port<line> = comm::port();
    let ch = comm::chan(p);
    comm::send(writech, ch);
    let cout: std::io::writer = alt path {
        "" {
            {dn: 0} as std::io::writer
        }
        "-" {
            std::io::stdout()
        }
        _ {
            result::get(
                std::io::file_writer(path,
                [std::io::create, std::io::truncate]))
        }
    };
    cout.write_line("P4");
    cout.write_line(#fmt("%u %u", size, size));
    let lines = std::map::new_uint_hash();
    let done = 0_u;
    let i = 0_u;
    while i < size {
        let aline = comm::recv(p);
        if aline.i == done {
            #debug("W %u", aline.i);
            cout.write(aline.b);
            done += 1_u;
            let prev = done;
            while prev <= i {
                if lines.contains_key(prev) {
                    #debug("WS %u", prev);
                    cout.write(lines.get(prev));
                    done += 1_u;
                    lines.remove(prev);
                    prev += 1_u;
                }
                else {
                    break
                }
            };
        }
        else {
            #debug("S %u", aline.i);
            lines.insert(aline.i, aline.b);
        };
        i += 1_u;
    }
}

fn main(argv: [str])
{
    let size = if vec::len(argv) < 2_u {
        80u
    }
    else {
        uint::from_str(argv[1])
    };
    let yieldevery = if vec::len(argv) < 3_u {
        10_u
    }
    else {
        uint::from_str(argv[2])
    };
    let path = if vec::len(argv) < 4_u {
        ""
    }
    else {
        argv[3]
    };
    let writep = comm::port();
    let writech = comm::chan(writep);
    task::spawn {
        || writer(path, writech, size);
    };
    let ch = comm::recv(writep);
    uint::range(0_u, size) {
        |j| task::spawn {
            || chanmb(j, size, ch);
        };
        if j % yieldevery == 0_u {
            #debug("Y %u", j);
            task::yield();
        };
    };
}
<|endoftext|>


<commit_before>// xfail-pretty
// xfail-win32
// Issue #2303

// This is the type with the questionable alignment
type inner = {
    c64: u64
};

// This is the type that contains the type with the
// questionable alignment, for testing
type outer = {
    c8: u8,
    t: inner
};

#[cfg(target_arch = "x86")]
fn main() {

    let x = {c8: 22u8, t: {c64: 44u64}};

    // Send it through the shape code
    let y = #fmt["%?", x];

    #debug("align inner = %?", sys::pref_align_of::<inner>()); // 8
    #debug("size outer = %?", sys::size_of::<outer>());   // 12
    #debug("y = %s", y);                                  // (22, (0))

    // per clang/gcc the alignment of `inner` is 4 on x86.
    // we say it's 8
    //assert sys::align_of::<inner>() == 4u; // fails

    // per clang/gcc the size of `outer` should be 12
    // because `inner`s alignment was 4.
    // LLVM packs the struct the way clang likes, despite
    // our intents regarding the alignment of `inner` and
    // we end up with the same size `outer` as clang
    assert sys::size_of::<outer>() == 12u; // passes

    // But now our shape code doesn't find the inner struct
    // We print (22, (0))
    assert y == "(22, (44))"; // fails
}

#[cfg(target_arch = "x86_64")]
fn main() { }
<commit_msg>test: Enable an assert in run-pass/rec-align-32-bit.rs<commit_after>// xfail-pretty
// xfail-win32
// Issue #2303

#[abi = "rust-intrinsic"]
native mod rusti {
    fn pref_align_of<T>() -> uint;
    fn min_align_of<T>() -> uint;
}

// This is the type with the questionable alignment
type inner = {
    c64: u64
};

// This is the type that contains the type with the
// questionable alignment, for testing
type outer = {
    c8: u8,
    t: inner
};

#[cfg(target_arch = "x86")]
fn main() {

    let x = {c8: 22u8, t: {c64: 44u64}};

    // Send it through the shape code
    let y = #fmt["%?", x];

    #debug("align inner = %?", rusti::min_align_of::<inner>());
    #debug("size outer = %?", sys::size_of::<outer>());
    #debug("y = %s", y);

    // per clang/gcc the alignment of `inner` is 4 on x86.
    assert rusti::min_align_of::<inner>() == 4u;

    // per clang/gcc the size of `outer` should be 12
    // because `inner`s alignment was 4.
    assert sys::size_of::<outer>() == 12u;

    assert y == "(22, (44))";
}

#[cfg(target_arch = "x86_64")]
fn main() { }
<|endoftext|>


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

const x: () = {
    return; //~ ERROR return statement outside of function body
};

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Changes for chapter 2.9, Match<commit_after><|endoftext|>


<commit_before><commit_msg>Add test for Issue 2823<commit_after>struct C {
    x: int,
    drop {
        #error("dropping: %?", self.x);
    }
}

fn main() {
    let c = C{ x: 2};
    let d = copy c; //~ ERROR copying a noncopyable value
    #error("%?", d.x);
}<|endoftext|>


<commit_before><commit_msg>day 5 solved.<commit_after>use std::collections::HashMap;
use std::io::prelude::*;
use std::fs::File;
use std::path::Path;

fn main() {
    let mut f = File::open(Path::new("/Users/PetarV/rust-proj/advent-of-rust/target/input.txt"))
    	.ok()
    	.expect("Failed to open the input file!");

	let mut input = String::new();
	f.read_to_string(&mut input)
		.ok()
		.expect("Failed to read from the input file!");

    let vowels = ['a', 'e', 'i', 'o', 'u'];
    let illegal = ["ab", "cd", "pq", "xy"];

    let ret = input.lines().fold(0, |acc, line| {
        let vowel_cnt = line.chars().fold(0, |acc, ch| {
            if vowels.contains(&ch) {
                acc + 1
            } else {
                acc
            }
        });

        let has_twice = line.chars().collect::<Vec<_>>()
            .windows(2)
            .fold(false, |acc, win| {
                acc || win[0] == win[1]
            });

        let has_illegal = illegal.iter().fold(false, |acc, ill| {
            acc || line.contains(ill)
        });

        if vowel_cnt >= 3 && has_twice && !has_illegal {
            acc + 1
        } else {
            acc
        }
    });

    println!("There are {} nice strings.", ret);

    let ret = input.lines().fold(0, |acc, line| {
        let mut hmap = HashMap::new();

        let cond1 = line.chars().collect::<Vec<_>>()
            .windows(2).enumerate()
            .fold(false, |acc, (i, win)| {
                acc || if hmap.contains_key(win) {
                    hmap[win] != i - 1
                } else {
                    hmap.insert(win.to_vec(), i);
                    false
                }
            });

        let cond2 = line.chars().collect::<Vec<_>>().windows(3)
            .fold(false, |acc, win| {
                acc || win[0] == win[2]
            });

        if cond1 && cond2 {
            acc + 1
        } else {
            acc
        }
    });

    println!("There are {} nice strings under the new rules.", ret);
}<|endoftext|>


<commit_before><commit_msg>Remove trailing space<commit_after><|endoftext|>


<commit_before>use std::rc::Rc;

use gtk::{DrawingArea, WidgetExt};

use app::AppContextPointer;

mod callbacks;

pub fn set_up_hodograph_area(hodo_area: &DrawingArea, app_context: &AppContextPointer) {

    hodo_area.set_hexpand(true);
    hodo_area.set_vexpand(true);

    let ac = Rc::clone(app_context);
    hodo_area.connect_draw(move |_da, cr| callbacks::draw_hodo(cr, &ac));
}
<commit_msg>Get ready to implement pan and zoom on hodographs.<commit_after>use std::rc::Rc;

use gdk::EventMask;
use gtk::prelude::*;
use gtk::DrawingArea;

use app::AppContextPointer;

mod callbacks;

pub fn set_up_hodograph_area(hodo_area: &DrawingArea, app_context: &AppContextPointer) {

    hodo_area.set_hexpand(true);
    hodo_area.set_vexpand(true);

    let ac = Rc::clone(app_context);
    hodo_area.connect_draw(move |_da, cr| callbacks::draw_hodo(cr, &ac));

    hodo_area.add_events(
        (EventMask::SCROLL_MASK | EventMask::BUTTON_PRESS_MASK | EventMask::BUTTON_RELEASE_MASK |
             EventMask::POINTER_MOTION_HINT_MASK |
             EventMask::POINTER_MOTION_MASK | EventMask::LEAVE_NOTIFY_MASK |
             EventMask::KEY_RELEASE_MASK | EventMask::KEY_PRESS_MASK)
            .bits() as i32,
    );
}
<|endoftext|>


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

trait Trait {
        fn method(self) -> int;
}

struct Wrapper<T> {
        field: T
}

impl<'a, T> Trait for &'a Wrapper<T> where &'a T: Trait {
    fn method(self) -> int {
        let r: &'a T = &self.field;
        Trait::method(r); // these should both work
        r.method()
    }
}

fn main() {}
<|endoftext|>


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

use std::cell::RefCell;
use std::rc::Rc;

pub struct Callbacks {
    callbacks: Vec<Rc<RefCell<FnMut(i32)>>>,
}

impl Callbacks {
    pub fn register<F: FnMut(i32)+'static>(&mut self, callback: F) {
        self.callbacks.push(Rc::new(RefCell::new(callback)));
    }
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>[No-auto] bin/core/diagnostics: Fix Clippy warnings<commit_after><|endoftext|>


<commit_before><commit_msg>Remove unused code<commit_after><|endoftext|>


<commit_before>use alloc::boxed::*;

use string::*;
use vec::Vec;

use event::*;

use orbital::*;
use graphics::color::Color;

use rand_old::*;

static mut window: *mut ConsoleWindow = 0 as *mut ConsoleWindow;

/// Create a new console window
pub fn console_window() -> &'static mut ConsoleWindow {
    unsafe {
        if window as usize == 0 {
            window = Box::into_raw(ConsoleWindow::new((rand() % 400 + 50) as isize,
                                          (rand() % 300 + 50) as isize,
                                          640,
                                          480,
                                          "Console"));
            (*window).sync();
        }
        &mut *window
    }
}

/// Initialize console
pub unsafe fn console_init() {
    window = 0 as *mut ConsoleWindow;
}

/// Destroy the console
pub unsafe fn console_destroy() {
    if window as usize > 0 {
        drop(Box::from_raw(window));
        window = 0 as *mut ConsoleWindow;
    }
}

/// Set the title of the console window
// TODO: Move this to a `Window` trait?
pub fn console_title(title: &str) {
    console_window().set_title(title);
}

/// Print to console
#[macro_export]
macro_rules! print {
    ($($arg:tt)*) => ({
        console_window().print(&format!($($arg)*), $crate::Color::rgba(224, 224, 224, 255));
        console_window().sync();
    });
}

/// Print to console with color
#[macro_export]
macro_rules! print_color {
    ($color:expr, $($arg:tt)*) => ({
        console_window().print(&format!($($arg)*), $color);
        console_window().sync();
    });
}

/// Print new line to console
#[macro_export]
macro_rules! println {
    ($($arg:tt)*) => ({
        print!($($arg)*);
        print!("\n");
    });
}

/// Print new line to console with color
#[macro_export]
macro_rules! println_color {
    ($color:expr, $($arg:tt)*) => ({
        print_color!($color, $($arg)*);
        print_color!($color, "\n");
    });
}

/// Read a line from the console
#[macro_export]
macro_rules! readln {
    () => (console_window().read());
}

/// A console char
pub struct ConsoleChar {
    /// The char
    character: char,
    /// The color
    color: Color,
}

/// A console window
pub struct ConsoleWindow {
    /// The window
    pub window: Box<Window>,
    /// The char buffer
    pub output: Vec<ConsoleChar>,
    /// The current input command
    pub command: String,
    /// Offset
    pub offset: usize,
    /// Scroll distance x
    pub scroll_x: isize,
    /// Scroll distance y
    pub scroll_y: isize,
    /// Wrap the text, if true
    pub wrap: bool,
}

impl ConsoleWindow {
    /// Create a new console window
    pub fn new(x: isize, y: isize, w: usize, h: usize, title: &str) -> Box<Self> {
        box ConsoleWindow {
            window: Window::new(x, y, w, h, title).unwrap(),
            output: Vec::new(),
            command: String::new(),
            offset: 0,
            scroll_x: 0,
            scroll_y: 0,
            wrap: true,
        }
    }

    /// Set the window title
    pub fn set_title(&mut self, title: &str) {
        //TODO THIS IS A HACK, should use self.window.setTitle(title);
        self.window = Window::new(self.window.x(),
                                  self.window.y(),
                                  self.window.width(),
                                  self.window.height(),
                                  title).unwrap();
    }

    /// Poll the window
    pub fn poll(&mut self) -> Option<Event> {
        self.window.poll()
    }

    /// Print to the window
    pub fn print(&mut self, string: &str, color: Color) {
        for c in string.chars() {
            self.output.push(ConsoleChar {
                character: c,
                color: color,
            });
        }
    }

    /// Read input
    pub fn read(&mut self) -> Option<String> {
        while let Some(event) = self.poll() {
            match event.to_option() {
                EventOption::Key(key_event) => {
                    if key_event.pressed {
                        match key_event.scancode {
                            K_BKSP => if self.offset > 0 {
                                self.command = self.command[0 .. self.offset - 1].to_string() +
                                               &self.command[self.offset .. self.command.len()];
                                self.offset -= 1;
                            },
                            K_DEL => if self.offset < self.command.len() {
                                self.command =
                                    self.command[0 .. self.offset].to_string() +
                                    &self.command[self.offset + 1 .. self.command.len() - 1];
                            },
                            K_HOME => self.offset = 0,
                            K_UP => {
                                //self.command = self.last_command.clone();
                                //self.offset = self.command.len();
                            }
                            K_LEFT => if self.offset > 0 {
                                self.offset -= 1;
                            },
                            K_RIGHT => if self.offset < self.command.len() {
                                self.offset += 1;
                            },
                            K_END => self.offset = self.command.len(),
                            K_DOWN => {
                                //self.command.clear()
                                //self.offset = self.command.len();
                            }
                            _ => match key_event.character {
                                '\x00' => (),
                                '\n' => {
                                    let command = self.command.clone();
                                    self.command.clear();
                                    self.offset = 0;
                                    return Some(command);
                                }
                                '\x1B' => break,
                                _ => {
                                    self.command = self.command[0 .. self.offset].to_string() +
                                                   &key_event.character.to_string() +
                                                   &self.command[self.offset .. self.command.len()];
                                    self.offset += 1;
                                }
                            },
                        }
                    }
                    self.sync();
                }
                _ => (),
            }
        }

        return None;
    }

    /// Redraw the window
    pub fn sync(&mut self) {
        let scroll_x = self.scroll_x;
        let scroll_y = self.scroll_y;

        let mut col = -scroll_x;
        let cols = self.window.width() as isize / 8;
        let mut row = -scroll_y;
        let rows = self.window.height() as isize / 16;

        {
            self.window.set(Color::BLACK);

            for c in self.output.iter() {
                if self.wrap && col >= cols {
                    col = -scroll_x;
                    row += 1;
                }

                if c.character == '\n' {
                    col = -scroll_x;
                    row += 1;
                } else if c.character == '\t' {
                    col += 8 - col % 8;
                } else {
                    if col >= 0 && col < cols && row >= 0 && row < rows {
                        self.window.char(8 * col, 16 * row, c.character, c.color);
                    }
                    col += 1;
                }
            }

            if col > -scroll_x {
                col = -scroll_x;
                row += 1;
            }

            if col >= 0 && col < cols && row >= 0 && row < rows {
                self.window.char(8 * col, 16 * row, '#', Color::WHITE);
                col += 2;
            }

            let mut i = 0;
            for c in self.command.chars() {
                if self.wrap && col >= cols {
                    col = -scroll_x;
                    row += 1;
                }

                if self.offset == i && col >= 0 && col < cols && row >= 0 && row < rows {
                    self.window.char(8 * col, 16 * row, '_', Color::WHITE);
                }

                if c == '\n' {
                    col = -scroll_x;
                    row += 1;
                } else if c == '\t' {
                    col += 8 - col % 8;
                } else {
                    if col >= 0 && col < cols && row >= 0 && row < rows {
                        self.window.char(8 * col, 16 * row, c, Color::WHITE);
                    }
                    col += 1;
                }

                i += 1;
            }

            if self.wrap && col >= cols {
                col = -scroll_x;
                row += 1;
            }

            if self.offset == i && col >= 0 && col < cols && row >= 0 && row < rows {
                self.window.char(8 * col, 16 * row, '_', Color::WHITE);
            }
        }

        self.window.sync();

        if row >= rows {
            self.scroll_y += row - rows + 1;

            self.sync();
        }
    }
}
<commit_msg>more if letting<commit_after>use alloc::boxed::*;

use string::*;
use vec::Vec;

use event::*;

use orbital::*;
use graphics::color::Color;

use rand_old::*;

static mut window: *mut ConsoleWindow = 0 as *mut ConsoleWindow;

/// Create a new console window
pub fn console_window() -> &'static mut ConsoleWindow {
    unsafe {
        if window as usize == 0 {
            window = Box::into_raw(ConsoleWindow::new((rand() % 400 + 50) as isize,
                                   (rand() % 300 + 50) as isize,
                                   640,
                                   480,
                                   "Console"));
            (*window).sync();
        }
        &mut *window
    }
}

/// Initialize console
pub unsafe fn console_init() {
    window = 0 as *mut ConsoleWindow;
}

/// Destroy the console
pub unsafe fn console_destroy() {
    if window as usize > 0 {
        drop(Box::from_raw(window));
        window = 0 as *mut ConsoleWindow;
    }
}

/// Set the title of the console window
// TODO: Move this to a `Window` trait?
pub fn console_title(title: &str) {
    console_window().set_title(title);
}

/// Print to console
#[macro_export]
macro_rules! print {
    ($($arg:tt)*) => ({
        console_window().print(&format!($($arg)*), $crate::Color::rgba(224, 224, 224, 255));
        console_window().sync();
    });
}

/// Print to console with color
#[macro_export]
macro_rules! print_color {
    ($color:expr, $($arg:tt)*) => ({
        console_window().print(&format!($($arg)*), $color);
        console_window().sync();
    });
}

/// Print new line to console
#[macro_export]
macro_rules! println {
    ($($arg:tt)*) => ({
        print!($($arg)*);
        print!("\n");
    });
}

/// Print new line to console with color
#[macro_export]
macro_rules! println_color {
    ($color:expr, $($arg:tt)*) => ({
        print_color!($color, $($arg)*);
        print_color!($color, "\n");
    });
}

/// Read a line from the console
#[macro_export]
macro_rules! readln {
    () => (console_window().read());
}

/// A console char
pub struct ConsoleChar {
    /// The char
    character: char,
    /// The color
    color: Color,
}

/// A console window
pub struct ConsoleWindow {
    /// The window
    pub window: Box<Window>,
    /// The char buffer
    pub output: Vec<ConsoleChar>,
    /// The current input command
    pub command: String,
    /// Offset
    pub offset: usize,
    /// Scroll distance x
    pub scroll_x: isize,
    /// Scroll distance y
    pub scroll_y: isize,
    /// Wrap the text, if true
    pub wrap: bool,
}

impl ConsoleWindow {
    /// Create a new console window
    pub fn new(x: isize, y: isize, w: usize, h: usize, title: &str) -> Box<Self> {
        box ConsoleWindow {
            window: Window::new(x, y, w, h, title).unwrap(),
            output: Vec::new(),
            command: String::new(),
            offset: 0,
            scroll_x: 0,
            scroll_y: 0,
            wrap: true,
        }
    }

    /// Set the window title
    pub fn set_title(&mut self, title: &str) {
        //TODO THIS IS A HACK, should use self.window.setTitle(title);
        self.window = Window::new(self.window.x(),
                                  self.window.y(),
                                  self.window.width(),
                                  self.window.height(),
                                  title).unwrap();
    }

    /// Poll the window
    pub fn poll(&mut self) -> Option<Event> {
        self.window.poll()
    }

    /// Print to the window
    pub fn print(&mut self, string: &str, color: Color) {
        for c in string.chars() {
            self.output.push(ConsoleChar {
                character: c,
                color: color,
            });
        }
    }

    /// Read input
    pub fn read(&mut self) -> Option<String> {
        while let Some(event) = self.poll() {
            if let EventOption::Key(key_event) = event.to_option() {
                if key_event.pressed {
                    match key_event.scancode {
                        K_BKSP => if self.offset > 0 {
                            self.command = self.command[0 .. self.offset - 1].to_string() +
                                           &self.command[self.offset .. self.command.len()];
                            self.offset -= 1;
                        },
                        K_DEL => if self.offset < self.command.len() {
                            self.command =
                                self.command[0 .. self.offset].to_string() +
                                &self.command[self.offset + 1 .. self.command.len() - 1];
                        },
                        K_HOME => self.offset = 0,
                        K_UP => {
                            //self.command = self.last_command.clone();
                            //self.offset = self.command.len();
                        }
                        K_LEFT => if self.offset > 0 {
                            self.offset -= 1;
                        },
                        K_RIGHT => if self.offset < self.command.len() {
                            self.offset += 1;
                        },
                        K_END => self.offset = self.command.len(),
                        K_DOWN => {
                            //self.command.clear()
                            //self.offset = self.command.len();
                        }
                        _ => match key_event.character {
                            '\x00' => (),
                            '\n' => {
                                let command = self.command.clone();
                                self.command.clear();
                                self.offset = 0;
                                return Some(command);
                            }
                            '\x1B' => break,
                            _ => {
                                self.command = self.command[0 .. self.offset].to_string() +
                                               &key_event.character.to_string() +
                                               &self.command[self.offset .. self.command.len()];
                                self.offset += 1;
                            }
                        },
                    }
                }
                self.sync();
            }
        }

        return None;
    }

    /// Redraw the window
    pub fn sync(&mut self) {
        let scroll_x = self.scroll_x;
        let scroll_y = self.scroll_y;

        let mut col = -scroll_x;
        let cols = self.window.width() as isize / 8;
        let mut row = -scroll_y;
        let rows = self.window.height() as isize / 16;

        {
            self.window.set(Color::BLACK);

            for c in self.output.iter() {
                if self.wrap && col >= cols {
                    col = -scroll_x;
                    row += 1;
                }

                if c.character == '\n' {
                    col = -scroll_x;
                    row += 1;
                } else if c.character == '\t' {
                    col += 8 - col % 8;
                } else {
                    if col >= 0 && col < cols && row >= 0 && row < rows {
                        self.window.char(8 * col, 16 * row, c.character, c.color);
                    }
                    col += 1;
                }
            }

            if col > -scroll_x {
                col = -scroll_x;
                row += 1;
            }

            if col >= 0 && col < cols && row >= 0 && row < rows {
                self.window.char(8 * col, 16 * row, '#', Color::WHITE);
                col += 2;
            }

            let mut i = 0;
            for c in self.command.chars() {
                if self.wrap && col >= cols {
                    col = -scroll_x;
                    row += 1;
                }

                if self.offset == i && col >= 0 && col < cols && row >= 0 && row < rows {
                    self.window.char(8 * col, 16 * row, '_', Color::WHITE);
                }

                if c == '\n' {
                    col = -scroll_x;
                    row += 1;
                } else if c == '\t' {
                    col += 8 - col % 8;
                } else {
                    if col >= 0 && col < cols && row >= 0 && row < rows {
                        self.window.char(8 * col, 16 * row, c, Color::WHITE);
                    }
                    col += 1;
                }

                i += 1;
            }

            if self.wrap && col >= cols {
                col = -scroll_x;
                row += 1;
            }

            if self.offset == i && col >= 0 && col < cols && row >= 0 && row < rows {
                self.window.char(8 * col, 16 * row, '_', Color::WHITE);
            }
        }

        self.window.sync();

        if row >= rows {
            self.scroll_y += row - rows + 1;

            self.sync();
        }
    }
}
<|endoftext|>


<commit_before>use super::prelude::v1::*;
use super::hash::*;
use core::mem;

/// An linked list (used for entries)
pub enum LinkedList<T> {
    Elem(T, Box<LinkedList<T>>),
    Nil,
}

impl<T> LinkedList<T> {
    /// Follow
    pub fn follow(&self) -> Option<&Self> {
        use self::LinkedList::*;
        match *self {
            Elem(_, box ref l) => {
                Some(l)
            },
            Nil => {
                None
            },
        }
    }

    /// Follow mutable
    pub fn follow_mut(&mut self) -> Option<&mut Self> {
        use self::LinkedList::*;
        match *self {
            Elem(_, box ref mut l) => {
                Some(l)
            },
            Nil => {
                None
            },
        }
    }

    /// Push (consumes the list)
    pub fn push(self, elem: T) -> Self {
        LinkedList::Elem(elem, Box::new(self))
    }
}

/// A entry in the hash map
pub struct Entry<K, V> {
    data: LinkedList<(K, V)>,
}

impl<K: PartialEq<K>, V> Entry<K, V> {
    /// Create new
    pub fn new(key: K, value: V) -> Self {
        Entry {
            data: LinkedList::Elem((key, value), Box::new(LinkedList::Nil)),
        }
    }

    /// Get value from entry
    pub fn get(&self, key: &K) -> Option<&V> {
        let mut cur = self.data.follow();

        loop {
            cur = match cur {
                Some(&LinkedList::Elem((ref k, ref v), ref l)) => {
                    if key == k {
                        return Some(v);
                    } else {
                        l.follow()
                    }
                },
                Some(&LinkedList::Nil) | None => {
                    return None;
                },
            }
        }

    }

    /// Get value mutable from entry
    pub fn get_mut(&mut self, key: &K) -> Option<&mut V> {

        let mut cur = self.data.follow_mut();

        loop {
            cur = match cur {
                Some(x) => match *x {
                    LinkedList::Elem((ref k, ref mut v), ref mut l) => {
                        if key == k {
                            return Some(v);
                        } else {
                            l.follow_mut()
                        }
                    },
                    LinkedList::Nil => {
                        return None;
                    },
                },
                None => {
                    return None;
                },
            }

        }
    }

    /// Push to the list (consumes the entry returning the new one)
    pub fn push(self, key: K, value: V) -> Self {
        Entry {
            data: self.data.push((key, value)),
        }
    }
}

/// A hashtable
pub struct HashMap<K, V> {
    data: [Entry<K, V>; 256],
}

impl<K: Hash + PartialEq, V> HashMap<K, V> {
    /// Get value
    pub fn get(&self, key: &K) -> Option<&V> {
        let mut s = Djb2::new();
        key.hash(&mut s);
        self.data[(s.finish() % 256) as usize].get(key)
    }
    /// Get value mutable
    pub fn get_mut(&mut self, key: &K) -> Option<&mut V> {
        let mut s = Djb2::new();
        key.hash(&mut s);
        self.data[(s.finish() % 256) as usize].get_mut(key)
    }
    /// Set value
    pub fn set(&mut self, key: K, val: V) {
        let mut s = Djb2::new();
        key.hash(&mut s);
        match self.get_mut(&key) {
            Some(k) => {
                *k = val;
                return;
            },
            _ => {}
        }
        let n = (s.finish() % 256) as usize;
        mem::replace(&mut self.data[n], self.data[n].push(key, val));
    }
}

/// DJB2 hashing
pub struct Djb2 {
    state: u64,
}

impl Djb2 {
    /// Create new DJB2 hasher
    pub fn new() -> Self {
        Djb2 {
            state: 5381,
        }
    }
}

impl Hasher for Djb2 {
    fn finish(&self) -> u64 {
        self.state
    }
    fn write(&mut self, bytes: &[u8]) {
        for &b in bytes {
            self.state = ((self.state << 5) + self.state) + b as u64;
        }
    }
}
<commit_msg>Fix the last error<commit_after>use super::prelude::v1::*;
use super::hash::*;
use core::mem;

/// An linked list (used for entries)
#[derive(Clone)]
pub enum LinkedList<T: Clone> {
    Elem(T, Box<LinkedList<T>>),
    Nil,
}

impl<T: Clone> LinkedList<T> {
    /// Follow
    pub fn follow(&self) -> Option<&Self> {
        use self::LinkedList::*;
        match *self {
            Elem(_, box ref l) => {
                Some(l)
            },
            Nil => {
                None
            },
        }
    }

    /// Follow mutable
    pub fn follow_mut(&mut self) -> Option<&mut Self> {
        use self::LinkedList::*;
        match *self {
            Elem(_, box ref mut l) => {
                Some(l)
            },
            Nil => {
                None
            },
        }
    }

    /// Push (consumes the list)
    pub fn push(self, elem: T) -> Self {
        LinkedList::Elem(elem, Box::new(self))
    }
}

/// A entry in the hash map
#[derive(Clone)]
pub struct Entry<K: Clone, V: Clone> {
    data: LinkedList<(K, V)>,
}

impl<K: PartialEq<K> + Clone, V: Clone> Entry<K, V> {
    /// Create new
    pub fn new(key: K, value: V) -> Self {
        Entry {
            data: LinkedList::Elem((key, value), Box::new(LinkedList::Nil)),
        }
    }

    /// Get value from entry
    pub fn get(&self, key: &K) -> Option<&V> {
        let mut cur = self.data.follow();

        loop {
            cur = match cur {
                Some(&LinkedList::Elem((ref k, ref v), ref l)) => {
                    if key == k {
                        return Some(v);
                    } else {
                        l.follow()
                    }
                },
                Some(&LinkedList::Nil) | None => {
                    return None;
                },
            }
        }

    }

    /// Get value mutable from entry
    pub fn get_mut(&mut self, key: &K) -> Option<&mut V> {

        let mut cur = self.data.follow_mut();

        loop {
            cur = match cur {
                Some(x) => match *x {
                    LinkedList::Elem((ref k, ref mut v), ref mut l) => {
                        if key == k {
                            return Some(v);
                        } else {
                            l.follow_mut()
                        }
                    },
                    LinkedList::Nil => {
                        return None;
                    },
                },
                None => {
                    return None;
                },
            }

        }
    }

    /// Push to the list (consumes the entry returning the new one)
    pub fn push(self, key: K, value: V) -> Self {
        Entry {
            data: self.data.push((key, value)),
        }
    }
}

/// A hashtable
pub struct HashMap<K: Clone, V: Clone> {
    data: [Entry<K, V>; 256],
}

impl<K: Hash + PartialEq + Clone, V: Clone> HashMap<K, V> {
    /// Get value
    pub fn get(&self, key: &K) -> Option<&V> {
        let mut s = Djb2::new();
        key.hash(&mut s);
        self.data[(s.finish() % 256) as usize].get(key)
    }
    /// Get value mutable
    pub fn get_mut(&mut self, key: &K) -> Option<&mut V> {
        let mut s = Djb2::new();
        key.hash(&mut s);
        self.data[(s.finish() % 256) as usize].get_mut(key)
    }
    /// Set value
    pub fn set(&mut self, key: K, val: V) {
        let mut s = Djb2::new();
        key.hash(&mut s);
        match self.get_mut(&key) {
            Some(k) => {
                *k = val;
                return;
            },
            _ => {}
        }
        let n = (s.finish() % 256) as usize;
        self.data[n] = self.data[n].clone().push(key, val);
    }
}

/// DJB2 hashing
pub struct Djb2 {
    state: u64,
}

impl Djb2 {
    /// Create new DJB2 hasher
    pub fn new() -> Self {
        Djb2 {
            state: 5381,
        }
    }
}

impl Hasher for Djb2 {
    fn finish(&self) -> u64 {
        self.state
    }
    fn write(&mut self, bytes: &[u8]) {
        for &b in bytes {
            self.state = ((self.state << 5) + self.state) + b as u64;
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Solved "(5 kyu) RGB To Hex Conversion.rs" in Rust<commit_after><|endoftext|>


<commit_before><commit_msg>Add keyword parsing tests<commit_after>extern crate robin_core;

extern crate nom;

#[cfg(test)]
mod parser_tests {
    use nom::IResult;

    use robin_core::parser::expression;
    use robin_core::ast::Expression;

    #[test]
    fn parse_an_identifier_bool_lookalike_suffix() {
        assert_eq!(expression::expression_literal(b"truedog"),
                   IResult::Done(&b""[..], Expression::Identifier("truedog".to_string())));
    }

    #[test]
    fn parse_an_identifier_bool_lookalike_prefix() {
        assert_eq!(expression::expression_literal(b"falsecat"),
                   IResult::Done(&b""[..], Expression::Identifier("falsecat".to_string())));
    }
}<|endoftext|>


<commit_before><commit_msg>Remove unnecessary 'mut' keyword<commit_after><|endoftext|>


<commit_before><commit_msg>Add a test for unique boxes containing shared boxes<commit_after>use std;
import std::sys::rustrt::refcount;

fn main() {
    let i = ~@1;
    let j = ~@2;
    let rc1 = refcount(*i);
    let j = i;
    let rc2 = refcount(*i);
    log_err #fmt("rc1: %u rc2: %u", rc1, rc2);
    assert rc1 + 1u == rc2;
}<|endoftext|>


<commit_before><commit_msg>Fixed daemon<commit_after><|endoftext|>