<commit_before><commit_msg>indentation perfection<commit_after><|endoftext|>


<commit_before><commit_msg>Add test for unnecessary panic branches<commit_after>//! Tests that generators that cannot return or unwind don't have unnecessary
//! panic branches.

// compile-flags: -Zno-landing-pads

#![feature(generators, generator_trait)]

struct HasDrop;

impl Drop for HasDrop {
    fn drop(&mut self) {}
}

fn callee() {}

fn main() {
    let _gen = |_x: u8| {
        let _d = HasDrop;
        loop {
            yield;
            callee();
        }
    };
}

// END RUST SOURCE

// START rustc.main-{{closure}}.generator_resume.0.mir
// bb0: {
//     ...
//     switchInt(move _11) -> [0u32: bb1, 3u32: bb5, otherwise: bb6];
// }
// ...
// END rustc.main-{{closure}}.generator_resume.0.mir
<|endoftext|>


<commit_before>use std::fs::File;
use std::io::Read;
use std::path::Path;
use std::fmt::Display;
use std::env;
use std::collections::HashMap;

use clap::ArgMatches;
use toml::{Value, Parser};
use semver;

use git;
use CLOG_CONFIG_FILE;

pub struct ClogConfig {
    pub grep: String,
    pub format: String,
    pub repo: String,
    pub version: String,
    pub subtitle: String,
    pub from: String,
    pub to: String,
    pub changelog: String,
    pub section_map: HashMap<String, Vec<String>>
}

pub type ConfigResult = Result<ClogConfig, Box<Display>>;

