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

use std::path::PathBuf;
use std::collections::BTreeMap;
use std::fs::File;

use libimagstore::store::FileLockEntry;
use libimagstore::storeid::StoreId;
use libimagstore::storeid::IntoStoreId;
use libimagstore::store::Store;
use libimagerror::into::IntoError;

use toml::Value;

use error::RefErrorKind as REK;
use error::MapErrInto;
use flags::RefFlags;
use result::Result;
use hasher::*;
use module_path::ModuleEntryPath;
use util::*;

pub trait RefStore {

    /// Check whether there is a reference to the file at `pb`
    fn exists(&self, pb: PathBuf) -> Result<bool>;

    /// Try to get `si` as Ref object from the store
    fn get<'a>(&'a self, si: StoreId) -> Result<FileLockEntry<'a>>;

    /// Get a Ref object from the store by hash.
    ///
    /// Returns None if the hash cannot be found.
    fn get_by_hash<'a>(&'a self, hash: String) -> Result<Option<FileLockEntry<'a>>>;

    /// Delete a ref by hash
    ///
    /// If the returned Result contains an error, the ref might not be deleted.
    fn delete_by_hash(&self, hash: String) -> Result<()>;

    /// Create a Ref object which refers to `pb`
    fn create<'a>(&'a self, pb: PathBuf, flags: RefFlags) -> Result<FileLockEntry<'a>>;

    fn create_with_hasher<'a, H: Hasher>(&'a self, pb: PathBuf, flags: RefFlags, h: H)
        -> Result<FileLockEntry<'a>>;

}

impl RefStore for Store {

    /// Check whether there is a reference to the file at `pb`
    fn exists(&self, pb: PathBuf) -> Result<bool> {
        pb.canonicalize()
            .map_err_into(REK::PathCanonicalizationError)
            .and_then(|c| hash_path(&c))
            .map_err_into(REK::PathHashingError)
            .and_then(|hash| {
                self.retrieve_for_module("ref")
                    .map(|iter| (hash, iter))
                    .map_err_into(REK::StoreReadError)
            })
            .and_then(|(hash, possible_refs)| {
                // This is kind of a manual Iterator::filter() call what we do here, but with the
                // actual ::filter method we cannot return the error in a nice way, so we do it
                // manually here. If you can come up with a better version of this, feel free to
                // take this note as a todo.
                for r in possible_refs {
                    let contains_hash = try!(r.to_str()
                        .map_err_into(REK::TypeConversionError)
                        .map(|s| s.contains(&hash[..]))
                    );

                    if !contains_hash {
                        continue;
                    }

                    match self.get(r) {
                        Ok(Some(fle)) => {
                            if read_reference(&fle).map(|path| path == pb).unwrap_or(false) {
                                return Ok(true)
                            }
                        },

                        Ok(None) => return Err(REK::StoreReadError.into_error()),
                        Err(e)   => return Err(e).map_err_into(REK::StoreReadError)
                    }
                }

                Ok(false)
            })
    }

    /// Try to get `si` as Ref object from the store
    fn get<'a>(&'a self, si: StoreId) -> Result<FileLockEntry<'a>> {
        match self.get(si) {
            Err(e)        => return Err(e).map_err_into(REK::StoreReadError),
            Ok(None)      => return Err(REK::RefNotInStore.into_error()),
            Ok(Some(fle)) => Ok(fle),
        }
    }

    /// Get a Ref object from the store by hash.
    ///
    /// Returns None if the hash cannot be found.
    fn get_by_hash<'a>(&'a self, hash: String) -> Result<Option<FileLockEntry<'a>>> {
        ModuleEntryPath::new(hash)
            .into_storeid()
            .and_then(|id| self.get(id))
            .map_err_into(REK::StoreReadError)
    }

    /// Delete a ref by hash
    ///
    /// If the returned Result contains an error, the ref might not be deleted.
    fn delete_by_hash(&self, hash: String) -> Result<()> {
        ModuleEntryPath::new(hash)
            .into_storeid()
            .and_then(|id| self.delete(id))
            .map_err_into(REK::StoreWriteError)
    }

    /// Create a Ref object which refers to `pb`
    fn create<'a>(&'a self, pb: PathBuf, flags: RefFlags) -> Result<FileLockEntry<'a>> {
        self.create_with_hasher(pb, flags, DefaultHasher::new())
    }

    fn create_with_hasher<'a, H: Hasher>(&'a self, pb: PathBuf, flags: RefFlags, mut h: H)
        -> Result<FileLockEntry<'a>>
    {
        use toml_query::insert::TomlValueInsertExt;

        if !pb.exists() {
            return Err(REK::RefTargetDoesNotExist.into_error());
        }
        if flags.get_content_hashing() && pb.is_dir() {
            return Err(REK::RefTargetCannotBeHashed.into_error());
        }

        let (mut fle, content_hash, permissions, canonical_path) = { // scope to be able to fold
            try!(File::open(pb.clone())
                .map_err_into(REK::RefTargetFileCannotBeOpened)

                // If we were able to open this file,
                // we hash the contents of the file and return (file, hash)
                .and_then(|mut file| {
                    let opt_contenthash = if flags.get_content_hashing() {
                        Some(try!(h.create_hash(&pb, &mut file)))
                    } else {
                        None
                    };

                    Ok((file, opt_contenthash))
                })

                // and then we get the permissions if we have to
                // and return (file, content hash, permissions)
                .and_then(|(file, opt_contenthash)| {
                    let opt_permissions = if flags.get_permission_tracking() {
                        Some(try!(file
                                  .metadata()
                                  .map(|md| md.permissions())
                                  .map_err_into(REK::RefTargetCannotReadPermissions)
                        ))
                    } else {
                        None
                    };

                    Ok((opt_contenthash, opt_permissions))
                })

                // and then we try to canonicalize the PathBuf, because we want to store a
                // canonicalized path
                // and return (file, content hash, permissions, canonicalized path)
                .and_then(|(opt_contenthash, opt_permissions)| {
                    pb.canonicalize()
                        .map(|can| (opt_contenthash, opt_permissions, can))
                        // if PathBuf::canonicalize() failed, build an error from the return value
                        .map_err_into(REK::PathCanonicalizationError)
                })

                // and then we hash the canonicalized path
                // and return (file, content hash, permissions, canonicalized path, path hash)
                .and_then(|(opt_contenthash, opt_permissions, can)| {
                    let path_hash = try!(hash_path(&can).map_err_into(REK::PathHashingError));

                    Ok((opt_contenthash, opt_permissions, can, path_hash))
                })

                // and then we convert the PathBuf of the canonicalized path to a String to be able
                // to save it in the Ref FileLockEntry obj
                // and return
                // (file, content hash, permissions, canonicalized path as String, path hash)
                .and_then(|(opt_conhash, opt_perm, can, path_hash)| {
                    match can.to_str().map(String::from) {
                        // UTF convert error in PathBuf::to_str(),
                        None      => Err(REK::PathUTF8Error.into_error()),
                        Some(can) => Ok((opt_conhash, opt_perm, can, path_hash))
                    }
                })

                // and then we create the FileLockEntry in the Store
                // and return (filelockentry, content hash, permissions, canonicalized path)
                .and_then(|(opt_conhash, opt_perm, can, path_hash)| {
                    let fle = try!(self
                                   .create(ModuleEntryPath::new(path_hash))
                                   .map_err_into(REK::StoreWriteError)
                    );

                    Ok((fle, opt_conhash, opt_perm, can))
                })
            )
        };

        for tpl in [
                Some((String::from("ref"),              Value::Table(BTreeMap::new()))),
                Some((String::from("ref.permissions"),  Value::Table(BTreeMap::new()))),
                Some((String::from("ref.path"),         Value::String(canonical_path))),
                Some((String::from("ref.content_hash"), Value::Table(BTreeMap::new()))),

                content_hash.map(|hash| {
                    (format!("ref.content_hash.{}", h.hash_name()), Value::String(hash))
                }),
                permissions.map(|p| {
                    (String::from("ref.permissions.ro"), Value::Boolean(p.readonly()))
                }),
            ].into_iter()
        {
            match tpl {
                &Some((ref s, ref v)) => {
                    match fle.get_header_mut().insert(s, v.clone()) {
                        Ok(Some(_)) => {
                            let e = REK::HeaderFieldAlreadyExistsError.into_error();
                            return Err(e).map_err_into(REK::HeaderFieldWriteError);
                        },
                        Err(e) => return Err(e).map_err_into(REK::HeaderFieldWriteError),
                        _ => (),
                    }
                }
                &None => {
                    debug!("Not going to insert.");
                }
            }
        }

        Ok(fle)
    }

}

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

use std::path::PathBuf;
use std::collections::BTreeMap;
use std::fs::File;

use libimagstore::store::FileLockEntry;
use libimagstore::storeid::StoreId;
use libimagstore::storeid::IntoStoreId;
use libimagstore::store::Store;
use libimagerror::into::IntoError;

use toml::Value;

use error::RefErrorKind as REK;
use error::MapErrInto;
use flags::RefFlags;
use result::Result;
use hasher::*;
use module_path::ModuleEntryPath;
use util::*;

pub trait RefStore {

    /// Check whether there is a reference to the file at `pb`
    fn exists(&self, pb: PathBuf) -> Result<bool>;

    /// Try to get `si` as Ref object from the store
    fn get<'a>(&'a self, si: StoreId) -> Result<FileLockEntry<'a>>;

    /// Get a Ref object from the store by hash.
    ///
    /// Returns None if the hash cannot be found.
    fn get_by_hash<'a>(&'a self, hash: String) -> Result<Option<FileLockEntry<'a>>>;

    /// Delete a ref by hash
    ///
    /// If the returned Result contains an error, the ref might not be deleted.
    fn delete_by_hash(&self, hash: String) -> Result<()>;

    /// Create a Ref object which refers to `pb`
    fn create<'a>(&'a self, pb: PathBuf, flags: RefFlags) -> Result<FileLockEntry<'a>>;

    fn create_with_hasher<'a, H: Hasher>(&'a self, pb: PathBuf, flags: RefFlags, h: H)
        -> Result<FileLockEntry<'a>>;

}

impl RefStore for Store {

    /// Check whether there is a reference to the file at `pb`
    fn exists(&self, pb: PathBuf) -> Result<bool> {
        pb.canonicalize()
            .map_err_into(REK::PathCanonicalizationError)
            .and_then(|c| hash_path(&c))
            .map_err_into(REK::PathHashingError)
            .and_then(|hash| {
                self.retrieve_for_module("ref")
                    .map(|iter| (hash, iter))
                    .map_err_into(REK::StoreReadError)
            })
            .and_then(|(hash, possible_refs)| {
                // This is kind of a manual Iterator::filter() call what we do here, but with the
                // actual ::filter method we cannot return the error in a nice way, so we do it
                // manually here. If you can come up with a better version of this, feel free to
                // take this note as a todo.
                for r in possible_refs {
                    let contains_hash = try!(r.to_str()
                        .map_err_into(REK::TypeConversionError)
                        .map(|s| s.contains(&hash[..]))
                    );

                    if !contains_hash {
                        continue;
                    }

                    match self.get(r) {
                        Ok(Some(fle)) => {
                            if read_reference(&fle).map(|path| path == pb).unwrap_or(false) {
                                return Ok(true)
                            }
                        },

                        Ok(None) => return Err(REK::StoreReadError.into_error()),
                        Err(e)   => return Err(e).map_err_into(REK::StoreReadError)
                    }
                }

                Ok(false)
            })
    }

