<commit_before>use std::convert::Into;

use chrono::naive::datetime::NaiveDateTime;
use chrono::naive::time::NaiveTime;
use chrono::naive::date::NaiveDate;
use chrono::Datelike;
use chrono::Timelike;

use libimagstore::storeid::StoreId;
use libimagstore::storeid::IntoStoreId;

use module_path::ModuleEntryPath;

#[derive(Debug, Clone)]
pub struct DiaryId {
    name: String,
    year: i32,
    month: u32,
    day: u32,
    hour: u32,
    minute: u32,
}

impl DiaryId {

    pub fn new(name: String, y: i32, m: u32, d: u32, h: u32, min: u32) -> DiaryId {
        DiaryId {
            name: name,
            year: y,
            month: m,
            day: d,
            hour: h,
            minute: min,
        }
    }

    pub fn from_datetime<DT: Datelike + Timelike>(diary_name: String, dt: DT) -> DiaryId {
        DiaryId::new(diary_name, dt.year(), dt.month(), dt.day(), dt.hour(), dt.minute())
    }

    pub fn diary_name(&self) -> &String {
        &self.name
    }

    pub fn year(&self) -> i32 {
        self.year
    }

    pub fn month(&self) -> u32 {
        self.month
    }

    pub fn day(&self) -> u32 {
        self.day
    }

    pub fn hour(&self) -> u32 {
        self.hour
    }

    pub fn minute(&self) -> u32 {
        self.minute
    }

}

impl IntoStoreId for DiaryId {

    fn into_storeid(self) -> StoreId {
        let s : String = self.into();
        ModuleEntryPath::new(s).into_storeid()
    }

}

impl Into<String> for DiaryId {

    fn into(self) -> String {
        format!("{}/{:0>4}/{:0>2}/{:0>2}/{:0>2}:{:0>2}",
                self.name, self.year, self.month, self.day, self.hour, self.minute)
    }

}

impl Into<NaiveDateTime> for DiaryId {

    fn into(self) -> NaiveDateTime {
        let d = NaiveDate::from_ymd(self.year, self.month, self.day);
        let t = NaiveTime::from_hms(self.hour, self.minute, 0);
        NaiveDateTime::new(d, t)
    }

}

pub trait FromStoreId : Sized {

    fn from_storeid(&StoreId) -> Option<Self>;

}

use std::path::Component;

fn component_to_str<'a>(com: Component<'a>) -> Option<&'a str> {
    match com {
        Component::Normal(s) => Some(s),
        _ => None
    }.and_then(|s| s.to_str())
}

impl FromStoreId for DiaryId {

    fn from_storeid(s: &StoreId) -> Option<DiaryId> {
        use std::str::FromStr;

        let mut cmps   = s.components().rev();
        let (hour, minute) = match cmps.next().and_then(component_to_str)
            .and_then(|time| {
                let mut time = time.split(":");
                let hour     = time.next().and_then(|s| FromStr::from_str(s).ok());
                let minute   = time.next()
                    .and_then(|s| s.split("~").next())
                    .and_then(|s| FromStr::from_str(s).ok());

                debug!("Hour   = {:?}", hour);
                debug!("Minute = {:?}", minute);

                match (hour, minute) {
                    (Some(h), Some(m)) => Some((h, m)),
                    _ => None,
                }
            })
        {
            Some(s) => s,
            None => return None,
        };

        let day   :Option<u32> = cmps.next().and_then(component_to_str).and_then(|s| FromStr::from_str(s).ok());
        let month :Option<u32> = cmps.next().and_then(component_to_str).and_then(|s| FromStr::from_str(s).ok());
        let year  :Option<i32> = cmps.next().and_then(component_to_str).and_then(|s| FromStr::from_str(s).ok());
        let name       = cmps.next().and_then(component_to_str).map(String::from);

        debug!("Day   = {:?}", day);
        debug!("Month = {:?}", month);
        debug!("Year  = {:?}", year);
        debug!("Name  = {:?}", name);

        let day    = if day.is_none()    { return None; } else { day.unwrap() };
        let month  = if month.is_none()  { return None; } else { month.unwrap() };
        let year   = if year.is_none()   { return None; } else { year.unwrap() };
        let name   = if name.is_none()   { return None; } else { name.unwrap() };

        Some(DiaryId::new(name, year, month, day, hour, minute))
    }

}

<commit_msg>Add setters for DiaryId type<commit_after>use std::convert::Into;

use chrono::naive::datetime::NaiveDateTime;
use chrono::naive::time::NaiveTime;
use chrono::naive::date::NaiveDate;
use chrono::Datelike;
use chrono::Timelike;

use libimagstore::storeid::StoreId;
use libimagstore::storeid::IntoStoreId;

use module_path::ModuleEntryPath;

#[derive(Debug, Clone)]
pub struct DiaryId {
    name: String,
    year: i32,
    month: u32,
    day: u32,
    hour: u32,
    minute: u32,
}

impl DiaryId {

    pub fn new(name: String, y: i32, m: u32, d: u32, h: u32, min: u32) -> DiaryId {
        DiaryId {
            name: name,
            year: y,
            month: m,
            day: d,
            hour: h,
            minute: min,
        }
    }

    pub fn from_datetime<DT: Datelike + Timelike>(diary_name: String, dt: DT) -> DiaryId {
        DiaryId::new(diary_name, dt.year(), dt.month(), dt.day(), dt.hour(), dt.minute())
    }

    pub fn diary_name(&self) -> &String {
        &self.name
    }

    pub fn year(&self) -> i32 {
        self.year
    }

    pub fn month(&self) -> u32 {
        self.month
    }

    pub fn day(&self) -> u32 {
        self.day
    }

    pub fn hour(&self) -> u32 {
        self.hour
    }

    pub fn minute(&self) -> u32 {
        self.minute
    }

    pub fn with_diary_name(mut self, name: String) -> DiaryId {
        self.name = name;
        self
    }

    pub fn with_year(mut self, year: i32) -> DiaryId {
        self.year = year;
        self
    }

    pub fn with_month(mut self, month: u32) -> DiaryId {
        self.month = month;
        self
    }

    pub fn with_day(mut self, day: u32) -> DiaryId {
        self.day = day;
        self
    }

    pub fn with_hour(mut self, hour: u32) -> DiaryId {
        self.hour = hour;
        self
    }

    pub fn with_minute(mut self, minute: u32) -> DiaryId {
        self.minute = minute;
        self
    }

}

impl IntoStoreId for DiaryId {

    fn into_storeid(self) -> StoreId {
        let s : String = self.into();
        ModuleEntryPath::new(s).into_storeid()
    }

}

impl Into<String> for DiaryId {

    fn into(self) -> String {
        format!("{}/{:0>4}/{:0>2}/{:0>2}/{:0>2}:{:0>2}",
                self.name, self.year, self.month, self.day, self.hour, self.minute)
    }

}

impl Into<NaiveDateTime> for DiaryId {

