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

use hir::map::definitions::*;
use hir::def_id::{CRATE_DEF_INDEX, DefIndex, DefIndexAddressSpace};
use session::CrateDisambiguator;

use syntax::ast::*;
use syntax::ext::hygiene::Mark;
use syntax::visit;
use syntax::symbol::keywords;
use syntax::symbol::Symbol;
use syntax::parse::token::{self, Token};
use syntax_pos::Span;

use hir::map::{ITEM_LIKE_SPACE, REGULAR_SPACE};

/// Creates def ids for nodes in the AST.
pub struct DefCollector<'a> {
    definitions: &'a mut Definitions,
    parent_def: Option<DefIndex>,
    expansion: Mark,
    pub visit_macro_invoc: Option<&'a mut dyn FnMut(MacroInvocationData)>,
}

pub struct MacroInvocationData {
    pub mark: Mark,
    pub def_index: DefIndex,
    pub const_expr: bool,
}

impl<'a> DefCollector<'a> {
    pub fn new(definitions: &'a mut Definitions, expansion: Mark) -> Self {
        DefCollector {
            definitions,
            expansion,
            parent_def: None,
            visit_macro_invoc: None,
        }
    }

    pub fn collect_root(&mut self,
                        crate_name: &str,
                        crate_disambiguator: CrateDisambiguator) {
        let root = self.definitions.create_root_def(crate_name,
                                                    crate_disambiguator);
        assert_eq!(root, CRATE_DEF_INDEX);
        self.parent_def = Some(root);
    }

    fn create_def(&mut self,
                  node_id: NodeId,
                  data: DefPathData,
                  address_space: DefIndexAddressSpace,
                  span: Span)
                  -> DefIndex {
        let parent_def = self.parent_def.unwrap();
        debug!("create_def(node_id={:?}, data={:?}, parent_def={:?})", node_id, data, parent_def);
        self.definitions
            .create_def_with_parent(parent_def, node_id, data, address_space, self.expansion, span)
    }

    pub fn with_parent<F: FnOnce(&mut Self)>(&mut self, parent_def: DefIndex, f: F) {
        let parent = self.parent_def;
        self.parent_def = Some(parent_def);
        f(self);
        self.parent_def = parent;
    }

    pub fn visit_const_expr(&mut self, expr: &Expr) {
        match expr.node {
            // Find the node which will be used after lowering.
            ExprKind::Paren(ref inner) => return self.visit_const_expr(inner),
            ExprKind::Mac(..) => return self.visit_macro_invoc(expr.id, true),
            // FIXME(eddyb) Closures should have separate
            // function definition IDs and expression IDs.
            ExprKind::Closure(..) => return,
            _ => {}
        }

        self.create_def(expr.id, DefPathData::Initializer, REGULAR_SPACE, expr.span);
    }

    fn visit_macro_invoc(&mut self, id: NodeId, const_expr: bool) {
        if let Some(ref mut visit) = self.visit_macro_invoc {
            visit(MacroInvocationData {
                mark: id.placeholder_to_mark(),
                const_expr,
                def_index: self.parent_def.unwrap(),
            })
        }
    }
}

impl<'a> visit::Visitor<'a> for DefCollector<'a> {
    fn visit_item(&mut self, i: &'a Item) {
        debug!("visit_item: {:?}", i);

        // Pick the def data. This need not be unique, but the more
        // information we encapsulate into
        let def_data = match i.node {
            ItemKind::Impl(..) => DefPathData::Impl,
            ItemKind::Trait(..) => DefPathData::Trait(i.ident.name.as_interned_str()),
            ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) |
            ItemKind::TraitAlias(..) |
            ItemKind::ExternCrate(..) | ItemKind::ForeignMod(..) | ItemKind::Ty(..) =>
                DefPathData::TypeNs(i.ident.name.as_interned_str()),
            ItemKind::Mod(..) if i.ident == keywords::Invalid.ident() => {
                return visit::walk_item(self, i);
            }
            ItemKind::Mod(..) => DefPathData::Module(i.ident.name.as_interned_str()),
            ItemKind::Static(..) | ItemKind::Const(..) | ItemKind::Fn(..) =>
                DefPathData::ValueNs(i.ident.name.as_interned_str()),
            ItemKind::MacroDef(..) => DefPathData::MacroDef(i.ident.name.as_interned_str()),
            ItemKind::Mac(..) => return self.visit_macro_invoc(i.id, false),
            ItemKind::GlobalAsm(..) => DefPathData::Misc,
            ItemKind::Use(..) => {
                return visit::walk_item(self, i);
            }
        };
        let def = self.create_def(i.id, def_data, ITEM_LIKE_SPACE, i.span);

        self.with_parent(def, |this| {
            match i.node {
                ItemKind::Enum(ref enum_definition, _) => {
                    for v in &enum_definition.variants {
                        let variant_def_index =
                            this.create_def(v.node.data.id(),
                                            DefPathData::EnumVariant(v.node.ident
                                                                      .name.as_interned_str()),
                                            REGULAR_SPACE,
                                            v.span);
                        this.with_parent(variant_def_index, |this| {
                            for (index, field) in v.node.data.fields().iter().enumerate() {
                                let name = field.ident.map(|ident| ident.name)
                                    .unwrap_or_else(|| Symbol::intern(&index.to_string()));
                                this.create_def(field.id,
                                                DefPathData::Field(name.as_interned_str()),
                                                REGULAR_SPACE,
                                                field.span);
                            }

                            if let Some(ref expr) = v.node.disr_expr {
                                this.visit_const_expr(expr);
                            }
                        });
                    }
                }
                ItemKind::Struct(ref struct_def, _) | ItemKind::Union(ref struct_def, _) => {
                    // If this is a tuple-like struct, register the constructor.
                    if !struct_def.is_struct() {
                        this.create_def(struct_def.id(),
                                        DefPathData::StructCtor,
                                        REGULAR_SPACE,
                                        i.span);
                    }

                    for (index, field) in struct_def.fields().iter().enumerate() {
                        let name = field.ident.map(|ident| ident.name)
                            .unwrap_or_else(|| Symbol::intern(&index.to_string()));
                        this.create_def(field.id,
                                        DefPathData::Field(name.as_interned_str()),
                                        REGULAR_SPACE,
                                        field.span);
                    }
                }
                _ => {}
            }
            visit::walk_item(this, i);
        });
    }

    fn visit_use_tree(&mut self, use_tree: &'a UseTree, id: NodeId, _nested: bool) {
        self.create_def(id, DefPathData::Misc, ITEM_LIKE_SPACE, use_tree.span);
        visit::walk_use_tree(self, use_tree, id);
    }

    fn visit_foreign_item(&mut self, foreign_item: &'a ForeignItem) {
        if let ForeignItemKind::Macro(_) = foreign_item.node {
            return self.visit_macro_invoc(foreign_item.id, false);
        }

        let def = self.create_def(foreign_item.id,
                                  DefPathData::ValueNs(foreign_item.ident.name.as_interned_str()),
                                  REGULAR_SPACE,
                                  foreign_item.span);

        self.with_parent(def, |this| {
            visit::walk_foreign_item(this, foreign_item);
        });
    }

    fn visit_generic_param(&mut self, param: &'a GenericParam) {
        match *param {
            GenericParam::Lifetime(ref lifetime_def) => {
                self.create_def(
                    lifetime_def.lifetime.id,
                    DefPathData::LifetimeDef(lifetime_def.lifetime.ident.name.as_interned_str()),
                    REGULAR_SPACE,
                    lifetime_def.lifetime.ident.span
                );
            }
            GenericParam::Type(ref ty_param) => {
                self.create_def(
                    ty_param.id,
                    DefPathData::TypeParam(ty_param.ident.name.as_interned_str()),
                    REGULAR_SPACE,
                    ty_param.ident.span
                );
            }
        }

        visit::walk_generic_param(self, param);
    }

    fn visit_trait_item(&mut self, ti: &'a TraitItem) {
        let def_data = match ti.node {
            TraitItemKind::Method(..) | TraitItemKind::Const(..) =>
                DefPathData::ValueNs(ti.ident.name.as_interned_str()),
            TraitItemKind::Type(..) => {
                DefPathData::AssocTypeInTrait(ti.ident.name.as_interned_str())
            },
            TraitItemKind::Macro(..) => return self.visit_macro_invoc(ti.id, false),
        };

        let def = self.create_def(ti.id, def_data, ITEM_LIKE_SPACE, ti.span);
        self.with_parent(def, |this| {
            if let TraitItemKind::Const(_, Some(ref expr)) = ti.node {
                this.visit_const_expr(expr);
            }

            visit::walk_trait_item(this, ti);
        });
    }

    fn visit_impl_item(&mut self, ii: &'a ImplItem) {
        let def_data = match ii.node {
            ImplItemKind::Method(..) | ImplItemKind::Const(..) =>
                DefPathData::ValueNs(ii.ident.name.as_interned_str()),
            ImplItemKind::Type(..) => DefPathData::AssocTypeInImpl(ii.ident.name.as_interned_str()),
            ImplItemKind::Macro(..) => return self.visit_macro_invoc(ii.id, false),
        };

        let def = self.create_def(ii.id, def_data, ITEM_LIKE_SPACE, ii.span);
        self.with_parent(def, |this| {
            if let ImplItemKind::Const(_, ref expr) = ii.node {
                this.visit_const_expr(expr);
            }

            visit::walk_impl_item(this, ii);
        });
    }

    fn visit_pat(&mut self, pat: &'a Pat) {
        match pat.node {
            PatKind::Mac(..) => return self.visit_macro_invoc(pat.id, false),
            _ => visit::walk_pat(self, pat),
        }
    }

    fn visit_expr(&mut self, expr: &'a Expr) {
        let parent_def = self.parent_def;

        match expr.node {
            ExprKind::Mac(..) => return self.visit_macro_invoc(expr.id, false),
            ExprKind::Repeat(_, ref count) => self.visit_const_expr(count),
            ExprKind::Closure(..) => {
                let def = self.create_def(expr.id,
                                          DefPathData::ClosureExpr,
                                          REGULAR_SPACE,
                                          expr.span);
                self.parent_def = Some(def);
            }
            _ => {}
        }

        visit::walk_expr(self, expr);
        self.parent_def = parent_def;
    }

    fn visit_ty(&mut self, ty: &'a Ty) {
        match ty.node {
            TyKind::Mac(..) => return self.visit_macro_invoc(ty.id, false),
            TyKind::Array(_, ref length) => self.visit_const_expr(length),
            TyKind::ImplTrait(..) => {
                self.create_def(ty.id, DefPathData::ImplTrait, REGULAR_SPACE, ty.span);
            }
            TyKind::Typeof(ref expr) => self.visit_const_expr(expr),
            _ => {}
        }
        visit::walk_ty(self, ty);
    }

    fn visit_stmt(&mut self, stmt: &'a Stmt) {
        match stmt.node {
            StmtKind::Mac(..) => self.visit_macro_invoc(stmt.id, false),
            _ => visit::walk_stmt(self, stmt),
        }
    }

    fn visit_token(&mut self, t: Token) {
        if let Token::Interpolated(nt) = t {
            match nt.0 {
                token::NtExpr(ref expr) => {
                    if let ExprKind::Mac(..) = expr.node {
                        self.visit_macro_invoc(expr.id, false);
                    }
                }
                _ => {}
            }
        }
    }
}
<commit_msg>rustc: removed unused `DefPathData::Initializer` DefId's for associated constants.<commit_after>// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use hir::map::definitions::*;
use hir::def_id::{CRATE_DEF_INDEX, DefIndex, DefIndexAddressSpace};
use session::CrateDisambiguator;

