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

/*!

typeck.rs, an introduction

The type checker is responsible for:

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

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

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

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

3. Coherence checks for overlapping or orphaned impls

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

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

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

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

- coherence: enforces coherence rules, builds some tables

- variance: variance inference

- outlives: outlives inference

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

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

# Note

This API is completely unstable and subject to change.

*/

#![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/")]

#![allow(non_camel_case_types)]

#![feature(box_patterns)]
#![feature(box_syntax)]
#![feature(crate_visibility_modifier)]
#![feature(exhaustive_patterns)]
#![feature(iterator_find_map)]
#![feature(quote)]
#![feature(refcell_replace_swap)]
#![feature(rustc_diagnostic_macros)]
#![feature(slice_patterns)]
#![feature(slice_sort_by_cached_key)]
#![feature(never_type)]

#![recursion_limit="256"]

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

extern crate arena;
#[macro_use] extern crate rustc;
extern crate rustc_platform_intrinsics as intrinsics;
extern crate rustc_data_structures;
extern crate rustc_errors as errors;
extern crate rustc_target;

use rustc::hir;
use rustc::lint;
use rustc::middle;
use rustc::session;
use rustc::util;

use hir::map as hir_map;
use rustc::infer::InferOk;
use rustc::ty::subst::Substs;
use rustc::ty::{self, Ty, TyCtxt};
use rustc::ty::query::Providers;
use rustc::traits::{ObligationCause, ObligationCauseCode, TraitEngine, TraitEngineExt};
use rustc::util::profiling::ProfileCategory;
use session::{CompileIncomplete, config};
use util::common::time;

use syntax::ast;
use rustc_target::spec::abi::Abi;
use syntax_pos::Span;

use std::iter;

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

mod astconv;
mod check;
mod check_unused;
mod coherence;
mod collect;
mod constrained_type_params;
mod structured_errors;
mod impl_wf_check;
mod namespace;
mod outlives;
mod variance;

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

fn require_c_abi_if_variadic(tcx: TyCtxt,
                             decl: &hir::FnDecl,
                             abi: Abi,
                             span: Span) {
    if decl.variadic && !(abi == Abi::C || abi == Abi::Cdecl) {
        let mut err = struct_span_err!(tcx.sess, span, E0045,
                  "variadic function must have C or cdecl calling convention");
        err.span_label(span, "variadics require C or cdecl calling convention").emit();
    }
}

fn require_same_types<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                                cause: &ObligationCause<'tcx>,
                                expected: Ty<'tcx>,
                                actual: Ty<'tcx>)
                                -> bool {
    tcx.infer_ctxt().enter(|ref infcx| {
        let param_env = ty::ParamEnv::empty();
        let mut fulfill_cx = TraitEngine::new(infcx.tcx);
        match infcx.at(&cause, param_env).eq(expected, actual) {
            Ok(InferOk { obligations, .. }) => {
                fulfill_cx.register_predicate_obligations(infcx, obligations);
            }
            Err(err) => {
                infcx.report_mismatched_types(cause, expected, actual, err).emit();
                return false;
            }
        }

        match fulfill_cx.select_all_or_error(infcx) {
            Ok(()) => true,
            Err(errors) => {
                infcx.report_fulfillment_errors(&errors, None, false);
                false
            }
        }
    })
}

fn check_main_fn_ty<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                              main_id: ast::NodeId,
                              main_span: Span) {
    let main_def_id = tcx.hir.local_def_id(main_id);
    let main_t = tcx.type_of(main_def_id);
    match main_t.sty {
        ty::TyFnDef(..) => {
            match tcx.hir.find(main_id) {
                Some(hir_map::NodeItem(it)) => {
                    match it.node {
                        hir::ItemKind::Fn(.., ref generics, _) => {
                            let mut error = false;
                            if !generics.params.is_empty() {
                                let msg = "`main` function is not allowed to have generic \
                                           parameters".to_string();
                                let label = "`main` cannot have generic parameters".to_string();
                                struct_span_err!(tcx.sess, generics.span, E0131, "{}", msg)
                                    .span_label(generics.span, label)
                                    .emit();
                                error = true;
                            }
                            if let Some(sp) = generics.where_clause.span() {
                                struct_span_err!(tcx.sess, sp, E0646,
                                    "`main` function is not allowed to have a `where` clause")
                                    .span_label(sp, "`main` cannot have a `where` clause")
                                    .emit();
                                error = true;
                            }
                            if error {
                                return;
                            }
                        }
                        _ => ()
                    }
                }
                _ => ()
            }

            let actual = tcx.fn_sig(main_def_id);
            let expected_return_type = if tcx.lang_items().termination().is_some() {
                // we take the return type of the given main function, the real check is done
                // in `check_fn`
                actual.output().skip_binder()
            } else {
                // standard () main return type
                tcx.mk_nil()
            };

            let se_ty = tcx.mk_fn_ptr(ty::Binder::bind(
                tcx.mk_fn_sig(
                    iter::empty(),
                    expected_return_type,
                    false,
                    hir::Unsafety::Normal,
                    Abi::Rust
                )
            ));

            require_same_types(
                tcx,
                &ObligationCause::new(main_span, main_id, ObligationCauseCode::MainFunctionType),
                se_ty,
                tcx.mk_fn_ptr(actual));
        }
        _ => {
            span_bug!(main_span,
                      "main has a non-function type: found `{}`",
                      main_t);
        }
    }
}

fn check_start_fn_ty<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                               start_id: ast::NodeId,
                               start_span: Span) {
    let start_def_id = tcx.hir.local_def_id(start_id);
    let start_t = tcx.type_of(start_def_id);
    match start_t.sty {
        ty::TyFnDef(..) => {
            match tcx.hir.find(start_id) {
                Some(hir_map::NodeItem(it)) => {
                    match it.node {
                        hir::ItemKind::Fn(.., ref generics, _) => {
                            let mut error = false;
                            if !generics.params.is_empty() {
                                struct_span_err!(tcx.sess, generics.span, E0132,
                                    "start function is not allowed to have type parameters")
                                    .span_label(generics.span,
                                                "start function cannot have type parameters")
                                    .emit();
                                error = true;
                            }
                            if let Some(sp) = generics.where_clause.span() {
                                struct_span_err!(tcx.sess, sp, E0647,
                                    "start function is not allowed to have a `where` clause")
                                    .span_label(sp, "start function cannot have a `where` clause")
                                    .emit();
                                error = true;
                            }
                            if error {
                                return;
                            }
                        }
                        _ => ()
                    }
                }
                _ => ()
            }

            let se_ty = tcx.mk_fn_ptr(ty::Binder::bind(
                tcx.mk_fn_sig(
                    [
                        tcx.types.isize,
                        tcx.mk_imm_ptr(tcx.mk_imm_ptr(tcx.types.u8))
                    ].iter().cloned(),
                    tcx.types.isize,
                    false,
                    hir::Unsafety::Normal,
                    Abi::Rust
                )
            ));

            require_same_types(
                tcx,
                &ObligationCause::new(start_span, start_id, ObligationCauseCode::StartFunctionType),
                se_ty,
                tcx.mk_fn_ptr(tcx.fn_sig(start_def_id)));
        }
        _ => {
            span_bug!(start_span,
                      "start has a non-function type: found `{}`",
                      start_t);
        }
    }
}

fn check_for_entry_fn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
    if let Some((id, sp, entry_type)) = *tcx.sess.entry_fn.borrow() {
        match entry_type {
            config::EntryFnType::Main => check_main_fn_ty(tcx, id, sp),
            config::EntryFnType::Start => check_start_fn_ty(tcx, id, sp),
        }
    }
}

pub fn provide(providers: &mut Providers) {
    collect::provide(providers);
    coherence::provide(providers);
    check::provide(providers);
    variance::provide(providers);
    outlives::provide(providers);
}

pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>)
                             -> Result<(), CompileIncomplete>
{
    tcx.sess.profiler(|p| p.start_activity(ProfileCategory::TypeChecking));

    // this ensures that later parts of type checking can assume that items
    // have valid types and not error
    tcx.sess.track_errors(|| {
        time(tcx.sess, "type collecting", ||
             collect::collect_item_types(tcx));

    })?;

    tcx.sess.track_errors(|| {
        time(tcx.sess, "outlives testing", ||
            outlives::test::test_inferred_outlives(tcx));
    })?;

    tcx.sess.track_errors(|| {
        time(tcx.sess, "impl wf inference", ||
             impl_wf_check::impl_wf_check(tcx));
    })?;

    tcx.sess.track_errors(|| {
      time(tcx.sess, "coherence checking", ||
          coherence::check_coherence(tcx));
    })?;

    tcx.sess.track_errors(|| {
        time(tcx.sess, "variance testing", ||
             variance::test::test_variance(tcx));
    })?;

    time(tcx.sess, "wf checking", || check::check_wf_new(tcx))?;

    time(tcx.sess, "item-types checking", || check::check_item_types(tcx))?;

    time(tcx.sess, "item-bodies checking", || check::check_item_bodies(tcx))?;

    check_unused::check_crate(tcx);
    check_for_entry_fn(tcx);

    tcx.sess.profiler(|p| p.end_activity(ProfileCategory::TypeChecking));

    tcx.sess.compile_status()
}

/// A quasi-deprecated helper used in rustdoc and save-analysis to get
/// the type from a HIR node.
pub fn hir_ty_to_ty<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, hir_ty: &hir::Ty) -> Ty<'tcx> {
    // In case there are any projections etc, find the "environment"
    // def-id that will be used to determine the traits/predicates in
    // scope.  This is derived from the enclosing item-like thing.
    let env_node_id = tcx.hir.get_parent(hir_ty.id);
    let env_def_id = tcx.hir.local_def_id(env_node_id);
    let item_cx = self::collect::ItemCtxt::new(tcx, env_def_id);
    astconv::AstConv::ast_ty_to_ty(&item_cx, hir_ty)
}

pub fn hir_trait_to_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, hir_trait: &hir::TraitRef)
        -> (ty::PolyTraitRef<'tcx>, Vec<ty::PolyProjectionPredicate<'tcx>>) {
    // In case there are any projections etc, find the "environment"
    // def-id that will be used to determine the traits/predicates in
    // scope.  This is derived from the enclosing item-like thing.
    let env_node_id = tcx.hir.get_parent(hir_trait.ref_id);
    let env_def_id = tcx.hir.local_def_id(env_node_id);
    let item_cx = self::collect::ItemCtxt::new(tcx, env_def_id);
    let mut projections = Vec::new();
    let principal = astconv::AstConv::instantiate_poly_trait_ref_inner(
        &item_cx, hir_trait, tcx.types.err, &mut projections, true
    );
    (principal, projections)
}

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

/*!

typeck.rs, an introduction

The type checker is responsible for:

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

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

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

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

3. Coherence checks for overlapping or orphaned impls

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

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

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

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

- coherence: enforces coherence rules, builds some tables

- variance: variance inference

- outlives: outlives inference

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

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

# Note

This API is completely unstable and subject to change.

*/

#![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/")]

#![allow(non_camel_case_types)]

#![feature(box_patterns)]
#![feature(box_syntax)]
#![feature(crate_visibility_modifier)]
#![feature(exhaustive_patterns)]
#![feature(iterator_find_map)]
#![cfg_attr(not(stage0), feature(nll))]
#![feature(quote)]
#![feature(refcell_replace_swap)]
#![feature(rustc_diagnostic_macros)]
#![feature(slice_patterns)]
#![feature(slice_sort_by_cached_key)]
#![feature(never_type)]

