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

use session::config::Options;

use std::fs;
use std::io::{self, StdoutLock, Write};
use std::time::{Duration, Instant};

macro_rules! define_categories {
    ($($name:ident,)*) => {
        #[derive(Clone, Copy, Debug, PartialEq, Eq)]
        pub enum ProfileCategory {
            $($name),*
        }

        #[allow(nonstandard_style)]
        struct Categories<T> {
            $($name: T),*
        }

        impl<T: Default> Categories<T> {
            fn new() -> Categories<T> {
                Categories {
                    $($name: T::default()),*
                }
            }
        }

        impl<T> Categories<T> {
            fn get(&self, category: ProfileCategory) -> &T {
                match category {
                    $(ProfileCategory::$name => &self.$name),*
                }
            }

            fn set(&mut self, category: ProfileCategory, value: T) {
                match category {
                    $(ProfileCategory::$name => self.$name = value),*
                }
            }
        }

        struct CategoryData {
            times: Categories<u64>,
            query_counts: Categories<(u64, u64)>,
        }

        impl CategoryData {
            fn new() -> CategoryData {
                CategoryData {
                    times: Categories::new(),
                    query_counts: Categories::new(),
                }
            }

            fn print(&self, lock: &mut StdoutLock<'_>) {
                writeln!(lock, "| Phase            | Time (ms)      | Queries        | Hits (%) |")
                    .unwrap();
                writeln!(lock, "| ---------------- | -------------- | -------------- | -------- |")
                    .unwrap();

                $(
                    let (hits, total) = self.query_counts.$name;
                    let (hits, total) = if total > 0 {
                        (format!("{:.2}",
                        (((hits as f32) / (total as f32)) * 100.0)), total.to_string())
                    } else {
                        (String::new(), String::new())
                    };

                    writeln!(
                        lock,
                        "| {0: <16} | {1: <14} | {2: <14} | {3: <8} |",
                        stringify!($name),
                        self.times.$name / 1_000_000,
                        total,
                        hits
                    ).unwrap();
                )*
            }

            fn json(&self) -> String {
                let mut json = String::from("[");

                $(
                    let (hits, total) = self.query_counts.$name;

                    //normalize hits to 0%
                    let hit_percent =
                        if total > 0 {
                            ((hits as f32) / (total as f32)) * 100.0
                        } else {
                            0.0
                        };

                    json.push_str(&format!(
                        "{{ \"category\": {}, \"time_ms\": {},
                            \"query_count\": {}, \"query_hits\": {} }},",
                        stringify!($name),
                        self.times.$name / 1_000_000,
                        total,
                        format!("{:.2}", hit_percent)
                    ));
                )*

                //remove the trailing ',' character
                json.pop();

                json.push(']');

                json
            }
        }
    }
}

define_categories! {
    Parsing,
    Expansion,
    TypeChecking,
    BorrowChecking,
    Codegen,
    Linking,
    Other,
}

pub struct SelfProfiler {
    timer_stack: Vec<ProfileCategory>,
    data: CategoryData,
    current_timer: Instant,
}

impl SelfProfiler {
    pub fn new() -> SelfProfiler {
        let mut profiler = SelfProfiler {
            timer_stack: Vec::new(),
            data: CategoryData::new(),
            current_timer: Instant::now(),
        };

        profiler.start_activity(ProfileCategory::Other);

        profiler
    }

    pub fn start_activity(&mut self, category: ProfileCategory) {
        match self.timer_stack.last().cloned() {
            None => {
                self.current_timer = Instant::now();
            },
            Some(current_category) if current_category == category => {
                //since the current category is the same as the new activity's category,
                //we don't need to do anything with the timer, we just need to push it on the stack
            }
            Some(current_category) => {
                let elapsed = self.stop_timer();

                //record the current category's time
                let new_time = self.data.times.get(current_category) + elapsed;
                self.data.times.set(current_category, new_time);
            }
        }

        //push the new category
        self.timer_stack.push(category);
    }

    pub fn record_query(&mut self, category: ProfileCategory) {
        let (hits, total) = *self.data.query_counts.get(category);
        self.data.query_counts.set(category, (hits, total + 1));
    }

    pub fn record_query_hit(&mut self, category: ProfileCategory) {
        let (hits, total) = *self.data.query_counts.get(category);
        self.data.query_counts.set(category, (hits + 1, total));
    }

    pub fn end_activity(&mut self, category: ProfileCategory) {
        match self.timer_stack.pop() {
            None => bug!("end_activity() was called but there was no running activity"),
            Some(c) =>
                assert!(
                    c == category,
                    "end_activity() was called but a different activity was running"),
        }

        //check if the new running timer is in the same category as this one
        //if it is, we don't need to do anything
        if let Some(c) = self.timer_stack.last() {
            if *c == category {
                return;
            }
        }

        //the new timer is different than the previous,
        //so record the elapsed time and start a new timer
        let elapsed = self.stop_timer();
        let new_time = self.data.times.get(category) + elapsed;
        self.data.times.set(category, new_time);
    }

    fn stop_timer(&mut self) -> u64 {
        let elapsed = if cfg!(windows) {
            // On Windows, timers don't always appear to be monotonic (see #51648)
            // which can lead to panics when calculating elapsed time.
            // Work around this by testing to see if the current time is less than
            // our recorded time, and if it is, just returning 0.
            let now = Instant::now();
            if self.current_timer >= now {
                Duration::new(0, 0)
            } else {
                self.current_timer.elapsed()
            }
        } else {
            self.current_timer.elapsed()
        };

        self.current_timer = Instant::now();

        (elapsed.as_secs() * 1_000_000_000) + (elapsed.subsec_nanos() as u64)
    }

    pub fn print_results(&mut self, opts: &Options) {
        self.end_activity(ProfileCategory::Other);

        assert!(
            self.timer_stack.is_empty(),
            "there were timers running when print_results() was called");

        let out = io::stdout();
        let mut lock = out.lock();

        let crate_name =
            opts.crate_name
            .as_ref()
            .map(|n| format!(" for {}", n))
            .unwrap_or_default();

        writeln!(lock, "Self profiling results{}:", crate_name).unwrap();
        writeln!(lock).unwrap();

        self.data.print(&mut lock);

        writeln!(lock).unwrap();
        writeln!(lock, "Optimization level: {:?}", opts.optimize).unwrap();

        let incremental = if opts.incremental.is_some() { "on" } else { "off" };
        writeln!(lock, "Incremental: {}", incremental).unwrap();
    }

    pub fn save_results(&self, opts: &Options) {
        let category_data = self.data.json();
        let compilation_options =
            format!("{{ \"optimization_level\": \"{:?}\", \"incremental\": {} }}",
                    opts.optimize,
                    if opts.incremental.is_some() { "true" } else { "false" });

        let json = format!("{{ \"category_data\": {}, \"compilation_options\": {} }}",
                        category_data,
                        compilation_options);

        fs::write("self_profiler_results.json", json).unwrap();
    }
}
<commit_msg>Make JSON output from -Zprofile-json valid<commit_after>// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use session::config::Options;

use std::fs;
use std::io::{self, StdoutLock, Write};
use std::time::{Duration, Instant};

macro_rules! define_categories {
    ($($name:ident,)*) => {
        #[derive(Clone, Copy, Debug, PartialEq, Eq)]
        pub enum ProfileCategory {
            $($name),*
        }

        #[allow(nonstandard_style)]
        struct Categories<T> {
            $($name: T),*
        }

        impl<T: Default> Categories<T> {
            fn new() -> Categories<T> {
                Categories {
                    $($name: T::default()),*
                }
            }
        }

        impl<T> Categories<T> {
            fn get(&self, category: ProfileCategory) -> &T {
                match category {
                    $(ProfileCategory::$name => &self.$name),*
                }
            }

            fn set(&mut self, category: ProfileCategory, value: T) {
                match category {
                    $(ProfileCategory::$name => self.$name = value),*
                }
            }
        }

        struct CategoryData {
            times: Categories<u64>,
            query_counts: Categories<(u64, u64)>,
        }

        impl CategoryData {
            fn new() -> CategoryData {
                CategoryData {
                    times: Categories::new(),
                    query_counts: Categories::new(),
                }
            }

            fn print(&self, lock: &mut StdoutLock<'_>) {
                writeln!(lock, "| Phase            | Time (ms)      | Queries        | Hits (%) |")
                    .unwrap();
                writeln!(lock, "| ---------------- | -------------- | -------------- | -------- |")
                    .unwrap();

                $(
                    let (hits, total) = self.query_counts.$name;
                    let (hits, total) = if total > 0 {
                        (format!("{:.2}",
                        (((hits as f32) / (total as f32)) * 100.0)), total.to_string())
                    } else {
                        (String::new(), String::new())
                    };

                    writeln!(
                        lock,
                        "| {0: <16} | {1: <14} | {2: <14} | {3: <8} |",
                        stringify!($name),
                        self.times.$name / 1_000_000,
                        total,
                        hits
                    ).unwrap();
                )*
            }

            fn json(&self) -> String {
                let mut json = String::from("[");

                $(
                    let (hits, total) = self.query_counts.$name;

                    //normalize hits to 0%
                    let hit_percent =
                        if total > 0 {
                            ((hits as f32) / (total as f32)) * 100.0
                        } else {
                            0.0
                        };

                    json.push_str(&format!(
                        "{{ \"category\": \"{}\", \"time_ms\": {},\
                            \"query_count\": {}, \"query_hits\": {} }},",
                        stringify!($name),
                        self.times.$name / 1_000_000,
                        total,
                        format!("{:.2}", hit_percent)
                    ));
                )*

                //remove the trailing ',' character
                json.pop();

                json.push(']');

                json
            }
        }
    }
}

define_categories! {
    Parsing,
    Expansion,
    TypeChecking,
    BorrowChecking,
    Codegen,
    Linking,
    Other,
}

pub struct SelfProfiler {
    timer_stack: Vec<ProfileCategory>,
    data: CategoryData,
    current_timer: Instant,
}

impl SelfProfiler {
    pub fn new() -> SelfProfiler {
        let mut profiler = SelfProfiler {
            timer_stack: Vec::new(),
            data: CategoryData::new(),
            current_timer: Instant::now(),
        };

        profiler.start_activity(ProfileCategory::Other);

        profiler
    }

    pub fn start_activity(&mut self, category: ProfileCategory) {
        match self.timer_stack.last().cloned() {
            None => {
                self.current_timer = Instant::now();
            },
            Some(current_category) if current_category == category => {
                //since the current category is the same as the new activity's category,
                //we don't need to do anything with the timer, we just need to push it on the stack
            }
            Some(current_category) => {
                let elapsed = self.stop_timer();

                //record the current category's time
                let new_time = self.data.times.get(current_category) + elapsed;
                self.data.times.set(current_category, new_time);
            }
        }

        //push the new category
        self.timer_stack.push(category);
    }

