<commit_before>use crate::command_prelude::*;

use cargo::core::{GitReference, SourceId};
use cargo::ops;
use cargo::util::IntoUrl;

pub fn cli() -> App {
    subcommand("install")
        .about("Install a Rust binary. Default location is $HOME/.cargo/bin")
        .arg(opt("quiet", "No output printed to stdout").short("q"))
        .arg(Arg::with_name("crate").empty_values(false).multiple(true))
        .arg(
            opt("version", "Specify a version to install")
                .alias("vers")
                .value_name("VERSION")
                .requires("crate"),
        )
        .arg(
            opt("git", "Git URL to install the specified crate from")
                .value_name("URL")
                .conflicts_with_all(&["path", "index", "registry"]),
        )
        .arg(
            opt("branch", "Branch to use when installing from git")
                .value_name("BRANCH")
                .requires("git"),
        )
        .arg(
            opt("tag", "Tag to use when installing from git")
                .value_name("TAG")
                .requires("git"),
        )
        .arg(
            opt("rev", "Specific commit to use when installing from git")
                .value_name("SHA")
                .requires("git"),
        )
        .arg(
            opt("path", "Filesystem path to local crate to install")
                .value_name("PATH")
                .conflicts_with_all(&["git", "index", "registry"]),
        )
        .arg(opt(
            "list",
            "list all installed packages and their versions",
        ))
        .arg_jobs()
        .arg(opt("force", "Force overwriting existing crates or binaries").short("f"))
        .arg(opt("no-track", "Do not save tracking information"))
        .arg_features()
        .arg_profile("Install artifacts with the specified profile")
        .arg(opt("debug", "Build in debug mode instead of release mode"))
        .arg_targets_bins_examples(
            "Install only the specified binary",
            "Install all binaries",
            "Install only the specified example",
            "Install all examples",
        )
        .arg_target_triple("Build for the target triple")
        .arg_target_dir()
        .arg(opt("root", "Directory to install packages into").value_name("DIR"))
        .arg(
            opt("index", "Registry index to install from")
                .value_name("INDEX")
                .requires("crate")
                .conflicts_with_all(&["git", "path", "registry"]),
        )
        .arg(
            opt("registry", "Registry to use")
                .value_name("REGISTRY")
                .requires("crate")
                .conflicts_with_all(&["git", "path", "index"]),
        )
        .after_help("Run `cargo help install` for more detailed information.\n")
}

pub fn exec(config: &mut Config, args: &ArgMatches<'_>) -> CliResult {
    let workspace;
    if let Some(path) = args.value_of_path("path", config) {
        config.reload_rooted_at(path)?;
        // Only provide worksapce information for local crate installation
        workspace = args.workspace(config).ok();
    } else {
        config.reload_rooted_at(config.home().clone().into_path_unlocked())?;
        workspace = None;
    }

    let mut compile_opts = args.compile_options(
        config,
        CompileMode::Build,
        workspace.as_ref(),
        ProfileChecking::Checked,
    )?;

    compile_opts.build_config.requested_profile =
        args.get_profile_name(config, "release", ProfileChecking::Checked)?;

    let krates = args
        .values_of("crate")
        .unwrap_or_default()
        .collect::<Vec<_>>();

    let mut from_cwd = false;

    let source = if let Some(url) = args.value_of("git") {
        let url = url.into_url()?;
        let gitref = if let Some(branch) = args.value_of("branch") {
            GitReference::Branch(branch.to_string())
        } else if let Some(tag) = args.value_of("tag") {
            GitReference::Tag(tag.to_string())
        } else if let Some(rev) = args.value_of("rev") {
            GitReference::Rev(rev.to_string())
        } else {
            GitReference::DefaultBranch
        };
        SourceId::for_git(&url, gitref)?
    } else if let Some(path) = args.value_of_path("path", config) {
        SourceId::for_path(&path)?
    } else if krates.is_empty() {
        from_cwd = true;
        SourceId::for_path(config.cwd())?
    } else if let Some(registry) = args.registry(config)? {
        SourceId::alt_registry(config, &registry)?
    } else if let Some(index) = args.value_of("index") {
        SourceId::for_registry(&index.into_url()?)?
    } else {
        SourceId::crates_io(config)?
    };

    let version = args.value_of("version");
    let root = args.value_of("root");

    if args.is_present("list") {
        ops::install_list(root, config)?;
    } else {
        ops::install(
            config,
            root,
            krates,
            source,
            from_cwd,
            version,
            &compile_opts,
            args.is_present("force"),
            args.is_present("no-track"),
        )?;
    }
    Ok(())
}
<commit_msg>Only `--path` and cwd crate installation need workspace info<commit_after>use crate::command_prelude::*;

use cargo::core::{GitReference, SourceId};
use cargo::ops;
use cargo::util::IntoUrl;

pub fn cli() -> App {
    subcommand("install")
        .about("Install a Rust binary. Default location is $HOME/.cargo/bin")
        .arg(opt("quiet", "No output printed to stdout").short("q"))
        .arg(Arg::with_name("crate").empty_values(false).multiple(true))
        .arg(
            opt("version", "Specify a version to install")
                .alias("vers")
                .value_name("VERSION")
                .requires("crate"),
        )
        .arg(
            opt("git", "Git URL to install the specified crate from")
                .value_name("URL")
                .conflicts_with_all(&["path", "index", "registry"]),
        )
        .arg(
            opt("branch", "Branch to use when installing from git")
                .value_name("BRANCH")
                .requires("git"),
        )
        .arg(
            opt("tag", "Tag to use when installing from git")
                .value_name("TAG")
                .requires("git"),
        )
        .arg(
            opt("rev", "Specific commit to use when installing from git")
                .value_name("SHA")
                .requires("git"),
        )
        .arg(
            opt("path", "Filesystem path to local crate to install")
                .value_name("PATH")
                .conflicts_with_all(&["git", "index", "registry"]),
        )
        .arg(opt(
            "list",
            "list all installed packages and their versions",
        ))
        .arg_jobs()
        .arg(opt("force", "Force overwriting existing crates or binaries").short("f"))
        .arg(opt("no-track", "Do not save tracking information"))
        .arg_features()
        .arg_profile("Install artifacts with the specified profile")
        .arg(opt("debug", "Build in debug mode instead of release mode"))
        .arg_targets_bins_examples(
            "Install only the specified binary",
            "Install all binaries",
            "Install only the specified example",
            "Install all examples",
        )
        .arg_target_triple("Build for the target triple")
        .arg_target_dir()
        .arg(opt("root", "Directory to install packages into").value_name("DIR"))
        .arg(
            opt("index", "Registry index to install from")
                .value_name("INDEX")
                .requires("crate")
                .conflicts_with_all(&["git", "path", "registry"]),
        )
        .arg(
            opt("registry", "Registry to use")
                .value_name("REGISTRY")
                .requires("crate")
                .conflicts_with_all(&["git", "path", "index"]),
        )
        .after_help("Run `cargo help install` for more detailed information.\n")
}

pub fn exec(config: &mut Config, args: &ArgMatches<'_>) -> CliResult {
    if let Some(path) = args.value_of_path("path", config) {
        config.reload_rooted_at(path)?;
    } else {
        config.reload_rooted_at(config.home().clone().into_path_unlocked())?;
    }

    let krates = args
        .values_of("crate")
        .unwrap_or_default()
        .collect::<Vec<_>>();

    let mut from_cwd = false;

    let source = if let Some(url) = args.value_of("git") {
        let url = url.into_url()?;
        let gitref = if let Some(branch) = args.value_of("branch") {
            GitReference::Branch(branch.to_string())
        } else if let Some(tag) = args.value_of("tag") {
            GitReference::Tag(tag.to_string())
        } else if let Some(rev) = args.value_of("rev") {
            GitReference::Rev(rev.to_string())
        } else {
            GitReference::DefaultBranch
        };
        SourceId::for_git(&url, gitref)?
    } else if let Some(path) = args.value_of_path("path", config) {
        SourceId::for_path(&path)?
    } else if krates.is_empty() {
        from_cwd = true;
        SourceId::for_path(config.cwd())?
    } else if let Some(registry) = args.registry(config)? {
        SourceId::alt_registry(config, &registry)?
    } else if let Some(index) = args.value_of("index") {
        SourceId::for_registry(&index.into_url()?)?
    } else {
        SourceId::crates_io(config)?
    };

    let version = args.value_of("version");
    let root = args.value_of("root");

    // We only provide worksapce information for local crate installation from
    // one of the following sources:
    // - From current working directory (only work for edition 2015).
    // - From a specific local file path.
    let workspace = if from_cwd || args.is_present("path") {
        args.workspace(config).ok()
    } else {
        None
    };

    let mut compile_opts = args.compile_options(
        config,
        CompileMode::Build,
        workspace.as_ref(),
        ProfileChecking::Checked,
    )?;

    compile_opts.build_config.requested_profile =
        args.get_profile_name(config, "release", ProfileChecking::Checked)?;

    if args.is_present("list") {
        ops::install_list(root, config)?;
    } else {
        ops::install(
            config,
            root,
            krates,
            source,
            from_cwd,
            version,
            &compile_opts,
            args.is_present("force"),
            args.is_present("no-track"),
        )?;
    }
    Ok(())
}
<|endoftext|>


