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

//! Calculation and management of a Strict Version Hash for crates
//!
//! # Today's ABI problem
//!
//! In today's implementation of rustc, it is incredibly difficult to achieve
//! forward binary compatibility without resorting to C-like interfaces. Within
//! rust code itself, abi details such as symbol names suffer from a variety of
//! unrelated factors to code changing such as the "def id drift" problem. This
//! ends up yielding confusing error messages about metadata mismatches and
//! such.
//!
//! The core of this problem is when an upstream dependency changes and
//! downstream dependents are not recompiled. This causes compile errors because
//! the upstream crate's metadata has changed but the downstream crates are
//! still referencing the older crate's metadata.
//!
//! This problem exists for many reasons, the primary of which is that rust does
//! not currently support forwards ABI compatibility (in place upgrades of a
//! crate).
//!
//! # SVH and how it alleviates the problem
//!
//! With all of this knowledge on hand, this module contains the implementation
//! of a notion of a "Strict Version Hash" for a crate. This is essentially a
//! hash of all contents of a crate which can somehow be exposed to downstream
//! crates.
//!
//! This hash is currently calculated by just hashing the AST, but this is
//! obviously wrong (doc changes should not result in an incompatible ABI).
//! Implementation-wise, this is required at this moment in time.
//!
//! By encoding this strict version hash into all crate's metadata, stale crates
//! can be detected immediately and error'd about by rustc itself.
//!
//! # Relevant links
//!
//! Original issue: https://github.com/mozilla/rust/issues/10207

use std::fmt;
use std::hash::Hash;
use std::hash::sip::SipState;
use std::iter::range_step;
use syntax::ast;

#[deriving(Clone, Eq)]
pub struct Svh {
    hash: StrBuf,
}

impl Svh {
    pub fn new(hash: &str) -> Svh {
        assert!(hash.len() == 16);
        Svh { hash: hash.to_strbuf() }
    }

    pub fn as_str<'a>(&'a self) -> &'a str {
        self.hash.as_slice()
    }

    pub fn calculate(krate: &ast::Crate) -> Svh {
        // FIXME: see above for why this is wrong, it shouldn't just hash the
        //        crate.  Fixing this would require more in-depth analysis in
        //        this function about what portions of the crate are reachable
        //        in tandem with bug fixes throughout the rest of the compiler.
        //
        //        Note that for now we actually exclude some top-level things
        //        from the crate like the CrateConfig/span. The CrateConfig
        //        contains command-line `--cfg` flags, so this means that the
        //        stage1/stage2 AST for libstd and such is different hash-wise
        //        when it's actually the exact same representation-wise.
        //
        //        As a first stab at only hashing the relevant parts of the
        //        AST, this only hashes the module/attrs, not the CrateConfig
        //        field.
        //
        // FIXME: this should use SHA1, not SipHash. SipHash is not built to
        //        avoid collisions.
        let mut state = SipState::new();
        krate.module.hash(&mut state);
        krate.attrs.hash(&mut state);

        let hash = state.result();
        return Svh {
            hash: range_step(0, 64, 4).map(|i| hex(hash >> i)).collect()
        };

        fn hex(b: u64) -> char {
            let b = (b & 0xf) as u8;
            let b = match b {
                0 .. 9 => '0' as u8 + b,
                _ => 'a' as u8 + b - 10,
            };
            b as char
        }
    }
}

impl fmt::Show for Svh {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.pad(self.as_str())
    }
}
<commit_msg>Teach SVH computation to ignore more implementation artifacts.<commit_after>// Copyright 2012-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.

//! Calculation and management of a Strict Version Hash for crates
//!
//! # Today's ABI problem
//!
//! In today's implementation of rustc, it is incredibly difficult to achieve
//! forward binary compatibility without resorting to C-like interfaces. Within
//! rust code itself, abi details such as symbol names suffer from a variety of
//! unrelated factors to code changing such as the "def id drift" problem. This
//! ends up yielding confusing error messages about metadata mismatches and
//! such.
//!
//! The core of this problem is when an upstream dependency changes and
//! downstream dependents are not recompiled. This causes compile errors because
//! the upstream crate's metadata has changed but the downstream crates are
//! still referencing the older crate's metadata.
//!
//! This problem exists for many reasons, the primary of which is that rust does
//! not currently support forwards ABI compatibility (in place upgrades of a
//! crate).
//!
//! # SVH and how it alleviates the problem
//!
//! With all of this knowledge on hand, this module contains the implementation
//! of a notion of a "Strict Version Hash" for a crate. This is essentially a
//! hash of all contents of a crate which can somehow be exposed to downstream
//! crates.
//!
//! This hash is currently calculated by just hashing the AST, but this is
//! obviously wrong (doc changes should not result in an incompatible ABI).
//! Implementation-wise, this is required at this moment in time.
//!
//! By encoding this strict version hash into all crate's metadata, stale crates
//! can be detected immediately and error'd about by rustc itself.
//!
//! # Relevant links
//!
//! Original issue: https://github.com/mozilla/rust/issues/10207

use std::fmt;
use std::hash::Hash;
use std::hash::sip::SipState;
use std::iter::range_step;
use syntax::ast;
use syntax::visit;

#[deriving(Clone, Eq)]
pub struct Svh {
    hash: StrBuf,
}

impl Svh {
    pub fn new(hash: &str) -> Svh {
        assert!(hash.len() == 16);
        Svh { hash: hash.to_strbuf() }
    }

    pub fn as_str<'a>(&'a self) -> &'a str {
        self.hash.as_slice()
    }

    pub fn calculate(krate: &ast::Crate) -> Svh {
        // FIXME (#14132): This is better than it used to be, but it still not
        // ideal. We now attempt to hash only the relevant portions of the
        // Crate AST as well as the top-level crate attributes. (However,
        // the hashing of the crate attributes should be double-checked
        // to ensure it is not incorporating implementation artifacts into
        // the hash that are not otherwise visible.)

        // FIXME: this should use SHA1, not SipHash. SipHash is not built to
        //        avoid collisions.
        let mut state = SipState::new();

        {
            let mut visit = svh_visitor::make(&mut state);
            visit::walk_crate(&mut visit, krate, ());
        }

        // FIXME (#14132): This hash is still sensitive to e.g. the
        // spans of the crate Attributes and their underlying
        // MetaItems; we should make ContentHashable impl for those
        // types and then use hash_content.  But, since all crate
        // attributes should appear near beginning of the file, it is
        // not such a big deal to be sensitive to their spans for now.
        krate.attrs.hash(&mut state);

        let hash = state.result();
        return Svh {
            hash: range_step(0, 64, 4).map(|i| hex(hash >> i)).collect()
        };

        fn hex(b: u64) -> char {
            let b = (b & 0xf) as u8;
            let b = match b {
                0 .. 9 => '0' as u8 + b,
                _ => 'a' as u8 + b - 10,
            };
            b as char
        }
    }
}

impl fmt::Show for Svh {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.pad(self.as_str())
    }
}

// FIXME (#14132): Even this SVH computation still has implementation
// artifacts: namely, the order of item declaration will affect the
// hash computation, but for many kinds of items the order of
// declaration should be irrelevant to the ABI.

mod svh_visitor {
    use syntax::ast;
    use syntax::ast::*;
    use syntax::codemap::Span;
    use syntax::parse::token;
    use syntax::print::pprust;
    use syntax::visit;
    use syntax::visit::{Visitor, FnKind};

    use std::hash::Hash;
    use std::hash::sip::SipState;

