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

//! Basic html highlighting functionality
//!
//! This module uses libsyntax's lexer to provide token-based highlighting for
//! the HTML documentation generated by rustdoc.

use html::escape::Escape;

use std::io;
use std::io::prelude::*;
use syntax::parse::lexer::{self, Reader};
use syntax::parse::token;
use syntax::parse;

/// Highlights `src`, returning the HTML output.
pub fn render_with_highlighting(src: &str, class: Option<&str>, id: Option<&str>) -> String {
    debug!("highlighting: ================\n{}\n==============", src);
    let sess = parse::ParseSess::new();
    let fm = sess.codemap().new_filemap("<stdin>".to_string(), src.to_string());

    let mut out = Vec::new();
    write_header(class, id, &mut out).unwrap();
    if let Err(_) = write_source(&sess,
                                 lexer::StringReader::new(&sess.span_diagnostic, fm),
                                 &mut out) {
        return format!("
{}
", src)
    }
    write_footer(&mut out).unwrap();
    String::from_utf8_lossy(&out[..]).into_owned()
}

/// Highlights `src`, returning the HTML output. Returns only the inner html to
/// be inserted into an element. C.f., `render_with_highlighting` which includes
/// an enclosing `<pre>` block.
pub fn render_inner_with_highlighting(src: &str) -> io::Result<String> {
    let sess = parse::ParseSess::new();
    let fm = sess.codemap().new_filemap("<stdin>".to_string(), src.to_string());

    let mut out = Vec::new();
    write_source(&sess,
                 lexer::StringReader::new(&sess.span_diagnostic, fm),
                 &mut out)?;
    Ok(String::from_utf8_lossy(&out[..]).into_owned())
}

/// Exhausts the `lexer` writing the output into `out`.
///
/// The general structure for this method is to iterate over each token,
/// possibly giving it an HTML span with a class specifying what flavor of token
/// it's used. All source code emission is done as slices from the source map,
/// not from the tokens themselves, in order to stay true to the original
/// source.
fn write_source(sess: &parse::ParseSess,
                mut lexer: lexer::StringReader,
                out: &mut Write)
                -> io::Result<()> {
    let mut is_attribute = false;
    let mut is_macro = false;
    let mut is_macro_nonterminal = false;
    loop {
        let next = match lexer.try_next_token() {
            Ok(tok) => tok,
            Err(_) => {
                lexer.emit_fatal_errors();
                lexer.span_diagnostic.struct_warn("Backing out of syntax highlighting")
                                     .note("You probably did not intend to render this \
                                            as a rust code-block")
                                     .emit();
                return Err(io::Error::new(io::ErrorKind::Other, ""))
            },
        };

        let snip = |sp| sess.codemap().span_to_snippet(sp).unwrap();

        if next.tok == token::Eof { break }

        let klass = match next.tok {
            token::Whitespace => {
                write!(out, "{}", Escape(&snip(next.sp)))?;
                continue
            },
            token::Comment => {
                write!(out, "{}",
                       Escape(&snip(next.sp)))?;
                continue
            },
            token::Shebang(s) => {
                write!(out, "{}", Escape(&s.as_str()))?;
                continue
            },
            // If this '&' token is directly adjacent to another token, assume
            // that it's the address-of operator instead of the and-operator.
            // This allows us to give all pointers their own class (`Box` and
            // `@` are below).
            token::BinOp(token::And) if lexer.peek().sp.lo == next.sp.hi => "kw-2",
            token::At | token::Tilde => "kw-2",

            // consider this as part of a macro invocation if there was a
            // leading identifier
            token::Not if is_macro => { is_macro = false; "macro" }

            // operators
            token::Eq | token::Lt | token::Le | token::EqEq | token::Ne | token::Ge | token::Gt |
                token::AndAnd | token::OrOr | token::Not | token::BinOp(..) | token::RArrow |
                token::BinOpEq(..) | token::FatArrow => "op",

            // miscellaneous, no highlighting
            token::Dot | token::DotDot | token::DotDotDot | token::Comma | token::Semi |
                token::Colon | token::ModSep | token::LArrow | token::OpenDelim(_) |
                token::CloseDelim(token::Brace) | token::CloseDelim(token::Paren) |
                token::Question => "",
            token::Dollar => {
                if lexer.peek().tok.is_ident() {
                    is_macro_nonterminal = true;
                    "macro-nonterminal"
                } else {
                    ""
                }
            }

            // This is the start of an attribute. We're going to want to
            // continue highlighting it as an attribute until the ending ']' is
            // seen, so skip out early. Down below we terminate the attribute
            // span when we see the ']'.
            token::Pound => {
                is_attribute = true;
                write!(out, r"#")?;
                continue
            }
            token::CloseDelim(token::Bracket) => {
                if is_attribute {
                    is_attribute = false;
                    write!(out, "]")?;
                    continue
                } else {
                    ""
                }
            }

            token::Literal(lit, _suf) => {
                match lit {
                    // text literals
                    token::Byte(..) | token::Char(..) |
                        token::ByteStr(..) | token::ByteStrRaw(..) |
                        token::Str_(..) | token::StrRaw(..) => "string",

                    // number literals
                    token::Integer(..) | token::Float(..) => "number",
                }
            }

            // keywords are also included in the identifier set
            token::Ident(ident) => {
                match &*ident.name.as_str() {
                    "ref" | "mut" => "kw-2",

                    "self" => "self",
                    "false" | "true" => "boolval",

                    "Option" | "Result" => "prelude-ty",
                    "Some" | "None" | "Ok" | "Err" => "prelude-val",

                    _ if next.tok.is_any_keyword() => "kw",
                    _ => {
                        if is_macro_nonterminal {
                            is_macro_nonterminal = false;
                            "macro-nonterminal"
                        } else if lexer.peek().tok == token::Not {
                            is_macro = true;
                            "macro"
                        } else {
                            "ident"
                        }
                    }
                }
            }

            // Special macro vars are like keywords
            token::SpecialVarNt(_) => "kw-2",

            token::Lifetime(..) => "lifetime",
            token::DocComment(..) => "doccomment",
            token::Underscore | token::Eof | token::Interpolated(..) |
                token::MatchNt(..) | token::SubstNt(..) => "",
        };

        // as mentioned above, use the original source code instead of
        // stringifying this token
        let snip = sess.codemap().span_to_snippet(next.sp).unwrap();
        if klass == "" {
            write!(out, "{}", Escape(&snip))?;
        } else {
            write!(out, "{}", klass, Escape(&snip))?;
        }
    }

    Ok(())
}

fn write_header(class: Option<&str>,
                id: Option<&str>,
                out: &mut Write)
                -> io::Result<()> {
    write!(out, "
 write!(out, "id='{}' ", id)?,
        None => {}
    }
    write!(out, "class='rust {}'>\n", class.unwrap_or(""))
}

fn write_footer(out: &mut Write) -> io::Result<()> {
    write!(out, "
\n")
}
<commit_msg>rustdoc: refactor rustdoc syntax highlighting for a more flexible API<commit_after>// Copyright 2014-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.

//! Basic syntax highlighting functionality.
//!
//! This module uses libsyntax's lexer to provide token-based highlighting for
//! the HTML documentation generated by rustdoc.
//!
//! If you just want to syntax highlighting for a Rust program, then you can use
//! the `render_inner_with_highlighting` or `render_with_highlighting`
//! functions. For more advanced use cases (if you want to supply your own css
//! classes or control how the HTML is generated, or even generate something
//! other then HTML), then you should implement the the `Writer` trait and use a
//! `Classifier`.

use html::escape::Escape;

use std::fmt::Display;
use std::io;
use std::io::prelude::*;

use syntax::codemap::{CodeMap, Span};
use syntax::parse::lexer::{self, Reader, TokenAndSpan};
use syntax::parse::token;
use syntax::parse;

/// Highlights `src`, returning the HTML output.
pub fn render_with_highlighting(src: &str, class: Option<&str>, id: Option<&str>) -> String {
    debug!("highlighting: ================\n{}\n==============", src);
    let sess = parse::ParseSess::new();
    let fm = sess.codemap().new_filemap("<stdin>".to_string(), src.to_string());

    let mut out = Vec::new();
    write_header(class, id, &mut out).unwrap();

    let mut classifier = Classifier::new(lexer::StringReader::new(&sess.span_diagnostic, fm),
                                         sess.codemap());
    if let Err(_) = classifier.write_source(&mut out) {
        return format!("
{}
", src);
    }

    write_footer(&mut out).unwrap();
    String::from_utf8_lossy(&out[..]).into_owned()
}

/// Highlights `src`, returning the HTML output. Returns only the inner html to
/// be inserted into an element. C.f., `render_with_highlighting` which includes
/// an enclosing `<pre>` block.
pub fn render_inner_with_highlighting(src: &str) -> io::Result<String> {
    let sess = parse::ParseSess::new();
    let fm = sess.codemap().new_filemap("<stdin>".to_string(), src.to_string());

    let mut out = Vec::new();
    let mut classifier = Classifier::new(lexer::StringReader::new(&sess.span_diagnostic, fm),
                                         sess.codemap());
    classifier.write_source(&mut out)?;

    Ok(String::from_utf8_lossy(&out).into_owned())
}

/// Processes a program (nested in the internal `lexer`), classifying strings of
/// text by highlighting category (`Class`). Calls out to a `Writer` to write
/// each span of text in sequence.
pub struct Classifier<'a> {
    lexer: lexer::StringReader<'a>,
    codemap: &'a CodeMap,

    // State of the classifier.
    in_attribute: bool,
    in_macro: bool,
    in_macro_nonterminal: bool,
}

/// How a span of text is classified. Mostly corresponds to token kinds.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Class {
    None,
    Comment,
    DocComment,
    Attribute,
    KeyWord,
    // Keywords that do pointer/reference stuff.
    RefKeyWord,
    Self_,
    Op,
    Macro,
    MacroNonTerminal,
    String,
    Number,
    Bool,
    Ident,
    Lifetime,
    PreludeTy,
    PreludeVal,
}

/// Trait that controls writing the output of syntax highlighting. Users should
/// implement this trait to customise writing output.
///
/// The classifier will call into the `Writer` implementation as it finds spans
/// of text to highlight. Exactly how that text should be highlighted is up to
/// the implemention.
pub trait Writer {
    /// Called when we start processing a span of text that should be highlighted.
    /// The `Class` argument specifies how it should be highlighted.
    fn enter_span(&mut self, Class) -> io::Result<()>;

    /// Called at the end of a span of highlighted text.
    fn exit_span(&mut self) -> io::Result<()>;

    /// Called for a span of text, usually, but not always, a single token. If
    /// the string of text (`T`) does correspond to a token, then the token will
    /// also be passed. If the text should be highlighted differently from the
    /// surrounding text, then the `Class` argument will be a value other than
    /// `None`.
    /// The following sequences of callbacks are equivalent:
    /// ```plain
    ///     enter_span(Foo), string("text", None), exit_span()
    ///     string("text", Foo)
    /// ```
    /// The latter can be thought of as a shorthand for the former, which is
    /// more flexible.
    fn string<T: Display>(&mut self, T, Class, Option<&TokenAndSpan>) -> io::Result<()>;
}

// Implement `Writer` for anthing that can be written to, this just implements
// the default rustdoc behaviour.
impl Writer for U {
    fn string<T: Display>(&mut self,
                          text: T,
                          klass: Class,
                          _tas: Option<&TokenAndSpan>)
                          -> io::Result<()> {
        match klass {
            Class::None => write!(self, "{}", text),
            klass => write!(self, "{}", klass.rustdoc_class(), text),
        }
    }

    fn enter_span(&mut self, klass: Class) -> io::Result<()> {
        write!(self, "", klass.rustdoc_class())
    }

    fn exit_span(&mut self) -> io::Result<()> {
        write!(self, "")
    }
}

impl<'a> Classifier<'a> {
    pub fn new(lexer: lexer::StringReader<'a>, codemap: &'a CodeMap) -> Classifier<'a> {
        Classifier {
            lexer: lexer,
            codemap: codemap,
            in_attribute: false,
            in_macro: false,
            in_macro_nonterminal: false,
        }
    }

    /// Exhausts the `lexer` writing the output into `out`.
    ///
    /// The general structure for this method is to iterate over each token,
    /// possibly giving it an HTML span with a class specifying what flavor of token
    /// is used. All source code emission is done as slices from the source map,
    /// not from the tokens themselves, in order to stay true to the original
    /// source.
    pub fn write_source<W: Writer>(&mut self,
                                   out: &mut W)
                                   -> io::Result<()> {
        loop {
            let next = match self.lexer.try_next_token() {
                Ok(tas) => tas,
                Err(_) => {
                    self.lexer.emit_fatal_errors();
                    self.lexer.span_diagnostic.struct_warn("Backing out of syntax highlighting")
                                              .note("You probably did not intend to render this \
                                                     as a rust code-block")
                                              .emit();
                    return Err(io::Error::new(io::ErrorKind::Other, ""));
                }
            };

            if next.tok == token::Eof {
                break;
            }

            self.write_token(out, next)?;
        }

        Ok(())
    }

    // Handles an individual token from the lexer.
    fn write_token<W: Writer>(&mut self,
                              out: &mut W,
                              tas: TokenAndSpan)
                              -> io::Result<()> {
        let klass = match tas.tok {
            token::Shebang(s) => {
                out.string(Escape(&s.as_str()), Class::None, Some(&tas))?;
                return Ok(());
            },

            token::Whitespace => Class::None,
            token::Comment => Class::Comment,
            token::DocComment(..) => Class::DocComment,

            // If this '&' token is directly adjacent to another token, assume
            // that it's the address-of operator instead of the and-operator.
            token::BinOp(token::And) if self.lexer.peek().sp.lo == tas.sp.hi => Class::RefKeyWord,

            // Consider this as part of a macro invocation if there was a
            // leading identifier.
            token::Not if self.in_macro => {
                self.in_macro = false;
                Class::Macro
            }

            // Operators.
            token::Eq | token::Lt | token::Le | token::EqEq | token::Ne | token::Ge | token::Gt |
                token::AndAnd | token::OrOr | token::Not | token::BinOp(..) | token::RArrow |
                token::BinOpEq(..) | token::FatArrow => Class::Op,

            // Miscellaneous, no highlighting.
            token::Dot | token::DotDot | token::DotDotDot | token::Comma | token::Semi |
                token::Colon | token::ModSep | token::LArrow | token::OpenDelim(_) |
                token::CloseDelim(token::Brace) | token::CloseDelim(token::Paren) |
                token::Question => Class::None,
            token::Dollar => {
                if self.lexer.peek().tok.is_ident() {
                    self.in_macro_nonterminal = true;
                    Class::MacroNonTerminal
                } else {
                    Class::None
                }
            }

            // This is the start of an attribute. We're going to want to
            // continue highlighting it as an attribute until the ending ']' is
            // seen, so skip out early. Down below we terminate the attribute
            // span when we see the ']'.
            token::Pound => {
                self.in_attribute = true;
                out.enter_span(Class::Attribute)?;
                out.string("#", Class::None, None)?;
                return Ok(());
            }
            token::CloseDelim(token::Bracket) => {
                if self.in_attribute {
                    self.in_attribute = false;
                    out.string("]", Class::None, None)?;
                    out.exit_span()?;
                    return Ok(());
                } else {
                    Class::None
                }
            }

            token::Literal(lit, _suf) => {
                match lit {
                    // Text literals.
                    token::Byte(..) | token::Char(..) |
                        token::ByteStr(..) | token::ByteStrRaw(..) |
                        token::Str_(..) | token::StrRaw(..) => Class::String,

                    // Number literals.
                    token::Integer(..) | token::Float(..) => Class::Number,
                }
            }

            // Keywords are also included in the identifier set.
            token::Ident(ident) => {
                match &*ident.name.as_str() {
                    "ref" | "mut" => Class::RefKeyWord,

                    "self" |"Self" => Class::Self_,
                    "false" | "true" => Class::Bool,

                    "Option" | "Result" => Class::PreludeTy,
                    "Some" | "None" | "Ok" | "Err" => Class::PreludeVal,

                    _ if tas.tok.is_any_keyword() => Class::KeyWord,
                    _ => {
                        if self.in_macro_nonterminal {
                            self.in_macro_nonterminal = false;
                            Class::MacroNonTerminal
                        } else if self.lexer.peek().tok == token::Not {
                            self.in_macro = true;
                            Class::Macro
                        } else {
                            Class::Ident
                        }
                    }
                }
            }

            // Special macro vars are like keywords.
            token::SpecialVarNt(_) => Class::KeyWord,

            token::Lifetime(..) => Class::Lifetime,

            token::Underscore | token::Eof | token::Interpolated(..) |
            token::MatchNt(..) | token::SubstNt(..) | token::Tilde | token::At => Class::None,
        };

        // Anything that didn't return above is the simple case where we the
        // class just spans a single token, so we can use the `string` method.
        out.string(Escape(&self.snip(tas.sp)), klass, Some(&tas))
    }

    // Helper function to get a snippet from the codemap.
    fn snip(&self, sp: Span) -> String {
        self.codemap.span_to_snippet(sp).unwrap()
    }
}

