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

use ast;
use ast::{MetaItem, Item, Expr};
use codemap::Span;
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use ext::deriving::generic::*;
use parse::token::InternedString;
use parse::token;

pub fn expand_deriving_to_str(cx: &mut ExtCtxt,
                              span: Span,
                              mitem: @MetaItem,
                              in_items: ~[@Item])
                              -> ~[@Item] {
    let trait_def = TraitDef {
        span: span,
        path: Path::new(~["std", "to_str", "ToStr"]),
        additional_bounds: ~[],
        generics: LifetimeBounds::empty(),
        methods: ~[
            MethodDef {
                name: "to_str",
                generics: LifetimeBounds::empty(),
                explicit_self: borrowed_explicit_self(),
                args: ~[],
                ret_ty: Ptr(~Literal(Path::new_local("str")), Send),
                inline: false,
                const_nonmatching: false,
                combine_substructure: to_str_substructure
            }
        ]
    };
    trait_def.expand(cx, mitem, in_items)
}

// It used to be the case that this deriving implementation invoked
// std::repr::repr_to_str, but this isn't sufficient because it
// doesn't invoke the to_str() method on each field. Hence we mirror
// the logic of the repr_to_str() method, but with tweaks to call to_str()
// on sub-fields.
fn to_str_substructure(cx: &mut ExtCtxt, span: Span, substr: &Substructure)
                       -> @Expr {
    let to_str = cx.ident_of("to_str");

    let doit = |start: &str,
                end: InternedString,
                name: ast::Ident,
                fields: &[FieldInfo]| {
        if fields.len() == 0 {
            cx.expr_str_uniq(span, token::get_ident(name.name))
        } else {
            let buf = cx.ident_of("buf");
            let interned_str = token::get_ident(name.name);
            let start =
                token::intern_and_get_ident(interned_str.get() + start);
            let init = cx.expr_str_uniq(span, start);
            let mut stmts = ~[cx.stmt_let(span, true, buf, init)];
            let push_str = cx.ident_of("push_str");

            let push = |s: @Expr| {
                let ebuf = cx.expr_ident(span, buf);
                let call = cx.expr_method_call(span, ebuf, push_str, ~[s]);
                stmts.push(cx.stmt_expr(call));
            };

            for (i, &FieldInfo {name, span, self_, .. }) in fields.iter().enumerate() {
                if i > 0 {
                    push(cx.expr_str(span, InternedString::new(", ")));
                }
                match name {
                    None => {}
                    Some(id) => {
                        let interned_id = token::get_ident(id.name);
                        let name = interned_id.get() + ": ";
                        push(cx.expr_str(span,
                                         token::intern_and_get_ident(name)));
                    }
                }
                push(cx.expr_method_call(span, self_, to_str, ~[]));
            }
            push(cx.expr_str(span, end));

            cx.expr_block(cx.block(span, stmts, Some(cx.expr_ident(span,
                                                                   buf))))
        }
    };

    return match *substr.fields {
        Struct(ref fields) => {
            if fields.len() == 0 || fields[0].name.is_none() {
                doit("(",
                     InternedString::new(")"),
                     substr.type_ident,
                     *fields)
            } else {
                doit("{",
                     InternedString::new("}"),
                     substr.type_ident,
                     *fields)
            }
        }

        EnumMatching(_, variant, ref fields) => {
            match variant.node.kind {
                ast::TupleVariantKind(..) =>
                    doit("(",
                         InternedString::new(")"),
                         variant.node.name,
                         *fields),
                ast::StructVariantKind(..) =>
                    doit("{",
                         InternedString::new("}"),
                         variant.node.name,
                         *fields),
            }
        }

        _ => cx.bug("expected Struct or EnumMatching in deriving(ToStr)")
    };
}
<commit_msg>to_str -- update to contain scope of closure<commit_after>// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use ast;
use ast::{MetaItem, Item, Expr};
use codemap::Span;
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use ext::deriving::generic::*;
use parse::token::InternedString;
use parse::token;

pub fn expand_deriving_to_str(cx: &mut ExtCtxt,
                              span: Span,
                              mitem: @MetaItem,
                              in_items: ~[@Item])
                              -> ~[@Item] {
    let trait_def = TraitDef {
        span: span,
        path: Path::new(~["std", "to_str", "ToStr"]),
        additional_bounds: ~[],
        generics: LifetimeBounds::empty(),
        methods: ~[
            MethodDef {
                name: "to_str",
                generics: LifetimeBounds::empty(),
                explicit_self: borrowed_explicit_self(),
                args: ~[],
                ret_ty: Ptr(~Literal(Path::new_local("str")), Send),
                inline: false,
                const_nonmatching: false,
                combine_substructure: to_str_substructure
            }
        ]
    };
    trait_def.expand(cx, mitem, in_items)
}

// It used to be the case that this deriving implementation invoked
// std::repr::repr_to_str, but this isn't sufficient because it
// doesn't invoke the to_str() method on each field. Hence we mirror
// the logic of the repr_to_str() method, but with tweaks to call to_str()
// on sub-fields.
fn to_str_substructure(cx: &mut ExtCtxt, span: Span, substr: &Substructure)
                       -> @Expr {
    let to_str = cx.ident_of("to_str");

    let doit = |start: &str,
                end: InternedString,
                name: ast::Ident,
                fields: &[FieldInfo]| {
        if fields.len() == 0 {
            cx.expr_str_uniq(span, token::get_ident(name.name))
        } else {
            let buf = cx.ident_of("buf");
            let interned_str = token::get_ident(name.name);
            let start =
                token::intern_and_get_ident(interned_str.get() + start);
            let init = cx.expr_str_uniq(span, start);
            let mut stmts = ~[cx.stmt_let(span, true, buf, init)];
            let push_str = cx.ident_of("push_str");

            {
                let push = |s: @Expr| {
                    let ebuf = cx.expr_ident(span, buf);
                    let call = cx.expr_method_call(span, ebuf, push_str, ~[s]);
                    stmts.push(cx.stmt_expr(call));
                };

                for (i, &FieldInfo {name, span, self_, .. }) in fields.iter().enumerate() {
                    if i > 0 {
                        push(cx.expr_str(span, InternedString::new(", ")));
                    }
                    match name {
                        None => {}
                        Some(id) => {
                            let interned_id = token::get_ident(id.name);
                            let name = interned_id.get() + ": ";
                            push(cx.expr_str(span,
                                             token::intern_and_get_ident(name)));
                        }
                    }
                    push(cx.expr_method_call(span, self_, to_str, ~[]));
                }
                push(cx.expr_str(span, end));
            }

            cx.expr_block(cx.block(span, stmts, Some(cx.expr_ident(span, buf))))
        }
    };

    return match *substr.fields {
        Struct(ref fields) => {
            if fields.len() == 0 || fields[0].name.is_none() {
                doit("(",
                     InternedString::new(")"),
                     substr.type_ident,
                     *fields)
            } else {
                doit("{",
                     InternedString::new("}"),
                     substr.type_ident,
                     *fields)
            }
        }

        EnumMatching(_, variant, ref fields) => {
            match variant.node.kind {
                ast::TupleVariantKind(..) =>
                    doit("(",
                         InternedString::new(")"),
                         variant.node.name,
                         *fields),
                ast::StructVariantKind(..) =>
                    doit("{",
                         InternedString::new("}"),
                         variant.node.name,
                         *fields),
            }
        }

        _ => cx.bug("expected Struct or EnumMatching in deriving(ToStr)")
    };
}
<|endoftext|>


<commit_before><commit_msg>Add simple SSL example<commit_after>extern crate ldap;

use ldap::LdapSync;

pub fn main() {
    let addr = "example.org:636";

    let mut ldap = LdapSync::connect_ssl(&addr).unwrap();

    let res = ldap.simple_bind("cn=root,dc=example,dc=org".to_string(), "secret".to_string()).unwrap();

    if res {
        println!("Bind succeeded!");
    } else {
        println!("Bind failed! :(");
    }
}
<|endoftext|>


<commit_before>static LANGUAGE: &'static str = "Rust";
static THRESHOLD: int = 10;

fn is_big(n: int) -> bool {
    // access constant in some function
    n > THRESHOLD
}

fn main() {
    let n = 16;

    // access constant in the main loop
    println!("This is {}", LANGUAGE);
    println!("The threshold is {}", THRESHOLD);
    println!("{} is {}", n, if is_big(n) { "big" } else { "small" });

    // Error: cannot modify static item
    //THRESHOLD = 5;

    if true {
        // string literals are placed in read-only memory
        let static_string: &'static str = "In read-only memory";

        // when static_string goes out of scope, we can't no longer refer
        // to it, but the string remains in the read-only memory
    }
}
<commit_msg>constants: fix typo. Closes #68<commit_after>static LANGUAGE: &'static str = "Rust";
static THRESHOLD: int = 10;

fn is_big(n: int) -> bool {
    // access constant in some function
    n > THRESHOLD
}

fn main() {
    let n = 16;

    // access constant in the main loop
    println!("This is {}", LANGUAGE);
    println!("The threshold is {}", THRESHOLD);
    println!("{} is {}", n, if is_big(n) { "big" } else { "small" });

    // Error: cannot modify static item
    //THRESHOLD = 5;

    if true {
        // string literals are placed in read-only memory
        let static_string: &'static str = "In read-only memory";

        // when static_string goes out of scope, we can no longer refer
        // to it, but the string remains in the read-only memory
    }
}
<|endoftext|>


<commit_before>// Issue #2263.

// Here, `f` is a function that takes a pointer `x` and a function
// `g`, where `g` requires its argument `y` to be in the same region
// that `x` is in.
fn has_same_region(f: fn(x: &a.int, g: fn(y: &a.int))) {
    // Somewhat counterintuitively, this fails because, in
    // `wants_two_regions`, the `g` argument needs to be able to
    // accept any region.  That is, the type that `has_same_region`
    // expects is *not* a subtype of the type that `wants_two_regions`
    // expects.
    wants_two_regions(f); //! ERROR mismatched types
}