    pub fn record_query(&mut self, category: ProfileCategory) {
        let (hits, total) = *self.data.query_counts.get(category);
        self.data.query_counts.set(category, (hits, total + 1));
    }

    pub fn record_query_hit(&mut self, category: ProfileCategory) {
        let (hits, total) = *self.data.query_counts.get(category);
        self.data.query_counts.set(category, (hits + 1, total));
    }

    pub fn end_activity(&mut self, category: ProfileCategory) {
        match self.timer_stack.pop() {
            None => bug!("end_activity() was called but there was no running activity"),
            Some(c) =>
                assert!(
                    c == category,
                    "end_activity() was called but a different activity was running"),
        }

        //check if the new running timer is in the same category as this one
        //if it is, we don't need to do anything
        if let Some(c) = self.timer_stack.last() {
            if *c == category {
                return;
            }
        }

        //the new timer is different than the previous,
        //so record the elapsed time and start a new timer
        let elapsed = self.stop_timer();
        let new_time = self.data.times.get(category) + elapsed;
        self.data.times.set(category, new_time);
    }

    fn stop_timer(&mut self) -> u64 {
        let elapsed = if cfg!(windows) {
            // On Windows, timers don't always appear to be monotonic (see #51648)
            // which can lead to panics when calculating elapsed time.
            // Work around this by testing to see if the current time is less than
            // our recorded time, and if it is, just returning 0.
            let now = Instant::now();
            if self.current_timer >= now {
                Duration::new(0, 0)
            } else {
                self.current_timer.elapsed()
            }
        } else {
            self.current_timer.elapsed()
        };

        self.current_timer = Instant::now();

        (elapsed.as_secs() * 1_000_000_000) + (elapsed.subsec_nanos() as u64)
    }

    pub fn print_results(&mut self, opts: &Options) {
        self.end_activity(ProfileCategory::Other);

        assert!(
            self.timer_stack.is_empty(),
            "there were timers running when print_results() was called");

        let out = io::stdout();
        let mut lock = out.lock();

        let crate_name =
            opts.crate_name
            .as_ref()
            .map(|n| format!(" for {}", n))
            .unwrap_or_default();

        writeln!(lock, "Self profiling results{}:", crate_name).unwrap();
        writeln!(lock).unwrap();

        self.data.print(&mut lock);

        writeln!(lock).unwrap();
        writeln!(lock, "Optimization level: {:?}", opts.optimize).unwrap();

        let incremental = if opts.incremental.is_some() { "on" } else { "off" };
        writeln!(lock, "Incremental: {}", incremental).unwrap();
    }

    pub fn save_results(&self, opts: &Options) {
        let category_data = self.data.json();
        let compilation_options =
            format!("{{ \"optimization_level\": \"{:?}\", \"incremental\": {} }}",
                    opts.optimize,
                    if opts.incremental.is_some() { "true" } else { "false" });

        let json = format!("{{ \"category_data\": {}, \"compilation_options\": {} }}",
                        category_data,
                        compilation_options);

        fs::write("self_profiler_results.json", json).unwrap();
    }
}
<|endoftext|>


<commit_before><commit_msg>Update get stores macro<commit_after><|endoftext|>


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

#![feature(intrinsics)]
extern "rust-intrinsic" {
    fn atomic_foo(); //~ ERROR E0092
}

fn main() {
}
<commit_msg>Update unit test for E0092<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(intrinsics)]
extern "rust-intrinsic" {
    fn atomic_foo(); //~ ERROR E0092
}                    //~| NOTE unrecognized atomic operation

fn main() {
}
<|endoftext|>


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

#![feature(rustc_attrs)]

// no-pretty-expanded FIXME #15189
// ignore-android FIXME #17520
// compile-flags:-g

use std::env;
use std::process::{Command, Stdio};
use std::str;

// FIXME #31005 MIR missing debuginfo currently.
#[cfg_attr(target_env = "msvc", rustc_no_mir)]
#[inline(never)]
fn foo() {
    let _v = vec![1, 2, 3];
    if env::var_os("IS_TEST").is_some() {
        panic!()
    }
}

// FIXME #31005 MIR missing debuginfo currently.
#[cfg_attr(target_env = "msvc", rustc_no_mir)]
#[inline(never)]
fn double() {
    struct Double;

    impl Drop for Double {
        fn drop(&mut self) { panic!("twice") }
    }

    let _d = Double;

    panic!("once");
}

fn template(me: &str) -> Command {
    let mut m = Command::new(me);
    m.env("IS_TEST", "1")
     .stdout(Stdio::piped())
     .stderr(Stdio::piped());
    return m;
}

fn expected(fn_name: &str) -> String {
    // FIXME(#32481)
    //
    // On windows, we read the function name from debuginfo using some
    // system APIs. For whatever reason, these APIs seem to use the
    // "name" field, which is only the "relative" name, not the full
    // name with namespace info, so we just see `foo` and not
    // `backtrace::foo` as we see on linux (which uses the linkage
    // name).

    if cfg!(windows) {
        format!(" - {}", fn_name)
    } else {
        format!(" - backtrace::{}", fn_name)
    }
}

fn runtest(me: &str) {
    // Make sure that the stack trace is printed
    let p = template(me).arg("fail").env("RUST_BACKTRACE", "1").spawn().unwrap();
    let out = p.wait_with_output().unwrap();
    assert!(!out.status.success());
    let s = str::from_utf8(&out.stderr).unwrap();
    assert!(s.contains("stack backtrace") && s.contains(&expected("foo")),
            "bad output: {}", s);

    // Make sure the stack trace is *not* printed
    // (Remove RUST_BACKTRACE from our own environment, in case developer
    // is running `make check` with it on.)
    let p = template(me).arg("fail").env_remove("RUST_BACKTRACE").spawn().unwrap();
    let out = p.wait_with_output().unwrap();
    assert!(!out.status.success());
    let s = str::from_utf8(&out.stderr).unwrap();
    assert!(!s.contains("stack backtrace") && !s.contains(&expected("foo")),
            "bad output2: {}", s);

    // Make sure a stack trace is printed
    let p = template(me).arg("double-fail").spawn().unwrap();
    let out = p.wait_with_output().unwrap();
    assert!(!out.status.success());
    let s = str::from_utf8(&out.stderr).unwrap();
    // loosened the following from double::h to double:: due to
    // spurious failures on mac, 32bit, optimized
    assert!(s.contains("stack backtrace") && s.contains(&expected("double")),
            "bad output3: {}", s);

    // Make sure a stack trace isn't printed too many times
    let p = template(me).arg("double-fail")
                                .env("RUST_BACKTRACE", "1").spawn().unwrap();
    let out = p.wait_with_output().unwrap();
    assert!(!out.status.success());
    let s = str::from_utf8(&out.stderr).unwrap();
    let mut i = 0;
    for _ in 0..2 {
        i += s[i + 10..].find("stack backtrace").unwrap() + 10;
    }
    assert!(s[i + 10..].find("stack backtrace").is_none(),
            "bad output4: {}", s);
}

fn main() {
    if cfg!(windows) && cfg!(target_arch = "x86") && cfg!(target_env = "gnu") {
        return
    }

    let args: Vec<String> = env::args().collect();
    if args.len() >= 2 && args[1] == "fail" {
        foo();
    } else if args.len() >= 2 && args[1] == "double-fail" {
        double();
    } else {
        runtest(&args[0]);
    }
}
<commit_msg>change test to be specific for msvc<commit_after>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![feature(rustc_attrs)]

// no-pretty-expanded FIXME #15189
// ignore-android FIXME #17520
// compile-flags:-g

use std::env;
use std::process::{Command, Stdio};
use std::str;

// FIXME #31005 MIR missing debuginfo currently.
#[cfg_attr(target_env = "msvc", rustc_no_mir)]
#[inline(never)]
fn foo() {
    let _v = vec![1, 2, 3];
    if env::var_os("IS_TEST").is_some() {
        panic!()
    }
}

// FIXME #31005 MIR missing debuginfo currently.
#[cfg_attr(target_env = "msvc", rustc_no_mir)]
#[inline(never)]
fn double() {
    struct Double;

    impl Drop for Double {
        fn drop(&mut self) { panic!("twice") }
    }

    let _d = Double;

    panic!("once");
}

fn template(me: &str) -> Command {
    let mut m = Command::new(me);
    m.env("IS_TEST", "1")
     .stdout(Stdio::piped())
     .stderr(Stdio::piped());
    return m;
}

fn expected(fn_name: &str) -> String {
    // FIXME(#32481)
    //
    // On windows, we read the function name from debuginfo using some
    // system APIs. For whatever reason, these APIs seem to use the
    // "name" field, which is only the "relative" name, not the full
    // name with namespace info, so we just see `foo` and not
    // `backtrace::foo` as we see on linux (which uses the linkage
    // name).
    if cfg!(windows) && cfg!(target_env = "msvc") {
        format!(" - {}", fn_name)
    } else {
        format!(" - backtrace::{}", fn_name)
    }
}

fn runtest(me: &str) {
    // Make sure that the stack trace is printed
    let p = template(me).arg("fail").env("RUST_BACKTRACE", "1").spawn().unwrap();
    let out = p.wait_with_output().unwrap();
    assert!(!out.status.success());
    let s = str::from_utf8(&out.stderr).unwrap();
    assert!(s.contains("stack backtrace") && s.contains(&expected("foo")),
            "bad output: {}", s);

    // Make sure the stack trace is *not* printed
    // (Remove RUST_BACKTRACE from our own environment, in case developer
    // is running `make check` with it on.)
    let p = template(me).arg("fail").env_remove("RUST_BACKTRACE").spawn().unwrap();
    let out = p.wait_with_output().unwrap();
    assert!(!out.status.success());
    let s = str::from_utf8(&out.stderr).unwrap();
    assert!(!s.contains("stack backtrace") && !s.contains(&expected("foo")),
            "bad output2: {}", s);

    // Make sure a stack trace is printed
    let p = template(me).arg("double-fail").spawn().unwrap();
    let out = p.wait_with_output().unwrap();
    assert!(!out.status.success());
    let s = str::from_utf8(&out.stderr).unwrap();
    // loosened the following from double::h to double:: due to
    // spurious failures on mac, 32bit, optimized
    assert!(s.contains("stack backtrace") && s.contains(&expected("double")),
            "bad output3: {}", s);

    // Make sure a stack trace isn't printed too many times
    let p = template(me).arg("double-fail")
                                .env("RUST_BACKTRACE", "1").spawn().unwrap();
    let out = p.wait_with_output().unwrap();
    assert!(!out.status.success());
    let s = str::from_utf8(&out.stderr).unwrap();
    let mut i = 0;
    for _ in 0..2 {
        i += s[i + 10..].find("stack backtrace").unwrap() + 10;
    }
    assert!(s[i + 10..].find("stack backtrace").is_none(),
            "bad output4: {}", s);
}