use syntax::ast::*;
use syntax::ext::hygiene::Mark;
use syntax::visit;
use syntax::symbol::keywords;
use syntax::symbol::Symbol;
use syntax::parse::token::{self, Token};
use syntax_pos::Span;

use hir::map::{ITEM_LIKE_SPACE, REGULAR_SPACE};

/// Creates def ids for nodes in the AST.
pub struct DefCollector<'a> {
    definitions: &'a mut Definitions,
    parent_def: Option<DefIndex>,
    expansion: Mark,
    pub visit_macro_invoc: Option<&'a mut dyn FnMut(MacroInvocationData)>,
}

pub struct MacroInvocationData {
    pub mark: Mark,
    pub def_index: DefIndex,
    pub const_expr: bool,
}

impl<'a> DefCollector<'a> {
    pub fn new(definitions: &'a mut Definitions, expansion: Mark) -> Self {
        DefCollector {
            definitions,
            expansion,
            parent_def: None,
            visit_macro_invoc: None,
        }
    }

    pub fn collect_root(&mut self,
                        crate_name: &str,
                        crate_disambiguator: CrateDisambiguator) {
        let root = self.definitions.create_root_def(crate_name,
                                                    crate_disambiguator);
        assert_eq!(root, CRATE_DEF_INDEX);
        self.parent_def = Some(root);
    }

    fn create_def(&mut self,
                  node_id: NodeId,
                  data: DefPathData,
                  address_space: DefIndexAddressSpace,
                  span: Span)
                  -> DefIndex {
        let parent_def = self.parent_def.unwrap();
        debug!("create_def(node_id={:?}, data={:?}, parent_def={:?})", node_id, data, parent_def);
        self.definitions
            .create_def_with_parent(parent_def, node_id, data, address_space, self.expansion, span)
    }

    pub fn with_parent<F: FnOnce(&mut Self)>(&mut self, parent_def: DefIndex, f: F) {
        let parent = self.parent_def;
        self.parent_def = Some(parent_def);
        f(self);
        self.parent_def = parent;
    }

    pub fn visit_const_expr(&mut self, expr: &Expr) {
        match expr.node {
            // Find the node which will be used after lowering.
            ExprKind::Paren(ref inner) => return self.visit_const_expr(inner),
            ExprKind::Mac(..) => return self.visit_macro_invoc(expr.id, true),
            // FIXME(eddyb) Closures should have separate
            // function definition IDs and expression IDs.
            ExprKind::Closure(..) => return,
            _ => {}
        }

        self.create_def(expr.id, DefPathData::Initializer, REGULAR_SPACE, expr.span);
    }

    fn visit_macro_invoc(&mut self, id: NodeId, const_expr: bool) {
        if let Some(ref mut visit) = self.visit_macro_invoc {
            visit(MacroInvocationData {
                mark: id.placeholder_to_mark(),
                const_expr,
                def_index: self.parent_def.unwrap(),
            })
        }
    }
}

impl<'a> visit::Visitor<'a> for DefCollector<'a> {
    fn visit_item(&mut self, i: &'a Item) {
        debug!("visit_item: {:?}", i);

        // Pick the def data. This need not be unique, but the more
        // information we encapsulate into
        let def_data = match i.node {
            ItemKind::Impl(..) => DefPathData::Impl,
            ItemKind::Trait(..) => DefPathData::Trait(i.ident.name.as_interned_str()),
            ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) |
            ItemKind::TraitAlias(..) |
            ItemKind::ExternCrate(..) | ItemKind::ForeignMod(..) | ItemKind::Ty(..) =>
                DefPathData::TypeNs(i.ident.name.as_interned_str()),
            ItemKind::Mod(..) if i.ident == keywords::Invalid.ident() => {
                return visit::walk_item(self, i);
            }
            ItemKind::Mod(..) => DefPathData::Module(i.ident.name.as_interned_str()),
            ItemKind::Static(..) | ItemKind::Const(..) | ItemKind::Fn(..) =>
                DefPathData::ValueNs(i.ident.name.as_interned_str()),
            ItemKind::MacroDef(..) => DefPathData::MacroDef(i.ident.name.as_interned_str()),
            ItemKind::Mac(..) => return self.visit_macro_invoc(i.id, false),
            ItemKind::GlobalAsm(..) => DefPathData::Misc,
            ItemKind::Use(..) => {
                return visit::walk_item(self, i);
            }
        };
        let def = self.create_def(i.id, def_data, ITEM_LIKE_SPACE, i.span);

        self.with_parent(def, |this| {
            match i.node {
                ItemKind::Enum(ref enum_definition, _) => {
                    for v in &enum_definition.variants {
                        let variant_def_index =
                            this.create_def(v.node.data.id(),
                                            DefPathData::EnumVariant(v.node.ident
                                                                      .name.as_interned_str()),
                                            REGULAR_SPACE,
                                            v.span);
                        this.with_parent(variant_def_index, |this| {
                            for (index, field) in v.node.data.fields().iter().enumerate() {
                                let name = field.ident.map(|ident| ident.name)
                                    .unwrap_or_else(|| Symbol::intern(&index.to_string()));
                                this.create_def(field.id,
                                                DefPathData::Field(name.as_interned_str()),
                                                REGULAR_SPACE,
                                                field.span);
                            }

                            if let Some(ref expr) = v.node.disr_expr {
                                this.visit_const_expr(expr);
                            }
                        });
                    }
                }
                ItemKind::Struct(ref struct_def, _) | ItemKind::Union(ref struct_def, _) => {
                    // If this is a tuple-like struct, register the constructor.
                    if !struct_def.is_struct() {
                        this.create_def(struct_def.id(),
                                        DefPathData::StructCtor,
                                        REGULAR_SPACE,
                                        i.span);
                    }

                    for (index, field) in struct_def.fields().iter().enumerate() {
                        let name = field.ident.map(|ident| ident.name)
                            .unwrap_or_else(|| Symbol::intern(&index.to_string()));
                        this.create_def(field.id,
                                        DefPathData::Field(name.as_interned_str()),
                                        REGULAR_SPACE,
                                        field.span);
                    }
                }
                _ => {}
            }
            visit::walk_item(this, i);
        });
    }

    fn visit_use_tree(&mut self, use_tree: &'a UseTree, id: NodeId, _nested: bool) {
        self.create_def(id, DefPathData::Misc, ITEM_LIKE_SPACE, use_tree.span);
        visit::walk_use_tree(self, use_tree, id);
    }

    fn visit_foreign_item(&mut self, foreign_item: &'a ForeignItem) {
        if let ForeignItemKind::Macro(_) = foreign_item.node {
            return self.visit_macro_invoc(foreign_item.id, false);
        }

        let def = self.create_def(foreign_item.id,
                                  DefPathData::ValueNs(foreign_item.ident.name.as_interned_str()),
                                  REGULAR_SPACE,
                                  foreign_item.span);

        self.with_parent(def, |this| {
            visit::walk_foreign_item(this, foreign_item);
        });
    }

    fn visit_generic_param(&mut self, param: &'a GenericParam) {
        match *param {
            GenericParam::Lifetime(ref lifetime_def) => {
                self.create_def(
                    lifetime_def.lifetime.id,
                    DefPathData::LifetimeDef(lifetime_def.lifetime.ident.name.as_interned_str()),
                    REGULAR_SPACE,
                    lifetime_def.lifetime.ident.span
                );
            }
            GenericParam::Type(ref ty_param) => {
                self.create_def(
                    ty_param.id,
                    DefPathData::TypeParam(ty_param.ident.name.as_interned_str()),
                    REGULAR_SPACE,
                    ty_param.ident.span
                );
            }
        }

        visit::walk_generic_param(self, param);
    }

    fn visit_trait_item(&mut self, ti: &'a TraitItem) {
        let def_data = match ti.node {
            TraitItemKind::Method(..) | TraitItemKind::Const(..) =>
                DefPathData::ValueNs(ti.ident.name.as_interned_str()),
            TraitItemKind::Type(..) => {
                DefPathData::AssocTypeInTrait(ti.ident.name.as_interned_str())
            },
            TraitItemKind::Macro(..) => return self.visit_macro_invoc(ti.id, false),
        };

        let def = self.create_def(ti.id, def_data, ITEM_LIKE_SPACE, ti.span);
        self.with_parent(def, |this| visit::walk_trait_item(this, ti));
    }

    fn visit_impl_item(&mut self, ii: &'a ImplItem) {
        let def_data = match ii.node {
            ImplItemKind::Method(..) | ImplItemKind::Const(..) =>
                DefPathData::ValueNs(ii.ident.name.as_interned_str()),
            ImplItemKind::Type(..) => DefPathData::AssocTypeInImpl(ii.ident.name.as_interned_str()),
            ImplItemKind::Macro(..) => return self.visit_macro_invoc(ii.id, false),
        };

        let def = self.create_def(ii.id, def_data, ITEM_LIKE_SPACE, ii.span);
        self.with_parent(def, |this| visit::walk_impl_item(this, ii));
    }

    fn visit_pat(&mut self, pat: &'a Pat) {
        match pat.node {
            PatKind::Mac(..) => return self.visit_macro_invoc(pat.id, false),
            _ => visit::walk_pat(self, pat),
        }
    }

    fn visit_expr(&mut self, expr: &'a Expr) {
        let parent_def = self.parent_def;

        match expr.node {
            ExprKind::Mac(..) => return self.visit_macro_invoc(expr.id, false),
            ExprKind::Repeat(_, ref count) => self.visit_const_expr(count),
            ExprKind::Closure(..) => {
                let def = self.create_def(expr.id,
                                          DefPathData::ClosureExpr,
                                          REGULAR_SPACE,
                                          expr.span);
                self.parent_def = Some(def);
            }
            _ => {}
        }

        visit::walk_expr(self, expr);
        self.parent_def = parent_def;
    }

    fn visit_ty(&mut self, ty: &'a Ty) {
        match ty.node {
            TyKind::Mac(..) => return self.visit_macro_invoc(ty.id, false),
            TyKind::Array(_, ref length) => self.visit_const_expr(length),
            TyKind::ImplTrait(..) => {
                self.create_def(ty.id, DefPathData::ImplTrait, REGULAR_SPACE, ty.span);
            }
            TyKind::Typeof(ref expr) => self.visit_const_expr(expr),
            _ => {}
        }
        visit::walk_ty(self, ty);
    }

    fn visit_stmt(&mut self, stmt: &'a Stmt) {
        match stmt.node {
            StmtKind::Mac(..) => self.visit_macro_invoc(stmt.id, false),
            _ => visit::walk_stmt(self, stmt),
        }
    }

    fn visit_token(&mut self, t: Token) {
        if let Token::Interpolated(nt) = t {
            match nt.0 {
                token::NtExpr(ref expr) => {
                    if let ExprKind::Mac(..) = expr.node {
                        self.visit_macro_invoc(expr.id, false);
                    }
                }
                _ => {}
            }
        }
    }
}
<|endoftext|>


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