impl Class {
    /// Returns the css class expected by rustdoc for each `Class`.
    pub fn rustdoc_class(self) -> &'static str {
        match self {
            Class::None => "",
            Class::Comment => "comment",
            Class::DocComment => "doccomment",
            Class::Attribute => "attribute",
            Class::KeyWord => "kw",
            Class::RefKeyWord => "kw-2",
            Class::Self_ => "self",
            Class::Op => "op",
            Class::Macro => "macro",
            Class::MacroNonTerminal => "macro-nonterminal",
            Class::String => "string",
            Class::Number => "number",
            Class::Bool => "boolvalue",
            Class::Ident => "ident",
            Class::Lifetime => "lifetime",
            Class::PreludeTy => "prelude-ty",
            Class::PreludeVal => "prelude-val",
        }
    }
}

fn write_header(class: Option<&str>,
                id: Option<&str>,
                out: &mut Write)
                -> io::Result<()> {
    write!(out, "
 write!(out, "id='{}' ", id)?,
        None => {}
    }
    write!(out, "class='rust {}'>\n", class.unwrap_or(""))
}

fn write_footer(out: &mut Write) -> io::Result<()> {
    write!(out, "
\n")
}
<|endoftext|>


<commit_before>//! Server flow statistic

use std::sync::atomic::Ordering;

#[cfg(not(any(target_arch = "mips", target_arch = "powerpc")))]
type FlowCounter = std::sync::atomic::AtomicU64;
#[cfg(any(target_arch = "mips", target_arch = "powerpc"))]
type FlowCounter = std::sync::atomic::AtomicU32;

/// Connection flow statistic
pub struct FlowStat {
    tx: FlowCounter,
    rx: FlowCounter,
}

impl FlowStat {
    /// Create an empty flow statistic
    pub fn new() -> FlowStat {
        FlowStat {
            tx: FlowCounter::new(0),
            rx: FlowCounter::new(0),
        }
    }

    /// Transmitted bytes count
    #[cfg(not(any(target_arch = "mips", target_arch = "powerpc")))]
    pub fn tx(&self) -> u64 {
        self.tx.load(Ordering::Relaxed)
    }

    /// Transmitted bytes count
    #[cfg(any(target_arch = "mips", target_arch = "powerpc"))]
    pub fn tx(&self) -> u64 {
        self.tx.load(Ordering::Relaxed) as u64
    }

    /// Increase transmitted bytes
    #[cfg(not(any(target_arch = "mips", target_arch = "powerpc")))]
    pub fn incr_tx(&self, n: u64) {
        self.tx.fetch_add(n, Ordering::AcqRel);
    }

    /// Increase transmitted bytes
    #[cfg(any(target_arch = "mips", target_arch = "powerpc"))]
    pub fn incr_tx(&self, n: u64) {
        self.tx.fetch_add(n as u32, Ordering::AcqRel);
    }

    /// Received bytes count
    #[cfg(not(any(target_arch = "mips", target_arch = "powerpc")))]
    pub fn rx(&self) -> u64 {
        self.rx.load(Ordering::Relaxed)
    }

    /// Received bytes count
    #[cfg(any(target_arch = "mips", target_arch = "powerpc"))]
    pub fn rx(&self) -> u64 {
        self.rx.load(Ordering::Relaxed) as u32
    }

    /// Increase received bytes
    #[cfg(not(any(target_arch = "mips", target_arch = "powerpc")))]
    pub fn incr_rx(&self, n: u64) {
        self.rx.fetch_add(n, Ordering::AcqRel);
    }

    /// Increase received bytes
    #[cfg(any(target_arch = "mips", target_arch = "powerpc"))]
    pub fn incr_rx(&self, n: u64) {
        self.rx.fetch_add(n as u32, Ordering::AcqRel);
    }
}
<commit_msg>fix mips flow.rs build error<commit_after>//! Server flow statistic

use std::sync::atomic::Ordering;

#[cfg(not(any(target_arch = "mips", target_arch = "powerpc")))]
type FlowCounter = std::sync::atomic::AtomicU64;
#[cfg(any(target_arch = "mips", target_arch = "powerpc"))]
type FlowCounter = std::sync::atomic::AtomicU32;

/// Connection flow statistic
pub struct FlowStat {
    tx: FlowCounter,
    rx: FlowCounter,
}

impl FlowStat {
    /// Create an empty flow statistic
    pub fn new() -> FlowStat {
        FlowStat {
            tx: FlowCounter::new(0),
            rx: FlowCounter::new(0),
        }
    }

    /// Transmitted bytes count
    #[cfg(not(any(target_arch = "mips", target_arch = "powerpc")))]
    pub fn tx(&self) -> u64 {
        self.tx.load(Ordering::Relaxed)
    }

    /// Transmitted bytes count
    #[cfg(any(target_arch = "mips", target_arch = "powerpc"))]
    pub fn tx(&self) -> u64 {
        self.tx.load(Ordering::Relaxed) as u64
    }

    /// Increase transmitted bytes
    #[cfg(not(any(target_arch = "mips", target_arch = "powerpc")))]
    pub fn incr_tx(&self, n: u64) {
        self.tx.fetch_add(n, Ordering::AcqRel);
    }

    /// Increase transmitted bytes
    #[cfg(any(target_arch = "mips", target_arch = "powerpc"))]
    pub fn incr_tx(&self, n: u64) {
        self.tx.fetch_add(n as u32, Ordering::AcqRel);
    }

    /// Received bytes count
    #[cfg(not(any(target_arch = "mips", target_arch = "powerpc")))]
    pub fn rx(&self) -> u64 {
        self.rx.load(Ordering::Relaxed)
    }

    /// Received bytes count
    #[cfg(any(target_arch = "mips", target_arch = "powerpc"))]
    pub fn rx(&self) -> u64 {
        self.rx.load(Ordering::Relaxed) as u64
    }

    /// Increase received bytes
    #[cfg(not(any(target_arch = "mips", target_arch = "powerpc")))]
    pub fn incr_rx(&self, n: u64) {
        self.rx.fetch_add(n, Ordering::AcqRel);
    }

    /// Increase received bytes
    #[cfg(any(target_arch = "mips", target_arch = "powerpc"))]
    pub fn incr_rx(&self, n: u64) {
        self.rx.fetch_add(n as u32, Ordering::AcqRel);
    }
}
<|endoftext|>


<commit_before>#![no_std]
#![allow(ctypes)]

enum Color {
    Black      = 0,
    Blue       = 1,
    Green      = 2,
    Cyan       = 3,
    Red        = 4,
    Pink       = 5,
    Brown      = 6,
    LightGray  = 7,
    DarkGray   = 8,
    LightBlue  = 9,
    LightGreen = 10,
    LightCyan  = 11,
    LightRed   = 12,
    LightPink  = 13,
    Yellow     = 14,
    White      = 15,
}

enum Option<T> {
    None,
    Some(T)
}

struct IntRange {
    cur: int,
    max: int
}

impl IntRange {
    fn next(&mut self) -> Option<int> {
        if self.cur < self.max {
            self.cur += 1;
            Some(self.cur - 1)
        } else {
            None
        }
    }
}

fn range(lo: int, hi: int) -> IntRange {
    IntRange { cur: lo, max: hi }
}

fn clear_screen(background: Color) {
    for i in range(0, 80 * 25) {
        unsafe {
            *((0xb8000 + i * 2) as *mut u16) = (background as u16) << 12;
        }
    }
}

#[no_mangle]
#[no_split_stack]
pub fn main() {
    clear_screen(LightRed);
}
<commit_msg>Fix main.rs for rustc 1.17.0-nightly (0e7727795 2017-02-19)<commit_after>#![feature(custom_attribute)]
#![no_std]
#![allow(dead_code)]
#![allow(unused_attributes)]

#[derive(Copy, Clone)]
enum Color {
    Black = 0,
    Blue = 1,
    Green = 2,
    Cyan = 3,
    Red = 4,
    Pink = 5,
    Brown = 6,
    LightGray = 7,
    DarkGray = 8,
    LightBlue = 9,
    LightGreen = 10,
    LightCyan = 11,
    LightRed = 12,
    LightPink = 13,
    Yellow = 14,
    White = 15,
}

fn clear_screen(background: Color) {
    for i in 0..80 * 25 {
        unsafe {
            *((0xb8000 + i * 2) as *mut u16) = (background as u16) << 12;
        }
    }
}

#[no_mangle]
#[no_split_stack]
pub fn main() {
    clear_screen(Color::Cyan);
}
<|endoftext|>


<commit_before>extern crate libc;

use api::ErrorCode;
use commands::{Command, CommandExecutor};
use commands::agent::AgentCommand;
use errors::ToErrorCode;
use utils::cstring::CStringUtils;

use self::libc::c_char;

/// Establishes agent to agent connection.
///
/// Information about sender Identity must be saved in the wallet with sovrin_create_and_store_my_did
/// call before establishing of connection.
///
/// Information about receiver Identity can be saved in the wallet with sovrin_store_their_did
/// call before establishing of connection. If there is no corresponded wallet record for receiver Identity
/// than this call will lookup Identity Ledger and cache this information in the wallet.
///
/// Note that messages encryption/decryption will be performed automatically.
///
/// #Params
/// command_handle: Command handle to map callback to caller context.
/// pool_handle: Pool handle (created by open_pool_ledger).
/// wallet_handle: Wallet handle (created by open_wallet).
/// sender_did: Id of sender Identity stored in secured Wallet.
/// receiver_did: Id of receiver Identity.
/// connection_cb: Callback that will be called after establishing of connection or on error.
///     Will be called exactly once with result of connect operation.
/// message_cb: Callback that will be called on receiving of an incoming message.
///     Can be called multiply times: once for each incoming message.
///
/// #Returns
/// Error code
/// connection_cb:
/// - xcommand_handle: command handle to map callback to caller context.
/// - err: Error code.
/// - connection_handle: Connection handle to use for messages sending and mapping of incomming messages to this connection.
/// message_cb:
/// - xconnection_handle: Connection handle. Indetnifies connection.
/// - err: Error code.
/// - message: Received message.
#[no_mangle]
pub extern fn sovrin_agent_connect(command_handle: i32,
                                   pool_handle: i32,
                                   wallet_handle: i32,
                                   sender_did: *const c_char,
                                   receiver_did: *const c_char,
                                   connection_cb: Option<extern fn(xcommand_handle: i32,
                                                                   err: ErrorCode,
                                                                   connection_handle: i32)>,
                                   message_cb: Option<extern fn(xconnection_handle: i32,
                                                                err: ErrorCode,
                                                                message: *const c_char)>) -> ErrorCode {
    check_useful_c_str!(sender_did, ErrorCode::CommonInvalidParam3);
    check_useful_c_str!(receiver_did, ErrorCode::CommonInvalidParam4);
    check_useful_c_callback!(connection_cb, ErrorCode::CommonInvalidParam5);
    check_useful_c_callback!(message_cb, ErrorCode::CommonInvalidParam6);

    let result = CommandExecutor::instance().send(
        Command::Agent(
            AgentCommand::Connect(
                pool_handle,
                wallet_handle,
                sender_did,
                receiver_did,
                Box::new(move |result| {
                    let (err, handle) = result_to_err_code_1!(result, 0);
                    connection_cb(command_handle, err, handle);
                }),
                Box::new(move |result| {
                    let (err, handle, msg) = result_to_err_code_2!(result, 0, String::new());
                    let msg = CStringUtils::string_to_cstring(msg);
                    message_cb(handle, err, msg.as_ptr());
                })
            )
        )
    );

    result_to_err_code!(result)
}

/// Starts listening of agent connections.
///
/// Listener will accept only connections to registered DIDs by sovrin_agent_add_identity call.
///
/// Information about sender Identity for incomming connection validation can be saved in the wallet
/// with sovrin_store_their_did call before establishing of connection. If there is no corresponded
/// wallet record for sender Identity than listener will lookup Identity Ledger and cache this
/// information in the wallet.
///
/// Note that messages encryption/decryption will be performed automatically.
///
/// #Params
/// command_handle: command handle to map callback to caller context.
/// endpoint: endpoint to use in starting listener.
/// listener_cb: Callback that will be called after listening started or on error.
///     Will be called exactly once with result of start listen operation.
/// connection_cb: Callback that will be called after establishing of incoming connection.
///     Can be called multiply times: once for each incoming connection.
/// message_cb: Callback that will be called on receiving of an incoming message.
///     Can be called multiply times: once for each incoming message.
///
/// #Returns
/// Error code
/// listener_cb:
/// - xcommand_handle: command handle to map callback to caller context.
/// - err: Error code
/// - listener_handle: Listener handle to use for mapping of incomming connections to this listener.
/// connection_cb:
/// - xlistener_handle: Listener handle. Identifies listener.
/// - err: Error code
/// - connection_handle: Connection handle to use for messages sending and mapping of incomming messages to to this connection.
/// - sender_did: Id of sender Identity stored in secured Wallet.
/// - receiver_did: Id of receiver Identity.
/// message_cb:
/// - xconnection_handle: Connection handle. Indetnifies connection.
/// - err: Error code.
/// - message: Received message.
#[no_mangle]
pub extern fn sovrin_agent_listen(command_handle: i32,
                                  endpoint: *const c_char,
                                  listener_cb: Option<extern fn(xcommand_handle: i32,
                                                                err: ErrorCode,
                                                                listener_handle: i32)>,
                                  connection_cb: Option<extern fn(xlistener_handle: i32,
                                                                  err: ErrorCode,
                                                                  connection_handle: i32,
                                                                  sender_did: *const c_char,
                                                                  receiver_did: *const c_char)>,
                                  message_cb: Option<extern fn(xconnection_handle: i32,
                                                               err: ErrorCode,
                                                               message: *const c_char)>) -> ErrorCode {
    check_useful_c_str!(endpoint, ErrorCode::CommonInvalidParam3);
    check_useful_c_callback!(listener_cb, ErrorCode::CommonInvalidParam4);
    check_useful_c_callback!(connection_cb, ErrorCode::CommonInvalidParam5);
    check_useful_c_callback!(message_cb, ErrorCode::CommonInvalidParam6);

    let cmd = Command::Agent(AgentCommand::Listen(
        endpoint,
        Box::new(move |result| {
            let (err, handle) = result_to_err_code_1!(result, 0);
            listener_cb(command_handle, err, handle);
        }),
        Box::new(move |result| {
            let (err, listener_handle, conn_handle, sender_did, receiver_did) =
                result_to_err_code_4!(result, 0, 0, String::new(), String::new());
            connection_cb(listener_handle, err, conn_handle,
                          CStringUtils::string_to_cstring(sender_did).as_ptr(),
                          CStringUtils::string_to_cstring(receiver_did).as_ptr());
        }),
        Box::new(move |result| {
            let (err, handle, msg) = result_to_err_code_2!(result, 0, String::new());
            let msg = CStringUtils::string_to_cstring(msg);
            message_cb(handle, err, msg.as_ptr());
        })
    ));

    let result = CommandExecutor::instance().send(cmd);

    result_to_err_code!(result)
}

/// Add identity to listener.
///
/// Performs wallet lookup to find corresponded receiver Identity information.
/// Information about receiver Identity must be saved in the wallet with
/// sovrin_create_and_store_my_did call before this call.
///
/// After successfully add_identity listener will start to accept incoming connection to added DID.
///
///
/// #Params
/// command_handle: command handle to map callback to caller context.
/// listener_handle: listener handle (created by sovrin_agent_listen).
/// wallet_handle: wallet handle (created by open_wallet).
///
/// add_identity_cb: Callback that will be called after listening started or on error.
///     Will be called exactly once with result of start listen operation.
///
/// #Returns
/// Error code
/// listener_cb:
/// - xcommand_handle: command handle to map callback to caller context.
/// - err: Error code
#[no_mangle]
#[allow(unused_variables)]
pub extern fn sovrin_agent_add_identity(command_handle: i32,
                                        listener_handle: i32,
                                        wallet_handle: i32,
                                        did: *const c_char,
                                        add_identity_cb: Option<extern fn(xcommand_handle: i32,
                                                                          err: ErrorCode)>) -> ErrorCode {
    unimplemented!();
}

/// Sends message to connected agent.
///
/// Note that this call works for both incoming and outgoing connections.
/// Note that messages encryption/decryption will be performed automatically.
///
/// #Params
/// command_handle: command handle to map callback to caller context.
/// connection_handle: Connection handle returned by sovrin_agent_connect or sovrin_agent_listen calls.
/// message: Message to send.
/// cb: Callback that will be called after message sent or on error. Will be called exactly once.
///
/// #Returns
/// err: Error code
/// cb:
/// - xcommand_handle: Command handle to map callback to caller context.
/// - err: Error code
///
/// #Errors
#[no_mangle]
pub extern fn sovrin_agent_send(command_handle: i32,
                                connection_handle: i32,
                                message: *const c_char,
                                cb: Option<extern fn(xcommand_handle: i32,
                                                     err: ErrorCode)>) -> ErrorCode {
    check_useful_opt_c_str!(message, ErrorCode::CommonInvalidParam3);
    check_useful_c_callback!(cb, ErrorCode::CommonInvalidParam4);

    let cmd = Command::Agent(AgentCommand::Send(
        connection_handle,
        message,
        Box::new(move |result| {
            cb(command_handle, result_to_err_code!(result))
        })
    ));

    let res = CommandExecutor::instance().send(cmd);
    result_to_err_code!(res)
}

/// Closes agent connection.
///
/// Note that this call works for both incoming and outgoing connections.
///
/// #Params
/// command_handle: command handle to map callback to caller context.
/// connection_handle: Connection handle returned by sovrin_agent_connect or sovrin_agent_listen calls.
/// cb: Callback that will be called after connection closed or on error. Will be called exactly once.
///
/// #Returns
/// Error code
/// cb:
/// - xcommand_handle: command handle to map callback to caller context.
/// - err: Error code
///
/// #Errors
#[no_mangle]
pub extern fn sovrin_agent_close_connection(command_handle: i32,
                                            connection_handle: i32,
                                            cb: Option<extern fn(xcommand_handle: i32,
                                                                 err: ErrorCode)>) -> ErrorCode {
    check_useful_c_callback!(cb, ErrorCode::CommonInvalidParam4);

    let cmd = Command::Agent(AgentCommand::CloseConnection(
        connection_handle,
        Box::new(move |result| {
            cb(command_handle, result_to_err_code!(result))
        })
    ));

    let res = CommandExecutor::instance().send(cmd);
    result_to_err_code!(res)
}

/// Closes listener and stops listening for agent connections.
///
/// Note that all opened incomming connections will be closed automatically.
///
/// #Params
/// command_handle: command handle to map callback to caller context.
/// listener_handle: Listener handle returned by sovrin_agent_listen call.
/// cb: Callback that will be called after listener closed or on error. Will be called exactly once.
///
/// #Returns
/// Error code
/// cb:
/// - xcommand_handle: command handle to map callback to caller context.
/// - err: Error code
///
/// #Errors
#[no_mangle]
pub extern fn sovrin_agent_close_listener(command_handle: i32,
                                          listener_handle: i32,
                                          cb: Option<extern fn(xcommand_handle: i32,
                                                               err: ErrorCode)>) -> ErrorCode {
    check_useful_c_callback!(cb, ErrorCode::CommonInvalidParam4);

    let cmd = Command::Agent(AgentCommand::CloseListener(
        listener_handle,
        Box::new(move |result| {
            cb(command_handle, result_to_err_code!(result))
        })
    ));

    let res = CommandExecutor::instance().send(cmd);
    result_to_err_code!(res)
}<commit_msg>Implement API layer for sovrin_agent_add_identity.<commit_after>extern crate libc;

use api::ErrorCode;
use commands::{Command, CommandExecutor};
use commands::agent::AgentCommand;
use errors::ToErrorCode;
use utils::cstring::CStringUtils;

use self::libc::c_char;

/// Establishes agent to agent connection.
///
/// Information about sender Identity must be saved in the wallet with sovrin_create_and_store_my_did
/// call before establishing of connection.
///
/// Information about receiver Identity can be saved in the wallet with sovrin_store_their_did
/// call before establishing of connection. If there is no corresponded wallet record for receiver Identity
/// than this call will lookup Identity Ledger and cache this information in the wallet.
///
/// Note that messages encryption/decryption will be performed automatically.
///
/// #Params
/// command_handle: Command handle to map callback to caller context.
/// pool_handle: Pool handle (created by open_pool_ledger).
/// wallet_handle: Wallet handle (created by open_wallet).
/// sender_did: Id of sender Identity stored in secured Wallet.
/// receiver_did: Id of receiver Identity.
/// connection_cb: Callback that will be called after establishing of connection or on error.
///     Will be called exactly once with result of connect operation.
/// message_cb: Callback that will be called on receiving of an incoming message.
///     Can be called multiply times: once for each incoming message.
///
/// #Returns
/// Error code
/// connection_cb:
/// - xcommand_handle: command handle to map callback to caller context.
/// - err: Error code.
/// - connection_handle: Connection handle to use for messages sending and mapping of incomming messages to this connection.
/// message_cb:
/// - xconnection_handle: Connection handle. Indetnifies connection.
/// - err: Error code.
/// - message: Received message.
#[no_mangle]
pub extern fn sovrin_agent_connect(command_handle: i32,
                                   pool_handle: i32,
                                   wallet_handle: i32,
                                   sender_did: *const c_char,
                                   receiver_did: *const c_char,
                                   connection_cb: Option<extern fn(xcommand_handle: i32,
                                                                   err: ErrorCode,
                                                                   connection_handle: i32)>,
                                   message_cb: Option<extern fn(xconnection_handle: i32,
                                                                err: ErrorCode,
                                                                message: *const c_char)>) -> ErrorCode {
    check_useful_c_str!(sender_did, ErrorCode::CommonInvalidParam3);
    check_useful_c_str!(receiver_did, ErrorCode::CommonInvalidParam4);
    check_useful_c_callback!(connection_cb, ErrorCode::CommonInvalidParam5);
    check_useful_c_callback!(message_cb, ErrorCode::CommonInvalidParam6);

    let result = CommandExecutor::instance().send(
        Command::Agent(
            AgentCommand::Connect(
                pool_handle,
                wallet_handle,
                sender_did,
                receiver_did,
                Box::new(move |result| {
                    let (err, handle) = result_to_err_code_1!(result, 0);
                    connection_cb(command_handle, err, handle);
                }),
                Box::new(move |result| {
                    let (err, handle, msg) = result_to_err_code_2!(result, 0, String::new());
                    let msg = CStringUtils::string_to_cstring(msg);
                    message_cb(handle, err, msg.as_ptr());
                })
            )
        )
    );

    result_to_err_code!(result)
}

/// Starts listening of agent connections.
///
/// Listener will accept only connections to registered DIDs by sovrin_agent_add_identity call.
///
/// Information about sender Identity for incomming connection validation can be saved in the wallet
/// with sovrin_store_their_did call before establishing of connection. If there is no corresponded
/// wallet record for sender Identity than listener will lookup Identity Ledger and cache this
/// information in the wallet.
///
/// Note that messages encryption/decryption will be performed automatically.
///
/// #Params
/// command_handle: command handle to map callback to caller context.
/// endpoint: endpoint to use in starting listener.
/// listener_cb: Callback that will be called after listening started or on error.
///     Will be called exactly once with result of start listen operation.
/// connection_cb: Callback that will be called after establishing of incoming connection.
///     Can be called multiply times: once for each incoming connection.
/// message_cb: Callback that will be called on receiving of an incoming message.
///     Can be called multiply times: once for each incoming message.
///
/// #Returns
/// Error code
/// listener_cb:
/// - xcommand_handle: command handle to map callback to caller context.
/// - err: Error code
/// - listener_handle: Listener handle to use for mapping of incomming connections to this listener.
/// connection_cb:
/// - xlistener_handle: Listener handle. Identifies listener.
/// - err: Error code
/// - connection_handle: Connection handle to use for messages sending and mapping of incomming messages to to this connection.
/// - sender_did: Id of sender Identity stored in secured Wallet.
/// - receiver_did: Id of receiver Identity.
/// message_cb:
/// - xconnection_handle: Connection handle. Indetnifies connection.
/// - err: Error code.
/// - message: Received message.
#[no_mangle]
pub extern fn sovrin_agent_listen(command_handle: i32,
                                  endpoint: *const c_char,
                                  listener_cb: Option<extern fn(xcommand_handle: i32,
                                                                err: ErrorCode,
                                                                listener_handle: i32)>,
                                  connection_cb: Option<extern fn(xlistener_handle: i32,
                                                                  err: ErrorCode,
                                                                  connection_handle: i32,
                                                                  sender_did: *const c_char,
                                                                  receiver_did: *const c_char)>,
                                  message_cb: Option<extern fn(xconnection_handle: i32,
                                                               err: ErrorCode,
                                                               message: *const c_char)>) -> ErrorCode {
    check_useful_c_str!(endpoint, ErrorCode::CommonInvalidParam3);
    check_useful_c_callback!(listener_cb, ErrorCode::CommonInvalidParam4);
    check_useful_c_callback!(connection_cb, ErrorCode::CommonInvalidParam5);
    check_useful_c_callback!(message_cb, ErrorCode::CommonInvalidParam6);

    let cmd = Command::Agent(AgentCommand::Listen(
        endpoint,
        Box::new(move |result| {
            let (err, handle) = result_to_err_code_1!(result, 0);
            listener_cb(command_handle, err, handle);
        }),
        Box::new(move |result| {
            let (err, listener_handle, conn_handle, sender_did, receiver_did) =
                result_to_err_code_4!(result, 0, 0, String::new(), String::new());
            connection_cb(listener_handle, err, conn_handle,
                          CStringUtils::string_to_cstring(sender_did).as_ptr(),
                          CStringUtils::string_to_cstring(receiver_did).as_ptr());
        }),
        Box::new(move |result| {
            let (err, handle, msg) = result_to_err_code_2!(result, 0, String::new());
            let msg = CStringUtils::string_to_cstring(msg);
            message_cb(handle, err, msg.as_ptr());
        })
    ));

    let result = CommandExecutor::instance().send(cmd);

    result_to_err_code!(result)
}

/// Add identity to listener.
///
/// Performs wallet lookup to find corresponded receiver Identity information.
/// Information about receiver Identity must be saved in the wallet with
/// sovrin_create_and_store_my_did call before this call.
///
/// After successfully add_identity listener will start to accept incoming connection to added DID.
///
///
/// #Params
/// command_handle: command handle to map callback to caller context.
/// listener_handle: listener handle (created by sovrin_agent_listen).
/// wallet_handle: wallet handle (created by open_wallet).
///
/// add_identity_cb: Callback that will be called after listening started or on error.
///     Will be called exactly once with result of start listen operation.
///
/// #Returns
/// Error code
/// listener_cb:
/// - xcommand_handle: command handle to map callback to caller context.
/// - err: Error code
#[no_mangle]
#[allow(unused_variables)]
pub extern fn sovrin_agent_add_identity(command_handle: i32,
                                        listener_handle: i32,
                                        wallet_handle: i32,
                                        did: *const c_char,
                                        add_identity_cb: Option<extern fn(xcommand_handle: i32,
                                                                          err: ErrorCode)>) -> ErrorCode {
    check_useful_c_str!(did, ErrorCode::CommonInvalidParam4);
    check_useful_c_callback!(add_identity_cb, ErrorCode::CommonInvalidParam5);

    let cmd = Command::Agent(AgentCommand::ListenerAddIdentity(
        listener_handle,
        wallet_handle,
        did,
        Box::new(move |result| {
            let result = result_to_err_code!(result);
            add_identity_cb(command_handle, result);
        }),
    ));

    let result = CommandExecutor::instance().send(cmd);

    result_to_err_code!(result)
}

/// Sends message to connected agent.
///
/// Note that this call works for both incoming and outgoing connections.
/// Note that messages encryption/decryption will be performed automatically.
///
/// #Params
/// command_handle: command handle to map callback to caller context.
/// connection_handle: Connection handle returned by sovrin_agent_connect or sovrin_agent_listen calls.
/// message: Message to send.
/// cb: Callback that will be called after message sent or on error. Will be called exactly once.
///
/// #Returns
/// err: Error code
/// cb:
/// - xcommand_handle: Command handle to map callback to caller context.
/// - err: Error code
///
/// #Errors
#[no_mangle]
pub extern fn sovrin_agent_send(command_handle: i32,
                                connection_handle: i32,
                                message: *const c_char,
                                cb: Option<extern fn(xcommand_handle: i32,
                                                     err: ErrorCode)>) -> ErrorCode {
    check_useful_opt_c_str!(message, ErrorCode::CommonInvalidParam3);
    check_useful_c_callback!(cb, ErrorCode::CommonInvalidParam4);

    let cmd = Command::Agent(AgentCommand::Send(
        connection_handle,
        message,
        Box::new(move |result| {
            cb(command_handle, result_to_err_code!(result))
        })
    ));

    let res = CommandExecutor::instance().send(cmd);
    result_to_err_code!(res)
}

/// Closes agent connection.
///
/// Note that this call works for both incoming and outgoing connections.
///
/// #Params
/// command_handle: command handle to map callback to caller context.
/// connection_handle: Connection handle returned by sovrin_agent_connect or sovrin_agent_listen calls.
/// cb: Callback that will be called after connection closed or on error. Will be called exactly once.
///
/// #Returns
/// Error code
/// cb:
/// - xcommand_handle: command handle to map callback to caller context.
/// - err: Error code
///
/// #Errors
#[no_mangle]
pub extern fn sovrin_agent_close_connection(command_handle: i32,
                                            connection_handle: i32,
                                            cb: Option<extern fn(xcommand_handle: i32,
                                                                 err: ErrorCode)>) -> ErrorCode {
    check_useful_c_callback!(cb, ErrorCode::CommonInvalidParam4);

    let cmd = Command::Agent(AgentCommand::CloseConnection(
        connection_handle,
        Box::new(move |result| {
            cb(command_handle, result_to_err_code!(result))
        })
    ));

    let res = CommandExecutor::instance().send(cmd);
    result_to_err_code!(res)
}

/// Closes listener and stops listening for agent connections.
///
/// Note that all opened incomming connections will be closed automatically.
///
/// #Params
/// command_handle: command handle to map callback to caller context.
/// listener_handle: Listener handle returned by sovrin_agent_listen call.
/// cb: Callback that will be called after listener closed or on error. Will be called exactly once.
///
/// #Returns
/// Error code
/// cb:
/// - xcommand_handle: command handle to map callback to caller context.
/// - err: Error code
///
/// #Errors
#[no_mangle]
pub extern fn sovrin_agent_close_listener(command_handle: i32,
                                          listener_handle: i32,
                                          cb: Option<extern fn(xcommand_handle: i32,
                                                               err: ErrorCode)>) -> ErrorCode {
    check_useful_c_callback!(cb, ErrorCode::CommonInvalidParam4);

    let cmd = Command::Agent(AgentCommand::CloseListener(
        listener_handle,
        Box::new(move |result| {
            cb(command_handle, result_to_err_code!(result))
        })
    ));

    let res = CommandExecutor::instance().send(cmd);
    result_to_err_code!(res)
}<|endoftext|>


<commit_before>use std::collections::HashMap;
use std::string::String;

pub trait ValueDescriptor {
    fn into_value(self) -> Value;
    fn try_deref_value(value: &Value) -> Option<&Self>;
}

macro_rules! value_desc {
    ($name:ident) => {
        impl ValueDescriptor for $name {
            fn into_value(self) -> Value {
                Value::$name(self)
            }
            fn try_deref_value(value: &Value) -> Option<&Self> {
                match value {
                    Value::$name(value) => Some(value),
                    _ => None,
                }
            }
        }
    };
}

pub trait AttributeDescriptor {
    const ID: &'static str;
    type Value: ValueDescriptor;

    fn id(&self) -> &'static str {
        Self::ID
    }

    fn validate(value: &Value) -> bool {
        Self::Value::try_deref_value(value).is_some()
    }
}