fn main() {
    if cfg!(windows) && cfg!(target_arch = "x86") && cfg!(target_env = "gnu") {
        return
    }

    let args: Vec<String> = env::args().collect();
    if args.len() >= 2 && args[1] == "fail" {
        foo();
    } else if args.len() >= 2 && args[1] == "double-fail" {
        double();
    } else {
        runtest(&args[0]);
    }
}
<|endoftext|>


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


<commit_before><commit_msg>Add '--output' option support<commit_after><|endoftext|>


<commit_before><commit_msg>add missing export<commit_after><|endoftext|>


<commit_before>#![allow(dead_code)]
extern crate rusoto;
extern crate xml;
extern crate time;
extern crate regex;
extern crate rustc_serialize;
use rusoto::credentials::*;
use rusoto::error::*;
use rusoto::sqs::*;
use time::*;

fn main() {
	let mut provider = DefaultAWSCredentialsProviderChain::new();
	let creds = provider.get_credentials();

	println!("Creds in main: {}, {}, {}.", creds.get_aws_secret_key(), creds.get_aws_secret_key(),
		creds.get_token());

	match sqs_roundtrip_tests(&creds) {
		Ok(_) => { println!("Everything worked."); },
		Err(err) => { println!("Got error: {:#?}", err); }
	}
}

// fn sns_roundtrip_tests(creds: AWSCredentials) -> Result<(), AWSError> {
// 	let sns = SQSClient::new(creds, "us-east-1");
//
// 	let response = try!(sns.list_topics());
// 	println!("{:#?}", response);
// 	Ok(())
// }

fn sqs_roundtrip_tests(creds: &AWSCredentials) -> Result<(), AWSError> {
	return Ok(());
	let sqs = SQSHelper::new(&creds, "us-east-1");

	// list existing queues
	let response = try!(sqs.list_queues());
	for q in response.queue_urls {
		println!("Existing queue: {}", q);
	}

	// create a new queue
	let q_name = &format!("test_q_{}", get_time().sec);
	let response = try!(sqs.create_queue(q_name));
	println!("Created queue {} with url {}", q_name, response.queue_url);

	// query it by name
	let response = try!(sqs.get_queue_url(q_name));
	let queue_url = &response.queue_url;
	println!("Verified queue url {} for queue name {}", queue_url, q_name);

	// send it a message
	let msg_str = "lorem ipsum dolor sit amet";
	let response = try!(sqs.send_message(queue_url, msg_str));
	println!("Send message with body '{}' and created message_id {}", msg_str, response.message_id);

	// receive a message
	let response = try!(sqs.receive_message(queue_url));
	for msg in response.messages {
		println!("Received message '{}' with id {}", msg.body, msg.message_id);
		try!(sqs.delete_message(queue_url, &msg.receipt_handle));
	}

	// delete the queue
	try!(sqs.delete_queue(queue_url));
	println!("Queue {} deleted", queue_url);

	Ok(())
}
<commit_msg>Removes debugging line in main.<commit_after>#![allow(dead_code)]
extern crate rusoto;
extern crate xml;
extern crate time;
extern crate regex;
extern crate rustc_serialize;
use rusoto::credentials::*;
use rusoto::error::*;
use rusoto::sqs::*;
use time::*;

fn main() {
	let mut provider = DefaultAWSCredentialsProviderChain::new();
	let creds = provider.get_credentials();

	println!("Creds in main: {}, {}, {}.", creds.get_aws_secret_key(), creds.get_aws_secret_key(),
		creds.get_token());

	match sqs_roundtrip_tests(&creds) {
		Ok(_) => { println!("Everything worked."); },
		Err(err) => { println!("Got error: {:#?}", err); }
	}
}

// fn sns_roundtrip_tests(creds: AWSCredentials) -> Result<(), AWSError> {
// 	let sns = SQSClient::new(creds, "us-east-1");
//
// 	let response = try!(sns.list_topics());
// 	println!("{:#?}", response);
// 	Ok(())
// }

fn sqs_roundtrip_tests(creds: &AWSCredentials) -> Result<(), AWSError> {
	let sqs = SQSHelper::new(&creds, "us-east-1");

	// list existing queues
	let response = try!(sqs.list_queues());
	for q in response.queue_urls {
		println!("Existing queue: {}", q);
	}

	// create a new queue
	let q_name = &format!("test_q_{}", get_time().sec);
	let response = try!(sqs.create_queue(q_name));
	println!("Created queue {} with url {}", q_name, response.queue_url);

	// query it by name
	let response = try!(sqs.get_queue_url(q_name));
	let queue_url = &response.queue_url;
	println!("Verified queue url {} for queue name {}", queue_url, q_name);

	// send it a message
	let msg_str = "lorem ipsum dolor sit amet";
	let response = try!(sqs.send_message(queue_url, msg_str));
	println!("Send message with body '{}' and created message_id {}", msg_str, response.message_id);

	// receive a message
	let response = try!(sqs.receive_message(queue_url));
	for msg in response.messages {
		println!("Received message '{}' with id {}", msg.body, msg.message_id);
		try!(sqs.delete_message(queue_url, &msg.receipt_handle));
	}

	// delete the queue
	try!(sqs.delete_queue(queue_url));
	println!("Queue {} deleted", queue_url);

	Ok(())
}
<|endoftext|>


<commit_before>#![feature(rustc_private, custom_attribute)]
#![allow(unused_attributes)]

extern crate getopts;
extern crate miri;
extern crate rustc;
extern crate rustc_driver;
extern crate env_logger;
extern crate log_settings;
extern crate log;

use miri::interpreter;
use rustc::session::Session;
use rustc_driver::{driver, CompilerCalls};

struct MiriCompilerCalls;

impl<'a> CompilerCalls<'a> for MiriCompilerCalls {
    fn build_controller(
        &mut self,
        _: &Session,
        _: &getopts::Matches
    ) -> driver::CompileController<'a> {
        let mut control = driver::CompileController::basic();

        control.after_analysis.callback = Box::new(|state| {
            state.session.abort_if_errors();
            interpreter::interpret_start_points(state.tcx.unwrap(), state.mir_map.unwrap());
        });

        control
    }
}

#[miri_run]
fn main() {
    init_logger();
    let args: Vec<String> = std::env::args().collect();
    rustc_driver::run_compiler(&args, &mut MiriCompilerCalls);
}

#[miri_run]
fn init_logger() {
    let format = |record: &log::LogRecord| {
        // prepend spaces to indent the final string
        let indentation = log_settings::settings().indentation;
        let spaces = "                                  ";
        let indentation = &spaces[..std::cmp::min(indentation, spaces.len())];
        format!("{} -{} {}", record.level(), indentation, record.args())
    };

    let mut builder = env_logger::LogBuilder::new();
    builder.format(format).filter(None, log::LogLevelFilter::Info);

    if std::env::var("RUST_LOG").is_ok() {
        builder.parse(&std::env::var("RUST_LOG").unwrap());
    }

    builder.init().unwrap();
}
<commit_msg>re-introduce the module name to the logs and show vertical bars<commit_after>#![feature(rustc_private, custom_attribute)]
#![allow(unused_attributes)]

extern crate getopts;
extern crate miri;
extern crate rustc;
extern crate rustc_driver;
extern crate env_logger;
extern crate log_settings;
extern crate log;

use miri::interpreter;
use rustc::session::Session;
use rustc_driver::{driver, CompilerCalls};

struct MiriCompilerCalls;

impl<'a> CompilerCalls<'a> for MiriCompilerCalls {
    fn build_controller(
        &mut self,
        _: &Session,
        _: &getopts::Matches
    ) -> driver::CompileController<'a> {
        let mut control = driver::CompileController::basic();

        control.after_analysis.callback = Box::new(|state| {
            state.session.abort_if_errors();
            interpreter::interpret_start_points(state.tcx.unwrap(), state.mir_map.unwrap());
        });

        control
    }
}

#[miri_run]
fn main() {
    init_logger();
    let args: Vec<String> = std::env::args().collect();
    rustc_driver::run_compiler(&args, &mut MiriCompilerCalls);
}

#[miri_run]
fn init_logger() {
    let format = |record: &log::LogRecord| {
        // prepend spaces to indent the final string
        let indentation = log_settings::settings().indentation;
        let spaces = "    |    |    |    |    |    |    |    |    ";
        let indentation = &spaces[..std::cmp::min(indentation, spaces.len())];
        format!("{}:{}|{} {}", record.level(), record.location().module_path(), indentation, record.args())
    };

    let mut builder = env_logger::LogBuilder::new();
    builder.format(format).filter(None, log::LogLevelFilter::Info);

    if std::env::var("RUST_LOG").is_ok() {
        builder.parse(&std::env::var("RUST_LOG").unwrap());
    }

    builder.init().unwrap();
}
<|endoftext|>


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

use infer::at::At;
use infer::canonical::{Canonical, Canonicalize, QueryResult};
use infer::InferOk;
use std::iter::FromIterator;
use traits::query::CanonicalTyGoal;
use ty::{self, Ty, TyCtxt};
use ty::subst::Kind;
use std::rc::Rc;