    pub struct StrictVersionHashVisitor<'a> {
        pub st: &'a mut SipState,
    }

    pub fn make<'a>(st: &'a mut SipState) -> StrictVersionHashVisitor<'a> {
        StrictVersionHashVisitor { st: st }
    }

    // To off-load the bulk of the hash-computation on deriving(Hash),
    // we define a set of enums corresponding to the content that our
    // crate visitor will encounter as it traverses the ast.
    //
    // The important invariant is that all of the Saw*Component enums
    // do not carry any Spans, Names, or Idents.
    //
    // Not carrying any Names/Idents is the important fix for problem
    // noted on PR #13948: using the ident.name as the basis for a
    // hash leads to unstable SVH, because ident.name is just an index
    // into intern table (i.e. essentially a random address), not
    // computed from the name content.
    //
    // With the below enums, the SVH computation is not sensitive to
    // artifacts of how rustc was invoked nor of how the source code
    // was laid out.  (Or at least it is *less* sensitive.)

    // This enum represents the different potential bits of code the
    // visitor could encounter that could affect the ABI for the crate,
    // and assigns each a distinct tag to feed into the hash computation.
    #[deriving(Hash)]
    enum SawAbiComponent<'a> {

        // FIXME (#14132): should we include (some function of)
        // ident.ctxt as well?
        SawIdent(token::InternedString),
        SawStructDef(token::InternedString),

        SawLifetimeRef(token::InternedString),
        SawLifetimeDecl(token::InternedString),

        SawMod,
        SawViewItem,
        SawForeignItem,
        SawItem,
        SawDecl,
        SawTy,
        SawGenerics,
        SawFn,
        SawTyMethod,
        SawTraitMethod,
        SawStructField,
        SawVariant,
        SawExplicitSelf,
        SawPath,
        SawOptLifetimeRef,
        SawBlock,
        SawPat,
        SawLocal,
        SawArm,
        SawExpr(SawExprComponent<'a>),
        SawStmt(SawStmtComponent),
    }

    /// SawExprComponent carries all of the information that we want
    /// to include in the hash that *won't* be covered by the
    /// subsequent recursive traversal of the expression's
    /// substructure by the visitor.
    ///
    /// We know every Expr_ variant is covered by a variant because
    /// `fn saw_expr` maps each to some case below.  Ensuring that
    /// each variant carries an appropriate payload has to be verified
    /// by hand.
    ///
    /// (However, getting that *exactly* right is not so important
    /// because the SVH is just a developer convenience; there is no
    /// guarantee of collision-freedom, hash collisions are just
    /// (hopefully) unlikely.)
    #[deriving(Hash)]
    pub enum SawExprComponent<'a> {

        SawExprLoop(Option<token::InternedString>),
        SawExprField(token::InternedString),
        SawExprBreak(Option<token::InternedString>),
        SawExprAgain(Option<token::InternedString>),

        SawExprVstore,
        SawExprBox,
        SawExprVec,
        SawExprCall,
        SawExprMethodCall,
        SawExprTup,
        SawExprBinary(ast::BinOp),
        SawExprUnary(ast::UnOp),
        SawExprLit(ast::Lit_),
        SawExprCast,
        SawExprIf,
        SawExprWhile,
        SawExprMatch,
        SawExprFnBlock,
        SawExprProc,
        SawExprBlock,
        SawExprAssign,
        SawExprAssignOp(ast::BinOp),
        SawExprIndex,
        SawExprPath,
        SawExprAddrOf(ast::Mutability),
        SawExprRet,
        SawExprInlineAsm(&'a ast::InlineAsm),
        SawExprStruct,
        SawExprRepeat,
        SawExprParen,
    }

    fn saw_expr<'a>(node: &'a Expr_) -> SawExprComponent<'a> {
        match *node {
            ExprVstore(..)           => SawExprVstore,
            ExprBox(..)              => SawExprBox,
            ExprVec(..)              => SawExprVec,
            ExprCall(..)             => SawExprCall,
            ExprMethodCall(..)       => SawExprMethodCall,
            ExprTup(..)              => SawExprTup,
            ExprBinary(op, _, _)     => SawExprBinary(op),
            ExprUnary(op, _)         => SawExprUnary(op),
            ExprLit(lit)             => SawExprLit(lit.node.clone()),
            ExprCast(..)             => SawExprCast,
            ExprIf(..)               => SawExprIf,
            ExprWhile(..)            => SawExprWhile,
            ExprLoop(_, id)          => SawExprLoop(id.map(content)),
            ExprMatch(..)            => SawExprMatch,
            ExprFnBlock(..)          => SawExprFnBlock,
            ExprProc(..)             => SawExprProc,
            ExprBlock(..)            => SawExprBlock,
            ExprAssign(..)           => SawExprAssign,
            ExprAssignOp(op, _, _)   => SawExprAssignOp(op),
            ExprField(_, id, _)      => SawExprField(content(id)),
            ExprIndex(..)            => SawExprIndex,
            ExprPath(..)             => SawExprPath,
            ExprAddrOf(m, _)         => SawExprAddrOf(m),
            ExprBreak(id)            => SawExprBreak(id.map(content)),
            ExprAgain(id)            => SawExprAgain(id.map(content)),
            ExprRet(..)              => SawExprRet,
            ExprInlineAsm(ref asm)   => SawExprInlineAsm(asm),
            ExprStruct(..)           => SawExprStruct,
            ExprRepeat(..)           => SawExprRepeat,
            ExprParen(..)            => SawExprParen,

            // just syntactic artifacts, expanded away by time of SVH.
            ExprForLoop(..)          => unreachable!(),
            ExprMac(..)              => unreachable!(),
        }
    }

    /// SawStmtComponent is analogous to SawExprComponent, but for statements.
    #[deriving(Hash)]
    pub enum SawStmtComponent {
        SawStmtDecl,
        SawStmtExpr,
        SawStmtSemi,
    }

    fn saw_stmt(node: &Stmt_) -> SawStmtComponent {
        match *node {
            StmtDecl(..) => SawStmtDecl,
            StmtExpr(..) => SawStmtExpr,
            StmtSemi(..) => SawStmtSemi,
            StmtMac(..)  => unreachable!(),
        }
    }

    // Ad-hoc overloading between Ident and Name to their intern table lookups.
    trait InternKey { fn get_content(self) -> token::InternedString; }
    impl InternKey for Ident {
        fn get_content(self) -> token::InternedString { token::get_ident(self) }
    }
    impl InternKey for Name {
        fn get_content(self) -> token::InternedString { token::get_name(self) }
    }
    fn content<K:InternKey>(k: K) -> token::InternedString { k.get_content() }

    // local short-hand eases writing signatures of syntax::visit mod.
    type E = ();

    impl<'a> Visitor<E> for StrictVersionHashVisitor<'a> {

        fn visit_mac(&mut self, macro: &Mac, e: E) {
            // macro invocations, namely macro_rules definitions,
            // *can* appear as items, even in the expanded crate AST.

            if macro_name(macro).get() == "macro_rules" {
                // Pretty-printing definition to a string strips out
                // surface artifacts (currently), such as the span
                // information, yielding a content-based hash.

                // FIXME (#14132): building temporary string is
                // expensive; a direct content-based hash on token
                // trees might be faster. Implementing this is far
                // easier in short term.
                let macro_defn_as_string =
                    pprust::to_str(|pp_state| pp_state.print_mac(macro));
                macro_defn_as_string.hash(self.st);
            } else {
                // It is not possible to observe any kind of macro
                // invocation at this stage except `macro_rules!`.
                fail!("reached macro somehow: {}",
                      pprust::to_str(|pp_state| pp_state.print_mac(macro)));
            }

            visit::walk_mac(self, macro, e);

            fn macro_name(macro: &Mac) -> token::InternedString {
                match &macro.node {
                    &MacInvocTT(ref path, ref _tts, ref _stx_ctxt) => {
                        let s = path.segments.as_slice();
                        assert_eq!(s.len(), 1);
                        content(s[0].identifier)
                    }
                }
            }
        }

        fn visit_struct_def(&mut self, s: &StructDef, ident: Ident,
                            g: &Generics, _: NodeId, e: E) {
            SawStructDef(content(ident)).hash(self.st);
            visit::walk_generics(self, g, e.clone());
            visit::walk_struct_def(self, s, e)
        }

        fn visit_variant(&mut self, v: &Variant, g: &Generics, e: E) {
            SawVariant.hash(self.st);
            // walk_variant does not call walk_generics, so do it here.
            visit::walk_generics(self, g, e.clone());
            visit::walk_variant(self, v, g, e)
        }

        fn visit_opt_lifetime_ref(&mut self, _: Span, l: &Option<Lifetime>, env: E) {
            SawOptLifetimeRef.hash(self.st);
            // (This is a strange method in the visitor trait, in that
            // it does not expose a walk function to do the subroutine
            // calls.)
            match *l {
                Some(ref l) => self.visit_lifetime_ref(l, env),
                None => ()
            }
        }

        // All of the remaining methods just record (in the hash
        // SipState) that the visitor saw that particular variant
        // (with its payload), and continue walking as the default
        // visitor would.
        //
        // Some of the implementations have some notes as to how one
        // might try to make their SVH computation less discerning
        // (e.g. by incorporating reachability analysis).  But
        // currently all of their implementations are uniform and
        // uninteresting.
        //
        // (If you edit a method such that it deviates from the
        // pattern, please move that method up above this comment.)

        fn visit_ident(&mut self, _: Span, ident: Ident, _: E) {
            SawIdent(content(ident)).hash(self.st);
        }

        fn visit_lifetime_ref(&mut self, l: &Lifetime, _: E) {
            SawLifetimeRef(content(l.name)).hash(self.st);
        }

        fn visit_lifetime_decl(&mut self, l: &Lifetime, _: E) {
            SawLifetimeDecl(content(l.name)).hash(self.st);
        }

        // We do recursively walk the bodies of functions/methods
        // (rather than omitting their bodies from the hash) since
        // monomorphization and cross-crate inlining generally implies
        // that a change to a crate body will require downstream
        // crates to be recompiled.
        fn visit_expr(&mut self, ex: &Expr, e: E) {
            SawExpr(saw_expr(&ex.node)).hash(self.st); visit::walk_expr(self, ex, e)
        }

        fn visit_stmt(&mut self, s: &Stmt, e: E) {
            SawStmt(saw_stmt(&s.node)).hash(self.st); visit::walk_stmt(self, s, e)
        }

        fn visit_view_item(&mut self, i: &ViewItem, e: E) {
            // Two kinds of view items can affect the ABI for a crate:
            // exported `pub use` view items (since that may expose
            // items that downstream crates can call), and `use
            // foo::Trait`, since changing that may affect method
            // resolution.
            //
            // The simplest approach to handling both of the above is
            // just to adopt the same simple-minded (fine-grained)
            // hash that I am deploying elsewhere here.
            SawViewItem.hash(self.st); visit::walk_view_item(self, i, e)
        }

        fn visit_foreign_item(&mut self, i: &ForeignItem, e: E) {
            // FIXME (#14132) ideally we would incorporate privacy (or
            // perhaps reachability) somewhere here, so foreign items
            // that do not leak into downstream crates would not be
            // part of the ABI.
            SawForeignItem.hash(self.st); visit::walk_foreign_item(self, i, e)
        }

        fn visit_item(&mut self, i: &Item, e: E) {
            // FIXME (#14132) ideally would incorporate reachability
            // analysis somewhere here, so items that never leak into
            // downstream crates (e.g. via monomorphisation or
            // inlining) would not be part of the ABI.
            SawItem.hash(self.st); visit::walk_item(self, i, e)
        }

        fn visit_mod(&mut self, m: &Mod, _s: Span, _n: NodeId, e: E) {
            SawMod.hash(self.st); visit::walk_mod(self, m, e)
        }

        fn visit_decl(&mut self, d: &Decl, e: E) {
            SawDecl.hash(self.st); visit::walk_decl(self, d, e)
        }

        fn visit_ty(&mut self, t: &Ty, e: E) {
            SawTy.hash(self.st); visit::walk_ty(self, t, e)
        }

        fn visit_generics(&mut self, g: &Generics, e: E) {
            SawGenerics.hash(self.st); visit::walk_generics(self, g, e)
        }

        fn visit_fn(&mut self, fk: &FnKind, fd: &FnDecl, b: &Block, s: Span, _: NodeId, e: E) {
            SawFn.hash(self.st); visit::walk_fn(self, fk, fd, b, s, e)
        }

        fn visit_ty_method(&mut self, t: &TypeMethod, e: E) {
            SawTyMethod.hash(self.st); visit::walk_ty_method(self, t, e)
        }

        fn visit_trait_method(&mut self, t: &TraitMethod, e: E) {
            SawTraitMethod.hash(self.st); visit::walk_trait_method(self, t, e)
        }

        fn visit_struct_field(&mut self, s: &StructField, e: E) {
            SawStructField.hash(self.st); visit::walk_struct_field(self, s, e)
        }

        fn visit_explicit_self(&mut self, es: &ExplicitSelf, e: E) {
            SawExplicitSelf.hash(self.st); visit::walk_explicit_self(self, es, e)
        }

        fn visit_path(&mut self, path: &Path, _: ast::NodeId, e: E) {
            SawPath.hash(self.st); visit::walk_path(self, path, e)
        }

        fn visit_block(&mut self, b: &Block, e: E) {
            SawBlock.hash(self.st); visit::walk_block(self, b, e)
        }

        fn visit_pat(&mut self, p: &Pat, e: E) {
            SawPat.hash(self.st); visit::walk_pat(self, p, e)
        }

        fn visit_local(&mut self, l: &Local, e: E) {
            SawLocal.hash(self.st); visit::walk_local(self, l, e)
        }

        fn visit_arm(&mut self, a: &Arm, e: E) {
            SawArm.hash(self.st); visit::walk_arm(self, a, e)
        }
    }
}
<|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 fmt;
use from_str::from_str;
use libc::{uintptr_t, exit};
use option::{Some, None, Option};
use rt;
use rt::util::dumb_println;
use rt::crate_map::{ModEntry, iter_crate_map};
use rt::crate_map::get_crate_map;
use str::StrSlice;
use str::raw::from_c_str;
use u32;
use vec::ImmutableVector;
use cast::transmute;

struct LogDirective {
    name: Option<~str>,
    level: u32
}

static MAX_LOG_LEVEL: u32 = 255;
static DEFAULT_LOG_LEVEL: u32 = 1;
static log_level_names : &'static[&'static str] = &'static["error", "warn", "info", "debug"];

/// Parse an individual log level that is either a number or a symbolic log level
fn parse_log_level(level: &str) -> Option<u32> {
    let num = from_str::<u32>(level);
    let mut log_level;
    match num {
        Some(num) => {
            if num < MAX_LOG_LEVEL {
                log_level = Some(num);
            } else {
                log_level = Some(MAX_LOG_LEVEL);
            }
        }
        _ => {
            let position = log_level_names.iter().position(|&name| name == level);
            match position {
                Some(position) => {
                    log_level = Some(u32::min(MAX_LOG_LEVEL, (position + 1) as u32))
                },
                _ => {
                    log_level = None;
                }
            }
        }
    }
    log_level
}

/// Parse a logging specification string (e.g: "crate1,crate2::mod3,crate3::x=1")
/// and return a vector with log directives.
/// Valid log levels are 0-255, with the most likely ones being 1-4 (defined in std::).
/// Also supports string log levels of error, warn, info, and debug
fn parse_logging_spec(spec: ~str) -> ~[LogDirective]{
    let mut dirs = ~[];
    for s in spec.split_iter(',') {
        let parts: ~[&str] = s.split_iter('=').collect();
        let mut log_level;
        let mut name = Some(parts[0].to_owned());
        match parts.len() {
            1 => {
                //if the single argument is a log-level string or number,
                //treat that as a global fallback
                let possible_log_level = parse_log_level(parts[0]);
                match possible_log_level {
                    Some(num) => {
                        name = None;
                        log_level = num;
                    },
                    _ => {
                        log_level = MAX_LOG_LEVEL
                    }
                }
            }
            2 => {
                let possible_log_level = parse_log_level(parts[1]);
                match possible_log_level {
                    Some(num) => {
                        log_level = num;
                    },
                    _ => {
                        dumb_println(fmt!("warning: invalid logging spec \
                                           '%s', ignoring it", parts[1]));
                        loop;
                    }
                }
            },
            _ => {
                dumb_println(fmt!("warning: invalid logging spec '%s',\
                                  ignoring it", s));
                loop;
            }
        }
        let dir = LogDirective {name: name, level: log_level};
        dirs.push(dir);
    }
    return dirs;
}

/// Set the log level of an entry in the crate map depending on the vector
/// of log directives
fn update_entry(dirs: &[LogDirective], entry: *mut ModEntry) -> u32 {
    let mut new_lvl: u32 = DEFAULT_LOG_LEVEL;
    let mut longest_match = -1i;
    unsafe {
        for dir in dirs.iter() {
            match dir.name {
                None => {
                    if longest_match == -1 {
                        longest_match = 0;
                        new_lvl = dir.level;
                    }
                }
                Some(ref dir_name) => {
                    let name = from_c_str((*entry).name);
                    let len = dir_name.len() as int;
                    if name.starts_with(*dir_name) &&
                        len >= longest_match {
                        longest_match = len;
                        new_lvl = dir.level;
                    }
                }
            };
        }
        *(*entry).log_level = new_lvl;
    }
    if longest_match >= 0 { return 1; } else { return 0; }
}