<commit_before>#[doc = "A standard linked list"];

import core::option;
import option::*;
import option::{some, none};

enum list<T> {
    cons(T, @list<T>),
    nil,
}

#[doc = "Create a list from a vector"]
fn from_vec<T: copy>(v: [const T]) -> list<T> {
    *vec::foldr(v, @nil::<T>, { |h, t| @cons(h, t) })
}

#[doc = "
Left fold

Applies `f` to `u` and the first element in the list, then applies `f` to the
result of the previous call and the second element, and so on, returning the
accumulated result.

# Arguments

* ls - The list to fold
* z - The initial value
* f - The function to apply
"]
fn foldl<T: copy, U>(z: T, ls: list<U>, f: fn(T, U) -> T) -> T {
    let mut accum: T = z;
    iter(ls) {|elt| accum = f(accum, elt);}
    accum
}

#[doc = "
Search for an element that matches a given predicate

Apply function `f` to each element of `v`, starting from the first.
When function `f` returns true then an option containing the element
is returned. If `f` matches no elements then none is returned.
"]
fn find<T: copy>(ls: list<T>, f: fn(T) -> bool) -> option<T> {
    let mut ls = ls;
    loop {
        ls = alt ls {
          cons(hd, tl) {
            if f(hd) { ret some(hd); }
            *tl
          }
          nil { ret none; }
        }
    };
}

#[doc = "Returns true if a list contains an element with the given value"]
fn has<T: copy>(ls: list<T>, elt: T) -> bool {
    for each(ls) { |e|
        if e == elt { ret true; }
    }
    ret false;
}

#[doc = "Returns true if the list is empty"]
pure fn is_empty<T: copy>(ls: list<T>) -> bool {
    alt ls {
        nil { true }
        _ { false }
    }
}

#[doc = "Returns true if the list is not empty"]
pure fn is_not_empty<T: copy>(ls: list<T>) -> bool {
    ret !is_empty(ls);
}

#[doc = "Returns the length of a list"]
fn len<T>(ls: list<T>) -> uint {
    let mut count = 0u;
    iter(ls) {|_e| count += 1u;}
    count
}

#[doc = "Returns all but the first element of a list"]
pure fn tail<T: copy>(ls: list<T>) -> list<T> {
    alt ls {
        cons(_, tl) { ret *tl; }
        nil { fail "list empty" }
    }
}

#[doc = "Returns the first element of a list"]
pure fn head<T: copy>(ls: list<T>) -> T {
    alt check ls { cons(hd, _) { hd } }
}

#[doc = "Appends one list to another"]
pure fn append<T: copy>(l: list<T>, m: list<T>) -> list<T> {
    alt l {
      nil { ret m; }
      cons(x, xs) { let rest = append(*xs, m); ret cons(x, @rest); }
    }
}

#[doc = "Iterate over a list"]
fn iter<T>(l: list<T>, f: fn(T)) {
    alt l {
      cons(hd, tl) {
        f(hd);
        let mut cur = tl;
        loop {
            alt *cur {
              cons(hd, tl) {
                f(hd);
                cur = tl;
              }
              nil { break; }
            }
        }
      }
      nil {}
    }
}

#[doc = "Iterate over a list"]
fn each<T>(l: list<T>, f: fn(T) -> bool) {
    alt l {
      cons(hd, tl) {
        if !f(hd) { ret; }
        let mut cur = tl;
        loop {
            alt *cur {
              cons(hd, tl) {
                if !f(hd) { ret; }
                cur = tl;
              }
              nil { break; }
            }
        }
      }
      nil {}
    }
}

#[cfg(test)]
mod tests {

    #[test]
    fn test_is_empty() {
        let empty : list::list<int> = from_vec([]);
        let full1 = from_vec([1]);
        let full2 = from_vec(['r', 'u']);

        assert is_empty(empty);
        assert !is_empty(full1);
        assert !is_empty(full2);

        assert !is_not_empty(empty);
        assert is_not_empty(full1);
        assert is_not_empty(full2);
    }

    #[test]
    fn test_from_vec() {
        let l = from_vec([0, 1, 2]);

        assert (head(l) == 0);

        let tail_l = tail(l);
        assert (head(tail_l) == 1);

        let tail_tail_l = tail(tail_l);
        assert (head(tail_tail_l) == 2);
    }

    #[test]
    fn test_from_vec_empty() {
        let empty : list::list<int> = from_vec([]);
        assert (empty == list::nil::<int>);
    }

    #[test]
    fn test_from_vec_mut() {
        let l = from_vec([mut 0, 1, 2]);

        assert (head(l) == 0);

        let tail_l = tail(l);
        assert (head(tail_l) == 1);

        let tail_tail_l = tail(tail_l);
        assert (head(tail_tail_l) == 2);
    }

    #[test]
    fn test_foldl() {
        fn add(&&a: uint, &&b: int) -> uint { ret a + (b as uint); }
        let l = from_vec([0, 1, 2, 3, 4]);
        let empty = list::nil::<int>;
        assert (list::foldl(0u, l, add) == 10u);
        assert (list::foldl(0u, empty, add) == 0u);
    }

    #[test]
    fn test_foldl2() {
        fn sub(&&a: int, &&b: int) -> int {
            a - b
        }
        let l = from_vec([1, 2, 3, 4]);
        assert (list::foldl(0, l, sub) == -10);
    }

    #[test]
    fn test_find_success() {
        fn match(&&i: int) -> bool { ret i == 2; }
        let l = from_vec([0, 1, 2]);
        assert (list::find(l, match) == option::some(2));
    }

    #[test]
    fn test_find_fail() {
        fn match(&&_i: int) -> bool { ret false; }
        let l = from_vec([0, 1, 2]);
        let empty = list::nil::<int>;
        assert (list::find(l, match) == option::none::<int>);
        assert (list::find(empty, match) == option::none::<int>);
    }

    #[test]
    fn test_has() {
        let l = from_vec([5, 8, 6]);
        let empty = list::nil::<int>;
        assert (list::has(l, 5));
        assert (!list::has(l, 7));
        assert (list::has(l, 8));
        assert (!list::has(empty, 5));
    }

    #[test]
    fn test_len() {
        let l = from_vec([0, 1, 2]);
        let empty = list::nil::<int>;
        assert (list::len(l) == 3u);
        assert (list::len(empty) == 0u);
    }

}

// Local Variables:
// mode: rust;
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
<commit_msg>make list based on boxes<commit_after>#[doc = "A standard linked list"];

import core::option;
import option::*;
import option::{some, none};

enum list<T> {
    cons(T, @list<T>),
    nil,
}

#[doc = "Create a list from a vector"]
fn from_vec<T: copy>(v: [const T]) -> @list<T> {
    @vec::foldr(v, @nil::<T>, { |h, t| @cons(h, t) })
}

#[doc = "
Left fold

Applies `f` to `u` and the first element in the list, then applies `f` to the
result of the previous call and the second element, and so on, returning the
accumulated result.

# Arguments

* ls - The list to fold
* z - The initial value
* f - The function to apply
"]
fn foldl<T: copy, U>(z: T, ls: @list<U>, f: fn(T, U) -> T) -> T {
    let mut accum: T = z;
    iter(ls) {|elt| accum = f(accum, elt);}
    accum
}

#[doc = "
Search for an element that matches a given predicate

Apply function `f` to each element of `v`, starting from the first.
When function `f` returns true then an option containing the element
is returned. If `f` matches no elements then none is returned.
"]
fn find<T: copy>(ls: @list<T>, f: fn(T) -> bool) -> option<T> {
    let mut ls = ls;
    loop {
        ls = alt ls {
          cons(hd, tl) {
            if f(hd) { ret some(hd); }
            tl
          }
          nil { ret none; }
        }
    };
}