    /// Try to get `si` as Ref object from the store
    fn get<'a>(&'a self, si: StoreId) -> Result<FileLockEntry<'a>> {
        match self.get(si) {
            Err(e)        => return Err(e).map_err_into(REK::StoreReadError),
            Ok(None)      => return Err(REK::RefNotInStore.into_error()),
            Ok(Some(fle)) => Ok(fle),
        }
    }

    /// Get a Ref object from the store by hash.
    ///
    /// Returns None if the hash cannot be found.
    fn get_by_hash<'a>(&'a self, hash: String) -> Result<Option<FileLockEntry<'a>>> {
        ModuleEntryPath::new(hash)
            .into_storeid()
            .and_then(|id| self.get(id))
            .map_err_into(REK::StoreReadError)
    }

    /// Delete a ref by hash
    ///
    /// If the returned Result contains an error, the ref might not be deleted.
    fn delete_by_hash(&self, hash: String) -> Result<()> {
        ModuleEntryPath::new(hash)
            .into_storeid()
            .and_then(|id| self.delete(id))
            .map_err_into(REK::StoreWriteError)
    }

    /// Create a Ref object which refers to `pb`
    fn create<'a>(&'a self, pb: PathBuf, flags: RefFlags) -> Result<FileLockEntry<'a>> {
        self.create_with_hasher(pb, flags, DefaultHasher::new())
    }

    fn create_with_hasher<'a, H: Hasher>(&'a self, pb: PathBuf, flags: RefFlags, mut h: H)
        -> Result<FileLockEntry<'a>>
    {
        use toml_query::insert::TomlValueInsertExt;

        if !pb.exists() {
            return Err(REK::RefTargetDoesNotExist.into_error());
        }
        if flags.get_content_hashing() && pb.is_dir() {
            return Err(REK::RefTargetCannotBeHashed.into_error());
        }

        let (mut fle, content_hash, permissions, canonical_path) = { // scope to be able to fold
            try!(File::open(pb.clone())
                .map_err_into(REK::RefTargetFileCannotBeOpened)

                // If we were able to open this file,
                // we hash the contents of the file and return (file, hash)
                .and_then(|mut file| {
                    let opt_contenthash = if flags.get_content_hashing() {
                        Some(try!(h.create_hash(&pb, &mut file)))
                    } else {
                        None
                    };

                    Ok((file, opt_contenthash))
                })

                // and then we get the permissions if we have to
                // and return (file, content hash, permissions)
                .and_then(|(file, opt_contenthash)| {
                    let opt_permissions = if flags.get_permission_tracking() {
                        Some(try!(file
                                  .metadata()
                                  .map(|md| md.permissions())
                                  .map_err_into(REK::RefTargetCannotReadPermissions)
                        ))
                    } else {
                        None
                    };

                    Ok((opt_contenthash, opt_permissions))
                })

                // and then we try to canonicalize the PathBuf, because we want to store a
                // canonicalized path
                // and return (file, content hash, permissions, canonicalized path)
                .and_then(|(opt_contenthash, opt_permissions)| {
                    pb.canonicalize()
                        .map(|can| (opt_contenthash, opt_permissions, can))
                        // if PathBuf::canonicalize() failed, build an error from the return value
                        .map_err_into(REK::PathCanonicalizationError)
                })

                // and then we hash the canonicalized path
                // and return (file, content hash, permissions, canonicalized path, path hash)
                .and_then(|(opt_contenthash, opt_permissions, can)| {
                    let path_hash = try!(hash_path(&can).map_err_into(REK::PathHashingError));

                    Ok((opt_contenthash, opt_permissions, can, path_hash))
                })

                // and then we convert the PathBuf of the canonicalized path to a String to be able
                // to save it in the Ref FileLockEntry obj
                // and return
                // (file, content hash, permissions, canonicalized path as String, path hash)
                .and_then(|(opt_conhash, opt_perm, can, path_hash)| {
                    match can.to_str().map(String::from) {
                        // UTF convert error in PathBuf::to_str(),
                        None      => Err(REK::PathUTF8Error.into_error()),
                        Some(can) => Ok((opt_conhash, opt_perm, can, path_hash))
                    }
                })

                // and then we create the FileLockEntry in the Store
                // and return (filelockentry, content hash, permissions, canonicalized path)
                .and_then(|(opt_conhash, opt_perm, can, path_hash)| {
                    let fle = try!(self
                                   .create(ModuleEntryPath::new(path_hash))
                                   .map_err_into(REK::StoreWriteError)
                    );

                    Ok((fle, opt_conhash, opt_perm, can))
                })
            )
        };

        for tpl in [
                Some((String::from("ref"),              Value::Table(BTreeMap::new()))),
                Some((String::from("ref.permissions"),  Value::Table(BTreeMap::new()))),
                Some((String::from("ref.path"),         Value::String(canonical_path))),
                Some((String::from("ref.content_hash"), Value::Table(BTreeMap::new()))),

                content_hash.map(|hash| {
                    (format!("ref.content_hash.{}", h.hash_name()), Value::String(hash))
                }),
                permissions.map(|p| {
                    (String::from("ref.permissions.ro"), Value::Boolean(p.readonly()))
                }),
            ].into_iter()
        {
            match tpl {
                &Some((ref s, ref v)) => {
                    match fle.get_header_mut().insert(s, v.clone()) {
                        Ok(Some(_)) => {
                            let e = REK::HeaderFieldAlreadyExistsError.into_error();
                            return Err(e).map_err_into(REK::HeaderFieldWriteError);
                        },
                        Ok(None) => {
                            // Okay, we just inserted a new header value...
                        },
                        Err(e) => return Err(e).map_err_into(REK::HeaderFieldWriteError),
                        _ => (),
                    }
                }
                &None => {
                    debug!("Not going to insert.");
                }
            }
        }

        Ok(fle)
    }

}

<|endoftext|>


<commit_before><commit_msg>aarch64: Basic exception handlers<commit_after>use crate::{
    interrupt::stack_trace,
    syscall,
    syscall::flag::*,

    with_exception_stack,
    exception_stack,
};

exception_stack!(synchronous_exception_at_el1_with_sp0, |stack| {
    println!("Synchronous exception at EL1 with SP0");
    stack.dump();
    stack_trace();
    loop {}
});

exception_stack!(synchronous_exception_at_el1_with_spx, |stack| {
    println!("Synchronous exception at EL1 with SPx");
    stack.dump();
    stack_trace();
    loop {}
});

exception_stack!(synchronous_exception_at_el0, |stack| {
    with_exception_stack!(|stack| {
        let fp;
        asm!("mov {}, fp", out(reg) fp);

        let exception_code = (stack.iret.esr_el1 & (0x3f << 26)) >> 26;
        if exception_code != 0b010101 {
            println!("FATAL: Not an SVC induced synchronous exception");
            stack.dump();
            stack_trace();
            loop {}
        }

        let scratch = &stack.scratch;
        syscall::syscall(scratch.x8, scratch.x0, scratch.x1, scratch.x2, scratch.x3, scratch.x4, fp, stack)
    });
});

exception_stack!(unhandled_exception, |stack| {
    println!("Unhandled exception");
    stack.dump();
    stack_trace();
    loop {}
});
<|endoftext|>


<commit_before><commit_msg>Fix Redox build<commit_after><|endoftext|>


<commit_before><commit_msg>Updates<commit_after><|endoftext|>


<commit_before><commit_msg>Add test<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.

#![feature(rustc_attrs)]
#![allow(dead_code)]

mod foo {
    pub use self::bar::T;
    mod bar {
        pub trait T {
            fn f(&self) {}
        }
        impl T for () {}
    }
}

fn g() {
    use foo::T;
    ().f(); // Check that this does not trigger a privacy error
}

#[rustc_error]
fn main() {} //~ ERROR compilation successful
<|endoftext|>


<commit_before><commit_msg>new example using mouse events<commit_after>//! Test of kiss3d's planar camera. Just moves a cross around the screen whenever the mouse is clicked. Shows conversions between co-ordinate systems.
extern crate kiss3d;
extern crate nalgebra as na;

use kiss3d::event::{Action, WindowEvent};
use kiss3d::light::Light;
use kiss3d::planar_camera::*;
use kiss3d::window::Window;

/// main program
fn main() {
    let mut window = Window::new("Generation tile test");
    let mut camera = kiss3d::planar_camera::FixedView::new();
    window.set_light(Light::StickToCamera);
    let draw_colour = na::Point3::new(0.5, 1.0, 0.5);
    let mut last_pos = na::Point2::new(0.0f32, 0.0f32);
    let mut sel_pos = na::Point2::new(0.0f32, 0.0f32);
    while window.render_with(None, Some(&mut camera), None) {
        for event in window.events().iter() {
            match event.value {
                WindowEvent::FramebufferSize(x, y) => {
                    println!("frame buffer size event {}, {}", x, y);
                }
                WindowEvent::MouseButton(button, Action::Press, modif) => {
                    println!("mouse press event on {:?} with {:?}", button, modif);
                    let window_size =
                        na::Vector2::new(window.size()[0] as f32, window.size()[1] as f32);
                    sel_pos = camera.unproject(&last_pos, &window_size);
                    println!(
                        "conv {:?} to {:?} win siz {:?} ",
                        last_pos, sel_pos, window_size
                    );
                }
                WindowEvent::Key(key, action, modif) => {
                    println!("key event {:?} on {:?} with {:?}", key, action, modif);
                }
                WindowEvent::CursorPos(x, y, _modif) => {
                    last_pos = na::Point2::new(x as f32, y as f32);
                }
                WindowEvent::Close => {
                    println!("close event");
                }
                _ => {}
            }
        }
        const CROSS_SIZE: f32 = 10.0;
        let UP = na::Vector2::new(CROSS_SIZE, 0.0);
        window.draw_planar_line(&(sel_pos - UP), &(sel_pos + UP), &draw_colour);

        let RIGHT = na::Vector2::new(0.0, CROSS_SIZE);
        window.draw_planar_line(&(sel_pos - RIGHT), &(sel_pos + RIGHT), &draw_colour);
    }
}
<|endoftext|>


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

// FIXME:
// Alignment of 128 bit types is not currently handled, this will
// need to be fixed when PowerPC vector support is added.

use abi::call::{FnType, ArgType, Reg, RegKind, Uniform};
use abi::{Align, Endian, HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods};

#[derive(Debug, Clone, Copy, PartialEq)]
enum ABI {
    ELFv1, // original ABI used for powerpc64 (big-endian)
    ELFv2, // newer ABI used for powerpc64le
}
use self::ABI::*;

fn is_homogeneous_aggregate<'a, Ty, C>(cx: &C, arg: &mut ArgType<'a, Ty>, abi: ABI)
                                       -> Option<Uniform>
    where Ty: TyLayoutMethods<'a, C> + Copy,
          C: LayoutOf<Ty = Ty, TyLayout = TyLayout<'a, Ty>> + HasDataLayout
{
    arg.layout.homogeneous_aggregate(cx).and_then(|unit| {
        // ELFv1 only passes one-member aggregates transparently.
        // ELFv2 passes up to eight uniquely addressable members.
        if (abi == ELFv1 && arg.layout.size > unit.size)
                || arg.layout.size > unit.size.checked_mul(8, cx).unwrap() {
            return None;
        }

        let valid_unit = match unit.kind {
            RegKind::Integer => false,
            RegKind::Float => true,
            RegKind::Vector => arg.layout.size.bits() == 128
        };

        if valid_unit {
            Some(Uniform {
                unit,
                total: arg.layout.size
            })
        } else {
            None
        }
    })
}