#[fixed_stack_segment] #[inline(never)]
/// Set log level for every entry in crate_map according to the sepecification
/// in settings
fn update_log_settings(crate_map: *u8, settings: ~str) {
    let mut dirs = ~[];
    if settings.len() > 0 {
        if settings == ~"::help" || settings == ~"?" {
            dumb_println("\nCrate log map:\n");
            unsafe {
                do iter_crate_map(transmute(crate_map)) |entry: *mut ModEntry| {
                    dumb_println(" "+from_c_str((*entry).name));
                }
                exit(1);
            }
        }
        dirs = parse_logging_spec(settings);
    }

    let mut n_matches: u32 = 0;
    unsafe {
        do iter_crate_map(transmute(crate_map)) |entry: *mut ModEntry| {
            let m = update_entry(dirs, entry);
            n_matches += m;
        }
    }

    if n_matches < (dirs.len() as u32) {
        dumb_println(fmt!("warning: got %u RUST_LOG specs but only matched %u of them.\n\
                          You may have mistyped a RUST_LOG spec.\n\
                          Use RUST_LOG=::help to see the list of crates and modules.\n",
                          dirs.len() as uint, n_matches as uint));
    }
}

pub trait Logger {
    fn log(&mut self, args: &fmt::Arguments);
}

pub struct StdErrLogger;

impl Logger for StdErrLogger {
    fn log(&mut self, args: &fmt::Arguments) {
        if should_log_console() {
            fmt::write(self as &mut rt::io::Writer, args);
        }
    }
}

impl rt::io::Writer for StdErrLogger {
    fn write(&mut self, buf: &[u8]) {
        // Nothing like swapping between I/O implementations! In theory this
        // could use the libuv bindings for writing to file descriptors, but
        // that may not necessarily be desirable because logging should work
        // outside of the uv loop. (modify with caution)
        use io::Writer;
        let dbg = ::libc::STDERR_FILENO as ::io::fd_t;
        dbg.write(buf);
    }

    fn flush(&mut self) {}
}

/// Configure logging by traversing the crate map and setting the
/// per-module global logging flags based on the logging spec
pub fn init() {
    use os;

    let crate_map = get_crate_map() as *u8;

    let log_spec = os::getenv("RUST_LOG");
    match log_spec {
        Some(spec) => {
            update_log_settings(crate_map, spec);
        }
        None => {
            update_log_settings(crate_map, ~"");
        }
    }
}

#[fixed_stack_segment] #[inline(never)]
pub fn console_on() { unsafe { rust_log_console_on() } }

#[fixed_stack_segment] #[inline(never)]
pub fn console_off() { unsafe { rust_log_console_off() } }

#[fixed_stack_segment] #[inline(never)]
fn should_log_console() -> bool { unsafe { rust_should_log_console() != 0 } }

extern {
    fn rust_log_console_on();
    fn rust_log_console_off();
    fn rust_should_log_console() -> uintptr_t;
}

// Tests for parse_logging_spec()
#[test]
fn parse_logging_spec_valid() {
    let dirs = parse_logging_spec(~"crate1::mod1=1,crate1::mod2,crate2=4");
    assert_eq!(dirs.len(), 3);
    assert!(dirs[0].name == Some(~"crate1::mod1"));
    assert_eq!(dirs[0].level, 1);

    assert!(dirs[1].name == Some(~"crate1::mod2"));
    assert_eq!(dirs[1].level, MAX_LOG_LEVEL);

    assert!(dirs[2].name == Some(~"crate2"));
    assert_eq!(dirs[2].level, 4);
}

#[test]
fn parse_logging_spec_invalid_crate() {
    // test parse_logging_spec with multiple = in specification
    let dirs = parse_logging_spec(~"crate1::mod1=1=2,crate2=4");
    assert_eq!(dirs.len(), 1);
    assert!(dirs[0].name == Some(~"crate2"));
    assert_eq!(dirs[0].level, 4);
}

#[test]
fn parse_logging_spec_invalid_log_level() {
    // test parse_logging_spec with 'noNumber' as log level
    let dirs = parse_logging_spec(~"crate1::mod1=noNumber,crate2=4");
    assert_eq!(dirs.len(), 1);
    assert!(dirs[0].name == Some(~"crate2"));
    assert_eq!(dirs[0].level, 4);
}

#[test]
fn parse_logging_spec_string_log_level() {
    // test parse_logging_spec with 'warn' as log level
    let dirs = parse_logging_spec(~"crate1::mod1=wrong,crate2=warn");
    assert_eq!(dirs.len(), 1);
    assert!(dirs[0].name == Some(~"crate2"));
    assert_eq!(dirs[0].level, 2);
}

#[test]
fn parse_logging_spec_global() {
    // test parse_logging_spec with no crate
    let dirs = parse_logging_spec(~"warn,crate2=4");
    assert_eq!(dirs.len(), 2);
    assert!(dirs[0].name == None);
    assert_eq!(dirs[0].level, 2);
    assert!(dirs[1].name == Some(~"crate2"));
    assert_eq!(dirs[1].level, 4);
}

// Tests for update_entry
#[test]
fn update_entry_match_full_path() {
    use c_str::ToCStr;
    let dirs = ~[LogDirective {name: Some(~"crate1::mod1"), level: 2 },
                 LogDirective {name: Some(~"crate2"), level: 3}];
    let level = &mut 0;
    unsafe {
        do "crate1::mod1".with_c_str |ptr| {
            let entry= &ModEntry {name: ptr, log_level: level};
            let m = update_entry(dirs, transmute(entry));
            assert!(*entry.log_level == 2);
            assert!(m == 1);
        }
    }
}

#[test]
fn update_entry_no_match() {
    use c_str::ToCStr;
    let dirs = ~[LogDirective {name: Some(~"crate1::mod1"), level: 2 },
                 LogDirective {name: Some(~"crate2"), level: 3}];
    let level = &mut 0;
    unsafe {
        do "crate3::mod1".with_c_str |ptr| {
            let entry= &ModEntry {name: ptr, log_level: level};
            let m = update_entry(dirs, transmute(entry));
            assert!(*entry.log_level == DEFAULT_LOG_LEVEL);
            assert!(m == 0);
        }
    }
}

#[test]
fn update_entry_match_beginning() {
    use c_str::ToCStr;
    let dirs = ~[LogDirective {name: Some(~"crate1::mod1"), level: 2 },
                 LogDirective {name: Some(~"crate2"), level: 3}];
    let level = &mut 0;
    unsafe {
        do "crate2::mod1".with_c_str |ptr| {
            let entry= &ModEntry {name: ptr, log_level: level};
            let m = update_entry(dirs, transmute(entry));
            assert!(*entry.log_level == 3);
            assert!(m == 1);
        }
    }
}

#[test]
fn update_entry_match_beginning_longest_match() {
    use c_str::ToCStr;
    let dirs = ~[LogDirective {name: Some(~"crate1::mod1"), level: 2 },
                 LogDirective {name: Some(~"crate2"), level: 3},
                 LogDirective {name: Some(~"crate2::mod"), level: 4}];
    let level = &mut 0;
    unsafe {
        do "crate2::mod1".with_c_str |ptr| {
            let entry = &ModEntry {name: ptr, log_level: level};
            let m = update_entry(dirs, transmute(entry));
            assert!(*entry.log_level == 4);
            assert!(m == 1);
        }
    }
}

#[test]
fn update_entry_match_default() {
    use c_str::ToCStr;
    let dirs = ~[LogDirective {name: Some(~"crate1::mod1"), level: 2 },
                 LogDirective {name: None, level: 3}
                ];
    let level = &mut 0;
    unsafe {
        do "crate1::mod1".with_c_str |ptr| {
            let entry= &ModEntry {name: ptr, log_level: level};
            let m = update_entry(dirs, transmute(entry));
            assert!(*entry.log_level == 2);
            assert!(m == 1);
        }
        do "crate2::mod2".with_c_str |ptr| {
            let entry= &ModEntry {name: ptr, log_level: level};
            let m = update_entry(dirs, transmute(entry));
            assert!(*entry.log_level == 3);
            assert!(m == 1);
        }
    }
}
<commit_msg>auto merge of #9609 : alexcrichton/rust/fix-logging-newline, r=catamorphism<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 fmt;
use from_str::from_str;
use libc::{uintptr_t, exit};
use option::{Some, None, Option};
use rt;
use rt::util::dumb_println;
use rt::crate_map::{ModEntry, iter_crate_map};
use rt::crate_map::get_crate_map;
use str::StrSlice;
use str::raw::from_c_str;
use u32;
use vec::ImmutableVector;
use cast::transmute;

struct LogDirective {
    name: Option<~str>,
    level: u32
}

static MAX_LOG_LEVEL: u32 = 255;
static DEFAULT_LOG_LEVEL: u32 = 1;
static log_level_names : &'static[&'static str] = &'static["error", "warn", "info", "debug"];

/// Parse an individual log level that is either a number or a symbolic log level
fn parse_log_level(level: &str) -> Option<u32> {
    let num = from_str::<u32>(level);
    let mut log_level;
    match num {
        Some(num) => {
            if num < MAX_LOG_LEVEL {
                log_level = Some(num);
            } else {
                log_level = Some(MAX_LOG_LEVEL);
            }
        }
        _ => {
            let position = log_level_names.iter().position(|&name| name == level);
            match position {
                Some(position) => {
                    log_level = Some(u32::min(MAX_LOG_LEVEL, (position + 1) as u32))
                },
                _ => {
                    log_level = None;
                }
            }
        }
    }
    log_level
}

/// Parse a logging specification string (e.g: "crate1,crate2::mod3,crate3::x=1")
/// and return a vector with log directives.
/// Valid log levels are 0-255, with the most likely ones being 1-4 (defined in std::).
/// Also supports string log levels of error, warn, info, and debug
fn parse_logging_spec(spec: ~str) -> ~[LogDirective]{
    let mut dirs = ~[];
    for s in spec.split_iter(',') {
        let parts: ~[&str] = s.split_iter('=').collect();
        let mut log_level;
        let mut name = Some(parts[0].to_owned());
        match parts.len() {
            1 => {
                //if the single argument is a log-level string or number,
                //treat that as a global fallback
                let possible_log_level = parse_log_level(parts[0]);
                match possible_log_level {
                    Some(num) => {
                        name = None;
                        log_level = num;
                    },
                    _ => {
                        log_level = MAX_LOG_LEVEL
                    }
                }
            }
            2 => {
                let possible_log_level = parse_log_level(parts[1]);
                match possible_log_level {
                    Some(num) => {
                        log_level = num;
                    },
                    _ => {
                        dumb_println(fmt!("warning: invalid logging spec \
                                           '%s', ignoring it", parts[1]));
                        loop;
                    }
                }
            },
            _ => {
                dumb_println(fmt!("warning: invalid logging spec '%s',\
                                  ignoring it", s));
                loop;
            }
        }
        let dir = LogDirective {name: name, level: log_level};
        dirs.push(dir);
    }
    return dirs;
}

/// Set the log level of an entry in the crate map depending on the vector
/// of log directives
fn update_entry(dirs: &[LogDirective], entry: *mut ModEntry) -> u32 {
    let mut new_lvl: u32 = DEFAULT_LOG_LEVEL;
    let mut longest_match = -1i;
    unsafe {
        for dir in dirs.iter() {
            match dir.name {
                None => {
                    if longest_match == -1 {
                        longest_match = 0;
                        new_lvl = dir.level;
                    }
                }
                Some(ref dir_name) => {
                    let name = from_c_str((*entry).name);
                    let len = dir_name.len() as int;
                    if name.starts_with(*dir_name) &&
                        len >= longest_match {
                        longest_match = len;
                        new_lvl = dir.level;
                    }
                }
            };
        }
        *(*entry).log_level = new_lvl;
    }
    if longest_match >= 0 { return 1; } else { return 0; }
}

#[fixed_stack_segment] #[inline(never)]
/// Set log level for every entry in crate_map according to the sepecification
/// in settings
fn update_log_settings(crate_map: *u8, settings: ~str) {
    let mut dirs = ~[];
    if settings.len() > 0 {
        if settings == ~"::help" || settings == ~"?" {
            dumb_println("\nCrate log map:\n");
            unsafe {
                do iter_crate_map(transmute(crate_map)) |entry: *mut ModEntry| {
                    dumb_println(" "+from_c_str((*entry).name));
                }
                exit(1);
            }
        }
        dirs = parse_logging_spec(settings);
    }

    let mut n_matches: u32 = 0;
    unsafe {
        do iter_crate_map(transmute(crate_map)) |entry: *mut ModEntry| {
            let m = update_entry(dirs, entry);
            n_matches += m;
        }
    }

    if n_matches < (dirs.len() as u32) {
        dumb_println(fmt!("warning: got %u RUST_LOG specs but only matched %u of them.\n\
                          You may have mistyped a RUST_LOG spec.\n\
                          Use RUST_LOG=::help to see the list of crates and modules.\n",
                          dirs.len() as uint, n_matches as uint));
    }
}

