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

// Detecting language items.
//
// Language items are items that represent concepts intrinsic to the language
// itself. Examples are:
//
// * Traits that specify "kinds"; e.g. "Freeze", "Send".
//
// * Traits that represent operators; e.g. "Add", "Sub", "Index".
//
// * Functions called by the compiler itself.

use driver::session::Session;
use metadata::csearch::each_lang_item;
use middle::ty::{BuiltinBound, BoundFreeze, BoundPod, BoundSend, BoundSized};
use syntax::ast;
use syntax::ast_util::local_def;
use syntax::attr::AttrMetaMethods;
use syntax::visit;
use syntax::visit::Visitor;

use std::hashmap::HashMap;
use std::iter::Enumerate;
use std::vec;

// The actual lang items defined come at the end of this file in one handy table.
// So you probably just want to nip down to the end.
macro_rules! lets_do_this {
    (
        There are $num_lang_items:expr lang items.
        $( $num:pat, $variant:ident, $name:expr, $method:ident; )*
    ) => {

pub enum LangItem {
    $($variant),*
}

pub struct LanguageItems {
    items: [Option<ast::DefId>, ..$num_lang_items]
}

impl LanguageItems {
    pub fn new() -> LanguageItems {
        LanguageItems {
            items: [ None, ..$num_lang_items ]
        }
    }

    pub fn items<'a>(&'a self) -> Enumerate<vec::Items<'a, Option<ast::DefId>>> {
        self.items.iter().enumerate()
    }

    pub fn item_name(index: uint) -> &'static str {
        match index {
            $( $num => $name, )*
            _ => "???"
        }
    }

    pub fn require(&self, it: LangItem) -> Result<ast::DefId, ~str> {
        match self.items[it as uint] {
            Some(id) => Ok(id),
            None => Err(format!("requires `{}` lang_item",
                             LanguageItems::item_name(it as uint)))
        }
    }

    pub fn to_builtin_kind(&self, id: ast::DefId) -> Option<BuiltinBound> {
        if Some(id) == self.freeze_trait() {
            Some(BoundFreeze)
        } else if Some(id) == self.send_trait() {
            Some(BoundSend)
        } else if Some(id) == self.sized_trait() {
            Some(BoundSized)
        } else if Some(id) == self.pod_trait() {
            Some(BoundPod)
        } else {
            None
        }
    }

    $(
        pub fn $method(&self) -> Option<ast::DefId> {
            self.items[$variant as uint]
        }
    )*
}

struct LanguageItemCollector {
    items: LanguageItems,

    session: Session,

    item_refs: HashMap<&'static str, uint>,
}

struct LanguageItemVisitor<'a> {
    this: &'a mut LanguageItemCollector,
}

impl<'a> Visitor<()> for LanguageItemVisitor<'a> {
    fn visit_item(&mut self, item: &ast::Item, _: ()) {
        match extract(item.attrs) {
            Some(value) => {
                let item_index = self.this.item_refs.find_equiv(&value).map(|x| *x);

                match item_index {
                    Some(item_index) => {
                        self.this.collect_item(item_index, local_def(item.id))
                    }
                    None => {}
                }
            }
            None => {}
        }

        visit::walk_item(self, item, ());
    }
}

impl LanguageItemCollector {
    pub fn new(session: Session) -> LanguageItemCollector {
        let mut item_refs = HashMap::new();

        $( item_refs.insert($name, $variant as uint); )*

        LanguageItemCollector {
            session: session,
            items: LanguageItems::new(),
            item_refs: item_refs
        }
    }

    pub fn collect_item(&mut self, item_index: uint, item_def_id: ast::DefId) {
        // Check for duplicates.
        match self.items.items[item_index] {
            Some(original_def_id) if original_def_id != item_def_id => {
                self.session.err(format!("duplicate entry for `{}`",
                                      LanguageItems::item_name(item_index)));
            }
            Some(_) | None => {
                // OK.
            }
        }

        // Matched.
        self.items.items[item_index] = Some(item_def_id);
    }

    pub fn collect_local_language_items(&mut self, crate: &ast::Crate) {
        let mut v = LanguageItemVisitor { this: self };
        visit::walk_crate(&mut v, crate, ());
    }

    pub fn collect_external_language_items(&mut self) {
        let crate_store = self.session.cstore;
        crate_store.iter_crate_data(|crate_number, _crate_metadata| {
            each_lang_item(crate_store, crate_number, |node_id, item_index| {
                let def_id = ast::DefId { crate: crate_number, node: node_id };
                self.collect_item(item_index, def_id);
                true
            });
        })
    }

    pub fn collect(&mut self, crate: &ast::Crate) {
        self.collect_local_language_items(crate);
        self.collect_external_language_items();
    }
}

pub fn extract(attrs: &[ast::Attribute]) -> Option<@str> {
    for attribute in attrs.iter() {
        match attribute.name_str_pair() {
            Some((key, value)) if "lang" == key => {
                return Some(value);
            }
            Some(..) | None => {}
        }
    }

    return None;
}

pub fn collect_language_items(crate: &ast::Crate,
                              session: Session)
                           -> LanguageItems {
    let mut collector = LanguageItemCollector::new(session);
    collector.collect(crate);
    let LanguageItemCollector { items, .. } = collector;
    session.abort_if_errors();
    items
}

// End of the macro
    }
}

lets_do_this! {
    There are 40 lang items.

//  ID, Variant name,                    Name,                      Method name;
    0,  FreezeTraitLangItem,             "freeze",                  freeze_trait;
    1,  SendTraitLangItem,               "send",                    send_trait;
    2,  SizedTraitLangItem,              "sized",                   sized_trait;
    3,  PodTraitLangItem,                "pod",                     pod_trait;

    4,  DropTraitLangItem,               "drop",                    drop_trait;

    5,  AddTraitLangItem,                "add",                     add_trait;
    6,  SubTraitLangItem,                "sub",                     sub_trait;
    7,  MulTraitLangItem,                "mul",                     mul_trait;
    8,  DivTraitLangItem,                "div",                     div_trait;
    9,  RemTraitLangItem,                "rem",                     rem_trait;
    10, NegTraitLangItem,                "neg",                     neg_trait;
    11, NotTraitLangItem,                "not",                     not_trait;
    12, BitXorTraitLangItem,             "bitxor",                  bitxor_trait;
    13, BitAndTraitLangItem,             "bitand",                  bitand_trait;
    14, BitOrTraitLangItem,              "bitor",                   bitor_trait;
    15, ShlTraitLangItem,                "shl",                     shl_trait;
    16, ShrTraitLangItem,                "shr",                     shr_trait;
    17, IndexTraitLangItem,              "index",                   index_trait;

    18, EqTraitLangItem,                 "eq",                      eq_trait;
    19, OrdTraitLangItem,                "ord",                     ord_trait;

    20, StrEqFnLangItem,                 "str_eq",                  str_eq_fn;
    21, UniqStrEqFnLangItem,             "uniq_str_eq",             uniq_str_eq_fn;
    22, FailFnLangItem,                  "fail_",                   fail_fn;
    23, FailBoundsCheckFnLangItem,       "fail_bounds_check",       fail_bounds_check_fn;
    24, ExchangeMallocFnLangItem,        "exchange_malloc",         exchange_malloc_fn;
    25, ClosureExchangeMallocFnLangItem, "closure_exchange_malloc", closure_exchange_malloc_fn;
    26, ExchangeFreeFnLangItem,          "exchange_free",           exchange_free_fn;
    27, MallocFnLangItem,                "malloc",                  malloc_fn;
    28, FreeFnLangItem,                  "free",                    free_fn;
    29, StrDupUniqFnLangItem,            "strdup_uniq",             strdup_uniq_fn;

    30, StartFnLangItem,                 "start",                   start_fn;

    31, TyDescStructLangItem,            "ty_desc",                 ty_desc;
    32, TyVisitorTraitLangItem,          "ty_visitor",              ty_visitor;
    33, OpaqueStructLangItem,            "opaque",                  opaque;

    34, EventLoopFactoryLangItem,        "event_loop_factory",      event_loop_factory;

    35, TypeIdLangItem,                  "type_id",                 type_id;

    36, EhPersonalityLangItem,           "eh_personality",          eh_personality_fn;

    37, ManagedHeapLangItem,             "managed_heap",            managed_heap;
    38, ExchangeHeapLangItem,            "exchange_heap",           exchange_heap;
    39, GcLangItem,                      "gc",                      gc;
}

<commit_msg>rustc: remove the explicit count from the lang_item macro.<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.

// Detecting language items.
//
// Language items are items that represent concepts intrinsic to the language
// itself. Examples are:
//
// * Traits that specify "kinds"; e.g. "Freeze", "Send".
//
// * Traits that represent operators; e.g. "Add", "Sub", "Index".
//
// * Functions called by the compiler itself.

use driver::session::Session;
use metadata::csearch::each_lang_item;
use middle::ty::{BuiltinBound, BoundFreeze, BoundPod, BoundSend, BoundSized};
use syntax::ast;
use syntax::ast_util::local_def;
use syntax::attr::AttrMetaMethods;
use syntax::visit;
use syntax::visit::Visitor;

use std::hashmap::HashMap;
use std::iter::Enumerate;
use std::vec;