fn wants_two_regions(_f: fn(x: &int, g: fn(y: &int))) {
}

fn main() {
}

<commit_msg>Clarifying comments in test.<commit_after>// Here, `f` is a function that takes a pointer `x` and a function
// `g`, where `g` requires its argument `y` to be in the same region
// that `x` is in.
fn has_same_region(f: fn(x: &a.int, g: fn(y: &a.int))) {
    // Somewhat counterintuitively, this fails because, in
    // `wants_two_regions`, the `g` argument needs to be able to
    // accept any region.  That is, the type that `has_same_region`
    // expects is *not* a subtype of the type that `wants_two_regions`
    // expects.
    wants_two_regions(f); //! ERROR mismatched types
}

fn wants_two_regions(_f: fn(x: &int, g: fn(y: &int))) {
    // Suppose we were to write code here that passed some arbitrary
    // &int and some arbitrary fn(&int) to whatever's passed in as _f.
    // This would be fine as far as the type annotation on the formal
    // parameter _f goes, but if _f were `f` we'd be in trouble since
    // `f` can't handle those arguments.
}

fn main() {
}

<|endoftext|>


<commit_before><commit_msg>Fix: Do not check whether path exists - check whether its a file<commit_after><|endoftext|>


<commit_before><commit_msg>genet-abi: remove genet_abi_version_marker__<commit_after><|endoftext|>


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

// ignore-tidy-linelength

use std::ops::{Add, Sub};

type Test = Add +
            //~^ ERROR the type parameter `RHS` must be explicitly specified in an object type because its default value `Self` references the type `Self`
            Sub;
            //~^ ERROR only the builtin traits can be used as closure or object bounds

fn main() { }
<|endoftext|>


<commit_before><commit_msg>Improve dbgsh kpanic!<commit_after><|endoftext|>


<commit_before><commit_msg>Properly use STYLE_THREAD_POOL in layout 2020<commit_after><|endoftext|>


<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.

use prelude::*;

use io::IoResult;

#[cfg(target_word_size = "64")] pub const HEX_WIDTH: uint = 18;
#[cfg(target_word_size = "32")] pub const HEX_WIDTH: uint = 10;

// All rust symbols are in theory lists of "::"-separated identifiers. Some
// assemblers, however, can't handle these characters in symbol names. To get
// around this, we use C++-style mangling. The mangling method is:
//
// 1. Prefix the symbol with "_ZN"
// 2. For each element of the path, emit the length plus the element
// 3. End the path with "E"
//
// For example, "_ZN4testE" => "test" and "_ZN3foo3bar" => "foo::bar".
//
// We're the ones printing our backtraces, so we can't rely on anything else to
// demangle our symbols. It's *much* nicer to look at demangled symbols, so
// this function is implemented to give us nice pretty output.
//
// Note that this demangler isn't quite as fancy as it could be. We have lots
// of other information in our symbols like hashes, version, type information,
// etc. Additionally, this doesn't handle glue symbols at all.
pub fn demangle(writer: &mut Writer, s: &str) -> IoResult<()> {
    // First validate the symbol. If it doesn't look like anything we're
    // expecting, we just print it literally. Note that we must handle non-rust
    // symbols because we could have any function in the backtrace.
    let mut valid = true;
    let mut inner = s;
    if s.len() > 4 && s.starts_with("_ZN") && s.ends_with("E") {
        inner = s.slice(3, s.len() - 1);
    // On Windows, dbghelp strips leading underscores, so we accept "ZN...E" form too.
    } else if s.len() > 3 && s.starts_with("ZN") && s.ends_with("E") {
        inner = s.slice(2, s.len() - 1);
    } else {
        valid = false;
    }

    if valid {
        let mut chars = inner.chars();
        while valid {
            let mut i = 0;
            for c in chars {
                if c.is_numeric() {
                    i = i * 10 + c as uint - '0' as uint;
                } else {
                    break
                }
            }
            if i == 0 {
                valid = chars.next().is_none();
                break
            } else if chars.by_ref().take(i - 1).count() != i - 1 {
                valid = false;
            }
        }
    }

    // Alright, let's do this.
    if !valid {
        try!(writer.write_str(s));
    } else {
        let mut first = true;
        while inner.len() > 0 {
            if !first {
                try!(writer.write_str("::"));
            } else {
                first = false;
            }
            let mut rest = inner;
            while rest.char_at(0).is_numeric() {
                rest = rest.slice_from(1);
            }
            let i: uint = inner.slice_to(inner.len() - rest.len()).parse().unwrap();
            inner = rest.slice_from(i);
            rest = rest.slice_to(i);
            while rest.len() > 0 {
                if rest.starts_with("$") {
                    macro_rules! demangle {
                        ($($pat:expr => $demangled:expr),*) => ({
                            $(if rest.starts_with($pat) {
                                try!(writer.write_str($demangled));
                                rest = rest.slice_from($pat.len());
                              } else)*
                            {
                                try!(writer.write_str(rest));
                                break;
                            }

                        })
                    }

                    // see src/librustc/back/link.rs for these mappings
                    demangle! (
                        "$SP$" => "@",
                        "$UP$" => "Box",
                        "$RP$" => "*",
                        "$BP$" => "&",
                        "$LT$" => "<",
                        "$GT$" => ">",
                        "$LP$" => "(",
                        "$RP$" => ")",
                        "$C$"  => ",",

                        // in theory we can demangle any Unicode code point, but
                        // for simplicity we just catch the common ones.
                        "$x20" => " ",
                        "$x27" => "'",
                        "$x5b" => "[",
                        "$x5d" => "]"
                    )
                } else {
                    let idx = match rest.find('$') {
                        None => rest.len(),
                        Some(i) => i,
                    };
                    try!(writer.write_str(rest.slice_to(idx)));
                    rest = rest.slice_from(idx);
                }
            }
        }
    }

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

use prelude::*;

use io::IoResult;

#[cfg(target_word_size = "64")] pub const HEX_WIDTH: uint = 18;
#[cfg(target_word_size = "32")] pub const HEX_WIDTH: uint = 10;

// All rust symbols are in theory lists of "::"-separated identifiers. Some
// assemblers, however, can't handle these characters in symbol names. To get
// around this, we use C++-style mangling. The mangling method is:
//
// 1. Prefix the symbol with "_ZN"
// 2. For each element of the path, emit the length plus the element
// 3. End the path with "E"
//
// For example, "_ZN4testE" => "test" and "_ZN3foo3bar" => "foo::bar".
//
// We're the ones printing our backtraces, so we can't rely on anything else to
// demangle our symbols. It's *much* nicer to look at demangled symbols, so
// this function is implemented to give us nice pretty output.
//
// Note that this demangler isn't quite as fancy as it could be. We have lots
// of other information in our symbols like hashes, version, type information,
// etc. Additionally, this doesn't handle glue symbols at all.
pub fn demangle(writer: &mut Writer, s: &str) -> IoResult<()> {
    // First validate the symbol. If it doesn't look like anything we're
    // expecting, we just print it literally. Note that we must handle non-rust
    // symbols because we could have any function in the backtrace.
    let mut valid = true;
    let mut inner = s;
    if s.len() > 4 && s.starts_with("_ZN") && s.ends_with("E") {
        inner = s.slice(3, s.len() - 1);
    // On Windows, dbghelp strips leading underscores, so we accept "ZN...E" form too.
    } else if s.len() > 3 && s.starts_with("ZN") && s.ends_with("E") {
        inner = s.slice(2, s.len() - 1);
    } else {
        valid = false;
    }

    if valid {
        let mut chars = inner.chars();
        while valid {
            let mut i = 0;
            for c in chars {
                if c.is_numeric() {
                    i = i * 10 + c as uint - '0' as uint;
                } else {
                    break
                }
            }
            if i == 0 {
                valid = chars.next().is_none();
                break
            } else if chars.by_ref().take(i - 1).count() != i - 1 {
                valid = false;
            }
        }
    }

    // Alright, let's do this.
    if !valid {
        try!(writer.write_str(s));
    } else {
        let mut first = true;
        while inner.len() > 0 {
            if !first {
                try!(writer.write_str("::"));
            } else {
                first = false;
            }
            let mut rest = inner;
            while rest.char_at(0).is_numeric() {
                rest = rest.slice_from(1);
            }
            let i: uint = inner.slice_to(inner.len() - rest.len()).parse().unwrap();
            inner = rest.slice_from(i);
            rest = rest.slice_to(i);
            while rest.len() > 0 {
                if rest.starts_with("$") {
                    macro_rules! demangle {
                        ($($pat:expr => $demangled:expr),*) => ({
                            $(if rest.starts_with($pat) {
                                try!(writer.write_str($demangled));
                                rest = rest.slice_from($pat.len());
                              } else)*
                            {
                                try!(writer.write_str(rest));
                                break;
                            }

                        })
                    }

                    // see src/librustc/back/link.rs for these mappings
                    demangle! (
                        "$SP$" => "@",
                        "$UP$" => "Box",
                        "$RP$" => "*",
                        "$BP$" => "&",
                        "$LT$" => "<",
                        "$GT$" => ">",
                        "$LP$" => "(",
                        "$RP$" => ")",
                        "$C$"  => ",",

                        // in theory we can demangle any Unicode code point, but
                        // for simplicity we just catch the common ones.
                        "$u{20}" => " ",
                        "$u{27}" => "'",
                        "$u{5b}" => "[",
                        "$u{5d}" => "]"
                    )
                } else {
                    let idx = match rest.find('$') {
                        None => rest.len(),
                        Some(i) => i,
                    };
                    try!(writer.write_str(rest.slice_to(idx)));
                    rest = rest.slice_from(idx);
                }
            }
        }
    }

    Ok(())
}
<|endoftext|>


<commit_before><commit_msg>benches: add lorem ipsum generation benchmark<commit_after>#![feature(test)]
extern crate test;
extern crate lipsum;

use test::Bencher;

#[bench]
fn generate_lorem_ipsum_100(b: &mut Bencher) {
    b.iter(|| lipsum::lipsum(100))
}

#[bench]
fn generate_lorem_ipsum_200(b: &mut Bencher) {
    b.iter(|| lipsum::lipsum(200))
}
<|endoftext|>


<commit_before>// error-pattern:fail

fn failfn() {
    fail;
}

fn main() {
    @0;
    failfn();
}<commit_msg>Actually use unique boxes in run-fail/unwind-unique<commit_after>// error-pattern:fail

fn failfn() {
    fail;
}

fn main() {
    ~0;
    failfn();
}<|endoftext|>


<commit_before><commit_msg>Add a test<commit_after>#![allow(dead_code, unused_imports)]
#![feature(no_core)]
#![no_core]
// edition:2018

extern crate std;
extern crate core;
use core::{prelude::v1::*, *};

fn foo() {
    for _ in &[()] {}
}

fn bar() -> Option<()> {
    None?
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Study with Project<commit_after>fn main() }
	println!("This is book manage program for studying rust");
}
<|endoftext|>