    fn into(self) -> NaiveDateTime {
        let d = NaiveDate::from_ymd(self.year, self.month, self.day);
        let t = NaiveTime::from_hms(self.hour, self.minute, 0);
        NaiveDateTime::new(d, t)
    }

}

pub trait FromStoreId : Sized {

    fn from_storeid(&StoreId) -> Option<Self>;

}

use std::path::Component;

fn component_to_str<'a>(com: Component<'a>) -> Option<&'a str> {
    match com {
        Component::Normal(s) => Some(s),
        _ => None
    }.and_then(|s| s.to_str())
}

impl FromStoreId for DiaryId {

    fn from_storeid(s: &StoreId) -> Option<DiaryId> {
        use std::str::FromStr;

        let mut cmps   = s.components().rev();
        let (hour, minute) = match cmps.next().and_then(component_to_str)
            .and_then(|time| {
                let mut time = time.split(":");
                let hour     = time.next().and_then(|s| FromStr::from_str(s).ok());
                let minute   = time.next()
                    .and_then(|s| s.split("~").next())
                    .and_then(|s| FromStr::from_str(s).ok());

                debug!("Hour   = {:?}", hour);
                debug!("Minute = {:?}", minute);

                match (hour, minute) {
                    (Some(h), Some(m)) => Some((h, m)),
                    _ => None,
                }
            })
        {
            Some(s) => s,
            None => return None,
        };

        let day   :Option<u32> = cmps.next().and_then(component_to_str).and_then(|s| FromStr::from_str(s).ok());
        let month :Option<u32> = cmps.next().and_then(component_to_str).and_then(|s| FromStr::from_str(s).ok());
        let year  :Option<i32> = cmps.next().and_then(component_to_str).and_then(|s| FromStr::from_str(s).ok());
        let name       = cmps.next().and_then(component_to_str).map(String::from);

        debug!("Day   = {:?}", day);
        debug!("Month = {:?}", month);
        debug!("Year  = {:?}", year);
        debug!("Name  = {:?}", name);

        let day    = if day.is_none()    { return None; } else { day.unwrap() };
        let month  = if month.is_none()  { return None; } else { month.unwrap() };
        let year   = if year.is_none()   { return None; } else { year.unwrap() };
        let name   = if name.is_none()   { return None; } else { name.unwrap() };

        Some(DiaryId::new(name, year, month, day, hour, minute))
    }

}

<|endoftext|>


<commit_before>use std::path::PathBuf;
use glob::Paths;

/// The Index into the Store
pub type StoreId = PathBuf;

/// This Trait allows you to convert various representations to a single one
/// suitable for usage in the Store
trait IntoStoreId {
    fn into_storeid(self) -> StoreId;
}

impl IntoStoreId for PathBuf {
    fn into_storeid(self) -> StoreId {
        self
    }
}

#[macro_export]
macro_rules! module_entry_path_mod {
    ($name:expr, $version:expr) => (
        #[deny(missing_docs,
                missing_copy_implementations,
                trivial_casts, trivial_numeric_casts,
                unsafe_code,
                unstable_features,
                unused_import_braces, unused_qualifications,
                unused_imports)]
        pub mod module_path {
            use semver::Version;
            use std::convert::AsRef;
            use std::path::Path;
            use std::path::PathBuf;

            /// A Struct giving you the ability to choose store entries assigned
            /// to it.
            ///
            /// It is created through a call to `new`.
            pub struct ModuleEntryPath(PathBuf);

            impl ModuleEntryPath {
                /// Path has to be a valid UTF-8 string or this will panic!
                pub fn new<P: AsRef<Path>>(pa: P) -> ModuleEntryPath {
                    let mut path = PathBuf::new();
                    path.push(format!("/{}", $name));
                    path.push(pa.as_ref().clone());
                    let version = Version::parse($version).unwrap();
                    let name = pa.as_ref().file_name().unwrap()
                        .to_str().unwrap();
                    path.set_file_name(format!("{}~{}",
                                               name,
                                               version));
                    ModuleEntryPath(path)
                }
            }

            impl $crate::storeid::IntoStoreId for ModuleEntryPath {
                fn into_storeid(mut self) -> $crate::storeid::StoreId {
                    self.0
                }
            }
        }
    )
}

pub struct StoreIdIterator {
    paths: Paths,
}

impl StoreIdIterator {

    pub fn new(paths: Paths) -> StoreIdIterator {
        StoreIdIterator {
            paths: paths,
        }
    }

}

impl Iterator for StoreIdIterator {
    type Item = StoreId;

    fn next(&mut self) -> Option<StoreId> {
        self.paths.next().and_then(|o| o.ok())
    }

}

#[cfg(test)]
mod test {

    use storeid::IntoStoreId;

    module_entry_path_mod!("test", "0.2.0-alpha+leet1337");

    #[test]
    fn correct_path() {
        let p = module_path::ModuleEntryPath::new("test");

        assert_eq!(p.into_storeid().to_str().unwrap(),
        "/test/test~0.2.0-alpha+leet1337");
    }

}
<commit_msg>Fix: Add missing documentation for mod module_path<commit_after>use std::path::PathBuf;
use glob::Paths;

/// The Index into the Store
pub type StoreId = PathBuf;

/// This Trait allows you to convert various representations to a single one
/// suitable for usage in the Store
trait IntoStoreId {
    fn into_storeid(self) -> StoreId;
}

impl IntoStoreId for PathBuf {
    fn into_storeid(self) -> StoreId {
        self
    }
}

#[macro_export]
macro_rules! module_entry_path_mod {
    ($name:expr, $version:expr) => (
        #[deny(missing_docs,
                missing_copy_implementations,
                trivial_casts, trivial_numeric_casts,
                unsafe_code,
                unstable_features,
                unused_import_braces, unused_qualifications,
                unused_imports)]
        /// A helper module to create valid module entry paths
        pub mod module_path {
            use semver::Version;
            use std::convert::AsRef;
            use std::path::Path;
            use std::path::PathBuf;

            /// A Struct giving you the ability to choose store entries assigned
            /// to it.
            ///
            /// It is created through a call to `new`.
            pub struct ModuleEntryPath(PathBuf);

            impl ModuleEntryPath {
                /// Path has to be a valid UTF-8 string or this will panic!
                pub fn new<P: AsRef<Path>>(pa: P) -> ModuleEntryPath {
                    let mut path = PathBuf::new();
                    path.push(format!("/{}", $name));
                    path.push(pa.as_ref().clone());
                    let version = Version::parse($version).unwrap();
                    let name = pa.as_ref().file_name().unwrap()
                        .to_str().unwrap();
                    path.set_file_name(format!("{}~{}",
                                               name,
                                               version));
                    ModuleEntryPath(path)
                }
            }

            impl $crate::storeid::IntoStoreId for ModuleEntryPath {
                fn into_storeid(mut self) -> $crate::storeid::StoreId {
                    self.0
                }
            }
        }
    )
}

pub struct StoreIdIterator {
    paths: Paths,
}

impl StoreIdIterator {

    pub fn new(paths: Paths) -> StoreIdIterator {
        StoreIdIterator {
            paths: paths,
        }
    }

}