pub trait Logger {
    fn log(&mut self, args: &fmt::Arguments);
}

pub struct StdErrLogger;

impl Logger for StdErrLogger {
    fn log(&mut self, args: &fmt::Arguments) {
        if should_log_console() {
            fmt::writeln(self as &mut rt::io::Writer, args);
        }
    }
}

impl rt::io::Writer for StdErrLogger {
    fn write(&mut self, buf: &[u8]) {
        // Nothing like swapping between I/O implementations! In theory this
        // could use the libuv bindings for writing to file descriptors, but
        // that may not necessarily be desirable because logging should work
        // outside of the uv loop. (modify with caution)
        use io::Writer;
        let dbg = ::libc::STDERR_FILENO as ::io::fd_t;
        dbg.write(buf);
    }

    fn flush(&mut self) {}
}

/// Configure logging by traversing the crate map and setting the
/// per-module global logging flags based on the logging spec
pub fn init() {
    use os;

    let crate_map = get_crate_map() as *u8;

    let log_spec = os::getenv("RUST_LOG");
    match log_spec {
        Some(spec) => {
            update_log_settings(crate_map, spec);
        }
        None => {
            update_log_settings(crate_map, ~"");
        }
    }
}

#[fixed_stack_segment] #[inline(never)]
pub fn console_on() { unsafe { rust_log_console_on() } }

#[fixed_stack_segment] #[inline(never)]
pub fn console_off() { unsafe { rust_log_console_off() } }

#[fixed_stack_segment] #[inline(never)]
fn should_log_console() -> bool { unsafe { rust_should_log_console() != 0 } }

extern {
    fn rust_log_console_on();
    fn rust_log_console_off();
    fn rust_should_log_console() -> uintptr_t;
}

// Tests for parse_logging_spec()
#[test]
fn parse_logging_spec_valid() {
    let dirs = parse_logging_spec(~"crate1::mod1=1,crate1::mod2,crate2=4");
    assert_eq!(dirs.len(), 3);
    assert!(dirs[0].name == Some(~"crate1::mod1"));
    assert_eq!(dirs[0].level, 1);

    assert!(dirs[1].name == Some(~"crate1::mod2"));
    assert_eq!(dirs[1].level, MAX_LOG_LEVEL);

    assert!(dirs[2].name == Some(~"crate2"));
    assert_eq!(dirs[2].level, 4);
}

#[test]
fn parse_logging_spec_invalid_crate() {
    // test parse_logging_spec with multiple = in specification
    let dirs = parse_logging_spec(~"crate1::mod1=1=2,crate2=4");
    assert_eq!(dirs.len(), 1);
    assert!(dirs[0].name == Some(~"crate2"));
    assert_eq!(dirs[0].level, 4);
}

#[test]
fn parse_logging_spec_invalid_log_level() {
    // test parse_logging_spec with 'noNumber' as log level
    let dirs = parse_logging_spec(~"crate1::mod1=noNumber,crate2=4");
    assert_eq!(dirs.len(), 1);
    assert!(dirs[0].name == Some(~"crate2"));
    assert_eq!(dirs[0].level, 4);
}

#[test]
fn parse_logging_spec_string_log_level() {
    // test parse_logging_spec with 'warn' as log level
    let dirs = parse_logging_spec(~"crate1::mod1=wrong,crate2=warn");
    assert_eq!(dirs.len(), 1);
    assert!(dirs[0].name == Some(~"crate2"));
    assert_eq!(dirs[0].level, 2);
}

#[test]
fn parse_logging_spec_global() {
    // test parse_logging_spec with no crate
    let dirs = parse_logging_spec(~"warn,crate2=4");
    assert_eq!(dirs.len(), 2);
    assert!(dirs[0].name == None);
    assert_eq!(dirs[0].level, 2);
    assert!(dirs[1].name == Some(~"crate2"));
    assert_eq!(dirs[1].level, 4);
}

// Tests for update_entry
#[test]
fn update_entry_match_full_path() {
    use c_str::ToCStr;
    let dirs = ~[LogDirective {name: Some(~"crate1::mod1"), level: 2 },
                 LogDirective {name: Some(~"crate2"), level: 3}];
    let level = &mut 0;
    unsafe {
        do "crate1::mod1".with_c_str |ptr| {
            let entry= &ModEntry {name: ptr, log_level: level};
            let m = update_entry(dirs, transmute(entry));
            assert!(*entry.log_level == 2);
            assert!(m == 1);
        }
    }
}

#[test]
fn update_entry_no_match() {
    use c_str::ToCStr;
    let dirs = ~[LogDirective {name: Some(~"crate1::mod1"), level: 2 },
                 LogDirective {name: Some(~"crate2"), level: 3}];
    let level = &mut 0;
    unsafe {
        do "crate3::mod1".with_c_str |ptr| {
            let entry= &ModEntry {name: ptr, log_level: level};
            let m = update_entry(dirs, transmute(entry));
            assert!(*entry.log_level == DEFAULT_LOG_LEVEL);
            assert!(m == 0);
        }
    }
}

#[test]
fn update_entry_match_beginning() {
    use c_str::ToCStr;
    let dirs = ~[LogDirective {name: Some(~"crate1::mod1"), level: 2 },
                 LogDirective {name: Some(~"crate2"), level: 3}];
    let level = &mut 0;
    unsafe {
        do "crate2::mod1".with_c_str |ptr| {
            let entry= &ModEntry {name: ptr, log_level: level};
            let m = update_entry(dirs, transmute(entry));
            assert!(*entry.log_level == 3);
            assert!(m == 1);
        }
    }
}

#[test]
fn update_entry_match_beginning_longest_match() {
    use c_str::ToCStr;
    let dirs = ~[LogDirective {name: Some(~"crate1::mod1"), level: 2 },
                 LogDirective {name: Some(~"crate2"), level: 3},
                 LogDirective {name: Some(~"crate2::mod"), level: 4}];
    let level = &mut 0;
    unsafe {
        do "crate2::mod1".with_c_str |ptr| {
            let entry = &ModEntry {name: ptr, log_level: level};
            let m = update_entry(dirs, transmute(entry));
            assert!(*entry.log_level == 4);
            assert!(m == 1);
        }
    }
}

#[test]
fn update_entry_match_default() {
    use c_str::ToCStr;
    let dirs = ~[LogDirective {name: Some(~"crate1::mod1"), level: 2 },
                 LogDirective {name: None, level: 3}
                ];
    let level = &mut 0;
    unsafe {
        do "crate1::mod1".with_c_str |ptr| {
            let entry= &ModEntry {name: ptr, log_level: level};
            let m = update_entry(dirs, transmute(entry));
            assert!(*entry.log_level == 2);
            assert!(m == 1);
        }
        do "crate2::mod2".with_c_str |ptr| {
            let entry= &ModEntry {name: ptr, log_level: level};
            let m = update_entry(dirs, transmute(entry));
            assert!(*entry.log_level == 3);
            assert!(m == 1);
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Add a mutex_map example<commit_after>//! This example shows how to wrap a data structure in a mutex to achieve safe mutability.
extern crate lazy_static;
use lazy_static::lazy_static;
use std::collections::HashMap;
use std::sync::Mutex;

lazy_static! {
    static ref MUTEX_MAP: Mutex<HashMap<u32, &'static str>> = {
        let mut m = HashMap::new();
        m.insert(0, "foo");
        m.insert(1, "bar");
        m.insert(2, "baz");
        Mutex::new(m)
    };
}

fn main() {
    MUTEX_MAP.lock().unwrap().insert(0, "boo");
    println!(
        "The entry for `0` is \"{}\".",
        MUTEX_MAP.lock().unwrap().get(&0).unwrap()
    );
}
<|endoftext|>


<commit_before>// Copyright 2012-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 core::to_bytes;
use core::to_str::ToStr;

#[deriving(Eq)]
pub enum Abi {
    // NB: This ordering MUST match the AbiDatas array below.
    // (This is ensured by the test indices_are_correct().)

    // Single platform ABIs come first (`for_arch()` relies on this)
    Cdecl,
    Stdcall,
    Fastcall,
    Aapcs,

    // Multiplatform ABIs second
    Rust,
    C,
    RustIntrinsic,
}

#[deriving(Eq)]
pub enum Architecture {
    // NB. You cannot change the ordering of these
    // constants without adjusting IntelBits below.
    // (This is ensured by the test indices_are_correct().)
    X86,
    X86_64,
    Arm,
    Mips
}

// FIXME(#5423) After a snapshot, we can change these constants:
// const IntelBits: u32 = (1 << (X86 as uint)) | (1 << X86_64 as uint));
// const ArmBits: u32 = (1 << (Arm as uint));
static IntelBits: u32 = 1 | 2;
static ArmBits: u32 = 4;

struct AbiData {
    abi: Abi,

    // Name of this ABI as we like it called.
    name: &'static str,

    // Is it specific to a platform? If so, which one?  Also, what is
    // the name that LLVM gives it (in case we disagree)
    abi_arch: AbiArchitecture
}

enum AbiArchitecture {
    RustArch,   // Not a real ABI (e.g., intrinsic)
    AllArch,    // An ABI that specifies cross-platform defaults (e.g., "C")
    Archs(u32)  // Multiple architectures (bitset)
}

#[auto_encode]
#[auto_decode]
#[deriving(Eq)]
pub struct AbiSet {
    priv bits: u32   // each bit represents one of the abis below
}

static AbiDatas: &'static [AbiData] = &[
    // Platform-specific ABIs
    AbiData {abi: Cdecl, name: "cdecl", abi_arch: Archs(IntelBits)},
    AbiData {abi: Stdcall, name: "stdcall", abi_arch: Archs(IntelBits)},
    AbiData {abi: Fastcall, name:"fastcall", abi_arch: Archs(IntelBits)},
    AbiData {abi: Aapcs, name: "aapcs", abi_arch: Archs(ArmBits)},

    // Cross-platform ABIs
    //
    // NB: Do not adjust this ordering without
    // adjusting the indices below.
    AbiData {abi: Rust, name: "Rust", abi_arch: RustArch},
    AbiData {abi: C, name: "C", abi_arch: AllArch},
    AbiData {abi: RustIntrinsic, name: "rust-intrinsic", abi_arch: RustArch},
];

fn each_abi(op: &fn(abi: Abi) -> bool) {
    /*!
     *
     * Iterates through each of the defined ABIs.
     */

    for AbiDatas.each |abi_data| {
        if !op(abi_data.abi) {
            return;
        }
    }
}

pub fn lookup(name: &str) -> Option<Abi> {
    /*!
     *
     * Returns the ABI with the given name (if any).
     */

    for each_abi |abi| {
        if name == abi.data().name {
            return Some(abi);
        }
    }
    return None;
}

pub fn all_names() -> ~[&'static str] {
    AbiDatas.map(|d| d.name)
}

pub impl Abi {
    #[inline]
    fn index(&self) -> uint {
        *self as uint
    }

    #[inline]
    fn data(&self) -> &'static AbiData {
        &AbiDatas[self.index()]
    }

    fn name(&self) -> &'static str {
        self.data().name
    }
}

impl Architecture {
    fn bit(&self) -> u32 {
        1 << (*self as u32)
    }
}

pub impl AbiSet {
    fn from(abi: Abi) -> AbiSet {
        AbiSet { bits: (1 << abi.index()) }
    }

    #[inline]
    fn Rust() -> AbiSet {
        AbiSet::from(Rust)
    }

    #[inline]
    fn C() -> AbiSet {
        AbiSet::from(C)
    }

    #[inline]
    fn Intrinsic() -> AbiSet {
        AbiSet::from(RustIntrinsic)
    }

    fn default() -> AbiSet {
        AbiSet::C()
    }

    fn empty() -> AbiSet {
        AbiSet { bits: 0 }
    }

    #[inline]
    fn is_rust(&self) -> bool {
        self.bits == 1 << Rust.index()
    }

    #[inline]
    fn is_c(&self) -> bool {
        self.bits == 1 << C.index()
    }

    #[inline]
    fn is_intrinsic(&self) -> bool {
        self.bits == 1 << RustIntrinsic.index()
    }

    fn contains(&self, abi: Abi) -> bool {
        (self.bits & (1 << abi.index())) != 0
    }