impl<'cx, 'gcx, 'tcx> At<'cx, 'gcx, 'tcx> {
    /// Given a type `ty` of some value being dropped, computes a set
    /// of "kinds" (types, regions) that must be outlive the execution
    /// of the destructor. These basically correspond to data that the
    /// destructor might access. This is used during regionck to
    /// impose "outlives" constraints on any lifetimes referenced
    /// within.
    ///
    /// The rules here are given by the "dropck" RFCs, notably [#1238]
    /// and [#1327]. This is a fixed-point computation, where we
    /// explore all the data that will be dropped (transitively) when
    /// a value of type `ty` is dropped. For each type T that will be
    /// dropped and which has a destructor, we must assume that all
    /// the types/regions of T are live during the destructor, unless
    /// they are marked with a special attribute (`#[may_dangle]`).
    ///
    /// [#1238]: https://github.com/rust-lang/rfcs/blob/master/text/1238-nonparametric-dropck.md
    /// [#1327]: https://github.com/rust-lang/rfcs/blob/master/text/1327-dropck-param-eyepatch.md
    pub fn dropck_outlives(&self, ty: Ty<'tcx>) -> InferOk<'tcx, Vec<Kind<'tcx>>> {
        debug!(
            "dropck_outlives(ty={:?}, param_env={:?})",
            ty,
            self.param_env,
        );

        let tcx = self.infcx.tcx;
        let gcx = tcx.global_tcx();
        let (c_ty, orig_values) = self.infcx.canonicalize_query(&self.param_env.and(ty));
        let span = self.cause.span;
        match &gcx.dropck_outlives(c_ty) {
            Ok(result) if result.is_proven() => {
                match self.infcx.instantiate_query_result(
                    self.cause,
                    self.param_env,
                    &orig_values,
                    result,
                ) {
                    Ok(InferOk {
                        value: DropckOutlivesResult { kinds, overflows },
                        obligations,
                    }) => {
                        for overflow_ty in overflows.into_iter().take(1) {
                            let mut err = struct_span_err!(
                                tcx.sess,
                                span,
                                E0320,
                                "overflow while adding drop-check rules for {}",
                                self.infcx.resolve_type_vars_if_possible(&ty),
                            );
                            err.note(&format!("overflowed on {}", overflow_ty));
                            err.emit();
                        }

                        return InferOk {
                            value: kinds,
                            obligations,
                        };
                    }

                    Err(_) => { /* fallthrough to error-handling code below */ }
                }
            }

            _ => { /* fallthrough to error-handling code below */ }
        }

        // Errors and ambiuity in dropck occur in two cases:
        // - unresolved inference variables at the end of typeck
        // - non well-formed types where projections cannot be resolved
        // Either of these should hvae created an error before.
        tcx.sess
            .delay_span_bug(span, "dtorck encountered internal error");
        return InferOk {
            value: vec![],
            obligations: vec![],
        };
    }
}

#[derive(Clone, Debug)]
pub struct DropckOutlivesResult<'tcx> {
    pub kinds: Vec<Kind<'tcx>>,
    pub overflows: Vec<Ty<'tcx>>,
}

/// A set of constraints that need to be satisfied in order for
/// a type to be valid for destruction.
#[derive(Clone, Debug)]
pub struct DtorckConstraint<'tcx> {
    /// Types that are required to be alive in order for this
    /// type to be valid for destruction.
    pub outlives: Vec<ty::subst::Kind<'tcx>>,

    /// Types that could not be resolved: projections and params.
    pub dtorck_types: Vec<Ty<'tcx>>,

    /// If, during the computation of the dtorck constraint, we
    /// overflow, that gets recorded here. The caller is expected to
    /// report an error.
    pub overflows: Vec<Ty<'tcx>>,
}

impl<'tcx> DtorckConstraint<'tcx> {
    pub fn empty() -> DtorckConstraint<'tcx> {
        DtorckConstraint {
            outlives: vec![],
            dtorck_types: vec![],
            overflows: vec![],
        }
    }
}

impl<'tcx> FromIterator<DtorckConstraint<'tcx>> for DtorckConstraint<'tcx> {
    fn from_iter<I: IntoIterator<Item = DtorckConstraint<'tcx>>>(iter: I) -> Self {
        let mut result = Self::empty();

        for DtorckConstraint {
            outlives,
            dtorck_types,
            overflows,
        } in iter
        {
            result.outlives.extend(outlives);
            result.dtorck_types.extend(dtorck_types);
            result.overflows.extend(overflows);
        }

        result
    }
}
impl<'gcx: 'tcx, 'tcx> Canonicalize<'gcx, 'tcx> for ty::ParamEnvAnd<'tcx, Ty<'tcx>> {
    type Canonicalized = CanonicalTyGoal<'gcx>;

    fn intern(
        _gcx: TyCtxt<'_, 'gcx, 'gcx>,
        value: Canonical<'gcx, Self::Lifted>,
    ) -> Self::Canonicalized {
        value
    }
}

BraceStructTypeFoldableImpl! {
    impl<'tcx> TypeFoldable<'tcx> for DropckOutlivesResult<'tcx> {
        kinds, overflows
    }
}

BraceStructLiftImpl! {
    impl<'a, 'tcx> Lift<'tcx> for DropckOutlivesResult<'a> {
        type Lifted = DropckOutlivesResult<'tcx>;
        kinds, overflows
    }
}

impl_stable_hash_for!(struct DropckOutlivesResult<'tcx> {
    kinds, overflows
});

impl<'gcx: 'tcx, 'tcx> Canonicalize<'gcx, 'tcx> for QueryResult<'tcx, DropckOutlivesResult<'tcx>> {
    // we ought to intern this, but I'm too lazy just now
    type Canonicalized = Rc<Canonical<'gcx, QueryResult<'gcx, DropckOutlivesResult<'gcx>>>>;

    fn intern(
        _gcx: TyCtxt<'_, 'gcx, 'gcx>,
        value: Canonical<'gcx, Self::Lifted>,
    ) -> Self::Canonicalized {
        Rc::new(value)
    }
}

impl_stable_hash_for!(struct DtorckConstraint<'tcx> {
    outlives,
    dtorck_types,
    overflows
});
<commit_msg>short-circuit `dropck_outlives` for simple cases<commit_after>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use infer::at::At;
use infer::canonical::{Canonical, Canonicalize, QueryResult};
use infer::InferOk;
use std::iter::FromIterator;
use traits::query::CanonicalTyGoal;
use ty::{self, Ty, TyCtxt};
use ty::subst::Kind;
use std::rc::Rc;

impl<'cx, 'gcx, 'tcx> At<'cx, 'gcx, 'tcx> {
    /// Given a type `ty` of some value being dropped, computes a set
    /// of "kinds" (types, regions) that must be outlive the execution
    /// of the destructor. These basically correspond to data that the
    /// destructor might access. This is used during regionck to
    /// impose "outlives" constraints on any lifetimes referenced
    /// within.
    ///
    /// The rules here are given by the "dropck" RFCs, notably [#1238]
    /// and [#1327]. This is a fixed-point computation, where we
    /// explore all the data that will be dropped (transitively) when
    /// a value of type `ty` is dropped. For each type T that will be
    /// dropped and which has a destructor, we must assume that all
    /// the types/regions of T are live during the destructor, unless
    /// they are marked with a special attribute (`#[may_dangle]`).
    ///
    /// [#1238]: https://github.com/rust-lang/rfcs/blob/master/text/1238-nonparametric-dropck.md
    /// [#1327]: https://github.com/rust-lang/rfcs/blob/master/text/1327-dropck-param-eyepatch.md
    pub fn dropck_outlives(&self, ty: Ty<'tcx>) -> InferOk<'tcx, Vec<Kind<'tcx>>> {
        debug!(
            "dropck_outlives(ty={:?}, param_env={:?})",
            ty, self.param_env,
        );

        // Quick check: there are a number of cases that we know do not require
        // any destructor.
        let tcx = self.infcx.tcx;
        if trivial_dropck_outlives(tcx, ty) {
            return InferOk { value: vec![], obligations: vec![] };
        }

        let gcx = tcx.global_tcx();
        let (c_ty, orig_values) = self.infcx.canonicalize_query(&self.param_env.and(ty));
        let span = self.cause.span;
        match &gcx.dropck_outlives(c_ty) {
            Ok(result) if result.is_proven() => {
                match self.infcx.instantiate_query_result(
                    self.cause,
                    self.param_env,
                    &orig_values,
                    result,
                ) {
                    Ok(InferOk {
                        value: DropckOutlivesResult { kinds, overflows },
                        obligations,
                    }) => {
                        for overflow_ty in overflows.into_iter().take(1) {
                            let mut err = struct_span_err!(
                                tcx.sess,
                                span,
                                E0320,
                                "overflow while adding drop-check rules for {}",
                                self.infcx.resolve_type_vars_if_possible(&ty),
                            );
                            err.note(&format!("overflowed on {}", overflow_ty));
                            err.emit();
                        }

                        return InferOk {
                            value: kinds,
                            obligations,
                        };
                    }

                    Err(_) => { /* fallthrough to error-handling code below */ }
                }
            }

            _ => { /* fallthrough to error-handling code below */ }
        }

        // Errors and ambiuity in dropck occur in two cases:
        // - unresolved inference variables at the end of typeck
        // - non well-formed types where projections cannot be resolved
        // Either of these should hvae created an error before.
        tcx.sess
            .delay_span_bug(span, "dtorck encountered internal error");
        return InferOk {
            value: vec![],
            obligations: vec![],
        };
    }
}

#[derive(Clone, Debug)]
pub struct DropckOutlivesResult<'tcx> {
    pub kinds: Vec<Kind<'tcx>>,
    pub overflows: Vec<Ty<'tcx>>,
}

/// A set of constraints that need to be satisfied in order for
/// a type to be valid for destruction.
#[derive(Clone, Debug)]
pub struct DtorckConstraint<'tcx> {
    /// Types that are required to be alive in order for this
    /// type to be valid for destruction.
    pub outlives: Vec<ty::subst::Kind<'tcx>>,

    /// Types that could not be resolved: projections and params.
    pub dtorck_types: Vec<Ty<'tcx>>,

    /// If, during the computation of the dtorck constraint, we
    /// overflow, that gets recorded here. The caller is expected to
    /// report an error.
    pub overflows: Vec<Ty<'tcx>>,
}

impl<'tcx> DtorckConstraint<'tcx> {
    pub fn empty() -> DtorckConstraint<'tcx> {
        DtorckConstraint {
            outlives: vec![],
            dtorck_types: vec![],
            overflows: vec![],
        }
    }
}

impl<'tcx> FromIterator<DtorckConstraint<'tcx>> for DtorckConstraint<'tcx> {
    fn from_iter<I: IntoIterator<Item = DtorckConstraint<'tcx>>>(iter: I) -> Self {
        let mut result = Self::empty();

        for DtorckConstraint {
            outlives,
            dtorck_types,
            overflows,
        } in iter
        {
            result.outlives.extend(outlives);
            result.dtorck_types.extend(dtorck_types);
            result.overflows.extend(overflows);
        }

        result
    }
}
impl<'gcx: 'tcx, 'tcx> Canonicalize<'gcx, 'tcx> for ty::ParamEnvAnd<'tcx, Ty<'tcx>> {
    type Canonicalized = CanonicalTyGoal<'gcx>;

    fn intern(
        _gcx: TyCtxt<'_, 'gcx, 'gcx>,
        value: Canonical<'gcx, Self::Lifted>,
    ) -> Self::Canonicalized {
        value
    }
}

BraceStructTypeFoldableImpl! {
    impl<'tcx> TypeFoldable<'tcx> for DropckOutlivesResult<'tcx> {
        kinds, overflows
    }
}

