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

//! Pulls type information out of the AST and attaches it to the document

use astsrv;
use doc::ItemUtils;
use doc;
use extract::to_str;
use extract;
use fold::Fold;
use fold;
use pass::Pass;

use syntax::ast;
use syntax::print::pprust;
use syntax::ast_map;

pub fn mk_pass() -> Pass {
    Pass {
        name: ~"tystr",
        f: run
    }
}

pub fn run(
    srv: astsrv::Srv,
    doc: doc::Doc
) -> doc::Doc {
    let fold = Fold {
        ctxt: srv.clone(),
        fold_fn: fold_fn,
        fold_const: fold_const,
        fold_enum: fold_enum,
        fold_trait: fold_trait,
        fold_impl: fold_impl,
        fold_type: fold_type,
        fold_struct: fold_struct,
        .. fold::default_any_fold(srv)
    };
    (fold.fold_doc)(&fold, doc)
}

fn fold_fn(
    fold: &fold::Fold<astsrv::Srv>,
    doc: doc::FnDoc
) -> doc::FnDoc {

    let srv = fold.ctxt.clone();

    doc::SimpleItemDoc {
        sig: get_fn_sig(srv, doc.id()),
        .. doc
    }
}

fn get_fn_sig(srv: astsrv::Srv, fn_id: doc::AstId) -> Option<~str> {
    do astsrv::exec(srv) |ctxt| {
        match *ctxt.ast_map.get(&fn_id) {
            ast_map::node_item(@ast::item {
                ident: ident,
                node: ast::item_fn(ref decl, purity, _, ref tys, _), _
            }, _) |
            ast_map::node_foreign_item(@ast::foreign_item {
                ident: ident,
                node: ast::foreign_item_fn(ref decl, purity, ref tys), _
            }, _, _, _) => {
                Some(pprust::fun_to_str(decl, purity, ident, None, tys,
                                        extract::interner()))
            }
            _ => fail!(~"get_fn_sig: fn_id not bound to a fn item")
        }
    }
}

fn fold_const(
    fold: &fold::Fold<astsrv::Srv>,
    doc: doc::ConstDoc
) -> doc::ConstDoc {
    let srv = fold.ctxt.clone();

    doc::SimpleItemDoc {
        sig: Some({
            let doc = copy doc;
            do astsrv::exec(srv) |ctxt| {
                match *ctxt.ast_map.get(&doc.id()) {
                    ast_map::node_item(@ast::item {
                        node: ast::item_const(ty, _), _
                    }, _) => {
                        pprust::ty_to_str(ty, extract::interner())
                    }
                    _ => fail!(~"fold_const: id not bound to a const item")
                }
            }}),
        .. doc
    }
}

fn fold_enum(
    fold: &fold::Fold<astsrv::Srv>,
    doc: doc::EnumDoc
) -> doc::EnumDoc {
    let doc_id = doc.id();
    let srv = fold.ctxt.clone();

    doc::EnumDoc {
        variants: do vec::map(doc.variants) |variant| {
            let sig = {
                let variant = copy *variant;
                do astsrv::exec(srv.clone()) |ctxt| {
                    match *ctxt.ast_map.get(&doc_id) {
                        ast_map::node_item(@ast::item {
                            node: ast::item_enum(ref enum_definition, _), _
                        }, _) => {
                            let ast_variant =
                                do vec::find(enum_definition.variants) |v| {
                                to_str(v.node.name) == variant.name
                            }.get();

                            pprust::variant_to_str(
                                ast_variant, extract::interner())
                        }
                        _ => fail!(~"enum variant not bound to an enum item")
                    }
                }
            };

            doc::VariantDoc {
                sig: Some(sig),
                .. copy *variant
            }
        },
        .. doc
    }
}

fn fold_trait(
    fold: &fold::Fold<astsrv::Srv>,
    doc: doc::TraitDoc
) -> doc::TraitDoc {
    doc::TraitDoc {
        methods: merge_methods(fold.ctxt.clone(), doc.id(), copy doc.methods),
        .. doc
    }
}

fn merge_methods(
    srv: astsrv::Srv,
    item_id: doc::AstId,
    docs: ~[doc::MethodDoc]
) -> ~[doc::MethodDoc] {
    do vec::map(docs) |doc| {
        doc::MethodDoc {
            sig: get_method_sig(srv.clone(), item_id, copy doc.name),
            .. copy *doc
        }
    }
}

fn get_method_sig(
    srv: astsrv::Srv,
    item_id: doc::AstId,
    method_name: ~str
) -> Option<~str> {
    do astsrv::exec(srv) |ctxt| {
        match *ctxt.ast_map.get(&item_id) {
            ast_map::node_item(@ast::item {
                node: ast::item_trait(_, _, ref methods), _
            }, _) => {
                match vec::find(*methods, |method| {
                    match copy *method {
                        ast::required(ty_m) => to_str(ty_m.ident) == method_name,
                        ast::provided(m) => to_str(m.ident) == method_name,
                    }
                }) {
                    Some(method) => {
                        match method {
                            ast::required(ty_m) => {
                                Some(pprust::fun_to_str(
                                    &ty_m.decl,
                                    ty_m.purity,
                                    ty_m.ident,
                                    Some(ty_m.self_ty.node),
                                    &ty_m.generics,
                                    extract::interner()
                                ))
                            }
                            ast::provided(m) => {
                                Some(pprust::fun_to_str(
                                    &m.decl,
                                    m.purity,
                                    m.ident,
                                    Some(m.self_ty.node),
                                    &m.generics,
                                    extract::interner()
                                ))
                            }
                        }
                    }
                    _ => fail!(~"method not found")
                }
            }
            ast_map::node_item(@ast::item {
                node: ast::item_impl(_, _, _, ref methods), _
            }, _) => {
                match vec::find(*methods, |method| {
                    to_str(method.ident) == method_name
                }) {
                    Some(method) => {
                        Some(pprust::fun_to_str(
                            &method.decl,
                            method.purity,
                            method.ident,
                            Some(method.self_ty.node),
                            &method.generics,
                            extract::interner()
                        ))
                    }
                    None => fail!(~"method not found")
                }
            }
            _ => fail!(~"get_method_sig: item ID not bound to trait or impl")
        }
    }
}

fn fold_impl(
    fold: &fold::Fold<astsrv::Srv>,
    doc: doc::ImplDoc
) -> doc::ImplDoc {

    let srv = fold.ctxt.clone();

    let (bounds, trait_types, self_ty) = {
        let doc = copy doc;
        do astsrv::exec(srv) |ctxt| {
            match *ctxt.ast_map.get(&doc.id()) {
                ast_map::node_item(@ast::item {
                    node: ast::item_impl(ref generics, opt_trait_type, self_ty, _), _
                }, _) => {
                    let bounds = pprust::generics_to_str(generics, extract::interner());
                    let bounds = if bounds.is_empty() { None } else { Some(bounds) };
                    let trait_types = opt_trait_type.map_default(~[], |p| {
                        ~[pprust::path_to_str(p.path, extract::interner())]
                    });
                    (bounds,
                     trait_types,
                     Some(pprust::ty_to_str(
                         self_ty, extract::interner())))
                }
                _ => fail!(~"expected impl")
            }
        }
    };

    doc::ImplDoc {
        bounds_str: bounds,
        trait_types: trait_types,
        self_ty: self_ty,
        methods: merge_methods(fold.ctxt.clone(), doc.id(), copy doc.methods),
        .. doc
    }
}

fn fold_type(
    fold: &fold::Fold<astsrv::Srv>,
    doc: doc::TyDoc
) -> doc::TyDoc {

    let srv = fold.ctxt.clone();

    doc::SimpleItemDoc {
        sig: {
            let doc = copy doc;
            do astsrv::exec(srv) |ctxt| {
                match *ctxt.ast_map.get(&doc.id()) {
                    ast_map::node_item(@ast::item {
                        ident: ident,
                        node: ast::item_ty(ty, ref params), _
                    }, _) => {
                        Some(fmt!(
                            "type %s%s = %s",
                            to_str(ident),
                            pprust::generics_to_str(params,
                                                    extract::interner()),
                            pprust::ty_to_str(ty,
                                              extract::interner())
                        ))
                    }
                    _ => fail!(~"expected type")
                }
            }
        },
        .. doc
    }
}

fn fold_struct(
    fold: &fold::Fold<astsrv::Srv>,
    doc: doc::StructDoc
) -> doc::StructDoc {
    let srv = fold.ctxt.clone();

    doc::StructDoc {
        sig: {
            let doc = copy doc;
            do astsrv::exec(srv) |ctxt| {
                match *ctxt.ast_map.get(&doc.id()) {
                    ast_map::node_item(item, _) => {
                        let item = strip_struct_extra_stuff(item);
                        Some(pprust::item_to_str(item,
                                                 extract::interner()))
                    }
                    _ => fail!(~"not an item")
                }
            }
        },
        .. doc
    }
}

/// Removes various things from the struct item definition that
/// shouldn't be displayed in the struct signature. Probably there
/// should be a simple pprust::struct_to_str function that does
/// what I actually want
fn strip_struct_extra_stuff(item: @ast::item) -> @ast::item {
    let node = match copy item.node {
        ast::item_struct(def, tys) => ast::item_struct(def, tys),
        _ => fail!(~"not a struct")
    };

    @ast::item {
        attrs: ~[], // Remove the attributes
        node: node,
        .. copy *item
    }
}

#[cfg(test)]
mod test {
    use astsrv;
    use doc;
    use extract;
    use tystr_pass::run;

    fn mk_doc(source: ~str) -> doc::Doc {
        do astsrv::from_str(copy source) |srv| {
            let doc = extract::from_srv(srv.clone(), ~"");
            run(srv.clone(), doc)
        }
    }

    #[test]
    fn should_add_fn_sig() {
        let doc = mk_doc(~"fn a<T>() -> int { }");
        assert!(doc.cratemod().fns()[0].sig == Some(~"fn a<T>() -> int"));
    }

    #[test]
    fn should_add_foreign_fn_sig() {
        let doc = mk_doc(~"extern mod a { fn a<T>() -> int; }");
        assert!(doc.cratemod().nmods()[0].fns[0].sig ==
                Some(~"fn a<T>() -> int"));
    }

    #[test]
    fn should_add_const_types() {
        let doc = mk_doc(~"static a: bool = true;");
        assert!(doc.cratemod().consts()[0].sig == Some(~"bool"));
    }

    #[test]
    fn should_add_variant_sigs() {
        let doc = mk_doc(~"enum a { b(int) }");
        assert!(doc.cratemod().enums()[0].variants[0].sig ==
                Some(~"b(int)"));
    }

    #[test]
    fn should_add_trait_method_sigs() {
        let doc = mk_doc(~"trait i { fn a<T>(&mut self) -> int; }");
        assert!(doc.cratemod().traits()[0].methods[0].sig
                == Some(~"fn a<T>(&mut self) -> int"));
    }

    #[test]
    fn should_add_impl_bounds() {
        let doc = mk_doc(~"impl<T, U: Copy, V: Copy + Clone> Option<T, U, V> { }");
        assert!(doc.cratemod().impls()[0].bounds_str == Some(~"<T, U: Copy, V: Copy + Clone>"));
    }