    fn subset_of(&self, other_abi_set: AbiSet) -> bool {
        (self.bits & other_abi_set.bits) == self.bits
    }

    fn add(&mut self, abi: Abi) {
        self.bits |= (1 << abi.index());
    }

    fn each(&self, op: &fn(abi: Abi) -> bool) {
        for each_abi |abi| {
            if self.contains(abi) {
                if !op(abi) {
                    return;
                }
            }
        }
    }

    fn is_empty(&self) -> bool {
        self.bits == 0
    }

    fn for_arch(&self, arch: Architecture) -> Option<Abi> {
        // NB---Single platform ABIs come first
        for self.each |abi| {
            let data = abi.data();
            match data.abi_arch {
                Archs(a) if (a & arch.bit()) != 0 => { return Some(abi); }
                Archs(_) => { }
                RustArch | AllArch => { return Some(abi); }
            }
        }

        None
    }

    fn check_valid(&self) -> Option<(Abi, Abi)> {
        let mut abis = ~[];
        for self.each |abi| { abis.push(abi); }

        for abis.eachi |i, abi| {
            let data = abi.data();
            for abis.slice(0, i).each |other_abi| {
                let other_data = other_abi.data();
                debug!("abis=(%?,%?) datas=(%?,%?)",
                       abi, data.abi_arch,
                       other_abi, other_data.abi_arch);
                match (&data.abi_arch, &other_data.abi_arch) {
                    (&AllArch, &AllArch) => {
                        // Two cross-architecture ABIs
                        return Some((*abi, *other_abi));
                    }
                    (_, &RustArch) |
                    (&RustArch, _) => {
                        // Cannot combine Rust or Rust-Intrinsic with
                        // anything else.
                        return Some((*abi, *other_abi));
                    }
                    (&Archs(is), &Archs(js)) if (is & js) != 0 => {
                        // Two ABIs for same architecture
                        return Some((*abi, *other_abi));
                    }
                    _ => {}
                }
            }
        }

        return None;
    }
}

impl to_bytes::IterBytes for Abi {
    fn iter_bytes(&self, +lsb0: bool, f: to_bytes::Cb) {
        self.index().iter_bytes(lsb0, f)
    }
}

impl to_bytes::IterBytes for AbiSet {
    fn iter_bytes(&self, +lsb0: bool, f: to_bytes::Cb) {
        self.bits.iter_bytes(lsb0, f)
    }
}

impl ToStr for Abi {
    fn to_str(&self) -> ~str {
        self.data().name.to_str()
    }
}

impl ToStr for AbiSet {
    fn to_str(&self) -> ~str {
        unsafe { // so we can push to strs.
            let mut strs = ~[];
            for self.each |abi| {
                strs.push(abi.data().name);
            }
            fmt!("\"%s\"", str::connect_slices(strs, " "))
        }
    }
}

#[test]
fn lookup_Rust() {
    let abi = lookup("Rust");
    assert!(abi.is_some() && abi.get().data().name == "Rust");
}

#[test]
fn lookup_cdecl() {
    let abi = lookup("cdecl");
    assert!(abi.is_some() && abi.get().data().name == "cdecl");
}

#[test]
fn lookup_baz() {
    let abi = lookup("baz");
    assert!(abi.is_none());
}

#[cfg(test)]
fn cannot_combine(n: Abi, m: Abi) {
    let mut set = AbiSet::empty();
    set.add(n);
    set.add(m);
    match set.check_valid() {
        Some((a, b)) => {
            assert!((n == a && m == b) ||
                         (m == a && n == b));
        }
        None => {
            fail!(~"Invalid match not detected");
        }
    }
}

#[cfg(test)]
fn can_combine(n: Abi, m: Abi) {
    let mut set = AbiSet::empty();
    set.add(n);
    set.add(m);
    match set.check_valid() {
        Some((_, _)) => {
            fail!(~"Valid match declared invalid");
        }
        None => {}
    }
}

#[test]
fn cannot_combine_cdecl_and_stdcall() {
    cannot_combine(Cdecl, Stdcall);
}

#[test]
fn cannot_combine_c_and_rust() {
    cannot_combine(C, Rust);
}

#[test]
fn cannot_combine_rust_and_cdecl() {
    cannot_combine(Rust, Cdecl);
}

#[test]
fn cannot_combine_rust_intrinsic_and_cdecl() {
    cannot_combine(RustIntrinsic, Cdecl);
}

#[test]
fn can_combine_c_and_stdcall() {
    can_combine(C, Stdcall);
}

#[test]
fn can_combine_aapcs_and_stdcall() {
    can_combine(Aapcs, Stdcall);
}

#[test]
fn abi_to_str_stdcall_aaps() {
    let mut set = AbiSet::empty();
    set.add(Aapcs);
    set.add(Stdcall);
    assert!(set.to_str() == ~"\"stdcall aapcs\"");
}

#[test]
fn abi_to_str_c_aaps() {
    let mut set = AbiSet::empty();
    set.add(Aapcs);
    set.add(C);
    debug!("set = %s", set.to_str());
    assert!(set.to_str() == ~"\"aapcs C\"");
}

#[test]
fn abi_to_str_rust() {
    let mut set = AbiSet::empty();
    set.add(Rust);
    debug!("set = %s", set.to_str());
    assert!(set.to_str() == ~"\"Rust\"");
}

#[test]
fn indices_are_correct() {
    for AbiDatas.eachi |i, abi_data| {
        assert!(i == abi_data.abi.index());
    }

    let bits = 1 << (X86 as u32);
    let bits = bits | 1 << (X86_64 as u32);
    assert!(IntelBits == bits);

    let bits = 1 << (Arm as u32);
    assert!(ArmBits == bits);
}

#[cfg(test)]
fn check_arch(abis: &[Abi], arch: Architecture, expect: Option<Abi>) {
    let mut set = AbiSet::empty();
    for abis.each |&abi| {
        set.add(abi);
    }
    let r = set.for_arch(arch);
    assert!(r == expect);
}

#[test]
fn pick_multiplatform() {
    check_arch([C, Cdecl], X86, Some(Cdecl));
    check_arch([C, Cdecl], X86_64, Some(Cdecl));
    check_arch([C, Cdecl], Arm, Some(C));
}

#[test]
fn pick_uniplatform() {
    check_arch([Stdcall], X86, Some(Stdcall));
    check_arch([Stdcall], Arm, None);
}
<commit_msg>libsyntax: Update abi constants. Fixes #5423.<commit_after>// Copyright 2012-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 core::to_bytes;
use core::to_str::ToStr;

#[deriving(Eq)]
pub enum Abi {
    // NB: This ordering MUST match the AbiDatas array below.
    // (This is ensured by the test indices_are_correct().)

    // Single platform ABIs come first (`for_arch()` relies on this)
    Cdecl,
    Stdcall,
    Fastcall,
    Aapcs,

    // Multiplatform ABIs second
    Rust,
    C,
    RustIntrinsic,
}

#[deriving(Eq)]
pub enum Architecture {
    // NB. You cannot change the ordering of these
    // constants without adjusting IntelBits below.
    // (This is ensured by the test indices_are_correct().)
    X86,
    X86_64,
    Arm,
    Mips
}

static IntelBits: u32 = (1 << (X86 as uint)) | (1 << (X86_64 as uint));
static ArmBits: u32 = (1 << (Arm as uint));

struct AbiData {
    abi: Abi,

    // Name of this ABI as we like it called.
    name: &'static str,

    // Is it specific to a platform? If so, which one?  Also, what is
    // the name that LLVM gives it (in case we disagree)
    abi_arch: AbiArchitecture
}

enum AbiArchitecture {
    RustArch,   // Not a real ABI (e.g., intrinsic)
    AllArch,    // An ABI that specifies cross-platform defaults (e.g., "C")
    Archs(u32)  // Multiple architectures (bitset)
}

#[auto_encode]
#[auto_decode]
#[deriving(Eq)]
pub struct AbiSet {
    priv bits: u32   // each bit represents one of the abis below
}

static AbiDatas: &'static [AbiData] = &[
    // Platform-specific ABIs
    AbiData {abi: Cdecl, name: "cdecl", abi_arch: Archs(IntelBits)},
    AbiData {abi: Stdcall, name: "stdcall", abi_arch: Archs(IntelBits)},
    AbiData {abi: Fastcall, name:"fastcall", abi_arch: Archs(IntelBits)},
    AbiData {abi: Aapcs, name: "aapcs", abi_arch: Archs(ArmBits)},

    // Cross-platform ABIs
    //
    // NB: Do not adjust this ordering without
    // adjusting the indices below.
    AbiData {abi: Rust, name: "Rust", abi_arch: RustArch},
    AbiData {abi: C, name: "C", abi_arch: AllArch},
    AbiData {abi: RustIntrinsic, name: "rust-intrinsic", abi_arch: RustArch},
];

fn each_abi(op: &fn(abi: Abi) -> bool) {
    /*!
     *
     * Iterates through each of the defined ABIs.
     */

    for AbiDatas.each |abi_data| {
        if !op(abi_data.abi) {
            return;
        }
    }
}

pub fn lookup(name: &str) -> Option<Abi> {
    /*!
     *
     * Returns the ABI with the given name (if any).
     */

    for each_abi |abi| {
        if name == abi.data().name {
            return Some(abi);
        }
    }
    return None;
}

pub fn all_names() -> ~[&'static str] {
    AbiDatas.map(|d| d.name)
}

pub impl Abi {
    #[inline]
    fn index(&self) -> uint {
        *self as uint
    }

    #[inline]
    fn data(&self) -> &'static AbiData {
        &AbiDatas[self.index()]
    }

    fn name(&self) -> &'static str {
        self.data().name
    }
}

impl Architecture {
    fn bit(&self) -> u32 {
        1 << (*self as u32)
    }
}

pub impl AbiSet {
    fn from(abi: Abi) -> AbiSet {
        AbiSet { bits: (1 << abi.index()) }
    }

    #[inline]
    fn Rust() -> AbiSet {
        AbiSet::from(Rust)
    }

    #[inline]
    fn C() -> AbiSet {
        AbiSet::from(C)
    }

    #[inline]
    fn Intrinsic() -> AbiSet {
        AbiSet::from(RustIntrinsic)
    }

    fn default() -> AbiSet {
        AbiSet::C()
    }

    fn empty() -> AbiSet {
        AbiSet { bits: 0 }
    }

    #[inline]
    fn is_rust(&self) -> bool {
        self.bits == 1 << Rust.index()
    }

    #[inline]
    fn is_c(&self) -> bool {
        self.bits == 1 << C.index()
    }

    #[inline]
    fn is_intrinsic(&self) -> bool {
        self.bits == 1 << RustIntrinsic.index()
    }

    fn contains(&self, abi: Abi) -> bool {
        (self.bits & (1 << abi.index())) != 0
    }

    fn subset_of(&self, other_abi_set: AbiSet) -> bool {
        (self.bits & other_abi_set.bits) == self.bits
    }

    fn add(&mut self, abi: Abi) {
        self.bits |= (1 << abi.index());
    }

    fn each(&self, op: &fn(abi: Abi) -> bool) {
        for each_abi |abi| {
            if self.contains(abi) {
                if !op(abi) {
                    return;
                }
            }
        }
    }

    fn is_empty(&self) -> bool {
        self.bits == 0
    }

    fn for_arch(&self, arch: Architecture) -> Option<Abi> {
        // NB---Single platform ABIs come first
        for self.each |abi| {
            let data = abi.data();
            match data.abi_arch {
                Archs(a) if (a & arch.bit()) != 0 => { return Some(abi); }
                Archs(_) => { }
                RustArch | AllArch => { return Some(abi); }
            }
        }

        None
    }

    fn check_valid(&self) -> Option<(Abi, Abi)> {
        let mut abis = ~[];
        for self.each |abi| { abis.push(abi); }

        for abis.eachi |i, abi| {
            let data = abi.data();
            for abis.slice(0, i).each |other_abi| {
                let other_data = other_abi.data();
                debug!("abis=(%?,%?) datas=(%?,%?)",
                       abi, data.abi_arch,
                       other_abi, other_data.abi_arch);
                match (&data.abi_arch, &other_data.abi_arch) {
                    (&AllArch, &AllArch) => {
                        // Two cross-architecture ABIs
                        return Some((*abi, *other_abi));
                    }
                    (_, &RustArch) |
                    (&RustArch, _) => {
                        // Cannot combine Rust or Rust-Intrinsic with
                        // anything else.
                        return Some((*abi, *other_abi));
                    }
                    (&Archs(is), &Archs(js)) if (is & js) != 0 => {
                        // Two ABIs for same architecture
                        return Some((*abi, *other_abi));
                    }
                    _ => {}
                }
            }
        }

        return None;
    }
}