// Get the last "argument" (has to be done recursively to avoid phoney local ambiguity error)
macro_rules! last {
    ( $first:expr, $( $remainder:expr, )+ ) => ( last!( $( $remainder, )+ ) );
    ( $first:expr, ) => ( $first )
}

// The actual lang items defined come at the end of this file in one handy table.
// So you probably just want to nip down to the end.
macro_rules! lets_do_this {
    // secondary rule to allow us to use `$num` as both an expression
    // and a pattern.
    (
        $( $num:tt, $variant:ident, $name:expr, $method:ident; )*
    ) => {
        lets_do_this!(count = 1 + last!($($num,)*),
                      $($num, $variant, $name, $method; )*)
    };

    (
        count = $num_lang_items:expr, $( $num:pat, $variant:ident, $name:expr, $method:ident; )*
    ) => {

pub enum LangItem {
    $($variant),*
}

pub struct LanguageItems {
    items: [Option<ast::DefId>, ..$num_lang_items]
}

impl LanguageItems {
    pub fn new() -> LanguageItems {
        LanguageItems {
            items: [ None, ..$num_lang_items ]
        }
    }

    pub fn items<'a>(&'a self) -> Enumerate<vec::Items<'a, Option<ast::DefId>>> {
        self.items.iter().enumerate()
    }

    pub fn item_name(index: uint) -> &'static str {
        match index {
            $( $num => $name, )*
            _ => "???"
        }
    }

    pub fn require(&self, it: LangItem) -> Result<ast::DefId, ~str> {
        match self.items[it as uint] {
            Some(id) => Ok(id),
            None => Err(format!("requires `{}` lang_item",
                             LanguageItems::item_name(it as uint)))
        }
    }

    pub fn to_builtin_kind(&self, id: ast::DefId) -> Option<BuiltinBound> {
        if Some(id) == self.freeze_trait() {
            Some(BoundFreeze)
        } else if Some(id) == self.send_trait() {
            Some(BoundSend)
        } else if Some(id) == self.sized_trait() {
            Some(BoundSized)
        } else if Some(id) == self.pod_trait() {
            Some(BoundPod)
        } else {
            None
        }
    }

    $(
        pub fn $method(&self) -> Option<ast::DefId> {
            self.items[$variant as uint]
        }
    )*
}

struct LanguageItemCollector {
    items: LanguageItems,

    session: Session,

    item_refs: HashMap<&'static str, uint>,
}

struct LanguageItemVisitor<'a> {
    this: &'a mut LanguageItemCollector,
}

impl<'a> Visitor<()> for LanguageItemVisitor<'a> {
    fn visit_item(&mut self, item: &ast::Item, _: ()) {
        match extract(item.attrs) {
            Some(value) => {
                let item_index = self.this.item_refs.find_equiv(&value).map(|x| *x);

                match item_index {
                    Some(item_index) => {
                        self.this.collect_item(item_index, local_def(item.id))
                    }
                    None => {}
                }
            }
            None => {}
        }

        visit::walk_item(self, item, ());
    }
}

impl LanguageItemCollector {
    pub fn new(session: Session) -> LanguageItemCollector {
        let mut item_refs = HashMap::new();

        $( item_refs.insert($name, $variant as uint); )*

        LanguageItemCollector {
            session: session,
            items: LanguageItems::new(),
            item_refs: item_refs
        }
    }

    pub fn collect_item(&mut self, item_index: uint, item_def_id: ast::DefId) {
        // Check for duplicates.
        match self.items.items[item_index] {
            Some(original_def_id) if original_def_id != item_def_id => {
                self.session.err(format!("duplicate entry for `{}`",
                                      LanguageItems::item_name(item_index)));
            }
            Some(_) | None => {
                // OK.
            }
        }

        // Matched.
        self.items.items[item_index] = Some(item_def_id);
    }

    pub fn collect_local_language_items(&mut self, crate: &ast::Crate) {
        let mut v = LanguageItemVisitor { this: self };
        visit::walk_crate(&mut v, crate, ());
    }

    pub fn collect_external_language_items(&mut self) {
        let crate_store = self.session.cstore;
        crate_store.iter_crate_data(|crate_number, _crate_metadata| {
            each_lang_item(crate_store, crate_number, |node_id, item_index| {
                let def_id = ast::DefId { crate: crate_number, node: node_id };
                self.collect_item(item_index, def_id);
                true
            });
        })
    }

    pub fn collect(&mut self, crate: &ast::Crate) {
        self.collect_local_language_items(crate);
        self.collect_external_language_items();
    }
}

pub fn extract(attrs: &[ast::Attribute]) -> Option<@str> {
    for attribute in attrs.iter() {
        match attribute.name_str_pair() {
            Some((key, value)) if "lang" == key => {
                return Some(value);
            }
            Some(..) | None => {}
        }
    }

    return None;
}

pub fn collect_language_items(crate: &ast::Crate,
                              session: Session)
                           -> LanguageItems {
    let mut collector = LanguageItemCollector::new(session);
    collector.collect(crate);
    let LanguageItemCollector { items, .. } = collector;
    session.abort_if_errors();
    items
}

// End of the macro
    }
}

lets_do_this! {
//  ID, Variant name,                    Name,                      Method name;
    0,  FreezeTraitLangItem,             "freeze",                  freeze_trait;
    1,  SendTraitLangItem,               "send",                    send_trait;
    2,  SizedTraitLangItem,              "sized",                   sized_trait;
    3,  PodTraitLangItem,                "pod",                     pod_trait;

    4,  DropTraitLangItem,               "drop",                    drop_trait;

    5,  AddTraitLangItem,                "add",                     add_trait;
    6,  SubTraitLangItem,                "sub",                     sub_trait;
    7,  MulTraitLangItem,                "mul",                     mul_trait;
    8,  DivTraitLangItem,                "div",                     div_trait;
    9,  RemTraitLangItem,                "rem",                     rem_trait;
    10, NegTraitLangItem,                "neg",                     neg_trait;
    11, NotTraitLangItem,                "not",                     not_trait;
    12, BitXorTraitLangItem,             "bitxor",                  bitxor_trait;
    13, BitAndTraitLangItem,             "bitand",                  bitand_trait;
    14, BitOrTraitLangItem,              "bitor",                   bitor_trait;
    15, ShlTraitLangItem,                "shl",                     shl_trait;
    16, ShrTraitLangItem,                "shr",                     shr_trait;
    17, IndexTraitLangItem,              "index",                   index_trait;

    18, EqTraitLangItem,                 "eq",                      eq_trait;
    19, OrdTraitLangItem,                "ord",                     ord_trait;

    20, StrEqFnLangItem,                 "str_eq",                  str_eq_fn;
    21, UniqStrEqFnLangItem,             "uniq_str_eq",             uniq_str_eq_fn;
    22, FailFnLangItem,                  "fail_",                   fail_fn;
    23, FailBoundsCheckFnLangItem,       "fail_bounds_check",       fail_bounds_check_fn;
    24, ExchangeMallocFnLangItem,        "exchange_malloc",         exchange_malloc_fn;
    25, ClosureExchangeMallocFnLangItem, "closure_exchange_malloc", closure_exchange_malloc_fn;
    26, ExchangeFreeFnLangItem,          "exchange_free",           exchange_free_fn;
    27, MallocFnLangItem,                "malloc",                  malloc_fn;
    28, FreeFnLangItem,                  "free",                    free_fn;
    29, StrDupUniqFnLangItem,            "strdup_uniq",             strdup_uniq_fn;

    30, StartFnLangItem,                 "start",                   start_fn;

    31, TyDescStructLangItem,            "ty_desc",                 ty_desc;
    32, TyVisitorTraitLangItem,          "ty_visitor",              ty_visitor;
    33, OpaqueStructLangItem,            "opaque",                  opaque;

    34, EventLoopFactoryLangItem,        "event_loop_factory",      event_loop_factory;

    35, TypeIdLangItem,                  "type_id",                 type_id;

    36, EhPersonalityLangItem,           "eh_personality",          eh_personality_fn;

    37, ManagedHeapLangItem,             "managed_heap",            managed_heap;
    38, ExchangeHeapLangItem,            "exchange_heap",           exchange_heap;
    39, GcLangItem,                      "gc",                      gc;
}
<|endoftext|>


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

//! Platform-specific extensions to `std` for Windows.
//!
//! Provides access to platform-level information for Windows, and exposes
//! Windows-specific idioms that would otherwise be inappropriate as part
//! the core `std` library. These extensions allow developers to use
//! `std` types and idioms with Windows in a way that the normal
//! platform-agnostic idioms would not normally support.

#![stable(feature = "rust1", since = "1.0.0")]
#![doc(cfg(windows))]

pub mod ffi;
pub mod fs;
pub mod io;
pub mod raw;
pub mod process;
pub mod thread;

/// A prelude for conveniently writing platform-specific code.
///
/// Includes all extension traits, and some important type definitions.
#[stable(feature = "rust1", since = "1.0.0")]
pub mod prelude {
    #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")]
    pub use super::io::{RawSocket, RawHandle, AsRawSocket, AsRawHandle};
    #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")]
    pub use super::io::{FromRawSocket, FromRawHandle, IntoRawSocket, IntoRawHandle};
    #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")]
    pub use super::ffi::{OsStrExt, OsStringExt};
    #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")]
    pub use super::fs::{OpenOptionsExt, MetadataExt};
    #[doc(no_inline)] #[stable(feature = "file_offset", since = "1.15.0")]
    pub use super::fs::FileExt;
}
<commit_msg>Add missing allow_missing_docs<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.