fn classify_ret_ty<'a, Ty, C>(cx: &C, ret: &mut ArgType<'a, Ty>, abi: ABI)
    where Ty: TyLayoutMethods<'a, C> + Copy,
          C: LayoutOf<Ty = Ty, TyLayout = TyLayout<'a, Ty>> + HasDataLayout
{
    if !ret.layout.is_aggregate() {
        ret.extend_integer_width_to(64);
        return;
    }

    // The ELFv1 ABI doesn't return aggregates in registers
    if abi == ELFv1 {
        ret.make_indirect();
        return;
    }

    if let Some(uniform) = is_homogeneous_aggregate(cx, ret, abi) {
        ret.cast_to(uniform);
        return;
    }

    let size = ret.layout.size;
    let bits = size.bits();
    if bits <= 128 {
        let unit = if cx.data_layout().endian == Endian::Big {
            Reg { kind: RegKind::Integer, size }
        } else if bits <= 8 {
            Reg::i8()
        } else if bits <= 16 {
            Reg::i16()
        } else if bits <= 32 {
            Reg::i32()
        } else {
            Reg::i64()
        };

        ret.cast_to(Uniform {
            unit,
            total: size
        });
        return;
    }

    ret.make_indirect();
}

fn classify_arg_ty<'a, Ty, C>(cx: &C, arg: &mut ArgType<'a, Ty>, abi: ABI)
    where Ty: TyLayoutMethods<'a, C> + Copy,
          C: LayoutOf<Ty = Ty, TyLayout = TyLayout<'a, Ty>> + HasDataLayout
{
    if !arg.layout.is_aggregate() {
        arg.extend_integer_width_to(64);
        return;
    }

    if let Some(uniform) = is_homogeneous_aggregate(cx, arg, abi) {
        arg.cast_to(uniform);
        return;
    }

    let size = arg.layout.size;
    let (unit, total) = if size.bits() <= 64 {
        // Aggregates smaller than a doubleword should appear in
        // the least-significant bits of the parameter doubleword.
        (Reg { kind: RegKind::Integer, size }, size)
    } else {
        // Aggregates larger than a doubleword should be padded
        // at the tail to fill out a whole number of doublewords.
        let align = Align::from_bits(64, 64).unwrap();
        (Reg::i64(), size.abi_align(align))
    };

    arg.cast_to(Uniform {
        unit,
        total
    });
}

pub fn compute_abi_info<'a, Ty, C>(cx: &C, fty: &mut FnType<'a, Ty>)
    where Ty: TyLayoutMethods<'a, C> + Copy,
          C: LayoutOf<Ty = Ty, TyLayout = TyLayout<'a, Ty>> + HasDataLayout
{
    let abi = match cx.data_layout().endian {
        Endian::Big => ELFv1,
        Endian::Little => ELFv2,
    };

    if !fty.ret.is_ignore() {
        classify_ret_ty(cx, &mut fty.ret, abi);
    }

    for arg in &mut fty.args {
        if arg.is_ignore() { continue; }
        classify_arg_ty(cx, arg, abi);
    }
}
<commit_msg>Use the ELFv2 ABI on powerpc64 musl<commit_after>// Copyright 2014-2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// FIXME:
// Alignment of 128 bit types is not currently handled, this will
// need to be fixed when PowerPC vector support is added.

use abi::call::{FnType, ArgType, Reg, RegKind, Uniform};
use abi::{Align, Endian, HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods};
use spec::HasTargetSpec;

#[derive(Debug, Clone, Copy, PartialEq)]
enum ABI {
    ELFv1, // original ABI used for powerpc64 (big-endian)
    ELFv2, // newer ABI used for powerpc64le and musl (both endians)
}
use self::ABI::*;

fn is_homogeneous_aggregate<'a, Ty, C>(cx: &C, arg: &mut ArgType<'a, Ty>, abi: ABI)
                                       -> Option<Uniform>
    where Ty: TyLayoutMethods<'a, C> + Copy,
          C: LayoutOf<Ty = Ty, TyLayout = TyLayout<'a, Ty>> + HasDataLayout
{
    arg.layout.homogeneous_aggregate(cx).and_then(|unit| {
        // ELFv1 only passes one-member aggregates transparently.
        // ELFv2 passes up to eight uniquely addressable members.
        if (abi == ELFv1 && arg.layout.size > unit.size)
                || arg.layout.size > unit.size.checked_mul(8, cx).unwrap() {
            return None;
        }

        let valid_unit = match unit.kind {
            RegKind::Integer => false,
            RegKind::Float => true,
            RegKind::Vector => arg.layout.size.bits() == 128
        };

        if valid_unit {
            Some(Uniform {
                unit,
                total: arg.layout.size
            })
        } else {
            None
        }
    })
}

fn classify_ret_ty<'a, Ty, C>(cx: &C, ret: &mut ArgType<'a, Ty>, abi: ABI)
    where Ty: TyLayoutMethods<'a, C> + Copy,
          C: LayoutOf<Ty = Ty, TyLayout = TyLayout<'a, Ty>> + HasDataLayout
{
    if !ret.layout.is_aggregate() {
        ret.extend_integer_width_to(64);
        return;
    }

    // The ELFv1 ABI doesn't return aggregates in registers
    if abi == ELFv1 {
        ret.make_indirect();
        return;
    }

    if let Some(uniform) = is_homogeneous_aggregate(cx, ret, abi) {
        ret.cast_to(uniform);
        return;
    }

    let size = ret.layout.size;
    let bits = size.bits();
    if bits <= 128 {
        let unit = if cx.data_layout().endian == Endian::Big {
            Reg { kind: RegKind::Integer, size }
        } else if bits <= 8 {
            Reg::i8()
        } else if bits <= 16 {
            Reg::i16()
        } else if bits <= 32 {
            Reg::i32()
        } else {
            Reg::i64()
        };

        ret.cast_to(Uniform {
            unit,
            total: size
        });
        return;
    }

    ret.make_indirect();
}

fn classify_arg_ty<'a, Ty, C>(cx: &C, arg: &mut ArgType<'a, Ty>, abi: ABI)
    where Ty: TyLayoutMethods<'a, C> + Copy,
          C: LayoutOf<Ty = Ty, TyLayout = TyLayout<'a, Ty>> + HasDataLayout
{
    if !arg.layout.is_aggregate() {
        arg.extend_integer_width_to(64);
        return;
    }

    if let Some(uniform) = is_homogeneous_aggregate(cx, arg, abi) {
        arg.cast_to(uniform);
        return;
    }

    let size = arg.layout.size;
    let (unit, total) = if size.bits() <= 64 {
        // Aggregates smaller than a doubleword should appear in
        // the least-significant bits of the parameter doubleword.
        (Reg { kind: RegKind::Integer, size }, size)
    } else {
        // Aggregates larger than a doubleword should be padded
        // at the tail to fill out a whole number of doublewords.
        let align = Align::from_bits(64, 64).unwrap();
        (Reg::i64(), size.abi_align(align))
    };

    arg.cast_to(Uniform {
        unit,
        total
    });
}

pub fn compute_abi_info<'a, Ty, C>(cx: &C, fty: &mut FnType<'a, Ty>)
    where Ty: TyLayoutMethods<'a, C> + Copy,
          C: LayoutOf<Ty = Ty, TyLayout = TyLayout<'a, Ty>> + HasDataLayout + HasTargetSpec
{
    let abi = if cx.target_spec().target_env == "musl" {
        ELFv2
    } else {
        match cx.data_layout().endian {
            Endian::Big => ELFv1,
            Endian::Little => ELFv2
        }
    };

    if !fty.ret.is_ignore() {
        classify_ret_ty(cx, &mut fty.ret, abi);
    }

    for arg in &mut fty.args {
        if arg.is_ignore() { continue; }
        classify_arg_ty(cx, arg, abi);
    }
}
<|endoftext|>


<commit_before>// xfail-test

// A port of task-killjoin to use a class with a dtor to manage
// the join.

use std;
import task;

class notify {
    let ch: comm::chan<bool>; let v: @mut bool;
    new(ch: comm::chan<bool>, v: @mut bool) { self.ch = ch; self.v = v; }
    drop {
        #error~["notify: task=%? v=%x unwinding=%b b=%b",
               task::get_task(),
               ptr::addr_of(*(self.v)) as uint,
               task::failing(),
               *(self.v)];
        let b = *(self.v);
        comm::send(self.ch, b);
    }
}

fn joinable(f: fn~()) -> comm::port<bool> {
    fn wrapper(+pair: (comm::chan<bool>, fn())) {
        let (c, f) = pair;
        let b = @mut false;
        #error~["wrapper: task=%? allocated v=%x",
               task::get_task(),
               ptr::addr_of(*b) as uint];
        let _r = notify(c, b);
        f();
        *b = true;
    }
    let p = comm::port();
    let c = comm::chan(p);
    let _ = task::spawn_unlinked {|| wrapper((c, f)) };
    p
}

fn join(port: comm::port<bool>) -> bool {
    comm::recv(port)
}

fn supervised() {
    // Yield to make sure the supervisor joins before we
    // fail. This is currently not needed because the supervisor
    // runs first, but I can imagine that changing.
    #error["supervised task=%?", task::get_task];
    task::yield();
    fail;
}

fn supervisor() {
    #error["supervisor task=%?", task::get_task()];
    let t = joinable(supervised);
    join(t);
}

fn main() {
    join(joinable({|| supervisor()}));
}

// Local Variables:
// mode: rust;
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
<commit_msg>Fix and un-xfail task-killjoin-rsrc.rs<commit_after>// A port of task-killjoin to use a class with a dtor to manage
// the join.

use std;
import task;

class notify {
    let ch: comm::chan<bool>; let v: @mut bool;
    new(ch: comm::chan<bool>, v: @mut bool) { self.ch = ch; self.v = v; }
    drop {
        #error["notify: task=%? v=%x unwinding=%b b=%b",
               task::get_task(),
               ptr::addr_of(*(self.v)) as uint,
               task::failing(),
               *(self.v)];
        let b = *(self.v);
        comm::send(self.ch, b);
    }
}

fn joinable(+f: fn~()) -> comm::port<bool> {
    fn wrapper(+c: comm::chan<bool>, +f: fn()) {
        let b = @mut false;
        #error["wrapper: task=%? allocated v=%x",
               task::get_task(),
               ptr::addr_of(*b) as uint];
        let _r = notify(c, b);
        f();
        *b = true;
    }
    let p = comm::port();
    let c = comm::chan(p);
    do task::spawn_unlinked { wrapper(c, copy f) };
    p
}

fn join(port: comm::port<bool>) -> bool {
    comm::recv(port)
}

fn supervised() {
    // Yield to make sure the supervisor joins before we
    // fail. This is currently not needed because the supervisor
    // runs first, but I can imagine that changing.
    #error["supervised task=%?", task::get_task];
    task::yield();
    fail;
}

fn supervisor() {
    #error["supervisor task=%?", task::get_task()];
    let t = joinable(supervised);
    join(t);
}

fn main() {
    join(joinable(supervisor));
}

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


<commit_before><commit_msg>Wrap all metrics into a single struct.<commit_after><|endoftext|>


<commit_before><commit_msg>error: compose own error type<commit_after><|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.

//! Lints in the Rust compiler.
//!
//! This currently only contains the definitions and implementations
//! of most of the lints that `rustc` supports directly, it does not
//! contain the infrastructure for defining/registering lints. That is
//! available in `rustc::lint` and `rustc_plugin` respectively.
//!
//! # Note
//!
//! This API is completely unstable and subject to change.

#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
      html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
      html_root_url = "https://doc.rust-lang.org/nightly/")]
#![deny(warnings)]

#![cfg_attr(test, feature(test))]
#![feature(box_patterns)]
#![feature(box_syntax)]
#![feature(i128_type)]
#![feature(macro_vis_matcher)]
#![feature(quote)]
#![feature(rustc_diagnostic_macros)]
#![feature(slice_patterns)]