/// For all the linkers we support, and information they might
/// need out of the shared crate context before we get rid of it.

use rustc::session::{Session, config};
use rustc::session::search_paths::PathKind;
use rustc::middle::dependency_format::Linkage;
use rustc::middle::cstore::LibSource;
use rustc_target::spec::LinkerFlavor;
use rustc::hir::def_id::CrateNum;

use super::command::Command;
use CrateInfo;

use cc::windows_registry;
use std::fs;
use std::path::{Path, PathBuf};
use std::env;

pub fn remove(sess: &Session, path: &Path) {
    if let Err(e) = fs::remove_file(path) {
        sess.err(&format!("failed to remove {}: {}",
                          path.display(),
                          e));
    }
}

// The third parameter is for env vars, used on windows to set up the
// path for MSVC to find its DLLs, and gcc to find its bundled
// toolchain
pub fn get_linker(sess: &Session, linker: &Path, flavor: LinkerFlavor) -> (PathBuf, Command) {
    let msvc_tool = windows_registry::find_tool(&sess.opts.target_triple.triple(), "link.exe");

    // If our linker looks like a batch script on Windows then to execute this
    // we'll need to spawn `cmd` explicitly. This is primarily done to handle
    // emscripten where the linker is `emcc.bat` and needs to be spawned as
    // `cmd /c emcc.bat ...`.
    //
    // This worked historically but is needed manually since #42436 (regression
    // was tagged as #42791) and some more info can be found on #44443 for
    // emscripten itself.
    let mut cmd = match linker.to_str() {
        Some(linker) if cfg!(windows) && linker.ends_with(".bat") => Command::bat_script(linker),
        _ => match flavor {
            LinkerFlavor::Lld(f) => Command::lld(linker, f),
            LinkerFlavor::Msvc
                if sess.opts.cg.linker.is_none() && sess.target.target.options.linker.is_none() =>
            {
                Command::new(msvc_tool.as_ref().map(|t| t.path()).unwrap_or(linker))
            },
            _ => Command::new(linker),
        }
    };

    // The compiler's sysroot often has some bundled tools, so add it to the
    // PATH for the child.
    let mut new_path = sess.host_filesearch(PathKind::All)
                           .get_tools_search_paths();
    let mut msvc_changed_path = false;
    if sess.target.target.options.is_like_msvc {
        if let Some(ref tool) = msvc_tool {
            cmd.args(tool.args());
            for &(ref k, ref v) in tool.env() {
                if k == "PATH" {
                    new_path.extend(env::split_paths(v));
                    msvc_changed_path = true;
                } else {
                    cmd.env(k, v);
                }
            }
        }
    }

    if !msvc_changed_path {
        if let Some(path) = env::var_os("PATH") {
            new_path.extend(env::split_paths(&path));
        }
    }
    cmd.env("PATH", env::join_paths(new_path).unwrap());

    (linker.to_path_buf(), cmd)
}

pub fn each_linked_rlib(sess: &Session,
                               info: &CrateInfo,
                               f: &mut dyn FnMut(CrateNum, &Path)) -> Result<(), String> {
    let crates = info.used_crates_static.iter();
    let fmts = sess.dependency_formats.borrow();
    let fmts = fmts.get(&config::CrateType::Executable)
                   .or_else(|| fmts.get(&config::CrateType::Staticlib))
                   .or_else(|| fmts.get(&config::CrateType::Cdylib))
                   .or_else(|| fmts.get(&config::CrateType::ProcMacro));
    let fmts = match fmts {
        Some(f) => f,
        None => return Err("could not find formats for rlibs".to_string())
    };
    for &(cnum, ref path) in crates {
        match fmts.get(cnum.as_usize() - 1) {
            Some(&Linkage::NotLinked) |
            Some(&Linkage::IncludedFromDylib) => continue,
            Some(_) => {}
            None => return Err("could not find formats for rlibs".to_string())
        }
        let name = &info.crate_name[&cnum];
        let path = match *path {
            LibSource::Some(ref p) => p,
            LibSource::MetadataOnly => {
                return Err(format!("could not find rlib for: `{}`, found rmeta (metadata) file",
                                   name))
            }
            LibSource::None => {
                return Err(format!("could not find rlib for: `{}`", name))
            }
        };
        f(cnum, &path);
    }
    Ok(())
}

/// Returns a boolean indicating whether the specified crate should be ignored
/// during LTO.
///
/// Crates ignored during LTO are not lumped together in the "massive object
/// file" that we create and are linked in their normal rlib states. See
/// comments below for what crates do not participate in LTO.
///
/// It's unusual for a crate to not participate in LTO. Typically only
/// compiler-specific and unstable crates have a reason to not participate in
/// LTO.
pub fn ignored_for_lto(sess: &Session, info: &CrateInfo, cnum: CrateNum) -> bool {
    // If our target enables builtin function lowering in LLVM then the
    // crates providing these functions don't participate in LTO (e.g.
    // no_builtins or compiler builtins crates).
    !sess.target.target.options.no_builtins &&
        (info.compiler_builtins == Some(cnum) || info.is_no_builtins.contains(&cnum))
}

pub fn linker_and_flavor(sess: &Session) -> (PathBuf, LinkerFlavor) {
    fn infer_from(
        sess: &Session,
        linker: Option<PathBuf>,
        flavor: Option<LinkerFlavor>,
    ) -> Option<(PathBuf, LinkerFlavor)> {
        match (linker, flavor) {
            (Some(linker), Some(flavor)) => Some((linker, flavor)),
            // only the linker flavor is known; use the default linker for the selected flavor
            (None, Some(flavor)) => Some((PathBuf::from(match flavor {
                LinkerFlavor::Em  => if cfg!(windows) { "emcc.bat" } else { "emcc" },
                LinkerFlavor::Gcc => "cc",
                LinkerFlavor::Ld => "ld",
                LinkerFlavor::Msvc => "link.exe",
                LinkerFlavor::Lld(_) => "lld",
            }), flavor)),
            (Some(linker), None) => {
                let stem = linker.file_stem().and_then(|stem| stem.to_str()).unwrap_or_else(|| {
                    sess.fatal("couldn't extract file stem from specified linker");
                }).to_owned();

                let flavor = if stem == "emcc" {
                    LinkerFlavor::Em
                } else if stem == "gcc" || stem.ends_with("-gcc") {
                    LinkerFlavor::Gcc
                } else if stem == "ld" || stem == "ld.lld" || stem.ends_with("-ld") {
                    LinkerFlavor::Ld
                } else if stem == "link" || stem == "lld-link" {
                    LinkerFlavor::Msvc
                } else if stem == "lld" || stem == "rust-lld" {
                    LinkerFlavor::Lld(sess.target.target.options.lld_flavor)
                } else {
                    // fall back to the value in the target spec
                    sess.target.target.linker_flavor
                };

                Some((linker, flavor))
            },
            (None, None) => None,
        }
    }

    // linker and linker flavor specified via command line have precedence over what the target
    // specification specifies
    if let Some(ret) = infer_from(
        sess,
        sess.opts.cg.linker.clone(),
        sess.opts.debugging_opts.linker_flavor,
    ) {
        return ret;
    }

    if let Some(ret) = infer_from(
        sess,
        sess.target.target.options.linker.clone().map(PathBuf::from),
        Some(sess.target.target.linker_flavor),
    ) {
        return ret;
    }

    bug!("Not enough information provided to determine how to invoke the linker");
}
<commit_msg>Only consider stem when extension is exe.<commit_after>// Copyright 2018 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.

/// For all the linkers we support, and information they might
/// need out of the shared crate context before we get rid of it.

use rustc::session::{Session, config};
use rustc::session::search_paths::PathKind;
use rustc::middle::dependency_format::Linkage;
use rustc::middle::cstore::LibSource;
use rustc_target::spec::LinkerFlavor;
use rustc::hir::def_id::CrateNum;

use super::command::Command;
use CrateInfo;

use cc::windows_registry;
use std::fs;
use std::path::{Path, PathBuf};
use std::env;

pub fn remove(sess: &Session, path: &Path) {
    if let Err(e) = fs::remove_file(path) {
        sess.err(&format!("failed to remove {}: {}",
                          path.display(),
                          e));
    }
}