macro_rules! attr_desc {
    ($name:ident, $id:expr, $ty:ty) => {
        #[derive(Copy, Clone, Debug)]
        pub struct $name;
        impl AttributeDescriptor for $name {
            const ID: &'static str = $id;
            type Value = $ty;
        }
    };
}

#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum Unit {
    None,
    Em,
    Ex,
    Px,
    In,
    Cm,
    Mm,
    Pt,
    Pc,
    Percent,
}

#[derive(Copy, Clone, Debug)]
pub struct Length {
    pub value: f32,
    pub unit: Unit,
}

#[derive(Copy, Clone, Debug)]
pub struct Color {
    pub r: u8,
    pub g: u8,
    pub b: u8,
    pub a: u8,
}

#[derive(Clone, Debug)]
pub enum Value {
    Length(Length),
    Color(Color),
    String(String),
}

#[derive(Default, Debug)]
pub struct AttributeMap {
    items: HashMap<&'static str, Value>,
}

impl AttributeMap {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn insert<A: AttributeDescriptor>(
        &mut self,
        attr: A,
        value: impl Into<A::Value>,
    ) -> Option<Value> {
        self.items.insert(attr.id(), value.into().into_value())
    }

    pub fn get<A: AttributeDescriptor>(&self, attr: A) -> Option<&A::Value> {
        self.items
            .get(attr.id())
            .map(|value| A::Value::try_deref_value(value))
            .flatten()
    }