<commit_before>//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//

#[macro_use] extern crate log;
#[macro_use] extern crate version;
extern crate semver;
extern crate clap;

extern crate libimagstore;
extern crate libimagrt;
extern crate libimagref;
extern crate libimagerror;
extern crate libimagentrylist;
extern crate libimaginteraction;

mod ui;
use ui::build_ui;

use std::path::PathBuf;

use libimagref::reference::Ref;
use libimagref::flags::RefFlags;
use libimagerror::trace::trace_error;
use libimagrt::setup::generate_runtime_setup;
use libimagrt::runtime::Runtime;

fn main() {
    let rt = generate_runtime_setup("imag-ref",
                                    &version!()[..],
                                    "Reference files outside of the store",
                                    build_ui);
    rt.cli()
        .subcommand_name()
        .map(|name| {
            debug!("Call: {}", name);
            match name {
                "add"    => add(&rt),
                "remove" => remove(&rt),
                "list"   => list(&rt),
                _        => {
                    debug!("Unknown command"); // More error handling
                },
            };
        });
}

fn add(rt: &Runtime) {
    let cmd  = rt.cli().subcommand_matches("add").unwrap();
    let path = cmd.value_of("path").map(PathBuf::from).unwrap(); // saved by clap

    let flags = RefFlags::default()
        .with_content_hashing(cmd.is_present("track-content"))
        .with_permission_tracking(cmd.is_present("track-permissions"));

    match Ref::create(rt.store(), path, flags) {
        Ok(r) => {
            debug!("Reference created: {:?}", r);
            info!("Ok");
        },
        Err(e) => {
            trace_error(&e);
            warn!("Failed to create reference");
        },
    }
}

fn remove(rt: &Runtime) {
    use libimagref::error::RefErrorKind;
    use libimagerror::into::IntoError;
    use libimaginteraction::ask::ask_bool;

    let cmd  = rt.cli().subcommand_matches("remove").unwrap();
    let hash = cmd.value_of("hash").map(String::from).unwrap(); // saved by clap
    let yes  = cmd.is_present("yes");

    if yes || ask_bool(&format!("Delete Ref with hash '{}'", hash)[..], None) {
        match Ref::delete_by_hash(rt.store(), hash) {
            Err(e) => trace_error(&e),
            Ok(_) => info!("Ok"),
        }
    } else {
        info!("Aborted");
    }

}

fn list(rt: &Runtime) {
    use std::process::exit;
    use std::ops::Deref;

    use libimagentrylist::lister::Lister;
    use libimagentrylist::listers::core::CoreLister;
    use libimagref::lister::RefLister;

    let cmd                      = rt.cli().subcommand_matches("list").unwrap();
    let do_check_dead            = cmd.is_present("check-dead");
    let do_check_changed         = cmd.is_present("check-changed");
    let do_check_changed_content = cmd.is_present("check-changed-content");
    let do_check_changed_permiss = cmd.is_present("check-changed-permissions");

    let iter = match rt.store().retrieve_for_module("ref") {
        Ok(iter) => iter.filter_map(|id| {
            match Ref::get(rt.store(), id) {
                Ok(r) => Some(r),
                Err(e) => {
                    trace_error(&e);
                    None
                },
            }
        }),
        Err(e) => {
            trace_error(&e);
            exit(1);
        }
    };

    RefLister::new()
        .check_dead(do_check_dead)
        .check_changed(do_check_changed)
        .check_changed_content(do_check_changed_content)
        .check_changed_permiss(do_check_changed_permiss)
        .list(iter.map(|e| e.into()));
}

<commit_msg>Remove unused imports<commit_after>//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//

#[macro_use] extern crate log;
#[macro_use] extern crate version;
extern crate semver;
extern crate clap;

extern crate libimagstore;
extern crate libimagrt;
extern crate libimagref;
extern crate libimagerror;
extern crate libimagentrylist;
extern crate libimaginteraction;

mod ui;
use ui::build_ui;

use std::path::PathBuf;

use libimagref::reference::Ref;
use libimagref::flags::RefFlags;
use libimagerror::trace::trace_error;
use libimagrt::setup::generate_runtime_setup;
use libimagrt::runtime::Runtime;

fn main() {
    let rt = generate_runtime_setup("imag-ref",
                                    &version!()[..],
                                    "Reference files outside of the store",
                                    build_ui);
    rt.cli()
        .subcommand_name()
        .map(|name| {
            debug!("Call: {}", name);
            match name {
                "add"    => add(&rt),
                "remove" => remove(&rt),
                "list"   => list(&rt),
                _        => {
                    debug!("Unknown command"); // More error handling
                },
            };
        });
}

fn add(rt: &Runtime) {
    let cmd  = rt.cli().subcommand_matches("add").unwrap();
    let path = cmd.value_of("path").map(PathBuf::from).unwrap(); // saved by clap

    let flags = RefFlags::default()
        .with_content_hashing(cmd.is_present("track-content"))
        .with_permission_tracking(cmd.is_present("track-permissions"));

    match Ref::create(rt.store(), path, flags) {
        Ok(r) => {
            debug!("Reference created: {:?}", r);
            info!("Ok");
        },
        Err(e) => {
            trace_error(&e);
            warn!("Failed to create reference");
        },
    }
}

fn remove(rt: &Runtime) {
    use libimaginteraction::ask::ask_bool;

    let cmd  = rt.cli().subcommand_matches("remove").unwrap();
    let hash = cmd.value_of("hash").map(String::from).unwrap(); // saved by clap
    let yes  = cmd.is_present("yes");

    if yes || ask_bool(&format!("Delete Ref with hash '{}'", hash)[..], None) {
        match Ref::delete_by_hash(rt.store(), hash) {
            Err(e) => trace_error(&e),
            Ok(_) => info!("Ok"),
        }
    } else {
        info!("Aborted");
    }

}

fn list(rt: &Runtime) {
    use std::process::exit;

    use libimagentrylist::lister::Lister;
    use libimagref::lister::RefLister;

    let cmd                      = rt.cli().subcommand_matches("list").unwrap();
    let do_check_dead            = cmd.is_present("check-dead");
    let do_check_changed         = cmd.is_present("check-changed");
    let do_check_changed_content = cmd.is_present("check-changed-content");
    let do_check_changed_permiss = cmd.is_present("check-changed-permissions");

    let iter = match rt.store().retrieve_for_module("ref") {
        Ok(iter) => iter.filter_map(|id| {
            match Ref::get(rt.store(), id) {
                Ok(r) => Some(r),
                Err(e) => {
                    trace_error(&e);
                    None
                },
            }
        }),
        Err(e) => {
            trace_error(&e);
            exit(1);
        }
    };

    RefLister::new()
        .check_dead(do_check_dead)
        .check_changed(do_check_changed)
        .check_changed_content(do_check_changed_content)
        .check_changed_permiss(do_check_changed_permiss)
        .list(iter.map(|e| e.into()));
}

<|endoftext|>


<commit_before><commit_msg>Add ARM decode for block data transfer instructions<commit_after><|endoftext|>


<commit_before><commit_msg>Add test of current behavior (infer free region within closure body) previously not in test suite.<commit_after>// This is a collection of examples where a function's formal
// parameter has an explicit lifetime and a closure within that
// function returns that formal parameter. The closure's return type,
// to be correctly inferred, needs to include the lifetime introduced
// by the function.
//
// This works today, which precludes changing things so that closures
// follow the same lifetime-elision rules used elsehwere. See
// rust-lang/rust#56537

// compile-pass
// We are already testing NLL explicitly via the revision system below.
// ignore-compare-mode-nll

// revisions: ll nll migrate
//[ll] compile-flags:-Zborrowck=ast
//[nll] compile-flags:-Zborrowck=mir -Z two-phase-borrows
//[migrate] compile-flags:-Zborrowck=migrate -Z two-phase-borrows

fn willy_no_annot<'w>(p: &'w str, q: &str) -> &'w str {
    let free_dumb = |_x| { p }; // no type annotation at all
    let hello = format!("Hello");
    free_dumb(&hello)
}

fn willy_ret_type_annot<'w>(p: &'w str, q: &str) -> &'w str {
    let free_dumb = |_x| -> &str { p }; // type annotation on the return type
    let hello = format!("Hello");
    free_dumb(&hello)
}

fn willy_ret_region_annot<'w>(p: &'w str, q: &str) -> &'w str {
    let free_dumb = |_x| -> &'w str { p }; // type+region annotation on return type
    let hello = format!("Hello");
    free_dumb(&hello)
}

fn willy_arg_type_ret_type_annot<'w>(p: &'w str, q: &str) -> &'w str {
    let free_dumb = |_x: &str| -> &str { p }; // type annotation on arg and return types
    let hello = format!("Hello");
    free_dumb(&hello)
}

fn willy_arg_type_ret_region_annot<'w>(p: &'w str, q: &str) -> &'w str {
    let free_dumb = |_x: &str| -> &'w str { p }; // fully annotated
    let hello = format!("Hello");
    free_dumb(&hello)
}