#[macro_use]
extern crate syntax;
#[macro_use]
extern crate rustc;
#[macro_use]
extern crate log;
extern crate rustc_mir;
extern crate syntax_pos;

use rustc::lint;
use rustc::session;
use rustc::util;

use session::Session;
use syntax::epoch::Epoch;
use lint::LintId;
use lint::FutureIncompatibleInfo;

mod bad_style;
mod builtin;
mod types;
mod unused;

use bad_style::*;
use builtin::*;
use types::*;
use unused::*;

/// Tell the `LintStore` about all the built-in lints (the ones
/// defined in this crate and the ones defined in
/// `rustc::lint::builtin`).
pub fn register_builtins(store: &mut lint::LintStore, sess: Option<&Session>) {
    macro_rules! add_builtin {
        ($sess:ident, $($name:ident),*,) => (
            {$(
                store.register_late_pass($sess, false, box $name);
                )*}
            )
    }

    macro_rules! add_early_builtin {
        ($sess:ident, $($name:ident),*,) => (
            {$(
                store.register_early_pass($sess, false, box $name);
                )*}
            )
    }

    macro_rules! add_builtin_with_new {
        ($sess:ident, $($name:ident),*,) => (
            {$(
                store.register_late_pass($sess, false, box $name::new());
                )*}
            )
    }

    macro_rules! add_early_builtin_with_new {
        ($sess:ident, $($name:ident),*,) => (
            {$(
                store.register_early_pass($sess, false, box $name::new());
                )*}
            )
    }

    macro_rules! add_lint_group {
        ($sess:ident, $name:expr, $($lint:ident),*) => (
            store.register_group($sess, false, $name, vec![$(LintId::of($lint)),*]);
            )
    }

    add_early_builtin!(sess,
                       UnusedParens,
                       UnusedImportBraces,
                       AnonymousParameters,
                       UnusedDocComment,
                       );

    add_early_builtin_with_new!(sess,
                                DeprecatedAttr,
                                );

    add_builtin!(sess,
                 HardwiredLints,
                 WhileTrue,
                 ImproperCTypes,
                 VariantSizeDifferences,
                 BoxPointers,
                 UnusedAttributes,
                 PathStatements,
                 UnusedResults,
                 NonCamelCaseTypes,
                 NonSnakeCase,
                 NonUpperCaseGlobals,
                 NonShorthandFieldPatterns,
                 UnsafeCode,
                 UnusedAllocation,
                 MissingCopyImplementations,
                 UnstableFeatures,
                 UnconditionalRecursion,
                 InvalidNoMangleItems,
                 PluginAsLibrary,
                 MutableTransmutes,
                 UnionsWithDropFields,
                 UnreachablePub,
                 );

    add_builtin_with_new!(sess,
                          TypeLimits,
                          MissingDoc,
                          MissingDebugImplementations,
                          );

    add_lint_group!(sess,
                    "bad_style",
                    NON_CAMEL_CASE_TYPES,
                    NON_SNAKE_CASE,
                    NON_UPPER_CASE_GLOBALS);

    add_lint_group!(sess,
                    "nonstandard_style",
                    NON_CAMEL_CASE_TYPES,
                    NON_SNAKE_CASE,
                    NON_UPPER_CASE_GLOBALS);

    add_lint_group!(sess,
                    "unused",
                    UNUSED_IMPORTS,
                    UNUSED_VARIABLES,
                    UNUSED_ASSIGNMENTS,
                    DEAD_CODE,
                    UNUSED_MUT,
                    UNREACHABLE_CODE,
                    UNREACHABLE_PATTERNS,
                    UNUSED_MUST_USE,
                    UNUSED_UNSAFE,
                    PATH_STATEMENTS,
                    UNUSED_ATTRIBUTES,
                    UNUSED_MACROS,
                    UNUSED_ALLOCATION,
                    UNUSED_DOC_COMMENT,
                    UNUSED_EXTERN_CRATES,
                    UNUSED_FEATURES,
                    UNUSED_PARENS);

    // Guidelines for creating a future incompatibility lint:
    //
    // - Create a lint defaulting to warn as normal, with ideally the same error
    //   message you would normally give
    // - Add a suitable reference, typically an RFC or tracking issue. Go ahead
    //   and include the full URL, sort items in ascending order of issue numbers.
    // - Later, change lint to error
    // - Eventually, remove lint
    store.register_future_incompatible(sess,
                                       vec![
        FutureIncompatibleInfo {
            id: LintId::of(PRIVATE_IN_PUBLIC),
            reference: "issue #34537 <https://github.com/rust-lang/rust/issues/34537>",
            epoch: None,
        },
        FutureIncompatibleInfo {
            id: LintId::of(PUB_USE_OF_PRIVATE_EXTERN_CRATE),
            reference: "issue #34537 <https://github.com/rust-lang/rust/issues/34537>",
            epoch: None,
        },
        FutureIncompatibleInfo {
            id: LintId::of(PATTERNS_IN_FNS_WITHOUT_BODY),
            reference: "issue #35203 <https://github.com/rust-lang/rust/issues/35203>",
            epoch: None,
        },
        FutureIncompatibleInfo {
            id: LintId::of(SAFE_EXTERN_STATICS),
            reference: "issue #36247 <https://github.com/rust-lang/rust/issues/36247>",
            epoch: None,
        },
        FutureIncompatibleInfo {
            id: LintId::of(INVALID_TYPE_PARAM_DEFAULT),
            reference: "issue #36887 <https://github.com/rust-lang/rust/issues/36887>",
            epoch: None,
        },
        FutureIncompatibleInfo {
            id: LintId::of(LEGACY_DIRECTORY_OWNERSHIP),
            reference: "issue #37872 <https://github.com/rust-lang/rust/issues/37872>",
            epoch: None,
        },
        FutureIncompatibleInfo {
            id: LintId::of(LEGACY_IMPORTS),
            reference: "issue #38260 <https://github.com/rust-lang/rust/issues/38260>",
            epoch: None,
        },
        FutureIncompatibleInfo {
            id: LintId::of(LEGACY_CONSTRUCTOR_VISIBILITY),
            reference: "issue #39207 <https://github.com/rust-lang/rust/issues/39207>",
            epoch: None,
        },
        FutureIncompatibleInfo {
            id: LintId::of(RESOLVE_TRAIT_ON_DEFAULTED_UNIT),
            reference: "issue #39216 <https://github.com/rust-lang/rust/issues/39216>",
            epoch: None,
        },
        FutureIncompatibleInfo {
            id: LintId::of(MISSING_FRAGMENT_SPECIFIER),
            reference: "issue #40107 <https://github.com/rust-lang/rust/issues/40107>",
            epoch: None,
        },
        FutureIncompatibleInfo {
            id: LintId::of(ILLEGAL_FLOATING_POINT_LITERAL_PATTERN),
            reference: "issue #41620 <https://github.com/rust-lang/rust/issues/41620>",
            epoch: None,
        },
        FutureIncompatibleInfo {
            id: LintId::of(ANONYMOUS_PARAMETERS),
            reference: "issue #41686 <https://github.com/rust-lang/rust/issues/41686>",
            epoch: None,
        },
        FutureIncompatibleInfo {
            id: LintId::of(PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES),
            reference: "issue #42238 <https://github.com/rust-lang/rust/issues/42238>",
            epoch: None,
        },
        FutureIncompatibleInfo {
            id: LintId::of(LATE_BOUND_LIFETIME_ARGUMENTS),
            reference: "issue #42868 <https://github.com/rust-lang/rust/issues/42868>",
            epoch: None,
        },
        FutureIncompatibleInfo {
            id: LintId::of(SAFE_PACKED_BORROWS),
            reference: "issue #46043 <https://github.com/rust-lang/rust/issues/46043>",
            epoch: None,
        },
        FutureIncompatibleInfo {
            id: LintId::of(INCOHERENT_FUNDAMENTAL_IMPLS),
            reference: "issue #46205 <https://github.com/rust-lang/rust/issues/46205>",
            epoch: None,
        },
        FutureIncompatibleInfo {
            id: LintId::of(COERCE_NEVER),
            reference: "issue #46325 <https://github.com/rust-lang/rust/issues/46325>",
            epoch: None,
        },
        FutureIncompatibleInfo {
            id: LintId::of(TYVAR_BEHIND_RAW_POINTER),
            reference: "issue #46906 <https://github.com/rust-lang/rust/issues/46906>",
            epoch: None,
        },
         FutureIncompatibleInfo {
             id: LintId::of(lint::builtin::BARE_TRAIT_OBJECT),
             reference: "issue #48457 <https://github.com/rust-lang/rust/issues/48457>",
             epoch: Some(Epoch::Epoch2018),
         }
        ]);

    // Register renamed and removed lints
    store.register_renamed("unknown_features", "unused_features");
    store.register_removed("unsigned_negation", "replaced by negate_unsigned feature gate");
    store.register_removed("negate_unsigned", "cast a signed value instead");
    store.register_removed("raw_pointer_derive", "using derive with raw pointers is ok");
    // This was renamed to raw_pointer_derive, which was then removed,
    // so it is also considered removed
    store.register_removed("raw_pointer_deriving", "using derive with raw pointers is ok");
    store.register_removed("drop_with_repr_extern", "drop flags have been removed");
    store.register_removed("fat_ptr_transmutes", "was accidentally removed back in 2014");
    store.register_removed("deprecated_attr", "use `deprecated` instead");
    store.register_removed("transmute_from_fn_item_types",
        "always cast functions before transmuting them");
    store.register_removed("hr_lifetime_in_assoc_type",
        "converted into hard error, see https://github.com/rust-lang/rust/issues/33685");
    store.register_removed("inaccessible_extern_crate",
        "converted into hard error, see https://github.com/rust-lang/rust/issues/36886");
    store.register_removed("super_or_self_in_global_path",
        "converted into hard error, see https://github.com/rust-lang/rust/issues/36888");
    store.register_removed("overlapping_inherent_impls",
        "converted into hard error, see https://github.com/rust-lang/rust/issues/36889");
    store.register_removed("illegal_floating_point_constant_pattern",
        "converted into hard error, see https://github.com/rust-lang/rust/issues/36890");
    store.register_removed("illegal_struct_or_enum_constant_pattern",
        "converted into hard error, see https://github.com/rust-lang/rust/issues/36891");
    store.register_removed("lifetime_underscore",
        "converted into hard error, see https://github.com/rust-lang/rust/issues/36892");
    store.register_removed("extra_requirement_in_impl",
        "converted into hard error, see https://github.com/rust-lang/rust/issues/37166");
}
<commit_msg>Make tyvar_behind_raw_pointer an epoch lint<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.

//! Lints in the Rust compiler.
//!
//! This currently only contains the definitions and implementations
//! of most of the lints that `rustc` supports directly, it does not
//! contain the infrastructure for defining/registering lints. That is
//! available in `rustc::lint` and `rustc_plugin` respectively.
//!
//! # Note
//!
//! This API is completely unstable and subject to change.

#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
      html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
      html_root_url = "https://doc.rust-lang.org/nightly/")]
#![deny(warnings)]

#![cfg_attr(test, feature(test))]
#![feature(box_patterns)]
#![feature(box_syntax)]
#![feature(i128_type)]
#![feature(macro_vis_matcher)]
#![feature(quote)]
#![feature(rustc_diagnostic_macros)]
#![feature(slice_patterns)]

#[macro_use]
extern crate syntax;
#[macro_use]
extern crate rustc;
#[macro_use]
extern crate log;
extern crate rustc_mir;
extern crate syntax_pos;