    pub fn insert_by_id(&mut self, id: &str, value: Value) -> Result<Option<Value>, InsertError> {
        let (id, validator) = match ATTRIBUTE_VALIDATORS.binary_search_by(|probe| probe.0.cmp(id))
        {
            Ok(idx) => ATTRIBUTE_VALIDATORS[idx],
            _ => return Err(InsertError::InvalidAttribute),
        };
        if !validator(&value) {
            return Err(InsertError::InvalidValue);
        }
        Ok(self.items.insert(id, value))
    }

    pub fn get_by_id(&self, id: &str) -> Option<&Value> {
        self.items.get(id)
    }

    pub fn iter(&self) -> impl Iterator<Item = (&'static str, &Value)> + Clone {
        self.items.iter().map(|(a, b)| (*a, b))
    }
}

#[derive(Debug)]
pub enum InsertError {
    InvalidAttribute,
    InvalidValue,
}

include!("../generated/attribute.rs");
<commit_msg>clippy: replace map().flatten() on Option with and_then(); remove redundant closure<commit_after>use std::collections::HashMap;
use std::string::String;

pub trait ValueDescriptor {
    fn into_value(self) -> Value;
    fn try_deref_value(value: &Value) -> Option<&Self>;
}

macro_rules! value_desc {
    ($name:ident) => {
        impl ValueDescriptor for $name {
            fn into_value(self) -> Value {
                Value::$name(self)
            }
            fn try_deref_value(value: &Value) -> Option<&Self> {
                match value {
                    Value::$name(value) => Some(value),
                    _ => None,
                }
            }
        }
    };
}