fn main() {
    let world = format!("World");
    let w1: &str = {
        let hello = format!("He11o");
        willy_no_annot(&world, &hello)
    };
    let w2: &str = {
        let hello = format!("He22o");
        willy_ret_type_annot(&world, &hello)
    };
    let w3: &str = {
        let hello = format!("He33o");
        willy_ret_region_annot(&world, &hello)
    };
    let w4: &str = {
        let hello = format!("He44o");
        willy_arg_type_ret_type_annot(&world, &hello)
    };
    let w5: &str = {
        let hello = format!("He55o");
        willy_arg_type_ret_region_annot(&world, &hello)
    };
    assert_eq!((w1, w2, w3, w4, w5),
               ("World","World","World","World","World"));
}
<|endoftext|>


<commit_before>#![feature(old_io)]

extern crate xml;

use xml::attribute::Attribute;
use xml::common::XmlVersion;
use xml::name::Name;
use xml::namespace::Namespace;
use xml::writer::EventWriter;
use xml::writer::events::XmlEvent;

fn add_block<'a>(events: &mut Vec<XmlEvent<'a>>, namespace: &'a Namespace, tag_name: &'static str, chars: &'a str) {
    // <(tag_name)>
    events.push(XmlEvent::StartElement {
        name: Name::local(tag_name),
        attributes: vec![],
        namespace: namespace,
    });

    events.push(XmlEvent::Characters(chars));

    // </(tag_name)>
    events.push(XmlEvent::EndElement {
        name: Name::local(tag_name),
    });
}

trait Write {
    fn write<W: Writer>(&self, writer: W) -> Result<(), ()>;
}

trait ToXml<'a> {
    // todo: get rid of namespace parameter
    fn to_xml(&'a self, namespace: &'a Namespace) -> Vec<XmlEvent>;
}

/// RSS version 2.0
pub struct Rss<'a>(pub Vec<Channel<'a>>);

impl<'a> ToXml<'a> for Rss<'a> {
    fn to_xml(&'a self, namespace: &'a Namespace) -> Vec<XmlEvent> {
        let mut events = vec![];

        // <?xml version="1.0" encoding="UTF-8"?>
        events.push(XmlEvent::StartDocument{
            version: XmlVersion::Version10,
            encoding: Some("UTF-8"),
            standalone: None,
        });

        // <rss version="2.0">
        events.push(XmlEvent::StartElement {
            name: Name::local("rss"),
            attributes: vec![
                Attribute::new(Name::local("version"), "2.0"),
            ],
            namespace: namespace,
        });

        let &Rss(ref channels) = self;
        for channel in channels {
            for event in channel.to_xml(namespace) {
                events.push(event);
            }
        }

        // </rss>
        events.push(XmlEvent::EndElement {
            name: Name::local("rss"),
        });

        events
    }
}

impl<'a> Write for Rss<'a> {
    fn write<W: Writer>(&self, writer: W) -> Result<(), ()> {
        let mut event_writer = EventWriter::new(writer);

        let namespace = Namespace::empty();
        let events = self.to_xml(&namespace);

        for event in events {
            event_writer.write(event);
        };

        Ok(())
    }
}

pub struct Channel<'a> {
    pub title: String,
    pub link: String,
    pub description: String,
    pub items: Vec<Item<'a>>,
}

impl<'a> ToXml<'a> for Channel<'a> {
    fn to_xml(&'a self, namespace: &'a Namespace) -> Vec<XmlEvent> {
        let mut events = vec![];

        // <channel>
        events.push(XmlEvent::StartElement {
            name: Name::local("channel"),
            attributes: vec![],
            namespace: namespace,
        });

        add_block(&mut events, namespace, "title", &self.title);
        add_block(&mut events, namespace, "link", &self.link);
        add_block(&mut events, namespace, "description", &self.description);

        for item in &self.items {
            for event in item.to_xml(namespace) {
                events.push(event);
            }
        }

        // </channel>
        events.push(XmlEvent::EndElement {
            name: Name::local("channel"),
        });

        events
    }
}

pub struct Item<'a> {
    pub title: Option<&'a str>,
    pub link: Option<&'a str>,
    pub description: Option<&'a str>,
}

impl<'a> ToXml<'a> for Item<'a> {
    fn to_xml(&'a self, namespace: &'a Namespace) -> Vec<XmlEvent> {
        let mut events = vec![];

        // <channel>
        events.push(XmlEvent::StartElement {
            name: Name::local("item"),
            attributes: vec![],
            namespace: namespace,
        });

        match self.title {
            Some(s) => add_block(&mut events, namespace, "title", s),
            None => (),
        }

        match self.link {
            Some(s) => add_block(&mut events, namespace, "link", s),
            None => (),
        }

        match self.description {
            Some(s) => add_block(&mut events, namespace, "description", s),
            None => (),
        }

        // </channel>
        events.push(XmlEvent::EndElement {
            name: Name::local("item"),
        });

        events
    }
}

#[test]
fn test_consruct() {
    use std::old_io;

    let item = Item {
        title: Some("My first post!"),
        link: Some("http://myblog.com/post1"),
        description: Some("This is my first post"),
    };

    let channel = Channel {
        title: String::from_str("My Blog"),
        link: String::from_str("http://myblog.com"),
        description: String::from_str("Where I write stuff"),
        items: vec![item],
    };

    let rss = Rss(vec![channel]);
    rss.write(old_io::stdout());
}
<commit_msg>Remove ownership requirement for channel strings<commit_after>#![feature(old_io)]

extern crate xml;

use xml::attribute::Attribute;
use xml::common::XmlVersion;
use xml::name::Name;
use xml::namespace::Namespace;
use xml::writer::EventWriter;
use xml::writer::events::XmlEvent;

fn add_block<'a>(events: &mut Vec<XmlEvent<'a>>, namespace: &'a Namespace, tag_name: &'static str, chars: &'a str) {
    // <(tag_name)>
    events.push(XmlEvent::StartElement {
        name: Name::local(tag_name),
        attributes: vec![],
        namespace: namespace,
    });

    events.push(XmlEvent::Characters(chars));

    // </(tag_name)>
    events.push(XmlEvent::EndElement {
        name: Name::local(tag_name),
    });
}

trait Write {
    fn write<W: Writer>(&self, writer: W) -> Result<(), ()>;
}

trait ToXml<'a> {
    // todo: get rid of namespace parameter
    fn to_xml(&'a self, namespace: &'a Namespace) -> Vec<XmlEvent>;
}

/// RSS version 2.0
pub struct Rss<'a>(pub Vec<Channel<'a>>);

impl<'a> ToXml<'a> for Rss<'a> {
    fn to_xml(&'a self, namespace: &'a Namespace) -> Vec<XmlEvent> {
        let mut events = vec![];

        // <?xml version="1.0" encoding="UTF-8"?>
        events.push(XmlEvent::StartDocument{
            version: XmlVersion::Version10,
            encoding: Some("UTF-8"),
            standalone: None,
        });

        // <rss version="2.0">
        events.push(XmlEvent::StartElement {
            name: Name::local("rss"),
            attributes: vec![
                Attribute::new(Name::local("version"), "2.0"),
            ],
            namespace: namespace,
        });

        let &Rss(ref channels) = self;
        for channel in channels {
            for event in channel.to_xml(namespace) {
                events.push(event);
            }
        }

        // </rss>
        events.push(XmlEvent::EndElement {
            name: Name::local("rss"),
        });

        events
    }
}

impl<'a> Write for Rss<'a> {
    fn write<W: Writer>(&self, writer: W) -> Result<(), ()> {
        let mut event_writer = EventWriter::new(writer);

        let namespace = Namespace::empty();
        let events = self.to_xml(&namespace);

        for event in events {
            event_writer.write(event);
        };

        Ok(())
    }
}

pub struct Channel<'a> {
    pub title: &'a str,
    pub link: &'a str,
    pub description: &'a str,
    pub items: Vec<Item<'a>>,
}

impl<'a> ToXml<'a> for Channel<'a> {
    fn to_xml(&'a self, namespace: &'a Namespace) -> Vec<XmlEvent> {
        let mut events = vec![];

        // <channel>
        events.push(XmlEvent::StartElement {
            name: Name::local("channel"),
            attributes: vec![],
            namespace: namespace,
        });

        add_block(&mut events, namespace, "title", self.title);
        add_block(&mut events, namespace, "link", self.link);
        add_block(&mut events, namespace, "description", self.description);

        for item in &self.items {
            for event in item.to_xml(namespace) {
                events.push(event);
            }
        }

        // </channel>
        events.push(XmlEvent::EndElement {
            name: Name::local("channel"),
        });

        events
    }
}

pub struct Item<'a> {
    pub title: Option<&'a str>,
    pub link: Option<&'a str>,
    pub description: Option<&'a str>,
}

impl<'a> ToXml<'a> for Item<'a> {
    fn to_xml(&'a self, namespace: &'a Namespace) -> Vec<XmlEvent> {
        let mut events = vec![];

        // <channel>
        events.push(XmlEvent::StartElement {
            name: Name::local("item"),
            attributes: vec![],
            namespace: namespace,
        });

        match self.title {
            Some(s) => add_block(&mut events, namespace, "title", s),
            None => (),
        }

        match self.link {
            Some(s) => add_block(&mut events, namespace, "link", s),
            None => (),
        }

        match self.description {
            Some(s) => add_block(&mut events, namespace, "description", s),
            None => (),
        }

        // </channel>
        events.push(XmlEvent::EndElement {
            name: Name::local("item"),
        });

        events
    }
}

#[test]
fn test_consruct() {
    use std::old_io;

    let item = Item {
        title: Some("My first post!"),
        link: Some("http://myblog.com/post1"),
        description: Some("This is my first post"),
    };

    let channel = Channel {
        title: "My Blog",
        link: "http://myblog.com",
        description: "Where I write stuff",
        items: vec![item],
    };

    let rss = Rss(vec![channel]);
    rss.write(old_io::stdout());
}
<|endoftext|>


<commit_before><commit_msg>Improved documentation<commit_after><|endoftext|>


<commit_before><commit_msg>Added set_row() to Builder.<commit_after><|endoftext|>