#![recursion_limit="256"]

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

extern crate arena;
#[macro_use] extern crate rustc;
extern crate rustc_platform_intrinsics as intrinsics;
extern crate rustc_data_structures;
extern crate rustc_errors as errors;
extern crate rustc_target;

use rustc::hir;
use rustc::lint;
use rustc::middle;
use rustc::session;
use rustc::util;

use hir::map as hir_map;
use rustc::infer::InferOk;
use rustc::ty::subst::Substs;
use rustc::ty::{self, Ty, TyCtxt};
use rustc::ty::query::Providers;
use rustc::traits::{ObligationCause, ObligationCauseCode, TraitEngine, TraitEngineExt};
use rustc::util::profiling::ProfileCategory;
use session::{CompileIncomplete, config};
use util::common::time;

use syntax::ast;
use rustc_target::spec::abi::Abi;
use syntax_pos::Span;

use std::iter;

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

mod astconv;
mod check;
mod check_unused;
mod coherence;
mod collect;
mod constrained_type_params;
mod structured_errors;
mod impl_wf_check;
mod namespace;
mod outlives;
mod variance;

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

fn require_c_abi_if_variadic(tcx: TyCtxt,
                             decl: &hir::FnDecl,
                             abi: Abi,
                             span: Span) {
    if decl.variadic && !(abi == Abi::C || abi == Abi::Cdecl) {
        let mut err = struct_span_err!(tcx.sess, span, E0045,
                  "variadic function must have C or cdecl calling convention");
        err.span_label(span, "variadics require C or cdecl calling convention").emit();
    }
}

fn require_same_types<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                                cause: &ObligationCause<'tcx>,
                                expected: Ty<'tcx>,
                                actual: Ty<'tcx>)
                                -> bool {
    tcx.infer_ctxt().enter(|ref infcx| {
        let param_env = ty::ParamEnv::empty();
        let mut fulfill_cx = TraitEngine::new(infcx.tcx);
        match infcx.at(&cause, param_env).eq(expected, actual) {
            Ok(InferOk { obligations, .. }) => {
                fulfill_cx.register_predicate_obligations(infcx, obligations);
            }
            Err(err) => {
                infcx.report_mismatched_types(cause, expected, actual, err).emit();
                return false;
            }
        }

        match fulfill_cx.select_all_or_error(infcx) {
            Ok(()) => true,
            Err(errors) => {
                infcx.report_fulfillment_errors(&errors, None, false);
                false
            }
        }
    })
}

fn check_main_fn_ty<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                              main_id: ast::NodeId,
                              main_span: Span) {
    let main_def_id = tcx.hir.local_def_id(main_id);
    let main_t = tcx.type_of(main_def_id);
    match main_t.sty {
        ty::TyFnDef(..) => {
            match tcx.hir.find(main_id) {
                Some(hir_map::NodeItem(it)) => {
                    match it.node {
                        hir::ItemKind::Fn(.., ref generics, _) => {
                            let mut error = false;
                            if !generics.params.is_empty() {
                                let msg = "`main` function is not allowed to have generic \
                                           parameters".to_string();
                                let label = "`main` cannot have generic parameters".to_string();
                                struct_span_err!(tcx.sess, generics.span, E0131, "{}", msg)
                                    .span_label(generics.span, label)
                                    .emit();
                                error = true;
                            }
                            if let Some(sp) = generics.where_clause.span() {
                                struct_span_err!(tcx.sess, sp, E0646,
                                    "`main` function is not allowed to have a `where` clause")
                                    .span_label(sp, "`main` cannot have a `where` clause")
                                    .emit();
                                error = true;
                            }
                            if error {
                                return;
                            }
                        }
                        _ => ()
                    }
                }
                _ => ()
            }

            let actual = tcx.fn_sig(main_def_id);
            let expected_return_type = if tcx.lang_items().termination().is_some() {
                // we take the return type of the given main function, the real check is done
                // in `check_fn`
                actual.output().skip_binder()
            } else {
                // standard () main return type
                tcx.mk_nil()
            };

            let se_ty = tcx.mk_fn_ptr(ty::Binder::bind(
                tcx.mk_fn_sig(
                    iter::empty(),
                    expected_return_type,
                    false,
                    hir::Unsafety::Normal,
                    Abi::Rust
                )
            ));

            require_same_types(
                tcx,
                &ObligationCause::new(main_span, main_id, ObligationCauseCode::MainFunctionType),
                se_ty,
                tcx.mk_fn_ptr(actual));
        }
        _ => {
            span_bug!(main_span,
                      "main has a non-function type: found `{}`",
                      main_t);
        }
    }
}

fn check_start_fn_ty<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                               start_id: ast::NodeId,
                               start_span: Span) {
    let start_def_id = tcx.hir.local_def_id(start_id);
    let start_t = tcx.type_of(start_def_id);
    match start_t.sty {
        ty::TyFnDef(..) => {
            match tcx.hir.find(start_id) {
                Some(hir_map::NodeItem(it)) => {
                    match it.node {
                        hir::ItemKind::Fn(.., ref generics, _) => {
                            let mut error = false;
                            if !generics.params.is_empty() {
                                struct_span_err!(tcx.sess, generics.span, E0132,
                                    "start function is not allowed to have type parameters")
                                    .span_label(generics.span,
                                                "start function cannot have type parameters")
                                    .emit();
                                error = true;
                            }
                            if let Some(sp) = generics.where_clause.span() {
                                struct_span_err!(tcx.sess, sp, E0647,
                                    "start function is not allowed to have a `where` clause")
                                    .span_label(sp, "start function cannot have a `where` clause")
                                    .emit();
                                error = true;
                            }
                            if error {
                                return;
                            }
                        }
                        _ => ()
                    }
                }
                _ => ()
            }

            let se_ty = tcx.mk_fn_ptr(ty::Binder::bind(
                tcx.mk_fn_sig(
                    [
                        tcx.types.isize,
                        tcx.mk_imm_ptr(tcx.mk_imm_ptr(tcx.types.u8))
                    ].iter().cloned(),
                    tcx.types.isize,
                    false,
                    hir::Unsafety::Normal,
                    Abi::Rust
                )
            ));

            require_same_types(
                tcx,
                &ObligationCause::new(start_span, start_id, ObligationCauseCode::StartFunctionType),
                se_ty,
                tcx.mk_fn_ptr(tcx.fn_sig(start_def_id)));
        }
        _ => {
            span_bug!(start_span,
                      "start has a non-function type: found `{}`",
                      start_t);
        }
    }
}

fn check_for_entry_fn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
    if let Some((id, sp, entry_type)) = *tcx.sess.entry_fn.borrow() {
        match entry_type {
            config::EntryFnType::Main => check_main_fn_ty(tcx, id, sp),
            config::EntryFnType::Start => check_start_fn_ty(tcx, id, sp),
        }
    }
}

pub fn provide(providers: &mut Providers) {
    collect::provide(providers);
    coherence::provide(providers);
    check::provide(providers);
    variance::provide(providers);
    outlives::provide(providers);
}

pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>)
                             -> Result<(), CompileIncomplete>
{
    tcx.sess.profiler(|p| p.start_activity(ProfileCategory::TypeChecking));

    // this ensures that later parts of type checking can assume that items
    // have valid types and not error
    tcx.sess.track_errors(|| {
        time(tcx.sess, "type collecting", ||
             collect::collect_item_types(tcx));

    })?;

    tcx.sess.track_errors(|| {
        time(tcx.sess, "outlives testing", ||
            outlives::test::test_inferred_outlives(tcx));
    })?;

    tcx.sess.track_errors(|| {
        time(tcx.sess, "impl wf inference", ||
             impl_wf_check::impl_wf_check(tcx));
    })?;

    tcx.sess.track_errors(|| {
      time(tcx.sess, "coherence checking", ||
          coherence::check_coherence(tcx));
    })?;

    tcx.sess.track_errors(|| {
        time(tcx.sess, "variance testing", ||
             variance::test::test_variance(tcx));
    })?;

    time(tcx.sess, "wf checking", || check::check_wf_new(tcx))?;

    time(tcx.sess, "item-types checking", || check::check_item_types(tcx))?;

    time(tcx.sess, "item-bodies checking", || check::check_item_bodies(tcx))?;

    check_unused::check_crate(tcx);
    check_for_entry_fn(tcx);

    tcx.sess.profiler(|p| p.end_activity(ProfileCategory::TypeChecking));

    tcx.sess.compile_status()
}

/// A quasi-deprecated helper used in rustdoc and save-analysis to get
/// the type from a HIR node.
pub fn hir_ty_to_ty<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, hir_ty: &hir::Ty) -> Ty<'tcx> {
    // In case there are any projections etc, find the "environment"
    // def-id that will be used to determine the traits/predicates in
    // scope.  This is derived from the enclosing item-like thing.
    let env_node_id = tcx.hir.get_parent(hir_ty.id);
    let env_def_id = tcx.hir.local_def_id(env_node_id);
    let item_cx = self::collect::ItemCtxt::new(tcx, env_def_id);
    astconv::AstConv::ast_ty_to_ty(&item_cx, hir_ty)
}

pub fn hir_trait_to_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, hir_trait: &hir::TraitRef)
        -> (ty::PolyTraitRef<'tcx>, Vec<ty::PolyProjectionPredicate<'tcx>>) {
    // In case there are any projections etc, find the "environment"
    // def-id that will be used to determine the traits/predicates in
    // scope.  This is derived from the enclosing item-like thing.
    let env_node_id = tcx.hir.get_parent(hir_trait.ref_id);
    let env_def_id = tcx.hir.local_def_id(env_node_id);
    let item_cx = self::collect::ItemCtxt::new(tcx, env_def_id);
    let mut projections = Vec::new();
    let principal = astconv::AstConv::instantiate_poly_trait_ref_inner(
        &item_cx, hir_trait, tcx.types.err, &mut projections, true
    );
    (principal, projections)
}

__build_diagnostic_array! { librustc_typeck, DIAGNOSTICS }
<|endoftext|>


<commit_before><commit_msg>Add simple assembler parsing example<commit_after>extern crate r68k_tools;
extern crate pest;

use r68k_tools::assembler::parser::Rdp;
use std::io::{BufReader, BufRead};
use std::fs::File;
use pest::{Parser, StringInput};
use std::env;

fn main() {
    let file = if let Some(asmfile) = env::args().nth(1) {
        File::open(asmfile.as_str()).expect("could not open file")
    } else {
        panic!("Provide the path to an assembler file as first argument, to have it parsed");
    };
    let reader = BufReader::new(&file);
    let mut correct = 0;
    let mut fail = 0;
    let mut unended = 0;
    let mut lines = 0;
    for (num, line) in reader.lines().enumerate() {
        let input = match line {
            Ok(text) => text,
            Err(ex) => {
                println!("errd:{:04}: {}", num+1, ex);
                continue;
            }
        };
        let mut parser = Rdp::new(StringInput::new(&input));
        if parser.statement() {
            if parser.end() {
                correct += 1;
            } else {
                unended += 1;
                let qc = parser.queue_with_captures();
                println!("!end:{:04}: {:80} : {:?} (expected {:?})", num+1, input, qc, parser.expected());
            };
        } else {
            fail += 1;
            println!("fail:{:04}: {}", num+1, input);
        };
        lines = num;
    }
    println!("= END = total lines {:04}: correct {}, failed {}, incomplete {}", lines+1, correct, fail, unended);
}
<|endoftext|>


<commit_before><commit_msg>a simple example of getting module function exports with their names and types<commit_after>extern crate parity_wasm;