    #[test]
    fn should_add_impl_trait_types() {
        let doc = mk_doc(~"impl j for int { fn a<T>() { } }");
        assert!(doc.cratemod().impls()[0].trait_types[0] == ~"j");
    }

    #[test]
    fn should_not_add_impl_trait_types_if_none() {
        let doc = mk_doc(~"impl int { fn a() { } }");
        assert!(vec::len(doc.cratemod().impls()[0].trait_types) == 0);
    }

    #[test]
    fn should_add_impl_self_ty() {
        let doc = mk_doc(~"impl int { fn a() { } }");
        assert!(doc.cratemod().impls()[0].self_ty == Some(~"int"));
    }

    #[test]
    fn should_add_impl_method_sigs() {
        let doc = mk_doc(~"impl int { fn a<T>(&self) -> int { fail!() } }");
        assert!(doc.cratemod().impls()[0].methods[0].sig
                == Some(~"fn a<T>(&self) -> int"));
    }

    #[test]
    fn should_add_type_signatures() {
        let doc = mk_doc(~"type t<T> = int;");
        assert!(doc.cratemod().types()[0].sig == Some(~"type t<T> = int"));
    }

    #[test]
    fn should_add_struct_defs() {
        let doc = mk_doc(~"struct S { field: () }");
        assert!((&doc.cratemod().structs()[0].sig).get().contains(
            "struct S {"));
    }

    #[test]
    fn should_not_serialize_struct_drop_blocks() {
        // All we care about are the fields
        let doc = mk_doc(~"struct S { field: (), drop { } }");
        assert!(!(&doc.cratemod().structs()[0].sig).get().contains("drop"));
    }

    #[test]
    fn should_not_serialize_struct_attrs() {
        // All we care about are the fields
        let doc = mk_doc(~"#[wut] struct S { field: () }");
        assert!(!(&doc.cratemod().structs()[0].sig).get().contains("wut"));
    }
}
<commit_msg>rustdoc: Remove a now invalid test<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.

//! Pulls type information out of the AST and attaches it to the document

use astsrv;
use doc::ItemUtils;
use doc;
use extract::to_str;
use extract;
use fold::Fold;
use fold;
use pass::Pass;

use syntax::ast;
use syntax::print::pprust;
use syntax::ast_map;

pub fn mk_pass() -> Pass {
    Pass {
        name: ~"tystr",
        f: run
    }
}

pub fn run(
    srv: astsrv::Srv,
    doc: doc::Doc
) -> doc::Doc {
    let fold = Fold {
        ctxt: srv.clone(),
        fold_fn: fold_fn,
        fold_const: fold_const,
        fold_enum: fold_enum,
        fold_trait: fold_trait,
        fold_impl: fold_impl,
        fold_type: fold_type,
        fold_struct: fold_struct,
        .. fold::default_any_fold(srv)
    };
    (fold.fold_doc)(&fold, doc)
}

fn fold_fn(
    fold: &fold::Fold<astsrv::Srv>,
    doc: doc::FnDoc
) -> doc::FnDoc {

    let srv = fold.ctxt.clone();

    doc::SimpleItemDoc {
        sig: get_fn_sig(srv, doc.id()),
        .. doc
    }
}

fn get_fn_sig(srv: astsrv::Srv, fn_id: doc::AstId) -> Option<~str> {
    do astsrv::exec(srv) |ctxt| {
        match *ctxt.ast_map.get(&fn_id) {
            ast_map::node_item(@ast::item {
                ident: ident,
                node: ast::item_fn(ref decl, purity, _, ref tys, _), _
            }, _) |
            ast_map::node_foreign_item(@ast::foreign_item {
                ident: ident,
                node: ast::foreign_item_fn(ref decl, purity, ref tys), _
            }, _, _, _) => {
                Some(pprust::fun_to_str(decl, purity, ident, None, tys,
                                        extract::interner()))
            }
            _ => fail!(~"get_fn_sig: fn_id not bound to a fn item")
        }
    }
}

fn fold_const(
    fold: &fold::Fold<astsrv::Srv>,
    doc: doc::ConstDoc
) -> doc::ConstDoc {
    let srv = fold.ctxt.clone();

    doc::SimpleItemDoc {
        sig: Some({
            let doc = copy doc;
            do astsrv::exec(srv) |ctxt| {
                match *ctxt.ast_map.get(&doc.id()) {
                    ast_map::node_item(@ast::item {
                        node: ast::item_const(ty, _), _
                    }, _) => {
                        pprust::ty_to_str(ty, extract::interner())
                    }
                    _ => fail!(~"fold_const: id not bound to a const item")
                }
            }}),
        .. doc
    }
}

fn fold_enum(
    fold: &fold::Fold<astsrv::Srv>,
    doc: doc::EnumDoc
) -> doc::EnumDoc {
    let doc_id = doc.id();
    let srv = fold.ctxt.clone();

    doc::EnumDoc {
        variants: do vec::map(doc.variants) |variant| {
            let sig = {
                let variant = copy *variant;
                do astsrv::exec(srv.clone()) |ctxt| {
                    match *ctxt.ast_map.get(&doc_id) {
                        ast_map::node_item(@ast::item {
                            node: ast::item_enum(ref enum_definition, _), _
                        }, _) => {
                            let ast_variant =
                                do vec::find(enum_definition.variants) |v| {
                                to_str(v.node.name) == variant.name
                            }.get();

                            pprust::variant_to_str(
                                ast_variant, extract::interner())
                        }
                        _ => fail!(~"enum variant not bound to an enum item")
                    }
                }
            };

            doc::VariantDoc {
                sig: Some(sig),
                .. copy *variant
            }
        },
        .. doc
    }
}

fn fold_trait(
    fold: &fold::Fold<astsrv::Srv>,
    doc: doc::TraitDoc
) -> doc::TraitDoc {
    doc::TraitDoc {
        methods: merge_methods(fold.ctxt.clone(), doc.id(), copy doc.methods),
        .. doc
    }
}

fn merge_methods(
    srv: astsrv::Srv,
    item_id: doc::AstId,
    docs: ~[doc::MethodDoc]
) -> ~[doc::MethodDoc] {
    do vec::map(docs) |doc| {
        doc::MethodDoc {
            sig: get_method_sig(srv.clone(), item_id, copy doc.name),
            .. copy *doc
        }
    }
}

fn get_method_sig(
    srv: astsrv::Srv,
    item_id: doc::AstId,
    method_name: ~str
) -> Option<~str> {
    do astsrv::exec(srv) |ctxt| {
        match *ctxt.ast_map.get(&item_id) {
            ast_map::node_item(@ast::item {
                node: ast::item_trait(_, _, ref methods), _
            }, _) => {
                match vec::find(*methods, |method| {
                    match copy *method {
                        ast::required(ty_m) => to_str(ty_m.ident) == method_name,
                        ast::provided(m) => to_str(m.ident) == method_name,
                    }
                }) {
                    Some(method) => {
                        match method {
                            ast::required(ty_m) => {
                                Some(pprust::fun_to_str(
                                    &ty_m.decl,
                                    ty_m.purity,
                                    ty_m.ident,
                                    Some(ty_m.self_ty.node),
                                    &ty_m.generics,
                                    extract::interner()
                                ))
                            }
                            ast::provided(m) => {
                                Some(pprust::fun_to_str(
                                    &m.decl,
                                    m.purity,
                                    m.ident,
                                    Some(m.self_ty.node),
                                    &m.generics,
                                    extract::interner()
                                ))
                            }
                        }
                    }
                    _ => fail!(~"method not found")
                }
            }
            ast_map::node_item(@ast::item {
                node: ast::item_impl(_, _, _, ref methods), _
            }, _) => {
                match vec::find(*methods, |method| {
                    to_str(method.ident) == method_name
                }) {
                    Some(method) => {
                        Some(pprust::fun_to_str(
                            &method.decl,
                            method.purity,
                            method.ident,
                            Some(method.self_ty.node),
                            &method.generics,
                            extract::interner()
                        ))
                    }
                    None => fail!(~"method not found")
                }
            }
            _ => fail!(~"get_method_sig: item ID not bound to trait or impl")
        }
    }
}

fn fold_impl(
    fold: &fold::Fold<astsrv::Srv>,
    doc: doc::ImplDoc
) -> doc::ImplDoc {

    let srv = fold.ctxt.clone();

    let (bounds, trait_types, self_ty) = {
        let doc = copy doc;
        do astsrv::exec(srv) |ctxt| {
            match *ctxt.ast_map.get(&doc.id()) {
                ast_map::node_item(@ast::item {
                    node: ast::item_impl(ref generics, opt_trait_type, self_ty, _), _
                }, _) => {
                    let bounds = pprust::generics_to_str(generics, extract::interner());
                    let bounds = if bounds.is_empty() { None } else { Some(bounds) };
                    let trait_types = opt_trait_type.map_default(~[], |p| {
                        ~[pprust::path_to_str(p.path, extract::interner())]
                    });
                    (bounds,
                     trait_types,
                     Some(pprust::ty_to_str(
                         self_ty, extract::interner())))
                }
                _ => fail!(~"expected impl")
            }
        }
    };

    doc::ImplDoc {
        bounds_str: bounds,
        trait_types: trait_types,
        self_ty: self_ty,
        methods: merge_methods(fold.ctxt.clone(), doc.id(), copy doc.methods),
        .. doc
    }
}

fn fold_type(
    fold: &fold::Fold<astsrv::Srv>,
    doc: doc::TyDoc
) -> doc::TyDoc {

    let srv = fold.ctxt.clone();

    doc::SimpleItemDoc {
        sig: {
            let doc = copy doc;
            do astsrv::exec(srv) |ctxt| {
                match *ctxt.ast_map.get(&doc.id()) {
                    ast_map::node_item(@ast::item {
                        ident: ident,
                        node: ast::item_ty(ty, ref params), _
                    }, _) => {
                        Some(fmt!(
                            "type %s%s = %s",
                            to_str(ident),
                            pprust::generics_to_str(params,
                                                    extract::interner()),
                            pprust::ty_to_str(ty,
                                              extract::interner())
                        ))
                    }
                    _ => fail!(~"expected type")
                }
            }
        },
        .. doc
    }
}

fn fold_struct(
    fold: &fold::Fold<astsrv::Srv>,
    doc: doc::StructDoc
) -> doc::StructDoc {
    let srv = fold.ctxt.clone();

    doc::StructDoc {
        sig: {
            let doc = copy doc;
            do astsrv::exec(srv) |ctxt| {
                match *ctxt.ast_map.get(&doc.id()) {
                    ast_map::node_item(item, _) => {
                        let item = strip_struct_extra_stuff(item);
                        Some(pprust::item_to_str(item,
                                                 extract::interner()))
                    }
                    _ => fail!(~"not an item")
                }
            }
        },
        .. doc
    }
}

/// Removes various things from the struct item definition that
/// shouldn't be displayed in the struct signature. Probably there
/// should be a simple pprust::struct_to_str function that does
/// what I actually want
fn strip_struct_extra_stuff(item: @ast::item) -> @ast::item {
    let node = match copy item.node {
        ast::item_struct(def, tys) => ast::item_struct(def, tys),
        _ => fail!(~"not a struct")
    };

    @ast::item {
        attrs: ~[], // Remove the attributes
        node: node,
        .. copy *item
    }
}

#[cfg(test)]
mod test {
    use astsrv;
    use doc;
    use extract;
    use tystr_pass::run;