<commit_before><commit_msg>Add Scanner.next_token method.<commit_after><|endoftext|>


<commit_before><commit_msg>fixed target flag bug<commit_after><|endoftext|>


<commit_before>//! This crate provides native rust implementations of
//! Image encoders and decoders and basic image manipulation
//! functions.

#![crate_name = "image"]
#![crate_type = "rlib"]

#![warn(missing_docs)]
#![warn(unused_qualifications)]
#![warn(unused_typecasts)]
#![warn(unused_features)] // reduce errors due to using test&rand features
#![deny(missing_copy_implementations)]
#![feature(core)]
#![feature(collections)]
#![feature(io)]
#![feature(std_misc)]
#![feature(rustc_private)]
#![feature(step_by)]
#![feature(convert)]
#![cfg_attr(test, feature(test))]

extern crate byteorder;
extern crate flate;
extern crate num;
#[cfg(test)] extern crate test;

pub use color::ColorType as ColorType;
pub use traits::Primitive;

pub use color::ColorType:: {
    Gray,
    RGB,
    Palette,
    GrayA,
    RGBA,
};
pub use color:: {
    Luma,
    LumaA,
    Rgb,
    Rgba,
};

pub use buffer::Pixel;

pub use image::ImageDecoder as ImageDecoder;
pub use image::ImageError as ImageError;
pub use image::ImageResult as ImageResult;
pub use image::ImageFormat as ImageFormat;
pub use imageops::FilterType as FilterType;

pub use imageops:: {
    Triangle,
    Nearest,
    CatmullRom,
    Gaussian,
    Lanczos3
};

pub use image::ImageFormat:: {
    PNG,
    JPEG,
    GIF,
    WEBP,
    PPM
};

// Image Types
pub use image::SubImage as SubImage;
pub use dynimage::DynamicImage as DynamicImage;
pub use buffer::{
    ImageBuffer,
    RgbImage,
    RgbaImage,
    GrayImage,
    GrayAlphaImage
};

// Traits
pub use image::GenericImage as GenericImage;

// Iterators
pub use image::Pixels as Pixels;
pub use image::MutPixels as MutPixels;

/// Opening and loading images
pub use dynimage:: {
    open,
    load,
    load_from_memory,
    load_from_memory_with_format,
    save_buffer,
};
pub use dynimage::DynamicImage:: {
    ImageRgb8,
    ImageRgba8,
    ImageLuma8,
    ImageLumaA8,
};

pub use animation:: {
    Frame, Frames
};

// Math utils
pub mod math;

// Image Processing Functions
pub mod imageops;

// Image Codecs
#[cfg(feature = "webp")]
pub mod webp;
#[cfg(feature = "ppm")]
pub mod ppm;
#[cfg(feature = "png")]
pub mod png;
#[cfg(feature = "jpeg")]
pub mod jpeg;
#[cfg(feature = "gif")]
pub mod gif;
#[cfg(feature = "tiff")]
pub mod tiff;
#[cfg(feature = "tga")]
pub mod tga;

mod image;
mod utils;
mod dynimage;
mod color;
mod buffer;
mod traits;
mod animation;
<commit_msg>Add #![feature(slice_patterns)]<commit_after>//! This crate provides native rust implementations of
//! Image encoders and decoders and basic image manipulation
//! functions.

#![crate_name = "image"]
#![crate_type = "rlib"]

#![warn(missing_docs)]
#![warn(unused_qualifications)]
#![warn(unused_typecasts)]
#![warn(unused_features)] // reduce errors due to using test&rand features
#![deny(missing_copy_implementations)]
#![feature(core)]
#![feature(collections)]
#![feature(io)]
#![feature(std_misc)]
#![feature(rustc_private)]
#![feature(step_by)]
#![feature(convert)]
#![feature(slice_patterns)]
#![cfg_attr(test, feature(test))]

extern crate byteorder;
extern crate flate;
extern crate num;
#[cfg(test)] extern crate test;

pub use color::ColorType as ColorType;
pub use traits::Primitive;

pub use color::ColorType:: {
    Gray,
    RGB,
    Palette,
    GrayA,
    RGBA,
};
pub use color:: {
    Luma,
    LumaA,
    Rgb,
    Rgba,
};

pub use buffer::Pixel;

pub use image::ImageDecoder as ImageDecoder;
pub use image::ImageError as ImageError;
pub use image::ImageResult as ImageResult;
pub use image::ImageFormat as ImageFormat;
pub use imageops::FilterType as FilterType;

pub use imageops:: {
    Triangle,
    Nearest,
    CatmullRom,
    Gaussian,
    Lanczos3
};

pub use image::ImageFormat:: {
    PNG,
    JPEG,
    GIF,
    WEBP,
    PPM
};

// Image Types
pub use image::SubImage as SubImage;
pub use dynimage::DynamicImage as DynamicImage;
pub use buffer::{
    ImageBuffer,
    RgbImage,
    RgbaImage,
    GrayImage,
    GrayAlphaImage
};

// Traits
pub use image::GenericImage as GenericImage;

// Iterators
pub use image::Pixels as Pixels;
pub use image::MutPixels as MutPixels;

/// Opening and loading images
pub use dynimage:: {
    open,
    load,
    load_from_memory,
    load_from_memory_with_format,
    save_buffer,
};
pub use dynimage::DynamicImage:: {
    ImageRgb8,
    ImageRgba8,
    ImageLuma8,
    ImageLumaA8,
};

pub use animation:: {
    Frame, Frames
};

// Math utils
pub mod math;

// Image Processing Functions
pub mod imageops;

// Image Codecs
#[cfg(feature = "webp")]
pub mod webp;
#[cfg(feature = "ppm")]
pub mod ppm;
#[cfg(feature = "png")]
pub mod png;
#[cfg(feature = "jpeg")]
pub mod jpeg;
#[cfg(feature = "gif")]
pub mod gif;
#[cfg(feature = "tiff")]
pub mod tiff;
#[cfg(feature = "tga")]
pub mod tga;

mod image;
mod utils;
mod dynimage;
mod color;
mod buffer;
mod traits;
mod animation;
<|endoftext|>


<commit_before><commit_msg>add_history_persist<commit_after><|endoftext|>


<commit_before><commit_msg>Added a polygon line test<commit_after><|endoftext|>


<commit_before><commit_msg>`macro_rules` feature gate removed<commit_after><|endoftext|>


<commit_before><commit_msg>Implement add_dbrecord_to_leaf<commit_after><|endoftext|>


<commit_before><commit_msg>Cherrypick Becnhmark fixup<commit_after><|endoftext|>


<commit_before><commit_msg>Dropped unused feature flags<commit_after><|endoftext|>


<commit_before><commit_msg>Zero extend rhs for shl, not sign extend<commit_after><|endoftext|>


<commit_before><commit_msg>Add a test for #2329<commit_after>// Comments with characters which must be represented by multibyte.

// フー
use foo;
// バー
use bar;

impl MyStruct {
    // コメント
    fn f1() {} // こんにちは
    fn f2() {} // ありがとう
               // コメント
}

trait MyTrait {
    // コメント
    fn f1() {} // こんにちは
    fn f2() {} // ありがとう
               // コメント
}

fn main() {
    // コメント
    let x = 1; // Ｘ
    println!(
        "x = {}", // xの値
        x,        // Ｘ
    );
    // コメント
}
<|endoftext|>


<commit_before><commit_msg>Implement ContactStore::all_contacts()<commit_after><|endoftext|>


<commit_before><commit_msg>progress checkin; naive and optimized work, iterator almost works<commit_after>// http://rosettacode.org/wiki/Bernoulli_numbers

#![feature(test)]

extern crate num;
extern crate test;

use num::bigint::{BigInt, ToBigInt};
use num::rational::{BigRational};
use std::env;
use std::ops::{Mul, Sub};
use std::process;

struct Context {
    n: usize,
    bigone_const: BigInt,
    bigrat_const: BigRational,
    a: Vec<BigRational>,
    index: i32    // For iterator
}

impl Context {
    pub fn new(up_to: usize) -> Context {
        let bigone = 1.to_bigint().unwrap();
        let bigrat = BigRational::new(bigone.clone(), bigone.clone());
        let a_vec: Vec<BigRational> = vec![bigrat.clone(); up_to + 1];
        Context {
            n: up_to,
            bigone_const: bigone,
            bigrat_const: bigrat,
            a: a_vec,
            index: -1
        }
    }
}

fn help() {
    println!("Usage: bernoulli_numbers <up_to>");
}

fn main() {
    let args: Vec<String> = env::args().collect();
    let mut up_to: usize = 60;

    match args.len() {
        1 => {},
        2 => {
            up_to = args[1].parse::<usize>().unwrap();
        },
        _ => {
            help();
            process::exit(0);
        }
    }

    let mut context = Context::new(up_to);

    let mut res: Vec<(usize, BigRational)> = vec![];
    let mut widths: Vec<u32> = vec![];

    //for n in 0..up_to + 1 {
    //    let b = bernoulli(n, &mut context);
    //println!("got {} for {}", b, n);
    let mut res = context.take(up_to + 1).collect::<Vec<_>>();
    //let x = context.take(up_to + 1).count();
    /*for r in context.take(up_to + 1) {
        res.push(r.clone());
        widths.push(r.1.numer().to_string().len());
    }*/

    //let width = widths.iter().max().unwrap();
    let width = 10;
    for r in res.iter().filter(|r| r.0 % 2 == 0) {
        println!("B({:>2}) = {:>2$} / {denom}", r.0, r.1.numer(), width, denom = r.1.denom());
    }
}

// Implementation with no reused calculations.
fn bernoulli_naive(n: usize, c: &mut Context) -> BigRational {

    for m in 0..n + 1 {
        c.a[m] = BigRational::new(c.bigone_const.clone(), (m + 1).to_bigint().unwrap());
        for j in (1..m + 1).rev() {
            c.a[j - 1] = (c.a[j - 1].clone().sub(c.a[j].clone())).mul(
                BigRational::new(j.to_bigint().unwrap(), c.bigone_const.clone())
            );
        }
    }
    c.a[0].reduced()
}