impl ClogConfig {
    pub fn from_matches(matches: &ArgMatches) -> ConfigResult {
        // compute version early, so we can exit on error
        let version =  {
            // less typing later...
            let (major, minor, patch) = (matches.is_present("major"), matches.is_present("minor"), matches.is_present("patch"));
            if matches.is_present("ver") {
                matches.value_of("ver").unwrap().to_owned()
            } else if major || minor || patch {
                let mut had_v = false;
                let v_string = git::get_latest_tag_ver();
                let first_char = v_string.chars().nth(0).unwrap_or(' ');
                let v_slice = if first_char == 'v' || first_char == 'V' {
                    had_v = true;
                    v_string.trim_left_matches(|c| c == 'v' || c == 'V')
                } else {
                    &v_string[..]
                };
                match semver::Version::parse(v_slice) {
                    Ok(ref mut v) => {
                        // if-else may be quicker, but it's longer mentally, and this isn't slow
                        match (major, minor, patch) {
                            (true,_,_) => { v.major += 1; v.minor = 0; v.patch = 0; },
                            (_,true,_) => { v.minor += 1; v.patch = 0; },
                            (_,_,true) => { v.patch += 1; },
                            _          => unreachable!()
                        }
                        format!("{}{}", if had_v{"v"}else{""}, v)
                    },
                    Err(e) => {
                        return Err(Box::new(format!("Error: {}\n\n\tEnsure the tag format follows Semantic Versioning such as N.N.N\n\tor set the version manually with --setversion <version>" , e )));
                    }
                }
            } else {
                // Use short hash
                (&git::get_last_commit()[0..8]).to_owned()
            }
        };

        let cwd = match env::current_dir() {
            Ok(d)  => d,
            Err(e) => return Err(Box::new(e)),
        };

        let mut sections = HashMap::new();
        sections.insert("Features".to_owned(), vec!["ft".to_owned(), "feat".to_owned()]);
        sections.insert("Bug Fixes".to_owned(), vec!["fx".to_owned(), "fix".to_owned()]);
        sections.insert("Unknown".to_owned(), vec!["unk".to_owned()]);
        sections.insert("Breaks".to_owned(), vec![]);

        let cfg_file = Path::new(&cwd).join(CLOG_CONFIG_FILE);
        let mut toml_from_latest = None;
        let mut toml_repo = None;
        let mut toml_subtitle = None;

        let mut outfile = None;

        if let Ok(ref mut toml_f) = File::open(cfg_file){
            let mut toml_s = String::with_capacity(100);

            if let Err(e) = toml_f.read_to_string(&mut toml_s) {
                return Err(Box::new(e))
            }

            toml_s.shrink_to_fit();

            let mut toml = Parser::new(&toml_s[..]);

            let toml_table = match toml.parse() {
                Some(table) => table,
                None        => {
                    return Err(Box::new(format!("Error parsing file {}\n\nPlease check the format or specify the options manually", CLOG_CONFIG_FILE)))
                }
            };

            let clog_table = match toml_table.get("clog") {
                Some(table) => table,
                None        => {
                    return Err(Box::new(format!("Error parsing file {}\n\nPlease check the format or specify the options manually", CLOG_CONFIG_FILE)))
                }
            };

            toml_from_latest = clog_table.lookup("from-latest-tag").unwrap_or(&Value::Boolean(false)).as_bool();
            toml_repo = match clog_table.lookup("repository") {
                Some(val) => Some(val.as_str().unwrap_or("").to_owned()),
                None      => Some("".to_owned())
            };
            toml_subtitle = match clog_table.lookup("subtitle") {
                Some(val) => Some(val.as_str().unwrap_or("").to_owned()),
                None      => Some("".to_owned())
            };
<<<<<<< HEAD
            changelog = match clog_table.lookup("changelog") {
=======
            changelog = match clog_table.lookup("outfile") {
>>>>>>> da3e9b0... fixup! feat(changelog.md): allows specifying custom file for changelog
                Some(val) => Some(val.as_str().unwrap_or("changelog.md").to_owned()),
                None      => None
            };
            match toml_table.get("sections") {
                Some(table) => {
                    match table.as_table() {
                        Some(table) => {
                            for (sec, val) in table.iter() {
                                if let Some(vec) = val.as_slice() {
                                    let alias_vec = vec.iter().map(|v| v.as_str().unwrap_or("").to_owned()).collect::<Vec<_>>();
                                    sections.insert(sec.to_owned(), alias_vec);
                                }
                            }
                        },
                        None        => ()
                    }
                },
                None        => ()
            };
        };

        let from = if matches.is_present("from-latest-tag") || toml_from_latest.unwrap_or(false) {
            git::get_latest_tag()
        } else if let Some(from) = matches.value_of("from") {
            from.to_owned()
        } else {
           "".to_owned()
        };

        let repo = match matches.value_of("repository") {
            Some(repo) => repo.to_owned(),
            None       => toml_repo.unwrap_or("".to_owned())
        };

        let subtitle = match matches.value_of("subtitle") {
            Some(title) => title.to_owned(),
            None        => toml_subtitle.unwrap_or("".to_owned())
        };

        if let Some(file) = matches.value_of("outfile") {
            outfile = Some(file.to_owned());
        }

        Ok(ClogConfig{
            grep: format!("{}BREAKING'",
                sections.values()
                        .map(|v| v.iter().fold(String::new(), |acc, al| {
                            acc + &format!("^{}|", al)[..]
                        }))
                        .fold(String::new(), |acc, al| {
                            acc + &format!("^{}|", al)[..]
                        })),
            format: "%H%n%s%n%b%n==END==".to_owned(),
            repo: repo,
            version: version,
            subtitle: subtitle,
            from: from,
            to: matches.value_of("to").unwrap_or("HEAD").to_owned(),
            changelog: outfile.unwrap_or("changelog.md".to_owned()),
            section_map: sections
        })
    }

    pub fn section_for(&self, alias: &str) -> &String {
        self.section_map.iter().filter(|&(_, v)| v.iter().any(|s| s == alias)).map(|(k, _)| k).next().unwrap_or(self.section_map.keys().filter(|&k| *k == "Unknown".to_owned()).next().unwrap())
    }
}
<commit_msg>fix(--from): fixes a bug where --from is ignored if from-latest-tag is true .clog.toml<commit_after>use std::fs::File;
use std::io::Read;
use std::path::Path;
use std::fmt::Display;
use std::env;
use std::collections::HashMap;

use clap::ArgMatches;
use toml::{Value, Parser};
use semver;

use git;
use CLOG_CONFIG_FILE;

pub struct ClogConfig {
    pub grep: String,
    pub format: String,
    pub repo: String,
    pub version: String,
    pub subtitle: String,
    pub from: String,
    pub to: String,
    pub changelog: String,
    pub section_map: HashMap<String, Vec<String>>
}

pub type ConfigResult = Result<ClogConfig, Box<Display>>;

impl ClogConfig {
    pub fn from_matches(matches: &ArgMatches) -> ConfigResult {
        // compute version early, so we can exit on error
        let version =  {
            // less typing later...
            let (major, minor, patch) = (matches.is_present("major"), matches.is_present("minor"), matches.is_present("patch"));
            if matches.is_present("ver") {
                matches.value_of("ver").unwrap().to_owned()
            } else if major || minor || patch {
                let mut had_v = false;
                let v_string = git::get_latest_tag_ver();
                let first_char = v_string.chars().nth(0).unwrap_or(' ');
                let v_slice = if first_char == 'v' || first_char == 'V' {
                    had_v = true;
                    v_string.trim_left_matches(|c| c == 'v' || c == 'V')
                } else {
                    &v_string[..]
                };
                match semver::Version::parse(v_slice) {
                    Ok(ref mut v) => {
                        // if-else may be quicker, but it's longer mentally, and this isn't slow
                        match (major, minor, patch) {
                            (true,_,_) => { v.major += 1; v.minor = 0; v.patch = 0; },
                            (_,true,_) => { v.minor += 1; v.patch = 0; },
                            (_,_,true) => { v.patch += 1; },
                            _          => unreachable!()
                        }
                        format!("{}{}", if had_v{"v"}else{""}, v)
                    },
                    Err(e) => {
                        return Err(Box::new(format!("Error: {}\n\n\tEnsure the tag format follows Semantic Versioning such as N.N.N\n\tor set the version manually with --setversion <version>" , e )));
                    }
                }
            } else {
                // Use short hash
                (&git::get_last_commit()[0..8]).to_owned()
            }
        };

        let cwd = match env::current_dir() {
            Ok(d)  => d,
            Err(e) => return Err(Box::new(e)),
        };

        let mut sections = HashMap::new();
        sections.insert("Features".to_owned(), vec!["ft".to_owned(), "feat".to_owned()]);
        sections.insert("Bug Fixes".to_owned(), vec!["fx".to_owned(), "fix".to_owned()]);
        sections.insert("Unknown".to_owned(), vec!["unk".to_owned()]);
        sections.insert("Breaks".to_owned(), vec![]);

        let cfg_file = Path::new(&cwd).join(CLOG_CONFIG_FILE);
        let mut toml_from_latest = None;
        let mut toml_repo = None;
        let mut toml_subtitle = None;

        let mut outfile = None;

        if let Ok(ref mut toml_f) = File::open(cfg_file){
            let mut toml_s = String::with_capacity(100);

            if let Err(e) = toml_f.read_to_string(&mut toml_s) {
                return Err(Box::new(e))
            }

            toml_s.shrink_to_fit();

            let mut toml = Parser::new(&toml_s[..]);

            let toml_table = match toml.parse() {
                Some(table) => table,
                None        => {
                    return Err(Box::new(format!("Error parsing file {}\n\nPlease check the format or specify the options manually", CLOG_CONFIG_FILE)))
                }
            };

            let clog_table = match toml_table.get("clog") {
                Some(table) => table,
                None        => {
                    return Err(Box::new(format!("Error parsing file {}\n\nPlease check the format or specify the options manually", CLOG_CONFIG_FILE)))
                }
            };

            toml_from_latest = clog_table.lookup("from-latest-tag").unwrap_or(&Value::Boolean(false)).as_bool();
            toml_repo = match clog_table.lookup("repository") {
                Some(val) => Some(val.as_str().unwrap_or("").to_owned()),
                None      => Some("".to_owned())
            };
            toml_subtitle = match clog_table.lookup("subtitle") {
                Some(val) => Some(val.as_str().unwrap_or("").to_owned()),
                None      => Some("".to_owned())
            };
<<<<<<< HEAD
            changelog = match clog_table.lookup("changelog") {
=======
            changelog = match clog_table.lookup("outfile") {
>>>>>>> da3e9b0... fixup! feat(changelog.md): allows specifying custom file for changelog
                Some(val) => Some(val.as_str().unwrap_or("changelog.md").to_owned()),
                None      => None
            };
            match toml_table.get("sections") {
                Some(table) => {
                    match table.as_table() {
                        Some(table) => {
                            for (sec, val) in table.iter() {
                                if let Some(vec) = val.as_slice() {
                                    let alias_vec = vec.iter().map(|v| v.as_str().unwrap_or("").to_owned()).collect::<Vec<_>>();
                                    sections.insert(sec.to_owned(), alias_vec);
                                }
                            }
                        },
                        None        => ()
                    }
                },
                None        => ()
            };
        };

        let from = if let Some(from) = matches.value_of("from") {
            from.to_owned()
        } else if matches.is_present("from-latest-tag") || toml_from_latest.unwrap_or(false) {
            git::get_latest_tag()
        } else {
           "".to_owned()
        };

        let repo = match matches.value_of("repository") {
            Some(repo) => repo.to_owned(),
            None       => toml_repo.unwrap_or("".to_owned())
        };

        let subtitle = match matches.value_of("subtitle") {
            Some(title) => title.to_owned(),
            None        => toml_subtitle.unwrap_or("".to_owned())
        };

        if let Some(file) = matches.value_of("outfile") {
            outfile = Some(file.to_owned());
        }

        Ok(ClogConfig{
            grep: format!("{}BREAKING'",
                sections.values()
                        .map(|v| v.iter().fold(String::new(), |acc, al| {
                            acc + &format!("^{}|", al)[..]
                        }))
                        .fold(String::new(), |acc, al| {
                            acc + &format!("^{}|", al)[..]
                        })),
            format: "%H%n%s%n%b%n==END==".to_owned(),
            repo: repo,
            version: version,
            subtitle: subtitle,
            from: from,
            to: matches.value_of("to").unwrap_or("HEAD").to_owned(),
            changelog: outfile.unwrap_or("changelog.md".to_owned()),
            section_map: sections
        })
    }

    pub fn section_for(&self, alias: &str) -> &String {
        self.section_map.iter().filter(|&(_, v)| v.iter().any(|s| s == alias)).map(|(k, _)| k).next().unwrap_or(self.section_map.keys().filter(|&k| *k == "Unknown".to_owned()).next().unwrap())
    }
}
<|endoftext|>


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

/*!
# Translation of inline assembly.
*/

use llvm;
use middle::trans::build::*;
use middle::trans::callee;
use middle::trans::common::*;
use middle::trans::cleanup;
use middle::trans::cleanup::CleanupMethods;
use middle::trans::expr;
use middle::trans::type_of;
use middle::trans::type_::Type;

use std::c_str::ToCStr;
use std::string::String;
use syntax::ast;
use libc::{c_uint, c_char};

// Take an inline assembly expression and splat it out via LLVM
pub fn trans_inline_asm<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ia: &ast::InlineAsm)
                                    -> Block<'blk, 'tcx> {
    let fcx = bcx.fcx;
    let mut bcx = bcx;
    let mut constraints = Vec::new();
    let mut output_types = Vec::new();

    let temp_scope = fcx.push_custom_cleanup_scope();

    let mut ext_inputs = Vec::new();
    let mut ext_constraints = Vec::new();

    // Prepare the output operands
    let outputs = ia.outputs.iter().enumerate().map(|(i, &(ref c, ref out, is_rw))| {
        constraints.push((*c).clone());

        let out_datum = unpack_datum!(bcx, expr::trans(bcx, &**out));
        output_types.push(type_of::type_of(bcx.ccx(), out_datum.ty));
        let val = out_datum.val;
        if is_rw {
            ext_inputs.push(unpack_result!(bcx, {
                callee::trans_arg_datum(bcx,
                                       expr_ty(bcx, &**out),
                                       out_datum,
                                       cleanup::CustomScope(temp_scope),
                                       callee::DontAutorefArg)
            }));
            ext_constraints.push(i.to_string());
        }
        val

    }).collect::<Vec<_>>();

    // Now the input operands
    let inputs = ia.inputs.iter().map(|&(ref c, ref input)| {
        constraints.push((*c).clone());

        let in_datum = unpack_datum!(bcx, expr::trans(bcx, &**input));
        unpack_result!(bcx, {
            callee::trans_arg_datum(bcx,
                                    expr_ty(bcx, &**input),
                                    in_datum,
                                    cleanup::CustomScope(temp_scope),
                                    callee::DontAutorefArg)
        })
    }).collect::<Vec<_>>().append(ext_inputs.as_slice());

    // no failure occurred preparing operands, no need to cleanup
    fcx.pop_custom_cleanup_scope(temp_scope);

    let mut constraints =
        String::from_str(constraints.iter()
                                    .map(|s| s.get().to_string())
                                    .chain(ext_constraints.into_iter())
                                    .collect::<Vec<String>>()
                                    .connect(",")
                                    .as_slice());

    let mut clobbers = get_clobbers();
    if !ia.clobbers.get().is_empty() && !clobbers.is_empty() {
        clobbers = format!("{},{}", ia.clobbers.get(), clobbers);
    } else {
        clobbers.push_str(ia.clobbers.get());
    }

    // Add the clobbers to our constraints list
    if clobbers.len() != 0 && constraints.len() != 0 {
        constraints.push_char(',');
        constraints.push_str(clobbers.as_slice());
    } else {
        constraints.push_str(clobbers.as_slice());
    }

    debug!("Asm Constraints: {:?}", constraints.as_slice());

    let num_outputs = outputs.len();

    // Depending on how many outputs we have, the return type is different
    let output_type = if num_outputs == 0 {
        Type::void(bcx.ccx())
    } else if num_outputs == 1 {
        *output_types.get(0)
    } else {
        Type::struct_(bcx.ccx(), output_types.as_slice(), false)
    };

    let dialect = match ia.dialect {
        ast::AsmAtt   => llvm::AD_ATT,
        ast::AsmIntel => llvm::AD_Intel
    };

    let r = ia.asm.get().with_c_str(|a| {
        constraints.as_slice().with_c_str(|c| {
            InlineAsmCall(bcx,
                          a,
                          c,
                          inputs.as_slice(),
                          output_type,
                          ia.volatile,
                          ia.alignstack,
                          dialect)
        })
    });

    // Again, based on how many outputs we have
    if num_outputs == 1 {
        Store(bcx, r, *outputs.get(0));
    } else {
        for (i, o) in outputs.iter().enumerate() {
            let v = ExtractValue(bcx, r, i);
            Store(bcx, v, *o);
        }
    }

    // Store expn_id in a metadata node so we can map LLVM errors
    // back to source locations.  See #17552.
    unsafe {
        let key = "srcloc";
        let kind = llvm::LLVMGetMDKindIDInContext(bcx.ccx().llcx(),
            key.as_ptr() as *const c_char, key.len() as c_uint);

        let val: llvm::ValueRef = C_i32(bcx.ccx(), ia.expn_id.to_llvm_cookie());

        llvm::LLVMSetMetadata(r, kind,
            llvm::LLVMMDNodeInContext(bcx.ccx().llcx(), &val, 1));
    }

    return bcx;

}

// Default per-arch clobbers
// Basically what clang does

#[cfg(target_arch = "arm")]
#[cfg(target_arch = "mips")]
#[cfg(target_arch = "mipsel")]
fn get_clobbers() -> String {
    "".to_string()
}

#[cfg(target_arch = "x86")]
#[cfg(target_arch = "x86_64")]
fn get_clobbers() -> String {
    "~{dirflag},~{fpsr},~{flags}".to_string()
}
<commit_msg>Fix librustc<commit_after>// Copyright 2012-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.

/*!
# Translation of inline assembly.
*/

use llvm;
use middle::trans::build::*;
use middle::trans::callee;
use middle::trans::common::*;
use middle::trans::cleanup;
use middle::trans::cleanup::CleanupMethods;
use middle::trans::expr;
use middle::trans::type_of;
use middle::trans::type_::Type;

use std::c_str::ToCStr;
use std::string::String;
use syntax::ast;
use libc::{c_uint, c_char};

// Take an inline assembly expression and splat it out via LLVM
pub fn trans_inline_asm<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ia: &ast::InlineAsm)
                                    -> Block<'blk, 'tcx> {
    let fcx = bcx.fcx;
    let mut bcx = bcx;
    let mut constraints = Vec::new();
    let mut output_types = Vec::new();

    let temp_scope = fcx.push_custom_cleanup_scope();

    let mut ext_inputs = Vec::new();
    let mut ext_constraints = Vec::new();

    // Prepare the output operands
    let outputs = ia.outputs.iter().enumerate().map(|(i, &(ref c, ref out, is_rw))| {
        constraints.push((*c).clone());

        let out_datum = unpack_datum!(bcx, expr::trans(bcx, &**out));
        output_types.push(type_of::type_of(bcx.ccx(), out_datum.ty));
        let val = out_datum.val;
        if is_rw {
            ext_inputs.push(unpack_result!(bcx, {
                callee::trans_arg_datum(bcx,
                                       expr_ty(bcx, &**out),
                                       out_datum,
                                       cleanup::CustomScope(temp_scope),
                                       callee::DontAutorefArg)
            }));
            ext_constraints.push(i.to_string());
        }
        val

    }).collect::<Vec<_>>();

    // Now the input operands
    let inputs = ia.inputs.iter().map(|&(ref c, ref input)| {
        constraints.push((*c).clone());

        let in_datum = unpack_datum!(bcx, expr::trans(bcx, &**input));
        unpack_result!(bcx, {
            callee::trans_arg_datum(bcx,
                                    expr_ty(bcx, &**input),
                                    in_datum,
                                    cleanup::CustomScope(temp_scope),
                                    callee::DontAutorefArg)
        })
    }).collect::<Vec<_>>().append(ext_inputs.as_slice());

    // no failure occurred preparing operands, no need to cleanup
    fcx.pop_custom_cleanup_scope(temp_scope);

    let mut constraints =
        String::from_str(constraints.iter()
                                    .map(|s| s.get().to_string())
                                    .chain(ext_constraints.into_iter())
                                    .collect::<Vec<String>>()
                                    .connect(",")
                                    .as_slice());

    let mut clobbers = get_clobbers();
    if !ia.clobbers.get().is_empty() && !clobbers.is_empty() {
        clobbers = format!("{},{}", ia.clobbers.get(), clobbers);
    } else {
        clobbers.push_str(ia.clobbers.get());
    }

    // Add the clobbers to our constraints list
    if clobbers.len() != 0 && constraints.len() != 0 {
        constraints.push_char(',');
        constraints.push_str(clobbers.as_slice());
    } else {
        constraints.push_str(clobbers.as_slice());
    }

    debug!("Asm Constraints: {:?}", constraints.as_slice());

    let num_outputs = outputs.len();

    // Depending on how many outputs we have, the return type is different
    let output_type = if num_outputs == 0 {
        Type::void(bcx.ccx())
    } else if num_outputs == 1 {
        *output_types.get(0)
    } else {
        Type::struct_(bcx.ccx(), output_types.as_slice(), false)
    };

    let dialect = match ia.dialect {
        ast::AsmAtt   => llvm::AD_ATT,
        ast::AsmIntel => llvm::AD_Intel
    };

    let r = ia.asm.get().with_c_str(|a| {
        constraints.as_slice().with_c_str(|c| {
            InlineAsmCall(bcx,
                          a,
                          c,
                          inputs.as_slice(),
                          output_type,
                          ia.volatile,
                          ia.alignstack,
                          dialect)
        })
    });

    // Again, based on how many outputs we have
    if num_outputs == 1 {
        Store(bcx, r, *outputs.get(0));
    } else {
        for (i, o) in outputs.iter().enumerate() {
            let v = ExtractValue(bcx, r, i);
            Store(bcx, v, *o);
        }
    }

    // Store expn_id in a metadata node so we can map LLVM errors
    // back to source locations.  See #17552.
    unsafe {
        let key = "srcloc";
        let kind = llvm::LLVMGetMDKindIDInContext(bcx.ccx().llcx(),
            key.as_ptr() as *const c_char, key.len() as c_uint);

        let val: llvm::ValueRef = C_i32(bcx.ccx(), ia.expn_id.to_llvm_cookie());

        llvm::LLVMSetMetadata(r, kind,
            llvm::LLVMMDNodeInContext(bcx.ccx().llcx(), &val, 1));
    }

    return bcx;

}