//! Platform-specific extensions to `std` for Windows.
//!
//! Provides access to platform-level information for Windows, and exposes
//! Windows-specific idioms that would otherwise be inappropriate as part
//! the core `std` library. These extensions allow developers to use
//! `std` types and idioms with Windows in a way that the normal
//! platform-agnostic idioms would not normally support.

#![stable(feature = "rust1", since = "1.0.0")]
#![doc(cfg(windows))]
#![allow(missing_docs)]

pub mod ffi;
pub mod fs;
pub mod io;
pub mod raw;
pub mod process;
pub mod thread;

/// A prelude for conveniently writing platform-specific code.
///
/// Includes all extension traits, and some important type definitions.
#[stable(feature = "rust1", since = "1.0.0")]
pub mod prelude {
    #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")]
    pub use super::io::{RawSocket, RawHandle, AsRawSocket, AsRawHandle};
    #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")]
    pub use super::io::{FromRawSocket, FromRawHandle, IntoRawSocket, IntoRawHandle};
    #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")]
    pub use super::ffi::{OsStrExt, OsStringExt};
    #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")]
    pub use super::fs::{OpenOptionsExt, MetadataExt};
    #[doc(no_inline)] #[stable(feature = "file_offset", since = "1.15.0")]
    pub use super::fs::FileExt;
}
<|endoftext|>


<commit_before><commit_msg>Simplify code<commit_after><|endoftext|>


<commit_before><commit_msg>Accept several input files<commit_after><|endoftext|>


<commit_before><commit_msg>remove unused imports since add `new` fn<commit_after><|endoftext|>


<commit_before><commit_msg>Use a robust temporary directory<commit_after><|endoftext|>


<commit_before><commit_msg>Can't put a & in a column name<commit_after><|endoftext|>


<commit_before>//! The executable wiki for wikilib
#![deny(missing_docs)]

#[macro_use]
extern crate clap;
#[macro_use]
extern crate log;
extern crate wikilib;

use wikilib::{ErrorType, Wiki, WikiError, WikiResult};

use clap::App;
use log::LogLevel;

use std::process::exit;

fn main() {
    if let Err(error) = run() {
        error!("{}", error);
        exit(1);
    }
}

fn run() -> WikiResult<()> {
    // Parse the given arguments
    let yaml = load_yaml!("cli.yml");
    let app = App::from_yaml(yaml).version(crate_version!());
    let matches = app.get_matches();

    // Set the verbosity level
    let log_level = match matches.occurrences_of("verbose") {
        0 => LogLevel::Error,
        1 => LogLevel::Warn,
        2 => LogLevel::Info,
        3 => LogLevel::Debug,
        _ => LogLevel::Trace,
    };

    // Get the input directory
    let input_directory = matches.value_of("input_directory")
        .ok_or_else(|| {
            WikiError::new(ErrorType::CliParameterMissing,
                           "Input directory CLI parameter missing")
        })?;

    // Get the output directory
    let output_directory = matches.value_of("output_directory")
        .ok_or_else(|| {
            WikiError::new(ErrorType::CliParameterMissing,
                           "Output directory CLI parameter missing")
        })?;

    let enable_httpd = matches.is_present("www");

    // Do first processing steps
    let mut wiki = Wiki::new();

    wiki.init_logging(log_level)?;
    wiki.read_from_directory(input_directory)?;
    wiki.list_current_paths();
    wiki.read_content_from_current_paths(input_directory, output_directory)?;

    if enable_httpd {
        wiki.serve(output_directory)?;
    }

    Ok(())
}
<commit_msg>Added comment to the main run function<commit_after>//! The executable wiki for wikilib
#![deny(missing_docs)]

#[macro_use]
extern crate clap;
#[macro_use]
extern crate log;
extern crate wikilib;

use wikilib::{ErrorType, Wiki, WikiError, WikiResult};

use clap::App;
use log::LogLevel;

use std::process::exit;

fn main() {
    if let Err(error) = run() {
        error!("{}", error);
        exit(1);
    }
}

// The main running function
fn run() -> WikiResult<()> {
    // Parse the given arguments
    let yaml = load_yaml!("cli.yml");
    let app = App::from_yaml(yaml).version(crate_version!());
    let matches = app.get_matches();

    // Set the verbosity level
    let log_level = match matches.occurrences_of("verbose") {
        0 => LogLevel::Error,
        1 => LogLevel::Warn,
        2 => LogLevel::Info,
        3 => LogLevel::Debug,
        _ => LogLevel::Trace,
    };

    // Get the input directory
    let input_directory = matches.value_of("input_directory")
        .ok_or_else(|| {
            WikiError::new(ErrorType::CliParameterMissing,
                           "Input directory CLI parameter missing")
        })?;

    // Get the output directory
    let output_directory = matches.value_of("output_directory")
        .ok_or_else(|| {
            WikiError::new(ErrorType::CliParameterMissing,
                           "Output directory CLI parameter missing")
        })?;

    let enable_httpd = matches.is_present("www");

    // Do first processing steps
    let mut wiki = Wiki::new();

    wiki.init_logging(log_level)?;
    wiki.read_from_directory(input_directory)?;
    wiki.list_current_paths();
    wiki.read_content_from_current_paths(input_directory, output_directory)?;

    if enable_httpd {
        wiki.serve(output_directory)?;
    }

    Ok(())
}
<|endoftext|>