impl Iterator for StoreIdIterator {
    type Item = StoreId;

    fn next(&mut self) -> Option<StoreId> {
        self.paths.next().and_then(|o| o.ok())
    }

}

#[cfg(test)]
mod test {

    use storeid::IntoStoreId;

    module_entry_path_mod!("test", "0.2.0-alpha+leet1337");

    #[test]
    fn correct_path() {
        let p = module_path::ModuleEntryPath::new("test");

        assert_eq!(p.into_storeid().to_str().unwrap(),
        "/test/test~0.2.0-alpha+leet1337");
    }

}
<|endoftext|>


<commit_before><commit_msg>Add bindings/templates.rs example<commit_after>use std::marker::PhantomData;

// defined in accuse crate
trait Wraps<T> {
    fn from_wrapped(other: T) -> Self;
    fn into_wrapped(self) -> T;
}

trait BridgeFrom<T> {
    fn bridge_from(other: T) -> Self;
}

trait BridgeTo<T> {
    fn bridge(self) -> T;
}
impl<T, U> BridgeTo<U> for T
where
    U: BridgeFrom<T>,
{
    fn bridge(self) -> U {
        U::bridge_from(self)
    }
}

// defined in the "root" crate, my_vec, wrapping our C++ library.
cc_use!(<vector> in libstdc++, std::vector); // or maybe:
cc_bind!(<vector> in libstdc++ as vector, std::vector);
pub use vector::*;
// ^ `in libstdc++` is so we can grab relevant CFLAGS from metadata
// ^ expands to:
// extern crate libstdc_bind_my_vec;
// use libstdc_bind_my_vec::vector;

unsafe trait InstantiatesVector<T> {
    type Repr;
    const INSTANCE_HASH: usize;

    // maybe some methods can go here, if we determine / mark them as universal?
}

// defined in local instantiating crate
cc_use!(my_vec::vector::{<i32>, <bool>});
// ^ expands to:
// use my_vec::InstantiatesVector;  // we can infer it's generic, so we need the trait
// extern crate libstdc_bind_local;
// use libstdc_bind_local::{prelude::*, vector};
use remote::remote;

//  in libstdc_bind_local:
trait HasLocalVectorInstance {
    type Repr;
}
struct LocalVectorReprI32;
#[repr(transparent)]
struct LocalVector<T: HasLocalVectorInstance>(T::Repr);

impl HasLocalVectorInstance for i32 {
    type Repr = LocalVectorReprI32;
}
unsafe impl InstantiatesVector<i32> for LocalVector<i32> {
    type Repr = LocalVectorReprI32;
    const INSTANCE_HASH: usize = 0xdeadbeef;
}

impl<T: InstantiatesVector<U>, U: HasLocalVectorInstance> BridgeFrom<T> for LocalVector<U> {
    fn bridge_from(mut other: T) -> Self {
        // TODO: static assert that INSTANCE_HASH, sizes are equal
        unsafe { std::ptr::read(&mut other as *mut T as *mut Self) }
    }
}

//  in local:
fn local(x: LocalVector<i32>) {
    remote(x.bridge())
}

// defined in remote instantiating crate
cc_use!(my_vec::vector::{<i32>});
trait HasRemoteVectorInstance {
    type Repr;
}
struct RemoteVectorReprI32;
#[repr(transparent)]
struct RemoteVector<T: HasRemoteVectorInstance>(T::Repr);

impl HasRemoteVectorInstance for i32 {
    type Repr = RemoteVectorReprI32;
}
unsafe impl InstantiatesVector<i32> for RemoteVector<i32> {
    type Repr = RemoteVectorReprI32;
    const INSTANCE_HASH: usize = 0xdeadbeef;
}

impl<T: InstantiatesVector<U>, U: HasRemoteVectorInstance> BridgeFrom<T> for RemoteVector<U> {
    fn bridge_from(mut other: T) -> Self {
        // TODO: static assert that INSTANCE_HASH, sizes are equal
        unsafe { std::ptr::read(&mut other as *mut T as *mut Self) }
    }
}

fn remote(_x: RemoteVector<i32>) {}
<|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:

```compile_fail,E0454
#[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,E0455
#[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:

```compile_fail,E0458
#[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:

```compile_fail,E0459
#[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:

```compile_fail,E0463
#![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.
"##,

E0466: r##"
Macro import declarations were malformed.

Erroneous code examples:

```compile_fail,E0466
#[macro_use(a_macro(another_macro))] // error: invalid import declaration
extern crate some_crate;

#[macro_use(i_want = "some_macros")] // error: invalid import declaration
extern crate another_crate;
```

This is a syntax error at the level of attribute declarations. The proper
syntax for macro imports is the following:

```ignore
// In some_crate:
#[macro_export]
macro_rules! get_tacos {
    ...
}

#[macro_export]
macro_rules! get_pimientos {
    ...
}

// In your crate:
#[macro_use(get_tacos, get_pimientos)] // It imports `get_tacos` and
extern crate some_crate;               // `get_pimientos` macros from some_crate.
```

If you would like to import all exported macros, write `macro_use` with no
arguments.
"##,

E0467: r##"
Macro reexport declarations were empty or malformed.

Erroneous code examples:

```compile_fail,E0467
#[macro_reexport]                    // error: no macros listed for export
extern crate macros_for_good;

#[macro_reexport(fun_macro = "foo")] // error: not a macro identifier
extern crate other_macros_for_good;
```

This is a syntax error at the level of attribute declarations.

Currently, `macro_reexport` requires at least one macro name to be listed.
Unlike `macro_use`, listing no names does not reexport all macros from the
given crate.

Decide which macros you would like to export and list them properly.

These are proper reexport declarations:

```ignore
#[macro_reexport(some_macro, another_macro)]
extern crate macros_for_good;
```
"##,

E0468: r##"
A non-root module attempts to import macros from another crate.

Example of erroneous code:

```compile_fail,E0468
mod foo {
    #[macro_use(helpful_macro)] // error: must be at crate root to import
    extern crate some_crate;    //        macros from another crate
    helpful_macro!(...)
}
```

Only `extern crate` imports at the crate root level are allowed to import
macros.

Either move the macro import to crate root or do without the foreign macros.
This will work:

```ignore
#[macro_use(helpful_macro)]
extern crate some_crate;

mod foo {
    helpful_macro!(...)
}
```
"##,
}

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
    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 E0469 error explanation<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:

```compile_fail,E0454
#[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,E0455
#[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:

```compile_fail,E0458
#[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:

```compile_fail,E0459
#[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:

```compile_fail,E0463
#![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.
"##,

E0466: r##"
Macro import declarations were malformed.

Erroneous code examples:

```compile_fail,E0466
#[macro_use(a_macro(another_macro))] // error: invalid import declaration
extern crate some_crate;

#[macro_use(i_want = "some_macros")] // error: invalid import declaration
extern crate another_crate;
```

This is a syntax error at the level of attribute declarations. The proper
syntax for macro imports is the following:

```ignore
// In some_crate:
#[macro_export]
macro_rules! get_tacos {
    ...
}

#[macro_export]
macro_rules! get_pimientos {
    ...
}

// In your crate:
#[macro_use(get_tacos, get_pimientos)] // It imports `get_tacos` and
extern crate some_crate;               // `get_pimientos` macros from some_crate.
```

If you would like to import all exported macros, write `macro_use` with no
arguments.
"##,

E0467: r##"
Macro reexport declarations were empty or malformed.

Erroneous code examples:

```compile_fail,E0467
#[macro_reexport]                    // error: no macros listed for export
extern crate macros_for_good;

#[macro_reexport(fun_macro = "foo")] // error: not a macro identifier
extern crate other_macros_for_good;
```

This is a syntax error at the level of attribute declarations.

Currently, `macro_reexport` requires at least one macro name to be listed.
Unlike `macro_use`, listing no names does not reexport all macros from the
given crate.

Decide which macros you would like to export and list them properly.

These are proper reexport declarations:

```ignore
#[macro_reexport(some_macro, another_macro)]
extern crate macros_for_good;
```
"##,

E0468: r##"
A non-root module attempts to import macros from another crate.

Example of erroneous code:

```compile_fail,E0468
mod foo {
    #[macro_use(helpful_macro)] // error: must be at crate root to import
    extern crate some_crate;    //        macros from another crate
    helpful_macro!(...)
}
```

Only `extern crate` imports at the crate root level are allowed to import
macros.

Either move the macro import to crate root or do without the foreign macros.
This will work:

```ignore
#[macro_use(helpful_macro)]
extern crate some_crate;

mod foo {
    helpful_macro!(...)
}
```
"##,

E0469: r##"
A macro listed for import was not found.

Erroneous code example:

```compile_fail,E0469
#[macro_use(drink, be_merry)] // error: imported macro not found
extern crate collections;

fn main() {
    // ...
}
```

Either the listed macro is not contained in the imported crate, or it is not
exported from the given crate.

This could be caused by a typo. Did you misspell the macro's name?

Double-check the names of the macros listed for import, and that the crate
in question exports them.

A working version would be:

```ignore
// In some_crate:
#[macro_export]
macro_rules! eat {
    ...
}

#[macro_export]
macro_rules! drink {
    ...
}

// In your crate:
#[macro_use(eat, drink)]
extern crate some_crate; //ok!
```
"##,

}

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
    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><commit_msg>Add test for Inherent static methods can be called with a non-well-formed Self-type.<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.

struct Foo<'a, 'b: 'a>(&'a &'b ());