// Default per-arch clobbers
// Basically what clang does

#[cfg(any(target_arch = "arm",
          target_arch = "mips",
          target_arch = "mipsel"))]
fn get_clobbers() -> String {
    "".to_string()
}

#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn get_clobbers() -> String {
    "~{dirflag},~{fpsr},~{flags}".to_string()
}
<|endoftext|>


<commit_before><commit_msg>style: convert NS_STYLE_VISIBILITY_* to an enum class in nsStyleConsts.h<commit_after><|endoftext|>


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

#![feature(simd)]

#[simd]
struct T(f64, f64, f64);

static X: T = T(0.0, 0.0, 0.0);

fn main() {
    let _ = X;
}
<|endoftext|>


<commit_before><commit_msg>[compiler][causality] Generating the dependencies of spacetime expressions.<commit_after>// Copyright 2018 Pierre Talbot (IRCAM)

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

//     http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/// We capture the causal dependencies generated by expression of a spacetime program.
/// It is described in the Section 4.5.4 in the dissertation (Talbot, 2018).

use context::*;
use middle::causality::causal_model::*;

pub struct CausalDeps {}

impl CausalDeps {
  pub fn new() -> Self {
    CausalDeps { }
  }

  pub fn visit_expr(&self, expr: Expr, is_monotonic: bool, model: CausalModel) -> CausalModel {
    use ast::ExprKind::*;
    match expr.node {
      Number(_)
    | StringLiteral(_)
    | Trilean(_)
    | Bottom
    | Top => self.visit_constant(model),
      NewInstance(new_instance) => self.visit_exprs_simultaneously(new_instance.args, is_monotonic, model),
      Call(call) => self.visit_method_call(call, is_monotonic, model),
      Var(var) => self.visit_var(var, is_monotonic, model),
      Or(left, right)
    | And(left, right) => self.visit_bin_op(*left, *right, is_monotonic, model),
      Not(expr) => self.visit_expr(*expr, is_monotonic, model),
      Entailment(rel) => self.visit_entailment(*rel, is_monotonic, model)
    }
  }

  /// Arguments of a function must not be sequentially ordered: it is possible to execute them in any order.
  /// For example: `f(read x, write x)` must fail because we cannot sequentially order the write after the read.
  /// Constraining operations to be simultaneous enforces that these operations are not sequentially ordered.
  fn visit_exprs_simultaneously(&self, exprs: Vec<Expr>, is_monotonic: bool, mut model: CausalModel) -> CausalModel {
    let mut op_models = vec![];
    let mut models = vec![];
    for expr in exprs {
      let is_var = expr.is_var();
      let m = self.visit_expr(expr, is_monotonic, model.clone());
      if is_var {
        op_models.push(m);
      }
      else { models.push(m); }
    }
    model = model.fold(models);
    assert!(op_models.iter().all(|m| m.latest_ops.len() == 1),
      "visit_exprs_simultaneously: variable operation must only create one latest operation.");
    let simultaneous_ops: Vec<usize> = op_models.iter().map(|m| m.latest_ops[0]).collect();
    model = model.fold(op_models);
    model.add_simultaneous_ops_constraint(simultaneous_ops);
    model
  }

  /// We restrict ourselves to binary operations causal with a left-to-right order of evaluation.
  /// This is to simplify the runtime.
  fn visit_bin_op(&self, left: Expr, right: Expr, is_monotonic: bool, model: CausalModel) -> CausalModel {
    let m1 = self.visit_expr(left, is_monotonic, model);
    self.visit_expr(right, is_monotonic, m1)
  }

  fn visit_method_call(&self, call: MethodCall, is_monotonic: bool, model: CausalModel) -> CausalModel {
    assert_eq!(is_monotonic, false,
      "visit_method_call: method can only be called in a non-monotonic context.\n\
      This should be checked in `infer_permission.rs` (E0027).");
    let mut args = call.args;
    // From the point of view of the causality, the target of the method call is just an argument.
    if let Some(target) = call.target {
      args.insert(0, Expr::new(target.span, ExprKind::Var(target)));
    }
    self.visit_exprs_simultaneously(args, is_monotonic, model)
  }

  /// The sub-expressions of the entailment are quite limited:
  /// By the analysis E0026 and E0027 host functions, write and readwrite are forbidden.
  /// Therefore, there is no need to generate sequential constraints between the left and right sides.
  fn visit_entailment(&self, rel: EntailmentRel, is_monotonic: bool, model: CausalModel) -> CausalModel {
    let (l, r) =
      if is_monotonic { (true, false) }
      else { (false, true) };
    let m1 = self.visit_expr(rel.left, l, model.clone());
    let m2 = self.visit_expr(rel.right, r, model);
    m1.join_constraints(m2, CausalModel::and_inst)
  }

  pub fn visit_var(&self, var: Variable, is_monotonic: bool, mut model: CausalModel) -> CausalModel {
    if is_monotonic {
      return model;
    }
    model.add_sequential_constraint(var.op_no);
    model.instantaneous = true;
    model
  }

  fn visit_constant(&self, mut model: CausalModel) -> CausalModel {
    model.instantaneous = true;
    model
  }
}

<|endoftext|>


<commit_before><commit_msg>chore: add a simple example<commit_after>// Copyright (c) 2017 Nikita Pekin and the wolfram_alpha_rs contributors
// See the README.md file at the top-level directory of this distribution.
//
// 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.

extern crate futures;
extern crate hyper;
extern crate hyper_tls;
extern crate tokio_core;
extern crate wolfram_alpha;

use futures::future::Future;
use hyper::Client;
use hyper_tls::HttpsConnector;
use tokio_core::reactor::Core;
use wolfram_alpha::query::query;

const APP_ID: &str = "YOUR_APP_ID";

fn main() {
    let mut core = Core::new().unwrap();
    let client = Client::configure()
        .connector(HttpsConnector::new(4, &core.handle()).unwrap())
        .build(&core.handle());

    let input = "distance from the Sun to the Earth";
    let work = query(&client, APP_ID, input, None)
        .and_then(|res| {
            let subpod = &res.pod.unwrap()[1].subpod[0];
            let plaintext = subpod.plaintext.as_ref().unwrap();
            println!("Distance from the Sun to the Earth: {:?}", plaintext);
            Ok(())
        });

    core.run(work).unwrap();
}
<|endoftext|>


<commit_before><commit_msg>First pass<commit_after>#[deriving(Show)]
#[deriving(Clone)]
pub enum Doc {
    Nil,
    Append(Box<Doc>, Box<Doc>),
    Nest(uint, Box<Doc>),
    Text(String),
    Break(uint, uint),
    Newline,
    Group(Box<Doc>)
}

impl Doc {
    pub fn append(&self, e:Doc) -> Doc {
        match self {
            &Nil => e,
            x => match e {
                Nil => x.clone(),
                y => Append(box x.clone(), box y)
            }
        }
    }
}

fn concat(ds:&[Doc]) -> Doc {
    ds.iter().fold(Nil, |a, b| Append(box a, box b.clone()))
}

fn int(i:int) -> Doc {
    Text(format!("{}", i))
}

fn char(c:char) -> Doc {
    Text(format!("{}", c))
}

fn bool(b:bool) -> Doc {
    if b {
        Text(String::from_str("true"))
    } else {
        Text(String::from_str("false"))
    }
}

mod mode {
    #[deriving(Clone)]
    pub enum Mode {
        Flat,
        Break
    }
}

fn replicate<A:Clone>(x:A, l:uint) -> Vec<A> {
    let mut i = 0u;
    let mut res = Vec::new();
    for _ in range(i,l) {
        res.push(x.clone());
    }
    res
}
fn pad_right(c:char, l:uint, str:String) -> String {
    let str_len = str.len();
    if (l > str_len) {
        let padding = replicate(String::from_str(" "), l - str_len).concat();
        str.clone().append(padding.as_slice())
    } else {
        str
    }
}
fn pad_left(c:char, l:uint, str:String) -> String {
    let str_len = str.len();
    if (l > str_len) {
      let padding = replicate(String::from_str(" "), l - str_len).concat();
      padding.append(str.as_slice())
    } else {
        str
    }
}

fn nlspace<S>(outs:(|S,String| -> S), s:S, i:uint) -> S {
    outs(s, pad_right(' ', i + String::from_str("\n").len(), String::from_str("\n")))
}

fn spaces<S>(outs:(|S,String| -> S), s:S, i:uint) -> S {
    outs(s, pad_left(' ', i, String::from_str("")))
}

fn fitting(xs:&Vec<(uint,mode::Mode,Doc)>, left:uint) -> bool {
    if left as int >= 0 {
        match xs.as_slice() {
            [] => true,
            [(ref i, ref mode, ref doc), ref rest..] => match doc {
                &Nil => fitting(&rest.to_vec(), left),
                &Append(ref x, ref y) => {
                    let mut ys = [(*i,*mode,*x.clone()), (*i,*mode,*y.clone())].to_vec();
                    ys.push_all(*rest);
                    fitting(&ys,left)
                },
                &Nest(j, ref x) => {
                    let mut ys = [(*i+j,*mode,*x.clone())].to_vec();
                    ys.push_all(*rest);
                    fitting(&ys, left)
                },
                &Text(ref str) => fitting(&rest.to_vec(), left - str.len()),
                &Break(sp, _) => match *mode {
                    mode::Flat => fitting(&rest.to_vec(), left - sp),
                    mode::Break => true
                },
                &Newline => true,
                &Group(ref x) => {
                    let mut ys = [(*i,*mode, *x.clone())].to_vec();
                    ys.push_all(*rest);
                    fitting(&ys, left)
                }
            }
        }
    }
    else {
        false
    }
}