impl to_bytes::IterBytes for Abi {
    fn iter_bytes(&self, +lsb0: bool, f: to_bytes::Cb) {
        self.index().iter_bytes(lsb0, f)
    }
}

impl to_bytes::IterBytes for AbiSet {
    fn iter_bytes(&self, +lsb0: bool, f: to_bytes::Cb) {
        self.bits.iter_bytes(lsb0, f)
    }
}

impl ToStr for Abi {
    fn to_str(&self) -> ~str {
        self.data().name.to_str()
    }
}

impl ToStr for AbiSet {
    fn to_str(&self) -> ~str {
        unsafe { // so we can push to strs.
            let mut strs = ~[];
            for self.each |abi| {
                strs.push(abi.data().name);
            }
            fmt!("\"%s\"", str::connect_slices(strs, " "))
        }
    }
}

#[test]
fn lookup_Rust() {
    let abi = lookup("Rust");
    assert!(abi.is_some() && abi.get().data().name == "Rust");
}

#[test]
fn lookup_cdecl() {
    let abi = lookup("cdecl");
    assert!(abi.is_some() && abi.get().data().name == "cdecl");
}

#[test]
fn lookup_baz() {
    let abi = lookup("baz");
    assert!(abi.is_none());
}

#[cfg(test)]
fn cannot_combine(n: Abi, m: Abi) {
    let mut set = AbiSet::empty();
    set.add(n);
    set.add(m);
    match set.check_valid() {
        Some((a, b)) => {
            assert!((n == a && m == b) ||
                         (m == a && n == b));
        }
        None => {
            fail!(~"Invalid match not detected");
        }
    }
}

#[cfg(test)]
fn can_combine(n: Abi, m: Abi) {
    let mut set = AbiSet::empty();
    set.add(n);
    set.add(m);
    match set.check_valid() {
        Some((_, _)) => {
            fail!(~"Valid match declared invalid");
        }
        None => {}
    }
}

#[test]
fn cannot_combine_cdecl_and_stdcall() {
    cannot_combine(Cdecl, Stdcall);
}

#[test]
fn cannot_combine_c_and_rust() {
    cannot_combine(C, Rust);
}

#[test]
fn cannot_combine_rust_and_cdecl() {
    cannot_combine(Rust, Cdecl);
}

#[test]
fn cannot_combine_rust_intrinsic_and_cdecl() {
    cannot_combine(RustIntrinsic, Cdecl);
}

#[test]
fn can_combine_c_and_stdcall() {
    can_combine(C, Stdcall);
}

#[test]
fn can_combine_aapcs_and_stdcall() {
    can_combine(Aapcs, Stdcall);
}

#[test]
fn abi_to_str_stdcall_aaps() {
    let mut set = AbiSet::empty();
    set.add(Aapcs);
    set.add(Stdcall);
    assert!(set.to_str() == ~"\"stdcall aapcs\"");
}

#[test]
fn abi_to_str_c_aaps() {
    let mut set = AbiSet::empty();
    set.add(Aapcs);
    set.add(C);
    debug!("set = %s", set.to_str());
    assert!(set.to_str() == ~"\"aapcs C\"");
}

#[test]
fn abi_to_str_rust() {
    let mut set = AbiSet::empty();
    set.add(Rust);
    debug!("set = %s", set.to_str());
    assert!(set.to_str() == ~"\"Rust\"");
}

#[test]
fn indices_are_correct() {
    for AbiDatas.eachi |i, abi_data| {
        assert!(i == abi_data.abi.index());
    }

    let bits = 1 << (X86 as u32);
    let bits = bits | 1 << (X86_64 as u32);
    assert!(IntelBits == bits);

    let bits = 1 << (Arm as u32);
    assert!(ArmBits == bits);
}

#[cfg(test)]
fn check_arch(abis: &[Abi], arch: Architecture, expect: Option<Abi>) {
    let mut set = AbiSet::empty();
    for abis.each |&abi| {
        set.add(abi);
    }
    let r = set.for_arch(arch);
    assert!(r == expect);
}

#[test]
fn pick_multiplatform() {
    check_arch([C, Cdecl], X86, Some(Cdecl));
    check_arch([C, Cdecl], X86_64, Some(Cdecl));
    check_arch([C, Cdecl], Arm, Some(C));
}

#[test]
fn pick_uniplatform() {
    check_arch([Stdcall], X86, Some(Stdcall));
    check_arch([Stdcall], Arm, None);
}
<|endoftext|>


<commit_before><commit_msg>add integration tests for DynamoDB Streams<commit_after>#![cfg(feature = "dynamodbstreams")]

extern crate rusoto;

use rusoto::dynamodbstreams::{DynamoDbStreamsClient, ListStreamsInput};
use rusoto::{DefaultCredentialsProvider, Region};

#[test]
fn should_list_streams() {
    let credentials = DefaultCredentialsProvider::new().unwrap();
    let client = DynamoDbStreamsClient::new(credentials, Region::UsEast1);

    let request = ListStreamsInput::default();

    match client.list_streams(&request) {
        Ok(response) => {
            println!("{:#?}", response);
            assert!(true)
        },
        Err(err) => panic!("Expected OK response, got {:#?}", err)
    };
}

<|endoftext|>


<commit_before>extern crate clap;

use clap::{App, Arg, SubCommand, AppSettings, ErrorKind};

#[test]
fn sub_command_negate_required() {
    App::new("sub_command_negate")
        .setting(AppSettings::SubcommandsNegateReqs)
        .arg(Arg::with_name("test")
               .required(true)
               .index(1))
        .subcommand(SubCommand::with_name("sub1"))
        .get_matches_from(vec!["myprog", "sub1"]);
}

#[test]
fn sub_command_negate_required_2() {
    let result = App::new("sub_command_negate")
        .setting(AppSettings::SubcommandsNegateReqs)
        .arg(Arg::with_name("test")
               .required(true)
               .index(1))
        .subcommand(SubCommand::with_name("sub1"))
        .get_matches_from_safe(vec![""]);
    assert!(result.is_err());
    let err = result.err().unwrap();
    assert_eq!(err.kind, ErrorKind::MissingRequiredArgument);
}

#[test]
fn sub_command_required() {
    let result = App::new("sc_required")
        .setting(AppSettings::SubcommandRequired)
        .subcommand(SubCommand::with_name("sub1"))
        .get_matches_from_safe(vec![""]);
    assert!(result.is_err());
    let err = result.err().unwrap();
    assert_eq!(err.kind, ErrorKind::MissingSubcommand);
}

#[test]
fn arg_required_else_help() {
    let result = App::new("arg_required")
        .setting(AppSettings::ArgRequiredElseHelp)
        .arg(Arg::with_name("test")
               .index(1))
        .get_matches_from_safe(vec![""]);
    assert!(result.is_err());
    let err = result.err().unwrap();
    assert_eq!(err.kind, ErrorKind::MissingArgumentOrSubcommand);
}

#[test]
fn no_bin_name() {
    let result = App::new("arg_required")
        .setting(AppSettings::NoBinaryName)
        .arg(Arg::with_name("test")
               .required(true)
               .index(1))
        .get_matches_from_safe(vec!["testing"]);
    assert!(result.is_ok());
    let matches = result.unwrap();
    assert_eq!(matches.value_of("test").unwrap(), "testing");
}