use std::env::args;

use parity_wasm::elements::{Internal, External, Type, FunctionType, Module};

fn type_by_index(module: &Module, index: usize) -> FunctionType {
    let function_section = module.function_section().expect("No function section found");
    let type_section = module.type_section().expect("No type section found");

    let import_section_len: usize = match module.import_section() {
            Some(import) =>
                import.entries().iter().filter(|entry| match entry.external() {
                    &External::Function(_) => true,
                    _ => false,
                    }).count(),
            None => 0,
        };
    let function_index_in_section = index - import_section_len;
    let func_type_ref: usize = function_section.entries()[function_index_in_section].type_ref() as usize;
    match type_section.types()[func_type_ref] {
        Type::Function(ref func_type) => func_type.clone(),
    }
}

fn main() {
    let args: Vec<_> = args().collect();
    if args.len() < 2 {
        println!("Prints export function names with and their types");
        println!("Usage: {} <wasm file>", args[0]);
        return;
    }
    let module = parity_wasm::deserialize_file(&args[1]).expect("File to be deserialized");
    let export_section = module.export_section().expect("No export section found");
    let exports: Vec<String> = export_section.entries().iter()
        .filter_map(|entry|
            match *entry.internal() {
                Internal::Function(index) => Some((entry.field(), index as usize)),
                _ => None
            })
        .map(|(field, index)| format!("{:}: {:?}", field, type_by_index(&module, index).params())).collect();
    for export in exports {
        println!("{:}", export);
    }
}
<|endoftext|>


<commit_before><commit_msg>Rollup merge of #81843 - bstrie:issue-29821, r=lcnr<commit_after>// build-pass

pub trait Foo {
    type FooAssoc;
}

pub struct Bar<F: Foo> {
    id: F::FooAssoc
}

pub struct Baz;

impl Foo for Baz {
    type FooAssoc = usize;
}

static mut MY_FOO: Bar<Baz> = Bar { id: 0 };

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Document push<commit_after><|endoftext|>


<commit_before><commit_msg>added fromlp0.rs to examples<commit_after>use std::fs::File;
use std::io;

use escposify::printer::Printer;

fn main() -> io::Result<()> {
    let device_file = File::options().append(true).open("/dev/usb/lp0").unwrap();

    let file = escposify::device::File::from(device_file);
    let mut printer = Printer::new(file, None, None);

    printer
        .chain_size(0,0)?
        .chain_text("The quick brown fox jumps over the lazy dog")?
        .chain_feed(1)?
        .chain_cut(false)?
        .flush()
}<|endoftext|>


<commit_before><commit_msg>Add reverse mappings example<commit_after>extern crate mime_guess;

fn main() {
    print_exts("video/*");
    print_exts("video/x-matroska");
}

fn print_exts(mime_type: &str) {
    println!("Exts for {:?}: {:?}", mime_type, mime_guess::get_mime_extensions_str(mime_type));
}
<|endoftext|>


<commit_before><commit_msg>prettier Float trait<commit_after><|endoftext|>


<commit_before><commit_msg>Commands can be expanded now Fixes issues like the following:     ~/.cargo/bin/ion -c echo test     let COM = echo; $COM test<commit_after><|endoftext|>


<commit_before><commit_msg>abort parser before shutting down layout in exit pipeline<commit_after><|endoftext|>


<commit_before><commit_msg>orthogonal_line_segment_intersection: sweep line implementation<commit_after>extern crate algs4;
extern crate rand;

use std::cmp::Ordering;
use rand::{Rng, Rand};
// use rand::thread_rng;

use algs4::quicksort::quick_sort;
use algs4::symbol_tables::ST;
use algs4::symbol_tables::binary_search_tree::BST;
use algs4::geometric_search::RangeSearch1D;

use self::Event::*;
use self::OrthogonalLine::*;

#[derive(Debug, PartialEq, Clone)]
pub enum OrthogonalLine {
    HLine { x0: i32, x1: i32, y: i32 },
    VLine { x: i32, y0: i32, y1: i32 }
}

impl OrthogonalLine {
    fn to_events(&self) -> Vec<Event> {
        match self {
            &HLine { x0, x1, y } => vec!
                [HLineStart { x: x0, y: y },
                 HLineEnd   { x: x1, y: y }],
            &VLine { x, y0, y1 } => vec![VLineMet { x: x, y0: y0, y1: y1 }]
        }
    }
}

impl Rand for OrthogonalLine {
    fn rand<R: Rng>(rng: &mut R) -> Self {
        if rng.gen_weighted_bool(3) {
            VLine { x:  rng.gen_range(0, 100),
                    y0: rng.gen_range(0, 100),
                    y1: rng.gen_range(0, 100),
            }
        } else {
            HLine { x0: rng.gen_range(0, 100),
                    x1: rng.gen_range(0, 100),
                    y:  rng.gen_range(0, 100),
            }
        }
    }
}

#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Event {
    HLineStart { x: i32, y: i32 },
    HLineEnd { x: i32, y: i32 },
    VLineMet { x: i32, y0: i32, y1: i32 }
}

fn first_x_coords_of(event: &Event) -> i32 {
    match event {
        &HLineStart { x, .. } => x,
        &HLineEnd { x, .. } => x,
        &VLineMet { x, .. } => x
    }
}
impl PartialOrd for Event {
    fn partial_cmp(&self, other: &Event) -> Option<Ordering> {
        first_x_coords_of(self).partial_cmp(&first_x_coords_of(other))
    }
}

fn lines_from_slide() -> Vec<OrthogonalLine> {
    vec![
        HLine { x0: 20, x1: 145, y: 110 },
        HLine { x0: 30, x1: 95, y: 80 },
        HLine { x0: 40, x1: 60, y: 65 },
        HLine { x0: 40, x1: 60, y: 65 },
        HLine { x0: 50, x1: 120, y: 30 },
        HLine { x0: 50, x1: 120, y: 30 },
        HLine { x0: 100, x1: 170, y: 60 },
        HLine { x0: 120, x1: 190, y: 75 },
        HLine { x0: 150, x1: 180, y: 90 },
        HLine { x0: 150, x1: 175, y: 30 },
        VLine { x: 80, y0: 50, y1: 90 },
        VLine { x: 140, y0: 105, y1: 120 },
        VLine { x: 155, y0: 10, y1: 60 },
        VLine { x: 200, y0: 20, y1: 120 },
        ]
}

fn main() {
    let mut bst = BST::<i32,()>::new();

    let lines = lines_from_slide();
    let mut events: Vec<Event> = lines.iter().flat_map(|l| l.to_events()).collect();
    quick_sort(&mut events);
    for e in events.iter() {
        match *e {
            HLineStart { y, .. } => {
                bst.insert(y, ());
            },
            HLineEnd { y, .. } => {
                bst.delete(&y);
            },
            VLineMet { x, y0, y1 } => {
                println!("vline => ({},{})---({},{})", x, y0, x, y1);
                match bst.search(&y0, &y1) {
                    None => println!("no intersection"),
                    Some(ys) => for y in ys {
                        println!("intersection: ({}, {})", x, *y);
                    }
                }
            }

        }
    }
}
<|endoftext|>


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

//! Check license of third-party deps by inspecting src/vendor

use std::fs::File;
use std::io::Read;
use std::path::Path;

static LICENSES: &'static [&'static str] = &[
    "MIT/Apache-2.0",
    "MIT / Apache-2.0",
    "Apache-2.0/MIT",
    "Apache-2.0 / MIT",
    "MIT OR Apache-2.0",
    "MIT",
    "Unlicense/MIT",
];

// These are exceptions to Rust's permissive licensing policy, and
// should be considered bugs. Exceptions are only allowed in Rust
// tooling. It is _crucial_ that no exception crates be dependencies
// of the Rust runtime (std / test).
static EXCEPTIONS: &'static [&'static str] = &[
    "mdbook", // MPL2, mdbook
    "openssl", // BSD+advertising clause, cargo, mdbook
    "pest", // MPL2, mdbook via handlebars
    "thread-id", // Apache-2.0, mdbook
    "cssparser", // MPL-2.0, rustdoc
    "smallvec", // MPL-2.0, rustdoc
    // FIXME: remove magenta references when "everything" has moved over to using the zircon name.
    "magenta-sys", // BSD-3-Clause, rustdoc
    "magenta", // BSD-3-Clause, rustdoc
    "zircon-sys", // BSD-3-Clause, rustdoc
    "zircon", // BSD-3-Clause, rustdoc
    "cssparser-macros", // MPL-2.0, rustdoc
    "selectors", // MPL-2.0, rustdoc
];

pub fn check(path: &Path, bad: &mut bool) {
    let path = path.join("vendor");
    assert!(path.exists(), "vendor directory missing");
    let mut saw_dir = false;
    'next_path: for dir in t!(path.read_dir()) {
        saw_dir = true;
        let dir = t!(dir);

        // skip our exceptions
        for exception in EXCEPTIONS {
            if dir.path()
                .to_str()
                .unwrap()
                .contains(&format!("src/vendor/{}", exception)) {
                continue 'next_path;
            }
        }

        let toml = dir.path().join("Cargo.toml");
        if !check_license(&toml) {
            *bad = true;
        }
    }
    assert!(saw_dir, "no vendored source");
}

fn check_license(path: &Path) -> bool {
    if !path.exists() {
        panic!("{} does not exist", path.display());
    }
    let mut contents = String::new();
    t!(t!(File::open(path)).read_to_string(&mut contents));

    let mut found_license = false;
    for line in contents.lines() {
        if !line.starts_with("license") {
            continue;
        }
        let license = extract_license(line);
        if !LICENSES.contains(&&*license) {
            println!("invalid license {} in {}", license, path.display());
            return false;
        }
        found_license = true;
        break;
    }
    if !found_license {
        println!("no license in {}", path.display());
        return false;
    }

    true
}

fn extract_license(line: &str) -> String {
    let first_quote = line.find('"');
    let last_quote = line.rfind('"');
    if let (Some(f), Some(l)) = (first_quote, last_quote) {
        let license = &line[f + 1 .. l];
        license.into()
    } else {
        "bad-license-parse".into()
    }
}
<commit_msg>Update license exceptions.<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.

//! Check license of third-party deps by inspecting src/vendor

use std::fs::File;
use std::io::Read;
use std::path::Path;

static LICENSES: &'static [&'static str] = &[
    "MIT/Apache-2.0",
    "MIT / Apache-2.0",
    "Apache-2.0/MIT",
    "Apache-2.0 / MIT",
    "MIT OR Apache-2.0",
    "MIT",
    "Unlicense/MIT",
];

// These are exceptions to Rust's permissive licensing policy, and
// should be considered bugs. Exceptions are only allowed in Rust
// tooling. It is _crucial_ that no exception crates be dependencies
// of the Rust runtime (std / test).
static EXCEPTIONS: &'static [&'static str] = &[
    "mdbook", // MPL2, mdbook
    "openssl", // BSD+advertising clause, cargo, mdbook
    "pest", // MPL2, mdbook via handlebars
    "thread-id", // Apache-2.0, mdbook
    "cssparser", // MPL-2.0, rustdoc
    "smallvec", // MPL-2.0, rustdoc
    "fuchsia-zircon-sys", // BSD-3-Clause, rustdoc, rustc, cargo
    "fuchsia-zircon", // BSD-3-Clause, rustdoc, rustc, cargo (jobserver & tempdir)
    "cssparser-macros", // MPL-2.0, rustdoc
    "selectors", // MPL-2.0, rustdoc
];