BraceStructLiftImpl! {
    impl<'a, 'tcx> Lift<'tcx> for DropckOutlivesResult<'a> {
        type Lifted = DropckOutlivesResult<'tcx>;
        kinds, overflows
    }
}

impl_stable_hash_for!(struct DropckOutlivesResult<'tcx> {
    kinds, overflows
});

impl<'gcx: 'tcx, 'tcx> Canonicalize<'gcx, 'tcx> for QueryResult<'tcx, DropckOutlivesResult<'tcx>> {
    // we ought to intern this, but I'm too lazy just now
    type Canonicalized = Rc<Canonical<'gcx, QueryResult<'gcx, DropckOutlivesResult<'gcx>>>>;

    fn intern(
        _gcx: TyCtxt<'_, 'gcx, 'gcx>,
        value: Canonical<'gcx, Self::Lifted>,
    ) -> Self::Canonicalized {
        Rc::new(value)
    }
}

impl_stable_hash_for!(struct DtorckConstraint<'tcx> {
    outlives,
    dtorck_types,
    overflows
});

/// This returns true if the type `ty` is "trivial" for
/// dropck-outlives -- that is, if it doesn't require any types to
/// outlive. This is similar but not *quite* the same as the
/// `needs_drop` test in the compiler already -- that is, for every
/// type T for which this function return true, needs-drop would
/// return false. But the reverse does not hold: in particular,
/// `needs_drop` returns false for `PhantomData`, but it is not
/// trivial for dropck-outlives.
///
/// Note also that `needs_drop` requires a "global" type (i.e., one
/// with erased regions), but this funtcion does not.
fn trivial_dropck_outlives<'cx, 'tcx>(tcx: TyCtxt<'cx, '_, 'tcx>, ty: Ty<'tcx>) -> bool {
    match ty.sty {
        // None of these types have a destructor and hence they do not
        // require anything in particular to outlive the dtor's
        // execution.
        ty::TyInfer(ty::FreshIntTy(_))
        | ty::TyInfer(ty::FreshFloatTy(_))
        | ty::TyBool
        | ty::TyInt(_)
        | ty::TyUint(_)
        | ty::TyFloat(_)
        | ty::TyNever
        | ty::TyFnDef(..)
        | ty::TyFnPtr(_)
        | ty::TyChar
        | ty::TyGeneratorWitness(..)
        | ty::TyRawPtr(_)
        | ty::TyRef(..)
        | ty::TyStr
        | ty::TyForeign(..)
        | ty::TyError => true,

        // [T; N] and [T] have same properties as T.
        ty::TyArray(ty, _) | ty::TySlice(ty) => trivial_dropck_outlives(tcx, ty),

        // (T1..Tn) and closures have same properties as T1..Tn --
        // check if *any* of those are trivial.
        ty::TyTuple(ref tys, _) => tys.iter().cloned().all(|t| trivial_dropck_outlives(tcx, t)),
        ty::TyClosure(def_id, ref substs) => substs
            .upvar_tys(def_id, tcx)
            .all(|t| trivial_dropck_outlives(tcx, t)),

        ty::TyAdt(def, _) => {
            if def.is_union() {
                // Unions never run have a dtor.
                true
            } else {
                // Other types might. Moreover, PhantomData doesn't
                // have a dtor, but it is considered to own its
                // content, so it is non-trivial.
                false
            }
        }

        // The following *might* require a destructor: it would deeper inspection to tell.
        ty::TyDynamic(..)
        | ty::TyProjection(..)
        | ty::TyParam(_)
        | ty::TyAnon(..)
        | ty::TyInfer(_)
        | ty::TyGenerator(..) => false,
    }
}
<|endoftext|>


<commit_before>use super::*;
use redox::*;

impl Editor {
    /// Redraw the window
    pub fn redraw(&mut self) {
        // TODO: Only draw when relevant for the window
        let x = self.x();
        let y = self.y();
        // Redraw window
        self.window.set(Color::BLACK);

        self.window.rect(8 * (x - self.scroll_y) as isize,
                         16 * (y - self.scroll_x) as isize,
                         8,
                         16,
                         Color::WHITE);

        for (y, row) in self.text.iter().enumerate() {
            for (x, c) in row.iter().enumerate() {
                if self.x() == x && self.y() == y {
                    self.window.char(8 * (x - self.scroll_y) as isize,
                                     16 * (y - self.scroll_x) as isize,
                                     *c,
                                     Color::BLACK);
                } else {
                    self.window.char(8 * (x - self.scroll_y) as isize,
                                     16 * (y - self.scroll_x) as isize,
                                     *c,
                                     Color::WHITE);
                }
            }
        }
        let h = self.window.height();
        let w = self.window.width();
        self.window.rect(0, h as isize - 18, w, 18, Color::rgba(74, 74, 74, 255));

        for (n, c) in (if self.status_bar.mode.len() > w / (8 * 4) {
            self.status_bar.mode.chars().take(w / (8 * 4) - 5).chain(vec!['.', '.', '.']).collect::<Vec<_>>()
        } else {
            self.status_bar.mode.chars().collect()
        }).into_iter().enumerate() {
            self.window.char(n as isize * 8, h as isize - 16 - 1, if c == '\t' { ' ' } else { c }, Color::WHITE);
        }

        self.window.sync();
    }
}

/// The statubar (showing various info about the current state of the editor)
pub struct StatusBar {
    /// The current mode
    pub mode: String,
    /// The cureent char
    pub file: String,
    /// The current command
    pub cmd: String,
    /// A message (such as an error or other info to the user)
    pub msg: String,
}

impl StatusBar {
    /// Create new status bar
    pub fn new() -> Self {
        StatusBar {
            mode: "Normal".to_string(),
            file: String::new(),
            cmd: String::new(),
            msg: String::new(),
        }
    }
}
<commit_msg>Add basic highlighting<commit_after>use super::*;
use redox::*;

impl Editor {
    /// Redraw the window
    pub fn redraw(&mut self) {
        // TODO: Only draw when relevant for the window
        let x = self.x();
        let y = self.y();
        // Redraw window
        self.window.set(Color::BLACK);

        self.window.rect(8 * (x - self.scroll_y) as isize,
                         16 * (y - self.scroll_x) as isize,
                         8,
                         16,
                         Color::WHITE);

        for (y, row) in self.text.iter().enumerate() {
            for (x, c) in row.iter().enumerate() {
                if self.x() == x && self.y() == y {
                    self.window.char(8 * (x - self.scroll_y) as isize,
                                     16 * (y - self.scroll_x) as isize,
                                     *c,
                                     Color::BLACK);
                } else {
                    self.window.char(8 * (x - self.scroll_y) as isize,
                                     16 * (y - self.scroll_x) as isize,
                                     *c,
                                     Color::WHITE);
                }
            }
        }
        let h = self.window.height();
        let w = self.window.width();
        self.window.rect(0, h as isize - 18, w, 18, Color::rgba(74, 74, 74, 255));

        let mut string = false;

        for (n, c) in (if self.status_bar.mode.len() > w / (8 * 4) {
            self.status_bar.mode.chars().take(w / (8 * 4) - 5).chain(vec!['.', '.', '.']).collect::<Vec<_>>()
        } else {
            self.status_bar.mode.chars().collect()
        }).into_iter().enumerate() {
            let color = match c {
                _ if string => Color::BLUE,
                '\'' | '"' => {
                    string = true;
                    Color::RED
                },
                '!' | '@' | '#' | '$' | '%' | '^' | '&' | '*' | '+' | '-' | '/' | ':' | '=' | '<' | '>' => Color::RED,
                '.' | ',' => Color::BLUE,
                '(' | ')' | '[' | ']' | '{' | '}' => Color::GREEN,
                _ => Color::WHITE,
            };

            self.window.char(n as isize * 8, h as isize - 16 - 1, if c == '\t' { ' ' } else { c }, color);
        }

        self.window.sync();
    }
}

/// The statubar (showing various info about the current state of the editor)
pub struct StatusBar {
    /// The current mode
    pub mode: String,
    /// The cureent char
    pub file: String,
    /// The current command
    pub cmd: String,
    /// A message (such as an error or other info to the user)
    pub msg: String,
}

impl StatusBar {
    /// Create new status bar
    pub fn new() -> Self {
        StatusBar {
            mode: "Normal".to_string(),
            file: String::new(),
            cmd: String::new(),
            msg: String::new(),
        }
    }
}
<|endoftext|>


<commit_before>use super::*;

impl Editor {
    /// Get the position of the next char
    pub fn next_pos(&self) -> (usize, usize) {
        // TODO: Add numerals
        if self.x() == self.text[self.y()].len() {
            if self.y() < self.text.len() - 1 {
                (0, self.y() + 1)
            } else {
                (self.x(), self.y())
            }
        } else {
            (self.x() + 1, self.y())
        }
    }

    /// Get the position of previous char
    pub fn previous_pos(&self) -> (usize, usize) {
        if self.x() == 0 {
            if self.y() > 0 {
                (self.text[self.y() - 1].len(), self.y() - 1)
            } else {
                (self.x(), self.y())
            }
        } else {
            (self.x() - 1, self.y())
        }
    }

    /// Goto the next char
    pub fn goto_next(&mut self) {
        let (x, y) = self.next_pos();
        self.cursor_mut().x = x;
        self.cursor_mut().y = y;
    }
    /// Goto the previous char
    pub fn goto_previous(&mut self) {
        let (x, y) = self.previous_pos();
        self.cursor_mut().x = x;
        self.cursor_mut().y = y;
    }

    /// Get the position of the right char
    pub fn right_pos(&self, n: usize) -> (usize, usize) {
        let x = self.x() + n;

        if x > self.text[self.y()].len() {
            (self.text[self.y()].len(), self.y())
        } else {
            (x, self.y())
        }
    }
    /// Goto the right char
    pub fn goto_right(&mut self, n: usize) {
        self.cursor_mut().x = self.right_pos(n).0;
    }

    /// Get the position of the left char
    pub fn left_pos(&self, n: usize) -> (usize, usize) {
        if n <= self.x() {
            (self.x() - n, self.y())
        } else {
            (0, self.y())
        }

    }
    /// Goto the left char
    pub fn goto_left(&mut self, n: usize) {
        self.cursor_mut().x = self.left_pos(n).0;
    }

    /// Get the position of the char above the cursor
    pub fn up_pos(&self, n: usize) -> (usize, usize) {
        if n <= self.y() {
            (self.cursor().x, self.y() - n)
        } else {
            (self.cursor().x, 0)
        }
    }
    /// Go a char up
    pub fn goto_up(&mut self, n: usize) {
        let (x, y) = self.up_pos(n);
        self.cursor_mut().x = x;
        self.cursor_mut().y = y;
    }