pub trait AttributeDescriptor {
    const ID: &'static str;
    type Value: ValueDescriptor;

    fn id(&self) -> &'static str {
        Self::ID
    }

    fn validate(value: &Value) -> bool {
        Self::Value::try_deref_value(value).is_some()
    }
}

macro_rules! attr_desc {
    ($name:ident, $id:expr, $ty:ty) => {
        #[derive(Copy, Clone, Debug)]
        pub struct $name;
        impl AttributeDescriptor for $name {
            const ID: &'static str = $id;
            type Value = $ty;
        }
    };
}

#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum Unit {
    None,
    Em,
    Ex,
    Px,
    In,
    Cm,
    Mm,
    Pt,
    Pc,
    Percent,
}

#[derive(Copy, Clone, Debug)]
pub struct Length {
    pub value: f32,
    pub unit: Unit,
}

#[derive(Copy, Clone, Debug)]
pub struct Color {
    pub r: u8,
    pub g: u8,
    pub b: u8,
    pub a: u8,
}

#[derive(Clone, Debug)]
pub enum Value {
    Length(Length),
    Color(Color),
    String(String),
}

#[derive(Default, Debug)]
pub struct AttributeMap {
    items: HashMap<&'static str, Value>,
}

impl AttributeMap {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn insert<A: AttributeDescriptor>(
        &mut self,
        attr: A,
        value: impl Into<A::Value>,
    ) -> Option<Value> {
        self.items.insert(attr.id(), value.into().into_value())
    }