use rustc::lint;
use rustc::session;
use rustc::util;

use session::Session;
use syntax::epoch::Epoch;
use lint::LintId;
use lint::FutureIncompatibleInfo;

mod bad_style;
mod builtin;
mod types;
mod unused;

use bad_style::*;
use builtin::*;
use types::*;
use unused::*;

/// Tell the `LintStore` about all the built-in lints (the ones
/// defined in this crate and the ones defined in
/// `rustc::lint::builtin`).
pub fn register_builtins(store: &mut lint::LintStore, sess: Option<&Session>) {
    macro_rules! add_builtin {
        ($sess:ident, $($name:ident),*,) => (
            {$(
                store.register_late_pass($sess, false, box $name);
                )*}
            )
    }

    macro_rules! add_early_builtin {
        ($sess:ident, $($name:ident),*,) => (
            {$(
                store.register_early_pass($sess, false, box $name);
                )*}
            )
    }

    macro_rules! add_builtin_with_new {
        ($sess:ident, $($name:ident),*,) => (
            {$(
                store.register_late_pass($sess, false, box $name::new());
                )*}
            )
    }

    macro_rules! add_early_builtin_with_new {
        ($sess:ident, $($name:ident),*,) => (
            {$(
                store.register_early_pass($sess, false, box $name::new());
                )*}
            )
    }

    macro_rules! add_lint_group {
        ($sess:ident, $name:expr, $($lint:ident),*) => (
            store.register_group($sess, false, $name, vec![$(LintId::of($lint)),*]);
            )
    }

    add_early_builtin!(sess,
                       UnusedParens,
                       UnusedImportBraces,
                       AnonymousParameters,
                       UnusedDocComment,
                       );

    add_early_builtin_with_new!(sess,
                                DeprecatedAttr,
                                );

    add_builtin!(sess,
                 HardwiredLints,
                 WhileTrue,
                 ImproperCTypes,
                 VariantSizeDifferences,
                 BoxPointers,
                 UnusedAttributes,
                 PathStatements,
                 UnusedResults,
                 NonCamelCaseTypes,
                 NonSnakeCase,
                 NonUpperCaseGlobals,
                 NonShorthandFieldPatterns,
                 UnsafeCode,
                 UnusedAllocation,
                 MissingCopyImplementations,
                 UnstableFeatures,
                 UnconditionalRecursion,
                 InvalidNoMangleItems,
                 PluginAsLibrary,
                 MutableTransmutes,
                 UnionsWithDropFields,
                 UnreachablePub,
                 );

    add_builtin_with_new!(sess,
                          TypeLimits,
                          MissingDoc,
                          MissingDebugImplementations,
                          );

    add_lint_group!(sess,
                    "bad_style",
                    NON_CAMEL_CASE_TYPES,
                    NON_SNAKE_CASE,
                    NON_UPPER_CASE_GLOBALS);

    add_lint_group!(sess,
                    "nonstandard_style",
                    NON_CAMEL_CASE_TYPES,
                    NON_SNAKE_CASE,
                    NON_UPPER_CASE_GLOBALS);

    add_lint_group!(sess,
                    "unused",
                    UNUSED_IMPORTS,
                    UNUSED_VARIABLES,
                    UNUSED_ASSIGNMENTS,
                    DEAD_CODE,
                    UNUSED_MUT,
                    UNREACHABLE_CODE,
                    UNREACHABLE_PATTERNS,
                    UNUSED_MUST_USE,
                    UNUSED_UNSAFE,
                    PATH_STATEMENTS,
                    UNUSED_ATTRIBUTES,
                    UNUSED_MACROS,
                    UNUSED_ALLOCATION,
                    UNUSED_DOC_COMMENT,
                    UNUSED_EXTERN_CRATES,
                    UNUSED_FEATURES,
                    UNUSED_PARENS);

    // Guidelines for creating a future incompatibility lint:
    //
    // - Create a lint defaulting to warn as normal, with ideally the same error
    //   message you would normally give
    // - Add a suitable reference, typically an RFC or tracking issue. Go ahead
    //   and include the full URL, sort items in ascending order of issue numbers.
    // - Later, change lint to error
    // - Eventually, remove lint
    store.register_future_incompatible(sess,
                                       vec![
        FutureIncompatibleInfo {
            id: LintId::of(PRIVATE_IN_PUBLIC),
            reference: "issue #34537 <https://github.com/rust-lang/rust/issues/34537>",
            epoch: None,
        },
        FutureIncompatibleInfo {
            id: LintId::of(PUB_USE_OF_PRIVATE_EXTERN_CRATE),
            reference: "issue #34537 <https://github.com/rust-lang/rust/issues/34537>",
            epoch: None,
        },
        FutureIncompatibleInfo {
            id: LintId::of(PATTERNS_IN_FNS_WITHOUT_BODY),
            reference: "issue #35203 <https://github.com/rust-lang/rust/issues/35203>",
            epoch: None,
        },
        FutureIncompatibleInfo {
            id: LintId::of(SAFE_EXTERN_STATICS),
            reference: "issue #36247 <https://github.com/rust-lang/rust/issues/36247>",
            epoch: None,
        },
        FutureIncompatibleInfo {
            id: LintId::of(INVALID_TYPE_PARAM_DEFAULT),
            reference: "issue #36887 <https://github.com/rust-lang/rust/issues/36887>",
            epoch: None,
        },
        FutureIncompatibleInfo {
            id: LintId::of(LEGACY_DIRECTORY_OWNERSHIP),
            reference: "issue #37872 <https://github.com/rust-lang/rust/issues/37872>",
            epoch: None,
        },
        FutureIncompatibleInfo {
            id: LintId::of(LEGACY_IMPORTS),
            reference: "issue #38260 <https://github.com/rust-lang/rust/issues/38260>",
            epoch: None,
        },
        FutureIncompatibleInfo {
            id: LintId::of(LEGACY_CONSTRUCTOR_VISIBILITY),
            reference: "issue #39207 <https://github.com/rust-lang/rust/issues/39207>",
            epoch: None,
        },
        FutureIncompatibleInfo {
            id: LintId::of(RESOLVE_TRAIT_ON_DEFAULTED_UNIT),
            reference: "issue #39216 <https://github.com/rust-lang/rust/issues/39216>",
            epoch: None,
        },
        FutureIncompatibleInfo {
            id: LintId::of(MISSING_FRAGMENT_SPECIFIER),
            reference: "issue #40107 <https://github.com/rust-lang/rust/issues/40107>",
            epoch: None,
        },
        FutureIncompatibleInfo {
            id: LintId::of(ILLEGAL_FLOATING_POINT_LITERAL_PATTERN),
            reference: "issue #41620 <https://github.com/rust-lang/rust/issues/41620>",
            epoch: None,
        },
        FutureIncompatibleInfo {
            id: LintId::of(ANONYMOUS_PARAMETERS),
            reference: "issue #41686 <https://github.com/rust-lang/rust/issues/41686>",
            epoch: None,
        },
        FutureIncompatibleInfo {
            id: LintId::of(PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES),
            reference: "issue #42238 <https://github.com/rust-lang/rust/issues/42238>",
            epoch: None,
        },
        FutureIncompatibleInfo {
            id: LintId::of(LATE_BOUND_LIFETIME_ARGUMENTS),
            reference: "issue #42868 <https://github.com/rust-lang/rust/issues/42868>",
            epoch: None,
        },
        FutureIncompatibleInfo {
            id: LintId::of(SAFE_PACKED_BORROWS),
            reference: "issue #46043 <https://github.com/rust-lang/rust/issues/46043>",
            epoch: None,
        },
        FutureIncompatibleInfo {
            id: LintId::of(INCOHERENT_FUNDAMENTAL_IMPLS),
            reference: "issue #46205 <https://github.com/rust-lang/rust/issues/46205>",
            epoch: None,
        },
        FutureIncompatibleInfo {
            id: LintId::of(COERCE_NEVER),
            reference: "issue #46325 <https://github.com/rust-lang/rust/issues/46325>",
            epoch: None,
        },
        FutureIncompatibleInfo {
            id: LintId::of(TYVAR_BEHIND_RAW_POINTER),
            reference: "issue #46906 <https://github.com/rust-lang/rust/issues/46906>",
            epoch: Some(Epoch::Epoch2018),
        },
         FutureIncompatibleInfo {
             id: LintId::of(lint::builtin::BARE_TRAIT_OBJECT),
             reference: "issue #48457 <https://github.com/rust-lang/rust/issues/48457>",
             epoch: Some(Epoch::Epoch2018),
         }
        ]);

    // Register renamed and removed lints
    store.register_renamed("unknown_features", "unused_features");
    store.register_removed("unsigned_negation", "replaced by negate_unsigned feature gate");
    store.register_removed("negate_unsigned", "cast a signed value instead");
    store.register_removed("raw_pointer_derive", "using derive with raw pointers is ok");
    // This was renamed to raw_pointer_derive, which was then removed,
    // so it is also considered removed
    store.register_removed("raw_pointer_deriving", "using derive with raw pointers is ok");
    store.register_removed("drop_with_repr_extern", "drop flags have been removed");
    store.register_removed("fat_ptr_transmutes", "was accidentally removed back in 2014");
    store.register_removed("deprecated_attr", "use `deprecated` instead");
    store.register_removed("transmute_from_fn_item_types",
        "always cast functions before transmuting them");
    store.register_removed("hr_lifetime_in_assoc_type",
        "converted into hard error, see https://github.com/rust-lang/rust/issues/33685");
    store.register_removed("inaccessible_extern_crate",
        "converted into hard error, see https://github.com/rust-lang/rust/issues/36886");
    store.register_removed("super_or_self_in_global_path",
        "converted into hard error, see https://github.com/rust-lang/rust/issues/36888");
    store.register_removed("overlapping_inherent_impls",
        "converted into hard error, see https://github.com/rust-lang/rust/issues/36889");
    store.register_removed("illegal_floating_point_constant_pattern",
        "converted into hard error, see https://github.com/rust-lang/rust/issues/36890");
    store.register_removed("illegal_struct_or_enum_constant_pattern",
        "converted into hard error, see https://github.com/rust-lang/rust/issues/36891");
    store.register_removed("lifetime_underscore",
        "converted into hard error, see https://github.com/rust-lang/rust/issues/36892");
    store.register_removed("extra_requirement_in_impl",
        "converted into hard error, see https://github.com/rust-lang/rust/issues/37166");
}
<|endoftext|>


<commit_before><commit_msg>Arithmetic expression parser to AST.<commit_after>#[macro_use]
extern crate nom;

use std::fmt;
use std::fmt::{Display, Debug, Formatter};

use std::str;
use std::str::FromStr;

use nom::{IResult, digit, multispace};

pub enum Expr {
    Value(i64),
    Add(Box<Expr>, Box<Expr>),
    Sub(Box<Expr>, Box<Expr>),
    Mul(Box<Expr>, Box<Expr>),
    Div(Box<Expr>, Box<Expr>),
    Paren(Box<Expr>),
}

pub enum Oper {
    Add,
    Sub,
    Mul,
    Div,
}

impl Display for Expr {
    fn fmt(&self, format: &mut Formatter) -> fmt::Result {
        use self::Expr::*;
        match *self {
            Value(val) => write!(format, "{}", val),
            Add(ref left, ref right) => write!(format, "{} + {}", left, right),
            Sub(ref left, ref right) => write!(format, "{} - {}", left, right),
            Mul(ref left, ref right) => write!(format, "{} * {}", left, right),
            Div(ref left, ref right) => write!(format, "{} / {}", left, right),
            Paren(ref expr) => write!(format, "({})", expr),
        }
    }
}