    fn mk_doc(source: ~str) -> doc::Doc {
        do astsrv::from_str(copy source) |srv| {
            let doc = extract::from_srv(srv.clone(), ~"");
            run(srv.clone(), doc)
        }
    }

    #[test]
    fn should_add_fn_sig() {
        let doc = mk_doc(~"fn a<T>() -> int { }");
        assert!(doc.cratemod().fns()[0].sig == Some(~"fn a<T>() -> int"));
    }

    #[test]
    fn should_add_foreign_fn_sig() {
        let doc = mk_doc(~"extern mod a { fn a<T>() -> int; }");
        assert!(doc.cratemod().nmods()[0].fns[0].sig ==
                Some(~"fn a<T>() -> int"));
    }

    #[test]
    fn should_add_const_types() {
        let doc = mk_doc(~"static a: bool = true;");
        assert!(doc.cratemod().consts()[0].sig == Some(~"bool"));
    }

    #[test]
    fn should_add_variant_sigs() {
        let doc = mk_doc(~"enum a { b(int) }");
        assert!(doc.cratemod().enums()[0].variants[0].sig ==
                Some(~"b(int)"));
    }

    #[test]
    fn should_add_trait_method_sigs() {
        let doc = mk_doc(~"trait i { fn a<T>(&mut self) -> int; }");
        assert!(doc.cratemod().traits()[0].methods[0].sig
                == Some(~"fn a<T>(&mut self) -> int"));
    }

    #[test]
    fn should_add_impl_bounds() {
        let doc = mk_doc(~"impl<T, U: Copy, V: Copy + Clone> Option<T, U, V> { }");
        assert!(doc.cratemod().impls()[0].bounds_str == Some(~"<T, U: Copy, V: Copy + Clone>"));
    }

    #[test]
    fn should_add_impl_trait_types() {
        let doc = mk_doc(~"impl j for int { fn a<T>() { } }");
        assert!(doc.cratemod().impls()[0].trait_types[0] == ~"j");
    }

    #[test]
    fn should_not_add_impl_trait_types_if_none() {
        let doc = mk_doc(~"impl int { fn a() { } }");
        assert!(vec::len(doc.cratemod().impls()[0].trait_types) == 0);
    }

    #[test]
    fn should_add_impl_self_ty() {
        let doc = mk_doc(~"impl int { fn a() { } }");
        assert!(doc.cratemod().impls()[0].self_ty == Some(~"int"));
    }

    #[test]
    fn should_add_impl_method_sigs() {
        let doc = mk_doc(~"impl int { fn a<T>(&self) -> int { fail!() } }");
        assert!(doc.cratemod().impls()[0].methods[0].sig
                == Some(~"fn a<T>(&self) -> int"));
    }

    #[test]
    fn should_add_type_signatures() {
        let doc = mk_doc(~"type t<T> = int;");
        assert!(doc.cratemod().types()[0].sig == Some(~"type t<T> = int"));
    }

    #[test]
    fn should_add_struct_defs() {
        let doc = mk_doc(~"struct S { field: () }");
        assert!((&doc.cratemod().structs()[0].sig).get().contains(
            "struct S {"));
    }

    #[test]
    fn should_not_serialize_struct_attrs() {
        // All we care about are the fields
        let doc = mk_doc(~"#[wut] struct S { field: () }");
        assert!(!(&doc.cratemod().structs()[0].sig).get().contains("wut"));
    }
}
<|endoftext|>


<commit_before><commit_msg>Initial plugin instance worker implementation.<commit_after><|endoftext|>


<commit_before><commit_msg>Add some examples for Option<commit_after>// Copyright 2013 The rust-for-real developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 *
 * Options represent optional values that can be either Some(T) or None
 *
 * Optional values are very useful when working with non-deterministic
 * environments, concurrent environments, signals / events, etc.
 *
 * A common way to unwrap `Option` values is to use match and checking
 * whether it holds a value or not. Although this is widely used, `Option`
 * also implements a big set of useful methods that cover most of the cases:
 *
 *  - unwrap: Returns the value or fails if it's None.
 *
 *  - unwrap_or: This returns the held value if any or the value passed to
 *  this call.
 *
 *  - is_(none|some): Return a boolean saying whether it holds a value or None.
 *
 */

fn option_match() {
    let value: Option<int> = Some(10);

    // This is the most common
    // way to use Optional values.
    match value {
        // Using `_` as variable name since it's not being used,
        // this silents 'unused variable' warnings from the compiler
        Some(_) => println("It is indeed an int and has a value"),
        None => println("It'll never get here")
    }
}

fn optional_arguments(some_str: Option<&str>) {

    // We could invert this by
    // checking for `is_some`
    // instead of `is_none`
    if (some_str.is_none()) {
        println("Got nothing");
    } else {
        println(fmt!("Got %s", some_str.unwrap()));
    }

    // A simpler way to do this would be
    println(fmt!("Got %s", some_str.unwrap_or("nothing")));
}

fn main() {
    option_match();

    optional_arguments(Some("Testing"));
    optional_arguments(None);
}
<|endoftext|>


<commit_before>extern crate odbc;
use odbc::*;

#[test]
fn list_tables() {

    let env = Environment::new().unwrap();
    let env = env.set_odbc_version_3().unwrap();
    let ds = DataSource::with_parent(&env).unwrap();
    let ds = ds.connect("TestDataSource", "", "").unwrap();
    // scope is required (for now) to close statement before disconnecting
    {
        let statement = Statement::with_parent(&ds).unwrap();
        let statement = statement.tables().unwrap();
        assert_eq!(statement.num_result_cols().unwrap(), 5);
    }
    ds.disconnect().unwrap();
}

#[test]
fn not_read_only() {

    let env = Environment::new().unwrap();
    let env = env.set_odbc_version_3().unwrap();
    let conn = DataSource::with_parent(&env).unwrap();
    let conn = conn.connect("TestDataSource", "", "").unwrap();

    assert!(!conn.read_only().unwrap());
    conn.disconnect().unwrap();
}

#[test]
fn implicit_disconnect() {

    let env = Environment::new().unwrap();
    let env = env.set_odbc_version_3().unwrap();
    let conn = DataSource::with_parent(&env).unwrap();
    conn.connect("TestDataSource", "", "").unwrap();

    // if there would be no implicit disconnect, all the drops would panic with function sequence
    // error
}

#[test]
fn invalid_connection_string() {

    let expected = if cfg!(target_os = "windows") {
        "State: IM002, Native error: 0, Message: [Microsoft][ODBC Driver Manager] Data source \
            name not found and no default driver specified"
    } else {
        "State: IM002, Native error: 0, Message: [unixODBC][Driver Manager]Data source name not \
            found, and no default driver specified"
    };

    let environment = Environment::new().unwrap();
    let environment = environment.set_odbc_version_3().unwrap();
    let conn = DataSource::with_parent(&environment).unwrap();
    let result = conn.connect_with_connection_string("bla");
    let message = format!("{}", result.err().unwrap());
    assert_eq!(expected, message);
}

#[test]
fn test_connection_string() {

    let environment = Environment::new().unwrap();
    let environment = environment.set_odbc_version_3().unwrap();
    let conn = DataSource::with_parent(&environment).unwrap();
    let conn = conn.connect_with_connection_string("dsn=TestDataSource;Uid=;Pwd=;")
        .unwrap();
    conn.disconnect().unwrap();
}

#[test]
fn test_direct_select() {
    let env = Environment::new().unwrap().set_odbc_version_3().unwrap();
    let conn = DataSource::with_parent(&env).unwrap().connect("TestDataSource", "", "").unwrap();
    let stmt = Statement::with_parent(&conn).unwrap();

    let mut stmt = match stmt.exec_direct("SELECT TITLE, YEAR FROM MOVIES ORDER BY YEAR")
        .unwrap() {
        Data(stmt) => stmt,
        NoData(_) => panic!("SELECT statement did not return result set!"),
    };

    assert_eq!(stmt.num_result_cols().unwrap(), 2);

    #[derive(PartialEq, Debug)]
    struct Movie {
        title: String,
        year: i16,
    }

    let mut actual = Vec::new();
    while let Some(mut cursor) = stmt.fetch().unwrap() {
        actual.push(Movie {
            title: cursor.get_data(1).unwrap().unwrap(),
            year: cursor.get_data(2).unwrap().unwrap(),
        })
    }

    let check = actual ==
                vec![Movie {
                         title: "2001: A Space Odyssey".to_owned(),
                         year: 1968,
                     },
                     Movie {
                         title: "Jurassic Park".to_owned(),
                         year: 1993,
                     }];

    println!("test_direct_select query result: {:?}", actual);

    assert!(check);
}

#[test]
fn reuse_statement() {
    let env = Environment::new().unwrap().set_odbc_version_3().unwrap();
    let conn = DataSource::with_parent(&env).unwrap().connect("TestDataSource", "", "").unwrap();
    let stmt = Statement::with_parent(&conn).unwrap();

    let stmt = match stmt.exec_direct("CREATE TABLE STAGE (A VARCHAR, B VARCHAR);").unwrap() {
        Data(stmt) => stmt.close_cursor().unwrap(), //A result set has been returned, we need to close it.
        NoData(stmt) => stmt,
    };
    let stmt = match stmt.exec_direct("INSERT INTO STAGE (A, B) VALUES ('Hello', 'World');")
        .unwrap() {
        Data(stmt) => stmt.close_cursor().unwrap(),
        NoData(stmt) => stmt,
    };
    if let Data(mut stmt) = stmt.exec_direct("SELECT A, B FROM STAGE;").unwrap() {
        {
            let mut cursor = stmt.fetch().unwrap().unwrap();
            assert_eq!(cursor.get_data::<String>(1).unwrap().unwrap(),"Hello");
            assert_eq!(cursor.get_data::<String>(2).unwrap().unwrap(), "World");
        }
        let stmt = stmt.close_cursor().unwrap();
        stmt.exec_direct("DROP TABLE STAGE;").unwrap();
    } else {
        panic!("SELECT statement returned no result set")
    };
}

#[test]
fn execution_with_parameter() {
    let env = Environment::new().unwrap().set_odbc_version_3().unwrap();
    let conn = DataSource::with_parent(&env).unwrap().connect("TestDataSource", "", "").unwrap();
    let stmt = Statement::with_parent(&conn).unwrap();
    let param = 1968;
    let stmt = stmt.bind_parameter(1, &param).unwrap();

    if let Data(mut stmt) = stmt.exec_direct("SELECT TITLE FROM MOVIES WHERE YEAR = ?").unwrap() {
        let mut cursor = stmt.fetch().unwrap().unwrap();
        assert_eq!(cursor.get_data::<String>(1).unwrap().unwrap(), "2001: A Space Odyssey");
    } else {
        panic!("SELECT statement returned no result set")
    };
}