    pub fn get<A: AttributeDescriptor>(&self, attr: A) -> Option<&A::Value> {
        self.items
            .get(attr.id())
            .and_then(A::Value::try_deref_value)
    }

    pub fn insert_by_id(&mut self, id: &str, value: Value) -> Result<Option<Value>, InsertError> {
        let (id, validator) = match ATTRIBUTE_VALIDATORS.binary_search_by(|probe| probe.0.cmp(id))
        {
            Ok(idx) => ATTRIBUTE_VALIDATORS[idx],
            _ => return Err(InsertError::InvalidAttribute),
        };
        if !validator(&value) {
            return Err(InsertError::InvalidValue);
        }
        Ok(self.items.insert(id, value))
    }

    pub fn get_by_id(&self, id: &str) -> Option<&Value> {
        self.items.get(id)
    }

    pub fn iter(&self) -> impl Iterator<Item = (&'static str, &Value)> + Clone {
        self.items.iter().map(|(a, b)| (*a, b))
    }
}

#[derive(Debug)]
pub enum InsertError {
    InvalidAttribute,
    InvalidValue,
}

include!("../generated/attribute.rs");
<|endoftext|>


<commit_before>#[macro_use]
extern crate clap;

extern crate brain;

use std::process;
use std::io::prelude::*;
use std::fs::File;
use std::path::{Path, PathBuf};

use clap::{Arg, App};

use brain::{Program, OptimizationLevel, ParseError};

macro_rules! exit_with_error(
    ($($arg:tt)*) => { {
        writeln!(&mut ::std::io::stderr(), $($arg)*)
            .expect("Failed while printing to stderr");
        process::exit(1);
    } }
);

fn main() {
    let args = App::new(crate_name!())
        .version(crate_version!())
        .version_short("v")
        .author(crate_authors!())
        .about(crate_description!())
        .arg(Arg::with_name("input-file")
            .help("The brain file to process")
            .value_name("file")
            .takes_value(true)
            .required(true)
        )
        .arg(Arg::with_name("output-file")
            .short("o")
            .help("Write output to <target>")
            .value_name("target")
            .takes_value(true)
        )
        .get_matches();

    let source_path = Path::new(args.value_of("input-file").unwrap());
    if !source_path.exists() || !source_path.is_file() {
        exit_with_error!("Not a valid file: '{}'", source_path.display());
    }

    let output_path = args.value_of("output-file").map_or_else(|| {
        let mut path = PathBuf::from(source_path.file_name().and_then(|s| s.to_str()).unwrap_or(""));
        path.set_extension("bf");
        path
    }, |s| PathBuf::from(s));

    let mut source_file = File::open(source_path).unwrap_or_else(|e| {
        exit_with_error!("Could not open source file: {}", e);
    });
    let mut source = String::new();
    source_file.read_to_string(&mut source).unwrap_or_else(|e| {
        exit_with_error!("Could not read source file: {}", e);
    });

    let program: Program = source.parse().unwrap_or_else(|e: ParseError| {
        if e.expected.is_empty() {
            exit_with_error!("Syntax Error: no token expected at line {} col {}", e.line, e.col);
        } else {
            exit_with_error!("Syntax Error: expected token(s): {} at line {} col {}",
                e.expected.iter().map(|r| format!("{}", r)).collect::<Vec<String>>().join(", "),
                e.line, e.col);
        }
    });
    let mut instructions = Instructions::from_program(program).unwrap();
    instructions.optimize(OptimizationLevel::On);
    let generated_code: String = instructions.into();

    let mut output_file = File::create(output_path).unwrap_or_else(|e| {
        exit_with_error!("Could not create target file: {}", e);
    });
    output_file.write_all(generated_code.as_bytes()).and_then(|_| {
        // Write a newline because that's how a line is defined
        // http://stackoverflow.com/a/729795/551904
        output_file.write(&['\n' as u8])
    }).unwrap_or_else(|e| {
        exit_with_error!("Could not write target file: {}", e);
    });
}
<commit_msg>Making sure the executable compiles<commit_after>#[macro_use]
extern crate clap;

extern crate brain;

use std::process;
use std::io::prelude::*;
use std::fs::File;
use std::path::{Path, PathBuf};

use clap::{Arg, App};

use brain::{Program, ParseError};

macro_rules! exit_with_error(
    ($($arg:tt)*) => { {
        writeln!(&mut ::std::io::stderr(), $($arg)*)
            .expect("Failed while printing to stderr");
        process::exit(1);
    } }
);

fn main() {
    let args = App::new(crate_name!())
        .version(crate_version!())
        .version_short("v")
        .author(crate_authors!())
        .about(crate_description!())
        .arg(Arg::with_name("input-file")
            .help("The brain file to process")
            .value_name("file")
            .takes_value(true)
            .required(true)
        )
        .arg(Arg::with_name("output-file")
            .short("o")
            .help("Write output to <target>")
            .value_name("target")
            .takes_value(true)
        )
        .get_matches();

    let source_path = Path::new(args.value_of("input-file").unwrap());
    if !source_path.exists() || !source_path.is_file() {
        exit_with_error!("Not a valid file: '{}'", source_path.display());
    }

    let output_path = args.value_of("output-file").map_or_else(|| {
        let mut path = PathBuf::from(source_path.file_name().and_then(|s| s.to_str()).unwrap_or(""));
        path.set_extension("bf");
        path
    }, |s| PathBuf::from(s));

    let mut source_file = File::open(source_path).unwrap_or_else(|e| {
        exit_with_error!("Could not open source file: {}", e);
    });
    let mut source = String::new();
    source_file.read_to_string(&mut source).unwrap_or_else(|e| {
        exit_with_error!("Could not read source file: {}", e);
    });

    let generated_code: String = compile(source);

    let mut output_file = File::create(output_path).unwrap_or_else(|e| {
        exit_with_error!("Could not create target file: {}", e);
    });
    output_file.write_all(generated_code.as_bytes()).and_then(|_| {
        // Write a newline because that's how a line is defined
        // http://stackoverflow.com/a/729795/551904
        output_file.write(&['\n' as u8])
    }).unwrap_or_else(|e| {
        exit_with_error!("Could not write target file: {}", e);
    });
}

/// Compile the provided source code to brainfuck
fn compile(source: String) -> String {
    let program: Program = source.parse().unwrap_or_else(|e: ParseError| {
        if e.expected.is_empty() {
            exit_with_error!("Syntax Error: no token expected at line {} col {}", e.line, e.col);
        } else {
            exit_with_error!("Syntax Error: expected token(s): {} at line {} col {}",
                e.expected.iter().map(|r| format!("{}", r)).collect::<Vec<String>>().join(", "),
                e.line, e.col);
        }
    });

    unimplemented!();
}
<|endoftext|>


<commit_before>#![feature(phase)]

extern crate cargo;
extern crate hammer;
extern crate serialize;
#[phase(plugin, link)]
extern crate log;

use hammer::{FlagConfig,FlagConfiguration};
use std::os;
use std::io::process::{Command,InheritFd,ExitStatus,ExitSignal};
use serialize::Encodable;
use cargo::{GlobalFlags, NoFlags, execute_main_without_stdin, handle_error, shell};
use cargo::core::MultiShell;
use cargo::util::important_paths::find_project;
use cargo::util::{CliError, CliResult, Require, config, human};

fn main() {
    execute();
}

#[deriving(Encodable)]
struct ProjectLocation {
    root: String
}