#[test]
fn unified_help() {
    let mut app = App::new("test")
        .author("Kevin K.")
        .about("tests stuff")
        .version("1.3")
        .setting(AppSettings::UnifiedHelpMessage)
        .args_from_usage("-f, --flag 'some flag'
                          [arg1] 'some pos arg'
                          --option [opt] 'some option'");
    // We call a get_matches method to cause --help and --version to be built
    let _ = app.get_matches_from_safe_borrow(vec![""]);

    // Now we check the output of print_help()
    let mut help = vec![];
    app.write_help(&mut help).ok().expect("failed to print help");
    assert_eq!(&*String::from_utf8_lossy(&*help), &*String::from("test 1.3\n\
Kevin K.
tests stuff

USAGE:
\ttest [OPTIONS] [ARGS]

OPTIONS:
    -f, --flag            some flag
    -h, --help            Prints help information
        --option <opt>    some option
    -V, --version         Prints version information

ARGS:
    arg1    some pos arg\n"));
}

#[test]
fn skip_possible_values() {
    let mut app = App::new("test")
        .author("Kevin K.")
        .about("tests stuff")
        .version("1.3")
        .setting(AppSettings::HidePossibleValuesInHelp)
        .args(&[Arg::from_usage("-o, --opt [opt] 'some option'").possible_values(&["one", "two"]),
                Arg::from_usage("[arg1] 'some pos arg'").possible_values(&["three", "four"])]);
    // We call a get_matches method to cause --help and --version to be built
    let _ = app.get_matches_from_safe_borrow(vec![""]);

    // Now we check the output of print_help()
    let mut help = vec![];
    app.write_help(&mut help).expect("failed to print help");
    assert_eq!(&*String::from_utf8_lossy(&*help), &*String::from("test 1.3\n\
Kevin K.
tests stuff

USAGE:
\ttest [FLAGS] [OPTIONS] [ARGS]

FLAGS:
    -h, --help       Prints help information
    -V, --version    Prints version information

OPTIONS:
    -o, --opt <opt>    some option

ARGS:
    arg1    some pos arg\n"));
}

#[test]
fn app_settings_fromstr() {
    assert_eq!("subcommandsnegatereqs".parse::<AppSettings>().unwrap(), AppSettings::SubcommandsNegateReqs);
    assert_eq!("subcommandsrequired".parse::<AppSettings>().unwrap(), AppSettings::SubcommandRequired);
    assert_eq!("argrequiredelsehelp".parse::<AppSettings>().unwrap(), AppSettings::ArgRequiredElseHelp);
    assert_eq!("globalversion".parse::<AppSettings>().unwrap(), AppSettings::GlobalVersion);
    assert_eq!("versionlesssubcommands".parse::<AppSettings>().unwrap(), AppSettings::VersionlessSubcommands);
    assert_eq!("unifiedhelpmessage".parse::<AppSettings>().unwrap(), AppSettings::UnifiedHelpMessage);
    assert_eq!("waitonerror".parse::<AppSettings>().unwrap(), AppSettings::WaitOnError);
    assert_eq!("subcommandrequiredelsehelp".parse::<AppSettings>().unwrap(), AppSettings::SubcommandRequiredElseHelp);
    assert_eq!("allowexternalsubcommands".parse::<AppSettings>().unwrap(), AppSettings::AllowExternalSubcommands);
    assert_eq!("trailingvararg".parse::<AppSettings>().unwrap(), AppSettings::TrailingVarArg);
    assert_eq!("nobinaryname".parse::<AppSettings>().unwrap(), AppSettings::NoBinaryName);
    assert_eq!("strictutf8".parse::<AppSettings>().unwrap(), AppSettings::StrictUtf8);
    assert_eq!("allowinvalidutf8".parse::<AppSettings>().unwrap(), AppSettings::AllowInvalidUtf8);
    assert_eq!("allowleadinghyphen".parse::<AppSettings>().unwrap(), AppSettings::AllowLeadingHyphen);
    assert_eq!("hidepossiblevaluesinhelp".parse::<AppSettings>().unwrap(), AppSettings::HidePossibleValuesInHelp);
    assert_eq!("hidden".parse::<AppSettings>().unwrap(), AppSettings::Hidden);
    assert!("hahahaha".parse::<AppSettings>().is_err());
}

<commit_msg>tests(AppSettings): adds test for GlobalVersion<commit_after>extern crate clap;

use clap::{App, Arg, SubCommand, AppSettings, ErrorKind};

#[test]
fn sub_command_negate_required() {
    App::new("sub_command_negate")
        .setting(AppSettings::SubcommandsNegateReqs)
        .arg(Arg::with_name("test")
               .required(true)
               .index(1))
        .subcommand(SubCommand::with_name("sub1"))
        .get_matches_from(vec!["myprog", "sub1"]);
}

#[test]
fn global_version() {
    let app = App::new("global_version")
        .setting(AppSettings::GlobalVersion)
        .version("1.1")
        .subcommand(SubCommand::with_name("sub1"));
    assert_eq!(app.p.subcommands[0].p.meta.version, Some("1.1"));
}

#[test]
fn sub_command_negate_required_2() {
    let result = App::new("sub_command_negate")
        .setting(AppSettings::SubcommandsNegateReqs)
        .arg(Arg::with_name("test")
               .required(true)
               .index(1))
        .subcommand(SubCommand::with_name("sub1"))
        .get_matches_from_safe(vec![""]);
    assert!(result.is_err());
    let err = result.err().unwrap();
    assert_eq!(err.kind, ErrorKind::MissingRequiredArgument);
}

#[test]
fn sub_command_required() {
    let result = App::new("sc_required")
        .setting(AppSettings::SubcommandRequired)
        .subcommand(SubCommand::with_name("sub1"))
        .get_matches_from_safe(vec![""]);
    assert!(result.is_err());
    let err = result.err().unwrap();
    assert_eq!(err.kind, ErrorKind::MissingSubcommand);
}

#[test]
fn arg_required_else_help() {
    let result = App::new("arg_required")
        .setting(AppSettings::ArgRequiredElseHelp)
        .arg(Arg::with_name("test")
               .index(1))
        .get_matches_from_safe(vec![""]);
    assert!(result.is_err());
    let err = result.err().unwrap();
    assert_eq!(err.kind, ErrorKind::MissingArgumentOrSubcommand);
}

#[test]
fn no_bin_name() {
    let result = App::new("arg_required")
        .setting(AppSettings::NoBinaryName)
        .arg(Arg::with_name("test")
               .required(true)
               .index(1))
        .get_matches_from_safe(vec!["testing"]);
    assert!(result.is_ok());
    let matches = result.unwrap();
    assert_eq!(matches.value_of("test").unwrap(), "testing");
}

#[test]
fn unified_help() {
    let mut app = App::new("test")
        .author("Kevin K.")
        .about("tests stuff")
        .version("1.3")
        .setting(AppSettings::UnifiedHelpMessage)
        .args_from_usage("-f, --flag 'some flag'
                          [arg1] 'some pos arg'
                          --option [opt] 'some option'");
    // We call a get_matches method to cause --help and --version to be built
    let _ = app.get_matches_from_safe_borrow(vec![""]);

    // Now we check the output of print_help()
    let mut help = vec![];
    app.write_help(&mut help).ok().expect("failed to print help");
    assert_eq!(&*String::from_utf8_lossy(&*help), &*String::from("test 1.3\n\
Kevin K.
tests stuff

USAGE:
\ttest [OPTIONS] [ARGS]

OPTIONS:
    -f, --flag            some flag
    -h, --help            Prints help information
        --option <opt>    some option
    -V, --version         Prints version information

ARGS:
    arg1    some pos arg\n"));
}

#[test]
fn skip_possible_values() {
    let mut app = App::new("test")
        .author("Kevin K.")
        .about("tests stuff")
        .version("1.3")
        .setting(AppSettings::HidePossibleValuesInHelp)
        .args(&[Arg::from_usage("-o, --opt [opt] 'some option'").possible_values(&["one", "two"]),
                Arg::from_usage("[arg1] 'some pos arg'").possible_values(&["three", "four"])]);
    // We call a get_matches method to cause --help and --version to be built
    let _ = app.get_matches_from_safe_borrow(vec![""]);

    // Now we check the output of print_help()
    let mut help = vec![];
    app.write_help(&mut help).expect("failed to print help");
    assert_eq!(&*String::from_utf8_lossy(&*help), &*String::from("test 1.3\n\
Kevin K.
tests stuff

USAGE:
\ttest [FLAGS] [OPTIONS] [ARGS]

FLAGS:
    -h, --help       Prints help information
    -V, --version    Prints version information

OPTIONS:
    -o, --opt <opt>    some option

ARGS:
    arg1    some pos arg\n"));
}

#[test]
fn app_settings_fromstr() {
    assert_eq!("subcommandsnegatereqs".parse::<AppSettings>().unwrap(), AppSettings::SubcommandsNegateReqs);
    assert_eq!("subcommandsrequired".parse::<AppSettings>().unwrap(), AppSettings::SubcommandRequired);
    assert_eq!("argrequiredelsehelp".parse::<AppSettings>().unwrap(), AppSettings::ArgRequiredElseHelp);
    assert_eq!("globalversion".parse::<AppSettings>().unwrap(), AppSettings::GlobalVersion);
    assert_eq!("versionlesssubcommands".parse::<AppSettings>().unwrap(), AppSettings::VersionlessSubcommands);
    assert_eq!("unifiedhelpmessage".parse::<AppSettings>().unwrap(), AppSettings::UnifiedHelpMessage);
    assert_eq!("waitonerror".parse::<AppSettings>().unwrap(), AppSettings::WaitOnError);
    assert_eq!("subcommandrequiredelsehelp".parse::<AppSettings>().unwrap(), AppSettings::SubcommandRequiredElseHelp);
    assert_eq!("allowexternalsubcommands".parse::<AppSettings>().unwrap(), AppSettings::AllowExternalSubcommands);
    assert_eq!("trailingvararg".parse::<AppSettings>().unwrap(), AppSettings::TrailingVarArg);
    assert_eq!("nobinaryname".parse::<AppSettings>().unwrap(), AppSettings::NoBinaryName);
    assert_eq!("strictutf8".parse::<AppSettings>().unwrap(), AppSettings::StrictUtf8);
    assert_eq!("allowinvalidutf8".parse::<AppSettings>().unwrap(), AppSettings::AllowInvalidUtf8);
    assert_eq!("allowleadinghyphen".parse::<AppSettings>().unwrap(), AppSettings::AllowLeadingHyphen);
    assert_eq!("hidepossiblevaluesinhelp".parse::<AppSettings>().unwrap(), AppSettings::HidePossibleValuesInHelp);
    assert_eq!("hidden".parse::<AppSettings>().unwrap(), AppSettings::Hidden);
    assert!("hahahaha".parse::<AppSettings>().is_err());
}
<|endoftext|>


<commit_before><commit_msg>util/splitvec: Vector with stack-like state management<commit_after>//! Types for Vec-based storage with stack-like pushable states.

use std::fmt;
use std::mem;
use std::ptr;
use std::slice;
use std::convert::From;
use std::default::Default;
use std::ops::{Deref, DerefMut, Index, Range, RangeFrom, RangeFull, RangeTo};

/// Vec-like type with support for saving and restoring states via stack-like
/// operations
///
///
#[derive(Clone)]
pub struct SplitVec<T> {
    data: Vec<T>,
    splits: Vec<usize>
}

impl<T> SplitVec<T> {

    /// Create a new, empty SplitVec instance.
    #[inline]
    pub fn new() -> Self {
        SplitVec{data: Vec::new(), splits: Vec::new()}
    }

    /// Create a new, empty SplitVec instance with space for the specified
    /// number of entries.
    #[inline]
    pub fn with_capacity(data_capacity: usize, splits_capacity: usize) -> Self {
        SplitVec{data: Vec::with_capacity(data_capacity), splits: Vec::with_capacity(splits_capacity)}
    }

    /// Determine the offset of the first item in the current state.
    #[inline]
    fn offset(&self) -> usize {
        self.splits.last().cloned().unwrap_or_else(|| 0)
    }

    /// Mark a split above the current working state.
    ///
    /// This creates a new, empty state at the top of the `SplitVec`'s stack;
    /// you can use `pop_state` to return to the previous state or
    /// `pop_and_merge_states` to merge the current state with the
    /// previous one.
    #[inline]
    pub fn push_state(&mut self) {
        self.splits.push(self.data.len());
    }

    /// Mark a split above the current working state, then copy the contents of
    /// that state into the new working area.
    pub fn push_and_copy_state(&mut self) where T: Copy {
        let ofs = self.offset();
        let count = self.len();
        self.push_state();
        self.data.reserve(count);
        unsafe {
            let src = self.data.as_ptr().offset(ofs as isize);
            let dst = self.data.as_mut_ptr().offset((ofs + count) as isize);
            ptr::copy_nonoverlapping(src,
                                     dst,
                                     count);
            self.data.set_len(ofs + 2 * count);
        }
    }

    /// Restore the most-recently-pushed state, discarding all data added to
    /// the working vector since the last call to `push_state`.
    #[inline]
    pub fn pop_state(&mut self) {
        self.data.truncate(self.splits.pop().expect("Call to `pop_state` without prior matching `push_state` call"));
    }

    /// Remove the split between the current and previous states; this has the
    /// effect of merging their contents into the previous state.
    ///
    /// Calling this method will have no effect if no prior state exists.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # extern crate cripes;
    /// # use cripes::util::splitvec::SplitVec;
    /// # fn main() {
    /// let mut s = SplitVec::from(vec![1, 2, 3]);
    /// s.push_state();
    ///
    /// s.extend_from_slice(&[4, 5, 6]);
    /// assert_eq!(&*s, &[4, 5, 6]);
    ///
    /// s.pop_and_merge_states();
    /// assert_eq!(&*s, &[1, 2, 3, 4, 5, 6]);
    /// # }
    /// ```
    #[inline]
    pub fn pop_and_merge_states(&mut self) {
        self.splits.pop();
    }

    /// Get the number of items in the working state.
    #[inline]
    pub fn len(&self) -> usize {
        self.data.len() - self.offset()
    }

    /// Truncate the working state to at most a given number of elements.
    #[inline]
    pub fn truncate(&mut self, len: usize) {
        let ofs = self.offset();
        self.data.truncate(ofs + len)
    }

    /// Push an item onto the end of the working state.
    pub fn push(&mut self, value: T) {
        self.data.push(value)
    }

    /// Remove the top-most item from the working state and return it.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # extern crate cripes;
    /// # use cripes::util::splitvec::SplitVec;
    /// # fn main() {
    /// let mut s = SplitVec::new();
    /// assert_eq!(None, s.pop());
    ///
    /// s.extend_from_slice(&[1, 2, 3]);
    /// assert_eq!(Some(3), s.pop());
    /// # }
    /// ```
    ///
    /// `pop` works only within the current state, and will return `None` if the
    /// current state is empty even if a prior state is not:
    ///
    /// ```rust
    /// # extern crate cripes;
    /// # use cripes::util::splitvec::SplitVec;
    /// # fn main() {
    /// let mut s = SplitVec::from(vec![1, 2, 3]);
    /// s.push_state();
    ///
    /// assert_eq!(None, s.pop());
    /// # }
    /// ```
    pub fn pop(&mut self) -> Option<T> {
        if self.len() > 0 { self.data.pop() }
        else { None }
    }

    /// Extend the current working state from a slice.
    #[inline]
    pub fn extend_from_slice<'a>(&mut self, slice: &'a [T]) where T: Copy {
        self.data.extend_from_slice(slice)
    }

    /// Get a reference to the current working state as a slice.
    #[inline]
    pub fn as_slice(&self) -> &[T] {
        self
    }

    /// Remove adjacent duplicates in the working state.
    pub fn dedup(&mut self) where T: PartialEq {
        unsafe {
            let ofs = self.offset();
            let ln = self.data.len();
            if ln <= ofs {
                return;
            }

            let p = self.data.as_mut_ptr();
            let mut r: usize = 1 + ofs;
            let mut w: usize = 1 + ofs;

            while r < ln {
                let p_r = p.offset(r as isize);
                let p_wm1 = p.offset((w - 1) as isize);
                if *p_r != *p_wm1 {
                    if r != w {
                        let p_w = p_wm1.offset(1);
                        mem::swap(&mut *p_r, &mut *p_w);
                    }
                    w += 1;
                }
                r += 1;
            }

            self.truncate(w - ofs);
        }
    }

    /// Iterate over all states contained within the SplitVec.
    ///
    /// The final state is guaranteed to be the current working state.
    pub fn iter_states<'a>(&'a self) -> StateIter<'a, T> {
        StateIter{splits_iter: self.splits.iter(), data: &self.data[..], last_split: Some(0)}
    }
}

/// Iterator over the states of a SplitVec as slices.
///
/// Instances of `StateIter` are obtained by calling `iter_states` on
/// a [`SplitVec`](struct.SplitVec.html).
pub struct StateIter<'a,T> where T: 'a {
    splits_iter: slice::Iter<'a,usize>,
    data: &'a [T],
    last_split: Option<usize>
}

impl<'a, T: 'a> Iterator for StateIter<'a, T> {
    type Item = &'a [T];
    fn next(&mut self) -> Option<Self::Item> {
        if let Some(start) = self.last_split {
            if let Some(end) = self.splits_iter.next() {
                self.last_split = Some(*end);
                Some(&self.data[start..*end])
            } else {
                self.last_split = None;
                Some(&self.data[start..])
            }
        } else { None }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.splits_iter.size_hint()
    }
}

use itertools::Itertools;
impl<T> fmt::Debug for SplitVec<T> where T: fmt::Debug {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "[{}]",
               self.iter_states().map(|s| s.iter().map(|ref elt| format!("{:?}", elt)).join(", "))
               .join(" | "))
    }
}

impl<T> From<Vec<T>> for SplitVec<T> {
    fn from(v: Vec<T>) -> Self {
        SplitVec{data: v, splits: Vec::new()}
    }
}

impl<'a,T> From<&'a [T]> for SplitVec<T> where T: Clone {
    fn from(s: &'a [T]) -> Self {
        SplitVec{data: s.into(), splits: Vec::new()}
    }
}

impl<T> Default for SplitVec<T> {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl<T> Extend<T> for SplitVec<T> {
    fn extend<I>(&mut self, iter: I) where I: IntoIterator<Item=T> {
        self.data.extend(iter);
    }
}

impl<T> Deref for SplitVec<T> {
    type Target = [T];
    fn deref(&self) -> &Self::Target {
        let o = self.offset();
        &self.data[o..]
    }
}

impl<T> DerefMut for SplitVec<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        let o = self.offset();
        &mut self.data[o..]
    }
}

impl<T> Index<usize> for SplitVec<T> {
    type Output = T;
    #[inline]
    fn index<'a>(&'a self, idx: usize) -> &'a T {
        let o = self.offset();
        &self.data[idx + o]
    }
}

impl<T> Index<Range<usize>> for SplitVec<T> {
    type Output = [T];
    #[inline]
    fn index<'a>(&'a self, r: Range<usize>) -> &'a [T] {
        let o = self.offset();
        &self.data[(o + r.start)..(o + r.end)]
    }
}
impl<T> Index<RangeFrom<usize>> for SplitVec<T> {
    type Output = [T];
    #[inline]
    fn index<'a>(&'a self, r: RangeFrom<usize>) -> &'a [T] {
        let o = self.offset();
        &self.data[(o + r.start)..]
    }
}
impl<T> Index<RangeTo<usize>> for SplitVec<T> {
    type Output = [T];
    #[inline]
    fn index<'a>(&'a self, r: RangeTo<usize>) -> &'a [T] {
        let o = self.offset();
        &self.data[..(o + r.end)]
    }
}
impl<T> Index<RangeFull> for SplitVec<T> {
    type Output = [T];
    #[inline(always)]
    fn index<'a>(&'a self, _: RangeFull) -> &'a [T] {
        &self.data[..]
    }
}
<|endoftext|>