// Implementation with reused calculations (does not require sequential calls).
// This is ~100x faster.
fn bernoulli(n: usize, c: &mut Context) -> BigRational {
    for i in 1..n + 1 {
        if c.a[i].eq(&c.bigrat_const) {
            c.a[i] = BigRational::new(c.bigone_const.clone(), (i + 1).to_bigint().unwrap());
            for j in (1..i + 1).rev() {
                c.a[j - 1] = (c.a[j - 1].clone().sub(c.a[j].clone())).mul(
                    BigRational::new(j.to_bigint().unwrap(), c.bigone_const.clone())
                );
            }
        }
    }
    c.a[0].reduced()
}

// Iterator implementation.
impl Iterator for Context {
    type Item = (usize, BigRational);

    fn next(&mut self) -> Option<(usize, BigRational)> {
        self.index += 1;
        Some((self.index as usize, self.bigrat_const.clone()))
    }
}

#[cfg(test)]
mod tests {
    use super::{Context, bernoulli, bernoulli_naive};
    use num::rational::{BigRational};
    use std::str::FromStr;
    use test::Bencher;

    #[test]
    fn test_bernoulli_naive() {
        let mut context = Context::new(60);
    }

    #[test]
    fn test_bernoulli_naive() {
        let mut context = Context::new(60);
        assert_eq!(bernoulli_naive(60, &mut context), BigRational::new(
                FromStr::from_str("-1215233140483755572040304994079820246041491").unwrap(),
                FromStr::from_str("56786730").unwrap()
            )
        );
    }

    #[test]
    fn test_bernoulli() {
        let mut context = Context::new(60);
        assert_eq!(bernoulli(60, &mut context), BigRational::new(
                FromStr::from_str("-1215233140483755572040304994079820246041491").unwrap(),
                FromStr::from_str("56786730").unwrap()
            )
        );
    }

    #[bench]
    fn bench_bernoulli_naive(b: &mut Bencher) {
        let mut context = Context::new(30);
        b.iter(|| {
            let mut res: Vec<(usize, BigRational)> = vec![];
            for n in 0..30 + 1 {
                let b = bernoulli_naive(n, &mut context);
                res.push((n, b.clone()));
            }
        });
    }

    #[bench]
    fn bench_bernoulli(b: &mut Bencher) {
        let mut context = Context::new(30);
        b.iter(|| {
            let mut res: Vec<(usize, BigRational)> = vec![];
            for n in 0..30 + 1 {
                let b = bernoulli(n, &mut context);
                res.push((n, b.clone()));
            }
        });
    }
}
<|endoftext|>


<commit_before><commit_msg>Add simple drag and drop example<commit_after>//! Simple drag and drop example
//!
//! Ported over from example code:
//! https://developer.gnome.org/gtkmm-tutorial/stable/sec-dnd-example.html.en

extern crate gdk;
extern crate gtk;

use gtk::prelude::*;

fn main() {
    if gtk::init().is_err() {
        println!("Failed to initialize GTK.");
        return;
    }

    // Configure button as drag source for text
    let button = gtk::Button::new_with_label("Drag here");
    let targets = vec![gtk::TargetEntry::new("STRING", gtk::TARGET_SAME_APP, 0),
                       gtk::TargetEntry::new("text/plain", gtk::TARGET_SAME_APP, 0)];
    button.drag_source_set(gdk::MODIFIER_MASK, &targets, gdk::ACTION_COPY);
    button.connect_drag_data_get(|_, _, s, _, _| {
                                     let data = "I'm data!";
                                     s.set_text(data, data.len() as i32);
                                 });

    // Configure label as drag destination to receive text
    let label = gtk::Label::new("Drop here");
    label.drag_dest_set(gtk::DEST_DEFAULT_ALL, &targets, gdk::ACTION_COPY);
    label.connect_drag_data_received(|w, _, _, _, s, _, _| { w.set_text(&s.get_text().unwrap()); });

    // Stack the button and label horizontally
    let hbox = gtk::Box::new(gtk::Orientation::Horizontal, 0);
    hbox.pack_start(&button, true, true, 0);
    hbox.pack_start(&label, true, true, 0);

    // Finish populating the window and display everything
    let window = gtk::Window::new(gtk::WindowType::Toplevel);
    window.set_title("Simple Drag and Drop Example");
    window.add(&hbox);
    window.show_all();

    // GTK & main window boilerplate
    window.connect_delete_event(|_, _| {
                                    gtk::main_quit();
                                    Inhibit(false)
                                });
    gtk::main();
}
<|endoftext|>


<commit_before><commit_msg>Add a model for how conditional trait impls might be used to implement the Fn-FnMut-FnOnce hierarchy.<commit_after>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// A model for how the `Fn` traits could work. You can implement at
// most one of `Go`, `GoMut`, or `GoOnce`, and then the others follow
// automatically.

use std::rc::Rc;
use std::cell::Cell;

trait Go {
    fn go(&self, arg: int);
}

fn go<G:Go>(this: &G, arg: int) {
    this.go(arg)
}

trait GoMut {
    fn go_mut(&mut self, arg: int);
}

fn go_mut<G:GoMut>(this: &mut G, arg: int) {
    this.go_mut(arg)
}

trait GoOnce {
    fn go_once(self, arg: int);
}

fn go_once<G:GoOnce>(this: G, arg: int) {
    this.go_once(arg)
}

impl<G> GoMut for G
    where G : Go
{
    fn go_mut(&mut self, arg: int) {
        go(&*self, arg)
    }
}

impl<G> GoOnce for G
    where G : GoMut
{
    fn go_once(mut self, arg: int) {
        go_mut(&mut self, arg)
    }
}

///////////////////////////////////////////////////////////////////////////

struct SomeGoableThing {
    counter: Rc<Cell<int>>
}

impl Go for SomeGoableThing {
    fn go(&self, arg: int) {
        self.counter.set(self.counter.get() + arg);
    }
}

///////////////////////////////////////////////////////////////////////////

struct SomeGoOnceableThing {
    counter: Rc<Cell<int>>
}

impl GoOnce for SomeGoOnceableThing {
    fn go_once(self, arg: int) {
        self.counter.set(self.counter.get() + arg);
    }
}

///////////////////////////////////////////////////////////////////////////

fn main() {
    let counter = Rc::new(Cell::new(0));
    let mut x = SomeGoableThing { counter: counter.clone() };

    go(&x, 10);
    assert_eq!(counter.get(), 10);

    go_mut(&mut x, 100);
    assert_eq!(counter.get(), 110);

    go_once(x, 1_000);
    assert_eq!(counter.get(), 1_110);

    let x = SomeGoOnceableThing { counter: counter.clone() };

    go_once(x, 10_000);
    assert_eq!(counter.get(), 11_110);
}
<|endoftext|>


<commit_before><commit_msg>Add intra links for unstable features doc<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.

use core::prelude::*;

use core::os;
use core::run;
use core::str;

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

    let mut env = os::env();

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

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

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

pub struct Result {status: int, out: ~str, err: ~str}

pub fn run(lib_path: &str,
           prog: &str,
           args: &[~str],
           env: ~[(~str, ~str)],
           input: Option<~str>) -> Result {

    let env = env + target_env(lib_path, prog);
    let mut proc = run::Process::new(prog, args, run::ProcessOptions {
        env: Some(env.slice(0, env.len())),
        dir: None,
        in_fd: None,
        out_fd: None,
        err_fd: None
    });

    for input.iter().advance |input| {
        proc.input().write_str(*input);
    }
    let output = proc.finish_with_output();

    Result {
        status: output.status,
        out: str::from_bytes(output.output),
        err: str::from_bytes(output.error)
    }
}
<commit_msg>Converted vec::map to member.<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.

use core::prelude::*;

use core::os;
use core::run;
use core::str;

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

    let mut env = os::env();

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

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

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

pub struct Result {status: int, out: ~str, err: ~str}

pub fn run(lib_path: &str,
           prog: &str,
           args: &[~str],
           env: ~[(~str, ~str)],
           input: Option<~str>) -> Result {

    let env = env + target_env(lib_path, prog);
    let mut proc = run::Process::new(prog, args, run::ProcessOptions {
        env: Some(env.slice(0, env.len())),
        dir: None,
        in_fd: None,
        out_fd: None,
        err_fd: None
    });

    for input.iter().advance |input| {
        proc.input().write_str(*input);
    }
    let output = proc.finish_with_output();

    Result {
        status: output.status,
        out: str::from_bytes(output.output),
        err: str::from_bytes(output.error)
    }
}
<|endoftext|>


<commit_before><commit_msg>In the Vulkan renderer use a vector of vertex buffers and an index for each thread<commit_after><|endoftext|>


<commit_before><commit_msg>o'clock<commit_after><|endoftext|>


<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.

/*!

typeck.rs, an introduction

The type checker is responsible for:

1. Determining the type of each expression
2. Resolving methods and traits
3. Guaranteeing that most type rules are met ("most?", you say, "why most?"
   Well, dear reader, read on)

The main entry point is `check_crate()`.  Type checking operates in
several major phases:

1. The collect phase first passes over all items and determines their
   type, without examining their "innards".

2. Variance inference then runs to compute the variance of each parameter

3. Coherence checks for overlapping or orphaned impls

4. Finally, the check phase then checks function bodies and so forth.
   Within the check phase, we check each function body one at a time
   (bodies of function expressions are checked as part of the
   containing function).  Inference is used to supply types wherever
   they are unknown. The actual checking of a function itself has
   several phases (check, regionck, writeback), as discussed in the
   documentation for the `check` module.

The type checker is defined into various submodules which are documented
independently:

- astconv: converts the AST representation of types
  into the `ty` representation

- collect: computes the types of each top-level item and enters them into
  the `cx.tcache` table for later use

- coherence: enforces coherence rules, builds some tables

- variance: variance inference

- check: walks over function bodies and type checks them, inferring types for
  local variables, type parameters, etc as necessary.

- infer: finds the types to use for each type variable such that
  all subtyping and assignment constraints are met.  In essence, the check
  module specifies the constraints, and the infer module solves them.

# Note

This API is completely unstable and subject to change.

*/
// Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
#![cfg_attr(stage0, feature(custom_attribute))]
#![crate_name = "rustc_typeck"]
#![unstable(feature = "rustc_private")]
#![staged_api]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
      html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
      html_root_url = "http://doc.rust-lang.org/nightly/")]