/**
  The top-level `cargo` command handles configuration and project location
  because they are fundamental (and intertwined). Other commands can rely
  on this top-level information.
*/
fn execute() {
    debug!("executing; cmd=cargo; args={}", os::args());

    let (cmd, args) = process(os::args());

    match cmd.as_slice() {
        "config-for-key" => {
            log!(4, "cmd == config-for-key");
            execute_main_without_stdin(config_for_key)
        },
        "config-list" => {
            log!(4, "cmd == config-list");
            execute_main_without_stdin(config_list)
        },
        "locate-project" => {
            log!(4, "cmd == locate-project");
            execute_main_without_stdin(locate_project)
        },
        "--help" | "-h" | "help" | "-?" => {
            println!("Commands:");
            println!("  build          # compile the current project");
            println!("  test           # run the tests\n");

            let (_, options) = hammer::usage::<GlobalFlags>(false);
            println!("Options (for all commands):\n\n{}", options);
        },
        _ => {
            let command = format!("cargo-{}", cmd);
            let mut command = match os::self_exe_path() {
                Some(path) => Command::new(path.join(command)),
                None => Command::new(command),
            };
            let command = command
                .args(args.as_slice())
                .stdin(InheritFd(0))
                .stdout(InheritFd(1))
                .stderr(InheritFd(2))
                .status();

            match command {
                Ok(ExitStatus(0)) => (),
                Ok(ExitStatus(i)) | Ok(ExitSignal(i)) => {
                    handle_error(CliError::new("", i as uint), &mut shell(false))
                }
                Err(_) => handle_error(CliError::new("No such subcommand", 127), &mut shell(false))
            }
        }
    }
}

fn process(args: Vec<String>) -> (String, Vec<String>) {
    let mut args = Vec::from_slice(args.tail());
    let head = args.shift().unwrap_or("--help".to_string());

    (head, args)
}

#[deriving(Encodable)]
struct ConfigOut {
    values: std::collections::HashMap<String, config::ConfigValue>
}

#[deriving(Decodable)]
struct ConfigForKeyFlags {
    key: String,
    human: bool
}

impl FlagConfig for ConfigForKeyFlags {
    fn config(_: Option<ConfigForKeyFlags>,
              config: FlagConfiguration) -> FlagConfiguration {
        config.short("human", 'h')
    }
}

fn config_for_key(args: ConfigForKeyFlags, _: &mut MultiShell) -> CliResult<Option<ConfigOut>> {
    let value = try!(config::get_config(os::getcwd(),
                                        args.key.as_slice()).map_err(|_| {
        CliError::new("Couldn't load configuration",  1)
    }));

    if args.human {
        println!("{}", value);
        Ok(None)
    } else {
        let mut map = std::collections::HashMap::new();
        map.insert(args.key.clone(), value);
        Ok(Some(ConfigOut { values: map }))
    }
}

#[deriving(Decodable)]
struct ConfigListFlags {
    human: bool
}

impl FlagConfig for ConfigListFlags {
    fn config(_: Option<ConfigListFlags>,
              config: FlagConfiguration) -> FlagConfiguration {
        config.short("human", 'h')
    }
}

fn config_list(args: ConfigListFlags, _: &mut MultiShell) -> CliResult<Option<ConfigOut>> {
    let configs = try!(config::all_configs(os::getcwd()).map_err(|_|
        CliError::new("Couldn't load configuration", 1)));

    if args.human {
        for (key, value) in configs.iter() {
            println!("{} = {}", key, value);
        }
        Ok(None)
    } else {
        Ok(Some(ConfigOut { values: configs }))
    }
}

fn locate_project(_: NoFlags, _: &mut MultiShell) -> CliResult<Option<ProjectLocation>> {
    let root = try!(find_project(&os::getcwd(), "Cargo.toml").map_err(|e| {
        CliError::from_boxed(e, 1)
    }));

    let string = try!(root.as_str()
                      .require(|| human("Your project path contains characters \
                                         not representable in Unicode"))
                      .map_err(|e| CliError::from_boxed(e, 1)));

    Ok(Some(ProjectLocation { root: string.to_string() }))
}
<commit_msg>auto merge of #169 : cburgdorf/cargo/name_clean, r=alexcrichton<commit_after>#![feature(phase)]

extern crate cargo;
extern crate hammer;
extern crate serialize;
#[phase(plugin, link)]
extern crate log;

use hammer::{FlagConfig,FlagConfiguration};
use std::os;
use std::io::process::{Command,InheritFd,ExitStatus,ExitSignal};
use serialize::Encodable;
use cargo::{GlobalFlags, NoFlags, execute_main_without_stdin, handle_error, shell};
use cargo::core::MultiShell;
use cargo::util::important_paths::find_project;
use cargo::util::{CliError, CliResult, Require, config, human};

fn main() {
    execute();
}

#[deriving(Encodable)]
struct ProjectLocation {
    root: String
}

/**
  The top-level `cargo` command handles configuration and project location
  because they are fundamental (and intertwined). Other commands can rely
  on this top-level information.
*/
fn execute() {
    debug!("executing; cmd=cargo; args={}", os::args());

    let (cmd, args) = process(os::args());

    match cmd.as_slice() {
        "config-for-key" => {
            log!(4, "cmd == config-for-key");
            execute_main_without_stdin(config_for_key)
        },
        "config-list" => {
            log!(4, "cmd == config-list");
            execute_main_without_stdin(config_list)
        },
        "locate-project" => {
            log!(4, "cmd == locate-project");
            execute_main_without_stdin(locate_project)
        },
        "--help" | "-h" | "help" | "-?" => {
            println!("Commands:");
            println!("  build          # compile the current project");
            println!("  test           # run the tests");
            println!("  clean          # remove the target directory\n");

            let (_, options) = hammer::usage::<GlobalFlags>(false);
            println!("Options (for all commands):\n\n{}", options);
        },
        _ => {
            let command = format!("cargo-{}", cmd);
            let mut command = match os::self_exe_path() {
                Some(path) => Command::new(path.join(command)),
                None => Command::new(command),
            };
            let command = command
                .args(args.as_slice())
                .stdin(InheritFd(0))
                .stdout(InheritFd(1))
                .stderr(InheritFd(2))
                .status();

            match command {
                Ok(ExitStatus(0)) => (),
                Ok(ExitStatus(i)) | Ok(ExitSignal(i)) => {
                    handle_error(CliError::new("", i as uint), &mut shell(false))
                }
                Err(_) => handle_error(CliError::new("No such subcommand", 127), &mut shell(false))
            }
        }
    }
}

fn process(args: Vec<String>) -> (String, Vec<String>) {
    let mut args = Vec::from_slice(args.tail());
    let head = args.shift().unwrap_or("--help".to_string());

    (head, args)
}

#[deriving(Encodable)]
struct ConfigOut {
    values: std::collections::HashMap<String, config::ConfigValue>
}

#[deriving(Decodable)]
struct ConfigForKeyFlags {
    key: String,
    human: bool
}

impl FlagConfig for ConfigForKeyFlags {
    fn config(_: Option<ConfigForKeyFlags>,
              config: FlagConfiguration) -> FlagConfiguration {
        config.short("human", 'h')
    }
}

fn config_for_key(args: ConfigForKeyFlags, _: &mut MultiShell) -> CliResult<Option<ConfigOut>> {
    let value = try!(config::get_config(os::getcwd(),
                                        args.key.as_slice()).map_err(|_| {
        CliError::new("Couldn't load configuration",  1)
    }));

    if args.human {
        println!("{}", value);
        Ok(None)
    } else {
        let mut map = std::collections::HashMap::new();
        map.insert(args.key.clone(), value);
        Ok(Some(ConfigOut { values: map }))
    }
}

#[deriving(Decodable)]
struct ConfigListFlags {
    human: bool
}

impl FlagConfig for ConfigListFlags {
    fn config(_: Option<ConfigListFlags>,
              config: FlagConfiguration) -> FlagConfiguration {
        config.short("human", 'h')
    }
}

fn config_list(args: ConfigListFlags, _: &mut MultiShell) -> CliResult<Option<ConfigOut>> {
    let configs = try!(config::all_configs(os::getcwd()).map_err(|_|
        CliError::new("Couldn't load configuration", 1)));

    if args.human {
        for (key, value) in configs.iter() {
            println!("{} = {}", key, value);
        }
        Ok(None)
    } else {
        Ok(Some(ConfigOut { values: configs }))
    }
}

fn locate_project(_: NoFlags, _: &mut MultiShell) -> CliResult<Option<ProjectLocation>> {
    let root = try!(find_project(&os::getcwd(), "Cargo.toml").map_err(|e| {
        CliError::from_boxed(e, 1)
    }));

    let string = try!(root.as_str()
                      .require(|| human("Your project path contains characters \
                                         not representable in Unicode"))
                      .map_err(|e| CliError::from_boxed(e, 1)));

    Ok(Some(ProjectLocation { root: string.to_string() }))
}
<|endoftext|>


<commit_before>use std::env;

use cargo::core::Workspace;
use cargo::ops::{CompileOptions, CompileMode};
use cargo::ops;
use cargo::util::important_paths::{find_root_manifest_for_wd};
use cargo::util::{CliResult, CliError, Config, human};

#[derive(RustcDecodable)]
pub struct Options {
    arg_opts: Option<Vec<String>>,
    flag_package: Option<String>,
    flag_jobs: Option<u32>,
    flag_features: Vec<String>,
    flag_no_default_features: bool,
    flag_target: Option<String>,
    flag_manifest_path: Option<String>,
    flag_verbose: u32,
    flag_quiet: Option<bool>,
    flag_color: Option<String>,
    flag_release: bool,
    flag_lib: bool,
    flag_bin: Vec<String>,
    flag_example: Vec<String>,
    flag_test: Vec<String>,
    flag_bench: Vec<String>,
    flag_profile: Option<String>,
}

pub const USAGE: &'static str = "
Compile a package and all of its dependencies

Usage:
    cargo rustc [options] [--] [<opts>...]

Options:
    -h, --help               Print this message
    -p SPEC, --package SPEC  The profile to compile for
    -j N, --jobs N           Number of parallel jobs, defaults to # of CPUs
    --lib                    Build only this package's library
    --bin NAME               Build only the specified binary
    --example NAME           Build only the specified example
    --test NAME              Build only the specified test target
    --bench NAME             Build only the specified benchmark target
    --release                Build artifacts in release mode, with optimizations
    --profile PROFILE        Profile to build the selected target for
    --features FEATURES      Features to compile for the package
    --no-default-features    Do not compile default features for the package
    --target TRIPLE          Target triple which compiles will be for
    --manifest-path PATH     Path to the manifest to fetch dependencies for
    -v, --verbose ...        Use verbose output
    -q, --quiet              No output printed to stdout
    --color WHEN             Coloring: auto, always, never