fn best<S:Clone>(w:uint, outs:(|S, String| -> S), s:S, x:Doc) -> S {
    fn go<S:Clone>(w:uint, outs:(|S,String| -> S), s:S, k:uint, xs:Vec<(uint,mode::Mode,Doc)>) -> S {
        match xs.as_slice() {
            [] => s.clone(),
            [(ref i, ref mode, ref doc), ref rest..] => match doc {
                &Nil => go(w, outs, s, k, rest.to_vec()),
                &Append(ref x, ref y) => {
                    let mut rest2 = [(*i,*mode,*x.clone()), (*i,*mode,*y.clone())].to_vec();
                    rest2.push_all(*rest);
                    go(w, outs, s, k, rest2)
                },
                &Nest(j, ref x) => {
                    let mut rest2 = [(*i+j,*mode,*x.clone())].to_vec();
                    rest2.push_all(*rest);
                    go(w, outs, s, k, rest2)
                },
                &Text(ref str) => {
                    let ss = outs(s, str.clone());
                    go(w, outs, ss, (k + str.len()), rest.to_vec())
                },
                &Newline => {
                    let ss = nlspace(|x,y| outs(x,y), s, *i);
                    go(w, outs, ss, *i, rest.to_vec())
                }
                &Break(sp, off) => {
                    match *mode {
                        mode::Flat => {
                            let ss = spaces(|x,y| outs(x,y), s.clone(), sp);
                            go(w, outs, ss, k + sp, rest.to_vec())
                        },
                        mode::Break => {
                            let ss = nlspace(|x,y| outs(x,y), s.clone(), i + off);
                            go(w, outs, ss, i + off, rest.to_vec())
                        }
                    }
                },
                &Group(ref x) => {
                    match *mode {
                        mode::Flat => {
                            let mut rest2 = [(*i,mode::Flat,*x.clone())].to_vec();
                            rest2.push_all(*rest);
                            go(w, outs, s, k, rest2)
                        },
                        mode::Break => {
                            let mut rest2 = [(*i,mode::Flat,*x.clone())].to_vec();
                            rest2.push_all(*rest);
                            if fitting(&rest2, w - k) {
                                go(w, outs, s, k, rest2)
                            } else {
                                let mut rest3 = [(*i,mode::Break,*x.clone())].to_vec();
                                rest3.push_all(*rest);
                                go(w, outs, s, k, rest3)
                            }
                        }
                    }
                }
            }
        }
    }
    go(w, outs, s, 0, [(0,mode::Break,x)].to_vec())
}

impl Doc {
    pub fn to_string(&self, w:uint) -> String {
        let outs = |strs:Vec<String>, s:String| -> Vec<String> {
            let mut welp = [s].to_vec();
            welp.push_all(strs.as_slice()); // horrible
            welp
        };

        let mut strs = best(w, outs, [].to_vec(), self.clone());
        strs.reverse();
        strs.push(String::from_str("\n"));
        strs.concat()
    }
}

fn main() {
}
<|endoftext|>


<commit_before><commit_msg>Fix style issue reported by cargo fmt<commit_after><|endoftext|>


<commit_before><commit_msg>finally some progress<commit_after><|endoftext|>


<commit_before><commit_msg>Input parsing<commit_after><|endoftext|>


<commit_before><commit_msg>tests: test to see if crosvm can boot a kernel<commit_after>// Copyright 2019 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use std::env;
use std::fs;
use std::io::{stdout, Write};
use std::mem;
use std::os::unix::fs::symlink;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Once;

use libc::{cpu_set_t, sched_getaffinity};

use crosvm::{linux, Config, Executable};
use devices::{SerialParameters, SerialType};

const CHROOT_KERNEL_PATH: &str = "/mnt/host/source/src/third_party/kernel/v4.19/";
const CONTAINER_VM_DEFCONFIG: &str = "arch/x86/configs/chromiumos-container-vm-x86_64_defconfig";
const KERNEL_REPO: &str = "https://chromium.googlesource.com/chromiumos/third_party/kernel";
const KERNEL_REPO_BRANCH: &str = "chromeos-4.19";
// TODO(zachr): this URL is a placeholder until the automated builder is running and we've settled
// on a location.
const KERNEL_PREBUILT: &str = "http://storage.googleapis.com/crosvm-testing";

/// Returns the number of CPUs that this process and its children can use by querying our process's
/// CPU affinity.
fn get_cpu_count() -> usize {
    unsafe {
        let mut set: cpu_set_t = mem::zeroed();
        let ret = sched_getaffinity(0, mem::size_of::<cpu_set_t>(), &mut set);
        if ret != 0 {
            // A good guess.
            4
        } else {
            // The cpu_set_t is normally counted using the CPU_COUNT macro, but we don't have that
            // in Rust. Because it's always a bitset, we will treat it like one here.
            let set: [u8; mem::size_of::<cpu_set_t>()] = mem::transmute(set);
            set.iter().map(|b| b.count_ones() as usize).sum()
        }
    }
}

/// Clones a chrome os kernel into the given path.
fn clone_kernel_source(dir: &Path) {
    let status = Command::new("git")
        .args(&[
            "clone",
            "--depth",
            "1",
            "--branch",
            KERNEL_REPO_BRANCH,
            KERNEL_REPO,
        ])
        .arg(dir)
        .status()
        .expect("failed to execute git");
    if !status.success() {
        panic!("failed to clone kernel source: {}", status);
    }
}

// Kernel binary algorithm.
// 1: If CROSVM_CARGO_TEST_KERNEL_BINARY is in the env:
//        If CROSVM_CARGO_TEST_KERNEL_BINARY is empty, skip step 3.
//        If CROSVM_CARGO_TEST_KERNEL_BINARY does not exist, panic.
// 2: If "bzImage" exists in the target directory use that.
// 3: Download "bzImage" from the KERNEL_PREBUILT url and use that.
//    If the download does not work, go to the kernel source algorithm.
//
// Kernel source algorithm
// 1: If CROSVM_CARGO_TEST_KERNEL_SOURCE is in the env, use that.
//    If CROSVM_CARGO_TEST_KERNEL_SOURCE does not exist, panic
// 2: If CHROOT_KERNEL_PATH exists, use that.
// 3: Checkout and use the chromeos kernel.
//
// Kernel config algorithm
// 1: If the .config already exists in the kernel source, use that.
// 2: If the CONTAINER_VM_DEFCONFIG exists in the kernel source, use that.
// 3: Use `make defconfig`.
fn prepare_kernel_once(dir: &Path) {
    let kernel_binary = dir.join("bzImage");

    let mut download_prebuilt = true;
    if let Ok(env_kernel_binary) = env::var("CROSVM_CARGO_TEST_KERNEL_BINARY") {
        if env_kernel_binary.is_empty() {
            download_prebuilt = false;
        } else {
            println!(
                "using kernel binary from enviroment `{}`",
                env_kernel_binary
            );
            let env_kernel_binary = PathBuf::from(env_kernel_binary);
            if env_kernel_binary.exists() {
                symlink(env_kernel_binary, &kernel_binary)
                    .expect("failed to create symlink for kernel binary");
                return;
            } else {
                panic!(
                    "expected kernel binary at `{}`",
                    env_kernel_binary.display()
                )
            }
        }
    }

    println!("looking for kernel binary at `{}`", kernel_binary.display());
    if kernel_binary.exists() {
        println!("using kernel binary at `{}`", kernel_binary.display());
        return;
    }

    if download_prebuilt {
        // Resolve the base URL into a specific path for this architecture.
        let kernel_prebuilt = format!(
            "{}/{}/{}",
            KERNEL_PREBUILT,
            env::consts::ARCH,
            "latest-bzImage"
        );
        println!(
            "downloading prebuilt kernel binary from `{}`",
            kernel_prebuilt
        );
        let status = Command::new("curl")
            .args(&["--fail", "--location"])
            .arg("--output")
            .arg(&kernel_binary)
            .arg(kernel_prebuilt)
            .status();
        if let Ok(status) = status {
            if status.success() {
                println!("using prebuilt kernel binary");
                return;
            }
        }

        println!("failed to download prebuilt kernel binary");
    }

    let kernel_source = if let Ok(env_kernel_source) = env::var("CROSVM_CARGO_TEST_KERNEL_SOURCE") {
        if Path::new(&env_kernel_source).is_dir() {
            PathBuf::from(env_kernel_source)
        } else {
            panic!("expected kernel source at `{}`", env_kernel_source);
        }
    } else if Path::new(CHROOT_KERNEL_PATH).is_dir() {
        PathBuf::from(CHROOT_KERNEL_PATH)
    } else {
        let kernel_source = dir.join("kernel-source");
        // Check for kernel source
        if !kernel_source.is_dir() {
            clone_kernel_source(&kernel_source);
        }
        kernel_source
    };

    println!("building kernel from source `{}`", kernel_source.display());

    // Special provisions for using the ChromeOS kernel source and its config used in crostini.
    let current_config = kernel_source.join(".config");
    let container_vm_defconfig = kernel_source.join(CONTAINER_VM_DEFCONFIG);
    if current_config.exists() {
        fs::copy(current_config, dir.join(".config"))
            .expect("failed to copy existing kernel config");
    } else if container_vm_defconfig.exists() {
        fs::copy(container_vm_defconfig, dir.join(".config"))
            .expect("failed to copy  chromiumos container vm kernel config");
    } else {
        // TODO(zachr): the defconfig for vanilla kernels is probably inadequate. There should
        // probably be a step where additional options are added to the resulting .config.
        let status = Command::new("make")
            .current_dir(&kernel_source)
            .arg(format!("O={}", dir.display()))
            .arg("defconfig")
            .status()
            .expect("failed to execute make");
        if !status.success() {
            panic!("failed to default config kernel: {}", status);
        }
    }

    let output = Command::new("make")
        .current_dir(&kernel_source)
        .arg(format!("O={}", dir.display()))
        .args(&["bzImage", "-j"])
        .arg(format!("{}", get_cpu_count()))
        .output()
        .expect("failed to execute make");
    if !output.status.success() {
        let _ = stdout().lock().write(&output.stderr);
        panic!("failed to build kernel: {}", output.status);
    }

    fs::copy(dir.join("arch/x86/boot/bzImage"), &kernel_binary)
        .expect("failed to copy kernel binary");
}

/// Gets the target directory path for artifacts.
fn get_target_path() -> PathBuf {
    env::current_exe()
        .ok()
        .map(|mut path| {
            path.pop();
            path
        })
        .expect("failed to get target dir")
}

/// Thread-safe method for preparing a kernel and returning the path to its binary.
fn prepare_kernel() -> PathBuf {
    // Lots of unit tests need the kernel, but it should only get prepared once by any arbitrary
    // test. The rest of the tests should wait until the arbitrary one finishes.
    let default_linux_dir = get_target_path();
    static PREP_ONCE: Once = Once::new();
    PREP_ONCE.call_once(|| prepare_kernel_once(&default_linux_dir));
    default_linux_dir.join("bzImage")
}

#[test]
fn boot() {
    let kernel_path = prepare_kernel();

    let mut c = Config::default();
    c.sandbox = false;
    c.serial_parameters.insert(
        1,
        SerialParameters {
            type_: SerialType::Sink,
            path: None,
            num: 1,
            console: false,
            stdin: false,
        },
    );
    c.executable_path = Some(Executable::Kernel(kernel_path));

    let r = linux::run_config(c);
    r.expect("failed to run linux");
}
<|endoftext|>


<commit_before><commit_msg>Initial implementation of new constraint system in dedicated test file.<commit_after>use std::ops::{Deref, DerefMut};

trait Graph {
	fn graph_fn(&self) -> u32 ;
}
trait GraphMut: Graph {
	fn graph_mut(&mut self) -> &mut u32;
}

trait BaseConstraint: Sized {
	type Graph: Graph;
	fn get_graph(&self) -> &Self::Graph;
}
trait BaseConstraintMut: BaseConstraint
{
	type GraphMut: GraphMut;
	fn get_graph_mut(&mut self) -> &mut Self::GraphMut;
}
trait Constraint: Sized
{
	type Base:  BaseConstraint;
	type Constrained: Constraint<Base=Self::Base>;

	fn base_single(&self) -> &Self::Constrained;
	fn unconstrain_single(self) -> Self::Constrained;
	fn constrain_single(g: Self::Constrained) -> Result<Self, ()>;