#[test]
fn prepared_execution() {
    let env = Environment::new().unwrap().set_odbc_version_3().unwrap();
    let conn = DataSource::with_parent(&env).unwrap().connect("TestDataSource", "", "").unwrap();
    let stmt = Statement::with_parent(&conn).unwrap();
    let stmt = stmt.prepare("SELECT TITLE FROM MOVIES WHERE YEAR = ?").unwrap();

    fn execute_query<'a>(year: u16,
                         expected: &str,
                         stmt: Statement<'a, 'a, Prepared, NoResult>)
                         -> Result<Statement<'a, 'a, Prepared, NoResult>> {
        let stmt = stmt.bind_parameter(1, &year)?;
        let stmt = if let Data(mut stmt) = stmt.execute()? {
            {
                let mut cursor = stmt.fetch()?.unwrap();
                assert_eq!(cursor.get_data::<String>(1)?.unwrap(), expected);
            }
            stmt.close_cursor()?
        } else {
            panic!("SELECT statement returned no result set");
        };
        stmt.reset_parameters()
    };

    let stmt = execute_query(1968, "2001: A Space Odyssey", stmt).unwrap();
    execute_query(1993, "Jurassic Park", stmt).unwrap();
}

// These tests query the results of catalog functions. These results are only likely to match the
// expectation on the travis.ci build on linux. Therefore we limit compilation and execution of
// these tests to this platform.
#[cfg_attr(not(feature = "travis"), ignore)]
#[test]
fn list_drivers() {
    let environment = Environment::new().unwrap();
    let mut environment = environment.set_odbc_version_3().unwrap();
    let drivers = environment.drivers()
        .expect("Drivers can be iterated over");
    println!("{:?}", drivers);

    let expected = ["PostgreSQL ANSI", "PostgreSQL Unicode", "SQLite", "SQLite3"];
    assert!(drivers.iter().map(|d| &d.description).eq(expected.iter()));
}

#[cfg_attr(not(feature = "travis"), ignore)]
#[test]
fn list_data_sources() {
    let environment = Environment::new().unwrap();
    let mut environment = environment.set_odbc_version_3().unwrap();
    let sources = environment.data_sources()
        .expect("Data sources can be iterated over");
    println!("{:?}", sources);

    let expected = [DataSourceInfo {
                        server_name: "PostgreSQL".to_owned(),
                        driver: "PostgreSQL Unicode".to_owned(),
                    },
                    DataSourceInfo {
                        server_name: "TestDataSource".to_owned(),
                        driver: "SQLite3".to_owned(),
                    }];
    assert!(sources.iter().eq(expected.iter()));
}

#[cfg_attr(not(feature = "travis"), ignore)]
#[test]
fn list_user_data_sources() {
    let environment = Environment::new().unwrap();
    let mut environment = environment.set_odbc_version_3().unwrap();
    let sources = environment.user_data_sources()
        .expect("Data sources can be iterated over");
    println!("{:?}", sources);

    let expected = [DataSourceInfo {
                        server_name: "PostgreSQL".to_owned(),
                        driver: "PostgreSQL Unicode".to_owned(),
                    },
                    DataSourceInfo {
                        server_name: "TestDataSource".to_owned(),
                        driver: "SQLite3".to_owned(),
                    }];
    assert!(sources.iter().eq(expected.iter()));
}

#[cfg_attr(not(feature = "travis"), ignore)]
#[test]
fn list_system_data_sources() {
    let environment = Environment::new().unwrap();
    let mut environment = environment.set_odbc_version_3().unwrap();
    let sources = environment.system_data_sources()
        .expect("Data sources can be iterated over");
    println!("{:?}", sources);

    let expected: [DataSourceInfo; 0] = [];
    assert!(sources.iter().eq(expected.iter()));
}
<commit_msg>switch order in test expections<commit_after>extern crate odbc;
use odbc::*;

#[test]
fn list_tables() {

    let env = Environment::new().unwrap();
    let env = env.set_odbc_version_3().unwrap();
    let ds = DataSource::with_parent(&env).unwrap();
    let ds = ds.connect("TestDataSource", "", "").unwrap();
    // scope is required (for now) to close statement before disconnecting
    {
        let statement = Statement::with_parent(&ds).unwrap();
        let statement = statement.tables().unwrap();
        assert_eq!(statement.num_result_cols().unwrap(), 5);
    }
    ds.disconnect().unwrap();
}

#[test]
fn not_read_only() {

    let env = Environment::new().unwrap();
    let env = env.set_odbc_version_3().unwrap();
    let conn = DataSource::with_parent(&env).unwrap();
    let conn = conn.connect("TestDataSource", "", "").unwrap();

    assert!(!conn.read_only().unwrap());
    conn.disconnect().unwrap();
}

#[test]
fn implicit_disconnect() {

    let env = Environment::new().unwrap();
    let env = env.set_odbc_version_3().unwrap();
    let conn = DataSource::with_parent(&env).unwrap();
    conn.connect("TestDataSource", "", "").unwrap();

    // if there would be no implicit disconnect, all the drops would panic with function sequence
    // error
}

#[test]
fn invalid_connection_string() {

    let expected = if cfg!(target_os = "windows") {
        "State: IM002, Native error: 0, Message: [Microsoft][ODBC Driver Manager] Data source \
            name not found and no default driver specified"
    } else {
        "State: IM002, Native error: 0, Message: [unixODBC][Driver Manager]Data source name not \
            found, and no default driver specified"
    };

    let environment = Environment::new().unwrap();
    let environment = environment.set_odbc_version_3().unwrap();
    let conn = DataSource::with_parent(&environment).unwrap();
    let result = conn.connect_with_connection_string("bla");
    let message = format!("{}", result.err().unwrap());
    assert_eq!(expected, message);
}

#[test]
fn test_connection_string() {

    let environment = Environment::new().unwrap();
    let environment = environment.set_odbc_version_3().unwrap();
    let conn = DataSource::with_parent(&environment).unwrap();
    let conn = conn.connect_with_connection_string("dsn=TestDataSource;Uid=;Pwd=;")
        .unwrap();
    conn.disconnect().unwrap();
}

#[test]
fn test_direct_select() {
    let env = Environment::new().unwrap().set_odbc_version_3().unwrap();
    let conn = DataSource::with_parent(&env).unwrap().connect("TestDataSource", "", "").unwrap();
    let stmt = Statement::with_parent(&conn).unwrap();

    let mut stmt = match stmt.exec_direct("SELECT TITLE, YEAR FROM MOVIES ORDER BY YEAR")
        .unwrap() {
        Data(stmt) => stmt,
        NoData(_) => panic!("SELECT statement did not return result set!"),
    };

    assert_eq!(stmt.num_result_cols().unwrap(), 2);

    #[derive(PartialEq, Debug)]
    struct Movie {
        title: String,
        year: i16,
    }

    let mut actual = Vec::new();
    while let Some(mut cursor) = stmt.fetch().unwrap() {
        actual.push(Movie {
            title: cursor.get_data(1).unwrap().unwrap(),
            year: cursor.get_data(2).unwrap().unwrap(),
        })
    }

    let check = actual ==
                vec![Movie {
                         title: "2001: A Space Odyssey".to_owned(),
                         year: 1968,
                     },
                     Movie {
                         title: "Jurassic Park".to_owned(),
                         year: 1993,
                     }];

    println!("test_direct_select query result: {:?}", actual);

    assert!(check);
}

#[test]
fn reuse_statement() {
    let env = Environment::new().unwrap().set_odbc_version_3().unwrap();
    let conn = DataSource::with_parent(&env).unwrap().connect("TestDataSource", "", "").unwrap();
    let stmt = Statement::with_parent(&conn).unwrap();

    let stmt = match stmt.exec_direct("CREATE TABLE STAGE (A VARCHAR, B VARCHAR);").unwrap() {
        Data(stmt) => stmt.close_cursor().unwrap(), //A result set has been returned, we need to close it.
        NoData(stmt) => stmt,
    };
    let stmt = match stmt.exec_direct("INSERT INTO STAGE (A, B) VALUES ('Hello', 'World');")
        .unwrap() {
        Data(stmt) => stmt.close_cursor().unwrap(),
        NoData(stmt) => stmt,
    };
    if let Data(mut stmt) = stmt.exec_direct("SELECT A, B FROM STAGE;").unwrap() {
        {
            let mut cursor = stmt.fetch().unwrap().unwrap();
            assert_eq!(cursor.get_data::<String>(1).unwrap().unwrap(),"Hello");
            assert_eq!(cursor.get_data::<String>(2).unwrap().unwrap(), "World");
        }
        let stmt = stmt.close_cursor().unwrap();
        stmt.exec_direct("DROP TABLE STAGE;").unwrap();
    } else {
        panic!("SELECT statement returned no result set")
    };
}

#[test]
fn execution_with_parameter() {
    let env = Environment::new().unwrap().set_odbc_version_3().unwrap();
    let conn = DataSource::with_parent(&env).unwrap().connect("TestDataSource", "", "").unwrap();
    let stmt = Statement::with_parent(&conn).unwrap();
    let param = 1968;
    let stmt = stmt.bind_parameter(1, &param).unwrap();

    if let Data(mut stmt) = stmt.exec_direct("SELECT TITLE FROM MOVIES WHERE YEAR = ?").unwrap() {
        let mut cursor = stmt.fetch().unwrap().unwrap();
        assert_eq!(cursor.get_data::<String>(1).unwrap().unwrap(), "2001: A Space Odyssey");
    } else {
        panic!("SELECT statement returned no result set")
    };
}

#[test]
fn prepared_execution() {
    let env = Environment::new().unwrap().set_odbc_version_3().unwrap();
    let conn = DataSource::with_parent(&env).unwrap().connect("TestDataSource", "", "").unwrap();
    let stmt = Statement::with_parent(&conn).unwrap();
    let stmt = stmt.prepare("SELECT TITLE FROM MOVIES WHERE YEAR = ?").unwrap();

    fn execute_query<'a>(year: u16,
                         expected: &str,
                         stmt: Statement<'a, 'a, Prepared, NoResult>)
                         -> Result<Statement<'a, 'a, Prepared, NoResult>> {
        let stmt = stmt.bind_parameter(1, &year)?;
        let stmt = if let Data(mut stmt) = stmt.execute()? {
            {
                let mut cursor = stmt.fetch()?.unwrap();
                assert_eq!(cursor.get_data::<String>(1)?.unwrap(), expected);
            }
            stmt.close_cursor()?
        } else {
            panic!("SELECT statement returned no result set");
        };
        stmt.reset_parameters()
    };

    let stmt = execute_query(1968, "2001: A Space Odyssey", stmt).unwrap();
    execute_query(1993, "Jurassic Park", stmt).unwrap();
}

// These tests query the results of catalog functions. These results are only likely to match the
// expectation on the travis.ci build on linux. Therefore we limit compilation and execution of
// these tests to this platform.
#[cfg_attr(not(feature = "travis"), ignore)]
#[test]
fn list_drivers() {
    let environment = Environment::new().unwrap();
    let mut environment = environment.set_odbc_version_3().unwrap();
    let drivers = environment.drivers()
        .expect("Drivers can be iterated over");
    println!("{:?}", drivers);

    let expected = ["SQLite", "SQLite3", "PostgreSQL ANSI", "PostgreSQL Unicode"];
    assert!(drivers.iter().map(|d| &d.description).eq(expected.iter()));
}

#[cfg_attr(not(feature = "travis"), ignore)]
#[test]
fn list_data_sources() {
    let environment = Environment::new().unwrap();
    let mut environment = environment.set_odbc_version_3().unwrap();
    let sources = environment.data_sources()
        .expect("Data sources can be iterated over");
    println!("{:?}", sources);

    let expected = [DataSourceInfo {
                        server_name: "PostgreSQL".to_owned(),
                        driver: "PostgreSQL Unicode".to_owned(),
                    },
                    DataSourceInfo {
                        server_name: "TestDataSource".to_owned(),
                        driver: "SQLite3".to_owned(),
                    }];
    assert!(sources.iter().eq(expected.iter()));
}