    /// Get the position under the char
    pub fn down_pos(&self, n: usize) -> (usize, usize) {
        let y = self.y() + n;

        if y >= self.text.len() {
            (self.cursor().x, self.text.len() - 1)
        } else {
            (self.cursor().x, y)
        }
    }

    /// Go down
    pub fn goto_down(&mut self, n: usize) {
        let (x, y) = self.down_pos(n);
        self.cursor_mut().x = x;
        self.cursor_mut().y = y;
    }

}
<commit_msg>Refactor into using a .goto method<commit_after>use super::*;

impl Editor {
    /// Goto a given position
    pub fn goto(&mut self, (x, y): (usize, usize)) {
        self.cursor_mut().x = x;
        self.cursor_mut().y = y;
    }

    /// Get the position of the next char
    pub fn next_pos(&self) -> (usize, usize) {
        // TODO: Add numerals
        if self.x() == self.text[self.y()].len() {
            if self.y() < self.text.len() - 1 {
                (0, self.y() + 1)
            } else {
                (self.x(), self.y())
            }
        } else {
            (self.x() + 1, self.y())
        }
    }

    /// Get the position of previous char
    pub fn previous_pos(&self) -> (usize, usize) {
        if self.x() == 0 {
            if self.y() > 0 {
                (self.text[self.y() - 1].len(), self.y() - 1)
            } else {
                (self.x(), self.y())
            }
        } else {
            (self.x() - 1, self.y())
        }
    }

    /// Goto the next char
    pub fn goto_next(&mut self) {
        let p = self.next_pos();
        self.goto(p);
    }
    /// Goto the previous char
    pub fn goto_previous(&mut self) {
        let p = self.previous_pos();
        self.goto(p);
    }

    /// Get the position of the right char
    pub fn right_pos(&self, n: usize) -> (usize, usize) {
        let x = self.x() + n;

        if x > self.text[self.y()].len() {
            (self.text[self.y()].len(), self.y())
        } else {
            (x, self.y())
        }
    }
    /// Goto the right char
    pub fn goto_right(&mut self, n: usize) {
        self.cursor_mut().x = self.right_pos(n).0;
    }

    /// Get the position of the left char
    pub fn left_pos(&self, n: usize) -> (usize, usize) {
        if n <= self.x() {
            (self.x() - n, self.y())
        } else {
            (0, self.y())
        }

    }
    /// Goto the left char
    pub fn goto_left(&mut self, n: usize) {
        self.cursor_mut().x = self.left_pos(n).0;
    }

    /// Get the position of the char above the cursor
    pub fn up_pos(&self, n: usize) -> (usize, usize) {
        if n <= self.y() {
            (self.cursor().x, self.y() - n)
        } else {
            (self.cursor().x, 0)
        }
    }
    /// Go a char up
    pub fn goto_up(&mut self, n: usize) {
        let p = self.up_pos(n);
        self.goto(p);
    }

    /// Get the position under the char
    pub fn down_pos(&self, n: usize) -> (usize, usize) {
        let y = self.y() + n;

        if y >= self.text.len() {
            (self.cursor().x, self.text.len() - 1)
        } else {
            (self.cursor().x, y)
        }
    }

    /// Go down
    pub fn goto_down(&mut self, n: usize) {
        let p = self.down_pos(n);
        self.goto(p);
    }

}
<|endoftext|>


<commit_before>

// Simple ANSI color library.
//
// TODO: Windows support.
const u8 color_black = 0u8;

const u8 color_red = 1u8;

const u8 color_green = 2u8;

const u8 color_yellow = 3u8;

const u8 color_blue = 4u8;

const u8 color_magenta = 5u8;

const u8 color_cyan = 6u8;

const u8 color_light_gray = 7u8;

const u8 color_light_grey = 7u8;

const u8 color_dark_gray = 8u8;

const u8 color_dark_grey = 8u8;

const u8 color_bright_red = 9u8;

const u8 color_bright_green = 10u8;

const u8 color_bright_yellow = 11u8;

const u8 color_bright_blue = 12u8;

const u8 color_bright_magenta = 13u8;

const u8 color_bright_cyan = 14u8;

const u8 color_bright_white = 15u8;

fn esc(io::buf_writer writer) { writer.write([0x1bu8, '[' as u8]); }

fn reset(io::buf_writer writer) {
    esc(writer);
    writer.write(['0' as u8, 'm' as u8]);
}

fn color_supported() -> bool {

    ret generic_os::getenv("TERM") == option::some[str]("xterm-color");
}

fn set_color(io::buf_writer writer, u8 first_char, u8 color) {
    assert (color < 16u8);
    esc(writer);
    if (color >= 8u8) { writer.write(['1' as u8, ';' as u8]); color -= 8u8; }
    writer.write([first_char, ('0' as u8) + color, 'm' as u8]);
}

fn fg(io::buf_writer writer, u8 color) {
    ret set_color(writer, '3' as u8, color);
}

fn bg(io::buf_writer writer, u8 color) {
    ret set_color(writer, '4' as u8, color);
}
// export fg;
// export bg;

// Local Variables:
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
<commit_msg>stdlib: Add color support for GNU screen<commit_after>

// Simple ANSI color library.
//
// TODO: Windows support.
const u8 color_black = 0u8;

const u8 color_red = 1u8;

const u8 color_green = 2u8;

const u8 color_yellow = 3u8;

const u8 color_blue = 4u8;

const u8 color_magenta = 5u8;

const u8 color_cyan = 6u8;

const u8 color_light_gray = 7u8;

const u8 color_light_grey = 7u8;

const u8 color_dark_gray = 8u8;

const u8 color_dark_grey = 8u8;

const u8 color_bright_red = 9u8;

const u8 color_bright_green = 10u8;

const u8 color_bright_yellow = 11u8;

const u8 color_bright_blue = 12u8;

const u8 color_bright_magenta = 13u8;

const u8 color_bright_cyan = 14u8;

const u8 color_bright_white = 15u8;

fn esc(io::buf_writer writer) { writer.write([0x1bu8, '[' as u8]); }

fn reset(io::buf_writer writer) {
    esc(writer);
    writer.write(['0' as u8, 'm' as u8]);
}

fn color_supported() -> bool {
    auto supported_terms = ["xterm-color",
                            "screen-bce"];
    ret alt (generic_os::getenv("TERM")) {
        case (option::some(?env)) {
            vec::member(env, supported_terms)
        }
        case (option::none) {
            false
        }
    };
}

fn set_color(io::buf_writer writer, u8 first_char, u8 color) {
    assert (color < 16u8);
    esc(writer);
    if (color >= 8u8) { writer.write(['1' as u8, ';' as u8]); color -= 8u8; }
    writer.write([first_char, ('0' as u8) + color, 'm' as u8]);
}

fn fg(io::buf_writer writer, u8 color) {
    ret set_color(writer, '3' as u8, color);
}

fn bg(io::buf_writer writer, u8 color) {
    ret set_color(writer, '4' as u8, color);
}
// export fg;
// export bg;

// Local Variables:
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
<|endoftext|>


<commit_before><commit_msg>Add regression test for #60709<commit_after>// This used to compile the future down to ud2, due to uninhabited types being
// handled incorrectly in generators.
// compile-flags: -Copt-level=z -Cdebuginfo=2 --edition=2018

#![feature(async_await, await_macro)]
#![allow(unused)]

use std::future::Future;
use std::task::Poll;
use std::task::Context;
use std::pin::Pin;
use std::rc::Rc;

struct Never();
impl Future for Never {
    type Output = ();
    fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
        Poll::Pending
    }
}

fn main() {
    let fut = async {
        let _rc = Rc::new(()); // Also crashes with Arc
        await!(Never());
    };
    let _bla = fut; // Moving the future is required.
}
<|endoftext|>


<commit_before><commit_msg>documentation<commit_after><|endoftext|>


<commit_before><commit_msg>Test for issue #980<commit_after>tag maybe_pointy {
    no_pointy;
    yes_pointy(@pointy);
}

type pointy = {
    mutable x : maybe_pointy
};

fn main() {
    let m = @{ mutable x : no_pointy };
    m.x = yes_pointy(m);
}
<|endoftext|>


<commit_before><commit_msg>Use io.add_method instead of io.add_async_method<commit_after><|endoftext|>


<commit_before><commit_msg>Update serde attrs in room::history_visibility<commit_after><|endoftext|>


<commit_before><commit_msg>Start on counter_buttons example<commit_after>#![feature(conservative_impl_trait)]
extern crate domafic;
use domafic::{DOMNode, IntoNode};
use domafic::tags::{div, button};

type State = usize;

enum Msg {
    Increment,
    Decrement,
}

fn update(state: State, msg: Msg) -> State {
    match msg {
        Msg::Increment => state + 1,
        Msg::Decrement => state - 1,
    }
}

fn render(state: State) -> impl DOMNode<Message=Msg> {
    div ((
        button (("-".into_node())),
        button (("+".into_node())),
    ))
}

fn main() {
}
<|endoftext|>


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

extern mod std;