pub fn check(path: &Path, bad: &mut bool) {
    let path = path.join("vendor");
    assert!(path.exists(), "vendor directory missing");
    let mut saw_dir = false;
    'next_path: for dir in t!(path.read_dir()) {
        saw_dir = true;
        let dir = t!(dir);

        // skip our exceptions
        for exception in EXCEPTIONS {
            if dir.path()
                .to_str()
                .unwrap()
                .contains(&format!("src/vendor/{}", exception)) {
                continue 'next_path;
            }
        }

        let toml = dir.path().join("Cargo.toml");
        if !check_license(&toml) {
            *bad = true;
        }
    }
    assert!(saw_dir, "no vendored source");
}

fn check_license(path: &Path) -> bool {
    if !path.exists() {
        panic!("{} does not exist", path.display());
    }
    let mut contents = String::new();
    t!(t!(File::open(path)).read_to_string(&mut contents));

    let mut found_license = false;
    for line in contents.lines() {
        if !line.starts_with("license") {
            continue;
        }
        let license = extract_license(line);
        if !LICENSES.contains(&&*license) {
            println!("invalid license {} in {}", license, path.display());
            return false;
        }
        found_license = true;
        break;
    }
    if !found_license {
        println!("no license in {}", path.display());
        return false;
    }

    true
}

fn extract_license(line: &str) -> String {
    let first_quote = line.find('"');
    let last_quote = line.rfind('"');
    if let (Some(f), Some(l)) = (first_quote, last_quote) {
        let license = &line[f + 1 .. l];
        license.into()
    } else {
        "bad-license-parse".into()
    }
}
<|endoftext|>


<commit_before><commit_msg>rust anagram<commit_after>fn is_anagram(a: &str ,b : &str) ->  bool {
    if a.len() != b.len() { // initial check
        return false;
    }
    let mut a:Vec<char> = a.chars().collect();
    a.sort();
    let mut b:Vec<char> = b.chars().collect();
    b.sort();
    if a == b {
        return true
    }
    false
}
<|endoftext|>


<commit_before><commit_msg>Commented out the interactive tests<commit_after><|endoftext|>


<commit_before><commit_msg>hashjoin example<commit_after>extern crate rand;
extern crate timely;

use std::collections::HashMap;

use rand::{Rng, SeedableRng, StdRng};

use timely::dataflow::*;
use timely::dataflow::operators::{Input, Probe};
use timely::dataflow::operators::generic::Operator;
use timely::dataflow::channels::pact::Exchange;

fn main() {

    // command-line args: numbers of nodes and edges in the random graph.
    let keys: u64 = std::env::args().nth(1).unwrap().parse().unwrap();
    let vals: usize = std::env::args().nth(2).unwrap().parse().unwrap();
    let batch: usize = std::env::args().nth(3).unwrap().parse().unwrap();

    timely::execute_from_args(std::env::args().skip(4), move |worker| {

        let index = worker.index();
        let peers = worker.peers();

        let mut input1 = InputHandle::new();
        let mut input2 = InputHandle::new();
        let mut probe = ProbeHandle::new();

        worker.dataflow(|scope| {

            let stream1 = scope.input_from(&mut input1);
            let stream2 = scope.input_from(&mut input2);

            let exchange1 = Exchange::new(|x: &(u64, u64)| x.0);
            let exchange2 = Exchange::new(|x: &(u64, u64)| x.0);

            stream1
                .binary(&stream2, exchange1, exchange2, "HashJoin", |_capability| {

                    let mut map1 = HashMap::<u64, Vec<u64>>::new();
                    let mut map2 = HashMap::<u64, Vec<u64>>::new();

                    move |input1, input2, output| {

                        // Drain first input, check second map, update first map.
                        input1.for_each(|time, data| {
                            let mut session = output.session(&time);
                            for (key, val1) in data.drain(..) {
                                if let Some(values) = map2.get(&key) {
                                    for val2 in values.iter() {
                                        session.give((val1.clone(), val2.clone()));
                                    }
                                }

                                map1.entry(key).or_insert(Vec::new()).push(val1);
                            }
                        });

                        // Drain second input, check first map, update second map.
                        input2.for_each(|time, data| {
                            let mut session = output.session(&time);
                            for (key, val2) in data.drain(..) {
                                if let Some(values) = map1.get(&key) {
                                    for val1 in values.iter() {
                                        session.give((val1.clone(), val2.clone()));
                                    }
                                }

                                map2.entry(key).or_insert(Vec::new()).push(val2);
                            }
                        });
                    }
                })
                .probe_with(&mut probe);
        });

        let seed: &[_] = &[1, 2, 3, index];
        let mut rng: StdRng = SeedableRng::from_seed(seed);

        let timer = std::time::Instant::now();

        let mut sent = 0;
        while sent < (vals / peers) {

            // Send some amount of data, no more than `batch`.
            let to_send = std::cmp::min(batch, (vals/peers - sent));
            for _ in 0 .. to_send {
                input1.send((rng.gen_range(0, keys), rng.gen_range(0, keys)));
                input2.send((rng.gen_range(0, keys), rng.gen_range(0, keys)));
            }
            sent += to_send;

            // Advance input, iterate until data cleared.
            let next = input1.epoch() + 1;
            input1.advance_to(next);
            input2.advance_to(next);
            while probe.less_than(input1.time()) {
                worker.step();
            }

            println!("{:?}\tworker {} batch complete", timer.elapsed(), index)
        }

    }).unwrap(); // asserts error-free execution;
}<|endoftext|>


<commit_before><commit_msg>Add triangle demo [WIP]<commit_after>extern crate erya;
#[macro_use]
extern crate glium;

use std::path::PathBuf;
use std::default::Default;
use glium::glutin::Event;
use glium::Surface;
use glium::index::PrimitiveType::TrianglesList;
use erya::renderer::Renderer;
use erya::loader::Queue;
use erya::texture::Texture;
use erya::camera::{Camera3D, Camera};
use erya::sprite::Sprite;
use erya::mesh::{IndexBuffer, VertexBuffer, Mesh};

#[derive(Copy, Clone)]
struct Vertex {
    position: [f32; 2],
    color: [f32; 3],
}

implement_vertex!(Vertex, position, color);

fn main() {
    let display = erya::build_display("triangle", (800, 600));
    let renderer = Renderer::<erya::shader::Default>::new(&display);
    let camera = Camera3D::new(&display);
    let mesh = {
        let vb = VertexBuffer::new(&display, &[
            Vertex { position: [-0.5, -0.5], color: [0.0, 1.0, 0.0] },
            Vertex { position: [ 0.0,  0.5], color: [0.0, 0.0, 1.0] },
            Vertex { position: [ 0.5, -0.5], color: [1.0, 0.0, 0.0] },
        ]).unwrap();
        let ib = IndexBuffer::new(&display, TrianglesList, &[0, 1, 2]).unwrap();
        Mesh(vb, ib)
    };
    let program = program!(&display,
        140 => {
            vertex: "
                #version 140
                uniform mat4 matrix;
                in vec2 position;
                in vec3 color;
                out vec3 vColor;
                void main() {
                    gl_Position = vec4(position, 0.0, 1.0) * matrix;
                    vColor = color;
                }
            ",

            fragment: "
                #version 140
                in vec3 vColor;
                out vec4 f_color;
                void main() {
                    f_color = vec4(vColor, 1.0);
                }
            "
        }
    ).unwrap();

    let uniforms = uniform! {
        matrix: [
            [1.0, 0.0, 0.0, 0.0],
            [0.0, 1.0, 0.0, 0.0],
            [0.0, 0.0, 1.0, 0.0],
            [0.0, 0.0, 0.0, 1.0f32]
        ]
    };

    'main: loop {
        // let camera = camera.matrix();
        let mut target = display.draw();
        target.clear_color(0.25, 0.25, 0.25, 0.0);
        target.draw(&mesh.0, &mesh.1, &program, &uniforms, &Default::default()).unwrap();
        target.finish().unwrap();
        for event in display.poll_events() {
            match event {
                Event::Closed => break 'main,
                _ => (),
            }
        }
        erya::timer::sleep_ms(1);
    }
}
<|endoftext|>


<commit_before>use core_collections::borrow::ToOwned;
use io::{self, BufRead, BufReader, Read, Error, Result, Write, Seek, SeekFrom};
use os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
use mem;
use path::{PathBuf, Path};
use string::String;
use sys_common::AsInner;
use vec::Vec;

use system::syscall::{sys_open, sys_dup, sys_close, sys_fpath, sys_ftruncate, sys_read,
              sys_write, sys_lseek, sys_fsync, sys_mkdir, sys_rmdir, sys_stat, sys_unlink};
use system::syscall::{O_RDWR, O_RDONLY, O_WRONLY, O_APPEND, O_CREAT, O_TRUNC, MODE_DIR, MODE_FILE, SEEK_SET, SEEK_CUR, SEEK_END, Stat};

/// A Unix-style file
#[derive(Debug)]
pub struct File {
    /// The id for the file
    fd: usize,
}

impl File {
    /// Open a new file using a path
    pub fn open<P: AsRef<Path>>(path: P) -> Result<File> {
        let path_str = path.as_ref().as_os_str().as_inner();
        let mut path_c = path_str.to_owned();
        path_c.push_str("\0");
        unsafe {
            sys_open(path_c.as_ptr(), O_RDONLY, 0).map(|fd| File::from_raw_fd(fd) )
        }.map_err(|x| Error::from_sys(x))
    }

    /// Create a new file using a path
    pub fn create<P: AsRef<Path>>(path: P) -> Result<File> {
        let path_str = path.as_ref().as_os_str().as_inner();
        let mut path_c = path_str.to_owned();
        path_c.push_str("\0");
        unsafe {
            sys_open(path_c.as_ptr(), O_CREAT | O_RDWR | O_TRUNC, 0).map(|fd| File::from_raw_fd(fd) )
        }.map_err(|x| Error::from_sys(x))
    }

    /// Duplicate the file
    pub fn dup(&self) -> Result<File> {
        sys_dup(self.fd).map(|fd| unsafe { File::from_raw_fd(fd) }).map_err(|x| Error::from_sys(x))
    }

    /// Get the canonical path of the file
    pub fn path(&self) -> Result<PathBuf> {
        let mut buf: [u8; 4096] = [0; 4096];
        match sys_fpath(self.fd, &mut buf) {
            Ok(count) => Ok(PathBuf::from(unsafe { String::from_utf8_unchecked(Vec::from(&buf[0..count])) })),
            Err(err) => Err(Error::from_sys(err)),
        }
    }

    /// Flush the file data and metadata
    pub fn sync_all(&mut self) -> Result<()> {
        sys_fsync(self.fd).and(Ok(())).map_err(|x| Error::from_sys(x))
    }

    /// Flush the file data
    pub fn sync_data(&mut self) -> Result<()> {
        sys_fsync(self.fd).and(Ok(())).map_err(|x| Error::from_sys(x))
    }

    /// Truncates the file
    pub fn set_len(&mut self, size: u64) -> Result<()> {
        sys_ftruncate(self.fd, size as usize).and(Ok(())).map_err(|x| Error::from_sys(x))
    }
}

impl AsRawFd for File {
    fn as_raw_fd(&self) -> RawFd {
        self.fd
    }
}

impl FromRawFd for File {
    unsafe fn from_raw_fd(fd: RawFd) -> Self {
        File {
            fd: fd
        }
    }
}

impl IntoRawFd for File {
    fn into_raw_fd(self) -> RawFd {
        let fd = self.fd;
        mem::forget(self);
        fd
    }
}