#[cfg_attr(not(feature = "travis"), ignore)]
#[test]
fn list_user_data_sources() {
    let environment = Environment::new().unwrap();
    let mut environment = environment.set_odbc_version_3().unwrap();
    let sources = environment.user_data_sources()
        .expect("Data sources can be iterated over");
    println!("{:?}", sources);

    let expected = [DataSourceInfo {
                        server_name: "PostgreSQL".to_owned(),
                        driver: "PostgreSQL Unicode".to_owned(),
                    },
                    DataSourceInfo {
                        server_name: "TestDataSource".to_owned(),
                        driver: "SQLite3".to_owned(),
                    }];
    assert!(sources.iter().eq(expected.iter()));
}

#[cfg_attr(not(feature = "travis"), ignore)]
#[test]
fn list_system_data_sources() {
    let environment = Environment::new().unwrap();
    let mut environment = environment.set_odbc_version_3().unwrap();
    let sources = environment.system_data_sources()
        .expect("Data sources can be iterated over");
    println!("{:?}", sources);

    let expected: [DataSourceInfo; 0] = [];
    assert!(sources.iter().eq(expected.iter()));
}
<|endoftext|>


<commit_before><commit_msg>Separated tests into headless and non-headless.<commit_after>
// #[cfg(all(test, has_display))]

extern crate ggez;
use ggez::*;

#[test]
pub fn test_text_width() {
    let ctx = &mut Context::load_from_conf("test", "me", conf::Conf::new()).unwrap();
    let font = graphics::Font::default_font().unwrap();

    let text = "Hello There";

    let expected_width = font.get_width(text);
    let rendered_width = graphics::Text::new(ctx, text, &font).unwrap().width();

    println!("Text: {:?}, expected: {}, rendered: {}", text, expected_width, rendered_width);
    assert_eq!(expected_width as usize, rendered_width as usize);
}<|endoftext|>


<commit_before><commit_msg>Adds utilities that allow text comparison of bindings.<commit_after><|endoftext|>


<commit_before><commit_msg>test stderr.<commit_after>#![feature(std_misc)]
extern crate gag;

use std::io::{Read, Write};
use gag::{BufferRedirect, Hold};
use std::sync::{StaticMutex, MUTEX_INIT};

static STDERR_MUTEX: StaticMutex = MUTEX_INIT;

// Catch the cases not covered by the doc tests.

#[test]
fn test_buffer_stderr() {
    let _l = STDERR_MUTEX.lock().unwrap();

    let mut buf = BufferRedirect::stderr().unwrap();
    println!("Don't capture");
    ::std::io::stderr().write_all(b"Hello world!\n").unwrap();

    let mut output = String::new();
    buf.read_to_string(&mut output).unwrap();

    assert_eq!(&output[..], "Hello world!\n");
}

#[test]
fn test_gag_stderr_twice() {
    let _l = STDERR_MUTEX.lock().unwrap();

    let hold = Hold::stderr();
    let hold2 = Hold::stderr();
    assert!(hold.is_ok());
    assert!(hold2.is_err());
}
<|endoftext|>


<commit_before><commit_msg>Formatting<commit_after><|endoftext|>


<commit_before><commit_msg>fpscamera in tut3 working<commit_after><|endoftext|>


<commit_before><commit_msg>Document Entry more.<commit_after><|endoftext|>


<commit_before><commit_msg>Removed general purpose stack in favour of type specific. Removed Element concept<commit_after><|endoftext|>


<commit_before><commit_msg>Better naming consistency<commit_after><|endoftext|>


<commit_before><commit_msg>refactor(lib): extern regex module<commit_after><|endoftext|>


<commit_before><commit_msg>Remove unused attribute and fix warning<commit_after><|endoftext|>


<commit_before><commit_msg>Remove dependency on unstable features<commit_after><|endoftext|>


<commit_before><commit_msg>Workaround for Rust issue #24258<commit_after><|endoftext|>


<commit_before><commit_msg>Fix regex<commit_after><|endoftext|>


<commit_before><commit_msg>Reading file header as one block.<commit_after><|endoftext|>


<commit_before><commit_msg>Approaching usable state!<commit_after><|endoftext|>


<commit_before><commit_msg>clone Vec<commit_after><|endoftext|>


<commit_before><commit_msg>Add compile-fail test for missing import shadowing case<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 std::slice::Items;
//~^ ERROR import `Items` conflicts with type in this module

struct Items;

fn main() {
}

<|endoftext|>


<commit_before><commit_msg>Cleanup image processing example script.<commit_after><|endoftext|>


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


<commit_before><commit_msg>Add test for DropAndReplace bug<commit_after>// Regression test for incorrect DropAndReplace behavior introduced in #60840
// and fixed in #61373. When combined with the optimization implemented in
// #60187, this produced incorrect code for generators when a saved local was
// re-assigned.

#![feature(generators, generator_trait)]

use std::ops::{Generator, GeneratorState};
use std::pin::Pin;

#[derive(Debug, PartialEq)]
struct Foo(i32);

impl Drop for Foo {
    fn drop(&mut self) { }
}