impl<'a, 'b> Foo<'a, 'b> {
    fn xmute(a: &'b ()) -> &'a () {
        unreachable!()
    }
}

pub fn foo<'a, 'b>(u: &'b ()) -> &'a () {
    Foo::<'a, 'b>::xmute(u) //~ ERROR lifetime bound not satisfied
}

fn main() {}<|endoftext|>


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

// Check that we can use `-C lto` when linking against libraries that were
// separately compiled.

// aux-build:sepcomp_lib.rs
// compile-flags: -C lto -g
// no-prefer-dynamic
// ignore-android FIXME #18800

extern crate sepcomp_lib;
use sepcomp_lib::a::one;
use sepcomp_lib::b::two;
use sepcomp_lib::c::three;

fn main() {
    assert_eq!(one(), 1);
    assert_eq!(two(), 2);
    assert_eq!(three(), 3);
}
<commit_msg>Enable run-pass/sepcomp-lib-lto.rs on Android<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.

// Check that we can use `-C lto` when linking against libraries that were
// separately compiled.

// aux-build:sepcomp_lib.rs
// compile-flags: -C lto -g
// no-prefer-dynamic

extern crate sepcomp_lib;
use sepcomp_lib::a::one;
use sepcomp_lib::b::two;
use sepcomp_lib::c::three;

fn main() {
    assert_eq!(one(), 1);
    assert_eq!(two(), 2);
    assert_eq!(three(), 3);
}
<|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 std::rc::Rc;
use std::sync::Arc;

use base;
use monomorphize::Instance;
use rustc::hir::def_id::CrateNum;
use rustc::hir::def_id::{DefId, LOCAL_CRATE};
use rustc::middle::exported_symbols::SymbolExportLevel;
use rustc::session::config;
use rustc::ty::TyCtxt;
use rustc::ty::maps::Providers;
use rustc::util::nodemap::FxHashMap;
use rustc_allocator::ALLOCATOR_METHODS;
use syntax::attr;

pub type ExportedSymbols = FxHashMap<
    CrateNum,
    Arc<Vec<(String, Option<DefId>, SymbolExportLevel)>>,
>;

pub fn threshold(tcx: TyCtxt) -> SymbolExportLevel {
    crates_export_threshold(&tcx.sess.crate_types.borrow())
}

pub fn metadata_symbol_name(tcx: TyCtxt) -> String {
    format!("rust_metadata_{}_{}",
            tcx.crate_name(LOCAL_CRATE),
            tcx.crate_disambiguator(LOCAL_CRATE).to_fingerprint().to_hex())
}

fn crate_export_threshold(crate_type: config::CrateType) -> SymbolExportLevel {
    match crate_type {
        config::CrateTypeExecutable |
        config::CrateTypeStaticlib  |
        config::CrateTypeProcMacro  |
        config::CrateTypeCdylib     => SymbolExportLevel::C,
        config::CrateTypeRlib       |
        config::CrateTypeDylib      => SymbolExportLevel::Rust,
    }
}

pub fn crates_export_threshold(crate_types: &[config::CrateType])
                                      -> SymbolExportLevel {
    if crate_types.iter().any(|&crate_type| {
        crate_export_threshold(crate_type) == SymbolExportLevel::Rust
    }) {
        SymbolExportLevel::Rust
    } else {
        SymbolExportLevel::C
    }
}

pub fn provide_local(providers: &mut Providers) {
    providers.exported_symbol_ids = |tcx, cnum| {
        let export_threshold = threshold(tcx);
        Rc::new(tcx.exported_symbols(cnum)
            .iter()
            .filter_map(|&(_, id, level)| {
                id.and_then(|id| {
                    if level.is_below_threshold(export_threshold) {
                        Some(id)
                    } else {
                        None
                    }
                })
            })
            .collect())
    };

    providers.is_exported_symbol = |tcx, id| {
        tcx.exported_symbol_ids(id.krate).contains(&id)
    };

    providers.exported_symbols = |tcx, cnum| {
        assert_eq!(cnum, LOCAL_CRATE);
        let local_exported_symbols = base::find_exported_symbols(tcx);

        let mut local_crate: Vec<_> = local_exported_symbols
            .iter()
            .map(|&node_id| {
                tcx.hir.local_def_id(node_id)
            })
            .map(|def_id| {
                let name = tcx.symbol_name(Instance::mono(tcx, def_id));
                let export_level = export_level(tcx, def_id);
                debug!("EXPORTED SYMBOL (local): {} ({:?})", name, export_level);
                (str::to_owned(&name), Some(def_id), export_level)
            })
            .collect();

        if let Some(_) = *tcx.sess.entry_fn.borrow() {
            local_crate.push(("main".to_string(),
                              None,
                              SymbolExportLevel::C));
        }

        if tcx.sess.allocator_kind.get().is_some() {
            for method in ALLOCATOR_METHODS {
                local_crate.push((format!("__rust_{}", method.name),
                                  None,
                                  SymbolExportLevel::Rust));
            }
        }

        if let Some(id) = tcx.sess.derive_registrar_fn.get() {
            let def_id = tcx.hir.local_def_id(id);
            let idx = def_id.index;
            let disambiguator = tcx.sess.local_crate_disambiguator();
            let registrar = tcx.sess.generate_derive_registrar_symbol(disambiguator, idx);
            local_crate.push((registrar, Some(def_id), SymbolExportLevel::C));
        }

        if tcx.sess.crate_types.borrow().contains(&config::CrateTypeDylib) {
            local_crate.push((metadata_symbol_name(tcx),
                              None,
                              SymbolExportLevel::Rust));
        }
        Arc::new(local_crate)
    };
}

pub fn provide_extern(providers: &mut Providers) {
    providers.exported_symbols = |tcx, cnum| {
        // If this crate is a plugin and/or a custom derive crate, then
        // we're not even going to link those in so we skip those crates.
        if tcx.plugin_registrar_fn(cnum).is_some() ||
           tcx.derive_registrar_fn(cnum).is_some() {
            return Arc::new(Vec::new())
        }

        // Check to see if this crate is a "special runtime crate". These
        // crates, implementation details of the standard library, typically
        // have a bunch of `pub extern` and `#[no_mangle]` functions as the
        // ABI between them. We don't want their symbols to have a `C`
        // export level, however, as they're just implementation details.
        // Down below we'll hardwire all of the symbols to the `Rust` export
        // level instead.
        let special_runtime_crate =
            tcx.is_panic_runtime(cnum) || tcx.is_compiler_builtins(cnum);

        let crate_exports = tcx
            .exported_symbol_ids(cnum)
            .iter()
            .map(|&def_id| {
                let name = tcx.symbol_name(Instance::mono(tcx, def_id));
                let export_level = if special_runtime_crate {
                    // We can probably do better here by just ensuring that
                    // it has hidden visibility rather than public
                    // visibility, as this is primarily here to ensure it's
                    // not stripped during LTO.
                    //
                    // In general though we won't link right if these
                    // symbols are stripped, and LTO currently strips them.
                    if &*name == "rust_eh_personality" ||
                       &*name == "rust_eh_register_frames" ||
                       &*name == "rust_eh_unregister_frames" {
                        SymbolExportLevel::C
                    } else {
                        SymbolExportLevel::Rust
                    }
                } else {
                    export_level(tcx, def_id)
                };
                debug!("EXPORTED SYMBOL (re-export): {} ({:?})", name, export_level);
                (str::to_owned(&name), Some(def_id), export_level)
            })
            .collect();

        Arc::new(crate_exports)
    };
}

fn export_level(tcx: TyCtxt, sym_def_id: DefId) -> SymbolExportLevel {
    // We export anything that's not mangled at the "C" layer as it probably has
    // to do with ABI concerns. We do not, however, apply such treatment to
    // special symbols in the standard library for various plumbing between
    // core/std/allocators/etc. For example symbols used to hook up allocation
    // are not considered for export
    let is_extern = tcx.contains_extern_indicator(sym_def_id);
    let std_internal = attr::contains_name(&tcx.get_attrs(sym_def_id),
                                           "rustc_std_internal_symbol");
    if is_extern && !std_internal {
        SymbolExportLevel::C
    } else {
        SymbolExportLevel::Rust
    }
}
<commit_msg>incr.comp.: Sort exported symbols list in order to achieve stable incr. comp. hash.<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 std::rc::Rc;
use std::sync::Arc;

use base;
use monomorphize::Instance;
use rustc::hir::def_id::CrateNum;
use rustc::hir::def_id::{DefId, LOCAL_CRATE};
use rustc::middle::exported_symbols::SymbolExportLevel;
use rustc::session::config;
use rustc::ty::TyCtxt;
use rustc::ty::maps::Providers;
use rustc::util::nodemap::FxHashMap;
use rustc_allocator::ALLOCATOR_METHODS;
use syntax::attr;

pub type ExportedSymbols = FxHashMap<
    CrateNum,
    Arc<Vec<(String, Option<DefId>, SymbolExportLevel)>>,
>;

pub fn threshold(tcx: TyCtxt) -> SymbolExportLevel {
    crates_export_threshold(&tcx.sess.crate_types.borrow())
}

pub fn metadata_symbol_name(tcx: TyCtxt) -> String {
    format!("rust_metadata_{}_{}",
            tcx.crate_name(LOCAL_CRATE),
            tcx.crate_disambiguator(LOCAL_CRATE).to_fingerprint().to_hex())
}

fn crate_export_threshold(crate_type: config::CrateType) -> SymbolExportLevel {
    match crate_type {
        config::CrateTypeExecutable |
        config::CrateTypeStaticlib  |
        config::CrateTypeProcMacro  |
        config::CrateTypeCdylib     => SymbolExportLevel::C,
        config::CrateTypeRlib       |
        config::CrateTypeDylib      => SymbolExportLevel::Rust,
    }
}

pub fn crates_export_threshold(crate_types: &[config::CrateType])
                                      -> SymbolExportLevel {
    if crate_types.iter().any(|&crate_type| {
        crate_export_threshold(crate_type) == SymbolExportLevel::Rust
    }) {
        SymbolExportLevel::Rust
    } else {
        SymbolExportLevel::C
    }
}

pub fn provide_local(providers: &mut Providers) {
    providers.exported_symbol_ids = |tcx, cnum| {
        let export_threshold = threshold(tcx);
        Rc::new(tcx.exported_symbols(cnum)
            .iter()
            .filter_map(|&(_, id, level)| {
                id.and_then(|id| {
                    if level.is_below_threshold(export_threshold) {
                        Some(id)
                    } else {
                        None
                    }
                })
            })
            .collect())
    };

    providers.is_exported_symbol = |tcx, id| {
        tcx.exported_symbol_ids(id.krate).contains(&id)
    };

    providers.exported_symbols = |tcx, cnum| {
        assert_eq!(cnum, LOCAL_CRATE);
        let local_exported_symbols = base::find_exported_symbols(tcx);

        let mut local_crate: Vec<_> = local_exported_symbols
            .iter()
            .map(|&node_id| {
                tcx.hir.local_def_id(node_id)
            })
            .map(|def_id| {
                let name = tcx.symbol_name(Instance::mono(tcx, def_id));
                let export_level = export_level(tcx, def_id);
                debug!("EXPORTED SYMBOL (local): {} ({:?})", name, export_level);
                (str::to_owned(&name), Some(def_id), export_level)
            })
            .collect();

        if let Some(_) = *tcx.sess.entry_fn.borrow() {
            local_crate.push(("main".to_string(),
                              None,
                              SymbolExportLevel::C));
        }

        if tcx.sess.allocator_kind.get().is_some() {
            for method in ALLOCATOR_METHODS {
                local_crate.push((format!("__rust_{}", method.name),
                                  None,
                                  SymbolExportLevel::Rust));
            }
        }

        if let Some(id) = tcx.sess.derive_registrar_fn.get() {
            let def_id = tcx.hir.local_def_id(id);
            let idx = def_id.index;
            let disambiguator = tcx.sess.local_crate_disambiguator();
            let registrar = tcx.sess.generate_derive_registrar_symbol(disambiguator, idx);
            local_crate.push((registrar, Some(def_id), SymbolExportLevel::C));
        }

        if tcx.sess.crate_types.borrow().contains(&config::CrateTypeDylib) {
            local_crate.push((metadata_symbol_name(tcx),
                              None,
                              SymbolExportLevel::Rust));
        }

        // Sort so we get a stable incr. comp. hash.
        local_crate.sort_unstable_by(|&(ref name1, ..), &(ref name2, ..)| {
            name1.cmp(name2)
        });

        Arc::new(local_crate)
    };
}

pub fn provide_extern(providers: &mut Providers) {
    providers.exported_symbols = |tcx, cnum| {
        // If this crate is a plugin and/or a custom derive crate, then
        // we're not even going to link those in so we skip those crates.
        if tcx.plugin_registrar_fn(cnum).is_some() ||
           tcx.derive_registrar_fn(cnum).is_some() {
            return Arc::new(Vec::new())
        }

        // Check to see if this crate is a "special runtime crate". These
        // crates, implementation details of the standard library, typically
        // have a bunch of `pub extern` and `#[no_mangle]` functions as the
        // ABI between them. We don't want their symbols to have a `C`
        // export level, however, as they're just implementation details.
        // Down below we'll hardwire all of the symbols to the `Rust` export
        // level instead.
        let special_runtime_crate =
            tcx.is_panic_runtime(cnum) || tcx.is_compiler_builtins(cnum);

        let mut crate_exports: Vec<_> = tcx
            .exported_symbol_ids(cnum)
            .iter()
            .map(|&def_id| {
                let name = tcx.symbol_name(Instance::mono(tcx, def_id));
                let export_level = if special_runtime_crate {
                    // We can probably do better here by just ensuring that
                    // it has hidden visibility rather than public
                    // visibility, as this is primarily here to ensure it's
                    // not stripped during LTO.
                    //
                    // In general though we won't link right if these
                    // symbols are stripped, and LTO currently strips them.
                    if &*name == "rust_eh_personality" ||
                       &*name == "rust_eh_register_frames" ||
                       &*name == "rust_eh_unregister_frames" {
                        SymbolExportLevel::C
                    } else {
                        SymbolExportLevel::Rust
                    }
                } else {
                    export_level(tcx, def_id)
                };
                debug!("EXPORTED SYMBOL (re-export): {} ({:?})", name, export_level);
                (str::to_owned(&name), Some(def_id), export_level)
            })
            .collect();

        // Sort so we get a stable incr. comp. hash.
        crate_exports.sort_unstable_by(|&(ref name1, ..), &(ref name2, ..)| {
            name1.cmp(name2)
        });

        Arc::new(crate_exports)
    };
}

fn export_level(tcx: TyCtxt, sym_def_id: DefId) -> SymbolExportLevel {
    // We export anything that's not mangled at the "C" layer as it probably has
    // to do with ABI concerns. We do not, however, apply such treatment to
    // special symbols in the standard library for various plumbing between
    // core/std/allocators/etc. For example symbols used to hook up allocation
    // are not considered for export
    let is_extern = tcx.contains_extern_indicator(sym_def_id);
    let std_internal = attr::contains_name(&tcx.get_attrs(sym_def_id),
                                           "rustc_std_internal_symbol");
    if is_extern && !std_internal {
        SymbolExportLevel::C
    } else {
        SymbolExportLevel::Rust
    }
}
<|endoftext|>


<commit_before><commit_msg>languages/rust/learn-rust/3-chapter/7-code.rs<commit_after><|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.

// This test case tests the incremental compilation hash (ICH) implementation
// for let expressions.

// The general pattern followed here is: Change one thing between rev1 and rev2
// and make sure that the hash has changed, then change nothing between rev2 and
// rev3 and make sure that the hash has not changed.

// must-compile-successfully
// revisions: cfail1 cfail2 cfail3
// compile-flags: -Z query-dep-graph

#![allow(warnings)]
#![feature(rustc_attrs)]
#![crate_type="rlib"]

struct Foo;

// Change Method Name -----------------------------------------------------------
#[cfg(cfail1)]
impl Foo {
    pub fn method_name() { }
}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
impl Foo {
    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    pub fn method_name2() { }
}

// Change Method Body -----------------------------------------------------------
//
// This should affect the method itself, but not the impl.
#[cfg(cfail1)]
impl Foo {
    pub fn method_body() { }
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
impl Foo {
    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    pub fn method_body() {
        println!("Hello, world!");
    }
}

// Change Method Privacy -----------------------------------------------------------
#[cfg(cfail1)]
impl Foo {
    pub fn method_privacy() { }
}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
impl Foo {
    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    fn method_privacy() { }
}

// Change Method Selfness -----------------------------------------------------------
#[cfg(cfail1)]
impl Foo {
    pub fn method_selfness() { }
}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
impl Foo {
    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    pub fn method_selfness(&self) { }
}

// Change Method Selfmutness -----------------------------------------------------------
#[cfg(cfail1)]
impl Foo {
    pub fn method_selfmutness(&self) { }
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
impl Foo {
    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    pub fn method_selfmutness(&mut self) { }
}

<commit_msg>ICH: Add test cases for inherent impls.<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.

// This test case tests the incremental compilation hash (ICH) implementation
// for let expressions.

// The general pattern followed here is: Change one thing between rev1 and rev2
// and make sure that the hash has changed, then change nothing between rev2 and
// rev3 and make sure that the hash has not changed.

// must-compile-successfully
// revisions: cfail1 cfail2 cfail3
// compile-flags: -Z query-dep-graph

#![allow(warnings)]
#![feature(rustc_attrs)]
#![crate_type="rlib"]

struct Foo;

// Change Method Name -----------------------------------------------------------
#[cfg(cfail1)]
impl Foo {
    pub fn method_name() { }
}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
impl Foo {
    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    pub fn method_name2() { }
}

// Change Method Body -----------------------------------------------------------
//
// This should affect the method itself, but not the impl.
#[cfg(cfail1)]
impl Foo {
    pub fn method_body() { }
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
impl Foo {
    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    pub fn method_body() {
        println!("Hello, world!");
    }
}

// Change Method Privacy -----------------------------------------------------------
#[cfg(cfail1)]
impl Foo {
    pub fn method_privacy() { }
}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
impl Foo {
    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    fn method_privacy() { }
}

// Change Method Selfness -----------------------------------------------------------
#[cfg(cfail1)]
impl Foo {
    pub fn method_selfness() { }
}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
impl Foo {
    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    pub fn method_selfness(&self) { }
}

// Change Method Selfmutness ---------------------------------------------------
#[cfg(cfail1)]
impl Foo {
    pub fn method_selfmutness(&self) { }
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
impl Foo {
    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    pub fn method_selfmutness(&mut self) { }
}

// Add Method To Impl ----------------------------------------------------------
#[cfg(cfail1)]
impl Foo {
    pub fn add_method_to_impl1(&self) { }
}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
impl Foo {
    #[rustc_clean(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_clean(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    pub fn add_method_to_impl1(&self) { }

    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    pub fn add_method_to_impl2(&self) { }
}

// Add Method Parameter --------------------------------------------------------
#[cfg(cfail1)]
impl Foo {
    pub fn add_method_parameter(&self) { }
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
impl Foo {
    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    pub fn add_method_parameter(&self, _: i32) { }
}

// Change Method Parameter Name ------------------------------------------------
#[cfg(cfail1)]
impl Foo {
    pub fn change_method_parameter_name(&self, a: i64) { }
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
impl Foo {
    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    pub fn change_method_parameter_name(&self, b: i64) { }
}

// Change Method Return Type ---------------------------------------------------
#[cfg(cfail1)]
impl Foo {
    pub fn change_method_return_type(&self) -> u16 { 0 }
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
impl Foo {
    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    pub fn change_method_return_type(&self) -> u8 { 0 }
}

// Make Method #[inline] -------------------------------------------------------
#[cfg(cfail1)]
impl Foo {
    pub fn make_method_inline(&self) -> u8 { 0 }
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
impl Foo {
    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    #[inline]
    pub fn make_method_inline(&self) -> u8 { 0 }
}

//  Change order of parameters -------------------------------------------------
#[cfg(cfail1)]
impl Foo {
    pub fn change_method_parameter_order(&self, a: i64, b: i64) { }
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
impl Foo {
    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    pub fn change_method_parameter_order(&self, b: i64, a: i64) { }
}

// Make method unsafe ----------------------------------------------------------
#[cfg(cfail1)]
impl Foo {
    pub fn make_method_unsafe(&self) { }
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
impl Foo {
    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    pub unsafe fn make_method_unsafe(&self) { }
}

// Make method extern ----------------------------------------------------------
#[cfg(cfail1)]
impl Foo {
    pub fn make_method_extern(&self) { }
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
impl Foo {
    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    pub extern fn make_method_extern(&self) { }
}

// Change method calling convention --------------------------------------------
#[cfg(cfail1)]
impl Foo {
    pub extern "C" fn change_method_calling_convention(&self) { }
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
impl Foo {
    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    pub extern "system" fn change_method_calling_convention(&self) { }
}

// Add Lifetime Parameter to Method --------------------------------------------
#[cfg(cfail1)]
impl Foo {
    pub fn add_lifetime_parameter_to_method(&self) { }
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
impl Foo {
    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    pub fn add_lifetime_parameter_to_method<'a>(&self) { }
}

// Add Type Parameter To Method ------------------------------------------------
#[cfg(cfail1)]
impl Foo {
    pub fn add_type_parameter_to_method(&self) { }
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
impl Foo {
    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    pub fn add_type_parameter_to_method<T>(&self) { }
}

// Add Lifetime Bound to Lifetime Parameter of Method --------------------------
#[cfg(cfail1)]
impl Foo {
    pub fn add_lifetime_bound_to_lifetime_param_of_method<'a, 'b>(&self) { }
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
impl Foo {
    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    pub fn add_lifetime_bound_to_lifetime_param_of_method<'a, 'b: 'a>(&self) { }
}

// Add Lifetime Bound to Type Parameter of Method ------------------------------
#[cfg(cfail1)]
impl Foo {
    pub fn add_lifetime_bound_to_type_param_of_method<'a, T>(&self) { }
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
impl Foo {
    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    pub fn add_lifetime_bound_to_type_param_of_method<'a, T: 'a>(&self) { }
}

// Add Trait Bound to Type Parameter of Method ------------------------------
#[cfg(cfail1)]
impl Foo {
    pub fn add_trait_bound_to_type_param_of_method<T>(&self) { }
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
impl Foo {
    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    pub fn add_trait_bound_to_type_param_of_method<T: Clone>(&self) { }
}

// Add #[no_mangle] to Method --------------------------------------------------
#[cfg(cfail1)]
impl Foo {
    pub fn add_no_mangle_to_method(&self) { }
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
impl Foo {
    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    #[no_mangle]
    pub fn add_no_mangle_to_method(&self) { }
}

struct Bar<T>(T);

// Add Type Parameter To Impl --------------------------------------------------
#[cfg(cfail1)]
impl Bar<u32> {
    pub fn add_type_parameter_to_impl(&self) { }
}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
impl<T> Bar<T> {
    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    pub fn add_type_parameter_to_impl(&self) { }
}

// Change Self Type of Impl ----------------------------------------------------
#[cfg(cfail1)]
impl Bar<u32> {
    pub fn change_impl_self_type(&self) { }
}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
impl Bar<u64> {
    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    pub fn change_impl_self_type(&self) { }
}

// Add Lifetime Bound to Impl --------------------------------------------------
#[cfg(cfail1)]
impl<T> Bar<T> {
    pub fn add_lifetime_bound_to_impl_parameter(&self) { }
}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
impl<T: 'static> Bar<T> {
    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    pub fn add_lifetime_bound_to_impl_parameter(&self) { }
}

// Add Trait Bound to Impl Parameter -------------------------------------------
#[cfg(cfail1)]
impl<T> Bar<T> {
    pub fn add_trait_bound_to_impl_parameter(&self) { }
}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
impl<T: Clone> Bar<T> {
    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    pub fn add_trait_bound_to_impl_parameter(&self) { }
}
<|endoftext|>


<commit_before><commit_msg>[Auto] lib/entry/tag: Fix Clippy warnings<commit_after><|endoftext|>


<commit_before><commit_msg>dynamic traits from rustbook<commit_after>// error[E0277]: the size for values of type `(dyn Vegetable + 'static)` cannot be known at compilation time
//     --> /Users/juliankulesh/Experiments/coursera_learning/rust/programming_rust_notes/dynamic_traits.rs:4:5
//     |
//   4 |     veggies: Vec<Vegetable> // error: `Vegetable` does not have
//     |     ^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
//     |
// = help: the trait `std::marker::Sized` is not implemented for `(dyn Vegetable + 'static)`
// = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
// = note: required by `std::vec::Vec`
trait Vegetable {}

struct Salad {
    veggies: Vec<Vegetable>
}

fn main() {}
<|endoftext|>


<commit_before>use std::fs::File;
use std::io::{Read, Write};

use system::scheme::{Packet, Scheme};

extern crate system;

struct ExampleScheme;

impl Scheme for ExampleScheme {

}

fn main() {
   //In order to handle example:, we create :example
   let mut scheme = File::create(":example").unwrap();
   loop {
       let mut packet = Packet::default();
       if scheme.read(&mut packet).unwrap() == 0 {
           panic!("Unexpected EOF");
       }

       println!("Received: {:?}", packet);

       packet.a = 0;
       scheme.write(&packet).unwrap();
   }
}
<commit_msg>WIP: Implement tests for syscalls in example scheme<commit_after>use std::fs::File;
use std::io::{Read, Write};

use system::error::{Error, Result, ENOENT, EBADF};
use system::scheme::{Packet, Scheme};

extern crate system;

struct ExampleScheme;

impl Scheme for ExampleScheme {
    fn open(&mut self, path: &str, flags: usize, mode: usize) -> Result {
        println!("open {:X} = {}, {:X}, {:X}", path.as_ptr() as usize, path, flags, mode);
        Ok(0)
    }

    #[allow(unused_variables)]
    fn unlink(&mut self, path: &str) -> Result {
        println!("unlink {}", path);
        Err(Error::new(ENOENT))
    }

    #[allow(unused_variables)]
    fn mkdir(&mut self, path: &str, mode: usize) -> Result {
        println!("mkdir {}, {:X}", path, mode);
        Err(Error::new(ENOENT))
    }

    /* Resource operations */

    #[allow(unused_variables)]
    fn read(&mut self, id: usize, buf: &mut [u8]) -> Result {
        println!("read {}, {:X}, {}", id, buf.as_mut_ptr() as usize, buf.len());
        Err(Error::new(EBADF))
    }

    #[allow(unused_variables)]
    fn write(&mut self, id: usize, buf: &[u8]) -> Result {
        println!("write {}, {:X}, {}", id, buf.as_ptr() as usize, buf.len());
        Err(Error::new(EBADF))
    }

    #[allow(unused_variables)]
    fn seek(&mut self, id: usize, pos: usize, whence: usize) -> Result {
        println!("seek {}, {}, {}", id, pos, whence);
        Err(Error::new(EBADF))
    }

    #[allow(unused_variables)]
    fn sync(&mut self, id: usize) -> Result {
        println!("sync {}", id);
        Err(Error::new(EBADF))
    }

    #[allow(unused_variables)]
    fn truncate(&mut self, id: usize, len: usize) -> Result {
        println!("truncate {}, {}", id, len);
        Err(Error::new(EBADF))
    }
}

fn main() {
   //In order to handle example:, we create :example
   let mut scheme = ExampleScheme;
   let mut socket = File::create(":example").unwrap();
   loop {
       let mut packet = Packet::default();
       if socket.read(&mut packet).unwrap() == 0 {
           panic!("Unexpected EOF");
       }
       println!("Recv {:?}", packet);

       scheme.handle(&mut packet);

       socket.write(&packet).unwrap();
       println!("Sent {:?}", packet);
   }
}
<|endoftext|>


<commit_before>use super::{Drawable, BoundingBox, MeasureMode};
use ::props::Color;
use ::paint::{Canvas, Point, Rect};
use ::platform::Context;

pub type MathBackgroundReader<T> = fn (&T) -> &Color;

pub struct Wrapper<'a, T: 'a, U: Drawable> {
    wrapped: Option<U>,
    props: &'a T,
    math_background_reader: MathBackgroundReader<T>,

    bounding_box: BoundingBox
}

impl<'a, T, U: Drawable> Drawable for Wrapper<'a, T, U> {
    fn draw(&self, canvas: &Canvas, pen_pos: &Point) {
        canvas.draw_rect(
            pen_pos,
            self.bounding_box.rect(),
            (self.math_background_reader)(self.props)
        )
    }

    fn calculate(&mut self, context: &Context, width: f32, width_mode: &MeasureMode, height: f32,
                 height_mode: &MeasureMode) {
        if let Some(val) = self.wrapped.as_mut() {
            val.calculate(context, width, width_mode, height, height_mode);
        }
        self.bounding_box = BoundingBox {
            rect: if let Some(ref val) = self.wrapped {
                val.bounding_box().rect().clone()
            } else {
                Rect::new(0., 0.)
            },
            baseline: if let Some(ref val) = self.wrapped {
                val.bounding_box().baseline()
            } else {
                0.
            },
            axis: if let Some(ref val) = self.wrapped {
                val.bounding_box().axis()
            } else {
                0.
            },
        }
    }

    fn bounding_box(&self) -> &BoundingBox {
        &self.bounding_box
    }
}

impl<'a, T, U: Drawable> Wrapper<'a, T, U> {
    pub fn new(props: &'a T, math_background_reader: MathBackgroundReader<T>)
               -> Wrapper<'a, T, U> {
        Wrapper {
            wrapped: None,
            props,
            math_background_reader,
            bounding_box: BoundingBox::default()
        }
    }

    pub fn wrap(&mut self, drawable: U) {
        self.wrapped = Some(drawable);
    }
}<commit_msg>Fix wrapped elements not drawn<commit_after>use super::{Drawable, BoundingBox, MeasureMode};
use ::props::Color;
use ::paint::{Canvas, Point, Rect};
use ::platform::Context;

pub type MathBackgroundReader<T> = fn (&T) -> &Color;

pub struct Wrapper<'a, T: 'a, U: Drawable> {
    wrapped: Option<U>,
    props: &'a T,
    math_background_reader: MathBackgroundReader<T>,

    bounding_box: BoundingBox
}

impl<'a, T, U: Drawable> Drawable for Wrapper<'a, T, U> {
    fn draw(&self, canvas: &Canvas, pen_pos: &Point) {
        canvas.draw_rect(
            pen_pos,
            self.bounding_box.rect(),
            (self.math_background_reader)(self.props)
        );
        if let Some(ref wrapped) = self.wrapped {
            wrapped.draw(canvas, pen_pos);
        }
    }

    fn calculate(&mut self, context: &Context, width: f32, width_mode: &MeasureMode, height: f32,
                 height_mode: &MeasureMode) {
        if let Some(val) = self.wrapped.as_mut() {
            val.calculate(context, width, width_mode, height, height_mode);
        }
        self.bounding_box = BoundingBox {
            rect: if let Some(ref val) = self.wrapped {
                val.bounding_box().rect().clone()
            } else {
                Rect::new(0., 0.)
            },
            baseline: if let Some(ref val) = self.wrapped {
                val.bounding_box().baseline()
            } else {
                0.
            },
            axis: if let Some(ref val) = self.wrapped {
                val.bounding_box().axis()
            } else {
                0.
            },
        }
    }

    fn bounding_box(&self) -> &BoundingBox {
        &self.bounding_box
    }
}

impl<'a, T, U: Drawable> Wrapper<'a, T, U> {
    pub fn new(props: &'a T, math_background_reader: MathBackgroundReader<T>)
               -> Wrapper<'a, T, U> {
        Wrapper {
            wrapped: None,
            props,
            math_background_reader,
            bounding_box: BoundingBox::default()
        }
    }

    pub fn wrap(&mut self, drawable: U) {
        self.wrapped = Some(drawable);
    }
}<|endoftext|>