impl Debug for Expr {
    fn fmt(&self, format: &mut Formatter) -> fmt::Result {
        use self::Expr::*;
        match *self {
            Value(val) => write!(format, "{}", val),
            Add(ref left, ref right) => write!(format, "({:?} + {:?})", left, right),
            Sub(ref left, ref right) => write!(format, "({:?} - {:?})", left, right),
            Mul(ref left, ref right) => write!(format, "({:?} * {:?})", left, right),
            Div(ref left, ref right) => write!(format, "({:?} / {:?})", left, right),
            Paren(ref expr) => write!(format, "[{:?}]", expr),
        }
    }
}

named!(parens< Expr >, delimited!(
    delimited!(opt!(multispace), tag!("("), opt!(multispace)),
    map!(map!(expr, Box::new), Expr::Paren),
    delimited!(opt!(multispace), tag!(")"), opt!(multispace))
  )
);

named!(factor< Expr >, alt_complete!(
    map!(
      map_res!(
        map_res!(
          delimited!(opt!(multispace), digit, opt!(multispace)),
          str::from_utf8
        ),
      FromStr::from_str
    ),
    Expr::Value)
  | parens
  )
);

fn fold_exprs(initial: Expr, remainder: Vec<(Oper, Expr)>) -> Expr {
    remainder.into_iter().fold(initial, |acc, pair| {
        let (oper, expr) = pair;
        match oper {
            Oper::Add => Expr::Add(Box::new(acc), Box::new(expr)),
            Oper::Sub => Expr::Sub(Box::new(acc), Box::new(expr)),
            Oper::Mul => Expr::Mul(Box::new(acc), Box::new(expr)),
            Oper::Div => Expr::Div(Box::new(acc), Box::new(expr)),
        }
    })
}

named!(term< Expr >, chain!(
    initial: factor ~
    remainder: many0!(
           alt!(
             chain!(tag!("*") ~ mul: factor, || { (Oper::Mul, mul) }) |
             chain!(tag!("/") ~ div: factor, || { (Oper::Div, div) })
           )
         ),
    || fold_exprs(initial, remainder))
);

named!(expr< Expr >, chain!(
    initial: term ~
    remainder: many0!(
           alt!(
             chain!(tag!("+") ~ add: term, || { (Oper::Add, add) }) |
             chain!(tag!("-") ~ sub: term, || { (Oper::Sub, sub) })
           )
         ),
    || fold_exprs(initial, remainder))
);

#[test]
fn factor_test() {
    assert_eq!(factor(&b"  3  "[..]).map(|x| format!("{:?}", x)),
               IResult::Done(&b""[..], String::from("3")));
}

#[test]
fn term_test() {
    assert_eq!(term(&b" 3 *  5   "[..]).map(|x| format!("{:?}", x)),
               IResult::Done(&b""[..], String::from("(3 * 5)")));
}

#[test]
fn expr_test() {
    assert_eq!(expr(&b" 1 + 2 *  3 "[..]).map(|x| format!("{:?}", x)),
               IResult::Done(&b""[..], String::from("(1 + (2 * 3))")));
    assert_eq!(expr(&b" 1 + 2 *  3 / 4 - 5 "[..]).map(|x| format!("{:?}", x)),
               IResult::Done(&b""[..], String::from("((1 + ((2 * 3) / 4)) - 5)")));
    assert_eq!(expr(&b" 72 / 2 / 3 "[..]).map(|x| format!("{:?}", x)),
               IResult::Done(&b""[..], String::from("((72 / 2) / 3)")));
}

#[test]
fn parens_test() {
    assert_eq!(expr(&b" ( 1 + 2 ) *  3 "[..]).map(|x| format!("{:?}", x)),
               IResult::Done(&b""[..], String::from("([(1 + 2)] * 3)")));
}
<|endoftext|>


<commit_before>use harfbuzz;

export shape_text;

import libc::types::common::c99::int32_t;
import libc::{c_uint, c_int, c_void};
import font::font;
import glyph::{glyph, glyph_pos};
import ptr::{null, addr_of, offset};
import gfx::geometry::{au, px_to_au};
import geom::point::Point2D;

import unsafe::reinterpret_cast;
import harfbuzz::{HB_MEMORY_MODE_READONLY,
                  HB_DIRECTION_LTR};
import harfbuzz::{hb_blob_t, hb_face_t, hb_font_t, hb_buffer_t,
                  hb_codepoint_t, hb_bool_t, hb_glyph_position_t,
				  hb_var_int_t};
import harfbuzz::bindgen::{hb_blob_create, hb_blob_destroy,
                           hb_face_create, hb_face_destroy,
                           hb_font_create, hb_font_destroy,
                           hb_buffer_create, hb_buffer_destroy,
                           hb_buffer_add_utf8, hb_shape,
                           hb_buffer_get_glyph_infos,
                           hb_buffer_get_glyph_positions,
                           hb_font_set_ppem, hb_font_set_scale,
                           hb_buffer_set_direction,
                           hb_font_funcs_create, hb_font_funcs_destroy,
                           hb_font_set_funcs,
                           hb_font_funcs_set_glyph_h_advance_func,
                           hb_font_funcs_set_glyph_func,
                           hb_font_funcs_set_glyph_h_kerning_func};

#[doc = "
Calculate the layout metrics associated with a some given text
when rendered in a specific font.
"]
fn shape_text(_font: &font, text: str) -> [glyph] {
    let mut glyphs = [];
    let mut cur_x = 0u;
    for text.each_char {
        |ch|
        // TODO: Use HarfBuzz!
        let hb_pos = {
            x_advance: 10 as int32_t,
            y_advance: 0 as int32_t,
            x_offset: cur_x as int32_t,
            y_offset: 0 as int32_t,
            var: 0 as hb_var_int_t
        };

        let pos = hb_glyph_pos_to_servo_glyph_pos(hb_pos);
        vec::push(glyphs, glyph(ch as uint, pos));
        cur_x += 10u;
    };

    ret glyphs;
}

fn shape_text2(font: &font, text: str) -> [glyph] unsafe {
    #debug("shaping text '%s'", text);

    let face_blob = vec::as_buf(*(*font).buf()) { |buf|
        hb_blob_create(reinterpret_cast(buf),
                       (*(*font).buf()).len() as c_uint,
                       HB_MEMORY_MODE_READONLY,
                       null(),
                       null())
    };

    let face = hb_face_create(face_blob, 0 as c_uint);
    let font = hb_font_create(face);

    hb_font_set_ppem(font, 10 as c_uint, 10 as c_uint);
    hb_font_set_scale(font, 10 as c_int, 10 as c_int);

    let funcs = hb_font_funcs_create();
    hb_font_funcs_set_glyph_func(funcs, glyph_func, null(), null());
    hb_font_set_funcs(font, funcs, addr_of(*font), null());

    let buffer = hb_buffer_create();

    hb_buffer_set_direction(buffer, HB_DIRECTION_LTR);

    str::as_c_str(text) { |ctext|
        hb_buffer_add_utf8(buffer, ctext,
                           text.len() as c_int,
                           0 as c_uint,
                           text.len() as c_int);
    }

    hb_shape(font, buffer, null(), 0 as c_uint);

    let info_len = 0 as c_uint;
    let info_ = hb_buffer_get_glyph_infos(buffer, addr_of(info_len));
    assert info_.is_not_null();
    let pos_len = 0 as c_uint;
    let pos = hb_buffer_get_glyph_positions(buffer, addr_of(pos_len));
    assert pos.is_not_null();

    assert info_len == pos_len;

    for uint::range(0u, info_len as uint) { |i|
        let info_ = offset(info_, i);
        let pos = offset(pos, i);
        #debug("glyph %?: codep %?, cluster %?,\
                x_adv %?, y_adv %?, x_off %?, y_of %?",
               i, (*info_).codepoint, (*info_).cluster,
               (*pos).x_advance, (*pos).y_advance,
               (*pos).x_offset, (*pos).y_offset);
    }

    hb_buffer_destroy(buffer);
    hb_font_funcs_destroy(funcs);
    hb_font_destroy(font);
    hb_face_destroy(face);
    hb_blob_destroy(face_blob);

    ret [];
}

crust fn glyph_func(_font: *hb_font_t,
                    _font_data: *c_void,
                    _unicode: hb_codepoint_t,
                    _variant_selector: hb_codepoint_t,
                    glyph: *mut hb_codepoint_t,
                    _user_data: *c_void) -> hb_bool_t unsafe {

    *glyph = 40 as hb_codepoint_t;
    ret true as hb_bool_t;
}

fn hb_glyph_pos_to_servo_glyph_pos(hb_pos: hb_glyph_position_t) -> glyph_pos {
    glyph_pos(Point2D(px_to_au(hb_pos.x_advance as int),
                      px_to_au(hb_pos.y_advance as int)),
              Point2D(px_to_au(hb_pos.x_offset as int),
                      px_to_au(hb_pos.y_offset as int)))
}

#[test]
fn test_shape_basic() {
    let font = font::create_test_font();
    shape_text2(&font, "firecracker");
}
<commit_msg>Teach text::shaper how to find a glyph index from the font<commit_after>use harfbuzz;

export shape_text;

import libc::types::common::c99::int32_t;
import libc::{c_uint, c_int, c_void};
import font::font;
import glyph::{glyph, glyph_pos};
import ptr::{null, addr_of, offset};
import gfx::geometry::{au, px_to_au};
import geom::point::Point2D;

import unsafe::reinterpret_cast;
import harfbuzz::{HB_MEMORY_MODE_READONLY,
                  HB_DIRECTION_LTR};
import harfbuzz::{hb_blob_t, hb_face_t, hb_font_t, hb_buffer_t,
                  hb_codepoint_t, hb_bool_t, hb_glyph_position_t,
				  hb_var_int_t};
import harfbuzz::bindgen::{hb_blob_create, hb_blob_destroy,
                           hb_face_create, hb_face_destroy,
                           hb_font_create, hb_font_destroy,
                           hb_buffer_create, hb_buffer_destroy,
                           hb_buffer_add_utf8, hb_shape,
                           hb_buffer_get_glyph_infos,
                           hb_buffer_get_glyph_positions,
                           hb_font_set_ppem, hb_font_set_scale,
                           hb_buffer_set_direction,
                           hb_font_funcs_create, hb_font_funcs_destroy,
                           hb_font_set_funcs,
                           hb_font_funcs_set_glyph_h_advance_func,
                           hb_font_funcs_set_glyph_func,
                           hb_font_funcs_set_glyph_h_kerning_func};

#[doc = "
Calculate the layout metrics associated with a some given text
when rendered in a specific font.
"]
fn shape_text(_font: &font, text: str) -> [glyph] {
    let mut glyphs = [];
    let mut cur_x = 0u;
    for text.each_char {
        |ch|
        // TODO: Use HarfBuzz!
        let hb_pos = {
            x_advance: 10 as int32_t,
            y_advance: 0 as int32_t,
            x_offset: cur_x as int32_t,
            y_offset: 0 as int32_t,
            var: 0 as hb_var_int_t
        };

        let pos = hb_glyph_pos_to_servo_glyph_pos(hb_pos);
        vec::push(glyphs, glyph(ch as uint, pos));
        cur_x += 10u;
    };

    ret glyphs;
}