	fn unconstrain(self) -> Self::Base{
		self.unconstrain_single().unconstrain()
	}
	fn constrain(g: Self::Base) -> Result<Self, ()>{
		Self::constrain_single(Self::Constrained::constrain(g)?)
	}
	fn base(&self) -> &<Self::Base as BaseConstraint>::Graph {
		self.base_single().base()
	}

}
trait ConstraintMut: Constraint
{
	type BaseMut:  BaseConstraintMut;
	type ConstrainedMut: ConstraintMut<BaseMut=Self::BaseMut>;
	fn base_single_mut(&mut self) -> &mut Self::ConstrainedMut;
	fn base_mut(&mut self) -> &mut <Self::BaseMut as BaseConstraintMut>::GraphMut {
		self.base_single_mut().base_mut()
	}
}

impl<B: BaseConstraint> Constraint for B{
	type Base = Self;
	type Constrained = Self;

	fn base_single(&self) -> &Self::Constrained { &self }
	fn unconstrain_single(self) -> Self::Constrained { self }
	fn constrain_single(g: Self::Constrained) -> Result<Self, ()> { Ok(g)}

	fn unconstrain(self) -> Self::Base { self }
	fn constrain(g: Self::Base) -> Result<Self, ()>{ Ok(g) }
	fn base(&self) -> &<Self::Base as BaseConstraint>::Graph { self.get_graph() }
}
impl<B: BaseConstraintMut> ConstraintMut for B{
	type BaseMut = Self;
	type ConstrainedMut = Self;
	fn base_single_mut(&mut self) -> &mut Self::Constrained { self }
	fn base_mut(&mut self) -> &mut <Self::BaseMut as BaseConstraintMut>::GraphMut {
		self.get_graph_mut()
	}
}

impl<G: Graph, D: Deref<Target=G>> BaseConstraint for D
{
	type Graph = G;
	fn get_graph(&self) -> &Self::Graph {&**self}
}
impl<G: GraphMut, D: DerefMut<Target=G>> BaseConstraintMut for D
{
	type GraphMut = G;
	fn get_graph_mut(&mut self) -> &mut Self::GraphMut {&mut **self}
}

struct BaseGraph(u32);
impl Graph for BaseGraph{
	fn graph_fn(&self) -> u32 {
		self.0
	}
}
impl GraphMut for BaseGraph {
	fn graph_mut(&mut self) -> &mut u32 { &mut self.0 }
}
impl BaseConstraint for BaseGraph {
	type Graph = Self;
	fn get_graph(&self) -> &Self::Graph {self}
}
impl BaseConstraintMut for BaseGraph{
	type GraphMut = Self;
	fn get_graph_mut(&mut self) -> &mut Self::GraphMut {self}
}

struct Connected<C: Constraint>(C);
impl<C: Constraint> Graph for Connected<C>{
	fn graph_fn(&self) -> u32 {
		self.base().graph_fn()
	}
}
impl<C: ConstraintMut> GraphMut for Connected<C>
{
	fn graph_mut(&mut self) -> &mut u32 { self.0.base_mut().graph_mut() }
}
impl<C: Constraint> Constraint for Connected<C>
{
	type Base = C::Base;
	type Constrained = C;

	fn base_single(&self) -> &Self::Constrained { &self.0 }
	fn unconstrain_single(self) -> Self::Constrained { self.0 }
	fn constrain_single(g: Self::Constrained) -> Result<Self, ()> {
		if g.base().graph_fn() < 32 {
			Ok(Self(g))
		} else {
			Err(())
		}

	}
}
impl<C: ConstraintMut> ConstraintMut for Connected<C>
{
	type BaseMut = C::BaseMut;
	type ConstrainedMut = C;

	fn base_single_mut(&mut self) -> &mut Self::Constrained { &mut self.0 }
}

#[test]
fn test(){
	let mut g = BaseGraph(16);
	assert_eq!(g.graph_fn(), 16);

	let c_ref = Connected::constrain_single(&g).unwrap();
	assert_eq!(c_ref.graph_fn(), 16);

	let mut c_ref_mut = Connected::constrain_single(&mut g).unwrap();
	*c_ref_mut.graph_mut() = 30;
	assert_eq!(c_ref_mut.graph_fn(), 30);

	let c_owned = Connected::constrain_single(g).unwrap();
	assert_eq!(c_owned.graph_fn(), 30);

}<|endoftext|>


<commit_before><commit_msg>Update vec.rs<commit_after><|endoftext|>


<commit_before><commit_msg>A couple of tests.<commit_after><|endoftext|>


<commit_before><commit_msg>Create Vulkan device<commit_after><|endoftext|>


<commit_before><commit_msg>Skeleton for problem 2475<commit_after>// https://leetcode.com/problems/number-of-unequal-triplets-in-array/
pub fn unequal_triplets(nums: Vec<i32>) -> i32 {
    todo!()
}

fn main() {
    println!("{}", unequal_triplets(vec![4, 4, 2, 4, 3])); // 3
    println!("{}", unequal_triplets(vec![1, 1, 1, 1, 1])); // 0
}
<|endoftext|>


<commit_before><commit_msg>test: Add a max/min classes test case<commit_after>trait Product {
    fn product() -> int;
}

struct Foo {
    x: int;
    y: int;
}

impl Foo {
    fn sum() -> int {
        self.x + self.y
    }
}

impl Foo : Product {
    fn product() -> int {
        self.x * self.y
    }
}

fn Foo(x: int, y: int) -> Foo {
    Foo { x: x, y: y }
}