impl Read for File {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
        sys_read(self.fd, buf).map_err(|x| Error::from_sys(x))
    }
}

impl Write for File {
    fn write(&mut self, buf: &[u8]) -> Result<usize> {
        sys_write(self.fd, buf).map_err(|x| Error::from_sys(x))
    }

    fn flush(&mut self) -> Result<()> {
        sys_fsync(self.fd).and(Ok(())).map_err(|x| Error::from_sys(x))
    }
}

impl Seek for File {
    /// Seek a given position
    fn seek(&mut self, pos: SeekFrom) -> Result<u64> {
        let (whence, offset) = match pos {
            SeekFrom::Start(offset) => (SEEK_SET, offset as isize),
            SeekFrom::Current(offset) => (SEEK_CUR, offset as isize),
            SeekFrom::End(offset) => (SEEK_END, offset as isize),
        };

        sys_lseek(self.fd, offset, whence).map(|position| position as u64).map_err(|x| Error::from_sys(x))
    }
}

impl Drop for File {
    fn drop(&mut self) {
        let _ = sys_close(self.fd);
    }
}

#[derive(Copy, Clone, Eq, PartialEq)]
pub struct FileType {
    dir: bool,
    file: bool,
}

impl FileType {
    pub fn is_dir(&self) -> bool {
        self.dir
    }

    pub fn is_file(&self) -> bool {
        self.file
    }

    pub fn is_symlink(&self) -> bool {
        false
    }
}

pub struct OpenOptions {
    read: bool,
    write: bool,
    append: bool,
    create: bool,
    truncate: bool,
}

impl OpenOptions {
    pub fn new() -> OpenOptions {
        OpenOptions {
            read: false,
            write: false,
            append: false,
            create: false,
            truncate: false,
        }
    }

    pub fn read(&mut self, read: bool) -> &mut OpenOptions {
        self.read = read;
        self
    }

    pub fn write(&mut self, write: bool) -> &mut OpenOptions {
        self.write = write;
        self
    }

    pub fn append(&mut self, append: bool) -> &mut OpenOptions {
        self.append = append;
        self
    }

    pub fn create(&mut self, create: bool) -> &mut OpenOptions {
        self.create = create;
        self
    }

    pub fn truncate(&mut self, truncate: bool) -> &mut OpenOptions {
        self.truncate = truncate;
        self
    }

    pub fn open<P: AsRef<Path>>(&self, path: P) -> Result<File> {
        let mut flags = 0;

        if self.read && self.write {
            flags |= O_RDWR;
        } else if self.read {
            flags |= O_RDONLY;
        } else if self.write {
            flags |= O_WRONLY;
        }

        if self.append {
            flags |= O_APPEND;
        }

        if self.create {
            flags |= O_CREAT;
        }

        if self.truncate {
            flags |= O_TRUNC;
        }

        let path_str = path.as_ref().as_os_str().as_inner();
        let mut path_c = path_str.to_owned();
        path_c.push_str("\0");
        unsafe {
            sys_open(path_c.as_ptr(), flags, 0).map(|fd| File::from_raw_fd(fd))
        }.map_err(|x| Error::from_sys(x))
    }
}

pub struct Metadata {
    stat: Stat
}

impl Metadata {
    pub fn file_type(&self) -> FileType {
        FileType {
            dir: self.stat.st_mode & MODE_DIR == MODE_DIR,
            file: self.stat.st_mode & MODE_FILE == MODE_FILE
        }
    }

    pub fn is_dir(&self) -> bool {
        self.stat.st_mode & MODE_DIR == MODE_DIR
    }

    pub fn is_file(&self) -> bool {
        self.stat.st_mode & MODE_FILE == MODE_FILE
    }

    pub fn len(&self) -> u64 {
        self.stat.st_size as u64
    }
}

pub struct DirEntry {
    path: PathBuf,
    dir: bool,
    file: bool,
}

impl DirEntry {
    pub fn file_name(&self) -> &Path {
        unsafe { mem::transmute(self.path.file_name().unwrap().to_str().unwrap()) }
    }

    pub fn file_type(&self) -> Result<FileType> {
        Ok(FileType {
            dir: self.dir,
            file: self.file,
        })
    }

    pub fn metadata(&self) -> Result<Metadata> {
        metadata(&self.path)
    }

    pub fn path(&self) -> PathBuf {
        self.path.clone()
    }
}

pub struct ReadDir {
    path: PathBuf,
    file: BufReader<File>,
}

impl Iterator for ReadDir {
    type Item = Result<DirEntry>;
    fn next(&mut self) -> Option<Result<DirEntry>> {
        let mut name = String::new();
        match self.file.read_line(&mut name) {
            Ok(0) => None,
            Ok(_) => {
                if name.ends_with('\n') {
                    name.pop();
                }
                let dir = name.ends_with('/');
                if dir {
                    name.pop();
                }

                let mut path = self.path.clone();
                path.push(name);
                Some(Ok(DirEntry {
                    path: path,
                    dir: dir,
                    file: !dir,
                }))
            },
            Err(err) => Some(Err(err))
        }
    }
}

/// Find the canonical path of a file
pub fn canonicalize<P: AsRef<Path>>(path: P) -> Result<PathBuf> {
    match File::open(path) {
        Ok(file) => {
            match file.path() {
                Ok(realpath) => Ok(realpath),
                Err(err) => Err(err)
            }
        },
        Err(err) => Err(err)
    }
}

/// Get information about a file
pub fn metadata<P: AsRef<Path>>(path: P) -> Result<Metadata> {
    let mut stat = Stat::default();
    let path_str = path.as_ref().as_os_str().as_inner();
    let mut path_c = path_str.to_owned();
    path_c.push_str("\0");
    unsafe {
        try!(sys_stat(path_c.as_ptr(), &mut stat).map_err(|x| Error::from_sys(x)));
    }
    Ok(Metadata {
        stat: stat
    })
}

/// Get information about a file without following symlinks
/// Warning: Redox does not currently support symlinks
pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> Result<Metadata> {
    metadata(path)
}

/// Create a new directory, using a path
/// The default mode of the directory is 744
pub fn create_dir<P: AsRef<Path>>(path: P) -> Result<()> {
    let path_str = path.as_ref().as_os_str().as_inner();
    let mut path_c = path_str.to_owned();
    path_c.push_str("\0");
    unsafe {
        sys_mkdir(path_c.as_ptr(), 755).and(Ok(())).map_err(|x| Error::from_sys(x))
    }
}

/// Copy the contents of one file to another
pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> Result<u64> {
    let mut infile = try!(File::open(from));
    let mut outfile = try!(File::create(to));
    io::copy(&mut infile, &mut outfile)
}

/// Rename a file or directory to a new name
pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> Result<()> {
    try!(copy(Path::new(from.as_ref()), to));
    remove_file(from)
}

/// Return an iterator over the entries within a directory
pub fn read_dir<P: AsRef<Path>>(path: P) -> Result<ReadDir> {
    let path_buf = path.as_ref().to_owned();
    File::open(&path_buf).map(|file| ReadDir { path: path_buf, file: BufReader::new(file) })
}

/// Removes an existing, empty directory
pub fn remove_dir<P: AsRef<Path>>(path: P) -> Result<()> {
    let path_str = path.as_ref().as_os_str().as_inner();
    let mut path_c = path_str.to_owned();
    path_c.push_str("\0");
    unsafe {
        sys_rmdir(path_c.as_ptr()).and(Ok(()))
    }.map_err(|x| Error::from_sys(x))
}

/// Removes a file from the filesystem
pub fn remove_file<P: AsRef<Path>>(path: P) -> Result<()> {
    let path_str = path.as_ref().as_os_str().as_inner();
    let mut path_c = path_str.to_owned();
    path_c.push_str("\0");
    unsafe {
        sys_unlink(path_c.as_ptr()).and(Ok(()))
    }.map_err(|x| Error::from_sys(x))
}
<commit_msg>remove_dir_all<commit_after>use core_collections::borrow::ToOwned;
use io::{self, BufRead, BufReader, Read, Error, Result, Write, Seek, SeekFrom};
use os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
use mem;
use path::{PathBuf, Path};
use string::String;
use sys_common::AsInner;
use vec::Vec;

use system::syscall::{sys_open, sys_dup, sys_close, sys_fpath, sys_ftruncate, sys_read,
              sys_write, sys_lseek, sys_fsync, sys_mkdir, sys_rmdir, sys_stat, sys_unlink};
use system::syscall::{O_RDWR, O_RDONLY, O_WRONLY, O_APPEND, O_CREAT, O_TRUNC, MODE_DIR, MODE_FILE, SEEK_SET, SEEK_CUR, SEEK_END, Stat};

/// A Unix-style file
#[derive(Debug)]
pub struct File {
    /// The id for the file
    fd: usize,
}

impl File {
    /// Open a new file using a path
    pub fn open<P: AsRef<Path>>(path: P) -> Result<File> {
        let path_str = path.as_ref().as_os_str().as_inner();
        let mut path_c = path_str.to_owned();
        path_c.push_str("\0");
        unsafe {
            sys_open(path_c.as_ptr(), O_RDONLY, 0).map(|fd| File::from_raw_fd(fd) )
        }.map_err(|x| Error::from_sys(x))
    }

    /// Create a new file using a path
    pub fn create<P: AsRef<Path>>(path: P) -> Result<File> {
        let path_str = path.as_ref().as_os_str().as_inner();
        let mut path_c = path_str.to_owned();
        path_c.push_str("\0");
        unsafe {
            sys_open(path_c.as_ptr(), O_CREAT | O_RDWR | O_TRUNC, 0).map(|fd| File::from_raw_fd(fd) )
        }.map_err(|x| Error::from_sys(x))
    }

    /// Duplicate the file
    pub fn dup(&self) -> Result<File> {
        sys_dup(self.fd).map(|fd| unsafe { File::from_raw_fd(fd) }).map_err(|x| Error::from_sys(x))
    }

    /// Get the canonical path of the file
    pub fn path(&self) -> Result<PathBuf> {
        let mut buf: [u8; 4096] = [0; 4096];
        match sys_fpath(self.fd, &mut buf) {
            Ok(count) => Ok(PathBuf::from(unsafe { String::from_utf8_unchecked(Vec::from(&buf[0..count])) })),
            Err(err) => Err(Error::from_sys(err)),
        }
    }

    /// Flush the file data and metadata
    pub fn sync_all(&mut self) -> Result<()> {
        sys_fsync(self.fd).and(Ok(())).map_err(|x| Error::from_sys(x))
    }

    /// Flush the file data
    pub fn sync_data(&mut self) -> Result<()> {
        sys_fsync(self.fd).and(Ok(())).map_err(|x| Error::from_sys(x))
    }

    /// Truncates the file
    pub fn set_len(&mut self, size: u64) -> Result<()> {
        sys_ftruncate(self.fd, size as usize).and(Ok(())).map_err(|x| Error::from_sys(x))
    }
}

impl AsRawFd for File {
    fn as_raw_fd(&self) -> RawFd {
        self.fd
    }
}

impl FromRawFd for File {
    unsafe fn from_raw_fd(fd: RawFd) -> Self {
        File {
            fd: fd
        }
    }
}

impl IntoRawFd for File {
    fn into_raw_fd(self) -> RawFd {
        let fd = self.fd;
        mem::forget(self);
        fd
    }
}

impl Read for File {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
        sys_read(self.fd, buf).map_err(|x| Error::from_sys(x))
    }
}