fn shape_text2(font: &font, text: str) -> [glyph] unsafe {
    #debug("shaping text '%s'", text);

    let face_blob = vec::as_buf(*(*font).buf()) { |buf|
        hb_blob_create(reinterpret_cast(buf),
                       (*(*font).buf()).len() as c_uint,
                       HB_MEMORY_MODE_READONLY,
                       null(),
                       null())
    };

    let hbface = hb_face_create(face_blob, 0 as c_uint);
    let hbfont = hb_font_create(hbface);

    hb_font_set_ppem(hbfont, 10 as c_uint, 10 as c_uint);
    hb_font_set_scale(hbfont, 10 as c_int, 10 as c_int);

    let funcs = hb_font_funcs_create();
    hb_font_funcs_set_glyph_func(funcs, glyph_func, null(), null());
    hb_font_set_funcs(hbfont, funcs, reinterpret_cast(addr_of(*font)), null());

    let buffer = hb_buffer_create();

    hb_buffer_set_direction(buffer, HB_DIRECTION_LTR);

    str::as_c_str(text) { |ctext|
        hb_buffer_add_utf8(buffer, ctext,
                           text.len() as c_int,
                           0 as c_uint,
                           text.len() as c_int);
    }

    hb_shape(hbfont, buffer, null(), 0 as c_uint);

    let info_len = 0 as c_uint;
    let info_ = hb_buffer_get_glyph_infos(buffer, addr_of(info_len));
    assert info_.is_not_null();
    let pos_len = 0 as c_uint;
    let pos = hb_buffer_get_glyph_positions(buffer, addr_of(pos_len));
    assert pos.is_not_null();

    assert info_len == pos_len;

    for uint::range(0u, info_len as uint) { |i|
        let info_ = offset(info_, i);
        let pos = offset(pos, i);
        #debug("glyph %?: codep %?, cluster %?,\
                x_adv %?, y_adv %?, x_off %?, y_of %?",
               i, (*info_).codepoint, (*info_).cluster,
               (*pos).x_advance, (*pos).y_advance,
               (*pos).x_offset, (*pos).y_offset);
    }

    hb_buffer_destroy(buffer);
    hb_font_funcs_destroy(funcs);
    hb_font_destroy(hbfont);
    hb_face_destroy(hbface);
    hb_blob_destroy(face_blob);

    ret [];
}

crust fn glyph_func(_font: *hb_font_t,
                    font_data: *c_void,
                    unicode: hb_codepoint_t,
                    _variant_selector: hb_codepoint_t,
                    glyph: *mut hb_codepoint_t,
                    _user_data: *c_void) -> hb_bool_t unsafe {

    let font: *font = reinterpret_cast(font_data);
    assert font.is_not_null();

    ret alt (*font).get_glyph_idx(unicode as char) {
      some(g) {
        *glyph = g as hb_codepoint_t;
        true
      }
      none {
        false
      }
    } as hb_bool_t;
}

fn hb_glyph_pos_to_servo_glyph_pos(hb_pos: hb_glyph_position_t) -> glyph_pos {
    glyph_pos(Point2D(px_to_au(hb_pos.x_advance as int),
                      px_to_au(hb_pos.y_advance as int)),
              Point2D(px_to_au(hb_pos.x_offset as int),
                      px_to_au(hb_pos.y_offset as int)))
}

#[test]
fn test_shape_basic() {
    let font = font::create_test_font();
    shape_text2(&font, "firecracker");
}
<|endoftext|>


<commit_before><commit_msg>languages/rust/learn-rust/3-chapter/3-code.rs<commit_after><|endoftext|>


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

/*!

Signal handling

This modules provides bindings to receive signals safely, built on top of the
local I/O factory. There are a number of defined signals which can be caught,
but not all signals will work across all platforms (windows doesn't have
definitions for a number of signals.

*/

use clone::Clone;
use comm::{Sender, Receiver, channel};
use io;
use iter::Iterator;
use mem::drop;
use option::{Some, None};
use result::{Ok, Err};
use rt::rtio::{IoFactory, LocalIo, RtioSignal};
use slice::{ImmutableVector, OwnedVector};

/// Signals that can be sent and received
#[repr(int)]
#[deriving(Eq, Hash, Show)]
pub enum Signum {
    /// Equivalent to SIGBREAK, delivered when the user presses Ctrl-Break.
    Break = 21i,
    /// Equivalent to SIGHUP, delivered when the user closes the terminal
    /// window. On delivery of HangUp, the program is given approximately
    /// 10 seconds to perform any cleanup. After that, Windows will
    /// unconditionally terminate it.
    HangUp = 1i,
    /// Equivalent to SIGINT, delivered when the user presses Ctrl-c.
    Interrupt = 2i,
    /// Equivalent to SIGQUIT, delivered when the user presses Ctrl-\.
    Quit = 3i,
    /// Equivalent to SIGTSTP, delivered when the user presses Ctrl-z.
    StopTemporarily = 20i,
    /// Equivalent to SIGUSR1.
    User1 = 10i,
    /// Equivalent to SIGUSR2.
    User2 = 12i,
    /// Equivalent to SIGWINCH, delivered when the console has been resized.
    /// WindowSizeChange may not be delivered in a timely manner; size change
    /// will only be detected when the cursor is being moved.
    WindowSizeChange = 28i,
}

/// Listener provides a receiver to listen for registered signals.
///
/// Listener automatically unregisters its handles once it is out of scope.
/// However, clients can still unregister signums manually.
///
/// # Example
///
/// ```rust,ignore
/// use std::io::signal::{Listener, Interrupt};
///
/// let mut listener = Listener::new();
/// listener.register(Interrupt);
///
/// spawn({
///     loop {
///         match listener.rx.recv() {
///             Interrupt => println!("Got Interrupt'ed"),
///             _ => (),
///         }
///     }
/// });
///
/// ```
pub struct Listener {
    /// A map from signums to handles to keep the handles in memory
    handles: ~[(Signum, ~RtioSignal)],
    /// This is where all the handles send signums, which are received by
    /// the clients from the receiver.
    tx: Sender<Signum>,

    /// Clients of Listener can `recv()` on this receiver. This is exposed to
    /// allow selection over it as well as manipulation of the receiver
    /// directly.
    pub rx: Receiver<Signum>,
}

impl Listener {
    /// Creates a new listener for signals. Once created, signals are bound via
    /// the `register` method (otherwise nothing will ever be received)
    pub fn new() -> Listener {
        let (tx, rx) = channel();
        Listener {
            tx: tx,
            rx: rx,
            handles: ~[],
        }
    }

    /// Listen for a signal, returning true when successfully registered for
    /// signum. Signals can be received using `recv()`.
    ///
    /// Once a signal is registered, this listener will continue to receive
    /// notifications of signals until it is unregistered. This occurs
    /// regardless of the number of other listeners registered in other tasks
    /// (or on this task).
    ///
    /// Signals are still received if there is no task actively waiting for
    /// a signal, and a later call to `recv` will return the signal that was
    /// received while no task was waiting on it.
    ///
    /// # Error
    ///
    /// If this function fails to register a signal handler, then an error will
    /// be returned.
    pub fn register(&mut self, signum: Signum) -> io::IoResult<()> {
        if self.handles.iter().any(|&(sig, _)| sig == signum) {
            return Ok(()); // self is already listening to signum, so succeed
        }
        match LocalIo::maybe_raise(|io| {
            io.signal(signum, self.tx.clone())
        }) {
            Ok(handle) => {
                self.handles.push((signum, handle));
                Ok(())
            }
            Err(e) => Err(e)
        }
    }

    /// Unregisters a signal. If this listener currently had a handler
    /// registered for the signal, then it will stop receiving any more
    /// notification about the signal. If the signal has already been received,
    /// it may still be returned by `recv`.
    pub fn unregister(&mut self, signum: Signum) {
        match self.handles.iter().position(|&(i, _)| i == signum) {
            Some(i) => drop(self.handles.remove(i)),
            None => {}
        }
    }
}

#[cfg(test, unix)]
mod test_unix {
    use libc;
    use comm::Empty;
    use io::timer;
    use super::{Listener, Interrupt};

    fn sigint() {
        unsafe {
            libc::funcs::posix88::signal::kill(libc::getpid(), libc::SIGINT);
        }
    }

    #[test] #[cfg(not(target_os="android"))] // FIXME(#10378)
    fn test_io_signal_smoketest() {
        let mut signal = Listener::new();
        signal.register(Interrupt).unwrap();
        sigint();
        timer::sleep(10);
        match signal.rx.recv() {
            Interrupt => (),
            s => fail!("Expected Interrupt, got {:?}", s),
        }
    }

    #[test] #[cfg(not(target_os="android"))] // FIXME(#10378)
    fn test_io_signal_two_signal_one_signum() {
        let mut s1 = Listener::new();
        let mut s2 = Listener::new();
        s1.register(Interrupt).unwrap();
        s2.register(Interrupt).unwrap();
        sigint();
        timer::sleep(10);
        match s1.rx.recv() {
            Interrupt => (),
            s => fail!("Expected Interrupt, got {:?}", s),
        }
        match s2.rx.recv() {
            Interrupt => (),
            s => fail!("Expected Interrupt, got {:?}", s),
        }
    }

    #[test] #[cfg(not(target_os="android"))] // FIXME(#10378)
    fn test_io_signal_unregister() {
        let mut s1 = Listener::new();
        let mut s2 = Listener::new();
        s1.register(Interrupt).unwrap();
        s2.register(Interrupt).unwrap();
        s2.unregister(Interrupt);
        sigint();
        timer::sleep(10);
        assert_eq!(s2.rx.try_recv(), Empty);
    }
}

#[cfg(test, windows)]
mod test_windows {
    use super::{User1, Listener};
    use result::{Ok, Err};

    #[test]
    fn test_io_signal_invalid_signum() {
        let mut s = Listener::new();
        match s.register(User1) {
            Ok(..) => {
                fail!("Unexpected successful registry of signum {:?}", User1);
            }
            Err(..) => {}
        }
    }
}
<commit_msg>auto merge of #13354 : alexcrichton/rust/fixup-some-signals, r=sfackler<commit_after>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

/*!

Signal handling

This modules provides bindings to receive signals safely, built on top of the
local I/O factory. There are a number of defined signals which can be caught,
but not all signals will work across all platforms (windows doesn't have
definitions for a number of signals.

*/

use clone::Clone;
use comm::{Sender, Receiver, channel};
use io;
use iter::Iterator;
use kinds::Send;
use mem::drop;
use option::{Some, None};
use result::{Ok, Err};
use rt::rtio::{IoFactory, LocalIo, RtioSignal};
use slice::{ImmutableVector, OwnedVector};

/// Signals that can be sent and received
#[repr(int)]
#[deriving(Eq, Hash, Show)]
pub enum Signum {
    /// Equivalent to SIGBREAK, delivered when the user presses Ctrl-Break.
    Break = 21i,
    /// Equivalent to SIGHUP, delivered when the user closes the terminal
    /// window. On delivery of HangUp, the program is given approximately
    /// 10 seconds to perform any cleanup. After that, Windows will
    /// unconditionally terminate it.
    HangUp = 1i,
    /// Equivalent to SIGINT, delivered when the user presses Ctrl-c.
    Interrupt = 2i,
    /// Equivalent to SIGQUIT, delivered when the user presses Ctrl-\.
    Quit = 3i,
    /// Equivalent to SIGTSTP, delivered when the user presses Ctrl-z.
    StopTemporarily = 20i,
    /// Equivalent to SIGUSR1.
    User1 = 10i,
    /// Equivalent to SIGUSR2.
    User2 = 12i,
    /// Equivalent to SIGWINCH, delivered when the console has been resized.
    /// WindowSizeChange may not be delivered in a timely manner; size change
    /// will only be detected when the cursor is being moved.
    WindowSizeChange = 28i,
}