// The third parameter is for env vars, used on windows to set up the
// path for MSVC to find its DLLs, and gcc to find its bundled
// toolchain
pub fn get_linker(sess: &Session, linker: &Path, flavor: LinkerFlavor) -> (PathBuf, Command) {
    let msvc_tool = windows_registry::find_tool(&sess.opts.target_triple.triple(), "link.exe");

    // If our linker looks like a batch script on Windows then to execute this
    // we'll need to spawn `cmd` explicitly. This is primarily done to handle
    // emscripten where the linker is `emcc.bat` and needs to be spawned as
    // `cmd /c emcc.bat ...`.
    //
    // This worked historically but is needed manually since #42436 (regression
    // was tagged as #42791) and some more info can be found on #44443 for
    // emscripten itself.
    let mut cmd = match linker.to_str() {
        Some(linker) if cfg!(windows) && linker.ends_with(".bat") => Command::bat_script(linker),
        _ => match flavor {
            LinkerFlavor::Lld(f) => Command::lld(linker, f),
            LinkerFlavor::Msvc
                if sess.opts.cg.linker.is_none() && sess.target.target.options.linker.is_none() =>
            {
                Command::new(msvc_tool.as_ref().map(|t| t.path()).unwrap_or(linker))
            },
            _ => Command::new(linker),
        }
    };

    // The compiler's sysroot often has some bundled tools, so add it to the
    // PATH for the child.
    let mut new_path = sess.host_filesearch(PathKind::All)
                           .get_tools_search_paths();
    let mut msvc_changed_path = false;
    if sess.target.target.options.is_like_msvc {
        if let Some(ref tool) = msvc_tool {
            cmd.args(tool.args());
            for &(ref k, ref v) in tool.env() {
                if k == "PATH" {
                    new_path.extend(env::split_paths(v));
                    msvc_changed_path = true;
                } else {
                    cmd.env(k, v);
                }
            }
        }
    }

    if !msvc_changed_path {
        if let Some(path) = env::var_os("PATH") {
            new_path.extend(env::split_paths(&path));
        }
    }
    cmd.env("PATH", env::join_paths(new_path).unwrap());

    (linker.to_path_buf(), cmd)
}

pub fn each_linked_rlib(sess: &Session,
                               info: &CrateInfo,
                               f: &mut dyn FnMut(CrateNum, &Path)) -> Result<(), String> {
    let crates = info.used_crates_static.iter();
    let fmts = sess.dependency_formats.borrow();
    let fmts = fmts.get(&config::CrateType::Executable)
                   .or_else(|| fmts.get(&config::CrateType::Staticlib))
                   .or_else(|| fmts.get(&config::CrateType::Cdylib))
                   .or_else(|| fmts.get(&config::CrateType::ProcMacro));
    let fmts = match fmts {
        Some(f) => f,
        None => return Err("could not find formats for rlibs".to_string())
    };
    for &(cnum, ref path) in crates {
        match fmts.get(cnum.as_usize() - 1) {
            Some(&Linkage::NotLinked) |
            Some(&Linkage::IncludedFromDylib) => continue,
            Some(_) => {}
            None => return Err("could not find formats for rlibs".to_string())
        }
        let name = &info.crate_name[&cnum];
        let path = match *path {
            LibSource::Some(ref p) => p,
            LibSource::MetadataOnly => {
                return Err(format!("could not find rlib for: `{}`, found rmeta (metadata) file",
                                   name))
            }
            LibSource::None => {
                return Err(format!("could not find rlib for: `{}`", name))
            }
        };
        f(cnum, &path);
    }
    Ok(())
}

/// Returns a boolean indicating whether the specified crate should be ignored
/// during LTO.
///
/// Crates ignored during LTO are not lumped together in the "massive object
/// file" that we create and are linked in their normal rlib states. See
/// comments below for what crates do not participate in LTO.
///
/// It's unusual for a crate to not participate in LTO. Typically only
/// compiler-specific and unstable crates have a reason to not participate in
/// LTO.
pub fn ignored_for_lto(sess: &Session, info: &CrateInfo, cnum: CrateNum) -> bool {
    // If our target enables builtin function lowering in LLVM then the
    // crates providing these functions don't participate in LTO (e.g.
    // no_builtins or compiler builtins crates).
    !sess.target.target.options.no_builtins &&
        (info.compiler_builtins == Some(cnum) || info.is_no_builtins.contains(&cnum))
}

pub fn linker_and_flavor(sess: &Session) -> (PathBuf, LinkerFlavor) {
    fn infer_from(
        sess: &Session,
        linker: Option<PathBuf>,
        flavor: Option<LinkerFlavor>,
    ) -> Option<(PathBuf, LinkerFlavor)> {
        match (linker, flavor) {
            (Some(linker), Some(flavor)) => Some((linker, flavor)),
            // only the linker flavor is known; use the default linker for the selected flavor
            (None, Some(flavor)) => Some((PathBuf::from(match flavor {
                LinkerFlavor::Em  => if cfg!(windows) { "emcc.bat" } else { "emcc" },
                LinkerFlavor::Gcc => "cc",
                LinkerFlavor::Ld => "ld",
                LinkerFlavor::Msvc => "link.exe",
                LinkerFlavor::Lld(_) => "lld",
            }), flavor)),
            (Some(linker), None) => {
                let stem = if linker.extension().and_then(|ext| ext.to_str()) == Some("exe") {
                    linker.file_stem().and_then(|stem| stem.to_str())
                } else {
                    linker.to_str()
                }.unwrap_or_else(|| {
                    sess.fatal("couldn't extract file stem from specified linker");
                }).to_owned();

                let flavor = if stem == "emcc" {
                    LinkerFlavor::Em
                } else if stem == "gcc" || stem.ends_with("-gcc") {
                    LinkerFlavor::Gcc
                } else if stem == "ld" || stem == "ld.lld" || stem.ends_with("-ld") {
                    LinkerFlavor::Ld
                } else if stem == "link" || stem == "lld-link" {
                    LinkerFlavor::Msvc
                } else if stem == "lld" || stem == "rust-lld" {
                    LinkerFlavor::Lld(sess.target.target.options.lld_flavor)
                } else {
                    // fall back to the value in the target spec
                    sess.target.target.linker_flavor
                };

                Some((linker, flavor))
            },
            (None, None) => None,
        }
    }

    // linker and linker flavor specified via command line have precedence over what the target
    // specification specifies
    if let Some(ret) = infer_from(
        sess,
        sess.opts.cg.linker.clone(),
        sess.opts.debugging_opts.linker_flavor,
    ) {
        return ret;
    }

    if let Some(ret) = infer_from(
        sess,
        sess.target.target.options.linker.clone().map(PathBuf::from),
        Some(sess.target.target.linker_flavor),
    ) {
        return ret;
    }

    bug!("Not enough information provided to determine how to invoke the linker");
}
<|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 self::infer::InferenceContext;
use rustc::ty::TypeFoldable;
use rustc::ty::subst::{Kind, Substs};
use rustc::ty::{Ty, TyCtxt, ClosureSubsts, RegionVid, RegionKind};
use rustc::mir::{Mir, Location, Rvalue, BasicBlock, Statement, StatementKind};
use rustc::mir::visit::{MutVisitor, Lookup};
use rustc::mir::transform::{MirPass, MirSource};
use rustc::infer::{self as rustc_infer, InferCtxt};
use rustc::util::nodemap::FxHashSet;
use rustc_data_structures::indexed_vec::{IndexVec, Idx};
use syntax_pos::DUMMY_SP;
use std::collections::HashMap;
use std::fmt;

use util as mir_util;
use self::mir_util::PassWhere;

mod infer;

#[allow(dead_code)]
struct NLLVisitor<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
    lookup_map: HashMap<RegionVid, Lookup>,
    regions: IndexVec<RegionIndex, Region>,
    infcx: InferCtxt<'a, 'gcx, 'tcx>,
}

impl<'a, 'gcx, 'tcx> NLLVisitor<'a, 'gcx, 'tcx> {
    pub fn new(infcx: InferCtxt<'a, 'gcx, 'tcx>) -> Self {
        NLLVisitor {
            infcx,
            lookup_map: HashMap::new(),
            regions: IndexVec::new(),
        }
    }

    pub fn into_results(self) -> (HashMap<RegionVid, Lookup>, IndexVec<RegionIndex, Region>) {
        (self.lookup_map, self.regions)
    }

    fn renumber_regions<T>(&mut self, value: &T) -> T where T: TypeFoldable<'tcx> {
        self.infcx.tcx.fold_regions(value, &mut false, |_region, _depth| {
            self.regions.push(Region::default());
            self.infcx.next_region_var(rustc_infer::MiscVariable(DUMMY_SP))
        })
    }

    fn store_region(&mut self, region: &RegionKind, lookup: Lookup) {
        if let RegionKind::ReVar(rid) = *region {
            self.lookup_map.entry(rid).or_insert(lookup);
        }
    }

    fn store_ty_regions(&mut self, ty: &Ty<'tcx>, lookup: Lookup) {
        for region in ty.regions() {
            self.store_region(region, lookup);
        }
    }

    fn store_kind_regions(&mut self, kind: &'tcx Kind, lookup: Lookup) {
        if let Some(ty) = kind.as_type() {
            self.store_ty_regions(&ty, lookup);
        } else if let Some(region) = kind.as_region() {
            self.store_region(region, lookup);
        }
    }
}

impl<'a, 'gcx, 'tcx> MutVisitor<'tcx> for NLLVisitor<'a, 'gcx, 'tcx> {
    fn visit_ty(&mut self, ty: &mut Ty<'tcx>, lookup: Lookup) {
        let old_ty = *ty;
        *ty = self.renumber_regions(&old_ty);
        self.store_ty_regions(ty, lookup);
    }

    fn visit_substs(&mut self, substs: &mut &'tcx Substs<'tcx>, location: Location) {
        *substs = self.renumber_regions(&{*substs});
        let lookup = Lookup::Loc(location);
        for kind in *substs {
            self.store_kind_regions(kind, lookup);
        }
    }

    fn visit_rvalue(&mut self, rvalue: &mut Rvalue<'tcx>, location: Location) {
        match *rvalue {
            Rvalue::Ref(ref mut r, _, _) => {
                let old_r = *r;
                *r = self.renumber_regions(&old_r);
                let lookup = Lookup::Loc(location);
                self.store_region(r, lookup);
            }
            Rvalue::Use(..) |
            Rvalue::Repeat(..) |
            Rvalue::Len(..) |
            Rvalue::Cast(..) |
            Rvalue::BinaryOp(..) |
            Rvalue::CheckedBinaryOp(..) |
            Rvalue::UnaryOp(..) |
            Rvalue::Discriminant(..) |
            Rvalue::NullaryOp(..) |
            Rvalue::Aggregate(..) => {
                // These variants don't contain regions.
            }
        }
        self.super_rvalue(rvalue, location);
    }

    fn visit_closure_substs(&mut self,
                            substs: &mut ClosureSubsts<'tcx>,
                            location: Location) {
        *substs = self.renumber_regions(substs);
        let lookup = Lookup::Loc(location);
        for kind in substs.substs {
            self.store_kind_regions(kind, lookup);
        }
    }

    fn visit_statement(&mut self,
                       block: BasicBlock,
                       statement: &mut Statement<'tcx>,
                       location: Location) {
        if let StatementKind::EndRegion(_) = statement.kind {
            statement.kind = StatementKind::Nop;
        }
        self.super_statement(block, statement, location);
    }
}