fn main() {
    let foo = Foo(3, 20);
    io::println(#fmt("%d %d", foo.sum(), foo.product()));
}

<|endoftext|>


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

extern mod extra;
use extra::rc::RcMut;

trait Foo
{
    fn set(&mut self, v: RcMut<A>);
}

struct B
{
    v: Option<RcMut<A>>
}

impl Foo for B
{
    fn set(&mut self, v: RcMut<A>)
    {
        self.v = Some(v);
    }
}

struct A
{
    v: ~Foo,
}

fn main()
{
    let a = A {v: ~B{v: None} as ~Foo}; //~ ERROR cannot pack type `~B`, which does not fulfill `Send`
    let v = RcMut::from_freeze(a); //~ ERROR instantiating a type parameter with an incompatible type
    let w = v.clone();
    v.with_mut_borrow(|p| {p.v.set(w.clone());})
}
<|endoftext|>


<commit_before><commit_msg>Change the easage app to show help if a subcommand is not given<commit_after><|endoftext|>


<commit_before><commit_msg>Clarify error message.<commit_after><|endoftext|>


<commit_before><commit_msg>Add test for unnecessary mut passed lint<commit_after>#![feature(plugin)]
#![plugin(clippy)]

fn takes_an_immutable_reference(a: &i32) {
}

fn takes_a_mutable_reference(a: &mut i32) {
}

struct MyStruct;

impl MyStruct {
    fn takes_an_immutable_reference(&self, a: &i32) {
    }

    fn takes_a_mutable_reference(&self, a: &mut i32) {
    }
}

#[deny(unnecessary_mut_passed)]
fn main() {
    // Functions
    takes_an_immutable_reference(&mut 42); //~ERROR The function/method "takes_an_immutable_reference" doesn't need a mutable reference

    // Methods
    let my_struct = MyStruct;
    my_struct.takes_an_immutable_reference(&mut 42); //~ERROR The function/method "takes_an_immutable_reference" doesn't need a mutable reference

    // No error

    // Functions
    takes_an_immutable_reference(&42);
    takes_a_mutable_reference(&mut 42);
    let mut a = &mut 42;
    takes_an_immutable_reference(a);

    // Methods
    my_struct.takes_an_immutable_reference(&42);
    my_struct.takes_a_mutable_reference(&mut 42);
    my_struct.takes_an_immutable_reference(a);

}
<|endoftext|>


<commit_before><commit_msg>commit<commit_after><|endoftext|>


<commit_before><commit_msg>Fix some errors in errorCalculator.rs.<commit_after><|endoftext|>


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

use std::num;
use std::uint;

use syntax::ast;

use clean;
use clean::Item;
use plugins;
use fold;
use fold::DocFolder;

/// Strip items marked `#[doc(hidden)]`
pub fn strip_hidden(crate: clean::Crate) -> plugins::PluginResult {
    struct Stripper;
    impl fold::DocFolder for Stripper {
        fn fold_item(&mut self, i: Item) -> Option<Item> {
            for attr in i.attrs.iter() {
                match attr {
                    &clean::List(~"doc", ref l) => {
                        for innerattr in l.iter() {
                            match innerattr {
                                &clean::Word(ref s) if "hidden" == *s => {
                                    debug!("found one in strip_hidden; removing");
                                    return None;
                                },
                                _ => (),
                            }
                        }
                    },
                    _ => ()
                }
            }
            self.fold_item_recur(i)
        }
    }
    let mut stripper = Stripper;
    let crate = stripper.fold_crate(crate);
    (crate, None)
}

/// Strip private items from the point of view of a crate or externally from a
/// crate, specified by the `xcrate` flag.
pub fn strip_private(crate: clean::Crate) -> plugins::PluginResult {
    struct Stripper;
    impl fold::DocFolder for Stripper {
        fn fold_item(&mut self, i: Item) -> Option<Item> {
            match i.inner {
                // These items can all get re-exported
                clean::TypedefItem(*) | clean::StaticItem(*) |
                clean::StructItem(*) | clean::EnumItem(*) |
                clean::TraitItem(*) | clean::FunctionItem(*) |
                clean::ViewItemItem(*) | clean::MethodItem(*) => {
                    // XXX: re-exported items should get surfaced in the docs as
                    //      well (using the output of resolve analysis)
                    if i.visibility != Some(ast::public) {
                        return None;
                    }
                }

                // These are public-by-default (if the enum was public)
                clean::VariantItem(*) => {
                    if i.visibility == Some(ast::private) {
                        return None;
                    }
                }

                // We show these regardless of whether they're public/private
                // because it's useful to see sometimes
                clean::StructFieldItem(*) => {}

                // handled below
                clean::ModuleItem(*) => {}

                // impls/tymethods have no control over privacy
                clean::ImplItem(*) | clean::TyMethodItem(*) => {}
            }

            let fastreturn = match i.inner {
                // nothing left to do for traits (don't want to filter their
                // methods out, visibility controlled by the trait)
                clean::TraitItem(*) => true,

                // implementations of traits are always public.
                clean::ImplItem(ref imp) if imp.trait_.is_some() => true,

                _ => false,
            };

            let i = if fastreturn {
                return Some(i);
            } else {
                self.fold_item_recur(i)
            };

            match i {
                Some(i) => {
                    match i.inner {
                        // emptied modules/impls have no need to exist
                        clean::ModuleItem(ref m) if m.items.len() == 0 => None,
                        clean::ImplItem(ref i) if i.methods.len() == 0 => None,
                        _ => Some(i),
                    }
                }
                None => None,
            }
        }
    }
    let mut stripper = Stripper;
    let crate = stripper.fold_crate(crate);
    (crate, None)
}

pub fn unindent_comments(crate: clean::Crate) -> plugins::PluginResult {
    struct CommentCleaner;
    impl fold::DocFolder for CommentCleaner {
        fn fold_item(&mut self, i: Item) -> Option<Item> {
            let mut i = i;
            let mut avec: ~[clean::Attribute] = ~[];
            for attr in i.attrs.iter() {
                match attr {
                    &clean::NameValue(~"doc", ref s) => avec.push(
                        clean::NameValue(~"doc", unindent(*s))),
                    x => avec.push(x.clone())
                }
            }
            i.attrs = avec;
            self.fold_item_recur(i)
        }
    }
    let mut cleaner = CommentCleaner;
    let crate = cleaner.fold_crate(crate);
    (crate, None)
}

pub fn collapse_docs(crate: clean::Crate) -> plugins::PluginResult {
    struct Collapser;
    impl fold::DocFolder for Collapser {
        fn fold_item(&mut self, i: Item) -> Option<Item> {
            let mut docstr = ~"";
            let mut i = i;
            for attr in i.attrs.iter() {
                match *attr {
                    clean::NameValue(~"doc", ref s) => {
                        docstr.push_str(s.clone());
                        docstr.push_char('\n');
                    },
                    _ => ()
                }
            }
            let mut a: ~[clean::Attribute] = i.attrs.iter().filter(|&a| match a {
                &clean::NameValue(~"doc", _) => false,
                _ => true
            }).map(|x| x.clone()).collect();
            if "" != docstr {
                a.push(clean::NameValue(~"doc", docstr.trim().to_owned()));
            }
            i.attrs = a;
            self.fold_item_recur(i)
        }
    }
    let mut collapser = Collapser;
    let crate = collapser.fold_crate(crate);
    (crate, None)
}

pub fn unindent(s: &str) -> ~str {
    let lines = s.any_line_iter().collect::<~[&str]>();
    let mut saw_first_line = false;
    let mut saw_second_line = false;
    let min_indent = do lines.iter().fold(uint::max_value) |min_indent, line| {

        // After we see the first non-whitespace line, look at
        // the line we have. If it is not whitespace, and therefore
        // part of the first paragraph, then ignore the indentation
        // level of the first line
        let ignore_previous_indents =
            saw_first_line &&
            !saw_second_line &&
            !line.is_whitespace();

        let min_indent = if ignore_previous_indents {
            uint::max_value
        } else {
            min_indent
        };

        if saw_first_line {
            saw_second_line = true;
        }

        if line.is_whitespace() {
            min_indent
        } else {
            saw_first_line = true;
            let mut spaces = 0;
            do line.iter().all |char| {
                // Only comparing against space because I wouldn't
                // know what to do with mixed whitespace chars
                if char == ' ' {
                    spaces += 1;
                    true
                } else {
                    false
                }
            };
            num::min(min_indent, spaces)
        }
    };

    match lines {
        [head, .. tail] => {
            let mut unindented = ~[ head.trim() ];
            unindented.push_all(do tail.map |&line| {
                if line.is_whitespace() {
                    line
                } else {
                    assert!(line.len() >= min_indent);
                    line.slice_from(min_indent)
                }
            });
            unindented.connect("\n")
        }
        [] => s.to_owned()
    }
}

#[cfg(test)]
mod unindent_tests {
    use super::unindent;

    #[test]
    fn should_unindent() {
        let s = ~"    line1\n    line2";
        let r = unindent(s);
        assert_eq!(r, ~"line1\nline2");
    }

    #[test]
    fn should_unindent_multiple_paragraphs() {
        let s = ~"    line1\n\n    line2";
        let r = unindent(s);
        assert_eq!(r, ~"line1\n\nline2");
    }

    #[test]
    fn should_leave_multiple_indent_levels() {
        // Line 2 is indented another level beyond the
        // base indentation and should be preserved
        let s = ~"    line1\n\n        line2";
        let r = unindent(s);
        assert_eq!(r, ~"line1\n\n    line2");
    }

    #[test]
    fn should_ignore_first_line_indent() {
        // Thi first line of the first paragraph may not be indented as
        // far due to the way the doc string was written:
        //
        // #[doc = "Start way over here
        //          and continue here"]
        let s = ~"line1\n    line2";
        let r = unindent(s);
        assert_eq!(r, ~"line1\nline2");
    }

    #[test]
    fn should_not_ignore_first_line_indent_in_a_single_line_para() {
        let s = ~"line1\n\n    line2";
        let r = unindent(s);
        assert_eq!(r, ~"line1\n\n    line2");
    }
}
<commit_msg>rustdoc: Fix an unindentation bug when collapsing<commit_after>// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::num;
use std::uint;

use syntax::ast;

use clean;
use clean::Item;
use plugins;
use fold;
use fold::DocFolder;

/// Strip items marked `#[doc(hidden)]`
pub fn strip_hidden(crate: clean::Crate) -> plugins::PluginResult {
    struct Stripper;
    impl fold::DocFolder for Stripper {
        fn fold_item(&mut self, i: Item) -> Option<Item> {
            for attr in i.attrs.iter() {
                match attr {
                    &clean::List(~"doc", ref l) => {
                        for innerattr in l.iter() {
                            match innerattr {
                                &clean::Word(ref s) if "hidden" == *s => {
                                    debug!("found one in strip_hidden; removing");
                                    return None;
                                },
                                _ => (),
                            }
                        }
                    },
                    _ => ()
                }
            }
            self.fold_item_recur(i)
        }
    }
    let mut stripper = Stripper;
    let crate = stripper.fold_crate(crate);
    (crate, None)
}

/// Strip private items from the point of view of a crate or externally from a
/// crate, specified by the `xcrate` flag.
pub fn strip_private(crate: clean::Crate) -> plugins::PluginResult {
    struct Stripper;
    impl fold::DocFolder for Stripper {
        fn fold_item(&mut self, i: Item) -> Option<Item> {
            match i.inner {
                // These items can all get re-exported
                clean::TypedefItem(*) | clean::StaticItem(*) |
                clean::StructItem(*) | clean::EnumItem(*) |
                clean::TraitItem(*) | clean::FunctionItem(*) |
                clean::ViewItemItem(*) | clean::MethodItem(*) => {
                    // XXX: re-exported items should get surfaced in the docs as
                    //      well (using the output of resolve analysis)
                    if i.visibility != Some(ast::public) {
                        return None;
                    }
                }

                // These are public-by-default (if the enum was public)
                clean::VariantItem(*) => {
                    if i.visibility == Some(ast::private) {
                        return None;
                    }
                }

                // We show these regardless of whether they're public/private
                // because it's useful to see sometimes
                clean::StructFieldItem(*) => {}

                // handled below
                clean::ModuleItem(*) => {}

                // impls/tymethods have no control over privacy
                clean::ImplItem(*) | clean::TyMethodItem(*) => {}
            }

            let fastreturn = match i.inner {
                // nothing left to do for traits (don't want to filter their
                // methods out, visibility controlled by the trait)
                clean::TraitItem(*) => true,

                // implementations of traits are always public.
                clean::ImplItem(ref imp) if imp.trait_.is_some() => true,

                _ => false,
            };

            let i = if fastreturn {
                return Some(i);
            } else {
                self.fold_item_recur(i)
            };

            match i {
                Some(i) => {
                    match i.inner {
                        // emptied modules/impls have no need to exist
                        clean::ModuleItem(ref m) if m.items.len() == 0 => None,
                        clean::ImplItem(ref i) if i.methods.len() == 0 => None,
                        _ => Some(i),
                    }
                }
                None => None,
            }
        }
    }
    let mut stripper = Stripper;
    let crate = stripper.fold_crate(crate);
    (crate, None)
}

pub fn unindent_comments(crate: clean::Crate) -> plugins::PluginResult {
    struct CommentCleaner;
    impl fold::DocFolder for CommentCleaner {
        fn fold_item(&mut self, i: Item) -> Option<Item> {
            let mut i = i;
            let mut avec: ~[clean::Attribute] = ~[];
            for attr in i.attrs.iter() {
                match attr {
                    &clean::NameValue(~"doc", ref s) => avec.push(
                        clean::NameValue(~"doc", unindent(*s))),
                    x => avec.push(x.clone())
                }
            }
            i.attrs = avec;
            self.fold_item_recur(i)
        }
    }
    let mut cleaner = CommentCleaner;
    let crate = cleaner.fold_crate(crate);
    (crate, None)
}

pub fn collapse_docs(crate: clean::Crate) -> plugins::PluginResult {
    struct Collapser;
    impl fold::DocFolder for Collapser {
        fn fold_item(&mut self, i: Item) -> Option<Item> {
            let mut docstr = ~"";
            let mut i = i;
            for attr in i.attrs.iter() {
                match *attr {
                    clean::NameValue(~"doc", ref s) => {
                        docstr.push_str(s.clone());
                        docstr.push_char('\n');
                    },
                    _ => ()
                }
            }
            let mut a: ~[clean::Attribute] = i.attrs.iter().filter(|&a| match a {
                &clean::NameValue(~"doc", _) => false,
                _ => true
            }).map(|x| x.clone()).collect();
            if "" != docstr {
                a.push(clean::NameValue(~"doc", docstr));
            }
            i.attrs = a;
            self.fold_item_recur(i)
        }
    }
    let mut collapser = Collapser;
    let crate = collapser.fold_crate(crate);
    (crate, None)
}

pub fn unindent(s: &str) -> ~str {
    let lines = s.any_line_iter().collect::<~[&str]>();
    let mut saw_first_line = false;
    let mut saw_second_line = false;
    let min_indent = do lines.iter().fold(uint::max_value) |min_indent, line| {

        // After we see the first non-whitespace line, look at
        // the line we have. If it is not whitespace, and therefore
        // part of the first paragraph, then ignore the indentation
        // level of the first line
        let ignore_previous_indents =
            saw_first_line &&
            !saw_second_line &&
            !line.is_whitespace();

        let min_indent = if ignore_previous_indents {
            uint::max_value
        } else {
            min_indent
        };

        if saw_first_line {
            saw_second_line = true;
        }

        if line.is_whitespace() {
            min_indent
        } else {
            saw_first_line = true;
            let mut spaces = 0;
            do line.iter().all |char| {
                // Only comparing against space because I wouldn't
                // know what to do with mixed whitespace chars
                if char == ' ' {
                    spaces += 1;
                    true
                } else {
                    false
                }
            };
            num::min(min_indent, spaces)
        }
    };

    match lines {
        [head, .. tail] => {
            let mut unindented = ~[ head.trim() ];
            unindented.push_all(do tail.map |&line| {
                if line.is_whitespace() {
                    line
                } else {
                    assert!(line.len() >= min_indent);
                    line.slice_from(min_indent)
                }
            });
            unindented.connect("\n")
        }
        [] => s.to_owned()
    }
}

#[cfg(test)]
mod unindent_tests {
    use super::unindent;

    #[test]
    fn should_unindent() {
        let s = ~"    line1\n    line2";
        let r = unindent(s);
        assert_eq!(r, ~"line1\nline2");
    }

    #[test]
    fn should_unindent_multiple_paragraphs() {
        let s = ~"    line1\n\n    line2";
        let r = unindent(s);
        assert_eq!(r, ~"line1\n\nline2");
    }

    #[test]
    fn should_leave_multiple_indent_levels() {
        // Line 2 is indented another level beyond the
        // base indentation and should be preserved
        let s = ~"    line1\n\n        line2";
        let r = unindent(s);
        assert_eq!(r, ~"line1\n\n    line2");
    }

    #[test]
    fn should_ignore_first_line_indent() {
        // Thi first line of the first paragraph may not be indented as
        // far due to the way the doc string was written:
        //
        // #[doc = "Start way over here
        //          and continue here"]
        let s = ~"line1\n    line2";
        let r = unindent(s);
        assert_eq!(r, ~"line1\nline2");
    }

    #[test]
    fn should_not_ignore_first_line_indent_in_a_single_line_para() {
        let s = ~"line1\n\n    line2";
        let r = unindent(s);
        assert_eq!(r, ~"line1\n\n    line2");
    }
}
<|endoftext|>


<commit_before><commit_msg>Add a test case for #898. Closes #898.<commit_after>fn even(&&e: int) -> bool {
    e % 2 == 0
}