fn main() {
    let mut a = || {
        let mut x = Foo(4);
        yield;
        assert_eq!(x.0, 4);

        // At one point this tricked our dataflow analysis into thinking `x` was
        // StorageDead after the assignment.
        x = Foo(5);
        assert_eq!(x.0, 5);

        {
            let y = Foo(6);
            yield;
            assert_eq!(y.0, 6);
        }

        assert_eq!(x.0, 5);
    };

    loop {
        match Pin::new(&mut a).resume() {
            GeneratorState::Complete(()) => break,
            _ => (),
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>print struct #derive[Debug]<commit_after>#[derive(Debug)]
struct Rectangle {
    length: i32,
    width: i32,
}

fn main() {
    let rectangle = Rectangle{
        length: 50,
        width: 30,
    };

    println!("Area of Rectangle is {}", area(rectangle));
}

fn area(rectangle: Rectangle) -> i32 {
    println!("{:?}", rectangle);
    rectangle.length * rectangle.width

}<|endoftext|>


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

//! This mdoule defines types which are thread safe if cfg!(parallel_queries) is true.
//!
//! `Lrc` is an alias of either Rc or Arc.
//!
//! `Lock` is a mutex.
//! It internally uses `parking_lot::Mutex` if cfg!(parallel_queries) is true,
//! `RefCell` otherwise.
//!
//! `RwLock` is a read-write lock.
//! It internally uses `parking_lot::RwLock` if cfg!(parallel_queries) is true,
//! `RefCell` otherwise.
//!
//! `LockCell` is a thread safe version of `Cell`, with `set` and `get` operations.
//! It can never deadlock. It uses `Cell` when
//! cfg!(parallel_queries) is false, otherwise it is a `Lock`.
//!
//! `MTLock` is a mutex which disappears if cfg!(parallel_queries) is false.
//!
//! `rustc_erase_owner!` erases a OwningRef owner into Erased or Erased + Send + Sync
//! depending on the value of cfg!(parallel_queries).

use std::cmp::Ordering;
use std::fmt::Debug;
use std::fmt::Formatter;
use std::fmt;
use std;
use std::ops::{Deref, DerefMut};
use owning_ref::{Erased, OwningRef};

cfg_if! {
    if #[cfg(not(parallel_queries))] {
        pub auto trait Send {}
        pub auto trait Sync {}

        impl<T: ?Sized> Send for T {}
        impl<T: ?Sized> Sync for T {}

        #[macro_export]
        macro_rules! rustc_erase_owner {
            ($v:expr) => {
                $v.erase_owner()
            }
        }

        pub type MetadataRef = OwningRef<Box<Erased>, [u8]>;

        pub use std::rc::Rc as Lrc;
        pub use std::cell::Ref as ReadGuard;
        pub use std::cell::RefMut as WriteGuard;
        pub use std::cell::RefMut as LockGuard;

        use std::cell::RefCell as InnerRwLock;
        use std::cell::RefCell as InnerLock;

        use std::cell::Cell;

        #[derive(Debug)]
        pub struct MTLock<T>(T);

        impl<T> MTLock<T> {
            #[inline(always)]
            pub fn new(inner: T) -> Self {
                MTLock(inner)
            }

            #[inline(always)]
            pub fn into_inner(self) -> T {
                self.0
            }

            #[inline(always)]
            pub fn get_mut(&mut self) -> &mut T {
                &mut self.0
            }

            #[inline(always)]
            pub fn lock(&self) -> &T {
                &self.0
            }

            #[inline(always)]
            pub fn borrow(&self) -> &T {
                &self.0
            }

            #[inline(always)]
            pub fn borrow_mut(&self) -> &T {
                &self.0
            }
        }

        // FIXME: Probably a bad idea (in the threaded case)
        impl<T: Clone> Clone for MTLock<T> {
            #[inline]
            fn clone(&self) -> Self {
                MTLock(self.0.clone())
            }
        }

        pub struct LockCell<T>(Cell<T>);

        impl<T> LockCell<T> {
            #[inline(always)]
            pub fn new(inner: T) -> Self {
                LockCell(Cell::new(inner))
            }

            #[inline(always)]
            pub fn into_inner(self) -> T {
                self.0.into_inner()
            }

            #[inline(always)]
            pub fn set(&self, new_inner: T) {
                self.0.set(new_inner);
            }

            #[inline(always)]
            pub fn get(&self) -> T where T: Copy {
                self.0.get()
            }

            #[inline(always)]
            pub fn set_mut(&mut self, new_inner: T) {
                self.0.set(new_inner);
            }

            #[inline(always)]
            pub fn get_mut(&mut self) -> T where T: Copy {
                self.0.get()
            }
        }

        impl<T> LockCell<Option<T>> {
            #[inline(always)]
            pub fn take(&self) -> Option<T> {
                unsafe { (*self.0.as_ptr()).take() }
            }
        }
    } else {
        pub use std::marker::Send as Send;
        pub use std::marker::Sync as Sync;

        pub use parking_lot::RwLockReadGuard as ReadGuard;
        pub use parking_lot::RwLockWriteGuard as WriteGuard;

        pub use parking_lot::MutexGuard as LockGuard;

        pub use std::sync::Arc as Lrc;

        pub use self::Lock as MTLock;

        use parking_lot::Mutex as InnerLock;
        use parking_lot::RwLock as InnerRwLock;

        use std::thread;

        pub type MetadataRef = OwningRef<Box<Erased + Send + Sync>, [u8]>;

        /// This makes locks panic if they are already held.
        /// It is only useful when you are running in a single thread
        const ERROR_CHECKING: bool = false;

        #[macro_export]
        macro_rules! rustc_erase_owner {
            ($v:expr) => {{
                let v = $v;
                ::rustc_data_structures::sync::assert_send_val(&v);
                v.erase_send_sync_owner()
            }}
        }

        pub struct LockCell<T>(Lock<T>);

        impl<T> LockCell<T> {
            #[inline(always)]
            pub fn new(inner: T) -> Self {
                LockCell(Lock::new(inner))
            }

            #[inline(always)]
            pub fn into_inner(self) -> T {
                self.0.into_inner()
            }

            #[inline(always)]
            pub fn set(&self, new_inner: T) {
                *self.0.lock() = new_inner;
            }

            #[inline(always)]
            pub fn get(&self) -> T where T: Copy {
                *self.0.lock()
            }

            #[inline(always)]
            pub fn set_mut(&mut self, new_inner: T) {
                *self.0.get_mut() = new_inner;
            }

            #[inline(always)]
            pub fn get_mut(&mut self) -> T where T: Copy {
                *self.0.get_mut()
            }
        }

        impl<T> LockCell<Option<T>> {
            #[inline(always)]
            pub fn take(&self) -> Option<T> {
                self.0.lock().take()
            }
        }
    }
}

pub fn assert_sync<T: ?Sized + Sync>() {}
pub fn assert_send_val<T: ?Sized + Send>(_t: &T) {}
pub fn assert_send_sync_val<T: ?Sized + Sync + Send>(_t: &T) {}

impl<T: Copy + Debug> Debug for LockCell<T> {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        f.debug_struct("LockCell")
            .field("value", &self.get())
            .finish()
    }
}

impl<T:Default> Default for LockCell<T> {
    /// Creates a `LockCell<T>`, with the `Default` value for T.
    #[inline]
    fn default() -> LockCell<T> {
        LockCell::new(Default::default())
    }
}

impl<T:PartialEq + Copy> PartialEq for LockCell<T> {
    #[inline]
    fn eq(&self, other: &LockCell<T>) -> bool {
        self.get() == other.get()
    }
}

impl<T:Eq + Copy> Eq for LockCell<T> {}

impl<T:PartialOrd + Copy> PartialOrd for LockCell<T> {
    #[inline]
    fn partial_cmp(&self, other: &LockCell<T>) -> Option<Ordering> {
        self.get().partial_cmp(&other.get())
    }

    #[inline]
    fn lt(&self, other: &LockCell<T>) -> bool {
        self.get() < other.get()
    }

    #[inline]
    fn le(&self, other: &LockCell<T>) -> bool {
        self.get() <= other.get()
    }

    #[inline]
    fn gt(&self, other: &LockCell<T>) -> bool {
        self.get() > other.get()
    }

    #[inline]
    fn ge(&self, other: &LockCell<T>) -> bool {
        self.get() >= other.get()
    }
}

impl<T:Ord + Copy> Ord for LockCell<T> {
    #[inline]
    fn cmp(&self, other: &LockCell<T>) -> Ordering {
        self.get().cmp(&other.get())
    }
}

#[derive(Debug)]
pub struct Lock<T>(InnerLock<T>);

impl<T> Lock<T> {
    #[inline(always)]
    pub fn new(inner: T) -> Self {
        Lock(InnerLock::new(inner))
    }

    #[inline(always)]
    pub fn into_inner(self) -> T {
        self.0.into_inner()
    }

    #[inline(always)]
    pub fn get_mut(&mut self) -> &mut T {
        self.0.get_mut()
    }

    #[cfg(parallel_queries)]
    #[inline(always)]
    pub fn lock(&self) -> LockGuard<T> {
        if ERROR_CHECKING {
            self.0.try_lock().expect("lock was already held")
        } else {
            self.0.lock()
        }
    }

    #[cfg(not(parallel_queries))]
    #[inline(always)]
    pub fn lock(&self) -> LockGuard<T> {
        self.0.borrow_mut()
    }

    #[inline(always)]
    pub fn with_lock<F: FnOnce(&mut T) -> R, R>(&self, f: F) -> R {
        f(&mut *self.lock())
    }

    #[inline(always)]
    pub fn borrow(&self) -> LockGuard<T> {
        self.lock()
    }

    #[inline(always)]
    pub fn borrow_mut(&self) -> LockGuard<T> {
        self.lock()
    }
}

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

// FIXME: Probably a bad idea
impl<T: Clone> Clone for Lock<T> {
    #[inline]
    fn clone(&self) -> Self {
        Lock::new(self.borrow().clone())
    }
}

#[derive(Debug)]
pub struct RwLock<T>(InnerRwLock<T>);

impl<T> RwLock<T> {
    #[inline(always)]
    pub fn new(inner: T) -> Self {
        RwLock(InnerRwLock::new(inner))
    }

    #[inline(always)]
    pub fn into_inner(self) -> T {
        self.0.into_inner()
    }

    #[inline(always)]
    pub fn get_mut(&mut self) -> &mut T {
        self.0.get_mut()
    }

    #[cfg(not(parallel_queries))]
    #[inline(always)]
    pub fn read(&self) -> ReadGuard<T> {
        self.0.borrow()
    }

    #[cfg(parallel_queries)]
    #[inline(always)]
    pub fn read(&self) -> ReadGuard<T> {
        if ERROR_CHECKING {
            self.0.try_read().expect("lock was already held")
        } else {
            self.0.read()
        }
    }

    #[inline(always)]
    pub fn with_read_lock<F: FnOnce(&T) -> R, R>(&self, f: F) -> R {
        f(&*self.read())
    }

    #[cfg(not(parallel_queries))]
    #[inline(always)]
    pub fn try_write(&self) -> Result<WriteGuard<T>, ()> {
        self.0.try_borrow_mut().map_err(|_| ())
    }

    #[cfg(parallel_queries)]
    #[inline(always)]
    pub fn try_write(&self) -> Result<WriteGuard<T>, ()> {
        self.0.try_write().ok_or(())
    }

    #[cfg(not(parallel_queries))]
    #[inline(always)]
    pub fn write(&self) -> WriteGuard<T> {
        self.0.borrow_mut()
    }

    #[cfg(parallel_queries)]
    #[inline(always)]
    pub fn write(&self) -> WriteGuard<T> {
        if ERROR_CHECKING {
            self.0.try_write().expect("lock was already held")
        } else {
            self.0.write()
        }
    }

    #[inline(always)]
    pub fn with_write_lock<F: FnOnce(&mut T) -> R, R>(&self, f: F) -> R {
        f(&mut *self.write())
    }

    #[inline(always)]
    pub fn borrow(&self) -> ReadGuard<T> {
        self.read()
    }

    #[inline(always)]
    pub fn borrow_mut(&self) -> WriteGuard<T> {
        self.write()
    }
}

// FIXME: Probably a bad idea
impl<T: Clone> Clone for RwLock<T> {
    #[inline]
    fn clone(&self) -> Self {
        RwLock::new(self.borrow().clone())
    }
}

/// A type which only allows its inner value to be used in one thread.
/// It will panic if it is used on multiple threads.
#[derive(Copy, Clone, Hash, Debug, Eq, PartialEq)]
pub struct OneThread<T> {
    #[cfg(parallel_queries)]
    thread: thread::ThreadId,
    inner: T,
}

unsafe impl<T> std::marker::Sync for OneThread<T> {}
unsafe impl<T> std::marker::Send for OneThread<T> {}

impl<T> OneThread<T> {
    #[inline(always)]
    fn check(&self) {
        #[cfg(parallel_queries)]
        assert_eq!(thread::current().id(), self.thread);
    }

    #[inline(always)]
    pub fn new(inner: T) -> Self {
        OneThread {
            #[cfg(parallel_queries)]
            thread: thread::current().id(),
            inner,
        }
    }

    #[inline(always)]
    pub fn into_inner(value: Self) -> T {
        value.check();
        value.inner
    }
}

impl<T> Deref for OneThread<T> {
    type Target = T;

    fn deref(&self) -> &T {
        self.check();
        &self.inner
    }
}

impl<T> DerefMut for OneThread<T> {
    fn deref_mut(&mut self) -> &mut T {
        self.check();
        &mut self.inner
    }
}
<commit_msg>Add insert_same extension to HashMap<commit_after>// Copyright 2017 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.

//! This mdoule defines types which are thread safe if cfg!(parallel_queries) is true.
//!
//! `Lrc` is an alias of either Rc or Arc.
//!
//! `Lock` is a mutex.
//! It internally uses `parking_lot::Mutex` if cfg!(parallel_queries) is true,
//! `RefCell` otherwise.
//!
//! `RwLock` is a read-write lock.
//! It internally uses `parking_lot::RwLock` if cfg!(parallel_queries) is true,
//! `RefCell` otherwise.
//!
//! `LockCell` is a thread safe version of `Cell`, with `set` and `get` operations.
//! It can never deadlock. It uses `Cell` when
//! cfg!(parallel_queries) is false, otherwise it is a `Lock`.
//!
//! `MTLock` is a mutex which disappears if cfg!(parallel_queries) is false.
//!
//! `rustc_erase_owner!` erases a OwningRef owner into Erased or Erased + Send + Sync
//! depending on the value of cfg!(parallel_queries).

use std::collections::HashMap;
use std::hash::{Hash, BuildHasher};
use std::cmp::Ordering;
use std::fmt::Debug;
use std::fmt::Formatter;
use std::fmt;
use std;
use std::ops::{Deref, DerefMut};
use owning_ref::{Erased, OwningRef};

cfg_if! {
    if #[cfg(not(parallel_queries))] {
        pub auto trait Send {}
        pub auto trait Sync {}

        impl<T: ?Sized> Send for T {}
        impl<T: ?Sized> Sync for T {}

        #[macro_export]
        macro_rules! rustc_erase_owner {
            ($v:expr) => {
                $v.erase_owner()
            }
        }

        pub type MetadataRef = OwningRef<Box<Erased>, [u8]>;

        pub use std::rc::Rc as Lrc;
        pub use std::cell::Ref as ReadGuard;
        pub use std::cell::RefMut as WriteGuard;
        pub use std::cell::RefMut as LockGuard;

        use std::cell::RefCell as InnerRwLock;
        use std::cell::RefCell as InnerLock;

        use std::cell::Cell;

        #[derive(Debug)]
        pub struct MTLock<T>(T);

        impl<T> MTLock<T> {
            #[inline(always)]
            pub fn new(inner: T) -> Self {
                MTLock(inner)
            }

            #[inline(always)]
            pub fn into_inner(self) -> T {
                self.0
            }

            #[inline(always)]
            pub fn get_mut(&mut self) -> &mut T {
                &mut self.0
            }

            #[inline(always)]
            pub fn lock(&self) -> &T {
                &self.0
            }

            #[inline(always)]
            pub fn borrow(&self) -> &T {
                &self.0
            }

            #[inline(always)]
            pub fn borrow_mut(&self) -> &T {
                &self.0
            }
        }

        // FIXME: Probably a bad idea (in the threaded case)
        impl<T: Clone> Clone for MTLock<T> {
            #[inline]
            fn clone(&self) -> Self {
                MTLock(self.0.clone())
            }
        }

        pub struct LockCell<T>(Cell<T>);

        impl<T> LockCell<T> {
            #[inline(always)]
            pub fn new(inner: T) -> Self {
                LockCell(Cell::new(inner))
            }

            #[inline(always)]
            pub fn into_inner(self) -> T {
                self.0.into_inner()
            }

            #[inline(always)]
            pub fn set(&self, new_inner: T) {
                self.0.set(new_inner);
            }

            #[inline(always)]
            pub fn get(&self) -> T where T: Copy {
                self.0.get()
            }

            #[inline(always)]
            pub fn set_mut(&mut self, new_inner: T) {
                self.0.set(new_inner);
            }

            #[inline(always)]
            pub fn get_mut(&mut self) -> T where T: Copy {
                self.0.get()
            }
        }

        impl<T> LockCell<Option<T>> {
            #[inline(always)]
            pub fn take(&self) -> Option<T> {
                unsafe { (*self.0.as_ptr()).take() }
            }
        }
    } else {
        pub use std::marker::Send as Send;
        pub use std::marker::Sync as Sync;

        pub use parking_lot::RwLockReadGuard as ReadGuard;
        pub use parking_lot::RwLockWriteGuard as WriteGuard;

        pub use parking_lot::MutexGuard as LockGuard;

        pub use std::sync::Arc as Lrc;

        pub use self::Lock as MTLock;

        use parking_lot::Mutex as InnerLock;
        use parking_lot::RwLock as InnerRwLock;

        use std::thread;

        pub type MetadataRef = OwningRef<Box<Erased + Send + Sync>, [u8]>;

        /// This makes locks panic if they are already held.
        /// It is only useful when you are running in a single thread
        const ERROR_CHECKING: bool = false;

        #[macro_export]
        macro_rules! rustc_erase_owner {
            ($v:expr) => {{
                let v = $v;
                ::rustc_data_structures::sync::assert_send_val(&v);
                v.erase_send_sync_owner()
            }}
        }

        pub struct LockCell<T>(Lock<T>);

        impl<T> LockCell<T> {
            #[inline(always)]
            pub fn new(inner: T) -> Self {
                LockCell(Lock::new(inner))
            }

            #[inline(always)]
            pub fn into_inner(self) -> T {
                self.0.into_inner()
            }

            #[inline(always)]
            pub fn set(&self, new_inner: T) {
                *self.0.lock() = new_inner;
            }

            #[inline(always)]
            pub fn get(&self) -> T where T: Copy {
                *self.0.lock()
            }

            #[inline(always)]
            pub fn set_mut(&mut self, new_inner: T) {
                *self.0.get_mut() = new_inner;
            }

            #[inline(always)]
            pub fn get_mut(&mut self) -> T where T: Copy {
                *self.0.get_mut()
            }
        }

        impl<T> LockCell<Option<T>> {
            #[inline(always)]
            pub fn take(&self) -> Option<T> {
                self.0.lock().take()
            }
        }
    }
}