// MIR Pass for non-lexical lifetimes
pub struct NLL;

impl MirPass for NLL {
    fn run_pass<'a, 'tcx>(&self,
                          tcx: TyCtxt<'a, 'tcx, 'tcx>,
                          source: MirSource,
                          mir: &mut Mir<'tcx>) {
        if !tcx.sess.opts.debugging_opts.nll {
            return;
        }

        tcx.infer_ctxt().enter(|infcx| {
            // Clone mir so we can mutate it without disturbing the rest of the compiler
            let mut renumbered_mir = mir.clone();
            let mut visitor = NLLVisitor::new(infcx);
            visitor.visit_mir(&mut renumbered_mir);
            mir_util::dump_mir(tcx, None, "nll", &0, source, mir, |pass_where, out| {
                if let PassWhere::BeforeCFG = pass_where {
                    for (index, value) in visitor.regions.iter_enumerated() {
                        writeln!(out, "// R{:03}: {:?}", index.0, value)?;
                    }
                }
                Ok(())
            });
            let (_lookup_map, regions) = visitor.into_results();
            let inference_context = InferenceContext::new(regions);
            inference_context.solve(infcx, &renumbered_mir);
        })
    }
}

#[derive(Clone, Default, PartialEq, Eq)]
pub struct Region {
    points: FxHashSet<Location>,
}

impl fmt::Debug for Region {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        write!(formatter, "{:?}", self.points)
    }
}

impl Region {
    pub fn add_point(&mut self, point: Location) -> bool {
        self.points.insert(point)
    }

    pub fn may_contain(&self, point: Location) -> bool {
        self.points.contains(&point)
    }
}

newtype_index!(RegionIndex);
<commit_msg>inteference_context should be mut<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 self::infer::InferenceContext;
use rustc::ty::TypeFoldable;
use rustc::ty::subst::{Kind, Substs};
use rustc::ty::{Ty, TyCtxt, ClosureSubsts, RegionVid, RegionKind};
use rustc::mir::{Mir, Location, Rvalue, BasicBlock, Statement, StatementKind};
use rustc::mir::visit::{MutVisitor, Lookup};
use rustc::mir::transform::{MirPass, MirSource};
use rustc::infer::{self as rustc_infer, InferCtxt};
use rustc::util::nodemap::FxHashSet;
use rustc_data_structures::indexed_vec::{IndexVec, Idx};
use syntax_pos::DUMMY_SP;
use std::collections::HashMap;
use std::fmt;

use util as mir_util;
use self::mir_util::PassWhere;

mod infer;

#[allow(dead_code)]
struct NLLVisitor<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
    lookup_map: HashMap<RegionVid, Lookup>,
    regions: IndexVec<RegionIndex, Region>,
    infcx: InferCtxt<'a, 'gcx, 'tcx>,
}

impl<'a, 'gcx, 'tcx> NLLVisitor<'a, 'gcx, 'tcx> {
    pub fn new(infcx: InferCtxt<'a, 'gcx, 'tcx>) -> Self {
        NLLVisitor {
            infcx,
            lookup_map: HashMap::new(),
            regions: IndexVec::new(),
        }
    }

    pub fn into_results(self) -> (HashMap<RegionVid, Lookup>, IndexVec<RegionIndex, Region>) {
        (self.lookup_map, self.regions)
    }

    fn renumber_regions<T>(&mut self, value: &T) -> T where T: TypeFoldable<'tcx> {
        self.infcx.tcx.fold_regions(value, &mut false, |_region, _depth| {
            self.regions.push(Region::default());
            self.infcx.next_region_var(rustc_infer::MiscVariable(DUMMY_SP))
        })
    }

    fn store_region(&mut self, region: &RegionKind, lookup: Lookup) {
        if let RegionKind::ReVar(rid) = *region {
            self.lookup_map.entry(rid).or_insert(lookup);
        }
    }

    fn store_ty_regions(&mut self, ty: &Ty<'tcx>, lookup: Lookup) {
        for region in ty.regions() {
            self.store_region(region, lookup);
        }
    }

    fn store_kind_regions(&mut self, kind: &'tcx Kind, lookup: Lookup) {
        if let Some(ty) = kind.as_type() {
            self.store_ty_regions(&ty, lookup);
        } else if let Some(region) = kind.as_region() {
            self.store_region(region, lookup);
        }
    }
}

impl<'a, 'gcx, 'tcx> MutVisitor<'tcx> for NLLVisitor<'a, 'gcx, 'tcx> {
    fn visit_ty(&mut self, ty: &mut Ty<'tcx>, lookup: Lookup) {
        let old_ty = *ty;
        *ty = self.renumber_regions(&old_ty);
        self.store_ty_regions(ty, lookup);
    }

    fn visit_substs(&mut self, substs: &mut &'tcx Substs<'tcx>, location: Location) {
        *substs = self.renumber_regions(&{*substs});
        let lookup = Lookup::Loc(location);
        for kind in *substs {
            self.store_kind_regions(kind, lookup);
        }
    }

    fn visit_rvalue(&mut self, rvalue: &mut Rvalue<'tcx>, location: Location) {
        match *rvalue {
            Rvalue::Ref(ref mut r, _, _) => {
                let old_r = *r;
                *r = self.renumber_regions(&old_r);
                let lookup = Lookup::Loc(location);
                self.store_region(r, lookup);
            }
            Rvalue::Use(..) |
            Rvalue::Repeat(..) |
            Rvalue::Len(..) |
            Rvalue::Cast(..) |
            Rvalue::BinaryOp(..) |
            Rvalue::CheckedBinaryOp(..) |
            Rvalue::UnaryOp(..) |
            Rvalue::Discriminant(..) |
            Rvalue::NullaryOp(..) |
            Rvalue::Aggregate(..) => {
                // These variants don't contain regions.
            }
        }
        self.super_rvalue(rvalue, location);
    }

    fn visit_closure_substs(&mut self,
                            substs: &mut ClosureSubsts<'tcx>,
                            location: Location) {
        *substs = self.renumber_regions(substs);
        let lookup = Lookup::Loc(location);
        for kind in substs.substs {
            self.store_kind_regions(kind, lookup);
        }
    }

    fn visit_statement(&mut self,
                       block: BasicBlock,
                       statement: &mut Statement<'tcx>,
                       location: Location) {
        if let StatementKind::EndRegion(_) = statement.kind {
            statement.kind = StatementKind::Nop;
        }
        self.super_statement(block, statement, location);
    }
}

// MIR Pass for non-lexical lifetimes
pub struct NLL;

impl MirPass for NLL {
    fn run_pass<'a, 'tcx>(&self,
                          tcx: TyCtxt<'a, 'tcx, 'tcx>,
                          source: MirSource,
                          mir: &mut Mir<'tcx>) {
        if !tcx.sess.opts.debugging_opts.nll {
            return;
        }

        tcx.infer_ctxt().enter(|infcx| {
            // Clone mir so we can mutate it without disturbing the rest of the compiler
            let mut renumbered_mir = mir.clone();
            let mut visitor = NLLVisitor::new(infcx);
            visitor.visit_mir(&mut renumbered_mir);
            mir_util::dump_mir(tcx, None, "nll", &0, source, mir, |pass_where, out| {
                if let PassWhere::BeforeCFG = pass_where {
                    for (index, value) in visitor.regions.iter_enumerated() {
                        writeln!(out, "// R{:03}: {:?}", index.0, value)?;
                    }
                }
                Ok(())
            });
            let (_lookup_map, regions) = visitor.into_results();
            let mut inference_context = InferenceContext::new(regions);
            inference_context.solve(infcx, &renumbered_mir);
        })
    }
}

#[derive(Clone, Default, PartialEq, Eq)]
pub struct Region {
    points: FxHashSet<Location>,
}

impl fmt::Debug for Region {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        write!(formatter, "{:?}", self.points)
    }
}

impl Region {
    pub fn add_point(&mut self, point: Location) -> bool {
        self.points.insert(point)
    }

    pub fn may_contain(&self, point: Location) -> bool {
        self.points.contains(&point)
    }
}

newtype_index!(RegionIndex);
<|endoftext|>


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

// error-pattern:failed to resolve imports
use x = m::f;

mod m {
}

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

use x = m::f; //~ ERROR failed to resolve imports

mod m {
}

fn main() {
}
<|endoftext|>


<commit_before><commit_msg>Add serialization impl's for `response::Frame`<commit_after><|endoftext|>


<commit_before><commit_msg>Fix the comments for libsyntax::parse::parser::parse_sugary_call_expr<commit_after><|endoftext|>


<commit_before><commit_msg>Hello Rust!<commit_after>fn main()
{
  println!("Hello World");
}<|endoftext|>


<commit_before><commit_msg>Add arc ball from kiss3d 49b47206dbe602be319ac9c31c41c70adccf0463<commit_after>use std::f32;
use glfw::{Key, Action, MouseButton};
use glfw;
use glfw::WindowEvent;
use na::{Point3, Vector2, Vector3, Matrix4, Isometry3, Perspective3};
use na;
use camera::Camera;

/// Arc-ball camera mode.
///
/// An arc-ball camera is a camera rotating around a fixed point (the focus point) and always
/// looking at it. The following inputs are handled:
///
/// * Left button press + drag - rotates the camera around the focus point
/// * Right button press + drag - translates the focus point on the plane orthogonal to the view
/// direction
/// * Scroll in/out - zoom in/out
/// * Enter key - set the focus point to the origin
#[derive(Clone, Debug)]
pub struct ArcBall {
    /// The focus point.
    at:    Point3<f32>,
    /// Yaw of the camera (rotation along the y axis).
    yaw:   f32,
    /// Pitch of the camera (rotation along the x axis).
    pitch: f32,
    /// Distance from the camera to the `at` focus point.
    dist:  f32,

    /// Increment of the yaw per unit mouse movement. The default value is 0.005.
    yaw_step:   f32,
    /// Increment of the pitch per unit mouse movement. The default value is 0.005.
    pitch_step: f32,
    /// Increment of the distance per unit scrolling. The default value is 40.0.
    dist_step:  f32,
    rotate_button: Option<MouseButton>,
    drag_button:   Option<MouseButton>,
    reset_key:     Option<Key>,