impl Write for File {
    fn write(&mut self, buf: &[u8]) -> Result<usize> {
        sys_write(self.fd, buf).map_err(|x| Error::from_sys(x))
    }

    fn flush(&mut self) -> Result<()> {
        sys_fsync(self.fd).and(Ok(())).map_err(|x| Error::from_sys(x))
    }
}

impl Seek for File {
    /// Seek a given position
    fn seek(&mut self, pos: SeekFrom) -> Result<u64> {
        let (whence, offset) = match pos {
            SeekFrom::Start(offset) => (SEEK_SET, offset as isize),
            SeekFrom::Current(offset) => (SEEK_CUR, offset as isize),
            SeekFrom::End(offset) => (SEEK_END, offset as isize),
        };

        sys_lseek(self.fd, offset, whence).map(|position| position as u64).map_err(|x| Error::from_sys(x))
    }
}

impl Drop for File {
    fn drop(&mut self) {
        let _ = sys_close(self.fd);
    }
}

#[derive(Copy, Clone, Eq, PartialEq)]
pub struct FileType {
    dir: bool,
    file: bool,
}

impl FileType {
    pub fn is_dir(&self) -> bool {
        self.dir
    }

    pub fn is_file(&self) -> bool {
        self.file
    }

    pub fn is_symlink(&self) -> bool {
        false
    }
}

pub struct OpenOptions {
    read: bool,
    write: bool,
    append: bool,
    create: bool,
    truncate: bool,
}

impl OpenOptions {
    pub fn new() -> OpenOptions {
        OpenOptions {
            read: false,
            write: false,
            append: false,
            create: false,
            truncate: false,
        }
    }

    pub fn read(&mut self, read: bool) -> &mut OpenOptions {
        self.read = read;
        self
    }

    pub fn write(&mut self, write: bool) -> &mut OpenOptions {
        self.write = write;
        self
    }

    pub fn append(&mut self, append: bool) -> &mut OpenOptions {
        self.append = append;
        self
    }

    pub fn create(&mut self, create: bool) -> &mut OpenOptions {
        self.create = create;
        self
    }

    pub fn truncate(&mut self, truncate: bool) -> &mut OpenOptions {
        self.truncate = truncate;
        self
    }

    pub fn open<P: AsRef<Path>>(&self, path: P) -> Result<File> {
        let mut flags = 0;

        if self.read && self.write {
            flags |= O_RDWR;
        } else if self.read {
            flags |= O_RDONLY;
        } else if self.write {
            flags |= O_WRONLY;
        }

        if self.append {
            flags |= O_APPEND;
        }

        if self.create {
            flags |= O_CREAT;
        }

        if self.truncate {
            flags |= O_TRUNC;
        }

        let path_str = path.as_ref().as_os_str().as_inner();
        let mut path_c = path_str.to_owned();
        path_c.push_str("\0");
        unsafe {
            sys_open(path_c.as_ptr(), flags, 0).map(|fd| File::from_raw_fd(fd))
        }.map_err(|x| Error::from_sys(x))
    }
}

pub struct Metadata {
    stat: Stat
}

impl Metadata {
    pub fn file_type(&self) -> FileType {
        FileType {
            dir: self.stat.st_mode & MODE_DIR == MODE_DIR,
            file: self.stat.st_mode & MODE_FILE == MODE_FILE
        }
    }

    pub fn is_dir(&self) -> bool {
        self.stat.st_mode & MODE_DIR == MODE_DIR
    }

    pub fn is_file(&self) -> bool {
        self.stat.st_mode & MODE_FILE == MODE_FILE
    }

    pub fn len(&self) -> u64 {
        self.stat.st_size as u64
    }
}

pub struct DirEntry {
    path: PathBuf,
    dir: bool,
    file: bool,
}

impl DirEntry {
    pub fn file_name(&self) -> &Path {
        unsafe { mem::transmute(self.path.file_name().unwrap().to_str().unwrap()) }
    }

    pub fn file_type(&self) -> Result<FileType> {
        Ok(FileType {
            dir: self.dir,
            file: self.file,
        })
    }

    pub fn metadata(&self) -> Result<Metadata> {
        metadata(&self.path)
    }

    pub fn path(&self) -> PathBuf {
        self.path.clone()
    }
}

pub struct ReadDir {
    path: PathBuf,
    file: BufReader<File>,
}

impl Iterator for ReadDir {
    type Item = Result<DirEntry>;
    fn next(&mut self) -> Option<Result<DirEntry>> {
        let mut name = String::new();
        match self.file.read_line(&mut name) {
            Ok(0) => None,
            Ok(_) => {
                if name.ends_with('\n') {
                    name.pop();
                }
                let dir = name.ends_with('/');
                if dir {
                    name.pop();
                }

                let mut path = self.path.clone();
                path.push(name);
                Some(Ok(DirEntry {
                    path: path,
                    dir: dir,
                    file: !dir,
                }))
            },
            Err(err) => Some(Err(err))
        }
    }
}

/// Find the canonical path of a file
pub fn canonicalize<P: AsRef<Path>>(path: P) -> Result<PathBuf> {
    match File::open(path) {
        Ok(file) => {
            match file.path() {
                Ok(realpath) => Ok(realpath),
                Err(err) => Err(err)
            }
        },
        Err(err) => Err(err)
    }
}

/// Get information about a file
pub fn metadata<P: AsRef<Path>>(path: P) -> Result<Metadata> {
    let mut stat = Stat::default();
    let path_str = path.as_ref().as_os_str().as_inner();
    let mut path_c = path_str.to_owned();
    path_c.push_str("\0");
    unsafe {
        try!(sys_stat(path_c.as_ptr(), &mut stat).map_err(|x| Error::from_sys(x)));
    }
    Ok(Metadata {
        stat: stat
    })
}

/// Get information about a file without following symlinks
/// Warning: Redox does not currently support symlinks
pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> Result<Metadata> {
    metadata(path)
}

/// Create a new directory, using a path
/// The default mode of the directory is 744
pub fn create_dir<P: AsRef<Path>>(path: P) -> Result<()> {
    let path_str = path.as_ref().as_os_str().as_inner();
    let mut path_c = path_str.to_owned();
    path_c.push_str("\0");
    unsafe {
        sys_mkdir(path_c.as_ptr(), 755).and(Ok(())).map_err(|x| Error::from_sys(x))
    }
}

/// Copy the contents of one file to another
pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> Result<u64> {
    let mut infile = try!(File::open(from));
    let mut outfile = try!(File::create(to));
    io::copy(&mut infile, &mut outfile)
}

/// Rename a file or directory to a new name
pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> Result<()> {
    try!(copy(Path::new(from.as_ref()), to));
    remove_file(from)
}

/// Return an iterator over the entries within a directory
pub fn read_dir<P: AsRef<Path>>(path: P) -> Result<ReadDir> {
    let path_buf = path.as_ref().to_owned();
    File::open(&path_buf).map(|file| ReadDir { path: path_buf, file: BufReader::new(file) })
}

/// Removes an existing, empty directory
pub fn remove_dir<P: AsRef<Path>>(path: P) -> Result<()> {
    let path_str = path.as_ref().as_os_str().as_inner();
    let mut path_c = path_str.to_owned();
    path_c.push_str("\0");
    unsafe {
        sys_rmdir(path_c.as_ptr()).and(Ok(()))
    }.map_err(|x| Error::from_sys(x))
}

/// Removes a directory at this path, after removing all its contents. Use carefully!
pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> Result<()> {
    for child in try!(read_dir(&path)) {
        let child = try!(child);
        if try!(child.file_type()).is_dir() {
            try!(remove_dir_all(&child.path()));
        } else {
            try!(remove_file(&child.path()));
        }
    }
    remove_dir(path)
}

/// Removes a file from the filesystem
pub fn remove_file<P: AsRef<Path>>(path: P) -> Result<()> {
    let path_str = path.as_ref().as_os_str().as_inner();
    let mut path_c = path_str.to_owned();
    path_c.push_str("\0");
    unsafe {
        sys_unlink(path_c.as_ptr()).and(Ok(()))
    }.map_err(|x| Error::from_sys(x))
}
<|endoftext|>


<commit_before><commit_msg>Add benchmarks for zeros / default<commit_after>#![feature(test)]

extern crate test;
use test::Bencher;

#[macro_use(s)]
extern crate ndarray;
use ndarray::prelude::*;

#[bench]
fn default_f64(bench: &mut Bencher) {
    bench.iter(|| {
        Array::<f64, _>::default((128, 128))
    })
}

#[bench]
fn zeros_f64(bench: &mut Bencher) {
    bench.iter(|| {
        Array::<f64, _>::zeros((128, 128))
    })
}
<|endoftext|>


<commit_before><commit_msg>Add a test for #2526<commit_after>// Test that rustfmt will not warn about comments exceeding max width around lifetime.
// See #2526.

// comment comment comment comment comment comment comment comment comment comment comment comment comment
fn foo() -> F<'a> {
    bar()
}
// comment comment comment comment comment comment comment comment comment comment comment comment comment
<|endoftext|>


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

use fmt::{Formatter, Result, LowerExp, UpperExp, Display, Debug};
use num::flt2dec;

// Don't inline this so callers don't use the stack space this function
// requires unless they have to.
#[inline(never)]
fn float_to_decimal_common_exact<T>(fmt: &mut Formatter, num: &T,
                                    sign: flt2dec::Sign, precision: usize) -> Result
    where T: flt2dec::DecodableFloat
{
    let mut buf = [0; 1024]; // enough for f32 and f64
    let mut parts = [flt2dec::Part::Zero(0); 5];
    let formatted = flt2dec::to_exact_fixed_str(flt2dec::strategy::grisu::format_exact,
                                                *num, sign, precision,
                                                false, &mut buf, &mut parts);
    fmt.pad_formatted_parts(&formatted)
}

// Don't inline this so callers that call both this and the above won't wind
// up using the combined stack space of both functions in some cases.
#[inline(never)]
fn float_to_decimal_common_shortest<T>(fmt: &mut Formatter,
                                       num: &T, sign: flt2dec::Sign) -> Result
    where T: flt2dec::DecodableFloat
{
    let mut buf = [0; flt2dec::MAX_SIG_DIGITS]; // enough for f32 and f64
    let mut parts = [flt2dec::Part::Zero(0); 5];
    let formatted = flt2dec::to_shortest_str(flt2dec::strategy::grisu::format_shortest,
                                             *num, sign, 0, false, &mut buf, &mut parts);
    fmt.pad_formatted_parts(&formatted)
}

// Common code of floating point Debug and Display.
fn float_to_decimal_common<T>(fmt: &mut Formatter, num: &T, negative_zero: bool) -> Result
    where T: flt2dec::DecodableFloat
{
    let force_sign = fmt.sign_plus();
    let sign = match (force_sign, negative_zero) {
        (false, false) => flt2dec::Sign::Minus,
        (false, true)  => flt2dec::Sign::MinusRaw,
        (true,  false) => flt2dec::Sign::MinusPlus,
        (true,  true)  => flt2dec::Sign::MinusPlusRaw,
    };

    if let Some(precision) = fmt.precision {
        float_to_decimal_common_exact(fmt, num, sign, precision)
    } else {
        float_to_decimal_common_shortest(fmt, num, sign)
    }
}