pub fn assert_sync<T: ?Sized + Sync>() {}
pub fn assert_send_val<T: ?Sized + Send>(_t: &T) {}
pub fn assert_send_sync_val<T: ?Sized + Sync + Send>(_t: &T) {}

pub trait HashMapExt<K, V> {
    /// Same as HashMap::insert, but it may panic if there's already an
    /// entry for `key` with a value not equal to `value`
    fn insert_same(&mut self, key: K, value: V);
}

impl<K: Eq + Hash, V: Eq, S: BuildHasher> HashMapExt<K, V> for HashMap<K, V, S> {
    fn insert_same(&mut self, key: K, value: V) {
        self.entry(key).and_modify(|old| assert!(*old == value)).or_insert(value);
    }
}

impl<T: Copy + Debug> Debug for LockCell<T> {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        f.debug_struct("LockCell")
            .field("value", &self.get())
            .finish()
    }
}

impl<T:Default> Default for LockCell<T> {
    /// Creates a `LockCell<T>`, with the `Default` value for T.
    #[inline]
    fn default() -> LockCell<T> {
        LockCell::new(Default::default())
    }
}

impl<T:PartialEq + Copy> PartialEq for LockCell<T> {
    #[inline]
    fn eq(&self, other: &LockCell<T>) -> bool {
        self.get() == other.get()
    }
}

impl<T:Eq + Copy> Eq for LockCell<T> {}

impl<T:PartialOrd + Copy> PartialOrd for LockCell<T> {
    #[inline]
    fn partial_cmp(&self, other: &LockCell<T>) -> Option<Ordering> {
        self.get().partial_cmp(&other.get())
    }

    #[inline]
    fn lt(&self, other: &LockCell<T>) -> bool {
        self.get() < other.get()
    }

    #[inline]
    fn le(&self, other: &LockCell<T>) -> bool {
        self.get() <= other.get()
    }

    #[inline]
    fn gt(&self, other: &LockCell<T>) -> bool {
        self.get() > other.get()
    }

    #[inline]
    fn ge(&self, other: &LockCell<T>) -> bool {
        self.get() >= other.get()
    }
}

impl<T:Ord + Copy> Ord for LockCell<T> {
    #[inline]
    fn cmp(&self, other: &LockCell<T>) -> Ordering {
        self.get().cmp(&other.get())
    }
}

#[derive(Debug)]
pub struct Lock<T>(InnerLock<T>);

impl<T> Lock<T> {
    #[inline(always)]
    pub fn new(inner: T) -> Self {
        Lock(InnerLock::new(inner))
    }

    #[inline(always)]
    pub fn into_inner(self) -> T {
        self.0.into_inner()
    }

    #[inline(always)]
    pub fn get_mut(&mut self) -> &mut T {
        self.0.get_mut()
    }

    #[cfg(parallel_queries)]
    #[inline(always)]
    pub fn lock(&self) -> LockGuard<T> {
        if ERROR_CHECKING {
            self.0.try_lock().expect("lock was already held")
        } else {
            self.0.lock()
        }
    }

    #[cfg(not(parallel_queries))]
    #[inline(always)]
    pub fn lock(&self) -> LockGuard<T> {
        self.0.borrow_mut()
    }

    #[inline(always)]
    pub fn with_lock<F: FnOnce(&mut T) -> R, R>(&self, f: F) -> R {
        f(&mut *self.lock())
    }

    #[inline(always)]
    pub fn borrow(&self) -> LockGuard<T> {
        self.lock()
    }

    #[inline(always)]
    pub fn borrow_mut(&self) -> LockGuard<T> {
        self.lock()
    }
}

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

// FIXME: Probably a bad idea
impl<T: Clone> Clone for Lock<T> {
    #[inline]
    fn clone(&self) -> Self {
        Lock::new(self.borrow().clone())
    }
}

#[derive(Debug)]
pub struct RwLock<T>(InnerRwLock<T>);

impl<T> RwLock<T> {
    #[inline(always)]
    pub fn new(inner: T) -> Self {
        RwLock(InnerRwLock::new(inner))
    }

    #[inline(always)]
    pub fn into_inner(self) -> T {
        self.0.into_inner()
    }

    #[inline(always)]
    pub fn get_mut(&mut self) -> &mut T {
        self.0.get_mut()
    }

    #[cfg(not(parallel_queries))]
    #[inline(always)]
    pub fn read(&self) -> ReadGuard<T> {
        self.0.borrow()
    }

    #[cfg(parallel_queries)]
    #[inline(always)]
    pub fn read(&self) -> ReadGuard<T> {
        if ERROR_CHECKING {
            self.0.try_read().expect("lock was already held")
        } else {
            self.0.read()
        }
    }

    #[inline(always)]
    pub fn with_read_lock<F: FnOnce(&T) -> R, R>(&self, f: F) -> R {
        f(&*self.read())
    }

    #[cfg(not(parallel_queries))]
    #[inline(always)]
    pub fn try_write(&self) -> Result<WriteGuard<T>, ()> {
        self.0.try_borrow_mut().map_err(|_| ())
    }

    #[cfg(parallel_queries)]
    #[inline(always)]
    pub fn try_write(&self) -> Result<WriteGuard<T>, ()> {
        self.0.try_write().ok_or(())
    }

    #[cfg(not(parallel_queries))]
    #[inline(always)]
    pub fn write(&self) -> WriteGuard<T> {
        self.0.borrow_mut()
    }

    #[cfg(parallel_queries)]
    #[inline(always)]
    pub fn write(&self) -> WriteGuard<T> {
        if ERROR_CHECKING {
            self.0.try_write().expect("lock was already held")
        } else {
            self.0.write()
        }
    }

    #[inline(always)]
    pub fn with_write_lock<F: FnOnce(&mut T) -> R, R>(&self, f: F) -> R {
        f(&mut *self.write())
    }

    #[inline(always)]
    pub fn borrow(&self) -> ReadGuard<T> {
        self.read()
    }

    #[inline(always)]
    pub fn borrow_mut(&self) -> WriteGuard<T> {
        self.write()
    }
}

// FIXME: Probably a bad idea
impl<T: Clone> Clone for RwLock<T> {
    #[inline]
    fn clone(&self) -> Self {
        RwLock::new(self.borrow().clone())
    }
}

/// A type which only allows its inner value to be used in one thread.
/// It will panic if it is used on multiple threads.
#[derive(Copy, Clone, Hash, Debug, Eq, PartialEq)]
pub struct OneThread<T> {
    #[cfg(parallel_queries)]
    thread: thread::ThreadId,
    inner: T,
}

unsafe impl<T> std::marker::Sync for OneThread<T> {}
unsafe impl<T> std::marker::Send for OneThread<T> {}

impl<T> OneThread<T> {
    #[inline(always)]
    fn check(&self) {
        #[cfg(parallel_queries)]
        assert_eq!(thread::current().id(), self.thread);
    }

    #[inline(always)]
    pub fn new(inner: T) -> Self {
        OneThread {
            #[cfg(parallel_queries)]
            thread: thread::current().id(),
            inner,
        }
    }

    #[inline(always)]
    pub fn into_inner(value: Self) -> T {
        value.check();
        value.inner
    }
}

impl<T> Deref for OneThread<T> {
    type Target = T;

    fn deref(&self) -> &T {
        self.check();
        &self.inner
    }
}

impl<T> DerefMut for OneThread<T> {
    fn deref_mut(&mut self) -> &mut T {
        self.check();
        &mut self.inner
    }
}
<|endoftext|>


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

#![allow(non_snake_case)]

register_long_diagnostics! {
E0454: r##"
A link name was given with an empty name. Erroneous code example:

```
#[link(name = "")] extern {} // error: #[link(name = "")] given with empty name
```

The rust compiler cannot link to an external library if you don't give it its
name. Example:

```
#[link(name = "some_lib")] extern {} // ok!
```
"##,

E0458: r##"
An unknown "kind" was specified for a link attribute. Erroneous code example:

```
#[link(kind = "wonderful_unicorn")] extern {}
// error: unknown kind: `wonderful_unicorn`
```

Please specify a valid "kind" value, from one of the following:
 * static
 * dylib
 * framework
"##,

E0459: r##"
A link was used without a name parameter. Erroneous code example:

```
#[link(kind = "dylib")] extern {}
// error: #[link(...)] specified without `name = "foo"`
```

Please add the name parameter to allow the rust compiler to find the library
you want. Example:

```
#[link(kind = "dylib", name = "some_lib")] extern {} // ok!
```
"##,

E0463: r##"
A plugin/crate was declared but cannot be found. Erroneous code example:

```
#![feature(plugin)]
#![plugin(cookie_monster)] // error: can't find crate for `cookie_monster`
extern crate cake_is_a_lie; // error: can't find crate for `cake_is_a_lie`
```

You need to link your code to the relevant crate in order to be able to use it
(through Cargo or the `-L` option of rustc example). Plugins are crates as
well, and you link to them the same way.
"##,

}