    projection:        Perspective3<f32>,
    proj_view:         Matrix4<f32>,
    inverse_proj_view: Matrix4<f32>,
    last_cursor_pos:   Vector2<f32>
}

impl ArcBall {
    /// Create a new arc-ball camera.
    pub fn new(eye: Point3<f32>, at: Point3<f32>) -> ArcBall {
        ArcBall::new_with_frustrum(f32::consts::PI / 4.0, 0.1, 1024.0, eye, at)
    }

    /// Creates a new arc ball camera with default sensitivity values.
    pub fn new_with_frustrum(fov:    f32,
                             znear:  f32,
                             zfar:   f32,
                             eye:    Point3<f32>,
                             at:     Point3<f32>) -> ArcBall {
        let mut res = ArcBall {
            at:              Point3::new(0.0, 0.0, 0.0),
            yaw:             0.0,
            pitch:           0.0,
            dist:            0.0,
            yaw_step:        0.005,
            pitch_step:      0.005,
            dist_step:       40.0,
            rotate_button:   Some(glfw::MouseButtonLeft),
            drag_button:     Some(glfw::MouseButtonRight),
            reset_key:       Some(Key::Enter),
            projection:      Perspective3::new(800.0 / 600.0, fov, znear, zfar),
            proj_view:       na::zero(),
            inverse_proj_view:   na::zero(),
            last_cursor_pos: na::zero()
        };

        res.look_at(eye, at);

        res
    }

    /// The point the arc-ball is looking at.
    pub fn at(&self) -> Point3<f32> {
        self.at
    }

    /// Get a mutable reference to the point the camera is looking at.
    pub fn set_at(&mut self, at: Point3<f32>) {
        self.at = at;
        self.update_projviews();
    }

    /// The arc-ball camera `yaw`.
    pub fn yaw(&self) -> f32 {
        self.yaw
    }

    /// Sets the camera `yaw`. Change this to modify the rotation along the `up` axis.
    pub fn set_yaw(&mut self, yaw: f32) {
        self.yaw = yaw;

        self.update_restrictions();
        self.update_projviews();
    }

    /// The arc-ball camera `pitch`.
    pub fn pitch(&self) -> f32 {
        self.pitch
    }

    /// Sets the camera `pitch`.
    pub fn set_pitch(&mut self, pitch: f32) {
        self.pitch = pitch;

        self.update_restrictions();
        self.update_projviews();
    }

    /// The distance from the camera position to its view point.
    pub fn dist(&self) -> f32 {
        self.dist
    }

    /// Move the camera such that it is at a given distance from the view point.
    pub fn set_dist(&mut self, dist: f32) {
        self.dist = dist;

        self.update_restrictions();
        self.update_projviews();
    }

    /// Move and orient the camera such that it looks at a specific point.
    pub fn look_at(&mut self, eye: Point3<f32>, at: Point3<f32>) {
        let dist  = na::norm(&(eye - at));
        let pitch = ((eye.y - at.y) / dist).acos();
        let yaw   = (eye.z - at.z).atan2(eye.x - at.x);

        self.at    = at;
        self.dist  = dist;
        self.yaw   = yaw;
        self.pitch = pitch;

        self.update_restrictions();
        self.update_projviews();
    }

    /// Transformation applied by the camera without perspective.
    fn update_restrictions(&mut self) {
        if self.dist < 0.00001 {
            self.dist = 0.00001
        }

        if self.pitch <= 0.01 {
            self.pitch = 0.01
        }

        let _pi: f32 = f32::consts::PI;
        if self.pitch > _pi - 0.01 {
            self.pitch = _pi - 0.01
        }
    }

    /// The button used to rotate the ArcBall camera.
    pub fn rotate_button(&self) -> Option<MouseButton> {
        self.rotate_button
    }

    /// Set the button used to rotate the ArcBall camera.
    /// Use None to disable rotation.
    pub fn rebind_rotate_button(&mut self, new_button: Option<MouseButton>) {
        self.rotate_button = new_button;
    }

    /// The button used to drag the ArcBall camera.
    pub fn drag_button(&self) -> Option<MouseButton> {
        self.drag_button
    }

    /// Set the button used to drag the ArcBall camera.
    /// Use None to disable dragging.
    pub fn rebind_drag_button(&mut self, new_button: Option<MouseButton>) {
        self.drag_button = new_button;
    }

    /// The key used to reset the ArcBall camera.
    pub fn reset_key(&self) -> Option<Key> {
        self.reset_key
    }

    /// Set the key used to reset the ArcBall camera.
    /// Use None to disable reset.
    pub fn rebind_reset_key(&mut self, new_key : Option<Key>) {
        self.reset_key = new_key;
    }

    fn handle_left_button_displacement(&mut self, dpos: &Vector2<f32>) {
        self.yaw   = self.yaw   + dpos.x * self.yaw_step;
        self.pitch = self.pitch - dpos.y * self.pitch_step;

        self.update_restrictions();
        self.update_projviews();
    }

    fn handle_right_button_displacement(&mut self, dpos: &Vector2<f32>) {
        let eye       = self.eye();
        let dir       = na::normalize(&(self.at - eye));
        let tangent   = na::normalize(&Vector3::y().cross(&dir));
        let bitangent = dir.cross(&tangent);
        let mult      = self.dist / 1000.0;

        self.at = self.at + tangent * (dpos.x * mult) + bitangent * (dpos.y * mult);
        self.update_projviews();
    }

    fn handle_scroll(&mut self, off: f32) {
        self.dist = self.dist + self.dist_step * (off) / 120.0;
        self.update_restrictions();
        self.update_projviews();
    }

    fn update_projviews(&mut self) {
        self.proj_view         = *self.projection.as_matrix() * self.view_transform().to_homogeneous();
        self.inverse_proj_view = self.proj_view.try_inverse().unwrap();
    }
}

impl Camera for ArcBall {
    fn clip_planes(&self) -> (f32, f32) {
        (self.projection.znear(), self.projection.zfar())
    }

    fn view_transform(&self) -> Isometry3<f32> {
        Isometry3::look_at_rh(&self.eye(), &self.at, &Vector3::y())
    }

    fn eye(&self) -> Point3<f32> {
        let px = self.at.x + self.dist * self.yaw.cos() * self.pitch.sin();
        let py = self.at.y + self.dist * self.pitch.cos();
        let pz = self.at.z + self.dist * self.yaw.sin() * self.pitch.sin();

        Point3::new(px, py, pz)
    }

    fn handle_event(&mut self, window: &glfw::Window, event: &WindowEvent) {
        match *event {
            WindowEvent::CursorPos(x, y) => {
                let curr_pos = Vector2::new(x as f32, y as f32);

                if let Some(rotate_button) = self.rotate_button {
                    if window.get_mouse_button(rotate_button) == Action::Press {
                        let dpos = curr_pos - self.last_cursor_pos;
                        self.handle_left_button_displacement(&dpos)
                    }
                }

                if let Some(drag_button) = self.drag_button {
                    if window.get_mouse_button(drag_button) == Action::Press {
                        let dpos = curr_pos - self.last_cursor_pos;
                        self.handle_right_button_displacement(&dpos)
                    }
                }

                self.last_cursor_pos = curr_pos;
            },
            WindowEvent::Key(key, _, Action::Press, _) if Some(key) == self.reset_key => {
                self.at = Point3::origin();
                self.update_projviews();
            },
            WindowEvent::Scroll(_, off) => self.handle_scroll(off as f32),
            WindowEvent::FramebufferSize(w, h) => {
                self.projection.set_aspect(w as f32 / h as f32);
                self.update_projviews();
            },
            _ => { }
        }
    }

    fn transformation(&self) -> Matrix4<f32> {
        self.proj_view
    }

    fn inverse_transformation(&self) -> Matrix4<f32> {
        self.inverse_proj_view
    }

    fn update(&mut self, _: &glfw::Window) { }
}
<|endoftext|>


<commit_before><commit_msg>Look for substring matches when looking for ATI or NVidia drivers<commit_after><|endoftext|>


<commit_before><commit_msg>CreateAppMenu after CreateWindowExW<commit_after><|endoftext|>


<commit_before><commit_msg>Add configurable rotation size.<commit_after><|endoftext|>


<commit_before>use file;
use playpen;
use std::io::{UserRWX,fs};

pub struct Markdown<'a> {
    id: &'a str,
    content: String,
}