pub fn main() {
  let nan = float::NaN;
  assert!((float::is_NaN(nan)));

  let inf = float::infinity;
  assert!((-inf == float::neg_infinity));

  assert!(( nan !=  nan));
  assert!(( nan != -nan));
  assert!((-nan != -nan));
  assert!((-nan !=  nan));

  assert!(( nan !=   1.));
  assert!(( nan !=   0.));
  assert!(( nan !=  inf));
  assert!(( nan != -inf));

  assert!((  1. !=  nan));
  assert!((  0. !=  nan));
  assert!(( inf !=  nan));
  assert!((-inf !=  nan));

  assert!((!( nan ==  nan)));
  assert!((!( nan == -nan)));
  assert!((!( nan ==   1.)));
  assert!((!( nan ==   0.)));
  assert!((!( nan ==  inf)));
  assert!((!( nan == -inf)));
  assert!((!(  1. ==  nan)));
  assert!((!(  0. ==  nan)));
  assert!((!( inf ==  nan)));
  assert!((!(-inf ==  nan)));
  assert!((!(-nan ==  nan)));
  assert!((!(-nan == -nan)));

  assert!((!( nan >  nan)));
  assert!((!( nan > -nan)));
  assert!((!( nan >   0.)));
  assert!((!( nan >  inf)));
  assert!((!( nan > -inf)));
  assert!((!(  0. >  nan)));
  assert!((!( inf >  nan)));
  assert!((!(-inf >  nan)));
  assert!((!(-nan >  nan)));

  assert!((!(nan <   0.)));
  assert!((!(nan <   1.)));
  assert!((!(nan <  -1.)));
  assert!((!(nan <  inf)));
  assert!((!(nan < -inf)));
  assert!((!(nan <  nan)));
  assert!((!(nan < -nan)));

  assert!((!(  0. < nan)));
  assert!((!(  1. < nan)));
  assert!((!( -1. < nan)));
  assert!((!( inf < nan)));
  assert!((!(-inf < nan)));
  assert!((!(-nan < nan)));

  assert!((float::is_NaN(nan + inf)));
  assert!((float::is_NaN(nan + -inf)));
  assert!((float::is_NaN(nan + 0.)));
  assert!((float::is_NaN(nan + 1.)));
  assert!((float::is_NaN(nan * 1.)));
  assert!((float::is_NaN(nan / 1.)));
  assert!((float::is_NaN(nan / 0.)));
  assert!((float::is_NaN(0. / 0.)));
  assert!((float::is_NaN(-inf + inf)));
  assert!((float::is_NaN(inf - inf)));

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

extern mod std;

use core::num::Float::{
  NaN, infinity, neg_infinity
};

pub fn main() {
  let nan = NaN::<float>();
  assert!((nan).is_NaN());

  let inf = infinity::<float>();
  assert!(-inf == neg_infinity::<float>());

  assert!( nan !=  nan);
  assert!( nan != -nan);
  assert!(-nan != -nan);
  assert!(-nan !=  nan);

  assert!( nan !=   1.);
  assert!( nan !=   0.);
  assert!( nan !=  inf);
  assert!( nan != -inf);

  assert!(  1. !=  nan);
  assert!(  0. !=  nan);
  assert!( inf !=  nan);
  assert!(-inf !=  nan);

  assert!(!( nan ==  nan));
  assert!(!( nan == -nan));
  assert!(!( nan ==   1.));
  assert!(!( nan ==   0.));
  assert!(!( nan ==  inf));
  assert!(!( nan == -inf));
  assert!(!(  1. ==  nan));
  assert!(!(  0. ==  nan));
  assert!(!( inf ==  nan));
  assert!(!(-inf ==  nan));
  assert!(!(-nan ==  nan));
  assert!(!(-nan == -nan));

  assert!(!( nan >  nan));
  assert!(!( nan > -nan));
  assert!(!( nan >   0.));
  assert!(!( nan >  inf));
  assert!(!( nan > -inf));
  assert!(!(  0. >  nan));
  assert!(!( inf >  nan));
  assert!(!(-inf >  nan));
  assert!(!(-nan >  nan));

  assert!(!(nan <   0.));
  assert!(!(nan <   1.));
  assert!(!(nan <  -1.));
  assert!(!(nan <  inf));
  assert!(!(nan < -inf));
  assert!(!(nan <  nan));
  assert!(!(nan < -nan));

  assert!(!(  0. < nan));
  assert!(!(  1. < nan));
  assert!(!( -1. < nan));
  assert!(!( inf < nan));
  assert!(!(-inf < nan));
  assert!(!(-nan < nan));

  assert!((nan + inf).is_NaN());
  assert!((nan + -inf).is_NaN());
  assert!((nan + 0.).is_NaN());
  assert!((nan + 1.).is_NaN());
  assert!((nan * 1.).is_NaN());
  assert!((nan / 1.).is_NaN());
  assert!((nan / 0.).is_NaN());
  assert!((0f/0f).is_NaN());
  assert!((-inf + inf).is_NaN());
  assert!((inf - inf).is_NaN());

  assert!(!(-1f).is_NaN());
  assert!(!(0f).is_NaN());
  assert!(!(0.1f).is_NaN());
  assert!(!(1f).is_NaN());
  assert!(!(inf).is_NaN());
  assert!(!(-inf).is_NaN());
  assert!(!(1./-inf).is_NaN());
}
<|endoftext|>


<commit_before><commit_msg>Add regresstion test for #90024.<commit_after>// Test that rustc doesn't ICE as in #90024.
// check-pass
// edition=2018

#![warn(rust_2021_incompatible_closure_captures)]

// Checks there's no double-subst into the generic args, otherwise we get OOB
// MCVE by @lqd
pub struct Graph<N, E, Ix> {
    _edges: E,
    _nodes: N,
    _ix: Vec<Ix>,
}
fn graph<N, E>() -> Graph<N, E, i32> {
    todo!()
}
fn first_ice() {
    let g = graph::<i32, i32>();
    let _ = || g;
}

// Checks that there is a subst into the fields, otherwise we get normalization error
// MCVE by @cuviper
use std::iter::Empty;
struct Foo<I: Iterator> {
    data: Vec<I::Item>,
}
pub fn second_ice() {
    let v = Foo::<Empty<()>> { data: vec![] };

    (|| v.data[0])();
}

pub fn main() {
    first_ice();
    second_ice();
}
<|endoftext|>


<commit_before>use super::*;

impl Editor {
    /// Convert an instruction to a motion (new coordinate)
    pub fn to_motion(&mut self, Inst(n, cmd): Inst) -> Option<(usize, usize)> {
        use super::Key::*;
        match cmd {
            Char('h') => Some(self.left(n.d())),
            Char('l') => Some(self.right(n.d())),
            Char('j') => Some(self.down(n.d())),
            Char('k') => Some(self.up(n.d())),
            Char('g') => Some((0, n.or(1) - 1)),
            Char('G') => Some((0, self.text.len() - 1)),
            Char('L') => Some(self.ln_end()),
            Char('H') => Some((0, self.y())),
            Char('t') => {

                                                   // ~v~ Optimize (sorry, Knuth)
                if let Some(o) = self.next_ocur(ch, n.d()) {
                    Some(o)
                } else {
                    None
                }
            },
            _ => None,
        }
    }
}
<commit_msg>Fix error<commit_after>use super::*;

impl Editor {
    /// Convert an instruction to a motion (new coordinate)
    pub fn to_motion(&mut self, Inst(n, cmd): Inst) -> Option<(usize, usize)> {
        use super::Key::*;
        match cmd {
            Char('h') => Some(self.left(n.d())),
            Char('l') => Some(self.right(n.d())),
            Char('j') => Some(self.down(n.d())),
            Char('k') => Some(self.up(n.d())),
            Char('g') => Some((0, n.or(1) - 1)),
            Char('G') => Some((0, self.text.len() - 1)),
            Char('L') => Some(self.ln_end()),
            Char('H') => Some((0, self.y())),
            Char('t') => {

                let ch = self.next_char();

                                                   // ~v~ Optimize (sorry, Knuth)
                if let Some(o) = self.next_ocur(ch, n.d()) {
                    Some(o)
                } else {
                    None
                }
            },
            _ => None,
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>add tests for dropping `FutureObj`s<commit_after><|endoftext|>


<commit_before><commit_msg>Shots now time out.<commit_after><|endoftext|>


<commit_before><commit_msg>Added example connecting leds to buttons.<commit_after>#![feature(alloc)]
#![no_std]

extern crate tock;

use tock::buttons;
use tock::buttons::ButtonState;
use tock::led;
use tock::timer;
use tock::timer::Duration;

fn main() {
    let mut with_callback = buttons::with_callback(|button_num: usize, state| {
        let i = button_num as isize;
        match state {
            ButtonState::Pressed => led::get(i).unwrap().toggle(),
            ButtonState::Released => (),
        };
    });

    let mut buttons = with_callback.init().unwrap();

    for mut button in &mut buttons {
        button.enable().unwrap();
    }

    loop {
        timer::sleep(Duration::from_ms(500));
    }
}
<|endoftext|>


<commit_before><commit_msg>Use env::current_dir and handle error<commit_after><|endoftext|>


<commit_before><commit_msg>Remove some workarounds for rustc borrow check bugs. Makes the CPU simpler.<commit_after><|endoftext|>


<commit_before><commit_msg>x86: add raw syscalls<commit_after>/*
 * Copyright 2015, Corey Richardson
 * Copyright 2014, NICTA
 *
 * This software may be distributed and modified according to the terms of
 * the BSD 2-Clause license. Note that NO WARRANTY is provided.
 * See "LICENSE_BSD2.txt" for details.
 *
 * @TAG(NICTA_BSD)
 */

#[inline(always)]
pub unsafe fn seL4_GetTag() -> seL4_MessageInfo {
    let tag;
    asm!("movl %gs:0, $0" : "=r"(tag) : : : "volatile");
    tag
}

#[inline(always)]
pub unsafe fn seL4_SetTag(tag: seL4_MessageInfo) {
    asm!("movl $0, %gs:0" : : "r"(tag) : "memory" : "volatile");
}

#[inline(always)]
pub unsafe fn seL4_GetMR(regnum: isize) -> seL4_Word {
    let mr;
    asm!("movl %gs:4(,$1,0x4), $0" : "=r"(mr) : "r"(regnum) : : "volatile");
    mr
}

#[inline(always)]
pub unsafe fn seL4_SetMR(regnum: i, value: seL4_Word) {
    asm!("movl $0, %gs:4(,$1,0x4)" : : "r"(value), "r"(regnum) : "memory" : "volatile");
}

#[inline(always)]
pub unsafe fn seL4_GetUserData() -> seL4_Word {
    let data;
    asm!("movl %gs:484, $0" : "=r"(data) : : : "volatile");
    data
}

#[inline(always)]
pub unsafe fn seL4_SetUserData(data: seL4_Word) {
    asm!("movl $0, %gs:484" : : "r"(data) : "memory" : "volatile");
}

#[inline(always)]
pub unsafe fn seL4_GetBadge(index: isize) -> seL4_CapData {
    let badge;
    asm!("movl %gs:488(,$1,0x4), $0" : "=r"(badge) : "r"(index) : : "volatile");
    badge
}

#[inline(always)]
pub unsafe fn seL4_GetCap(index: isize) -> seL4_CPtr {
    let cptr;
    asm!("movl %gs:488(,$1,0x4), $0" : "=r"(cptr) : "r"(index) : : "volatile");
    cptr
}

#[inline(always)]
pub unsafe fn seL4_SetCap(index: isize, cptr: seL4_CPtr) {
    asm!("movl %0, %gs:488(,%1,0x4)" : : "r"(cptr), "r"(i) : "memory" : "volatile");
}

#[inline(always)]
pub unsafe fn seL4_GetCapReceivePath(receiveCNode: *mut seL4_CPtr,
                                     receiveIndex: *mut seL4_CPtr,
                                     receiveDepth: *mut seL4_Word) {
    if (receiveCNode != ::std::ptr::null_mut()) {
        asm!("movl %gs:500, $0" : "=r"(*receiveCNode) : : : "volatile");
    }

    if (receiveIndex != ::std::ptr::null_mut()) {
        asm!("movl %gs:504, $0" : "=r"(*receiveIndex) : : : "volatile");
    }

    if (receiveDepth != ::std::ptr::null_mut()) {
        asm!("movl %gs:508, $0" : "=r"(*receiveDepth) : : : "volatile");
    }
}

#[inline(always)]
pub unsafe fn seL4_SetCapReceivePath(receiveCNode: seL4_CPtr,
                       receiveIndex: seL4_CPtr,
                       receiveDepth: seL4_Word) {
    asm!("movl $0, %gs:500" : : "r"(receiveCNode) : "memory" : "volatile");
    asm!("movl $0, %gs:504" : : "r"(receiveIndex) : "memory" : "volatile");
    asm!("movl $0, %gs:508" : : "r"(receiveDepth) : "memory" : "volatile");
}
<|endoftext|>


<commit_before><commit_msg>chg comments<commit_after><|endoftext|>


<commit_before><commit_msg>minor<commit_after><|endoftext|>


<commit_before><commit_msg>remove duplicate code<commit_after><|endoftext|>


<commit_before><commit_msg>Add some if-condition tests.<commit_after><|endoftext|>


<commit_before><commit_msg>Game loop<commit_after>use std::time::{Duration, Instant};
use std::thread::sleep;

pub struct GameLoop {
    frame_number: u64,
    fps: u32
}

impl GameLoop {
    pub fn new(fps: u32) -> GameLoop {
        GameLoop {
            frame_number: 0,
            fps: fps
        }
    }

    pub fn run<F>(&mut self, fun: F)
        where F: Fn(u64) -> bool {  //FIXME: Could be an enum or something
        let ns_per_frame : Duration = Duration::new(0, 1_000_000_000 / self.fps);
        'running: loop {
            let start = Instant::now();

            if fun(self.frame_number) {
                break 'running;
            }
            // Framerate cap
            let next_render_step = start + ns_per_frame;
            let now = Instant::now();
            if next_render_step >= now {
                sleep(next_render_step - now);
            }
            self.frame_number += 1;
        }
    }
}
<|endoftext|>


<commit_before><commit_msg> #10 Warning cleanup for shader<commit_after><|endoftext|>


<commit_before>use core::cell::UnsafeCell;
use core::ops::{Deref, DerefMut};

use common::mutex::Mutex;

use scheduler::context::context_switch;

struct RwLockInner {
    writer: bool,
    readers: usize
}

pub struct RwLock<T> {
    inner: Mutex<RwLockInner>,
    value: UnsafeCell<T>
}

impl<T> RwLock<T> {
    /// Create a new mutex with value `value`.
    pub fn new(value: T) -> Self {
        RwLock {
            inner: Mutex::new(RwLockInner {
                writer: false,
                readers: 0
            }),
            value: UnsafeCell::new(value),
        }
    }
}

impl<T: ?Sized> RwLock<T> {
    /// Lock the mutex
    pub fn read(&self) -> RwLockReadGuard<T> {
        loop {
            {
                let mut inner = self.inner.lock();
                if inner.writer == false {
                    inner.readers += 1;
                    break;
                }
            }
            unsafe { context_switch(false) };
        }
        RwLockReadGuard::new(&self.inner, &self.value)
    }

    pub fn write(&self) -> RwLockWriteGuard<T> {
        loop {
            {
                let mut inner = self.inner.lock();
                if inner.writer == false && inner.readers == 0 {
                    inner.writer = true;
                    break;
                }
            }
            unsafe { context_switch(false) };
        }
        RwLockWriteGuard::new(&self.inner, &self.value)
    }
}

unsafe impl<T: ?Sized + Send> Send for RwLock<T> { }

unsafe impl<T: ?Sized + Send> Sync for RwLock<T> { }

/// A read guard (returned by .read())
pub struct RwLockReadGuard<'a, T: ?Sized + 'a> {
    inner: &'a Mutex<RwLockInner>,
    data: &'a UnsafeCell<T>,
}

impl<'mutex, T: ?Sized> RwLockReadGuard<'mutex, T> {
    fn new(inner: &'mutex Mutex<RwLockInner>, data: &'mutex UnsafeCell<T>) -> Self {
        RwLockReadGuard {
            inner: inner,
            data: data,
        }
    }
}

impl<'mutex, T: ?Sized> Deref for RwLockReadGuard<'mutex, T> {
    type Target = T;

    fn deref<'a>(&'a self) -> &'a T {
        unsafe { &*self.data.get() }
    }
}

impl<'a, T: ?Sized> Drop for RwLockReadGuard<'a, T> {
    fn drop(&mut self) {
        let mut inner = self.inner.lock();
        inner.readers -= 1;
    }
}

/// A write guard (returned by .write())
pub struct RwLockWriteGuard<'a, T: ?Sized + 'a> {
    inner: &'a Mutex<RwLockInner>,
    data: &'a UnsafeCell<T>,
}

impl<'mutex, T: ?Sized> RwLockWriteGuard<'mutex, T> {
    fn new(inner: &'mutex Mutex<RwLockInner>, data: &'mutex UnsafeCell<T>) -> Self {
        RwLockWriteGuard {
            inner: inner,
            data: data,
        }
    }
}

impl<'mutex, T: ?Sized> Deref for RwLockWriteGuard<'mutex, T> {
    type Target = T;

    fn deref<'a>(&'a self) -> &'a T {
        unsafe { &*self.data.get() }
    }
}