<commit_before><commit_msg>Dot "." also matches newline by default (closes #111)<commit_after><|endoftext|>


<commit_before><commit_msg>Add signin fields<commit_after><|endoftext|>


<commit_before><commit_msg>clean this up a bit<commit_after><|endoftext|>


<commit_before>mod rush {
    extern mod core;
    extern mod linenoise;
    use core::run;

    pub struct JobOutput {
        stdout: libc::c_int,
        stderr: libc::c_int,
        pid: libc::c_int,
    }

    pub fn exec_command(input: JobOutput, command: &str) -> JobOutput {
        let pipe_out = os::pipe();
        let pipe_err = os::pipe();
        let mut args: ~[~str] = ~[];
        let mut prog = ~"";
        let mut first = true;
        str::each_split_char(command, ' ', |item| {
            if (first) {
                prog = copy item.to_owned();
                first = false;
            } else {
                args.push(item.to_owned());
            }
            true
        });
        let pid = run::spawn_process(
                prog, args, &None, &None,
                input.stdout, pipe_out.out, pipe_err.out);
        os::close(input.stdout);
        os::close(pipe_out.out);
        os::close(pipe_err.out);
        JobOutput{
            pid: pid,
            stdout: pipe_out.in,
            stderr: pipe_err.in,
        }
    }

    pub fn handle_input(line: &str) {
        let mut commands: ~[&str] = ~[];
        str::each_split_char_no_trailing(line, '|', |command| { commands.push(str::trim(command)); true });
        let fake_out = JobOutput{
            stdout: -1,
            stderr: -1,
            pid: -1,
        };
        let job_output = vec::foldl(fake_out, commands, |stdin, command| {
            exec_command(stdin, *command)
        });
        if (job_output.pid == -1) { return }
        proxy_fds(job_output.stdout, libc::STDOUT_FILENO as libc::c_int);
        proxy_fds(job_output.stderr, libc::STDERR_FILENO as libc::c_int);
        run::waitpid(job_output.pid);
    }
    pub fn proxy_fds(input: libc::c_int, output: libc::c_int) {
        do task::spawn_sched(task::SingleThreaded) || {
            unsafe {
                let output = io::fd_writer(output, false);
                let file = os::fdopen(input);
                let reader = io::FILE_reader(file, false);
                let mut bytes = [0, ..4096];
                while !reader.eof() {
                    let nread = reader.read(bytes, bytes.len());
                    output.write(bytes.slice(0, nread));
                }
                os::fclose(file);
            }
        }
    }
    pub fn main() {
        linenoise::set_multiline(true);
        loop {
            prompt();
        }
    }
    pub fn prompt() {
        let line = linenoise::init("rush: ");
        linenoise::history_add(line);
        linenoise::history_save("history.txt");
        handle_input(line);
    }
}
<commit_msg>Updated with struct/impl<commit_after>mod rush {
    extern mod core;
    extern mod linenoise;
    use core::run;

    pub struct Job {
        command: ~str,
        stdin: os::Pipe,
        stdout: os::Pipe,
        stderr: os::Pipe,
    }

    impl Job {
        pub fn exec(&self) -> i32 {
            let mut args: ~[~str] = ~[];
            let mut prog = ~"";
            let mut first = true;
            str::each_split_char(self.command, ' ', |item| {
                if (first) {
                    prog = copy item.to_owned();
                    first = false;
                } else {
                    args.push(item.to_owned());
                }
                true
            });
            let pid = run::spawn_process(
                    prog, args, &None, &None,
                    self.stdin.in, self.stdout.out, self.stderr.out);
            os::close(self.stdin.in);
            if (self.stdout.out != libc::STDOUT_FILENO as libc::c_int) {
                os::close(self.stdout.out);
                os::close(self.stderr.out);
            }
            pid
        }
    }

    pub fn handle_input(line: &str) {
        if (line.is_empty()) { return; }
        let mut commands: ~[~str] = ~[];
        str::each_split_char_no_trailing(line, '|', |command| {
            commands.push(command.to_owned());
            true
        });
        let mut pipeline: ~[Job] = ~[];
        let mut index = 0;
        let mut stdin = os::Pipe{ in: -1, out: -1};
        commands.each(|command| {
            index += 1;
            // Needs to be initialized like this?
            // Surely I'm missing a nicer syntax for this?
            let mut stdout = os::Pipe{ in: -1, out: -1};
            let mut stderr = os::Pipe{ in: -1, out: -1};
            if (index==commands.len()) {
                // Pass the last job the stdout/stderr for the shell itself
                stdout = os::Pipe{
                    out: libc::STDOUT_FILENO as libc::c_int,
                    in: -1,
                };
                stderr = os::Pipe{
                    out: libc::STDERR_FILENO as libc::c_int,
                    in: -1,
                };
            } else {
                stdout = os::pipe();
                stderr = os::pipe();
            }
            pipeline.push(Job{
                command: str::trim(*command).to_owned(),
                stdin: stdin,
                stdout: stdout,
                stderr: stderr,
            });
            stdin = stdout;
            true
        });

        let mut pid = -1;
        pipeline.each(|job| { pid = job.exec(); true });
        os::waitpid(pid);
    }

    pub fn main() {
        linenoise::set_multiline(true);
        loop {
            prompt();
        }
    }

    pub fn prompt() {
        let line = linenoise::init("rush: ");
        linenoise::history_add(line);
        linenoise::history_save("history.txt");
        handle_input(line);
    }
}
<|endoftext|>


<commit_before><commit_msg>Auto merge of #2210 - sunfishcode:sunfishcode/wasi-o-cloexec, r=Amanieu<commit_after><|endoftext|>


<commit_before>// Test that the BK storage works.

extern crate rsure;
extern crate tempdir;

use rsure::bk::{self, BkDir};
use rsure::{TreeCompare, stdout_visitor};
use std::path::Path;
use std::process::Command;
use tempdir::TempDir;

#[test]
fn bk_create() {
    let tmp = TempDir::new("rsure").unwrap();

    // Can we create in an empty directory.
    bk::setup(tmp.path()).unwrap();
    verify_configs(tmp.path());

    // Make sure we can also create a directory.
    let sub = tmp.path().join("subdir");
    bk::setup(&sub).unwrap();
    verify_configs(&sub);

    // It seems that BitKeeper will create as many directories as
    // necessary.
    let sub = tmp.path().join("first").join("second");
    bk::setup(&sub).unwrap();
}

#[test]
fn bk_saves() {
    let tmp = TempDir::new("rsure").unwrap();

    bk::setup(tmp.path()).unwrap();
    let bkdir = BkDir::new(tmp.path()).unwrap();

    let tree = rsure::scan_fs(tmp.path()).unwrap();
    bkdir.save(&tree, "self.dat", "first-version").unwrap();

    let t2 = rsure::scan_fs(tmp.path()).unwrap();
    bkdir.save(&t2, "self.dat", "second-version").unwrap();

    // tmp.into_path();
    println!("Running query!!!");
    let qy = bkdir.query().unwrap();
    let mut found = 0;
    for ent in &qy {
        if ent.file == "self.dat" {
            if ent.name == "first-version" {
                found |= 1;
            } else if ent.name == "second-version" {
                found |= 2;
            }
        }
    }
    assert_eq!(found, 3);

    match bkdir.load("none.dat", "first-version") {
        Err(_) => (),
        Ok(_) => panic!("Shouldn't be able to find node."),
    }

    match bkdir.load("self.dat", "third-version") {
        Err(_) => (),
        Ok(_) => panic!("Shouldn't be able to find node."),
    }

    let tt1 = bkdir.load("self.dat", "first-version").unwrap();
    let tt2 = bkdir.load("self.dat", "second-version").unwrap();
    tt2.compare_from(&mut stdout_visitor(), &tt1, tmp.path());
}

fn verify_configs(base: &Path) {
    verify_config(base, "BAM", b"off\n");
    verify_config(base, "checkout", b"none\n");
}

fn verify_config(base: &Path, name: &str, expect: &[u8]) {
    let mut cmd = Command::new("bk");
    cmd.args(&["config", name]);
    cmd.current_dir(base);
    let out = cmd.output().unwrap();
    assert_eq!(out.stdout, expect);
    assert_eq!(out.stderr, b"");
    // println!("stdout: {:?}", String::from_utf8_lossy(&out.stdout));
    // println!("stderr: {:?}", String::from_utf8_lossy(&out.stderr));
}
<commit_msg>Comment out the bk test for now<commit_after>// Test that the BK storage works.

/*
extern crate rsure;
extern crate tempdir;

use rsure::bk::{self, BkDir};
use rsure::{TreeCompare, stdout_visitor};
use std::path::Path;
use std::process::Command;
use tempdir::TempDir;

#[test]
fn bk_create() {
    let tmp = TempDir::new("rsure").unwrap();

    // Can we create in an empty directory.
    bk::setup(tmp.path()).unwrap();
    verify_configs(tmp.path());

    // Make sure we can also create a directory.
    let sub = tmp.path().join("subdir");
    bk::setup(&sub).unwrap();
    verify_configs(&sub);

    // It seems that BitKeeper will create as many directories as
    // necessary.
    let sub = tmp.path().join("first").join("second");
    bk::setup(&sub).unwrap();
}

#[test]
fn bk_saves() {
    let tmp = TempDir::new("rsure").unwrap();

    bk::setup(tmp.path()).unwrap();
    let bkdir = BkDir::new(tmp.path()).unwrap();

    let tree = rsure::scan_fs(tmp.path()).unwrap();
    bkdir.save(&tree, "self.dat", "first-version").unwrap();

    let t2 = rsure::scan_fs(tmp.path()).unwrap();
    bkdir.save(&t2, "self.dat", "second-version").unwrap();

    // tmp.into_path();
    println!("Running query!!!");
    let qy = bkdir.query().unwrap();
    let mut found = 0;
    for ent in &qy {
        if ent.file == "self.dat" {
            if ent.name == "first-version" {
                found |= 1;
            } else if ent.name == "second-version" {
                found |= 2;
            }
        }
    }
    assert_eq!(found, 3);

    match bkdir.load("none.dat", "first-version") {
        Err(_) => (),
        Ok(_) => panic!("Shouldn't be able to find node."),
    }

    match bkdir.load("self.dat", "third-version") {
        Err(_) => (),
        Ok(_) => panic!("Shouldn't be able to find node."),
    }

    let tt1 = bkdir.load("self.dat", "first-version").unwrap();
    let tt2 = bkdir.load("self.dat", "second-version").unwrap();
    tt2.compare_from(&mut stdout_visitor(), &tt1, tmp.path());
}

fn verify_configs(base: &Path) {
    verify_config(base, "BAM", b"off\n");
    verify_config(base, "checkout", b"none\n");
}

fn verify_config(base: &Path, name: &str, expect: &[u8]) {
    let mut cmd = Command::new("bk");
    cmd.args(&["config", name]);
    cmd.current_dir(base);
    let out = cmd.output().unwrap();
    assert_eq!(out.stdout, expect);
    assert_eq!(out.stderr, b"");
    // println!("stdout: {:?}", String::from_utf8_lossy(&out.stdout));
    // println!("stderr: {:?}", String::from_utf8_lossy(&out.stderr));
}
*/
<|endoftext|>


<commit_before>use flowgger::config::Config;
use flowgger::merger::Merger;
use openssl::bn::BigNum;
use openssl::dh::DH;
use openssl::ssl::*;
use openssl::x509::X509FileType;
use std::error::Error;
use std::io;
use std::io::{stderr, BufWriter, ErrorKind, Write};
use std::net::TcpStream;
use std::path::{Path, PathBuf};
use std::sync::mpsc::Receiver;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
use super::Output;

const DEFAULT_CIPHERS: &'static str = "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA";
const DEFAULT_CONNECT: &'static str = "127.0.0.1:6514";
const DEFAULT_SLEEP_AFTER_CONNECTION_FAILURE: u32 = 1000;
const TLS_DEFAULT_TIMEOUT: u64 = 3600;
const TLS_DEFAULT_THREADS: u32 = 1;

pub struct TlsOutput {
    config: TlsConfig,
    threads: u32
}

#[derive(Clone)]
struct TlsConfig {
    timeout: Option<Duration>,
    connect: String
}

struct TlsWorker {
    arx: Arc<Mutex<Receiver<Vec<u8>>>>,
    merger: Arc<Option<Box<Merger + Send>>>,
    config: TlsConfig
}

impl TlsWorker {
    fn new(arx: Arc<Mutex<Receiver<Vec<u8>>>>, merger: Arc<Option<Box<Merger + Send>>>, config: TlsConfig) -> TlsWorker {
        TlsWorker {
            arx: arx,
            merger: merger,
            config: config
        }
    }

    fn handle_connection(&self, connect: &str) -> io::Result<()> {
        let client = try!(new_tcp(connect));
        let _ = writeln!(stderr(), "Connected to {}", connect);
        let tls_method = SslMethod::Sslv23;
        let mut ctx = SslContext::new(tls_method).unwrap();
        let ciphers = DEFAULT_CIPHERS;
        set_fs(&mut ctx);
        ctx.set_cipher_list(&ciphers).unwrap();
        let sslclient = match SslStream::connect(&ctx, client) {
            Err(_) => return Err(io::Error::new(io::ErrorKind::ConnectionAborted, "SSL handshake aborted by the server")),
            Ok(sslclient) => sslclient
        };
        let _ = writeln!(stderr(), "Completed SSL handshake with {}", connect);
        let mut writer = BufWriter::new(sslclient);
        let merger = &*self.merger;
        loop {
            let mut bytes = match { self.arx.lock().unwrap().recv() } {
                Ok(line) => line,
                Err(_) => return Err(io::Error::new(io::ErrorKind::Other, "Cannot read the message queue any more"))
            };
            if let Some(ref merger) = *merger {
                merger.frame(&mut bytes);
            }
            match writer.write_all(&bytes) {
                Ok(_) => { },
                Err(e) => match e.kind() {
                    ErrorKind::Interrupted => continue,
                    _ => return Err(e)
                }
            };
        }
    }

    fn run(self) {
        loop {
            let ref connect = self.config.connect;
            if let Err(e) = self.handle_connection(&connect) {
                match e.kind() {
                    ErrorKind::ConnectionRefused => {
                        let _ = writeln!(stderr(), "Connection to {} refused", connect);
                    }
                    ErrorKind::ConnectionAborted | ErrorKind::ConnectionReset => {
                        let _ = writeln!(stderr(), "Connection to {} aborted by the server", connect);
                    }
                    _ => {
                        let _ = writeln!(stderr(), "Error while communicating with {} - {}", connect, e);
                    }
                }
            }
            thread::sleep_ms(DEFAULT_SLEEP_AFTER_CONNECTION_FAILURE);
            let _ = writeln!(stderr(), "Attempting to reconnect");
        }
    }
}

fn new_tcp(connect: &str) -> Result<TcpStream, io::Error> {
    loop {
        match TcpStream::connect(connect) {
            Ok(stream) => return Ok(stream),
            Err(e) => {
                return Err(e);
            }
        }
    }
}

impl TlsOutput {
    pub fn new(config: &Config) -> TlsOutput {
        let connect = config.lookup("output.connect").map_or(DEFAULT_CONNECT, |x|x.as_str().
            expect("input.listen must be an ip:port string")).to_owned();
        let timeout = config.lookup("output.tls_timeout").
            map_or(TLS_DEFAULT_TIMEOUT, |x| x.as_integer().
                expect("output.tls_timeout must be an unsigned integer") as u64);
        let threads = config.lookup("output.tls_threads").
            map_or(TLS_DEFAULT_THREADS, |x| x.as_integer().
                expect("output.tls_threads must be a 32-bit integer") as u32);
        let tls_config = TlsConfig {
            connect: connect,
            timeout: Some(Duration::from_secs(timeout))
        };
        TlsOutput {
            config: tls_config,
            threads: threads
        }
    }
}

impl Output for TlsOutput {
    fn start(&self, arx: Arc<Mutex<Receiver<Vec<u8>>>>, merger: Option<Box<Merger>>) {
        for _ in 0..self.threads {
            let arx = arx.clone();
            let config = self.config.clone();
            let merger = match merger {
                Some(ref merger) => Some(merger.clone_boxed()) as Option<Box<Merger + Send>>,
                None => None
            };
            thread::spawn(move || {
                let worker = TlsWorker::new(arx, Arc::new(merger), config);
                worker.run();
            });
        }
    }
}

#[cfg(feature = "ecdh")]
fn set_ecdh(ctx: &mut SslContext) {
    ctx.set_ecdh_auto(true).unwrap();
}

#[cfg(not(feature = "ecdh"))]
fn set_ecdh(ctx: &mut SslContext) {
    let _ = ctx;
}

fn set_fs(ctx: &mut SslContext) {
    let p = BigNum::from_hex_str("87A8E61DB4B6663CFFBBD19C651959998CEEF608660DD0F25D2CEED4435E3B00E00DF8F1D61957D4FAF7DF4561B2AA3016C3D91134096FAA3BF4296D830E9A7C209E0C6497517ABD5A8A9D306BCF67ED91F9E6725B4758C022E0B1EF4275BF7B6C5BFC11D45F9088B941F54EB1E59BB8BC39A0BF12307F5C4FDB70C581B23F76B63ACAE1CAA6B7902D52526735488A0EF13C6D9A51BFA4AB3AD8347796524D8EF6A167B5A41825D967E144E5140564251CCACB83E6B486F6B3CA3F7971506026C0B857F689962856DED4010ABD0BE621C3A3960A54E710C375F26375D7014103A4B54330C198AF126116D2276E11715F693877FAD7EF09CADB094AE91E1A1597").unwrap();
    let g = BigNum::from_hex_str("3FB32C9B73134D0B2E77506660EDBD484CA7B18F21EF205407F4793A1A0BA12510DBC15077BE463FFF4FED4AAC0BB555BE3A6C1B0C6B47B1BC3773BF7E8C6F62901228F8C28CBB18A55AE31341000A650196F931C77A57F2DDF463E5E9EC144B777DE62AAAB8A8628AC376D282D6ED3864E67982428EBC831D14348F6F2F9193B5045AF2767164E1DFC967C1FB3F2E55A4BD1BFFE83B9C80D052B985D182EA0ADB2A3B7313D3FE14C8484B1E052588B9B7D2BBD2DF016199ECD06E1557CD0915B3353BBB64E0EC377FD028370DF92B52C7891428CDC67EB6184B523D1DB246C32F63078490F00EF8D647D148D47954515E2327CFEF98C582664B4C0F6CC41659").unwrap();
    let q = BigNum::from_hex_str("8CF83642A709A097B447997640129DA299B1A47D1EB3750BA308B0FE64F5FBD3").unwrap();
    let dh = DH::from_params(p, g, q).unwrap();
    ctx.set_tmp_dh(dh).unwrap();
    set_ecdh(ctx);
}
<commit_msg>We don't need no Arc for the Merger in TlsOutput<commit_after>use flowgger::config::Config;
use flowgger::merger::Merger;
use openssl::bn::BigNum;
use openssl::dh::DH;
use openssl::ssl::*;
use openssl::x509::X509FileType;
use std::error::Error;
use std::io;
use std::io::{stderr, BufWriter, ErrorKind, Write};
use std::net::TcpStream;
use std::path::{Path, PathBuf};
use std::sync::mpsc::Receiver;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
use super::Output;

const DEFAULT_CIPHERS: &'static str = "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA";
const DEFAULT_CONNECT: &'static str = "127.0.0.1:6514";
const DEFAULT_SLEEP_AFTER_CONNECTION_FAILURE: u32 = 1000;
const TLS_DEFAULT_TIMEOUT: u64 = 3600;
const TLS_DEFAULT_THREADS: u32 = 1;

pub struct TlsOutput {
    config: TlsConfig,
    threads: u32
}

#[derive(Clone)]
struct TlsConfig {
    timeout: Option<Duration>,
    connect: String
}

struct TlsWorker {
    arx: Arc<Mutex<Receiver<Vec<u8>>>>,
    merger: Option<Box<Merger + Send>>,
    config: TlsConfig
}

impl TlsWorker {
    fn new(arx: Arc<Mutex<Receiver<Vec<u8>>>>, merger: Option<Box<Merger + Send>>, config: TlsConfig) -> TlsWorker {
        TlsWorker {
            arx: arx,
            merger: merger,
            config: config
        }
    }

    fn handle_connection(&self, connect: &str) -> io::Result<()> {
        let client = try!(new_tcp(connect));
        let _ = writeln!(stderr(), "Connected to {}", connect);
        let tls_method = SslMethod::Sslv23;
        let mut ctx = SslContext::new(tls_method).unwrap();
        let ciphers = DEFAULT_CIPHERS;
        set_fs(&mut ctx);
        ctx.set_cipher_list(&ciphers).unwrap();
        let sslclient = match SslStream::connect(&ctx, client) {
            Err(_) => return Err(io::Error::new(io::ErrorKind::ConnectionAborted, "SSL handshake aborted by the server")),
            Ok(sslclient) => sslclient
        };
        let _ = writeln!(stderr(), "Completed SSL handshake with {}", connect);
        let mut writer = BufWriter::new(sslclient);
        let merger = &self.merger;
        loop {
            let mut bytes = match { self.arx.lock().unwrap().recv() } {
                Ok(line) => line,
                Err(_) => return Err(io::Error::new(io::ErrorKind::Other, "Cannot read the message queue any more"))
            };
            if let Some(ref merger) = *merger {
                merger.frame(&mut bytes);
            }
            match writer.write_all(&bytes) {
                Ok(_) => { },
                Err(e) => match e.kind() {
                    ErrorKind::Interrupted => continue,
                    _ => return Err(e)
                }
            };
        }
    }

    fn run(self) {
        loop {
            let ref connect = self.config.connect;
            if let Err(e) = self.handle_connection(&connect) {
                match e.kind() {
                    ErrorKind::ConnectionRefused => {
                        let _ = writeln!(stderr(), "Connection to {} refused", connect);
                    }
                    ErrorKind::ConnectionAborted | ErrorKind::ConnectionReset => {
                        let _ = writeln!(stderr(), "Connection to {} aborted by the server", connect);
                    }
                    _ => {
                        let _ = writeln!(stderr(), "Error while communicating with {} - {}", connect, e);
                    }
                }
            }
            thread::sleep_ms(DEFAULT_SLEEP_AFTER_CONNECTION_FAILURE);
            let _ = writeln!(stderr(), "Attempting to reconnect");
        }
    }
}

fn new_tcp(connect: &str) -> Result<TcpStream, io::Error> {
    loop {
        match TcpStream::connect(connect) {
            Ok(stream) => return Ok(stream),
            Err(e) => {
                return Err(e);
            }
        }
    }
}

impl TlsOutput {
    pub fn new(config: &Config) -> TlsOutput {
        let connect = config.lookup("output.connect").map_or(DEFAULT_CONNECT, |x|x.as_str().
            expect("input.listen must be an ip:port string")).to_owned();
        let timeout = config.lookup("output.tls_timeout").
            map_or(TLS_DEFAULT_TIMEOUT, |x| x.as_integer().
                expect("output.tls_timeout must be an unsigned integer") as u64);
        let threads = config.lookup("output.tls_threads").
            map_or(TLS_DEFAULT_THREADS, |x| x.as_integer().
                expect("output.tls_threads must be a 32-bit integer") as u32);
        let tls_config = TlsConfig {
            connect: connect,
            timeout: Some(Duration::from_secs(timeout))
        };
        TlsOutput {
            config: tls_config,
            threads: threads
        }
    }
}

impl Output for TlsOutput {
    fn start(&self, arx: Arc<Mutex<Receiver<Vec<u8>>>>, merger: Option<Box<Merger>>) {
        for _ in 0..self.threads {
            let arx = arx.clone();
            let config = self.config.clone();
            let merger = match merger {
                Some(ref merger) => Some(merger.clone_boxed()) as Option<Box<Merger + Send>>,
                None => None
            };
            thread::spawn(move || {
                let worker = TlsWorker::new(arx, merger, config);
                worker.run();
            });
        }
    }
}

#[cfg(feature = "ecdh")]
fn set_ecdh(ctx: &mut SslContext) {
    ctx.set_ecdh_auto(true).unwrap();
}

#[cfg(not(feature = "ecdh"))]
fn set_ecdh(ctx: &mut SslContext) {
    let _ = ctx;
}

fn set_fs(ctx: &mut SslContext) {
    let p = BigNum::from_hex_str("87A8E61DB4B6663CFFBBD19C651959998CEEF608660DD0F25D2CEED4435E3B00E00DF8F1D61957D4FAF7DF4561B2AA3016C3D91134096FAA3BF4296D830E9A7C209E0C6497517ABD5A8A9D306BCF67ED91F9E6725B4758C022E0B1EF4275BF7B6C5BFC11D45F9088B941F54EB1E59BB8BC39A0BF12307F5C4FDB70C581B23F76B63ACAE1CAA6B7902D52526735488A0EF13C6D9A51BFA4AB3AD8347796524D8EF6A167B5A41825D967E144E5140564251CCACB83E6B486F6B3CA3F7971506026C0B857F689962856DED4010ABD0BE621C3A3960A54E710C375F26375D7014103A4B54330C198AF126116D2276E11715F693877FAD7EF09CADB094AE91E1A1597").unwrap();
    let g = BigNum::from_hex_str("3FB32C9B73134D0B2E77506660EDBD484CA7B18F21EF205407F4793A1A0BA12510DBC15077BE463FFF4FED4AAC0BB555BE3A6C1B0C6B47B1BC3773BF7E8C6F62901228F8C28CBB18A55AE31341000A650196F931C77A57F2DDF463E5E9EC144B777DE62AAAB8A8628AC376D282D6ED3864E67982428EBC831D14348F6F2F9193B5045AF2767164E1DFC967C1FB3F2E55A4BD1BFFE83B9C80D052B985D182EA0ADB2A3B7313D3FE14C8484B1E052588B9B7D2BBD2DF016199ECD06E1557CD0915B3353BBB64E0EC377FD028370DF92B52C7891428CDC67EB6184B523D1DB246C32F63078490F00EF8D647D148D47954515E2327CFEF98C582664B4C0F6CC41659").unwrap();
    let q = BigNum::from_hex_str("8CF83642A709A097B447997640129DA299B1A47D1EB3750BA308B0FE64F5FBD3").unwrap();
    let dh = DH::from_params(p, g, q).unwrap();
    ctx.set_tmp_dh(dh).unwrap();
    set_ecdh(ctx);
}
<|endoftext|>


<commit_before>use autograd::{Function, FuncIntf, FuncDelegate, FIWrap};
use tensor::{TensorKindList, OptTensorKindList, TensorKind};

#[builder(pattern="owned")]
#[derive(Builder, Clone)]
pub struct MaxPoolFArgs {
    // just for code re-use
    #[builder(default="vec![1]")]
    pub kernel_size: Vec<i32>,
    pub stride: Vec<i32>,
    pub padding: Vec<i32>,
    pub dilation: Vec<i32>,
    #[builder(default="false")]
    pub ceil_mode: bool,
    #[builder(default="false")]
    pub return_indices: bool,
}

pub struct MaxPool1dArgs {
    pub v: MaxPoolFArgs,
}
pub struct MaxPool2dArgs {
    pub v: MaxPoolFArgs,
}
pub struct MaxPool3dArgs {
    pub v: MaxPoolFArgs,
}

impl Default for MaxPool1dArgs {
    fn default() -> Self {
        let args = MaxPoolFArgsBuilder::default()
            .stride(vec![0])
            .padding(vec![0])
            .dilation(vec![1])
            .build()
            .unwrap();
        MaxPool1dArgs { v: args }
    }
}

impl Default for MaxPool2dArgs {
    fn default() -> Self {
        let args = MaxPoolFArgsBuilder::default()
            .stride(vec![0])
            .padding(vec![0, 0])
            .dilation(vec![1, 1])
            .build()
            .unwrap();
        MaxPool2dArgs { v: args }
    }
}

impl Default for MaxPool3dArgs {
    fn default() -> Self {
        let args = MaxPoolFArgsBuilder::default()
            .stride(vec![0])
            .padding(vec![0, 0, 0])
            .dilation(vec![1, 1, 1])
            .build()
            .unwrap();
        MaxPool3dArgs { v: args }
    }
}

impl_func_args!(MaxPool2d, MaxPoolFArgs);

impl FuncIntf for MaxPool2d {
    fn forward(&mut self, input: &mut TensorKindList) -> TensorKindList {
        if self.args.stride[0] == 0 {
            self.args.stride = self.args.kernel_size.clone()
        }
        let p = self.args.clone();
        let mut input = input.remove(0);
        let mut backend = input.backend();
        let mut indices: TensorKind = ::torch::long_tensor(input.size()).into();
        let mut output = input.new(()).resize_as_(&input);
        backend.SpatialDilatedMaxPooling_updateOutput(&mut input,
                                                      &mut output,
                                                      &mut indices,
                                                      p.kernel_size[1],
                                                      p.kernel_size[0],
                                                      p.stride[1],
                                                      p.stride[0],
                                                      p.padding[1],
                                                      p.padding[0],
                                                      p.dilation[1],
                                                      p.dilation[0],
                                                      p.ceil_mode);
        let v = if p.return_indices {
            self.save_for_backward(&vec![input, indices.clone()]);
            self.mark_non_differentiable(&vec![indices.clone()]);
            vec![output, indices]
        } else {
            self.save_for_backward(&vec![input]);
            self.saved_tensors.push(indices);
            vec![output]
        };
        v
    }
    fn backward(&mut self, mut input: &mut OptTensorKindList) -> OptTensorKindList {
        unimplemented!()
    }
}
<commit_msg>implement backwards for MoxPool2D<commit_after>use autograd::{Function, FuncIntf, FuncDelegate, FIWrap};
use tensor::{TensorKindList, OptTensorKindList, TensorKind};

#[builder(pattern="owned")]
#[derive(Builder, Clone)]
pub struct MaxPoolFArgs {
    // just for code re-use
    #[builder(default="vec![1]")]
    pub kernel_size: Vec<i32>,
    pub stride: Vec<i32>,
    pub padding: Vec<i32>,
    pub dilation: Vec<i32>,
    #[builder(default="false")]
    pub ceil_mode: bool,
    #[builder(default="false")]
    pub return_indices: bool,
}

pub struct MaxPool1dArgs {
    pub v: MaxPoolFArgs,
}
pub struct MaxPool2dArgs {
    pub v: MaxPoolFArgs,
}
pub struct MaxPool3dArgs {
    pub v: MaxPoolFArgs,
}

impl Default for MaxPool1dArgs {
    fn default() -> Self {
        let args = MaxPoolFArgsBuilder::default()
            .stride(vec![0])
            .padding(vec![0])
            .dilation(vec![1])
            .build()
            .unwrap();
        MaxPool1dArgs { v: args }
    }
}

impl Default for MaxPool2dArgs {
    fn default() -> Self {
        let args = MaxPoolFArgsBuilder::default()
            .stride(vec![0])
            .padding(vec![0, 0])
            .dilation(vec![1, 1])
            .build()
            .unwrap();
        MaxPool2dArgs { v: args }
    }
}

impl Default for MaxPool3dArgs {
    fn default() -> Self {
        let args = MaxPoolFArgsBuilder::default()
            .stride(vec![0])
            .padding(vec![0, 0, 0])
            .dilation(vec![1, 1, 1])
            .build()
            .unwrap();
        MaxPool3dArgs { v: args }
    }
}

impl_func_args!(MaxPool2d, MaxPoolFArgs);

impl FuncIntf for MaxPool2d {
    fn forward(&mut self, input: &mut TensorKindList) -> TensorKindList {
        if self.args.stride[0] == 0 {
            self.args.stride = self.args.kernel_size.clone()
        }
        let p = self.args.clone();
        let mut input = input.remove(0);
        let mut backend = input.backend();
        let mut indices: TensorKind = ::torch::long_tensor(input.size()).into();
        let mut output = input.new(()).resize_as_(&input);
        backend.SpatialDilatedMaxPooling_updateOutput(&mut input,
                                                      &mut output,
                                                      &mut indices,
                                                      p.kernel_size[1],
                                                      p.kernel_size[0],
                                                      p.stride[1],
                                                      p.stride[0],
                                                      p.padding[1],
                                                      p.padding[0],
                                                      p.dilation[1],
                                                      p.dilation[0],
                                                      p.ceil_mode);
        let v = if p.return_indices {
            self.save_for_backward(&vec![input, indices.clone()]);
            self.mark_non_differentiable(&vec![indices.clone()]);
            vec![output, indices]
        } else {
            self.save_for_backward(&vec![input]);
            self.saved_tensors.push(indices);
            vec![output]
        };
        v
    }
    fn backward(&mut self, grad_output_list: &mut OptTensorKindList) -> OptTensorKindList {
        println!("MaxPool2d backward");
        let mut saved_tensors = self.saved_tensors();
        let mut grad_output = grad_output_list.remove(0).unwrap();
        let (mut input, mut indices) = if self.args.return_indices {
            (saved_tensors.remove(0), saved_tensors.remove(0))
        } else {
            (saved_tensors.remove(0), self.saved_tensors.remove(0))
        };
        let mut grad_input = grad_output.new(());
        let mut backend = input.backend();
        let p = &self.args;
        backend.SpatialDilatedMaxPooling_updateGradInput(&mut input, &mut grad_output, &mut grad_input, &mut indices,
                                                         p.kernel_size[1], p.kernel_size[0],
                                                         p.stride[1], p.stride[0],
                                                         p.padding[1], p.padding[0],
                                                         p.dilation[1], p.dilation[0],
                                                         p.ceil_mode);
        vec![Some(grad_input)]
    }
}
<|endoftext|>


<commit_before>// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0

use serde::{Deserialize, Serialize};
use thiserror::Error;

#[derive(Clone, Debug, Deserialize, Error, PartialEq, Serialize)]
/// Different reasons for proposal rejection
pub enum Error {
    #[error("Provided epoch, {0}, does not match expected epoch, {1}")]
    IncorrectEpoch(u64, u64),
    #[error("block has next round that wraps around: {0}")]
    IncorrectRound(u64),
    #[error("Provided round, {0}, is incompatible with last voted round, {1}")]
    IncorrectLastVotedRound(u64, u64),
    #[error("Provided round, {0}, is incompatible with preferred round, {1}")]
    IncorrectPreferredRound(u64, u64),
    #[error("Unable to verify that the new tree extneds the parent: {0}")]
    InvalidAccumulatorExtension(String),
    #[error("Invalid EpochChangeProof: {0}")]
    InvalidEpochChangeProof(String),
    #[error("Internal error: {0}")]
    InternalError(String),
    #[error("No next_epoch_state specified in the provided Ledger Info")]
    InvalidLedgerInfo,
    #[error("Invalid proposal: {}", {0})]
    InvalidProposal(String),
    #[error("Invalid QC: {}", {0})]
    InvalidQuorumCertificate(String),
    #[error("{0} is not set, SafetyRules is not initialized")]
    NotInitialized(String),
    #[error("Error returned by secure storage: {0}")]
    SecureStorageError(String),
    #[error("Serialization error: {0}")]
    SerializationError(String),
    #[error("Vote proposal missing expected signature")]
    VoteProposalSignatureNotFound,
}

impl From<lcs::Error> for Error {
    fn from(error: lcs::Error) -> Self {
        Self::SerializationError(format!("{}", error))
    }
}

impl From<libra_secure_net::Error> for Error {
    fn from(error: libra_secure_net::Error) -> Self {
        Self::InternalError(error.to_string())
    }
}

impl From<libra_secure_storage::Error> for Error {
    fn from(error: libra_secure_storage::Error) -> Self {
        Self::SecureStorageError(error.to_string())
    }
}
<commit_msg>[easy][safety-rules] fix the error representation<commit_after>// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0

use serde::{Deserialize, Serialize};
use thiserror::Error;

#[derive(Clone, Debug, Deserialize, Error, PartialEq, Serialize)]
/// Different reasons for proposal rejection
pub enum Error {
    #[error("Provided epoch, {0}, does not match expected epoch, {1}")]
    IncorrectEpoch(u64, u64),
    #[error("block has next round that wraps around: {0}")]
    IncorrectRound(u64),
    #[error("Provided round, {0}, is incompatible with last voted round, {1}")]
    IncorrectLastVotedRound(u64, u64),
    #[error("Provided round, {0}, is incompatible with preferred round, {1}")]
    IncorrectPreferredRound(u64, u64),
    #[error("Unable to verify that the new tree extneds the parent: {0}")]
    InvalidAccumulatorExtension(String),
    #[error("Invalid EpochChangeProof: {0}")]
    InvalidEpochChangeProof(String),
    #[error("Internal error: {0}")]
    InternalError(String),
    #[error("No next_epoch_state specified in the provided Ledger Info")]
    InvalidLedgerInfo,
    #[error("Invalid proposal: {0}")]
    InvalidProposal(String),
    #[error("Invalid QC: {0}")]
    InvalidQuorumCertificate(String),
    #[error("{0} is not set, SafetyRules is not initialized")]
    NotInitialized(String),
    #[error("Error returned by secure storage: {0}")]
    SecureStorageError(String),
    #[error("Serialization error: {0}")]
    SerializationError(String),
    #[error("Vote proposal missing expected signature")]
    VoteProposalSignatureNotFound,
}

impl From<lcs::Error> for Error {
    fn from(error: lcs::Error) -> Self {
        Self::SerializationError(format!("{}", error))
    }
}

impl From<libra_secure_net::Error> for Error {
    fn from(error: libra_secure_net::Error) -> Self {
        Self::InternalError(error.to_string())
    }
}

impl From<libra_secure_storage::Error> for Error {
    fn from(error: libra_secure_storage::Error) -> Self {
        Self::SecureStorageError(error.to_string())
    }
}
<|endoftext|>


<commit_before>// no-system-llvm
// assembly-output: emit-asm
// compile-flags: --target nvptx64-nvidia-cuda
// compile-flags: --crate-type cdylib

#![feature(no_core, lang_items, rustc_attrs)]
#![no_core]

#[rustc_builtin_macro]
macro_rules! asm {
    () => {};
}
#[rustc_builtin_macro]
macro_rules! concat {
    () => {};
}

#[lang = "sized"]
trait Sized {}
#[lang = "copy"]
trait Copy {}

type ptr = *mut u8;

impl Copy for i8 {}
impl Copy for i16 {}
impl Copy for i32 {}
impl Copy for f32 {}
impl Copy for i64 {}
impl Copy for f64 {}
impl Copy for ptr {}

#[no_mangle]
fn extern_func() {}

// CHECK-LABEL: .visible .func sym_fn()
// CHECK: // begin inline asm
// CHECK: call extern_func;
// CHECK: // end inline asm
#[no_mangle]
pub unsafe fn sym_fn() {
    asm!("call {};", sym extern_func);
}

macro_rules! check {
    ($func:ident $ty:ident $class:ident $mov:literal) => {
        #[no_mangle]
        pub unsafe fn $func(x: $ty) -> $ty {
            let y;
            asm!(concat!($mov, " {}, {};"), out($class) y, in($class) x);
            y
        }
    };
}

// CHECK-LABEL: .visible .func (.param .b32 func_retval0) reg16_i8
// CHECK: // begin inline asm
// CHECK: mov.i16 %{{[a-z0-9]+}}, %{{[a-z0-9]+}};
// CHECK: // end inline asm
check!(reg16_i8 i8 reg16 "mov.i16");

// CHECK-LABEL: .visible .func (.param .b32 func_retval0) reg16_i16
// CHECK: // begin inline asm
// CHECK: mov.i16 %{{[a-z0-9]+}}, %{{[a-z0-9]+}};
// CHECK: // end inline asm
check!(reg16_i16 i16 reg16 "mov.i16");

// CHECK-LABEL: .visible .func (.param .b32 func_retval0) reg32_i8
// CHECK: // begin inline asm
// CHECK: mov.i32 %{{[a-z0-9]+}}, %{{[a-z0-9]+}};
// CHECK: // end inline asm
check!(reg32_i8 i8 reg32 "mov.i32");

// CHECK-LABEL: .visible .func (.param .b32 func_retval0) reg32_i16
// CHECK: // begin inline asm
// CHECK: mov.i32 %{{[a-z0-9]+}}, %{{[a-z0-9]+}};
// CHECK: // end inline asm
check!(reg32_i16 i16 reg32 "mov.i32");

// CHECK-LABEL: .visible .func (.param .b32 func_retval0) reg32_i32
// CHECK: // begin inline asm
// CHECK: mov.i32 %{{[a-z0-9]+}}, %{{[a-z0-9]+}};
// CHECK: // end inline asm
check!(reg32_i32 i32 reg32 "mov.i32");

// CHECK-LABEL: .visible .func (.param .b32 func_retval0) reg32_f32
// CHECK: // begin inline asm
// CHECK: mov.i32 %{{[a-z0-9]+}}, %{{[a-z0-9]+}};
// CHECK: // end inline asm
check!(reg32_f32 f32 reg32 "mov.i32");

// CHECK-LABEL: .visible .func (.param .b32 func_retval0) reg64_i8
// CHECK: // begin inline asm
// CHECK: mov.i64 %{{[a-z0-9]+}}, %{{[a-z0-9]+}};
// CHECK: // end inline asm
check!(reg64_i8 i8 reg64 "mov.i64");

// CHECK-LABEL: .visible .func (.param .b32 func_retval0) reg64_i16
// CHECK: // begin inline asm
// CHECK: mov.i64 %{{[a-z0-9]+}}, %{{[a-z0-9]+}};
// CHECK: // end inline asm
check!(reg64_i16 i16 reg64 "mov.i64");

// CHECK-LABEL: .visible .func (.param .b32 func_retval0) reg64_i32
// CHECK: // begin inline asm
// CHECK: mov.i64 %{{[a-z0-9]+}}, %{{[a-z0-9]+}};
// CHECK: // end inline asm
check!(reg64_i32 i32 reg64 "mov.i64");

// CHECK-LABEL: .visible .func (.param .b32 func_retval0) reg64_f32
// CHECK: // begin inline asm
// CHECK: mov.i64 %{{[a-z0-9]+}}, %{{[a-z0-9]+}};
// CHECK: // end inline asm
check!(reg64_f32 f32 reg64 "mov.i64");

// CHECK-LABEL: .visible .func (.param .b64 func_retval0) reg64_i64
// CHECK: // begin inline asm
// CHECK: mov.i64 %{{[a-z0-9]+}}, %{{[a-z0-9]+}};
// CHECK: // end inline asm
check!(reg64_i64 i64 reg64 "mov.i64");

// CHECK-LABEL: .visible .func (.param .b64 func_retval0) reg64_f64
// CHECK: // begin inline asm
// CHECK: mov.i64 %{{[a-z0-9]+}}, %{{[a-z0-9]+}};
// CHECK: // end inline asm
check!(reg64_f64 f64 reg64 "mov.i64");

// CHECK-LABEL: .visible .func (.param .b64 func_retval0) reg64_ptr
// CHECK: // begin inline asm
// CHECK: mov.i64 %{{[a-z0-9]+}}, %{{[a-z0-9]+}};
// CHECK: // end inline asm
check!(reg64_ptr ptr reg64 "mov.i64");
<commit_msg>Added comment about static variables<commit_after>// no-system-llvm
// assembly-output: emit-asm
// compile-flags: --target nvptx64-nvidia-cuda
// compile-flags: --crate-type cdylib

#![feature(no_core, lang_items, rustc_attrs)]
#![no_core]

#[rustc_builtin_macro]
macro_rules! asm {
    () => {};
}
#[rustc_builtin_macro]
macro_rules! concat {
    () => {};
}

#[lang = "sized"]
trait Sized {}
#[lang = "copy"]
trait Copy {}

type ptr = *mut u8;

impl Copy for i8 {}
impl Copy for i16 {}
impl Copy for i32 {}
impl Copy for f32 {}
impl Copy for i64 {}
impl Copy for f64 {}
impl Copy for ptr {}

// NVPTX does not support static variables
#[no_mangle]
fn extern_func() {}

// CHECK-LABEL: .visible .func sym_fn()
// CHECK: // begin inline asm
// CHECK: call extern_func;
// CHECK: // end inline asm
#[no_mangle]
pub unsafe fn sym_fn() {
    asm!("call {};", sym extern_func);
}

macro_rules! check {
    ($func:ident $ty:ident $class:ident $mov:literal) => {
        #[no_mangle]
        pub unsafe fn $func(x: $ty) -> $ty {
            let y;
            asm!(concat!($mov, " {}, {};"), out($class) y, in($class) x);
            y
        }
    };
}

// CHECK-LABEL: .visible .func (.param .b32 func_retval0) reg16_i8
// CHECK: // begin inline asm
// CHECK: mov.i16 %{{[a-z0-9]+}}, %{{[a-z0-9]+}};
// CHECK: // end inline asm
check!(reg16_i8 i8 reg16 "mov.i16");

// CHECK-LABEL: .visible .func (.param .b32 func_retval0) reg16_i16
// CHECK: // begin inline asm
// CHECK: mov.i16 %{{[a-z0-9]+}}, %{{[a-z0-9]+}};
// CHECK: // end inline asm
check!(reg16_i16 i16 reg16 "mov.i16");

// CHECK-LABEL: .visible .func (.param .b32 func_retval0) reg32_i8
// CHECK: // begin inline asm
// CHECK: mov.i32 %{{[a-z0-9]+}}, %{{[a-z0-9]+}};
// CHECK: // end inline asm
check!(reg32_i8 i8 reg32 "mov.i32");

// CHECK-LABEL: .visible .func (.param .b32 func_retval0) reg32_i16
// CHECK: // begin inline asm
// CHECK: mov.i32 %{{[a-z0-9]+}}, %{{[a-z0-9]+}};
// CHECK: // end inline asm
check!(reg32_i16 i16 reg32 "mov.i32");

// CHECK-LABEL: .visible .func (.param .b32 func_retval0) reg32_i32
// CHECK: // begin inline asm
// CHECK: mov.i32 %{{[a-z0-9]+}}, %{{[a-z0-9]+}};
// CHECK: // end inline asm
check!(reg32_i32 i32 reg32 "mov.i32");

// CHECK-LABEL: .visible .func (.param .b32 func_retval0) reg32_f32
// CHECK: // begin inline asm
// CHECK: mov.i32 %{{[a-z0-9]+}}, %{{[a-z0-9]+}};
// CHECK: // end inline asm
check!(reg32_f32 f32 reg32 "mov.i32");

// CHECK-LABEL: .visible .func (.param .b32 func_retval0) reg64_i8
// CHECK: // begin inline asm
// CHECK: mov.i64 %{{[a-z0-9]+}}, %{{[a-z0-9]+}};
// CHECK: // end inline asm
check!(reg64_i8 i8 reg64 "mov.i64");

// CHECK-LABEL: .visible .func (.param .b32 func_retval0) reg64_i16
// CHECK: // begin inline asm
// CHECK: mov.i64 %{{[a-z0-9]+}}, %{{[a-z0-9]+}};
// CHECK: // end inline asm
check!(reg64_i16 i16 reg64 "mov.i64");

// CHECK-LABEL: .visible .func (.param .b32 func_retval0) reg64_i32
// CHECK: // begin inline asm
// CHECK: mov.i64 %{{[a-z0-9]+}}, %{{[a-z0-9]+}};
// CHECK: // end inline asm
check!(reg64_i32 i32 reg64 "mov.i64");

// CHECK-LABEL: .visible .func (.param .b32 func_retval0) reg64_f32
// CHECK: // begin inline asm
// CHECK: mov.i64 %{{[a-z0-9]+}}, %{{[a-z0-9]+}};
// CHECK: // end inline asm
check!(reg64_f32 f32 reg64 "mov.i64");

// CHECK-LABEL: .visible .func (.param .b64 func_retval0) reg64_i64
// CHECK: // begin inline asm
// CHECK: mov.i64 %{{[a-z0-9]+}}, %{{[a-z0-9]+}};
// CHECK: // end inline asm
check!(reg64_i64 i64 reg64 "mov.i64");

// CHECK-LABEL: .visible .func (.param .b64 func_retval0) reg64_f64
// CHECK: // begin inline asm
// CHECK: mov.i64 %{{[a-z0-9]+}}, %{{[a-z0-9]+}};
// CHECK: // end inline asm
check!(reg64_f64 f64 reg64 "mov.i64");

// CHECK-LABEL: .visible .func (.param .b64 func_retval0) reg64_ptr
// CHECK: // begin inline asm
// CHECK: mov.i64 %{{[a-z0-9]+}}, %{{[a-z0-9]+}};
// CHECK: // end inline asm
check!(reg64_ptr ptr reg64 "mov.i64");
<|endoftext|>