#![allow(non_camel_case_types)]

#![feature(box_patterns)]
#![feature(box_syntax)]
#![feature(collections, collections_drain)]
#![feature(core)]
#![feature(quote)]
#![feature(rustc_diagnostic_macros)]
#![feature(rustc_private)]
#![feature(staged_api)]

#[macro_use] extern crate log;
#[macro_use] extern crate syntax;

extern crate arena;
extern crate fmt_macros;
extern crate rustc;

pub use rustc::lint;
pub use rustc::metadata;
pub use rustc::middle;
pub use rustc::session;
pub use rustc::util;

use middle::def;
use middle::infer;
use middle::subst;
use middle::ty::{self, Ty};
use session::config;
use util::common::time;
use util::ppaux::Repr;
use util::ppaux;

use syntax::codemap::Span;
use syntax::print::pprust::*;
use syntax::{ast, ast_map, abi};
use syntax::ast_util::local_def;

use std::cell::RefCell;

// NB: This module needs to be declared first so diagnostics are
// registered before they are used.
pub mod diagnostics;

mod check;
mod rscope;
mod astconv;
mod collect;
mod constrained_type_params;
mod coherence;
mod variance;

pub struct TypeAndSubsts<'tcx> {
    pub substs: subst::Substs<'tcx>,
    pub ty: Ty<'tcx>,
}

pub struct CrateCtxt<'a, 'tcx: 'a> {
    // A mapping from method call sites to traits that have that method.
    trait_map: ty::TraitMap,
    /// A vector of every trait accessible in the whole crate
    /// (i.e. including those from subcrates). This is used only for
    /// error reporting, and so is lazily initialised and generally
    /// shouldn't taint the common path (hence the RefCell).
    all_traits: RefCell<Option<check::method::AllTraitsVec>>,
    tcx: &'a ty::ctxt<'tcx>,
}

// Functions that write types into the node type table
fn write_ty_to_tcx<'tcx>(tcx: &ty::ctxt<'tcx>, node_id: ast::NodeId, ty: Ty<'tcx>) {
    debug!("write_ty_to_tcx({}, {})", node_id, ppaux::ty_to_string(tcx, ty));
    assert!(!ty::type_needs_infer(ty));
    tcx.node_type_insert(node_id, ty);
}

fn write_substs_to_tcx<'tcx>(tcx: &ty::ctxt<'tcx>,
                                 node_id: ast::NodeId,
                                 item_substs: ty::ItemSubsts<'tcx>) {
    if !item_substs.is_noop() {
        debug!("write_substs_to_tcx({}, {})",
               node_id,
               item_substs.repr(tcx));

        assert!(item_substs.substs.types.all(|t| !ty::type_needs_infer(*t)));

        tcx.item_substs.borrow_mut().insert(node_id, item_substs);
    }
}

fn lookup_full_def(tcx: &ty::ctxt, sp: Span, id: ast::NodeId) -> def::Def {
    match tcx.def_map.borrow().get(&id) {
        Some(x) => x.full_def(),
        None => {
            span_fatal!(tcx.sess, sp, E0242, "internal error looking up a definition")
        }
    }
}

fn require_same_types<'a, 'tcx, M>(tcx: &ty::ctxt<'tcx>,
                                   maybe_infcx: Option<&infer::InferCtxt<'a, 'tcx>>,
                                   t1_is_expected: bool,
                                   span: Span,
                                   t1: Ty<'tcx>,
                                   t2: Ty<'tcx>,
                                   msg: M)
                                   -> bool where
    M: FnOnce() -> String,
{
    let result = match maybe_infcx {
        None => {
            let infcx = infer::new_infer_ctxt(tcx);
            infer::mk_eqty(&infcx, t1_is_expected, infer::Misc(span), t1, t2)
        }
        Some(infcx) => {
            infer::mk_eqty(infcx, t1_is_expected, infer::Misc(span), t1, t2)
        }
    };

    match result {
        Ok(_) => true,
        Err(ref terr) => {
            span_err!(tcx.sess, span, E0211,
                              "{}: {}",
                                      msg(),
                                      ty::type_err_to_str(tcx,
                                                          terr));
            ty::note_and_explain_type_err(tcx, terr, span);
            false
        }
    }
}

fn check_main_fn_ty(ccx: &CrateCtxt,
                    main_id: ast::NodeId,
                    main_span: Span) {
    let tcx = ccx.tcx;
    let main_t = ty::node_id_to_type(tcx, main_id);
    match main_t.sty {
        ty::ty_bare_fn(..) => {
            match tcx.map.find(main_id) {
                Some(ast_map::NodeItem(it)) => {
                    match it.node {
                        ast::ItemFn(_, _, _, ref ps, _)
                        if ps.is_parameterized() => {
                            span_err!(ccx.tcx.sess, main_span, E0131,
                                      "main function is not allowed to have type parameters");
                            return;
                        }
                        _ => ()
                    }
                }
                _ => ()
            }
            let se_ty = ty::mk_bare_fn(tcx, Some(local_def(main_id)), tcx.mk_bare_fn(ty::BareFnTy {
                unsafety: ast::Unsafety::Normal,
                abi: abi::Rust,
                sig: ty::Binder(ty::FnSig {
                    inputs: Vec::new(),
                    output: ty::FnConverging(ty::mk_nil(tcx)),
                    variadic: false
                })
            }));

            require_same_types(tcx, None, false, main_span, main_t, se_ty,
                || {
                    format!("main function expects type: `{}`",
                            ppaux::ty_to_string(ccx.tcx, se_ty))
                });
        }
        _ => {
            tcx.sess.span_bug(main_span,
                              &format!("main has a non-function type: found \
                                       `{}`",
                                      ppaux::ty_to_string(tcx,
                                                       main_t)));
        }
    }
}

fn check_start_fn_ty(ccx: &CrateCtxt,
                     start_id: ast::NodeId,
                     start_span: Span) {
    let tcx = ccx.tcx;
    let start_t = ty::node_id_to_type(tcx, start_id);
    match start_t.sty {
        ty::ty_bare_fn(..) => {
            match tcx.map.find(start_id) {
                Some(ast_map::NodeItem(it)) => {
                    match it.node {
                        ast::ItemFn(_,_,_,ref ps,_)
                        if ps.is_parameterized() => {
                            span_err!(tcx.sess, start_span, E0132,
                                      "start function is not allowed to have type parameters");
                            return;
                        }
                        _ => ()
                    }
                }
                _ => ()
            }

            let se_ty = ty::mk_bare_fn(tcx, Some(local_def(start_id)), tcx.mk_bare_fn(ty::BareFnTy {
                unsafety: ast::Unsafety::Normal,
                abi: abi::Rust,
                sig: ty::Binder(ty::FnSig {
                    inputs: vec!(
                        tcx.types.isize,
                        ty::mk_imm_ptr(tcx, ty::mk_imm_ptr(tcx, tcx.types.u8))
                    ),
                    output: ty::FnConverging(tcx.types.isize),
                    variadic: false,
                }),
            }));

            require_same_types(tcx, None, false, start_span, start_t, se_ty,
                || {
                    format!("start function expects type: `{}`",
                            ppaux::ty_to_string(ccx.tcx, se_ty))
                });

        }
        _ => {
            tcx.sess.span_bug(start_span,
                              &format!("start has a non-function type: found \
                                       `{}`",
                                      ppaux::ty_to_string(tcx, start_t)));
        }
    }
}

fn check_for_entry_fn(ccx: &CrateCtxt) {
    let tcx = ccx.tcx;
    match *tcx.sess.entry_fn.borrow() {
        Some((id, sp)) => match tcx.sess.entry_type.get() {
            Some(config::EntryMain) => check_main_fn_ty(ccx, id, sp),
            Some(config::EntryStart) => check_start_fn_ty(ccx, id, sp),
            Some(config::EntryNone) => {}
            None => tcx.sess.bug("entry function without a type")
        },
        None => {}
    }
}

pub fn check_crate(tcx: &ty::ctxt, trait_map: ty::TraitMap) {
    let time_passes = tcx.sess.time_passes();
    let ccx = CrateCtxt {
        trait_map: trait_map,
        all_traits: RefCell::new(None),
        tcx: tcx
    };

    time(time_passes, "type collecting", (), |_|
         collect::collect_item_types(tcx));

    // this ensures that later parts of type checking can assume that items
    // have valid types and not error
    tcx.sess.abort_if_errors();

    time(time_passes, "variance inference", (), |_|
         variance::infer_variance(tcx));

    time(time_passes, "coherence checking", (), |_|
        coherence::check_coherence(&ccx));

    time(time_passes, "type checking", (), |_|
        check::check_item_types(&ccx));

    check_for_entry_fn(&ccx);
    tcx.sess.abort_if_errors();
}

#[cfg(stage0)]
__build_diagnostic_array! { DIAGNOSTICS }
#[cfg(not(stage0))]
__build_diagnostic_array! { librustc_typeck, DIAGNOSTICS }
<commit_msg>Auto merge of #25390 - eddyb:typeck-pub, r=nrc<commit_after>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