#[doc = "Returns true if a list contains an element with the given value"]
fn has<T: copy>(ls: @list<T>, elt: T) -> bool {
    for each(ls) { |e|
        if e == elt { ret true; }
    }
    ret false;
}

#[doc = "Returns true if the list is empty"]
pure fn is_empty<T: copy>(ls: @list<T>) -> bool {
    alt *ls {
        nil { true }
        _ { false }
    }
}

#[doc = "Returns true if the list is not empty"]
pure fn is_not_empty<T: copy>(ls: @list<T>) -> bool {
    ret !is_empty(ls);
}

#[doc = "Returns the length of a list"]
fn len<T>(ls: @list<T>) -> uint {
    let mut count = 0u;
    iter(ls) {|_e| count += 1u;}
    count
}

#[doc = "Returns all but the first element of a list"]
pure fn tail<T: copy>(ls: @list<T>) -> list<T> {
    alt *ls {
        cons(_, tl) { ret tl; }
        nil { fail "list empty" }
    }
}

#[doc = "Returns the first element of a list"]
pure fn head<T: copy>(ls: @list<T>) -> T {
    alt check *ls { cons(hd, _) { hd } }
}

#[doc = "Appends one list to another"]
pure fn append<T: copy>(l: @list<T>, m: @list<T>) -> @list<T> {
    alt *l {
      nil { ret m; }
      cons(x, xs) { let rest = append(*xs, m); ret @cons(x, @rest); }
    }
}

#[doc = "Iterate over a list"]
fn iter<T>(l: @list<T>, f: fn(T)) {
    let mut cur = l;
    loop {
        cur = alt *cur {
          cons(hd, tl) {
            f(hd);
            tl
          }
          nil { break; }
        }
    }
}

#[doc = "Iterate over a list"]
fn each<T>(l: list<T>, f: fn(T) -> bool) {
    let mut cur = l;
    loop {
        cur = alt *cur {
          cons(hd, tl) {
            if !f(hd) { ret; }
          }
          nil { break; }
        }
    }
}

#[cfg(test)]
mod tests {

    #[test]
    fn test_is_empty() {
        let empty : @list::list<int> = from_vec([]);
        let full1 = from_vec([1]);
        let full2 = from_vec(['r', 'u']);

        assert is_empty(empty);
        assert !is_empty(full1);
        assert !is_empty(full2);

        assert !is_not_empty(empty);
        assert is_not_empty(full1);
        assert is_not_empty(full2);
    }

    #[test]
    fn test_from_vec() {
        let l = from_vec([0, 1, 2]);

        assert (head(l) == 0);

        let tail_l = tail(l);
        assert (head(tail_l) == 1);

        let tail_tail_l = tail(tail_l);
        assert (head(tail_tail_l) == 2);
    }

    #[test]
    fn test_from_vec_empty() {
        let empty : @list::list<int> = from_vec([]);
        assert (empty == list::nil::<int>);
    }

    #[test]
    fn test_from_vec_mut() {
        let l = from_vec([mut 0, 1, 2]);

        assert (head(l) == 0);

        let tail_l = tail(l);
        assert (head(tail_l) == 1);

        let tail_tail_l = tail(tail_l);
        assert (head(tail_tail_l) == 2);
    }

    #[test]
    fn test_foldl() {
        fn add(&&a: uint, &&b: int) -> uint { ret a + (b as uint); }
        let l = from_vec([0, 1, 2, 3, 4]);
        let empty = @list::nil::<int>;
        assert (list::foldl(0u, l, add) == 10u);
        assert (list::foldl(0u, empty, add) == 0u);
    }

    #[test]
    fn test_foldl2() {
        fn sub(&&a: int, &&b: int) -> int {
            a - b
        }
        let l = from_vec([1, 2, 3, 4]);
        assert (list::foldl(0, l, sub) == -10);
    }

    #[test]
    fn test_find_success() {
        fn match(&&i: int) -> bool { ret i == 2; }
        let l = from_vec([0, 1, 2]);
        assert (list::find(l, match) == option::some(2));
    }

    #[test]
    fn test_find_fail() {
        fn match(&&_i: int) -> bool { ret false; }
        let l = from_vec([0, 1, 2]);
        let empty = list::nil::<int>;
        assert (list::find(l, match) == option::none::<int>);
        assert (list::find(empty, match) == option::none::<int>);
    }

    #[test]
    fn test_has() {
        let l = from_vec([5, 8, 6]);
        let empty = @list::nil::<int>;
        assert (list::has(l, 5));
        assert (!list::has(l, 7));
        assert (list::has(l, 8));
        assert (!list::has(empty, 5));
    }

    #[test]
    fn test_len() {
        let l = from_vec([0, 1, 2]);
        let empty = @list::nil::<int>;
        assert (list::len(l) == 3u);
        assert (list::len(empty) == 0u);
    }

}

// Local Variables:
// mode: rust;
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
<|endoftext|>


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

//! Terminal formatting library.
//!
//! This crate provides the `Terminal` trait, which abstracts over an [ANSI
//! Termina][ansi] to provide color printing, among other things. There are two implementations,
//! the `TerminfoTerminal`, which uses control characters from a
//! [terminfo][ti] database, and `WinConsole`, which uses the [Win32 Console
//! API][win].
//!
//! ## Example
//!
//! ```rust
//! extern crate term;
//!
//! fn main() {
//!     let mut t = term::stdout();
//!     t.fg(term::color::GREEN);
//!     println!("hello, ");
//!     t.fg(term::color::RED);
//!     println!("world!");
//!     t.reset();
//! }
//! ```
//!
//! [ansi]: https://en.wikipedia.org/wiki/ANSI_escape_code
//! [win]: http://msdn.microsoft.com/en-us/library/windows/desktop/ms682010%28v=vs.85%29.aspx
//! [ti]: https://en.wikipedia.org/wiki/Terminfo

#![crate_id = "term#0.11.0-pre"]
#![comment = "Simple ANSI color library"]
#![license = "MIT/ASL2"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
       html_favicon_url = "http://www.rust-lang.org/favicon.ico",
       html_root_url = "http://static.rust-lang.org/doc/master")]

#![feature(macro_rules, phase)]

#![deny(missing_doc)]

#[phase(syntax, link)] extern crate log;
extern crate collections;

pub use terminfo::TerminfoTerminal;
#[cfg(windows)]
pub use win::WinConsole;

use std::io::IoResult;

pub mod terminfo;

#[cfg(windows)]
mod win;

#[cfg(not(windows))]
/// Return a Terminal wrapping stdout, or None if a terminal couldn't be
/// opened.
pub fn stdout() -> Option<Box<Terminal<Box<Writer:Send>>:Send>> {
    let ti: Option<TerminfoTerminal<Box<Writer:Send>>>
        = Terminal::new(box std::io::stdout() as Box<Writer:Send>);
    ti.map(|t| box t as Box<Terminal<Box<Writer:Send>:Send>:Send>)
}

#[cfg(windows)]
/// Return a Terminal wrapping stdout, or None if a terminal couldn't be
/// opened.
pub fn stdout() -> Option<Box<Terminal<Box<Writer:Send>:Send>:Send>> {
    let ti: Option<TerminfoTerminal<Box<Writer:Send>>>
        = Terminal::new(box std::io::stdout() as Box<Writer:Send>);

    match ti {
        Some(t) => Some(box t as Box<Terminal<Box<Writer:Send>:Send>:Send>),
        None => {
            let wc: Option<WinConsole<Box<Writer:Send>>>
                = Terminal::new(box std::io::stdout() as Box<Writer:Send>);
            wc.map(|w| box w as Box<Terminal<Box<Writer:Send>:Send>:Send>)
        }
    }
}

#[cfg(not(windows))]
/// Return a Terminal wrapping stderr, or None if a terminal couldn't be
/// opened.
pub fn stderr() -> Option<Box<Terminal<Box<Writer:Send>:Send>:Send>:Send> {
    let ti: Option<TerminfoTerminal<Box<Writer:Send>>>
        = Terminal::new(box std::io::stderr() as Box<Writer:Send>);
    ti.map(|t| box t as Box<Terminal<Box<Writer:Send>:Send>:Send>)
}

#[cfg(windows)]
/// Return a Terminal wrapping stderr, or None if a terminal couldn't be
/// opened.
pub fn stderr() -> Option<Box<Terminal<Box<Writer:Send>:Send>:Send>> {
    let ti: Option<TerminfoTerminal<Box<Writer:Send>>>
        = Terminal::new(box std::io::stderr() as Box<Writer:Send>);

    match ti {
        Some(t) => Some(box t as Box<Terminal<Box<Writer:Send>:Send>:Send>),
        None => {
            let wc: Option<WinConsole<Box<Writer:Send>>>
                = Terminal::new(box std::io::stderr() as Box<Writer:Send>);
            wc.map(|w| box w as Box<Terminal<Box<Writer:Send>:Send>:Send>)
        }
    }
}