register_diagnostics! {
    E0455, // native frameworks are only available on OSX targets
    E0456, // plugin `..` is not available for triple `..`
    E0457, // plugin `..` only found in rlib format, but must be available...
    E0514, // metadata version mismatch
    E0460, // found possibly newer version of crate `..`
    E0461, // couldn't find crate `..` with expected target triple ..
    E0462, // found staticlib `..` instead of rlib or dylib
    E0464, // multiple matching crates for `..`
    E0465, // multiple .. candidates for `..` found
    E0466, // bad macro import
    E0467, // bad macro reexport
    E0468, // an `extern crate` loading macros must be at the crate root
    E0469, // imported macro not found
    E0470, // reexported macro not found
    E0519, // local crate and dependency have same (crate-name, disambiguator)
    E0523, // two dependencies have same (crate-name, disambiguator) but different SVH
}
<commit_msg>Add error description for E0455<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.

#![allow(non_snake_case)]

register_long_diagnostics! {
E0454: r##"
A link name was given with an empty name. Erroneous code example:

```
#[link(name = "")] extern {} // error: #[link(name = "")] given with empty name
```

The rust compiler cannot link to an external library if you don't give it its
name. Example:

```
#[link(name = "some_lib")] extern {} // ok!
```
"##,

E0455: r##"
Linking with `kind=framework` is only supported when targeting OS X,
as frameworks are specific to that operating system.

Erroneous code example:

```compile_fail"
#[link(name = "FooCoreServices",  kind = "framework")] extern {}
// OS used to compile is Linux for example
```

To solve this error you can use conditional compilation:

```
#[cfg_attr(target="macos", link(name = "FooCoreServices", kind = "framework"))]
extern {}
```

See more: https://doc.rust-lang.org/book/conditional-compilation.html
"##,

E0458: r##"
An unknown "kind" was specified for a link attribute. Erroneous code example:

```
#[link(kind = "wonderful_unicorn")] extern {}
// error: unknown kind: `wonderful_unicorn`
```

Please specify a valid "kind" value, from one of the following:
 * static
 * dylib
 * framework
"##,

E0459: r##"
A link was used without a name parameter. Erroneous code example:

```
#[link(kind = "dylib")] extern {}
// error: #[link(...)] specified without `name = "foo"`
```

Please add the name parameter to allow the rust compiler to find the library
you want. Example:

```
#[link(kind = "dylib", name = "some_lib")] extern {} // ok!
```
"##,

E0463: r##"
A plugin/crate was declared but cannot be found. Erroneous code example:

```
#![feature(plugin)]
#![plugin(cookie_monster)] // error: can't find crate for `cookie_monster`
extern crate cake_is_a_lie; // error: can't find crate for `cake_is_a_lie`
```

You need to link your code to the relevant crate in order to be able to use it
(through Cargo or the `-L` option of rustc example). Plugins are crates as
well, and you link to them the same way.
"##,

}

register_diagnostics! {
    E0456, // plugin `..` is not available for triple `..`
    E0457, // plugin `..` only found in rlib format, but must be available...
    E0514, // metadata version mismatch
    E0460, // found possibly newer version of crate `..`
    E0461, // couldn't find crate `..` with expected target triple ..
    E0462, // found staticlib `..` instead of rlib or dylib
    E0464, // multiple matching crates for `..`
    E0465, // multiple .. candidates for `..` found
    E0466, // bad macro import
    E0467, // bad macro reexport
    E0468, // an `extern crate` loading macros must be at the crate root
    E0469, // imported macro not found
    E0470, // reexported macro not found
    E0519, // local crate and dependency have same (crate-name, disambiguator)
    E0523, // two dependencies have same (crate-name, disambiguator) but different SVH
}
<|endoftext|>


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

use core::ops::{Deref, DerefMut};
use core::{mem, slice};

#[derive(Copy, Clone, Debug, Default)]
#[repr(packed)]
pub struct Stat {
    pub st_dev: u64,
    pub st_ino: u64,
    pub st_mode: u16,
    pub st_nlink: u32,
    pub st_uid: u32,
    pub st_gid: u32,
    pub st_size: u64,
    pub st_blksize: u32,
    pub st_blocks: u64,
    pub st_mtime: u64,
    pub st_mtime_nsec: u32,
    pub st_atime: u64,
    pub st_atime_nsec: u32,
    pub st_ctime: u64,
    pub st_ctime_nsec: u32,
}

impl Deref for Stat {
    type Target = [u8];
    fn deref(&self) -> &[u8] {
        unsafe {
            slice::from_raw_parts(self as *const Stat as *const u8,
                                  mem::size_of::<Stat>()) as &[u8]
        }
    }
}

impl DerefMut for Stat {
    fn deref_mut(&mut self) -> &mut [u8] {
        unsafe {
            slice::from_raw_parts_mut(self as *mut Stat as *mut u8,
                                      mem::size_of::<Stat>()) as &mut [u8]
        }
    }
}

#[derive(Copy, Clone, Debug, Default)]
#[repr(packed)]
pub struct StatVfs {
    pub f_bsize: u32,
    pub f_blocks: u64,
    pub f_bfree: u64,
    pub f_bavail: u64,
}

impl Deref for StatVfs {
    type Target = [u8];
    fn deref(&self) -> &[u8] {
        unsafe {
            slice::from_raw_parts(self as *const StatVfs as *const u8,
                                  mem::size_of::<StatVfs>()) as &[u8]
        }
    }
}

impl DerefMut for StatVfs {
    fn deref_mut(&mut self) -> &mut [u8] {
        unsafe {
            slice::from_raw_parts_mut(self as *mut StatVfs as *mut u8,
                                      mem::size_of::<StatVfs>()) as &mut [u8]
        }
    }
}

#[derive(Copy, Clone, Debug, Default)]
#[repr(packed)]
pub struct TimeSpec {
    pub tv_sec: i64,
    pub tv_nsec: i32,
}

impl Deref for TimeSpec {
    type Target = [u8];
    fn deref(&self) -> &[u8] {
        unsafe {
            slice::from_raw_parts(self as *const TimeSpec as *const u8,
                                  mem::size_of::<TimeSpec>()) as &[u8]
        }
    }
}

impl DerefMut for TimeSpec {
    fn deref_mut(&mut self) -> &mut [u8] {
        unsafe {
            slice::from_raw_parts_mut(self as *mut TimeSpec as *mut u8,
                                      mem::size_of::<TimeSpec>()) as &mut [u8]
        }
    }
}
<commit_msg>Auto merge of #42398 - redox-os:master, r=sfackler<commit_after>// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use core::ops::{Deref, DerefMut};
use core::{mem, slice};

#[derive(Copy, Clone, Debug, Default)]
#[repr(C)]
pub struct Stat {
    pub st_dev: u64,
    pub st_ino: u64,
    pub st_mode: u16,
    pub st_nlink: u32,
    pub st_uid: u32,
    pub st_gid: u32,
    pub st_size: u64,
    pub st_blksize: u32,
    pub st_blocks: u64,
    pub st_mtime: u64,
    pub st_mtime_nsec: u32,
    pub st_atime: u64,
    pub st_atime_nsec: u32,
    pub st_ctime: u64,
    pub st_ctime_nsec: u32,
}

impl Deref for Stat {
    type Target = [u8];
    fn deref(&self) -> &[u8] {
        unsafe {
            slice::from_raw_parts(self as *const Stat as *const u8,
                                  mem::size_of::<Stat>()) as &[u8]
        }
    }
}

impl DerefMut for Stat {
    fn deref_mut(&mut self) -> &mut [u8] {
        unsafe {
            slice::from_raw_parts_mut(self as *mut Stat as *mut u8,
                                      mem::size_of::<Stat>()) as &mut [u8]
        }
    }
}

#[derive(Copy, Clone, Debug, Default)]
#[repr(C)]
pub struct StatVfs {
    pub f_bsize: u32,
    pub f_blocks: u64,
    pub f_bfree: u64,
    pub f_bavail: u64,
}

impl Deref for StatVfs {
    type Target = [u8];
    fn deref(&self) -> &[u8] {
        unsafe {
            slice::from_raw_parts(self as *const StatVfs as *const u8,
                                  mem::size_of::<StatVfs>()) as &[u8]
        }
    }
}

impl DerefMut for StatVfs {
    fn deref_mut(&mut self) -> &mut [u8] {
        unsafe {
            slice::from_raw_parts_mut(self as *mut StatVfs as *mut u8,
                                      mem::size_of::<StatVfs>()) as &mut [u8]
        }
    }
}

#[derive(Copy, Clone, Debug, Default)]
#[repr(C)]
pub struct TimeSpec {
    pub tv_sec: i64,
    pub tv_nsec: i32,
}

impl Deref for TimeSpec {
    type Target = [u8];
    fn deref(&self) -> &[u8] {
        unsafe {
            slice::from_raw_parts(self as *const TimeSpec as *const u8,
                                  mem::size_of::<TimeSpec>()) as &[u8]
        }
    }
}

impl DerefMut for TimeSpec {
    fn deref_mut(&mut self) -> &mut [u8] {
        unsafe {
            slice::from_raw_parts_mut(self as *mut TimeSpec as *mut u8,
                                      mem::size_of::<TimeSpec>()) as &mut [u8]
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>save game works<commit_after><|endoftext|>


<commit_before><commit_msg>if else<commit_after>fn main() {
    let foo = 5;
    if foo == 5 {
        println!("It works");
    } else if foo == 6 {
        println!("it's six");
    }else{
        println!("It's not five or six");
    }
}
<|endoftext|>


<commit_before><commit_msg>add window.rs<commit_after>extern crate libc;
extern crate x11;

use x11::xlib;
use super::super::libx;

const CWX: libc::c_uint = 1<<0;
const CWY: libc::c_uint = 1<<1;
const CWWidth: libc::c_uint = 1<<2;
const CWHeight: libc::c_uint = 1<<3;
const CWBorderWidth: libc::c_uint = 1<<4;
const CWSibling: libc::c_uint =	1<<5;
const CWStackMode: libc::c_uint = 1<<6;

#[derive(Debug, Copy, Clone)]
pub struct Window {
    pub id: xlib::Window,
    context: libx::Context,
}

impl PartialEq for Window {
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id
    }
}

impl Window {
    pub fn new(context: libx::Context, id: xlib::Window) -> Window{
        Window {
            context: context,
            id: id
        }
    }

    pub fn root(context: libx::Context, screen_num: libc::c_int) -> Window {
        let root = libx::root_window(context, screen_num);
        Window {
            context: context,
            id: root,
        }
    }

    pub fn configure(&self, x: i32, y: i32, width: i32, height: i32) {
        let mask = CWX | CWY | CWHeight | CWWidth;

        let mut change = xlib::XWindowChanges {
            x: x,
            y: y,
            width: width,
            height: height,
            border_width: 0,
            sibling: 0,
            stack_mode: 0
        };
        libx::configure_window(self.context, self.id, mask, change);
    }

    pub fn map(&self) {
        libx::map_window(self.context, self.id);
    }

    pub fn unmap(&self) {
        libx::unmap_window(self.context, self.id);
    }

    pub fn focus(&self) {
        libx::set_input_focus(self.context, self.id);
    }
}

#[test]
fn window_eq() {
    use std::ptr;
    let c1 = libx::Context {
        display: ptr::null_mut()
    };
    let w1 = Window::new(c1, 1);
    let c2 = libx::Context {
        display: ptr::null_mut()
    };
    let w2 = Window::new(c2, 1);
    assert_eq!(w1, w2);
}
<|endoftext|>