fn log_if<T>(c: fn(T)->bool, e: T) {
    if c(e) { log e; }
}

fn main() {
    (bind log_if(even, _))(2);
}
<|endoftext|>


<commit_before>//! Future-based abstractions for dealing with I/O
//!
//! Building on top of the `futures` crate the purpose of this crate is to
//! provide the abstractions necessary for interoperating I/O streams in an
//! asynchronous fashion.
//!
//! At its core is the abstraction of I/O objects as a collection of `Read`,
//! `Write`, and `Stream<Item=Ready, Error=io::Error>` implementations. This can
//! then be used to define a number of combinators and then later define further
//! abstractions on these streams.
//!
//! Note that this library is currently a work in progress, but stay tuned for
//! updates!

#![deny(missing_docs)]

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

use std::io;
use std::ops::BitOr;

use futures::{Task, Future};
use futures::stream::Stream;

/// A macro to assist with dealing with `io::Result<T>` types where the error
/// may have the type `WouldBlock`.
///
/// Converts all `Ok` values to `Some`, `WouldBlock` errors to `None`, and
/// otherwise returns all other errors upwards the stack.
#[macro_export]
macro_rules! try_nb {
    ($e:expr) => (match $e {
        Ok(e) => Some(e),
        Err(ref e) if e.kind() == ::std::io::ErrorKind::WouldBlock => None,
        Err(e) => return Err(::std::convert::From::from(e)),
    })
}

/// A convenience typedef around a `Future` whose error component is `io::Error`
pub type IoFuture<T> = Future<Item=T, Error=io::Error>;

/// A convenience typedef around a `Stream` whose error component is `io::Error`
pub type IoStream<T> = Stream<Item=T, Error=io::Error>;

mod impls;

mod buf_reader;
mod buf_writer;
mod chain;
mod copy;
mod empty;
mod flush;
mod read_to_end;
mod repeat;
mod ready_tracker;
mod sink;
mod take;
mod task;
pub use self::buf_reader::BufReader;
pub use self::buf_writer::BufWriter;
pub use self::chain::{chain, Chain};
pub use self::copy::{copy, Copy};
pub use self::empty::{empty, Empty};
pub use self::flush::{flush, Flush};
pub use self::read_to_end::{read_to_end, ReadToEnd};
pub use self::ready_tracker::ReadyTracker;
pub use self::repeat::{repeat, Repeat};
pub use self::sink::{sink, Sink};
pub use self::take::{take, Take};
pub use self::task::TaskIo;

/// Readiness notifications that a stream can deliver.
///
/// This is the primary point element yielded in `Stream` implementations on I/O
/// objects, indicating whether it is ready to be read or written to.
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum Ready {
    /// The I/O object is ready for a read.
    Read,
    /// The I/O object is ready for a write.
    Write,
    /// The I/O object is ready for both reading and writing.
    ReadWrite,
}

/// A trait representing streams that can be read within the context of a
/// future's `Task`.
///
/// This is a trait used to implement some of the "terminal" abstractions
/// provided by this crate. It is less general than the `Read` trait, and all
/// types which implement `Read` also implement this trait.
///
/// The main purpose of this trait is to allow insertion of I/O objects into
/// task-local storage but still allow for a `Read` implementation on the
/// returned handle.
pub trait ReadTask: Stream<Item=Ready, Error=io::Error> {
    /// Reads bytes into a buffer, optionally using `task` as a source of
    /// storage to draw from.
    ///
    /// Otherwise behaves the same as [`Read::read`][stdread].
    ///
    /// [stdread]: https://doc.rust-lang.org/std/io/trait.Read.html#tymethod.read
    fn read(&mut self, task: &mut Task, buf: &mut [u8]) -> io::Result<usize>;

    /// Reads as much information as possible from this underlying stream into
    /// the vector provided, optionally using the `task` as a source of storage
    /// to draw from.
    ///
    /// Otherwise behaves the same as [`Read::read_to_end`][stdreadtoend].
    ///
    /// [stdreadtoend]: https://doc.rust-lang.org/std/io/trait.Read.html#tymethod.read_to_end
    fn read_to_end(&mut self,
                   task: &mut Task,
                   buf: &mut Vec<u8>) -> io::Result<usize>;
}

/// A trait representing streams that can be written to within the context of a
/// future's `Task`.
///
/// This is a trait used to implement some of the "terminal" abstractions
/// provided by this crate. It is less general than the `Write` trait, and all
/// types which implement `Write` also implement this trait.
///
/// The main purpose of this trait is to allow insertion of I/O objects into
/// task-local storage but still allow for a `Write` implementation on the
/// returned handle.
pub trait WriteTask: Stream<Item=Ready, Error=io::Error> {
    /// Writes a list of bytes into this object, optionally using a `task` as a
    /// source of storage to draw from.
    ///
    /// Otherwise behaves the same as [`Write::write`][stdwrite]
    ///
    /// [stdwrite]: https://doc.rust-lang.org/std/io/trait.Write.html#tymethod.write
    fn write(&mut self, task: &mut Task, buf: &[u8]) -> io::Result<usize>;

    /// Flushes any internal buffers of this object, optionally using a `task`
    /// as a source of storage to draw from.
    ///
    /// Otherwise behaves the same as [`Write::flush`][stdflush]
    ///
    /// [stdflush]: https://doc.rust-lang.org/std/io/trait.Write.html#tymethod.flush
    fn flush(&mut self, task: &mut Task) -> io::Result<()>;
}

impl Ready {
    /// Returns whether this readiness notification indicates that an object is
    /// readable.
    pub fn is_read(&self) -> bool {
        match *self {
            Ready::Read | Ready::ReadWrite => true,
            Ready::Write => false,
        }
    }

    /// Returns whether this readiness notification indicates that an object is
    /// writable.
    pub fn is_write(&self) -> bool {
        match *self {
            Ready::Write | Ready::ReadWrite => true,
            Ready::Read => false,
        }
    }
}

impl BitOr for Ready {
    type Output = Ready;

    fn bitor(self, other: Ready) -> Ready {
        match (self, other) {
            (Ready::ReadWrite, _) |
            (_, Ready::ReadWrite) |
            (Ready::Write, Ready::Read) |
            (Ready::Read, Ready::Write) => Ready::ReadWrite,

            (Ready::Read, Ready::Read) => Ready::Read,
            (Ready::Write, Ready::Write) => Ready::Write,
        }
    }
}
<commit_msg>Reexport more TaskIo types<commit_after>//! Future-based abstractions for dealing with I/O
//!
//! Building on top of the `futures` crate the purpose of this crate is to
//! provide the abstractions necessary for interoperating I/O streams in an
//! asynchronous fashion.
//!
//! At its core is the abstraction of I/O objects as a collection of `Read`,
//! `Write`, and `Stream<Item=Ready, Error=io::Error>` implementations. This can
//! then be used to define a number of combinators and then later define further
//! abstractions on these streams.
//!
//! Note that this library is currently a work in progress, but stay tuned for
//! updates!

#![deny(missing_docs)]

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

use std::io;
use std::ops::BitOr;

use futures::{Task, Future};
use futures::stream::Stream;

/// A macro to assist with dealing with `io::Result<T>` types where the error
/// may have the type `WouldBlock`.
///
/// Converts all `Ok` values to `Some`, `WouldBlock` errors to `None`, and
/// otherwise returns all other errors upwards the stack.
#[macro_export]
macro_rules! try_nb {
    ($e:expr) => (match $e {
        Ok(e) => Some(e),
        Err(ref e) if e.kind() == ::std::io::ErrorKind::WouldBlock => None,
        Err(e) => return Err(::std::convert::From::from(e)),
    })
}

/// A convenience typedef around a `Future` whose error component is `io::Error`
pub type IoFuture<T> = Future<Item=T, Error=io::Error>;

/// A convenience typedef around a `Stream` whose error component is `io::Error`
pub type IoStream<T> = Stream<Item=T, Error=io::Error>;

mod impls;

mod buf_reader;
mod buf_writer;
mod chain;
mod copy;
mod empty;
mod flush;
mod read_to_end;
mod repeat;
mod ready_tracker;
mod sink;
mod take;
mod task;
pub use self::buf_reader::BufReader;
pub use self::buf_writer::BufWriter;
pub use self::chain::{chain, Chain};
pub use self::copy::{copy, Copy};
pub use self::empty::{empty, Empty};
pub use self::flush::{flush, Flush};
pub use self::read_to_end::{read_to_end, ReadToEnd};
pub use self::ready_tracker::ReadyTracker;
pub use self::repeat::{repeat, Repeat};
pub use self::sink::{sink, Sink};
pub use self::take::{take, Take};
pub use self::task::{TaskIo, TaskIoRead, TaskIoWrite};

/// Readiness notifications that a stream can deliver.
///
/// This is the primary point element yielded in `Stream` implementations on I/O
/// objects, indicating whether it is ready to be read or written to.
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum Ready {
    /// The I/O object is ready for a read.
    Read,
    /// The I/O object is ready for a write.
    Write,
    /// The I/O object is ready for both reading and writing.
    ReadWrite,
}

/// A trait representing streams that can be read within the context of a
/// future's `Task`.
///
/// This is a trait used to implement some of the "terminal" abstractions
/// provided by this crate. It is less general than the `Read` trait, and all
/// types which implement `Read` also implement this trait.
///
/// The main purpose of this trait is to allow insertion of I/O objects into
/// task-local storage but still allow for a `Read` implementation on the
/// returned handle.
pub trait ReadTask: Stream<Item=Ready, Error=io::Error> {
    /// Reads bytes into a buffer, optionally using `task` as a source of
    /// storage to draw from.
    ///
    /// Otherwise behaves the same as [`Read::read`][stdread].
    ///
    /// [stdread]: https://doc.rust-lang.org/std/io/trait.Read.html#tymethod.read
    fn read(&mut self, task: &mut Task, buf: &mut [u8]) -> io::Result<usize>;

    /// Reads as much information as possible from this underlying stream into
    /// the vector provided, optionally using the `task` as a source of storage
    /// to draw from.
    ///
    /// Otherwise behaves the same as [`Read::read_to_end`][stdreadtoend].
    ///
    /// [stdreadtoend]: https://doc.rust-lang.org/std/io/trait.Read.html#tymethod.read_to_end
    fn read_to_end(&mut self,
                   task: &mut Task,
                   buf: &mut Vec<u8>) -> io::Result<usize>;
}

/// A trait representing streams that can be written to within the context of a
/// future's `Task`.
///
/// This is a trait used to implement some of the "terminal" abstractions
/// provided by this crate. It is less general than the `Write` trait, and all
/// types which implement `Write` also implement this trait.
///
/// The main purpose of this trait is to allow insertion of I/O objects into
/// task-local storage but still allow for a `Write` implementation on the
/// returned handle.
pub trait WriteTask: Stream<Item=Ready, Error=io::Error> {
    /// Writes a list of bytes into this object, optionally using a `task` as a
    /// source of storage to draw from.
    ///
    /// Otherwise behaves the same as [`Write::write`][stdwrite]
    ///
    /// [stdwrite]: https://doc.rust-lang.org/std/io/trait.Write.html#tymethod.write
    fn write(&mut self, task: &mut Task, buf: &[u8]) -> io::Result<usize>;

    /// Flushes any internal buffers of this object, optionally using a `task`
    /// as a source of storage to draw from.
    ///
    /// Otherwise behaves the same as [`Write::flush`][stdflush]
    ///
    /// [stdflush]: https://doc.rust-lang.org/std/io/trait.Write.html#tymethod.flush
    fn flush(&mut self, task: &mut Task) -> io::Result<()>;
}