// Don't inline this so callers don't use the stack space this function
// requires unless they have to.
#[inline(never)]
fn float_to_exponential_common_exact<T>(fmt: &mut Formatter, num: &T,
                                        sign: flt2dec::Sign, precision: usize,
                                        upper: bool) -> Result
    where T: flt2dec::DecodableFloat
{
    let mut buf = [0; 1024]; // enough for f32 and f64
    let mut parts = [flt2dec::Part::Zero(0); 7];
    let formatted = flt2dec::to_exact_exp_str(flt2dec::strategy::grisu::format_exact,
                                              *num, sign, precision,
                                              upper, &mut buf, &mut parts);
    fmt.pad_formatted_parts(&formatted)
}

// Don't inline this so callers that call both this and the above won't wind
// up using the combined stack space of both functions in some cases.
#[inline(never)]
fn float_to_exponential_common_shortest<T>(fmt: &mut Formatter,
                                           num: &T, sign: flt2dec::Sign,
                                           upper: bool) -> Result
    where T: flt2dec::DecodableFloat
{
    let mut buf = [0; flt2dec::MAX_SIG_DIGITS]; // enough for f32 and f64
    let mut parts = [flt2dec::Part::Zero(0); 7];
    let formatted = flt2dec::to_shortest_exp_str(flt2dec::strategy::grisu::format_shortest, *num,
                                                 sign, (0, 0), upper, &mut buf, &mut parts);
    fmt.pad_formatted_parts(&formatted)
}

// Common code of floating point LowerExp and UpperExp.
fn float_to_exponential_common<T>(fmt: &mut Formatter, num: &T, upper: bool) -> Result
    where T: flt2dec::DecodableFloat
{
    let force_sign = fmt.sign_plus();
    let sign = match force_sign {
        false => flt2dec::Sign::Minus,
        true  => flt2dec::Sign::MinusPlus,
    };

    if let Some(precision) = fmt.precision {
        // 1 integral digit + `precision` fractional digits = `precision + 1` total digits
        float_to_exponential_common_exact(fmt, num, sign, precision + 1, upper)
    } else {
        float_to_exponential_common_shortest(fmt, num, sign, upper)
    }
}

macro_rules! floating {
    ($ty:ident) => (
        #[stable(feature = "rust1", since = "1.0.0")]
        impl Debug for $ty {
            fn fmt(&self, fmt: &mut Formatter) -> Result {
                float_to_decimal_common(fmt, self, true)
            }
        }

        #[stable(feature = "rust1", since = "1.0.0")]
        impl Display for $ty {
            fn fmt(&self, fmt: &mut Formatter) -> Result {
                float_to_decimal_common(fmt, self, false)
            }
        }

        #[stable(feature = "rust1", since = "1.0.0")]
        impl LowerExp for $ty {
            fn fmt(&self, fmt: &mut Formatter) -> Result {
                float_to_exponential_common(fmt, self, false)
            }
        }

        #[stable(feature = "rust1", since = "1.0.0")]
        impl UpperExp for $ty {
            fn fmt(&self, fmt: &mut Formatter) -> Result {
                float_to_exponential_common(fmt, self, true)
            }
        }
    )
}

floating! { f32 }
floating! { f64 }
<commit_msg>fmt: use mem::uninitialized for float formatting buffers<commit_after>// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use fmt::{Formatter, Result, LowerExp, UpperExp, Display, Debug};
use mem;
use num::flt2dec;

// Don't inline this so callers don't use the stack space this function
// requires unless they have to.
#[inline(never)]
fn float_to_decimal_common_exact<T>(fmt: &mut Formatter, num: &T,
                                    sign: flt2dec::Sign, precision: usize) -> Result
    where T: flt2dec::DecodableFloat
{
    unsafe {
        let mut buf: [u8; 1024] = mem::uninitialized(); // enough for f32 and f64
        let mut parts: [flt2dec::Part; 5] = mem::uninitialized();
        let formatted = flt2dec::to_exact_fixed_str(flt2dec::strategy::grisu::format_exact,
                                                    *num, sign, precision,
                                                    false, &mut buf, &mut parts);
        fmt.pad_formatted_parts(&formatted)
    }
}

// Don't inline this so callers that call both this and the above won't wind
// up using the combined stack space of both functions in some cases.
#[inline(never)]
fn float_to_decimal_common_shortest<T>(fmt: &mut Formatter,
                                       num: &T, sign: flt2dec::Sign) -> Result
    where T: flt2dec::DecodableFloat
{
    unsafe {
        // enough for f32 and f64
        let mut buf: [u8; flt2dec::MAX_SIG_DIGITS] = mem::uninitialized();
        let mut parts: [flt2dec::Part; 5] = mem::uninitialized();
        let formatted = flt2dec::to_shortest_str(flt2dec::strategy::grisu::format_shortest,
                                                 *num, sign, 0, false, &mut buf, &mut parts);
        fmt.pad_formatted_parts(&formatted)
    }
}

// Common code of floating point Debug and Display.
fn float_to_decimal_common<T>(fmt: &mut Formatter, num: &T, negative_zero: bool) -> Result
    where T: flt2dec::DecodableFloat
{
    let force_sign = fmt.sign_plus();
    let sign = match (force_sign, negative_zero) {
        (false, false) => flt2dec::Sign::Minus,
        (false, true)  => flt2dec::Sign::MinusRaw,
        (true,  false) => flt2dec::Sign::MinusPlus,
        (true,  true)  => flt2dec::Sign::MinusPlusRaw,
    };

    if let Some(precision) = fmt.precision {
        float_to_decimal_common_exact(fmt, num, sign, precision)
    } else {
        float_to_decimal_common_shortest(fmt, num, sign)
    }
}

// Don't inline this so callers don't use the stack space this function
// requires unless they have to.
#[inline(never)]
fn float_to_exponential_common_exact<T>(fmt: &mut Formatter, num: &T,
                                        sign: flt2dec::Sign, precision: usize,
                                        upper: bool) -> Result
    where T: flt2dec::DecodableFloat
{
    unsafe {
        let mut buf: [u8; 1024] = mem::uninitialized(); // enough for f32 and f64
        let mut parts: [flt2dec::Part; 7] = mem::uninitialized();
        let formatted = flt2dec::to_exact_exp_str(flt2dec::strategy::grisu::format_exact,
                                                  *num, sign, precision,
                                                  upper, &mut buf, &mut parts);
        fmt.pad_formatted_parts(&formatted)
    }
}

// Don't inline this so callers that call both this and the above won't wind
// up using the combined stack space of both functions in some cases.
#[inline(never)]
fn float_to_exponential_common_shortest<T>(fmt: &mut Formatter,
                                           num: &T, sign: flt2dec::Sign,
                                           upper: bool) -> Result
    where T: flt2dec::DecodableFloat
{
    unsafe {
        // enough for f32 and f64
        let mut buf: [u8; flt2dec::MAX_SIG_DIGITS] = mem::uninitialized();
        let mut parts: [flt2dec::Part; 7] = mem::uninitialized();
        let formatted = flt2dec::to_shortest_exp_str(flt2dec::strategy::grisu::format_shortest,
                                                     *num, sign, (0, 0), upper,
                                                     &mut buf, &mut parts);
        fmt.pad_formatted_parts(&formatted)
    }
}

// Common code of floating point LowerExp and UpperExp.
fn float_to_exponential_common<T>(fmt: &mut Formatter, num: &T, upper: bool) -> Result
    where T: flt2dec::DecodableFloat
{
    let force_sign = fmt.sign_plus();
    let sign = match force_sign {
        false => flt2dec::Sign::Minus,
        true  => flt2dec::Sign::MinusPlus,
    };

    if let Some(precision) = fmt.precision {
        // 1 integral digit + `precision` fractional digits = `precision + 1` total digits
        float_to_exponential_common_exact(fmt, num, sign, precision + 1, upper)
    } else {
        float_to_exponential_common_shortest(fmt, num, sign, upper)
    }
}

macro_rules! floating {
    ($ty:ident) => (
        #[stable(feature = "rust1", since = "1.0.0")]
        impl Debug for $ty {
            fn fmt(&self, fmt: &mut Formatter) -> Result {
                float_to_decimal_common(fmt, self, true)
            }
        }

        #[stable(feature = "rust1", since = "1.0.0")]
        impl Display for $ty {
            fn fmt(&self, fmt: &mut Formatter) -> Result {
                float_to_decimal_common(fmt, self, false)
            }
        }

        #[stable(feature = "rust1", since = "1.0.0")]
        impl LowerExp for $ty {
            fn fmt(&self, fmt: &mut Formatter) -> Result {
                float_to_exponential_common(fmt, self, false)
            }
        }

        #[stable(feature = "rust1", since = "1.0.0")]
        impl UpperExp for $ty {
            fn fmt(&self, fmt: &mut Formatter) -> Result {
                float_to_exponential_common(fmt, self, true)
            }
        }
    )
}

floating! { f32 }
floating! { f64 }
<|endoftext|>


<commit_before>#[doc="Fundamental layout structures and algorithms."]

import dom::base::{nk_div, nk_img, node_data, node_kind, node};
import dom::rcu;
import dom::rcu::reader_methods;
import gfx::geom;
import gfx::geom::{size, rect, point, au, zero_size_au};
import /*layout::*/block::block_layout_methods;
import /*layout::*/inline::inline_layout_methods;
import /*layout::*/style::style::{computed_style, di_block, di_inline};
import /*layout::*/style::style::style_methods;
import util::tree;

enum box_kind {
    bk_block,
    bk_inline,
    bk_intrinsic(@geom::size<au>)
}

enum box = {
    tree: tree::fields<@box>,
    node: node,
    mut bounds: geom::rect<au>,
    kind: box_kind
};

enum layout_data = {
    mut computed_style: computed_style,
    mut box: option<@box>
};

enum ntree { ntree }
impl of tree::rd_tree_ops<node> for ntree {
    fn each_child(node: node, f: fn(node) -> bool) {
        tree::each_child(self, node, f)
    }

    fn with_tree_fields<R>(n: node, f: fn(tree::fields<node>) -> R) -> R {
        n.rd { |n| f(n.tree) }
    }
}

enum btree { btree }
impl of tree::rd_tree_ops<@box> for btree {
    fn each_child(node: @box, f: fn(&&@box) -> bool) {
        tree::each_child(self, node, f)
    }

    fn with_tree_fields<R>(b: @box, f: fn(tree::fields<@box>) -> R) -> R {
        f(b.tree)
    }
}

impl of tree::wr_tree_ops<@box> for btree {
    fn add_child(node: @box, child: @box) {
        tree::add_child(self, node, child)
    }

    fn with_tree_fields<R>(b: @box, f: fn(tree::fields<@box>) -> R) -> R {
        f(b.tree)
    }
}

impl layout_methods for @box {
    #[doc="The main reflow routine."]
    fn reflow(available_width: au) {
        alt self.kind {
            bk_block { self.reflow_block(available_width) }
            bk_inline { self.reflow_inline(available_width) }
            bk_intrinsic(size) { self.reflow_intrinsic(*size) }
        }
    }

    #[doc="The trivial reflow routine for instrinsically-sized frames."]
    fn reflow_intrinsic(size: geom::size<au>) {
        self.bounds.size = size;

        #debug["reflow_intrinsic size=%?", self.bounds];
    }
}

#[cfg(test)]
mod test {
    import dom::base::{nk_img, node_data, node_kind, node, methods,
                       wr_tree_ops};
    import dom::rcu::scope;

    /*
    use sdl;
    import sdl::video;

    fn with_screen(f: fn(*sdl::surface)) {
        let screen = video::set_video_mode(
            320, 200, 32,
            [video::hwsurface], [video::doublebuf]);
        assert screen != ptr::null();

        f(screen);

        video::free_surface(screen);
    }
    */