/*!

typeck.rs, an introduction

The type checker is responsible for:

1. Determining the type of each expression
2. Resolving methods and traits
3. Guaranteeing that most type rules are met ("most?", you say, "why most?"
   Well, dear reader, read on)

The main entry point is `check_crate()`.  Type checking operates in
several major phases:

1. The collect phase first passes over all items and determines their
   type, without examining their "innards".

2. Variance inference then runs to compute the variance of each parameter

3. Coherence checks for overlapping or orphaned impls

4. Finally, the check phase then checks function bodies and so forth.
   Within the check phase, we check each function body one at a time
   (bodies of function expressions are checked as part of the
   containing function).  Inference is used to supply types wherever
   they are unknown. The actual checking of a function itself has
   several phases (check, regionck, writeback), as discussed in the
   documentation for the `check` module.

The type checker is defined into various submodules which are documented
independently:

- astconv: converts the AST representation of types
  into the `ty` representation

- collect: computes the types of each top-level item and enters them into
  the `cx.tcache` table for later use

- coherence: enforces coherence rules, builds some tables

- variance: variance inference

- check: walks over function bodies and type checks them, inferring types for
  local variables, type parameters, etc as necessary.

- infer: finds the types to use for each type variable such that
  all subtyping and assignment constraints are met.  In essence, the check
  module specifies the constraints, and the infer module solves them.

# Note

This API is completely unstable and subject to change.

*/
// Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
#![cfg_attr(stage0, feature(custom_attribute))]
#![crate_name = "rustc_typeck"]
#![unstable(feature = "rustc_private")]
#![staged_api]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
      html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
      html_root_url = "http://doc.rust-lang.org/nightly/")]

#![allow(non_camel_case_types)]

#![feature(box_patterns)]
#![feature(box_syntax)]
#![feature(collections, collections_drain)]
#![feature(core)]
#![feature(quote)]
#![feature(rustc_diagnostic_macros)]
#![feature(rustc_private)]
#![feature(staged_api)]

#[macro_use] extern crate log;
#[macro_use] extern crate syntax;

extern crate arena;
extern crate fmt_macros;
extern crate rustc;

pub use rustc::lint;
pub use rustc::metadata;
pub use rustc::middle;
pub use rustc::session;
pub use rustc::util;

use middle::def;
use middle::infer;
use middle::subst;
use middle::ty::{self, Ty};
use session::config;
use util::common::time;
use util::ppaux::Repr;
use util::ppaux;

use syntax::codemap::Span;
use syntax::print::pprust::*;
use syntax::{ast, ast_map, abi};
use syntax::ast_util::local_def;

use std::cell::RefCell;

// NB: This module needs to be declared first so diagnostics are
// registered before they are used.
pub mod diagnostics;

pub mod check;
mod rscope;
mod astconv;
pub mod collect;
mod constrained_type_params;
pub mod coherence;
pub mod variance;

pub struct TypeAndSubsts<'tcx> {
    pub substs: subst::Substs<'tcx>,
    pub ty: Ty<'tcx>,
}

pub struct CrateCtxt<'a, 'tcx: 'a> {
    // A mapping from method call sites to traits that have that method.
    pub trait_map: ty::TraitMap,
    /// A vector of every trait accessible in the whole crate
    /// (i.e. including those from subcrates). This is used only for
    /// error reporting, and so is lazily initialised and generally
    /// shouldn't taint the common path (hence the RefCell).
    pub all_traits: RefCell<Option<check::method::AllTraitsVec>>,
    pub tcx: &'a ty::ctxt<'tcx>,
}

// Functions that write types into the node type table
fn write_ty_to_tcx<'tcx>(tcx: &ty::ctxt<'tcx>, node_id: ast::NodeId, ty: Ty<'tcx>) {
    debug!("write_ty_to_tcx({}, {})", node_id, ppaux::ty_to_string(tcx, ty));
    assert!(!ty::type_needs_infer(ty));
    tcx.node_type_insert(node_id, ty);
}

fn write_substs_to_tcx<'tcx>(tcx: &ty::ctxt<'tcx>,
                                 node_id: ast::NodeId,
                                 item_substs: ty::ItemSubsts<'tcx>) {
    if !item_substs.is_noop() {
        debug!("write_substs_to_tcx({}, {})",
               node_id,
               item_substs.repr(tcx));

        assert!(item_substs.substs.types.all(|t| !ty::type_needs_infer(*t)));

        tcx.item_substs.borrow_mut().insert(node_id, item_substs);
    }
}

fn lookup_full_def(tcx: &ty::ctxt, sp: Span, id: ast::NodeId) -> def::Def {
    match tcx.def_map.borrow().get(&id) {
        Some(x) => x.full_def(),
        None => {
            span_fatal!(tcx.sess, sp, E0242, "internal error looking up a definition")
        }
    }
}

fn require_same_types<'a, 'tcx, M>(tcx: &ty::ctxt<'tcx>,
                                   maybe_infcx: Option<&infer::InferCtxt<'a, 'tcx>>,
                                   t1_is_expected: bool,
                                   span: Span,
                                   t1: Ty<'tcx>,
                                   t2: Ty<'tcx>,
                                   msg: M)
                                   -> bool where
    M: FnOnce() -> String,
{
    let result = match maybe_infcx {
        None => {
            let infcx = infer::new_infer_ctxt(tcx);
            infer::mk_eqty(&infcx, t1_is_expected, infer::Misc(span), t1, t2)
        }
        Some(infcx) => {
            infer::mk_eqty(infcx, t1_is_expected, infer::Misc(span), t1, t2)
        }
    };

    match result {
        Ok(_) => true,
        Err(ref terr) => {
            span_err!(tcx.sess, span, E0211,
                              "{}: {}",
                                      msg(),
                                      ty::type_err_to_str(tcx,
                                                          terr));
            ty::note_and_explain_type_err(tcx, terr, span);
            false
        }
    }
}

fn check_main_fn_ty(ccx: &CrateCtxt,
                    main_id: ast::NodeId,
                    main_span: Span) {
    let tcx = ccx.tcx;
    let main_t = ty::node_id_to_type(tcx, main_id);
    match main_t.sty {
        ty::ty_bare_fn(..) => {
            match tcx.map.find(main_id) {
                Some(ast_map::NodeItem(it)) => {
                    match it.node {
                        ast::ItemFn(_, _, _, ref ps, _)
                        if ps.is_parameterized() => {
                            span_err!(ccx.tcx.sess, main_span, E0131,
                                      "main function is not allowed to have type parameters");
                            return;
                        }
                        _ => ()
                    }
                }
                _ => ()
            }
            let se_ty = ty::mk_bare_fn(tcx, Some(local_def(main_id)), tcx.mk_bare_fn(ty::BareFnTy {
                unsafety: ast::Unsafety::Normal,
                abi: abi::Rust,
                sig: ty::Binder(ty::FnSig {
                    inputs: Vec::new(),
                    output: ty::FnConverging(ty::mk_nil(tcx)),
                    variadic: false
                })
            }));

            require_same_types(tcx, None, false, main_span, main_t, se_ty,
                || {
                    format!("main function expects type: `{}`",
                            ppaux::ty_to_string(ccx.tcx, se_ty))
                });
        }
        _ => {
            tcx.sess.span_bug(main_span,
                              &format!("main has a non-function type: found \
                                       `{}`",
                                      ppaux::ty_to_string(tcx,
                                                       main_t)));
        }
    }
}

fn check_start_fn_ty(ccx: &CrateCtxt,
                     start_id: ast::NodeId,
                     start_span: Span) {
    let tcx = ccx.tcx;
    let start_t = ty::node_id_to_type(tcx, start_id);
    match start_t.sty {
        ty::ty_bare_fn(..) => {
            match tcx.map.find(start_id) {
                Some(ast_map::NodeItem(it)) => {
                    match it.node {
                        ast::ItemFn(_,_,_,ref ps,_)
                        if ps.is_parameterized() => {
                            span_err!(tcx.sess, start_span, E0132,
                                      "start function is not allowed to have type parameters");
                            return;
                        }
                        _ => ()
                    }
                }
                _ => ()
            }

            let se_ty = ty::mk_bare_fn(tcx, Some(local_def(start_id)), tcx.mk_bare_fn(ty::BareFnTy {
                unsafety: ast::Unsafety::Normal,
                abi: abi::Rust,
                sig: ty::Binder(ty::FnSig {
                    inputs: vec!(
                        tcx.types.isize,
                        ty::mk_imm_ptr(tcx, ty::mk_imm_ptr(tcx, tcx.types.u8))
                    ),
                    output: ty::FnConverging(tcx.types.isize),
                    variadic: false,
                }),
            }));

            require_same_types(tcx, None, false, start_span, start_t, se_ty,
                || {
                    format!("start function expects type: `{}`",
                            ppaux::ty_to_string(ccx.tcx, se_ty))
                });

        }
        _ => {
            tcx.sess.span_bug(start_span,
                              &format!("start has a non-function type: found \
                                       `{}`",
                                      ppaux::ty_to_string(tcx, start_t)));
        }
    }
}

fn check_for_entry_fn(ccx: &CrateCtxt) {
    let tcx = ccx.tcx;
    match *tcx.sess.entry_fn.borrow() {
        Some((id, sp)) => match tcx.sess.entry_type.get() {
            Some(config::EntryMain) => check_main_fn_ty(ccx, id, sp),
            Some(config::EntryStart) => check_start_fn_ty(ccx, id, sp),
            Some(config::EntryNone) => {}
            None => tcx.sess.bug("entry function without a type")
        },
        None => {}
    }
}

pub fn check_crate(tcx: &ty::ctxt, trait_map: ty::TraitMap) {
    let time_passes = tcx.sess.time_passes();
    let ccx = CrateCtxt {
        trait_map: trait_map,
        all_traits: RefCell::new(None),
        tcx: tcx
    };

    time(time_passes, "type collecting", (), |_|
         collect::collect_item_types(tcx));

    // this ensures that later parts of type checking can assume that items
    // have valid types and not error
    tcx.sess.abort_if_errors();

    time(time_passes, "variance inference", (), |_|
         variance::infer_variance(tcx));

    time(time_passes, "coherence checking", (), |_|
        coherence::check_coherence(&ccx));

    time(time_passes, "type checking", (), |_|
        check::check_item_types(&ccx));

    check_for_entry_fn(&ccx);
    tcx.sess.abort_if_errors();
}

#[cfg(stage0)]
__build_diagnostic_array! { DIAGNOSTICS }
#[cfg(not(stage0))]
__build_diagnostic_array! { librustc_typeck, DIAGNOSTICS }
<|endoftext|>