impl Ready {
    /// Returns whether this readiness notification indicates that an object is
    /// readable.
    pub fn is_read(&self) -> bool {
        match *self {
            Ready::Read | Ready::ReadWrite => true,
            Ready::Write => false,
        }
    }

    /// Returns whether this readiness notification indicates that an object is
    /// writable.
    pub fn is_write(&self) -> bool {
        match *self {
            Ready::Write | Ready::ReadWrite => true,
            Ready::Read => false,
        }
    }
}

impl BitOr for Ready {
    type Output = Ready;

    fn bitor(self, other: Ready) -> Ready {
        match (self, other) {
            (Ready::ReadWrite, _) |
            (_, Ready::ReadWrite) |
            (Ready::Write, Ready::Read) |
            (Ready::Read, Ready::Write) => Ready::ReadWrite,

            (Ready::Read, Ready::Read) => Ready::Read,
            (Ready::Write, Ready::Write) => Ready::Write,
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Auto merge of #11044 - Eh2406:file_hash, r=weihanglo<commit_after><|endoftext|>


<commit_before>// Test rules governing higher-order pure fns.

fn assign_to_pure(x: pure fn(), y: fn(), z: unsafe fn()) {
    let a: pure fn() = x;
    let b: pure fn() = y; //! ERROR expected pure fn but found impure fn
    let c: pure fn() = z; //! ERROR expected pure fn but found unsafe fn
}

fn assign_to_impure(x: pure fn(), y: fn(), z: unsafe fn()) {
    let h: fn() = x;
    let i: fn() = y;
    let j: fn() = z; //! ERROR expected impure fn but found unsafe fn
}

fn assign_to_unsafe(x: pure fn(), y: fn(), z: unsafe fn()) {
    let m: unsafe fn() = x;
    let n: unsafe fn() = y;
    let o: unsafe fn() = z;
}

fn main() {
}<commit_msg>test our some of the various combinations of fn subtyping<commit_after>// Test rules governing higher-order pure fns.

fn assign_to_pure(x: pure fn(), y: fn(), z: unsafe fn()) {
    let a: pure fn() = x;
    let b: pure fn() = y; //! ERROR expected pure fn but found impure fn
    let c: pure fn() = z; //! ERROR expected pure fn but found unsafe fn
}

fn assign_to_impure(x: pure fn(), y: fn(), z: unsafe fn()) {
    let h: fn() = x;
    let i: fn() = y;
    let j: fn() = z; //! ERROR expected impure fn but found unsafe fn
}

fn assign_to_unsafe(x: pure fn(), y: fn(), z: unsafe fn()) {
    let m: unsafe fn() = x;
    let n: unsafe fn() = y;
    let o: unsafe fn() = z;
}

fn assign_to_pure2(x: pure fn@(), y: fn@(), z: unsafe fn@()) {
    let a: pure fn() = x;
    let b: pure fn() = y; //! ERROR expected pure fn but found impure fn
    let c: pure fn() = z; //! ERROR expected pure fn but found unsafe fn

    let a: pure fn~() = x; //! ERROR closure protocol mismatch (fn~ vs fn@)
    let b: pure fn~() = y; //! ERROR closure protocol mismatch (fn~ vs fn@)
    let c: pure fn~() = z; //! ERROR closure protocol mismatch (fn~ vs fn@)

    let a: unsafe fn~() = x; //! ERROR closure protocol mismatch (fn~ vs fn@)
    let b: unsafe fn~() = y; //! ERROR closure protocol mismatch (fn~ vs fn@)
    let c: unsafe fn~() = z; //! ERROR closure protocol mismatch (fn~ vs fn@)
}

fn main() {
}<|endoftext|>


<commit_before><commit_msg>Skeleton for problem 1996<commit_after>// https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/
pub fn number_of_weak_characters(properties: Vec<Vec<i32>>) -> i32 {
    todo!()
}

fn main() {
    println!(
        "{}",
        number_of_weak_characters(vec![vec![5, 5], vec![6, 3], vec![3, 6]])
    ); // 0
    println!(
        "{}",
        number_of_weak_characters(vec![vec![2, 2], vec![3, 3]])
    ); // 1
    println!(
        "{}",
        number_of_weak_characters(vec![vec![1, 5], vec![10, 4], vec![4, 3]])
    ); // 1
}
<|endoftext|>


<commit_before><commit_msg>continued demacrofication<commit_after><|endoftext|>


<commit_before><commit_msg>add Cognito Identity integration tests<commit_after>#![cfg(feature = "cognito-identity")]

extern crate rusoto;

use rusoto::cognitoidentity::{CognitoIdentityClient, ListIdentitiesInput, ListIdentitiesError, ListIdentityPoolsInput};
use rusoto::{DefaultCredentialsProvider, Region};

#[test]
fn should_list_identity_pools() {
    let credentials = DefaultCredentialsProvider::new().unwrap();
    let client = CognitoIdentityClient::new(credentials, Region::UsEast1);

    let mut request = ListIdentityPoolsInput::default();
    request.max_results = 10;

    match client.list_identity_pools(&request) {
    	Ok(response) => {
    		println!("{:#?}", response);
    		assert!(true)
    	},
    	Err(err) => panic!("Expected OK response, got {:#?}", err)
    };
}

#[test]
fn should_handle_validation_errors_gracefully() {
    let credentials = DefaultCredentialsProvider::new().unwrap();
    let client = CognitoIdentityClient::new(credentials, Region::UsEast1);

    let mut request = ListIdentitiesInput::default();
    request.max_results = 10;
    request.identity_pool_id = "invalid".to_string();

    match client.list_identities(&request) {
    	Err(ListIdentitiesError::Validation(msg)) => {
    		assert!(msg.contains("identityPoolId"))
    	},
    	err @ _ => panic!("Expected Validation error - got {:#?}", err),
    };
}
<|endoftext|>


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

#![feature(rustc_attrs)]

mod a {
    pub mod b { pub struct Foo; }

    pub mod c {
        use super::b;
        pub struct Bar(pub b::Foo);
    }

    pub use self::c::*;
}

#[rustc_error]
fn main() {  //~ ERROR compilation successful
    let _ = a::c::Bar(a::b::Foo);
    let _ = a::Bar(a::b::Foo);
}
<|endoftext|>


<commit_before><commit_msg>Added tcp server<commit_after>use std::net::{TcpListener, TcpStream};
use std::thread;
use std::io::{Read, Write, Error};

fn handle_client(mut stream: TcpStream) -> Result<(),Error> {
    println!("Incoming connection from: {}",stream.peer_addr()?);
    let mut buf = [0; 512];
    loop {
         let bytes_read = stream.read(&mut buf)?;
         if bytes_read == 0 {
            return Ok(());
         }
         stream.write(&buf[..bytes_read])?;
    }
}

fn main () {
    let listener = TcpListener::bind("0.0.0.0:8888").expect("Could not bind");
    for stream in listener.incoming() {
        match stream {
            Err(e) => { eprintln!("failed: {}",e)}
            Ok(stream) => {
                thread::spawn( move || {
                    handle_client(stream).unwrap_or_else(|error| eprintln!("{:?}",error));
                });
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>add liquid-dsp msresamp wrapper<commit_after>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Andres Vahter (andres.vahter@gmail.com)
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

use liquid::ffiliquid;
use liquid::{Complex32};

pub struct MsresampCrcf {
     object: ffiliquid::msresamp_crcf,
}

impl MsresampCrcf {

    /// create multi-stage arbitrary resampler
    ///  _r      :   resampling rate [output/input]
    ///  _as     :   stop-band attenuation [dB]
    pub fn new(_r: f32, _as: f32) -> MsresampCrcf {
        let resampler: ffiliquid::msresamp_crcf = unsafe{ffiliquid::msresamp_crcf_create(_r, _as)};
        MsresampCrcf{object: resampler}
    }

    /// get filter delay (output samples)
    pub fn get_delay(&self) -> f32 {
        unsafe{ffiliquid::msresamp_crcf_get_delay(self.object)}
    }

    /// execute multi-stage resampler
    ///  _q      :   msresamp object
    ///  _x      :   input sample array  [size: _nx x 1]
    ///  _nx     :   input sample array size
    ///  _y      :   output sample array [size: variable]
    ///  _ny     :   number of samples written to _y
    pub fn execute(&self, _x: *mut Complex32, _nx: u32, _y: *mut Complex32, _ny: *mut u32) {
        unsafe{ffiliquid::msresamp_crcf_execute(self.object, _x, _nx, _y, _ny)};
    }
}

impl Drop for MsresampCrcf {
    fn drop(&mut self) {
        unsafe{ffiliquid::msresamp_crcf_destroy(self.object)};
    }
}
<|endoftext|>


<commit_before><commit_msg>Use git-describe rather than rev-parse<commit_after><|endoftext|>


<commit_before><commit_msg> removed filter for testing<commit_after><|endoftext|>


<commit_before><commit_msg>update readme<commit_after>use std::marker::PhantomData;
use std::fmt::Debug;
//use std::{mem ,slice};

use num::traits::Num;

use core::*;

use super::BlockData;

// fn twice<W, O>(x: i32) -> i32 {
//     x + x
// }

// use FN
pub struct FunctionBlock<W, O>
where W: Num   , O: Num
{
    block: BlockData,
    w: PhantomData<W>,
    o: PhantomData<O>,
    //neural_behaviour: PhantomData<N>,
}

impl<W,O>  FunctionBlock<W,O>
where W: Num  , O: Num
{

    pub fn new (newid: BlockId , ncount: u32 , scount: u32) -> FunctionBlock<  W , O >
    {
        let block_data = BlockData { id : newid , neuron_count: ncount , synapse_count: scount , ..Default::default() } ;
        FunctionBlock::new_b(block_data )
    }

    pub fn new_b(block_data: BlockData )  -> FunctionBlock<  W , O >
    {
        if block_data.neuron_count == 0 || block_data.synapse_count == 0 {  panic!("neuron or synapse_count cannot be 0"); };
        FunctionBlock { block : block_data ,    w: ::std::marker::PhantomData , o: ::std::marker::PhantomData     }
    }
}

impl<W  ,O > IBlock for FunctionBlock< W ,O >
where W: Num + Debug  , O: Num + Debug
//where T:NeuronBlock<f32,f32>
{
    fn behaviour(&self) -> BlockBehaviour  { BlockBehaviour::Immutable }

// not needed ?
    fn get_id(&self) -> BlockId { self.block.id }

    fn process(&self , _data: & mut [u8] , _inputs: &[& [u8]] , outputs: & mut [u8])
    {
         if outputs.len() == 0 { println!("warning 0 length output " );}
        // unsafe
        // {
        //     let weight_size = mem::size_of::<W>();
        //     let weights: & [W] = slice::from_raw_parts( data.as_ptr() as *const W, data.len()/ weight_size);
        //     let input_o = inputs [0];
        //     let input: & [O] = slice::from_raw_parts( input_o.as_ptr() as *const O, input_o.len()/ mem::size_of::<O>());
        //     let outputs: & mut [O] = slice::from_raw_parts_mut( outputs.as_ptr() as *mut O, outputs.len()/ mem::size_of::<O>());
        //
        //     self.process_input( weights , input , outputs);
        //
        // }
    }

    fn process_self_copy_output(& mut self) ->  Vec<u8>
    {
            panic!("no buffers setup or NeuronBlocks cant be  mutable ");
    }

}

// full mesh checks
#[test]
fn functionblock_create_bloc ()
{
    let _block  =  FunctionBlock::<f32,f32>::new(5 , 5, 5);
}

//
<|endoftext|>