/// Terminal color definitions
pub mod color {
    /// Number for a terminal color
    pub type Color = u16;

    pub static BLACK:   Color = 0u16;
    pub static RED:     Color = 1u16;
    pub static GREEN:   Color = 2u16;
    pub static YELLOW:  Color = 3u16;
    pub static BLUE:    Color = 4u16;
    pub static MAGENTA: Color = 5u16;
    pub static CYAN:    Color = 6u16;
    pub static WHITE:   Color = 7u16;

    pub static BRIGHT_BLACK:   Color = 8u16;
    pub static BRIGHT_RED:     Color = 9u16;
    pub static BRIGHT_GREEN:   Color = 10u16;
    pub static BRIGHT_YELLOW:  Color = 11u16;
    pub static BRIGHT_BLUE:    Color = 12u16;
    pub static BRIGHT_MAGENTA: Color = 13u16;
    pub static BRIGHT_CYAN:    Color = 14u16;
    pub static BRIGHT_WHITE:   Color = 15u16;
}

/// Terminal attributes
pub mod attr {
    /// Terminal attributes for use with term.attr().
    ///
    /// Most attributes can only be turned on and must be turned off with term.reset().
    /// The ones that can be turned off explicitly take a boolean value.
    /// Color is also represented as an attribute for convenience.
    pub enum Attr {
        /// Bold (or possibly bright) mode
        Bold,
        /// Dim mode, also called faint or half-bright. Often not supported
        Dim,
        /// Italics mode. Often not supported
        Italic(bool),
        /// Underline mode
        Underline(bool),
        /// Blink mode
        Blink,
        /// Standout mode. Often implemented as Reverse, sometimes coupled with Bold
        Standout(bool),
        /// Reverse mode, inverts the foreground and background colors
        Reverse,
        /// Secure mode, also called invis mode. Hides the printed text
        Secure,
        /// Convenience attribute to set the foreground color
        ForegroundColor(super::color::Color),
        /// Convenience attribute to set the background color
        BackgroundColor(super::color::Color)
    }
}

/// A terminal with similar capabilities to an ANSI Terminal
/// (foreground/background colors etc).
pub trait Terminal<T: Writer>: Writer {
    /// Returns `None` whenever the terminal cannot be created for some
    /// reason.
    fn new(out: T) -> Option<Self>;

    /// Sets the foreground color to the given color.
    ///
    /// If the color is a bright color, but the terminal only supports 8 colors,
    /// the corresponding normal color will be used instead.
    ///
    /// Returns `Ok(true)` if the color was set, `Ok(false)` otherwise, and `Err(e)`
    /// if there was an I/O error.
    fn fg(&mut self, color: color::Color) -> IoResult<bool>;

    /// Sets the background color to the given color.
    ///
    /// If the color is a bright color, but the terminal only supports 8 colors,
    /// the corresponding normal color will be used instead.
    ///
    /// Returns `Ok(true)` if the color was set, `Ok(false)` otherwise, and `Err(e)`
    /// if there was an I/O error.
    fn bg(&mut self, color: color::Color) -> IoResult<bool>;

    /// Sets the given terminal attribute, if supported.  Returns `Ok(true)`
    /// if the attribute was supported, `Ok(false)` otherwise, and `Err(e)` if
    /// there was an I/O error.
    fn attr(&mut self, attr: attr::Attr) -> IoResult<bool>;

    /// Returns whether the given terminal attribute is supported.
    fn supports_attr(&self, attr: attr::Attr) -> bool;

    /// Resets all terminal attributes and color to the default.
    /// Returns `Ok()`.
    fn reset(&mut self) -> IoResult<()>;

    /// Returns the contained stream, destroying the `Terminal`
    fn unwrap(self) -> T;

    /// Gets an immutable reference to the stream inside
    fn get_ref<'a>(&'a self) -> &'a T;

    /// Gets a mutable reference to the stream inside
    fn get_mut<'a>(&'a mut self) -> &'a mut T;
}
<commit_msg>Fix example<commit_after>// Copyright 2013-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.

//! Terminal formatting library.
//!
//! This crate provides the `Terminal` trait, which abstracts over an [ANSI
//! Termina][ansi] to provide color printing, among other things. There are two implementations,
//! the `TerminfoTerminal`, which uses control characters from a
//! [terminfo][ti] database, and `WinConsole`, which uses the [Win32 Console
//! API][win].
//!
//! ## Example
//!
//! ```rust
//! extern crate term;
//!
//! fn main() {
//!     let mut t = term::stdout().unwrap();
//!     t.fg(term::color::GREEN).unwrap();
//!     println!("hello, ");
//!     t.fg(term::color::RED).unwrap();
//!     println!("world!");
//!     t.reset().unwrap();
//! }
//! ```
//!
//! [ansi]: https://en.wikipedia.org/wiki/ANSI_escape_code
//! [win]: http://msdn.microsoft.com/en-us/library/windows/desktop/ms682010%28v=vs.85%29.aspx
//! [ti]: https://en.wikipedia.org/wiki/Terminfo

#![crate_id = "term#0.11.0-pre"]
#![comment = "Simple ANSI color library"]
#![license = "MIT/ASL2"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
       html_favicon_url = "http://www.rust-lang.org/favicon.ico",
       html_root_url = "http://static.rust-lang.org/doc/master")]

#![feature(macro_rules, phase)]

#![deny(missing_doc)]

#[phase(syntax, link)] extern crate log;
extern crate collections;

pub use terminfo::TerminfoTerminal;
#[cfg(windows)]
pub use win::WinConsole;

use std::io::IoResult;

pub mod terminfo;

#[cfg(windows)]
mod win;

#[cfg(not(windows))]
/// Return a Terminal wrapping stdout, or None if a terminal couldn't be
/// opened.
pub fn stdout() -> Option<Box<Terminal<Box<Writer:Send>>:Send>> {
    let ti: Option<TerminfoTerminal<Box<Writer:Send>>>
        = Terminal::new(box std::io::stdout() as Box<Writer:Send>);
    ti.map(|t| box t as Box<Terminal<Box<Writer:Send>:Send>:Send>)
}

#[cfg(windows)]
/// Return a Terminal wrapping stdout, or None if a terminal couldn't be
/// opened.
pub fn stdout() -> Option<Box<Terminal<Box<Writer:Send>:Send>:Send>> {
    let ti: Option<TerminfoTerminal<Box<Writer:Send>>>
        = Terminal::new(box std::io::stdout() as Box<Writer:Send>);

    match ti {
        Some(t) => Some(box t as Box<Terminal<Box<Writer:Send>:Send>:Send>),
        None => {
            let wc: Option<WinConsole<Box<Writer:Send>>>
                = Terminal::new(box std::io::stdout() as Box<Writer:Send>);
            wc.map(|w| box w as Box<Terminal<Box<Writer:Send>:Send>:Send>)
        }
    }
}

#[cfg(not(windows))]
/// Return a Terminal wrapping stderr, or None if a terminal couldn't be
/// opened.
pub fn stderr() -> Option<Box<Terminal<Box<Writer:Send>:Send>:Send>:Send> {
    let ti: Option<TerminfoTerminal<Box<Writer:Send>>>
        = Terminal::new(box std::io::stderr() as Box<Writer:Send>);
    ti.map(|t| box t as Box<Terminal<Box<Writer:Send>:Send>:Send>)
}

#[cfg(windows)]
/// Return a Terminal wrapping stderr, or None if a terminal couldn't be
/// opened.
pub fn stderr() -> Option<Box<Terminal<Box<Writer:Send>:Send>:Send>> {
    let ti: Option<TerminfoTerminal<Box<Writer:Send>>>
        = Terminal::new(box std::io::stderr() as Box<Writer:Send>);

    match ti {
        Some(t) => Some(box t as Box<Terminal<Box<Writer:Send>:Send>:Send>),
        None => {
            let wc: Option<WinConsole<Box<Writer:Send>>>
                = Terminal::new(box std::io::stderr() as Box<Writer:Send>);
            wc.map(|w| box w as Box<Terminal<Box<Writer:Send>:Send>:Send>)
        }
    }
}