The specified target for the current package (or package specified by SPEC if
provided) will be compiled along with all of its dependencies. The specified
<opts>... will all be passed to the final compiler invocation, not any of the
dependencies. Note that the compiler will still unconditionally receive
arguments such as -L, --extern, and --crate-type, and the specified <opts>...
will simply be added to the compiler invocation.

This command requires that only one target is being compiled. If more than one
target is available for the current package the filters of --lib, --bin, etc,
must be used to select which target is compiled. To pass flags to all compiler
processes spawned by Cargo, use the $RUSTFLAGS environment variable or the
`build.rustflags` configuration option.
";

pub fn execute(options: Options, config: &Config) -> CliResult<Option<()>> {
    debug!("executing; cmd=cargo-rustc; args={:?}",
           env::args().collect::<Vec<_>>());
    try!(config.configure_shell(options.flag_verbose,
                                options.flag_quiet,
                                &options.flag_color));

    let root = try!(find_root_manifest_for_wd(options.flag_manifest_path,
                                              config.cwd()));
    let mode = match options.flag_profile.as_ref().map(|t| &t[..]) {
        Some("dev") | None => CompileMode::Build,
        Some("test") => CompileMode::Test,
        Some("bench") => CompileMode::Bench,
        Some(mode) => {
            let err = human(format!("unknown profile: `{}`, use dev,
                                     test, or bench", mode));
            return Err(CliError::new(err, 101))
        }
    };

    let opts = CompileOptions {
        config: config,
        jobs: options.flag_jobs,
        target: options.flag_target.as_ref().map(|t| &t[..]),
        features: &options.flag_features,
        no_default_features: options.flag_no_default_features,
        spec: &options.flag_package.map_or(Vec::new(), |s| vec![s]),
        exec_engine: None,
        mode: mode,
        release: options.flag_release,
        filter: ops::CompileFilter::new(options.flag_lib,
                                        &options.flag_bin,
                                        &options.flag_test,
                                        &options.flag_example,
                                        &options.flag_bench),
        target_rustdoc_args: None,
        target_rustc_args: options.arg_opts.as_ref().map(|a| &a[..]),
    };

    let ws = try!(Workspace::new(&root, config));
    try!(ops::compile(&ws, &opts));
    Ok(None)
}

<commit_msg>fix help for cargo rustc -p<commit_after>use std::env;

use cargo::core::Workspace;
use cargo::ops::{CompileOptions, CompileMode};
use cargo::ops;
use cargo::util::important_paths::{find_root_manifest_for_wd};
use cargo::util::{CliResult, CliError, Config, human};

#[derive(RustcDecodable)]
pub struct Options {
    arg_opts: Option<Vec<String>>,
    flag_package: Option<String>,
    flag_jobs: Option<u32>,
    flag_features: Vec<String>,
    flag_no_default_features: bool,
    flag_target: Option<String>,
    flag_manifest_path: Option<String>,
    flag_verbose: u32,
    flag_quiet: Option<bool>,
    flag_color: Option<String>,
    flag_release: bool,
    flag_lib: bool,
    flag_bin: Vec<String>,
    flag_example: Vec<String>,
    flag_test: Vec<String>,
    flag_bench: Vec<String>,
    flag_profile: Option<String>,
}

pub const USAGE: &'static str = "
Compile a package and all of its dependencies

Usage:
    cargo rustc [options] [--] [<opts>...]

Options:
    -h, --help               Print this message
    -p SPEC, --package SPEC  Package to build
    -j N, --jobs N           Number of parallel jobs, defaults to # of CPUs
    --lib                    Build only this package's library
    --bin NAME               Build only the specified binary
    --example NAME           Build only the specified example
    --test NAME              Build only the specified test target
    --bench NAME             Build only the specified benchmark target
    --release                Build artifacts in release mode, with optimizations
    --profile PROFILE        Profile to build the selected target for
    --features FEATURES      Features to compile for the package
    --no-default-features    Do not compile default features for the package
    --target TRIPLE          Target triple which compiles will be for
    --manifest-path PATH     Path to the manifest to fetch dependencies for
    -v, --verbose ...        Use verbose output
    -q, --quiet              No output printed to stdout
    --color WHEN             Coloring: auto, always, never

The specified target for the current package (or package specified by SPEC if
provided) will be compiled along with all of its dependencies. The specified
<opts>... will all be passed to the final compiler invocation, not any of the
dependencies. Note that the compiler will still unconditionally receive
arguments such as -L, --extern, and --crate-type, and the specified <opts>...
will simply be added to the compiler invocation.

This command requires that only one target is being compiled. If more than one
target is available for the current package the filters of --lib, --bin, etc,
must be used to select which target is compiled. To pass flags to all compiler
processes spawned by Cargo, use the $RUSTFLAGS environment variable or the
`build.rustflags` configuration option.
";

pub fn execute(options: Options, config: &Config) -> CliResult<Option<()>> {
    debug!("executing; cmd=cargo-rustc; args={:?}",
           env::args().collect::<Vec<_>>());
    try!(config.configure_shell(options.flag_verbose,
                                options.flag_quiet,
                                &options.flag_color));

    let root = try!(find_root_manifest_for_wd(options.flag_manifest_path,
                                              config.cwd()));
    let mode = match options.flag_profile.as_ref().map(|t| &t[..]) {
        Some("dev") | None => CompileMode::Build,
        Some("test") => CompileMode::Test,
        Some("bench") => CompileMode::Bench,
        Some(mode) => {
            let err = human(format!("unknown profile: `{}`, use dev,
                                     test, or bench", mode));
            return Err(CliError::new(err, 101))
        }
    };

    let opts = CompileOptions {
        config: config,
        jobs: options.flag_jobs,
        target: options.flag_target.as_ref().map(|t| &t[..]),
        features: &options.flag_features,
        no_default_features: options.flag_no_default_features,
        spec: &options.flag_package.map_or(Vec::new(), |s| vec![s]),
        exec_engine: None,
        mode: mode,
        release: options.flag_release,
        filter: ops::CompileFilter::new(options.flag_lib,
                                        &options.flag_bin,
                                        &options.flag_test,
                                        &options.flag_example,
                                        &options.flag_bench),
        target_rustdoc_args: None,
        target_rustc_args: options.arg_opts.as_ref().map(|a| &a[..]),
    };

    let ws = try!(Workspace::new(&root, config));
    try!(ops::compile(&ws, &opts));
    Ok(None)
}

<|endoftext|>


<commit_before>#![feature(plugin)]
#![plugin(docopt_macros)]

extern crate docopt;
extern crate richter;
extern crate rustc_serialize;

use docopt::Docopt;
use richter::pak::{Pak, PakError};
use std::env;
use std::fs::{self, File};
use std::io::{BufWriter, Write};
use std::path::Path;
use std::process::exit;

#[derive(RustcDecodable)]
struct Args {
    arg_source: String,
    arg_dest: Option<String>,
    flag_h: bool,
    flag_help: bool,
    flag_v: bool,
    flag_verbose: bool,
    flag_version: bool,
}

const USAGE: &'static str = "
Usage: unpak <source>
       unpak <source> <dest>

Options:
    -h, --help     Show this message.
    -v, --verbose  Produce detailed output.
        --version  Print version information.
";

fn main() {
    let args: Args = Docopt::new(USAGE)
                         .and_then(|d| d.decode())
                         .unwrap_or_else(|e| e.exit());

    let pak = match Pak::load(&args.arg_source) {
        Ok(p) => p,
        Err(why) => {
            println!("Couldn't open {}: {}", &args.arg_source, why);
            exit(1);
        }
    };

    for (k, v) in pak.iter() {
        let path = Path::new(k);

        if let Some(p) = path.parent() {
            if !p.exists() {
                if let Err(why) = fs::create_dir_all(p) {
                    println!("Couldn't create parent directories: {}", why);
                    exit(1);
                }
            }
        }

        let mut f = match File::create(k) {
            Ok(f) => f,
            Err(why) => {
                println!("Couldn't open {}: {}", k, why);
                exit(1);
            }
        };

        let mut writer = BufWriter::new(f);
        writer.write_all(v);
    }
}
<commit_msg>Add destination handling to unpak<commit_after>#![feature(plugin)]
#![plugin(docopt_macros)]

extern crate docopt;
extern crate richter;
extern crate rustc_serialize;

use docopt::Docopt;
use richter::pak::{Pak, PakError};
use std::env;
use std::fs::{self, File};
use std::io::{BufWriter, Write};
use std::path::{Path, PathBuf};
use std::process::exit;

#[derive(RustcDecodable)]
struct Args {
    arg_source: String,
    arg_dest: Option<String>,
    flag_h: bool,
    flag_help: bool,
    flag_v: bool,
    flag_verbose: bool,
    flag_version: bool,
}

const USAGE: &'static str = "
Usage: unpak <source>
       unpak <source> <dest>

Options:
    -v, --verbose  Produce detailed output.

    -h, --help     Show this message and exit.
        --version  Print version information and exit.
";

fn main() {
    let args: Args = Docopt::new(USAGE)
                         .and_then(|d| d.decode())
                         .unwrap_or_else(|e| e.exit());

    let pak = match Pak::load(&args.arg_source) {
        Ok(p) => p,
        Err(why) => {
            println!("Couldn't open {}: {}", &args.arg_source, why);
            exit(1);
        }
    };

    for (k, v) in pak.iter() {
        let mut path = PathBuf::new();

        if let Some(ref d) = args.arg_dest {
            path.push(d);
        }

        path.push(k);

        if let Some(p) = path.parent() {
            if !p.exists() {
                if let Err(why) = fs::create_dir_all(p) {
                    println!("Couldn't create parent directories: {}", why);
                    exit(1);
                }
            }
        }

        let mut file = match File::create(&path) {
            Ok(f) => f,
            Err(why) => {
                println!("Couldn't open {}: {}", path.to_str().unwrap(), why);
                exit(1);
            }
        };

        let mut writer = BufWriter::new(file);
        writer.write_all(v);
    }
}
<|endoftext|>