<commit_before><commit_msg>add regression test for #68596<commit_after>// check-pass
#![feature(const_generics)]
#![allow(incomplete_features)]

pub struct S(u8);

impl S {
    pub fn get<const A: u8>(&self) -> &u8 {
        &self.0
    }
}

fn main() {
    const A: u8 = 5;
    let s = S(0);

    s.get::<A>();
}
<|endoftext|>


<commit_before><commit_msg>Document encoding behavior for FormItems.<commit_after><|endoftext|>


<commit_before><commit_msg>Fix overflow in script<commit_after><|endoftext|>


<commit_before>#![feature(crate_visibility_modifier)]
#![feature(crate_in_paths)]

mod bar {
    crate struct Foo;
}

fn main() {
    Foo;
    //~^ ERROR cannot find value `Foo` in this scope [E0425]
}
<commit_msg>add missing license header<commit_after>// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![feature(crate_visibility_modifier)]
#![feature(crate_in_paths)]

mod bar {
    crate struct Foo;
}

fn main() {
    Foo;
    //~^ ERROR cannot find value `Foo` in this scope [E0425]
}
<|endoftext|>


<commit_before><commit_msg>add write-bytes test<commit_after>fn main() {
    const LENGTH: usize = 10;
    let mut v: [u64; LENGTH] = [0; LENGTH];

    for idx in 0..LENGTH {
        assert_eq!(v[idx], 0);
    }

    unsafe {
        let p = v.as_mut_ptr();
        ::std::ptr::write_bytes(p, 0xab, LENGTH);
    }

    for idx in 0..LENGTH {
        assert_eq!(v[idx], 0xabababababababab);
    }
}
<|endoftext|>


<commit_before><commit_msg>Revert `?` operator for Display for Host<commit_after><|endoftext|>


<commit_before><commit_msg>std::path is now stable<commit_after><|endoftext|>


<commit_before><commit_msg>Mostly ignore train orders.<commit_after><|endoftext|>


<commit_before><commit_msg>Update main.rs<commit_after><|endoftext|>


<commit_before><commit_msg>Renamed CommandMessage enum to UIToAPIMessage<commit_after><|endoftext|>


<commit_before><commit_msg>Read and output guess<commit_after>use std::io;

fn main() {
        println!("Guess the number!");

        println!("Please input your guess.");

        let mut guess = String::new();

        io::stdin().read_line(&mut guess)
            .ok()
            .expect("Failed to read line");

        println!("You guessed: {}", guess);
}
<|endoftext|>


<commit_before><commit_msg>Creating wrappers to help debug deadlocks<commit_after>use std::sync::{RwLock, LockResult, RwLockWriteGuard, RwLockReadGuard, PoisonError};
use std::ops::{Deref, DerefMut};

pub struct LoggingRwLock<T: ?Sized> {
    lock: RwLock<T>,
}

impl <T> LoggingRwLock<T> {
    pub fn new(t: T) -> LoggingRwLock<T> {
        LoggingRwLock {
            lock: RwLock::new(t),
        }
    }
}

impl<T: ?Sized> LoggingRwLock<T> {
    pub fn write(&self, site: u32) -> LockResult<LoggingRwLockWriteGuard<T>> {
       debug!("write() called at line {}", site);
       match self.lock.write() {
           Ok(locked) => {
               Ok(LoggingRwLockWriteGuard{guard: locked})
           },
           Err(locked) => {
               Err(PoisonError::new(LoggingRwLockWriteGuard{guard: locked.into_inner()}))
           },
       }
    }

    pub fn read(&self) -> LockResult<LoggingRwLockReadGuard<T>> {
        debug!("read() called");
        match self.lock.read() {
            Ok(locked) => {
                Ok(LoggingRwLockReadGuard{guard: locked})
            },
            Err(locked) => {
                Err(PoisonError::new(LoggingRwLockReadGuard{guard: locked.into_inner()}))
            },
        }
    }
}

pub struct LoggingRwLockReadGuard<'a, T: ?Sized + 'a> {
    guard: RwLockReadGuard<'a, T>,
}

impl <'rwlock, T: ?Sized> Deref for LoggingRwLockReadGuard<'rwlock, T> {
    type Target = T;
    fn deref(&self) -> &T {
        self.guard.deref()
    }
}
impl <'a, T: ?Sized> Drop for LoggingRwLockReadGuard<'a, T> {
    fn drop(&mut self) {
        debug!("dropping lock");
    }
}

pub struct LoggingRwLockWriteGuard<'a, T: ?Sized + 'a> {
    guard: RwLockWriteGuard<'a, T>,
}

impl <'rwlock, T: ?Sized> Deref for LoggingRwLockWriteGuard<'rwlock, T> {
    type Target = T;
    fn deref(&self) -> &T {
        self.guard.deref()
    }
}
impl <'rwlock, T: ?Sized> DerefMut for LoggingRwLockWriteGuard<'rwlock, T> {
    fn deref_mut(&mut self) -> &mut T {
        self.guard.deref_mut()
    }
}
impl <'a, T: ?Sized> Drop for LoggingRwLockWriteGuard<'a, T> {
    fn drop(&mut self) {
        debug!("dropping write lock");
    }
}
<|endoftext|>


<commit_before><commit_msg>Added support for router_id to ZMsgExtended<commit_after><|endoftext|>


<commit_before><commit_msg>Skeleton for problem 2309<commit_after>// https://leetcode.com/problems/greatest-english-letter-in-upper-and-lower-case/
pub fn greatest_letter(s: String) -> String {
    todo!();
}

fn main() {
    println!("{}", greatest_letter(String::from("lEeTcOdE"))); // "E"
    println!("{}", greatest_letter(String::from("arRAzFif"))); // "R"
    println!("{}", greatest_letter(String::from("AbCdEfGhIjK"))); // ""
}
<|endoftext|>


<commit_before><commit_msg>Started making a less inefficient collision detector<commit_after>use std::collections::HashSet;
use super::{Nearness};
use {RowId, ColumnId, Column, Mutator};
use std::marker::PhantomData;

pub trait Basics: super::Basics {
  type SpaceCoordinate;
  fn grid_size()->Self::SpaceCoordinate;
  fn get_center()->
}

struct Cell <B: Basics> {
  _marker: PhantomData<B>,
}
impl<B: Basics> Column for Cell <B> {
  type FieldType = HashSet <RowId>;
  fn column_id() -> ColumnId {
    ColumnId(B::nearness_column_id().0 ^ 0x030fc8868af34f2c)
  }
}

fn cell_row (x: i64, y: i64, me: B::DetectorId) {RowId::new (& [x, y, me])}
fn get_center<B: Basics, M: Mutator<B::StewardBasics>>(mutator: &mut M,
                                                       who: RowId,
                                                       me: B::DetectorId) {
  B::get_center(mutator, who, me)
}
pub fn insert<B: Basics, M: Mutator<B::StewardBasics>>(mutator: &mut M,
                                                       who: RowId,
                                                       me: B::DetectorId) {
  let (x, y) = get_center:: <B, M> (mutator, who, me);
  for next in x - 1..x + 2 {for what in y - 1..y + 2 {
    let row = cell_row (next, what, me);
    let mut members = mutator.get::<Cell <B>>(row).cloned().unwrap_or(HashSet::new());
    for member in members.iter() {
      let (id, contents) = Nearness::new(who, member.clone(), me);
      mutator.set::<Nearness<B>>(id, Some(contents));
    }
    if next == x && what == y {
      members.insert(who);
      mutator.set::<Cell <B>>(row, Some(members));
    }
  }}
}

pub fn erase<B: Basics, M: Mutator<B::StewardBasics>>(mutator: &mut M,
                                                      who: RowId,
                                                      me: B::DetectorId) {
  let (x, y) = get_center:: <B, M> (mutator, who, me);
  for next in x - 1..x + 2 {for what in y - 1..y + 2 {
    let row = cell_row (next, what, me);
    let mut members = mutator.get::<Cell <B>>(row).cloned().unwrap_or(HashSet::new());
    if next == x && what == y {
      members.remove (&who);
      mutator.set::<Cell <B>>(row, if members.is_empty() {
                               None
                             } else {
                               Some(members)
                             });
    }
    for member in members.iter() {
      let (id,_) = Nearness::new(who, member.clone(), me);
      mutator.set::<Nearness<B>>(id, None);
    }
  }}
}

macro_rules! push_predictors {
($module: ident, $predictors: ident) => {{
$predictors.push ($module::Predictor {
predictor_id: PredictorId (),
column_id:,
function: Rc::new (| accessor, id | {
let center = B::get_center (accessor, id: me);
if let Some (time) = B::when_escapes (accessor, id, center) {
accessor.predict_at_time (& time, Rc::new (move | mutator | {

});
}
}),
});
}}
}
<|endoftext|>


<commit_before><commit_msg>Add TokenType<commit_after>#[derive(Debug)]
pub enum TokenType {
    // single-character tokens
    LeftParen, RightParen, LeftBrace, RightBrace,
    Comma, Dot, Minus, Plus, Semicolon, Slash, Star,

    // One or two character tokens
    Bang, BangEqual,
    Equal, EqualEquaL,
    Greater, GreaterEqual,
    Lesser, LesserEqual,

    // Literals
    Identifier, String, Number,

    // Keywords
    And, Class, Else, False, Fun, For, If, Nil, Or,
    Print, Return, Super, This, True, Var, While,

    Eof,
}
<|endoftext|>


<commit_before><commit_msg>Make "ask" functions get input and output streams<commit_after><|endoftext|>


<commit_before><commit_msg>please the borrow checker.<commit_after><|endoftext|>


<commit_before>fn blk1(b: block()) -> fn@() { ret fn@() { }; }

fn test1() { (blk1 {|| #debug["hi"]; })(); }

fn test2() { (blk1 {|| #debug["hi"]; }) {|| #debug["ho"]; }; }
<commit_msg>make test typecheck<commit_after>fn blk1(b: block()) -> fn@() { ret fn@() { }; }
fn test1() { (blk1 {|| #debug["hi"]; })(); }
<|endoftext|>