/// Terminal color definitions
pub mod color {
    /// Number for a terminal color
    pub type Color = u16;

    pub static BLACK:   Color = 0u16;
    pub static RED:     Color = 1u16;
    pub static GREEN:   Color = 2u16;
    pub static YELLOW:  Color = 3u16;
    pub static BLUE:    Color = 4u16;
    pub static MAGENTA: Color = 5u16;
    pub static CYAN:    Color = 6u16;
    pub static WHITE:   Color = 7u16;

    pub static BRIGHT_BLACK:   Color = 8u16;
    pub static BRIGHT_RED:     Color = 9u16;
    pub static BRIGHT_GREEN:   Color = 10u16;
    pub static BRIGHT_YELLOW:  Color = 11u16;
    pub static BRIGHT_BLUE:    Color = 12u16;
    pub static BRIGHT_MAGENTA: Color = 13u16;
    pub static BRIGHT_CYAN:    Color = 14u16;
    pub static BRIGHT_WHITE:   Color = 15u16;
}

/// Terminal attributes
pub mod attr {
    /// Terminal attributes for use with term.attr().
    ///
    /// Most attributes can only be turned on and must be turned off with term.reset().
    /// The ones that can be turned off explicitly take a boolean value.
    /// Color is also represented as an attribute for convenience.
    pub enum Attr {
        /// Bold (or possibly bright) mode
        Bold,
        /// Dim mode, also called faint or half-bright. Often not supported
        Dim,
        /// Italics mode. Often not supported
        Italic(bool),
        /// Underline mode
        Underline(bool),
        /// Blink mode
        Blink,
        /// Standout mode. Often implemented as Reverse, sometimes coupled with Bold
        Standout(bool),
        /// Reverse mode, inverts the foreground and background colors
        Reverse,
        /// Secure mode, also called invis mode. Hides the printed text
        Secure,
        /// Convenience attribute to set the foreground color
        ForegroundColor(super::color::Color),
        /// Convenience attribute to set the background color
        BackgroundColor(super::color::Color)
    }
}

/// A terminal with similar capabilities to an ANSI Terminal
/// (foreground/background colors etc).
pub trait Terminal<T: Writer>: Writer {
    /// Returns `None` whenever the terminal cannot be created for some
    /// reason.
    fn new(out: T) -> Option<Self>;

    /// Sets the foreground color to the given color.
    ///
    /// If the color is a bright color, but the terminal only supports 8 colors,
    /// the corresponding normal color will be used instead.
    ///
    /// Returns `Ok(true)` if the color was set, `Ok(false)` otherwise, and `Err(e)`
    /// if there was an I/O error.
    fn fg(&mut self, color: color::Color) -> IoResult<bool>;

    /// Sets the background color to the given color.
    ///
    /// If the color is a bright color, but the terminal only supports 8 colors,
    /// the corresponding normal color will be used instead.
    ///
    /// Returns `Ok(true)` if the color was set, `Ok(false)` otherwise, and `Err(e)`
    /// if there was an I/O error.
    fn bg(&mut self, color: color::Color) -> IoResult<bool>;

    /// Sets the given terminal attribute, if supported.  Returns `Ok(true)`
    /// if the attribute was supported, `Ok(false)` otherwise, and `Err(e)` if
    /// there was an I/O error.
    fn attr(&mut self, attr: attr::Attr) -> IoResult<bool>;

    /// Returns whether the given terminal attribute is supported.
    fn supports_attr(&self, attr: attr::Attr) -> bool;

    /// Resets all terminal attributes and color to the default.
    /// Returns `Ok()`.
    fn reset(&mut self) -> IoResult<()>;

    /// Returns the contained stream, destroying the `Terminal`
    fn unwrap(self) -> T;

    /// Gets an immutable reference to the stream inside
    fn get_ref<'a>(&'a self) -> &'a T;

    /// Gets a mutable reference to the stream inside
    fn get_mut<'a>(&'a mut self) -> &'a mut T;
}
<|endoftext|>


<commit_before><commit_msg>Communicator crate updates<commit_after><|endoftext|>


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

// Detecting language items.
//
// Language items are items that represent concepts intrinsic to the language
// itself. Examples are:
//
// * Traits that specify "kinds"; e.g. "Share", "Send".
//
// * Traits that represent operators; e.g. "Add", "Sub", "Index".
//
// * Functions called by the compiler itself.

use driver::session::Session;
use metadata::csearch::each_lang_item;
use middle::ty;
use syntax::ast;
use syntax::ast_util::local_def;
use syntax::attr::AttrMetaMethods;
use syntax::parse::token::InternedString;
use syntax::visit::Visitor;
use syntax::visit;

use collections::HashMap;
use std::iter::Enumerate;
use std::slice;

// The actual lang items defined come at the end of this file in one handy table.
// So you probably just want to nip down to the end.
macro_rules! lets_do_this {
    (
        $( $variant:ident, $name:expr, $method:ident; )*
    ) => {

#[deriving(FromPrimitive)]
pub enum LangItem {
    $($variant),*
}

pub struct LanguageItems {
    pub items: Vec<Option<ast::DefId>> ,
}

impl LanguageItems {
    pub fn new() -> LanguageItems {
        fn foo(_: LangItem) -> Option<ast::DefId> { None }

        LanguageItems {
            items: vec!($(foo($variant)),*)
        }
    }

    pub fn items<'a>(&'a self) -> Enumerate<slice::Items<'a, Option<ast::DefId>>> {
        self.items.iter().enumerate()
    }

    pub fn item_name(index: uint) -> &'static str {
        let item: Option<LangItem> = FromPrimitive::from_uint(index);
        match item {
            $( Some($variant) => $name, )*
            None => "???"
        }
    }

    pub fn require(&self, it: LangItem) -> Result<ast::DefId, ~str> {
        match self.items.get(it as uint) {
            &Some(id) => Ok(id),
            &None => {
                Err(format!("requires `{}` lang_item",
                            LanguageItems::item_name(it as uint)))
            }
        }
    }

    pub fn to_builtin_kind(&self, id: ast::DefId) -> Option<ty::BuiltinBound> {
        if Some(id) == self.send_trait() {
            Some(ty::BoundSend)
        } else if Some(id) == self.sized_trait() {
            Some(ty::BoundSized)
        } else if Some(id) == self.copy_trait() {
            Some(ty::BoundCopy)
        } else if Some(id) == self.share_trait() {
            Some(ty::BoundShare)
        } else {
            None
        }
    }

    $(
        pub fn $method(&self) -> Option<ast::DefId> {
            *self.items.get($variant as uint)
        }
    )*
}

struct LanguageItemCollector<'a> {
    items: LanguageItems,

    session: &'a Session,

    item_refs: HashMap<&'static str, uint>,
}

impl<'a> Visitor<()> for LanguageItemCollector<'a> {
    fn visit_item(&mut self, item: &ast::Item, _: ()) {
        match extract(item.attrs.as_slice()) {
            Some(value) => {
                let item_index = self.item_refs.find_equiv(&value).map(|x| *x);

                match item_index {
                    Some(item_index) => {
                        self.collect_item(item_index, local_def(item.id))
                    }
                    None => {}
                }
            }
            None => {}
        }

        visit::walk_item(self, item, ());
    }
}

impl<'a> LanguageItemCollector<'a> {
    pub fn new(session: &'a Session) -> LanguageItemCollector<'a> {
        let mut item_refs = HashMap::new();

        $( item_refs.insert($name, $variant as uint); )*

        LanguageItemCollector {
            session: session,
            items: LanguageItems::new(),
            item_refs: item_refs
        }
    }

    pub fn collect_item(&mut self, item_index: uint, item_def_id: ast::DefId) {
        // Check for duplicates.
        match self.items.items.get(item_index) {
            &Some(original_def_id) if original_def_id != item_def_id => {
                self.session.err(format!("duplicate entry for `{}`",
                                      LanguageItems::item_name(item_index)));
            }
            &Some(_) | &None => {
                // OK.
            }
        }

        // Matched.
        *self.items.items.get_mut(item_index) = Some(item_def_id);
    }

    pub fn collect_local_language_items(&mut self, krate: &ast::Crate) {
        visit::walk_crate(self, krate, ());
    }

    pub fn collect_external_language_items(&mut self) {
        let crate_store = &self.session.cstore;
        crate_store.iter_crate_data(|crate_number, _crate_metadata| {
            each_lang_item(crate_store, crate_number, |node_id, item_index| {
                let def_id = ast::DefId { krate: crate_number, node: node_id };
                self.collect_item(item_index, def_id);
                true
            });
        })
    }

    pub fn collect(&mut self, krate: &ast::Crate) {
        self.collect_local_language_items(krate);
        self.collect_external_language_items();
    }
}

pub fn extract(attrs: &[ast::Attribute]) -> Option<InternedString> {
    for attribute in attrs.iter() {
        match attribute.name_str_pair() {
            Some((ref key, ref value)) if key.equiv(&("lang")) => {
                return Some((*value).clone());
            }
            Some(..) | None => {}
        }
    }

    return None;
}

pub fn collect_language_items(krate: &ast::Crate,
                              session: &Session) -> @LanguageItems {
    let mut collector = LanguageItemCollector::new(session);
    collector.collect(krate);
    let LanguageItemCollector { items, .. } = collector;
    session.abort_if_errors();
    @items
}

// End of the macro
    }
}