impl<'mutex, T: ?Sized> DerefMut for RwLockWriteGuard<'mutex, T> {
    fn deref_mut<'a>(&'a mut self) -> &'a mut T {
        unsafe { &mut *self.data.get() }
    }
}

impl<'a, T: ?Sized> Drop for RwLockWriteGuard<'a, T> {
    fn drop(&mut self) {
        let mut inner = self.inner.lock();
        inner.writer = false;
    }
}
<commit_msg>Rename comments for rwlock<commit_after>use core::cell::UnsafeCell;
use core::ops::{Deref, DerefMut};

use common::mutex::Mutex;

use scheduler::context::context_switch;

struct RwLockInner {
    writer: bool,
    readers: usize
}

pub struct RwLock<T> {
    inner: Mutex<RwLockInner>,
    value: UnsafeCell<T>
}

impl<T> RwLock<T> {
    /// Create a new mutex with value `value`.
    pub fn new(value: T) -> Self {
        RwLock {
            inner: Mutex::new(RwLockInner {
                writer: false,
                readers: 0
            }),
            value: UnsafeCell::new(value),
        }
    }
}

impl<T: ?Sized> RwLock<T> {
    /// Lock for read
    pub fn read(&self) -> RwLockReadGuard<T> {
        loop {
            {
                let mut inner = self.inner.lock();
                if inner.writer == false {
                    inner.readers += 1;
                    break;
                }
            }
            unsafe { context_switch(false) };
        }
        RwLockReadGuard::new(&self.inner, &self.value)
    }

    /// Lock for write
    pub fn write(&self) -> RwLockWriteGuard<T> {
        loop {
            {
                let mut inner = self.inner.lock();
                if inner.writer == false && inner.readers == 0 {
                    inner.writer = true;
                    break;
                }
            }
            unsafe { context_switch(false) };
        }
        RwLockWriteGuard::new(&self.inner, &self.value)
    }
}

unsafe impl<T: ?Sized + Send> Send for RwLock<T> { }

unsafe impl<T: ?Sized + Send> Sync for RwLock<T> { }

/// A read guard (returned by .read())
pub struct RwLockReadGuard<'a, T: ?Sized + 'a> {
    inner: &'a Mutex<RwLockInner>,
    data: &'a UnsafeCell<T>,
}

impl<'rwlock, T: ?Sized> RwLockReadGuard<'rwlock, T> {
    fn new(inner: &'rwlock Mutex<RwLockInner>, data: &'rwlock UnsafeCell<T>) -> Self {
        RwLockReadGuard {
            inner: inner,
            data: data,
        }
    }
}

impl<'rwlock, T: ?Sized> Deref for RwLockReadGuard<'rwlock, T> {
    type Target = T;

    fn deref<'a>(&'a self) -> &'a T {
        unsafe { &*self.data.get() }
    }
}

impl<'a, T: ?Sized> Drop for RwLockReadGuard<'a, T> {
    fn drop(&mut self) {
        let mut inner = self.inner.lock();
        inner.readers -= 1;
    }
}

/// A write guard (returned by .write())
pub struct RwLockWriteGuard<'a, T: ?Sized + 'a> {
    inner: &'a Mutex<RwLockInner>,
    data: &'a UnsafeCell<T>,
}

impl<'rwlock, T: ?Sized> RwLockWriteGuard<'rwlock, T> {
    fn new(inner: &'rwlock Mutex<RwLockInner>, data: &'rwlock UnsafeCell<T>) -> Self {
        RwLockWriteGuard {
            inner: inner,
            data: data,
        }
    }
}

impl<'rwlock, T: ?Sized> Deref for RwLockWriteGuard<'rwlock, T> {
    type Target = T;

    fn deref<'a>(&'a self) -> &'a T {
        unsafe { &*self.data.get() }
    }
}

impl<'rwlock, T: ?Sized> DerefMut for RwLockWriteGuard<'rwlock, T> {
    fn deref_mut<'a>(&'a mut self) -> &'a mut T {
        unsafe { &mut *self.data.get() }
    }
}

impl<'a, T: ?Sized> Drop for RwLockWriteGuard<'a, T> {
    fn drop(&mut self) {
        let mut inner = self.inner.lock();
        inner.writer = false;
    }
}
<|endoftext|>


<commit_before><commit_msg>Remove edge labels<commit_after><|endoftext|>


<commit_before><commit_msg>Clarify `readonly` method is also about being 'unwritable'.<commit_after><|endoftext|>


<commit_before><commit_msg>Add new test case showing that supertraits are not enough<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.

// Test that when a `..` impl applies, we also check that any
// supertrait conditions are met.

#![feature(optin_builtin_traits)]

trait NotImplemented { }

trait MyTrait
    where Option<Self> : NotImplemented
{}

impl NotImplemented for i32 {}

impl MyTrait for .. {}

fn foo<T:MyTrait>() {
    bar::<Option<T>>()
        //~^ ERROR not implemented for the type `Option<T>`
        //
        // This should probably typecheck. This is #20671.
}

fn bar<T:NotImplemented>() { }

fn main() {
    foo::<i32>(); //~ ERROR not implemented for the type `i32`
    bar::<Option<i32>>(); //~ ERROR not implemented for the type `Option<i32>`
}
<|endoftext|>