/// Listener provides a receiver to listen for registered signals.
///
/// Listener automatically unregisters its handles once it is out of scope.
/// However, clients can still unregister signums manually.
///
/// # Example
///
/// ```rust,no_run
/// # #![allow(unused_must_use)]
/// use std::io::signal::{Listener, Interrupt};
///
/// let mut listener = Listener::new();
/// listener.register(Interrupt);
///
/// loop {
///     match listener.rx.recv() {
///         Interrupt => println!("Got Interrupt'ed"),
///         _ => (),
///     }
/// }
/// ```
pub struct Listener {
    /// A map from signums to handles to keep the handles in memory
    handles: ~[(Signum, ~RtioSignal:Send)],
    /// This is where all the handles send signums, which are received by
    /// the clients from the receiver.
    tx: Sender<Signum>,

    /// Clients of Listener can `recv()` on this receiver. This is exposed to
    /// allow selection over it as well as manipulation of the receiver
    /// directly.
    pub rx: Receiver<Signum>,
}

impl Listener {
    /// Creates a new listener for signals. Once created, signals are bound via
    /// the `register` method (otherwise nothing will ever be received)
    pub fn new() -> Listener {
        let (tx, rx) = channel();
        Listener {
            tx: tx,
            rx: rx,
            handles: ~[],
        }
    }

    /// Listen for a signal, returning true when successfully registered for
    /// signum. Signals can be received using `recv()`.
    ///
    /// Once a signal is registered, this listener will continue to receive
    /// notifications of signals until it is unregistered. This occurs
    /// regardless of the number of other listeners registered in other tasks
    /// (or on this task).
    ///
    /// Signals are still received if there is no task actively waiting for
    /// a signal, and a later call to `recv` will return the signal that was
    /// received while no task was waiting on it.
    ///
    /// # Error
    ///
    /// If this function fails to register a signal handler, then an error will
    /// be returned.
    pub fn register(&mut self, signum: Signum) -> io::IoResult<()> {
        if self.handles.iter().any(|&(sig, _)| sig == signum) {
            return Ok(()); // self is already listening to signum, so succeed
        }
        match LocalIo::maybe_raise(|io| {
            io.signal(signum, self.tx.clone())
        }) {
            Ok(handle) => {
                self.handles.push((signum, handle));
                Ok(())
            }
            Err(e) => Err(e)
        }
    }

    /// Unregisters a signal. If this listener currently had a handler
    /// registered for the signal, then it will stop receiving any more
    /// notification about the signal. If the signal has already been received,
    /// it may still be returned by `recv`.
    pub fn unregister(&mut self, signum: Signum) {
        match self.handles.iter().position(|&(i, _)| i == signum) {
            Some(i) => drop(self.handles.remove(i)),
            None => {}
        }
    }
}

#[cfg(test, unix)]
mod test_unix {
    use libc;
    use comm::Empty;
    use io::timer;
    use super::{Listener, Interrupt};

    fn sigint() {
        unsafe {
            libc::funcs::posix88::signal::kill(libc::getpid(), libc::SIGINT);
        }
    }

    #[test] #[cfg(not(target_os="android"))] // FIXME(#10378)
    fn test_io_signal_smoketest() {
        let mut signal = Listener::new();
        signal.register(Interrupt).unwrap();
        sigint();
        timer::sleep(10);
        match signal.rx.recv() {
            Interrupt => (),
            s => fail!("Expected Interrupt, got {:?}", s),
        }
    }

    #[test] #[cfg(not(target_os="android"))] // FIXME(#10378)
    fn test_io_signal_two_signal_one_signum() {
        let mut s1 = Listener::new();
        let mut s2 = Listener::new();
        s1.register(Interrupt).unwrap();
        s2.register(Interrupt).unwrap();
        sigint();
        timer::sleep(10);
        match s1.rx.recv() {
            Interrupt => (),
            s => fail!("Expected Interrupt, got {:?}", s),
        }
        match s2.rx.recv() {
            Interrupt => (),
            s => fail!("Expected Interrupt, got {:?}", s),
        }
    }

    #[test] #[cfg(not(target_os="android"))] // FIXME(#10378)
    fn test_io_signal_unregister() {
        let mut s1 = Listener::new();
        let mut s2 = Listener::new();
        s1.register(Interrupt).unwrap();
        s2.register(Interrupt).unwrap();
        s2.unregister(Interrupt);
        sigint();
        timer::sleep(10);
        assert_eq!(s2.rx.try_recv(), Empty);
    }
}

#[cfg(test, windows)]
mod test_windows {
    use super::{User1, Listener};
    use result::{Ok, Err};

    #[test]
    fn test_io_signal_invalid_signum() {
        let mut s = Listener::new();
        match s.register(User1) {
            Ok(..) => {
                fail!("Unexpected successful registry of signum {:?}", User1);
            }
            Err(..) => {}
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Fix bug: panic when parsing invalid float literal.<commit_after><|endoftext|>


<commit_before><commit_msg>fix order in give command<commit_after><|endoftext|>


<commit_before><commit_msg>New separate variant types file<commit_after>use std::fmt;

#[deriving(Show)]
pub enum Type {
    Invalid = 0,
    Bool = 1,
    Int = 2,
    UInt = 3,
    LongLong = 4,
    ULongLong = 5,
    Double = 6,
    Char = 7,
    VariantMap = 8,
    VariantList = 9,
    String = 10,
    StringList = 11,
    ByteArray = 12,
    BitArray = 13,
    Date = 14,
    Time = 15,
    DateTime = 16,
    Url = 17,
    Locale = 18,
    Rect = 19,
    RectF = 20,
    Size = 21,
    SizeF = 22,
    Line = 23,
    LineF = 24,
    Point = 25,
    PointF = 26,
    RegExp = 27,
    VariantHash = 28,
    EasingCurve = 29,
    LastCoreType = 30,

    FirstGuiType = 63,
    Font = 64,
    Pixmap = 65,
    Brush = 66,
    Color = 67,
    Palette = 68,
    Icon = 69,
    Image = 70,
    Polygon = 71,
    Region = 72,
    Bitmap = 73,
    Cursor = 74,
    SizePolicy = 75,
    KeySequence = 76,
    Pen = 77,
    TextLength = 78,
    TextFormat = 79,
    Matrix = 80,
    Transform = 81,
    Matrix4x4 = 82,
    Vector2D = 83,
    Vector3D = 84,
    Vector4D = 85,
    Quaternion = 86,

    UserType = 127,
    UShort = 133,
    LastType = 0xffffffff
}
<|endoftext|>


<commit_before><commit_msg>use #[start]<commit_after><|endoftext|>


<commit_before><commit_msg>Add test for testing listing all entries with/out a certain tag<commit_after><|endoftext|>


<commit_before><commit_msg>Shutdown the websocket when the deploy is complete (#7)<commit_after><|endoftext|>


<commit_before><commit_msg>add missing `pub` annotations<commit_after><|endoftext|>


<commit_before><commit_msg>Implement logout.<commit_after><|endoftext|>


<commit_before><commit_msg>Skip serializing options.<commit_after><|endoftext|>


<commit_before><commit_msg>Print PANIC message on panic<commit_after><|endoftext|>


<commit_before><commit_msg>Auto merge of #268 - frewsxcv:path-segments, r=Ms2ger<commit_after><|endoftext|>


<commit_before><commit_msg>Invalid source code formating. Fixed.<commit_after><|endoftext|>


<commit_before><commit_msg>renamed console input cache<commit_after><|endoftext|>


<commit_before><commit_msg>Remove feature question mark<commit_after><|endoftext|>


<commit_before><commit_msg>Refactor fp flags<commit_after><|endoftext|>


<commit_before><commit_msg>Started work on a str module for str-based parsers. Implemented tag_str.<commit_after>use ::{
    Err,
    ErrorKind,
    IResult,
    Needed,

};

fn tag_str<'a, E>(input: &'a str, tag: &str) -> IResult<&'a str, &'a str, E> {
    if input.len() < tag.len() {
        IResult::Incomplete(Needed::Size(input.len()))
    } else if input.starts_with(tag) {
        IResult::Done(&input[tag.len()..], &input[0..tag.len()])
    } else {
        IResult::Error(Err::Position(ErrorKind::Tag, input))
    }
}
<|endoftext|>


<commit_before><commit_msg>Added "Access to wall post denied (210)" error<commit_after><|endoftext|>


<commit_before><commit_msg>Correct name mismatch<commit_after><|endoftext|>


<commit_before><commit_msg>Add test for using Morphism where Fn is expected<commit_after><|endoftext|>


<commit_before><commit_msg>Update to recent Rust.<commit_after><|endoftext|>


<commit_before><commit_msg>Simple Grid trait<commit_after>pub type Float = f32;
pub type Point = [Float; 3];

/// Generic grid type.
pub trait Grid {
    /// Cell coordinate on the grid.
    type Coordinate;
    /// Direciton on the grid.
    type Direction;
    /// Get the center point of a cell.
    fn get_cell_center(&self, Self::Coordinate) -> Point;
    /// Get the closest coordinate of a point.
    fn get_coordinate(&self, &Point) -> Self::Coordinate;
    /// Get the cell neighbor in a direction.
    fn get_neighbour(&self, Self::Coordinate, Self::Direction) -> Self::Coordinate;
    /// Fold over all neighbours.
    fn fold_neighbours<U, F: Fn(U, Self::Coordinate) -> U>(&self, Self::Coordinate, U) -> U;
    /// Fold over all cells in a radius.
    fn fold_in_radius<U, F: Fn(U, Self::Coordinate) -> U>(&self, Self::Coordinate, Float, U) -> U;
}

/// Position on the grid.
pub struct Position<G: Grid> {
    /// Coordinate.
    pub coord: G::Coordinate,
    /// Direction.
    pub dir: G::Direction,
}
<|endoftext|>


<commit_before><commit_msg>Update get_file_name to remove redundant code<commit_after><|endoftext|>


<commit_before><commit_msg>Implement `UnixDatagram::connect()`<commit_after><|endoftext|>


<commit_before><commit_msg>`quack::Me` got removed.<commit_after><|endoftext|>


<commit_before><commit_msg>Add code 125 to fix data connection on IIS Ftp server<commit_after><|endoftext|>


<commit_before><commit_msg>Add RETR command<commit_after><|endoftext|>


<commit_before><commit_msg>or_insert_default.<commit_after><|endoftext|>


<commit_before>#![feature(phase)]
#[phase(plugin)]
extern crate regex_macros;
extern crate regex;

use std::collections::HashMap;

mod lexer;
mod parser;

struct Liquid {
    text: String,
    content: HashMap<String, String>
}

impl Liquid {
    pub fn new(text: &str) -> Liquid {
        Liquid { text: text.to_string(), content: HashMap::new() }
    }
    pub fn parse (content: &HashMap<String, String>) -> String{
        "wtf".to_string()
    }
}

<commit_msg>Add &self to Liquid method<commit_after>#![feature(phase)]
#[phase(plugin)]
extern crate regex_macros;
extern crate regex;

use std::collections::HashMap;

mod lexer;
mod parser;

struct Liquid {
    text: String,
    content: HashMap<String, String>
}

impl Liquid {
    fn new(text: &str) -> Liquid {
        Liquid { text: text.to_string(), content: HashMap::new() }
    }
    fn parse (&self, content: &HashMap<String, String>) -> String{
        "wtf".to_string()
    }
}

<|endoftext|>


<commit_before><commit_msg>Rustup<commit_after><|endoftext|>


<commit_before><commit_msg>Adding 16-bit decoding<commit_after><|endoftext|>


<commit_before><commit_msg>Adding the ability to read 8-bit run-length encoded images.<commit_after><|endoftext|>


<commit_before><commit_msg>Fixed comment<commit_after><|endoftext|>


<commit_before><commit_msg>Improve docs and API.<commit_after><|endoftext|>