lets_do_this! {
//  Variant name,                    Name,                      Method name;
    SendTraitLangItem,               "send",                    send_trait;
    SizedTraitLangItem,              "sized",                   sized_trait;
    CopyTraitLangItem,               "copy",                    copy_trait;
    ShareTraitLangItem,              "share",                   share_trait;

    DropTraitLangItem,               "drop",                    drop_trait;

    AddTraitLangItem,                "add",                     add_trait;
    SubTraitLangItem,                "sub",                     sub_trait;
    MulTraitLangItem,                "mul",                     mul_trait;
    DivTraitLangItem,                "div",                     div_trait;
    RemTraitLangItem,                "rem",                     rem_trait;
    NegTraitLangItem,                "neg",                     neg_trait;
    NotTraitLangItem,                "not",                     not_trait;
    BitXorTraitLangItem,             "bitxor",                  bitxor_trait;
    BitAndTraitLangItem,             "bitand",                  bitand_trait;
    BitOrTraitLangItem,              "bitor",                   bitor_trait;
    ShlTraitLangItem,                "shl",                     shl_trait;
    ShrTraitLangItem,                "shr",                     shr_trait;
    IndexTraitLangItem,              "index",                   index_trait;

    UnsafeTypeLangItem,              "unsafe",                  unsafe_type;

    DerefTraitLangItem,              "deref",                   deref_trait;
    DerefMutTraitLangItem,           "deref_mut",               deref_mut_trait;

    EqTraitLangItem,                 "eq",                      eq_trait;
    OrdTraitLangItem,                "ord",                     ord_trait;

    StrEqFnLangItem,                 "str_eq",                  str_eq_fn;
    UniqStrEqFnLangItem,             "uniq_str_eq",             uniq_str_eq_fn;
    FailFnLangItem,                  "fail_",                   fail_fn;
    FailBoundsCheckFnLangItem,       "fail_bounds_check",       fail_bounds_check_fn;
    ExchangeMallocFnLangItem,        "exchange_malloc",         exchange_malloc_fn;
    ClosureExchangeMallocFnLangItem, "closure_exchange_malloc", closure_exchange_malloc_fn;
    ExchangeFreeFnLangItem,          "exchange_free",           exchange_free_fn;
    MallocFnLangItem,                "malloc",                  malloc_fn;
    FreeFnLangItem,                  "free",                    free_fn;
    StrDupUniqFnLangItem,            "strdup_uniq",             strdup_uniq_fn;

    StartFnLangItem,                 "start",                   start_fn;

    TyDescStructLangItem,            "ty_desc",                 ty_desc;
    TyVisitorTraitLangItem,          "ty_visitor",              ty_visitor;
    OpaqueStructLangItem,            "opaque",                  opaque;

    TypeIdLangItem,                  "type_id",                 type_id;

    EhPersonalityLangItem,           "eh_personality",          eh_personality_fn;

    ManagedHeapLangItem,             "managed_heap",            managed_heap;
    ExchangeHeapLangItem,            "exchange_heap",           exchange_heap;
    GcLangItem,                      "gc",                      gc;

    CovariantTypeItem,               "covariant_type",          covariant_type;
    ContravariantTypeItem,           "contravariant_type",      contravariant_type;
    InvariantTypeItem,               "invariant_type",          invariant_type;

    CovariantLifetimeItem,           "covariant_lifetime",      covariant_lifetime;
    ContravariantLifetimeItem,       "contravariant_lifetime",  contravariant_lifetime;
    InvariantLifetimeItem,           "invariant_lifetime",      invariant_lifetime;

    NoSendItem,                      "no_send_bound",           no_send_bound;
    NoCopyItem,                      "no_copy_bound",           no_copy_bound;
    NoShareItem,                     "no_share_bound",          no_share_bound;
    ManagedItem,                     "managed_bound",           managed_bound;
}
<commit_msg>middle: lang_items: allow dead code<commit_after>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// Detecting language items.
//
// Language items are items that represent concepts intrinsic to the language
// itself. Examples are:
//
// * Traits that specify "kinds"; e.g. "Share", "Send".
//
// * Traits that represent operators; e.g. "Add", "Sub", "Index".
//
// * Functions called by the compiler itself.

use driver::session::Session;
use metadata::csearch::each_lang_item;
use middle::ty;
use syntax::ast;
use syntax::ast_util::local_def;
use syntax::attr::AttrMetaMethods;
use syntax::parse::token::InternedString;
use syntax::visit::Visitor;
use syntax::visit;

use collections::HashMap;
use std::iter::Enumerate;
use std::slice;

// The actual lang items defined come at the end of this file in one handy table.
// So you probably just want to nip down to the end.
macro_rules! lets_do_this {
    (
        $( $variant:ident, $name:expr, $method:ident; )*
    ) => {

#[deriving(FromPrimitive)]
pub enum LangItem {
    $($variant),*
}

pub struct LanguageItems {
    pub items: Vec<Option<ast::DefId>> ,
}

impl LanguageItems {
    pub fn new() -> LanguageItems {
        fn foo(_: LangItem) -> Option<ast::DefId> { None }

        LanguageItems {
            items: vec!($(foo($variant)),*)
        }
    }

    pub fn items<'a>(&'a self) -> Enumerate<slice::Items<'a, Option<ast::DefId>>> {
        self.items.iter().enumerate()
    }

    pub fn item_name(index: uint) -> &'static str {
        let item: Option<LangItem> = FromPrimitive::from_uint(index);
        match item {
            $( Some($variant) => $name, )*
            None => "???"
        }
    }

    pub fn require(&self, it: LangItem) -> Result<ast::DefId, ~str> {
        match self.items.get(it as uint) {
            &Some(id) => Ok(id),
            &None => {
                Err(format!("requires `{}` lang_item",
                            LanguageItems::item_name(it as uint)))
            }
        }
    }

    pub fn to_builtin_kind(&self, id: ast::DefId) -> Option<ty::BuiltinBound> {
        if Some(id) == self.send_trait() {
            Some(ty::BoundSend)
        } else if Some(id) == self.sized_trait() {
            Some(ty::BoundSized)
        } else if Some(id) == self.copy_trait() {
            Some(ty::BoundCopy)
        } else if Some(id) == self.share_trait() {
            Some(ty::BoundShare)
        } else {
            None
        }
    }

    $(
        #[allow(dead_code)]
        pub fn $method(&self) -> Option<ast::DefId> {
            *self.items.get($variant as uint)
        }
    )*
}

struct LanguageItemCollector<'a> {
    items: LanguageItems,

    session: &'a Session,

    item_refs: HashMap<&'static str, uint>,
}

impl<'a> Visitor<()> for LanguageItemCollector<'a> {
    fn visit_item(&mut self, item: &ast::Item, _: ()) {
        match extract(item.attrs.as_slice()) {
            Some(value) => {
                let item_index = self.item_refs.find_equiv(&value).map(|x| *x);

                match item_index {
                    Some(item_index) => {
                        self.collect_item(item_index, local_def(item.id))
                    }
                    None => {}
                }
            }
            None => {}
        }

        visit::walk_item(self, item, ());
    }
}