impl<'a> Markdown<'a> {
    pub fn process(id: &'a str, title: &str) -> Result<Markdown<'a>, String> {
        let mut mkd = try!(Markdown::new(id, title));

        try!(mkd.insert_sources());
        try!(mkd.insert_outputs());
        try!(mkd.insert_playpen_links());
        try!(mkd.save());

        Ok(mkd)
    }

    fn new(id: &'a str, title: &str) -> Result<Markdown<'a>, String> {
        let p = Path::new(format!("examples/{}/input.md", id));
        let s = try!(file::read(&p));

        Ok(Markdown {
            id: id,
            content: format!("\\# {}\n\n{}", title, s),
        })
    }

    fn insert_sources(&mut self) -> Result<(), String> {
        let re = regex!(r"\{(.*\.rs)\}");

        let mut table = Vec::new();
        for line in self.content.as_slice().lines() {
            match re.captures(line) {
                None => {},
                Some(captures) => {
                    let src = captures.at(1);
                    let input = format!("\\{{}\\}", src);
                    let path = format!("examples/{}/{}", self.id, src);
                    let output = match file::read(&Path::new(path.as_slice())) {
                        Err(_) => {
                            return Err(format!("{} not found", path));
                        },
                        Ok(string) => {
                            format!("``` rust\n// {}\n{}```",
                                    captures.at(1), string)
                        }
                    };

                    table.push((input, output))
                }
            }
        }

        for (input, output) in table.move_iter() {
            self.content = self.content.replace(input.as_slice(),
                                                output.as_slice());
        }

        Ok(())
    }

    fn insert_outputs(&mut self) -> Result<(), String> {
        let r = regex!(r"\{(.*)\.out\}");

        let dir = Path::new(format!("stage/{}", self.id));

        match fs::mkdir(&dir, UserRWX) {
            Err(_) => {},
            Ok(_) => {},
        }

        let mut table = Vec::new();
        for line in self.content.as_slice().lines() {
            match r.captures(line) {
                None => {},
                Some(captures) => {
                    let src = captures.at(1);
                    let input = format!("\\{{}.out\\}", src);
                    let s = try!(file::run(self.id, src));
                    let s = format!("```\n$ rustc {0}.rs && ./{0}\n{1}```",
                                    src, s);

                    table.push((input, s));
                },
            }
        }

        for (input, output) in table.move_iter() {
            self.content = self.content.replace(input.as_slice(),
                                                output.as_slice());
        }

        match fs::rmdir(&dir) {
            Err(_) => Err(format!("couldn't remove {}", dir.display())),
            Ok(_) => Ok(()),
        }
    }

    fn insert_playpen_links(&mut self) -> Result<(), String> {
        let re = regex!(r"\{(.*)\.play\}");

        let mut table = Vec::new();
        for line in self.content.as_slice().lines() {
            match re.captures(line) {
                None => {},
                Some(captures) => {
                    let input = format!("\\{{}.play\\}", captures.at(1));
                    let src = format!("{}.rs", captures.at(1));
                    let path = format!("examples/{}/{}", self.id, src);
                    let output = match file::read(&Path::new(path.as_slice())) {
                        Err(_) => {
                            return Err(format!("{} not found", path));
                        },
                        Ok(source) => {
                            format!("([Try `{}` in the playpen!]({}))",
                                    src,
                                    playpen::link(source.as_slice()))
                        }
                    };

                    table.push((input, output))
                }
            }
        }

        for (input, output) in table.move_iter() {
            self.content = self.content.replace(input.as_slice(),
                                                output.as_slice());
        }

        Ok(())
    }

    fn save(&self) -> Result<(), String> {
        let path = Path::new(format!("stage/{}.md", self.id));

        file::write(&path, self.content.as_slice())
    }
}
<commit_msg>update.rs: keep line lengths below 80 chars<commit_after>use file;
use playpen;
use std::io::{UserRWX,fs};

pub struct Markdown<'a> {
    id: &'a str,
    content: String,
}

impl<'a> Markdown<'a> {
    pub fn process(id: &'a str, title: &str) -> Result<Markdown<'a>, String> {
        let mut mkd = try!(Markdown::new(id, title));

        try!(mkd.insert_sources());
        try!(mkd.insert_outputs());
        try!(mkd.insert_playpen_links());
        try!(mkd.save());

        Ok(mkd)
    }

    fn new(id: &'a str, title: &str) -> Result<Markdown<'a>, String> {
        let p = Path::new(format!("examples/{}/input.md", id));
        let s = try!(file::read(&p));

        Ok(Markdown {
            id: id,
            content: format!("\\# {}\n\n{}", title, s),
        })
    }

    fn insert_sources(&mut self) -> Result<(), String> {
        let re = regex!(r"\{(.*\.rs)\}");

        let mut table = Vec::new();
        for line in self.content.as_slice().lines() {
            match re.captures(line) {
                None => {},
                Some(captures) => {
                    let src = captures.at(1);
                    let input = format!("\\{{}\\}", src);
                    let p = format!("examples/{}/{}", self.id, src);
                    let output = match file::read(&Path::new(p.as_slice())) {
                        Err(_) => {
                            return Err(format!("{} not found", p));
                        },
                        Ok(string) => {
                            format!("``` rust\n// {}\n{}```",
                                    captures.at(1), string)
                        }
                    };

                    table.push((input, output))
                }
            }
        }

        for (input, output) in table.move_iter() {
            self.content = self.content.replace(input.as_slice(),
                                                output.as_slice());
        }

        Ok(())
    }

    fn insert_outputs(&mut self) -> Result<(), String> {
        let r = regex!(r"\{(.*)\.out\}");

        let dir = Path::new(format!("stage/{}", self.id));

        match fs::mkdir(&dir, UserRWX) {
            Err(_) => {},
            Ok(_) => {},
        }

        let mut table = Vec::new();
        for line in self.content.as_slice().lines() {
            match r.captures(line) {
                None => {},
                Some(captures) => {
                    let src = captures.at(1);
                    let input = format!("\\{{}.out\\}", src);
                    let s = try!(file::run(self.id, src));
                    let s = format!("```\n$ rustc {0}.rs && ./{0}\n{1}```",
                                    src, s);

                    table.push((input, s));
                },
            }
        }

        for (input, output) in table.move_iter() {
            self.content = self.content.replace(input.as_slice(),
                                                output.as_slice());
        }

        match fs::rmdir(&dir) {
            Err(_) => Err(format!("couldn't remove {}", dir.display())),
            Ok(_) => Ok(()),
        }
    }

    fn insert_playpen_links(&mut self) -> Result<(), String> {
        let re = regex!(r"\{(.*)\.play\}");

        let mut table = Vec::new();
        for line in self.content.as_slice().lines() {
            match re.captures(line) {
                None => {},
                Some(captures) => {
                    let input = format!("\\{{}.play\\}", captures.at(1));
                    let src = format!("{}.rs", captures.at(1));
                    let p = format!("examples/{}/{}", self.id, src);
                    let output = match file::read(&Path::new(p.as_slice())) {
                        Err(_) => {
                            return Err(format!("{} not found", p));
                        },
                        Ok(source) => {
                            format!("([Try `{}` in the playpen!]({}))",
                                    src,
                                    playpen::link(source.as_slice()))
                        }
                    };

                    table.push((input, output))
                }
            }
        }

        for (input, output) in table.move_iter() {
            self.content = self.content.replace(input.as_slice(),
                                                output.as_slice());
        }

        Ok(())
    }

    fn save(&self) -> Result<(), String> {
        let path = Path::new(format!("stage/{}.md", self.id));

        file::write(&path, self.content.as_slice())
    }
}
<|endoftext|>


<commit_before><commit_msg>add boot_delay utility<commit_after>#![feature(slice_position_elem)]
#![feature(duration)]
#![feature(thread_sleep)]

use std::fs::File;
use std::io::Read;
use std::mem::transmute;
use std::thread::sleep;
use std::time::Duration;
use std::env;

fn main() {
    let delay = match env::args().nth(1).and_then(|s| s.parse::<f32>().ok()) {
        Some(d) => 60.0 * d,
        None => {
            println!("Usage: boot_delay <minutes>");
            return;
        }
    };

    let mut buf = [0u8; 1024];
    let uptime = File::open("/proc/uptime")
        .and_then(|ref mut file| file.read(&mut buf))
        .map(|sz| {
            buf.position_elem(&0x20)
               .and_then(|p| if p < sz {
                   unsafe { transmute::<_, &str>(&buf[..p]) }.parse::<f32>().ok()
               } else {
                   None
               }).unwrap()
        })
        .unwrap();

    if delay > uptime {
        sleep(Duration::from_secs((delay - uptime) as u64));
    }
}
<|endoftext|>


<commit_before><commit_msg>Implement `Body::sized`<commit_after><|endoftext|>


<commit_before><commit_msg>Added GetInstrumentDataEx to startup / initialization.<commit_after><|endoftext|>


<commit_before><commit_msg>Writing out - 1st try<commit_after><|endoftext|>


<commit_before><commit_msg>dead code removal<commit_after><|endoftext|>


<commit_before><commit_msg>more random<commit_after><|endoftext|>


<commit_before><commit_msg>Added snappy encoding to reduce number of bytes sent over zeromq.<commit_after><|endoftext|>


<commit_before><commit_msg>Altered number of samples to fit within trigger period.<commit_after><|endoftext|>


<commit_before>#![cfg_attr(feature="lints", feature(plugin))]
#![cfg_attr(feature="lints", plugin(clippy))]

#[macro_use]
extern crate clap;
extern crate toml;
extern crate semver;
extern crate tempdir;
#[cfg(feature = "color")]
extern crate ansi_term;
extern crate tabwriter;

#[macro_use]
mod macros;
mod config;
mod lockfile;
mod deps;
mod error;
mod fmt;

use std::io::{Write, stdout};
#[cfg(feature="debug")]
use std::env;

use clap::{App, Arg, SubCommand, AppSettings};
use tabwriter::TabWriter;

use config::Config;
use lockfile::Lockfile;
use error::CliError;
use fmt::Format;

pub type CliResult<T> = Result<T, CliError>;

fn main() {
    debugln!("executing; cmd=cargo-outdated; args={:?}", env::args().collect::<Vec<_>>());
    let m = App::new("cargo-outdated")
        .author("Kevin K. <kbknapp@gmail.com>")
        .about("Displays information about project dependency versions")
        .version(&*format!("v{}", crate_version!()))
        // We have to lie about our binary name since this will be a third party
        // subcommand for cargo
        .bin_name("cargo")
        // Global version uses the version we supplied (Cargo.toml) for all subcommands as well
        .settings(&[AppSettings::GlobalVersion,
                    AppSettings::SubcommandRequired])
        // We use a subcommand because parsed after `cargo` is sent to the third party plugin
        // which will be interpreted as a subcommand/positional arg by clap
        .subcommand(SubCommand::with_name("outdated")
            .about("Displays information about project dependency versions")
            .args_from_usage("-p, --package [PKG]...    'Package to inspect for updates'
                              -v, --verbose             'Print verbose output'
                              -d, --depth [DEPTH]       'How deep in the dependency chain to search{n}\
                                                         (Defaults to all dependencies when omitted)'")
            // We separate -R so we can addd a conflicting argument
            .arg(Arg::from_usage("-R, --root-deps-only  'Only check root dependencies (Equivilant to --depth=1)'")
                .conflicts_with("DEPTH")))

        .get_matches();

    if let Some(m) = m.subcommand_matches("outdated") {
        let cfg = Config::from_matches(m);
        if let Err(e) = execute(cfg) {
            e.exit();
        }
    }
}

fn execute(cfg: Config) -> CliResult<()> {
    debugln!("executing; execute; cfg={:?}", cfg);

    verbose!(cfg, "Parsing {}...", Format::Warning("Cargo.lock"));
    let mut lf = try!(Lockfile::new());
    verboseln!(cfg, "{}", Format::Good("Done"));

    if let Ok(Some(res)) = lf.get_updates(&cfg) {
        println!("The following dependencies have newer versions available:\n");
        let mut tw = TabWriter::new(vec![]);
        write!(&mut tw, "\tName\tProject Ver\tSemVer Compat\tLatest Ver\n").unwrap();
        for (d_name, d) in res.iter() {
            write!(&mut tw, "\t{}\t   {}\t   {}\t  {}\n", d_name, d.project_ver, d.semver_ver.as_ref().unwrap_or(&String::from("  --  ")), d.latest_ver.as_ref().unwrap_or(&String::from("  --  "))).unwrap();
        }
        tw.flush().unwrap();
        write!(stdout(), "{}", String::from_utf8(tw.unwrap()).unwrap()).unwrap();
    } else {
        println!("All dependencies are up to date, yay!")
    }

    Ok(())
}

<commit_msg>wip: main.rs unwrap deletions<commit_after>#![cfg_attr(feature="lints", feature(plugin))]
#![cfg_attr(feature="lints", plugin(clippy))]

#[macro_use]
extern crate clap;
extern crate toml;
extern crate semver;
extern crate tempdir;
#[cfg(feature = "color")]
extern crate ansi_term;
extern crate tabwriter;

#[macro_use]
mod macros;
mod config;
mod lockfile;
mod deps;
mod error;
mod fmt;

use std::io::{Write, stdout};
#[cfg(feature="debug")]
use std::env;

use clap::{App, Arg, SubCommand, AppSettings};
use tabwriter::TabWriter;

use config::Config;
use lockfile::Lockfile;
use error::CliError;
use fmt::Format;

pub type CliResult<T> = Result<T, CliError>;

fn main() {
    debugln!("executing; cmd=cargo-outdated; args={:?}", env::args().collect::<Vec<_>>());
    let m = App::new("cargo-outdated")
        .author("Kevin K. <kbknapp@gmail.com>")
        .about("Displays information about project dependency versions")
        .version(&*format!("v{}", crate_version!()))
        // We have to lie about our binary name since this will be a third party
        // subcommand for cargo
        .bin_name("cargo")
        // Global version uses the version we supplied (Cargo.toml) for all subcommands as well
        .settings(&[AppSettings::GlobalVersion,
                    AppSettings::SubcommandRequired])
        // We use a subcommand because parsed after `cargo` is sent to the third party plugin
        // which will be interpreted as a subcommand/positional arg by clap
        .subcommand(SubCommand::with_name("outdated")
            .about("Displays information about project dependency versions")
            .args_from_usage("-p, --package [PKG]...    'Package to inspect for updates'
                              -v, --verbose             'Print verbose output'
                              -d, --depth [DEPTH]       'How deep in the dependency chain to search{n}\
                                                         (Defaults to all dependencies when omitted)'")
            // We separate -R so we can addd a conflicting argument
            .arg(Arg::from_usage("-R, --root-deps-only  'Only check root dependencies (Equivilant to --depth=1)'")
                .conflicts_with("DEPTH")))

        .get_matches();

    if let Some(m) = m.subcommand_matches("outdated") {
        let cfg = Config::from_matches(m);
        if let Err(e) = execute(cfg) {
            e.exit();
        }
    }
}

fn execute(cfg: Config) -> CliResult<()> {
    debugln!("executing; execute; cfg={:?}", cfg);

    verbose!(cfg, "Parsing {}...", Format::Warning("Cargo.lock"));
    let mut lf = try!(Lockfile::new());
    verboseln!(cfg, "{}", Format::Good("Done"));

    if let Ok(Some(res)) = lf.get_updates(&cfg) {
        println!("The following dependencies have newer versions available:\n");
        let mut tw = TabWriter::new(vec![]);
        write!(&mut tw, "\tName\tProject Ver\tSemVer Compat\tLatest Ver\n").unwrap_or_else(|e| {panic!("write! error: {}", e)});
        for (d_name, d) in res.iter() {
            write!(&mut tw, "\t{}\t   {}\t   {}\t  {}\n", d_name, d.project_ver, d.semver_ver.as_ref().unwrap_or(&String::from("  --  ")), d.latest_ver.as_ref().unwrap_or(&String::from("  --  "))).unwrap();
        }
        tw.flush().unwrap_or_else(|e| {panic!("failed to flush TabWriter: {}", e)});
        write!(stdout(), "{}", String::from_utf8(tw.unwrap()).unwrap_or_else(|e| {panic!("from_utf8 error: {}", e)})
              ).unwrap_or_else(|e| {panic!("write! error: {}", e)})
    } else {
        println!("All dependencies are up to date, yay!")
    }

    Ok(())
}

<|endoftext|>


<commit_before><commit_msg>start on plus<commit_after>use std::path::MAIN_SEPARATOR;
use libc::c_char;
use std::ffi::{CStr,CString};
use std::str;

#[no_mangle]
pub extern fn plus(string: *const c_char, string2: *const c_char) -> *const c_char {
  let c_str = unsafe {
    if string.is_null() {
      return string;
    }
    CStr::from_ptr(string)
  };

  let c_str2 = unsafe {
    if string2.is_null() {
      return string2;
    }
    CStr::from_ptr(string2)
  };

  let r_str = str::from_utf8(c_str.to_bytes()).unwrap();
  let r_str2 = str::from_utf8(c_str2.to_bytes()).unwrap();

  let mut prefix2 = r_str2.clone();
  let basename2: &str;
  let mut index2_list2: Vec<&str> = vec![];
  let mut basename_list2: Vec<&str> = vec![];
  loop {
    // chop basename
    (prefix2, basename2) = prefix2.split_at(prefix2.rfind('/').unwrap());
    index_list2.insert(0, prefix2.length());
    basename_list2.insert(0, basename2);
  }
  if prefix2.is_empty() { return string2 };
  let mut prefix1 = r_str.clone();
  loop {
    while !basename_list2.is_empty() && basename_list2[0] == "." {
      index_list2.remove(0);
      basename_list2.remove(0);
    }
    if !let Some(r1) = chop_basename(prefix1) { break };
    (prefix1,basename1) = r1;
    if basename1 == "." { continue };
    if basename1 == ".." || basename_list2.is_empty() || basename_list2[0] != ".." {
      prefix1 = prefix1 + basename1;
      break
    }
    index_list2.remove(0);
    basename_list2.remove(0);
  }
  if let Some(r1) = chop_basename(prefix1);
  if !r1 && (r1 = /#{SEPARATOR_PAT}/o =~ File.basename(prefix1)) {
    while !basename_list2.is_empty() && basename_list2[0] == ".." {
      index_list2.remove(0);
      basename_list2.remove(0);
    }
  }
  let result = if !basename_list2.is_empty() {
    suffix2 = path2[index_list2.first..-1];
    if r1 { File.join(prefix1, suffix2) } else { prefix1 + suffix2 }
  } else {
    if r1 { prefix1 } else { File.dirname(prefix1) }
  }

  let output = CString::new(result).unwrap();
  output.into_raw()
}

<|endoftext|>


<commit_before><commit_msg>I added a main function.  It just prints that it does nothing.<commit_after>fn main() {
    println!("So far, this does nothing.");
}
<|endoftext|>


<commit_before><commit_msg>Fix some errors in the Dice struct<commit_after><|endoftext|>


<commit_before>use alloc::boxed::Box;

use schemes::{Result, KScheme, Resource, Url, VecResource};

pub struct InterruptScheme;

impl KScheme for InterruptScheme {
    fn scheme(&self) -> &str {
        "interrupt"
    }

    fn open(&mut self, _: &Url, _: usize) -> Result<Box<Resource>> {
        let mut string = format!("{:<6}{:<16}", "INT", "COUNT");

        {
            let interrupts = ::env().interrupts.lock();
            for interrupt in 0..interrupts.len() {
                let count = interrupts[interrupt];

                if count > 0 {
                    string = string + "\n" + &format!("{:<6X}{:<16}", interrupt, count);
                }
            }
        }

        Ok(box VecResource::new(Url::from_str("interrupt:"), string.into_bytes()))
    }
}
<commit_msg>Add interrupt description to interrupt:<commit_after>use alloc::boxed::Box;

use schemes::{Result, KScheme, Resource, Url, VecResource};

pub struct InterruptScheme;

impl KScheme for InterruptScheme {
    fn scheme(&self) -> &str {
        "interrupt"
    }

    fn open(&mut self, _: &Url, _: usize) -> Result<Box<Resource>> {
        let mut string = format!("{:<6}{:<16}{}", "INT", "COUNT", "DESCRIPTION");

        {
            let interrupts = ::env().interrupts.lock();
            for interrupt in 0..interrupts.len() {
                let count = interrupts[interrupt];

                if count > 0 {
                    let description = match interrupt {
                        0x20 => "Programmable Interrupt Timer",
                        0x21 => "Keyboard",
                        0x22 => "Cascade",
                        0x23 => "Serial 2 and 4",
                        0x24 => "Serial 1 and 3",
                        0x25 => "Parallel 2",
                        0x26 => "Floppy",
                        0x27 => "Parallel 1",
                        0x28 => "Realtime Clock",
                        0x29 => "PCI 1",
                        0x2A => "PCI 2",
                        0x2B => "PCI 3",
                        0x2C => "Mouse",
                        0x2D => "Coprocessor",
                        0x2E => "IDE Primary",
                        0x2F => "IDE Secondary",
                        0x80 => "System Call",
                        0x0 => "Divide by zero exception",
                        0x1 => "Debug exception",
                        0x2 => "Non-maskable interrupt",
                        0x3 => "Breakpoint exception",
                        0x4 => "Overflow exception",
                        0x5 => "Bound range exceeded exception",
                        0x6 => "Invalid opcode exception",
                        0x7 => "Device not available exception",
                        0x8 => "Double fault",
                        0xA => "Invalid TSS exception",
                        0xB => "Segment not present exception",
                        0xC => "Stack-segment fault",
                        0xD => "General protection fault",
                        0xE => "Page fault",
                        0x10 => "x87 floating-point exception",
                        0x11 => "Alignment check exception",
                        0x12 => "Machine check exception",
                        0x13 => "SIMD floating-point exception",
                        0x14 => "Virtualization exception",
                        0x1E => "Security exception",
                        _ => "Unknown Interrupt",
                    };

                    string = string + "\n" + &format!("{:<6X}{:<16}{}", interrupt, count, description);
                }
            }
        }

        Ok(box VecResource::new(Url::from_str("interrupt:"), string.into_bytes()))
    }
}
<|endoftext|>


<commit_before><commit_msg>Won the figh with the borrow checker<commit_after><|endoftext|>


<commit_before><commit_msg>Removed unneeded unsafe part<commit_after><|endoftext|>


<commit_before><commit_msg>:fire: Remove unused struct<commit_after><|endoftext|>


<commit_before><commit_msg>	modified:   src/main.rs<commit_after><|endoftext|>


<commit_before><commit_msg>Fix read syscall argument<commit_after><|endoftext|>