    fn flat_bounds(root: @box) -> [geom::rect<au>] {
        let mut r = [];
        for tree::each_child(btree, root) {|c|
            r += flat_bounds(c);
        }
        ret r + [root.bounds];
    }

    #[test]
    fn do_layout() {
        let s = scope();

        let n0 = s.new_node(nk_img(size(au(10),au(10))));
        let n1 = s.new_node(nk_img(size(au(10),au(15))));
        let n2 = s.new_node(nk_img(size(au(10),au(20))));
        let n3 = s.new_node(nk_div);

        tree::add_child(s, n3, n0);
        tree::add_child(s, n3, n1);
        tree::add_child(s, n3, n2);

        let b0 = linked_box(n0);
        let b1 = linked_box(n1);
        let b2 = linked_box(n2);
        let b3 = linked_box(n3);

        tree::add_child(btree, b3, b0);
        tree::add_child(btree, b3, b1);
        tree::add_child(btree, b3, b2);

        b3.reflow_block(au(100));
        let fb = flat_bounds(b3);
        #debug["fb=%?", fb];
        assert fb == [geom::box(au(0), au(0), au(10), au(10)),   // n0
                      geom::box(au(0), au(10), au(10), au(15)),  // n1
                      geom::box(au(0), au(25), au(10), au(20)),  // n2
                      geom::box(au(0), au(0), au(100), au(45))]; // n3
    }
}

<commit_msg>Fix broken test<commit_after>#[doc="Fundamental layout structures and algorithms."]

import dom::base::{nk_div, nk_img, node_data, node_kind, node};
import dom::rcu;
import dom::rcu::reader_methods;
import gfx::geom;
import gfx::geom::{size, rect, point, au, zero_size_au};
import /*layout::*/block::block_layout_methods;
import /*layout::*/inline::inline_layout_methods;
import /*layout::*/style::style::{computed_style, di_block, di_inline};
import /*layout::*/style::style::style_methods;
import util::tree;

enum box_kind {
    bk_block,
    bk_inline,
    bk_intrinsic(@geom::size<au>)
}

enum box = {
    tree: tree::fields<@box>,
    node: node,
    mut bounds: geom::rect<au>,
    kind: box_kind
};

enum layout_data = {
    mut computed_style: computed_style,
    mut box: option<@box>
};

enum ntree { ntree }
impl of tree::rd_tree_ops<node> for ntree {
    fn each_child(node: node, f: fn(node) -> bool) {
        tree::each_child(self, node, f)
    }

    fn with_tree_fields<R>(n: node, f: fn(tree::fields<node>) -> R) -> R {
        n.rd { |n| f(n.tree) }
    }
}

enum btree { btree }
impl of tree::rd_tree_ops<@box> for btree {
    fn each_child(node: @box, f: fn(&&@box) -> bool) {
        tree::each_child(self, node, f)
    }

    fn with_tree_fields<R>(b: @box, f: fn(tree::fields<@box>) -> R) -> R {
        f(b.tree)
    }
}

impl of tree::wr_tree_ops<@box> for btree {
    fn add_child(node: @box, child: @box) {
        tree::add_child(self, node, child)
    }

    fn with_tree_fields<R>(b: @box, f: fn(tree::fields<@box>) -> R) -> R {
        f(b.tree)
    }
}

impl layout_methods for @box {
    #[doc="The main reflow routine."]
    fn reflow(available_width: au) {
        alt self.kind {
            bk_block { self.reflow_block(available_width) }
            bk_inline { self.reflow_inline(available_width) }
            bk_intrinsic(size) { self.reflow_intrinsic(*size) }
        }
    }

    #[doc="The trivial reflow routine for instrinsically-sized frames."]
    fn reflow_intrinsic(size: geom::size<au>) {
        self.bounds.size = size;

        #debug["reflow_intrinsic size=%?", self.bounds];
    }
}

#[cfg(test)]
mod test {
    import dom::base::{nk_img, node_data, node_kind, node, methods,
                       wr_tree_ops};
    import dom::rcu::scope;
    import box_builder::{box_builder_methods};

    /*
    use sdl;
    import sdl::video;

    fn with_screen(f: fn(*sdl::surface)) {
        let screen = video::set_video_mode(
            320, 200, 32,
            [video::hwsurface], [video::doublebuf]);
        assert screen != ptr::null();

        f(screen);

        video::free_surface(screen);
    }
    */

    fn flat_bounds(root: @box) -> [geom::rect<au>] {
        let mut r = [];
        for tree::each_child(btree, root) {|c|
            r += flat_bounds(c);
        }
        ret r + [root.bounds];
    }

    #[test]
    #[ignore(reason = "busted")]
    fn do_layout() {
        let s = scope();

        let n0 = s.new_node(nk_img(size(au(10),au(10))));
        let n1 = s.new_node(nk_img(size(au(10),au(15))));
        let n2 = s.new_node(nk_img(size(au(10),au(20))));
        let n3 = s.new_node(nk_div);

        tree::add_child(s, n3, n0);
        tree::add_child(s, n3, n1);
        tree::add_child(s, n3, n2);

        let b0 = n0.construct_boxes_for_subtree();
        let b1 = n1.construct_boxes_for_subtree();
        let b2 = n2.construct_boxes_for_subtree();
        let b3 = n3.construct_boxes_for_subtree();

        tree::add_child(btree, b3, b0);
        tree::add_child(btree, b3, b1);
        tree::add_child(btree, b3, b2);

        b3.reflow_block(au(100));
        let fb = flat_bounds(b3);
        #debug["fb=%?", fb];
        assert fb == [geom::box(au(0), au(0), au(10), au(10)),   // n0
                      geom::box(au(0), au(10), au(10), au(15)),  // n1
                      geom::box(au(0), au(25), au(10), au(20)),  // n2
                      geom::box(au(0), au(0), au(100), au(45))]; // n3
    }
}

<|endoftext|>


<commit_before><commit_msg>Add test for closure drop.<commit_after>struct Foo<'a>(&'a mut bool);

impl<'a> Drop for Foo<'a> {
    fn drop(&mut self) {
        *self.0 = true;
    }
}

fn f<T: FnOnce()>(t: T) {
    t()
}

fn main() {
    let mut ran_drop = false;
    {
        // FIXME: v is a temporary hack to force the below closure to be a FnOnce-only closure
        // (with sig fn(self)). Without it, the closure sig would be fn(&self) which requires a
        // shim to call via FnOnce::call_once, and Miri's current shim doesn't correctly call
        // destructors.
        let v = vec![1];
        let x = Foo(&mut ran_drop);
        let g = move || {
            let _ = x;
            drop(v); // Force the closure to be FnOnce-only by using a capture by-value.
        };
        f(g);
    }
    assert!(ran_drop);
}

<|endoftext|>


<commit_before><commit_msg>Rust implementation of swap.<commit_after>#![feature(macro_rules)]

macro_rules! swap {
    ($x:ident, $y:ident) => {
        {
            let tmp = $x;
            $x = $y;
            $y = tmp;
        }
    }
}

fn main() {
    let mut a = 1i;
    let mut b = 2i;

    swap!(a, b);

    println!("a: {} b: {}", a, b);
}
<|endoftext|>


<commit_before><commit_msg>Auto merge of #24818 - gterzian:fix_panic_on_finish_load, r=jdm<commit_after><|endoftext|>


<commit_before><commit_msg>Fix: In-Memory test backend: Actually remove the old entry on "move"<commit_after><|endoftext|>


<commit_before><commit_msg>Fix: Deleting an Entry could leave artifacts in cache<commit_after><|endoftext|>


<commit_before><commit_msg>Problem: we do not have a bare bones example<commit_after>extern crate tokio_core;
extern crate futures;
extern crate reql;

use tokio_core::reactor::Core;
use futures::stream::Stream;
use reql::{Client, Run, ResponseValue};
use reql::structs::ServerStatus;

fn main() {
    // Create a new ReQL client
    let r = Client::new();

    // Create an even loop
    let core = Core::new().unwrap();

    // Create a connection pool
    let conn = r.connect(&core.handle()).unwrap();

    // Run the query
    let query = r.db("rethinkdb").table("server_status").run::<ServerStatus>(conn).unwrap();

    // Process the results
    let stati = query.and_then(|status| {
        match status {
            // The server returned the response we were expecting
            Some(ResponseValue::Expected(change)) => {
                println!("{:?}", change);
            }
            // We got a response alright, but it wasn't the one were expecting
            // plus it's not an error either, otherwise it would have been
            // returned as such (This simply means that the response we got
            // couldn't be serialised into the type we were expecting)
            Some(ResponseValue::Unexpected(change)) => {
                println!("unexpected response from server: {:?}", change);
            }
            // This is impossible in this particular example since there
            // needs to be at least one server available to give this
            // response otherwise we would have run into an error for
            // failing to connect
            None => {
                println!("got no documents in the database");
            }
        }
        Ok(())
    })
    // Our query ran into an error
    .or_else(|error| {
        println!("{:?}", error);
        Err(())
    })
    ;

    // Wait for all the results to be processed
    for _ in stati.wait() { }
}
<|endoftext|>


<commit_before><commit_msg>Use "::std" instead of "std"<commit_after><|endoftext|>


<commit_before><commit_msg>updated build.rs to use 'git describe'<commit_after><|endoftext|>


<commit_before>#[macro_use] extern crate log;
extern crate toml;

extern crate libimagstore;

pub mod debug;

<commit_msg>Enable lints<commit_after>#![deny(
    dead_code,
    non_camel_case_types,
    non_snake_case,
    path_statements,
    trivial_numeric_casts,
    unstable_features,
    unused_allocation,
    unused_import_braces,
    unused_imports,
    unused_must_use,
    unused_mut,
    unused_qualifications,
    while_true,
)]

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

extern crate libimagstore;

pub mod debug;

<|endoftext|>


<commit_before><commit_msg>Added ² and ³ to calc (#298)<commit_after><|endoftext|>


<commit_before><commit_msg>Fix parsing bugs.<commit_after><|endoftext|>


<commit_before><commit_msg>Commit missing label.rs file (almost lost during git operations)<commit_after>//! Plugin which updates the `labels` in a `dc::File`.

use compose_yml::v2 as dc;
use std::marker::PhantomData;

use errors::*;
use plugins;
use plugins::{Operation, PluginNew, PluginTransform};
use project::Project;

/// Updates the `labels` in a `dc::File`.
#[derive(Debug)]
#[allow(missing_copy_implementations)]
pub struct Plugin {
    /// Placeholder field for future hidden fields, to keep this from being
    /// directly constructable.
    _placeholder: PhantomData<()>,
}

impl plugins::Plugin for Plugin {
    fn name(&self) -> &'static str {
        Self::plugin_name()
    }
}

impl PluginNew for Plugin {
    fn plugin_name() -> &'static str {
        "labels"
    }

    fn new(_project: &Project) -> Result<Self> {
        Ok(Plugin { _placeholder: PhantomData })
    }
}

impl PluginTransform for Plugin {
    fn transform(&self,
                 _op: Operation,
                 ctx: &plugins::Context,
                 file: &mut dc::File)
                 -> Result<()> {

        for service in &mut file.services.values_mut() {
            // These are intended for easy use as `docker ps --filter label
            service.labels
                .insert("io.fdy.cage.override".into(), ctx.ovr.name().into());
            service.labels.insert("io.fdy.cage.pod".into(), ctx.pod.name().into());

            // TODO LOW: Remove metadata-only `io.fdy.cage.` labels?
        }
        Ok(())
    }
}
<|endoftext|>