impl<'a> LanguageItemCollector<'a> {
    pub fn new(session: &'a Session) -> LanguageItemCollector<'a> {
        let mut item_refs = HashMap::new();

        $( item_refs.insert($name, $variant as uint); )*

        LanguageItemCollector {
            session: session,
            items: LanguageItems::new(),
            item_refs: item_refs
        }
    }

    pub fn collect_item(&mut self, item_index: uint, item_def_id: ast::DefId) {
        // Check for duplicates.
        match self.items.items.get(item_index) {
            &Some(original_def_id) if original_def_id != item_def_id => {
                self.session.err(format!("duplicate entry for `{}`",
                                      LanguageItems::item_name(item_index)));
            }
            &Some(_) | &None => {
                // OK.
            }
        }

        // Matched.
        *self.items.items.get_mut(item_index) = Some(item_def_id);
    }

    pub fn collect_local_language_items(&mut self, krate: &ast::Crate) {
        visit::walk_crate(self, krate, ());
    }

    pub fn collect_external_language_items(&mut self) {
        let crate_store = &self.session.cstore;
        crate_store.iter_crate_data(|crate_number, _crate_metadata| {
            each_lang_item(crate_store, crate_number, |node_id, item_index| {
                let def_id = ast::DefId { krate: crate_number, node: node_id };
                self.collect_item(item_index, def_id);
                true
            });
        })
    }

    pub fn collect(&mut self, krate: &ast::Crate) {
        self.collect_local_language_items(krate);
        self.collect_external_language_items();
    }
}

pub fn extract(attrs: &[ast::Attribute]) -> Option<InternedString> {
    for attribute in attrs.iter() {
        match attribute.name_str_pair() {
            Some((ref key, ref value)) if key.equiv(&("lang")) => {
                return Some((*value).clone());
            }
            Some(..) | None => {}
        }
    }

    return None;
}

pub fn collect_language_items(krate: &ast::Crate,
                              session: &Session) -> @LanguageItems {
    let mut collector = LanguageItemCollector::new(session);
    collector.collect(krate);
    let LanguageItemCollector { items, .. } = collector;
    session.abort_if_errors();
    @items
}

// End of the macro
    }
}

lets_do_this! {
//  Variant name,                    Name,                      Method name;
    SendTraitLangItem,               "send",                    send_trait;
    SizedTraitLangItem,              "sized",                   sized_trait;
    CopyTraitLangItem,               "copy",                    copy_trait;
    ShareTraitLangItem,              "share",                   share_trait;

    DropTraitLangItem,               "drop",                    drop_trait;

    AddTraitLangItem,                "add",                     add_trait;
    SubTraitLangItem,                "sub",                     sub_trait;
    MulTraitLangItem,                "mul",                     mul_trait;
    DivTraitLangItem,                "div",                     div_trait;
    RemTraitLangItem,                "rem",                     rem_trait;
    NegTraitLangItem,                "neg",                     neg_trait;
    NotTraitLangItem,                "not",                     not_trait;
    BitXorTraitLangItem,             "bitxor",                  bitxor_trait;
    BitAndTraitLangItem,             "bitand",                  bitand_trait;
    BitOrTraitLangItem,              "bitor",                   bitor_trait;
    ShlTraitLangItem,                "shl",                     shl_trait;
    ShrTraitLangItem,                "shr",                     shr_trait;
    IndexTraitLangItem,              "index",                   index_trait;

    UnsafeTypeLangItem,              "unsafe",                  unsafe_type;

    DerefTraitLangItem,              "deref",                   deref_trait;
    DerefMutTraitLangItem,           "deref_mut",               deref_mut_trait;

    EqTraitLangItem,                 "eq",                      eq_trait;
    OrdTraitLangItem,                "ord",                     ord_trait;

    StrEqFnLangItem,                 "str_eq",                  str_eq_fn;
    UniqStrEqFnLangItem,             "uniq_str_eq",             uniq_str_eq_fn;
    FailFnLangItem,                  "fail_",                   fail_fn;
    FailBoundsCheckFnLangItem,       "fail_bounds_check",       fail_bounds_check_fn;
    ExchangeMallocFnLangItem,        "exchange_malloc",         exchange_malloc_fn;
    ClosureExchangeMallocFnLangItem, "closure_exchange_malloc", closure_exchange_malloc_fn;
    ExchangeFreeFnLangItem,          "exchange_free",           exchange_free_fn;
    MallocFnLangItem,                "malloc",                  malloc_fn;
    FreeFnLangItem,                  "free",                    free_fn;
    StrDupUniqFnLangItem,            "strdup_uniq",             strdup_uniq_fn;

    StartFnLangItem,                 "start",                   start_fn;

    TyDescStructLangItem,            "ty_desc",                 ty_desc;
    TyVisitorTraitLangItem,          "ty_visitor",              ty_visitor;
    OpaqueStructLangItem,            "opaque",                  opaque;

    TypeIdLangItem,                  "type_id",                 type_id;

    EhPersonalityLangItem,           "eh_personality",          eh_personality_fn;

    ManagedHeapLangItem,             "managed_heap",            managed_heap;
    ExchangeHeapLangItem,            "exchange_heap",           exchange_heap;
    GcLangItem,                      "gc",                      gc;

    CovariantTypeItem,               "covariant_type",          covariant_type;
    ContravariantTypeItem,           "contravariant_type",      contravariant_type;
    InvariantTypeItem,               "invariant_type",          invariant_type;

    CovariantLifetimeItem,           "covariant_lifetime",      covariant_lifetime;
    ContravariantLifetimeItem,       "contravariant_lifetime",  contravariant_lifetime;
    InvariantLifetimeItem,           "invariant_lifetime",      invariant_lifetime;

    NoSendItem,                      "no_send_bound",           no_send_bound;
    NoCopyItem,                      "no_copy_bound",           no_copy_bound;
    NoShareItem,                     "no_share_bound",          no_share_bound;
    ManagedItem,                     "managed_bound",           managed_bound;
}
<|endoftext|>


<commit_before><commit_msg>add main4<commit_after>fn main() {
    let value = std::env::args().nth(1);
    let convert_and_double = compose(convert, double);

    match convert_and_double(value) {
        Some(n) => println!("{}", n),
        None => println!("No value"),
    }

}

fn convert(n: Option<String>) -> Option<f32> {
    n.and_then(|n| n.parse().ok())
}

fn double(n: Option<f32>) -> Option<f32> {
    n.map(|n| n * 2.0)
}

fn compose<'f, T1, T2, T3, F1, F2>(a: F1, b: F2) -> Box<Fn(T1) -> T3 + 'f>
    where   F1:Fn(T1) -> T2 + 'f,
            F2:Fn(T2) -> T3 + 'f
{
    Box::new(move |input| b(a(input)))
}<|endoftext|>


<commit_before><commit_msg>Document {Anime,Manga}Attributes::airing_status<commit_after><|endoftext|>


<commit_before><commit_msg>s/should_fail/should_panic<commit_after><|endoftext|>


<commit_before><commit_msg>video.putTag method<commit_after><|endoftext|>


<commit_before>use metadata::{Metadata, Package, PackageId, Resolve, ResolveNode, Target};
use racer_interner::InternedString;
use std::collections::HashMap;
use std::path::{Path, PathBuf};

/// Cached dependencies for racer
#[derive(Clone, Debug)]
pub struct PackageMap {
    manifest_to_id: HashMap<PathBuf, PackageId>,
    id_to_edition: HashMap<PackageId, InternedString>,
    id_to_deps: HashMap<PackageId, HashMap<InternedString, PathBuf>>,
    id_to_lib: HashMap<PackageId, Target>,
}

impl PackageMap {
    pub fn from_metadata(meta: Metadata) -> Self {
        let Metadata {
            packages, resolve, ..
        } = meta;
        PackageMap::new(packages, resolve)
    }
    pub fn new(packages: Vec<Package>, resolve: Option<Resolve>) -> Self {
        let mut manifest_to_id = HashMap::new();
        let mut id_to_lib = HashMap::new();
        let mut id_to_edition = HashMap::new();
        for package in packages {
            let Package {
                id,
                targets,
                manifest_path,
                edition,
                ..
            } = package;
            manifest_to_id.insert(manifest_path, id);
            id_to_edition.insert(id, edition);
            if let Some(t) = targets.into_iter().find(|t| t.is_lib()) {
                id_to_lib.insert(package.id, t.to_owned());
            }
        }
        let id_to_deps = resolve.map_or_else(
            || HashMap::new(),
            |res| construct_deps(res.nodes, &id_to_lib),
        );
        PackageMap {
            manifest_to_id,
            id_to_edition,
            id_to_deps,
            id_to_lib,
        }
    }
    pub fn get_id(&self, path: &Path) -> Option<PackageId> {
        self.manifest_to_id.get(path).map(|&id| id)
    }
    pub fn get_edition(&self, id: PackageId) -> Option<&str> {
        self.id_to_edition.get(&id).map(|s| s.as_str())
    }
    pub fn get_lib(&self, id: PackageId) -> Option<&Target> {
        self.id_to_lib.get(&id)
    }
    pub fn get_lib_src_path(&self, id: PackageId) -> Option<&Path> {
        self.get_lib(id).map(|t| t.src_path.as_ref())
    }
    pub fn ids(&self) -> impl Iterator<Item = &PackageId> {
        self.id_to_edition.keys()
    }
    pub fn get_dependencies(&self, id: PackageId) -> Option<&HashMap<InternedString, PathBuf>> {
        self.id_to_deps.get(&id)
    }
    pub fn get_src_path_from_libname(&self, id: PackageId, s: &str) -> Option<&Path> {
        let deps = self.get_dependencies(id)?;
        let query_str = InternedString::new_if_exists(s)?;
        deps.get(&query_str).map(AsRef::as_ref)
    }
}

fn construct_deps(
    nodes: Vec<ResolveNode>,
    targets: &HashMap<PackageId, Target>,
) -> HashMap<PackageId, HashMap<InternedString, PathBuf>> {
    nodes
        .into_iter()
        .map(|node| {
            let deps: HashMap<_, _> = node
                .dependencies
                .into_iter()
                .filter_map(|id| targets.get(&id).map(|t| (t.name, t.src_path.clone())))
                .collect();
            (node.id, deps)
        }).collect()
}
<commit_msg>Use vec for dependency<commit_after>use metadata::{Metadata, Package, PackageId, Resolve, ResolveNode, Target};
use racer_interner::InternedString;
use std::collections::HashMap;
use std::path::{Path, PathBuf};

/// Cached dependencies for racer
#[derive(Clone, Debug)]
pub struct PackageMap {
    manifest_to_id: HashMap<PathBuf, PackageId>,
    id_to_edition: HashMap<PackageId, InternedString>,
    id_to_deps: HashMap<PackageId, Vec<(InternedString, PathBuf)>>,
    id_to_lib: HashMap<PackageId, Target>,
}

impl PackageMap {
    pub fn from_metadata(meta: Metadata) -> Self {
        let Metadata {
            packages, resolve, ..
        } = meta;
        PackageMap::new(packages, resolve)
    }
    pub fn new(packages: Vec<Package>, resolve: Option<Resolve>) -> Self {
        let mut manifest_to_id = HashMap::new();
        let mut id_to_lib = HashMap::new();
        let mut id_to_edition = HashMap::new();
        for package in packages {
            let Package {
                id,
                targets,
                manifest_path,
                edition,
                ..
            } = package;
            manifest_to_id.insert(manifest_path, id);
            id_to_edition.insert(id, edition);
            if let Some(t) = targets.into_iter().find(|t| t.is_lib()) {
                id_to_lib.insert(package.id, t.to_owned());
            }
        }
        let id_to_deps = resolve.map_or_else(
            || HashMap::new(),
            |res| construct_deps(res.nodes, &id_to_lib),
        );
        PackageMap {
            manifest_to_id,
            id_to_edition,
            id_to_deps,
            id_to_lib,
        }
    }
    pub fn get_id(&self, path: &Path) -> Option<PackageId> {
        self.manifest_to_id.get(path).map(|&id| id)
    }
    pub fn get_edition(&self, id: PackageId) -> Option<&str> {
        self.id_to_edition.get(&id).map(|s| s.as_str())
    }
    pub fn get_lib(&self, id: PackageId) -> Option<&Target> {
        self.id_to_lib.get(&id)
    }
    pub fn get_lib_src_path(&self, id: PackageId) -> Option<&Path> {
        self.get_lib(id).map(|t| t.src_path.as_ref())
    }
    pub fn ids(&self) -> impl Iterator<Item = &PackageId> {
        self.id_to_edition.keys()
    }
    pub fn get_dependencies(&self, id: PackageId) -> Option<&Vec<(InternedString, PathBuf)>> {
        self.id_to_deps.get(&id)
    }
    pub fn get_src_path_from_libname(&self, id: PackageId, s: &str) -> Option<&Path> {
        let deps = self.get_dependencies(id)?;
        let query_str = InternedString::new_if_exists(s)?;
        deps.iter().find(|t| t.0 == query_str).map(|t| t.1.as_ref())
    }
}

fn construct_deps(
    nodes: Vec<ResolveNode>,
    targets: &HashMap<PackageId, Target>,
) -> HashMap<PackageId, Vec<(InternedString, PathBuf)>> {
    nodes
        .into_iter()
        .map(|node| {
            let deps: Vec<_> = node
                .dependencies
                .into_iter()
                .filter_map(|id| targets.get(&id).map(|t| (t.name, t.src_path.clone())))
                .collect();
            (node.id, deps)
        }).collect()
}
<|endoftext|>


<commit_before><commit_msg>load game screen<commit_after><|endoftext|>


<commit_before><commit_msg>Move update_db stuff into an sql transaction.<commit_after><|endoftext|>


<commit_before>// xfail-pretty

// -*- rust -*-
fn ho(f: fn(int) -> int ) -> int { let n: int = f(3); ret n; }

fn direct(x: int) -> int { ret x + 1; }

fn main() {
    let a: int =
        direct(3); // direct
                   //let int b = ho(direct); // indirect unbound

    let c: int =
        ho(bind direct(_)); // indirect bound
                            //assert (a == b);
                            //assert (b == c);

}<commit_msg>Clean up run-pass/fun-call-variants<commit_after>// -*- rust -*-
fn ho(f: fn(int) -> int ) -> int { let n: int = f(3); ret n; }

fn direct(x: int) -> int { ret x + 1; }

fn main() {
    let a: int =
        direct(3); // direct
    let b: int = ho(direct); // indirect unbound

    let c: int =
        ho(bind direct(_)); // indirect bound
    assert (a == b);
    assert (b == c);
}<|endoftext|>


<commit_before><commit_msg>Oops - forgot to git add cargo.rs<commit_after>use std::fs::File;
use std::io::Read;
use std::env;
use std::path::{Path,PathBuf};
use std::fs::{PathExt,read_dir};
use toml;

macro_rules! otry {
    ($e:expr) => (match $e { Some(e) => e, None => return None})
}

macro_rules! otry2 {
    ($e:expr) => (match $e { Ok(e) => e, Err(_) => return None})
}

fn find_src_via_lockfile(kratename: &str, cargofile: &Path) -> Option<PathBuf> {
    let mut file = otry2!(File::open(cargofile));
    let mut string = String::new();
    otry2!(file.read_to_string(&mut string));
    let mut parser = toml::Parser::new(&string);
    let lock_table = parser.parse().unwrap();

    debug!("PHIL found lock table {:?}",lock_table);

    let t = match lock_table.get("package") {
        Some(&toml::Value::Array(ref t1)) => t1,
        _ => return None
    };

    for item in t {
        if let &toml::Value::Table(ref t) = item {
            if Some(&toml::Value::String(kratename.to_string())) == t.get("name") {

                let version = otry!(getstr(t, "version"));
                let source = otry!(getstr(t, "source"));

                if Some("registry") == source.split("+").nth(0) {

                    let mut d = otry!(env::home_dir());
                    d.push(".cargo");
                    d.push("registry");
                    d.push("src");
                    d = otry!(find_git_dir(d));
                    d.push(kratename.to_string() + "-" + &version);
                    d.push("src");
                    d.push("lib.rs");
                    return Some(d)
                }
            }
        }
    }
    return None;
}

fn find_git_dir(d: PathBuf) -> Option<PathBuf> {
    for entry in otry2!(read_dir(d)) {
        let path = otry2!(entry).path();

        // Assume there is only one directory and it's the git one
        if path.is_dir() {
            if let Some(ref fname) = path.file_name().and_then(|s| s.to_str()) {
                println!("PHIL fname is {}",fname);
                if fname.starts_with("git-") {
                    return Some(path.clone());
                }
            }
        }
    }
    return None;
}

fn getstr(t: &toml::Table, k: &str) -> Option<String> {
    match t.get(k) {
        Some(&toml::Value::String(ref s)) => Some(s.clone()),
        _ => None
    }
}

fn find_cargo_lockfile(currentfile: &Path) -> Option<PathBuf> {
    let mut f = currentfile.to_path_buf();
    f.push("Cargo.lock");
    if f.exists() {
        return Some(f);
    } else {
        if f.pop() && f.pop() {
            return find_cargo_lockfile(&f);
        } else {
            None
        }
    }
}

pub fn get_crate_file(name: &str, from_path: &Path) -> Option<PathBuf> {
    if let Some(lockfile) = find_cargo_lockfile(from_path) {
        return find_src_via_lockfile(name, &lockfile);
    }
    None
}
<|endoftext|>