<commit_before>extern crate sdl2;

use sdl2::EventPump;
use sdl2::render::Renderer;
use std::error::Error;

pub fn init(name: &str, width: u32, height: u32) -> Result<(Renderer, EventPump), Box<Error>> {
    let sdl_ctx = try!(sdl2::init());
    let video_ctx = try!(sdl_ctx.video());
    let window = try!(video_ctx.window(name, width, height)
        .position_centered()
        .opengl()
        .build());

    let mut renderer = try!(window.renderer().present_vsync().build());

    renderer.clear();
    renderer.present();
    let mut event_pump = try!(sdl_ctx.event_pump());
    Ok((renderer, event_pump))
}
<commit_msg>do not make event_pump mutable until needed<commit_after>extern crate sdl2;

use sdl2::EventPump;
use sdl2::render::Renderer;
use std::error::Error;

pub fn init(name: &str, width: u32, height: u32) -> Result<(Renderer, EventPump), Box<Error>> {
    let sdl_ctx = try!(sdl2::init());
    let video_ctx = try!(sdl_ctx.video());
    let window = try!(video_ctx.window(name, width, height)
        .position_centered()
        .opengl()
        .build());

    let mut renderer = try!(window.renderer().present_vsync().build());

    renderer.clear();
    renderer.present();
    let event_pump = try!(sdl_ctx.event_pump());
    Ok((renderer, event_pump))
}
<|endoftext|>


<commit_before>use collections::{String, Vec};
use core::str;

use context;
use syscall::error::Result;

pub fn resource() -> Result<Vec<u8>> {
    let mut string = format!("{:<6}{:<6}{:<6}{:<6}{:<6}{:<6}{:<8}{}\n",
                             "PID",
                             "PPID",
                             "UID",
                             "GID",
                             "STAT",
                             "CPU",
                             "MEM",
                             "NAME");
    {
        let contexts = context::contexts();
        for (_id, context_lock) in contexts.iter() {
            let context = context_lock.read();

            let mut stat_string = String::new();
            if context.stack.is_some() {
                stat_string.push('U');
            } else {
                stat_string.push('K');
            }
            match context.status {
                context::Status::Runnable => {
                    stat_string.push('R');
                },
                context::Status::Blocked => if context.wake.is_some() {
                    stat_string.push('S');
                } else {
                    stat_string.push('B');
                },
                context::Status::Exited(_status) => {
                    stat_string.push('Z');
                }
            }
            if context.running {
                stat_string.push('+');
            }

            let cpu_string = if let Some(cpu_id) = context.cpu_id {
                format!("{}", cpu_id)
            } else {
                format!("?")
            };

            let mut memory = 0;
            if let Some(ref kfx) = context.kstack {
                memory += kfx.len();
            }
            if let Some(ref kstack) = context.kstack {
                memory += kstack.len();
            }
            for shared_mem in context.image.iter() {
                shared_mem.with(|mem| {
                    memory += mem.size();
                });
            }
            if let Some(ref heap) = context.heap {
                heap.with(|heap| {
                    memory += heap.size();
                });
            }
            if let Some(ref stack) = context.stack {
                memory += stack.size();
            }

            let memory_string = if memory >= 1024 * 1024 * 1024 {
                format!("{} GB", memory / 1024 / 1024 / 1024)
            } else if memory >= 1024 * 1024 {
                format!("{} MB", memory / 1024 / 1024)
            } else if memory >= 1024 {
                format!("{} KB", memory / 1024)
            } else {
                format!("{} B", memory)
            };

            let name_bytes = context.name.lock();
            let name = str::from_utf8(&name_bytes).unwrap_or("");

            string.push_str(&format!("{:<6}{:<6}{:<6}{:<6}{:<6}{:<6}{:<8}{}\n",
                               context.id.into(),
                               context.ppid.into(),
                               context.euid,
                               context.egid,
                               stat_string,
                               cpu_string,
                               memory_string,
                               name));
        }
    }

    Ok(string.into_bytes())
}
<commit_msg>Cleanup zombies in container - show scheme namespace in context list<commit_after>use collections::{String, Vec};
use core::str;

use context;
use syscall::error::Result;

pub fn resource() -> Result<Vec<u8>> {
    let mut string = format!("{:<6}{:<6}{:<6}{:<6}{:<6}{:<6}{:<8}{:<6}{}\n",
                             "PID",
                             "PPID",
                             "UID",
                             "GID",
                             "STAT",
                             "CPU",
                             "MEM",
                             "SNS",
                             "NAME");
    {
        let contexts = context::contexts();
        for (_id, context_lock) in contexts.iter() {
            let context = context_lock.read();

            let mut stat_string = String::new();
            if context.stack.is_some() {
                stat_string.push('U');
            } else {
                stat_string.push('K');
            }
            match context.status {
                context::Status::Runnable => {
                    stat_string.push('R');
                },
                context::Status::Blocked => if context.wake.is_some() {
                    stat_string.push('S');
                } else {
                    stat_string.push('B');
                },
                context::Status::Exited(_status) => {
                    stat_string.push('Z');
                }
            }
            if context.running {
                stat_string.push('+');
            }

            let cpu_string = if let Some(cpu_id) = context.cpu_id {
                format!("{}", cpu_id)
            } else {
                format!("?")
            };

            let mut memory = 0;
            if let Some(ref kfx) = context.kstack {
                memory += kfx.len();
            }
            if let Some(ref kstack) = context.kstack {
                memory += kstack.len();
            }
            for shared_mem in context.image.iter() {
                shared_mem.with(|mem| {
                    memory += mem.size();
                });
            }
            if let Some(ref heap) = context.heap {
                heap.with(|heap| {
                    memory += heap.size();
                });
            }
            if let Some(ref stack) = context.stack {
                memory += stack.size();
            }

            let memory_string = if memory >= 1024 * 1024 * 1024 {
                format!("{} GB", memory / 1024 / 1024 / 1024)
            } else if memory >= 1024 * 1024 {
                format!("{} MB", memory / 1024 / 1024)
            } else if memory >= 1024 {
                format!("{} KB", memory / 1024)
            } else {
                format!("{} B", memory)
            };

            let name_bytes = context.name.lock();
            let name = str::from_utf8(&name_bytes).unwrap_or("");

            string.push_str(&format!("{:<6}{:<6}{:<6}{:<6}{:<6}{:<6}{:<8}{:<6}{}\n",
                               context.id.into(),
                               context.ppid.into(),
                               context.euid,
                               context.egid,
                               stat_string,
                               cpu_string,
                               memory_string,
                               context.scheme_ns.into(),
                               name));
        }
    }

    Ok(string.into_bytes())
}
<|endoftext|>


<commit_before>#![feature(test)] // compiletest_rs requires this attribute
#![feature(once_cell)]
#![cfg_attr(feature = "deny-warnings", deny(warnings))]
#![warn(rust_2018_idioms, unused_lifetimes)]

use compiletest_rs as compiletest;
use compiletest_rs::common::Mode as TestMode;

use std::collections::HashMap;
use std::env::{self, remove_var, set_var, var_os};
use std::ffi::{OsStr, OsString};
use std::fs;
use std::io;
use std::path::{Path, PathBuf};

mod cargo;

// whether to run internal tests or not
const RUN_INTERNAL_TESTS: bool = cfg!(feature = "internal-lints");

/// All crates used in UI tests are listed here
static TEST_DEPENDENCIES: &[&str] = &[
    "clippy_utils",
    "derive_new",
    "if_chain",
    "itertools",
    "quote",
    "regex",
    "serde",
    "serde_derive",
    "syn",
];

// Test dependencies may need an `extern crate` here to ensure that they show up
// in the depinfo file (otherwise cargo thinks they are unused)
#[allow(unused_extern_crates)]
extern crate clippy_utils;
#[allow(unused_extern_crates)]
extern crate derive_new;
#[allow(unused_extern_crates)]
extern crate if_chain;
#[allow(unused_extern_crates)]
extern crate itertools;
#[allow(unused_extern_crates)]
extern crate quote;
#[allow(unused_extern_crates)]
extern crate syn;

fn host_lib() -> PathBuf {
    option_env!("HOST_LIBS").map_or(cargo::CARGO_TARGET_DIR.join(env!("PROFILE")), PathBuf::from)
}

fn clippy_driver_path() -> PathBuf {
    option_env!("CLIPPY_DRIVER_PATH").map_or(cargo::TARGET_LIB.join("clippy-driver"), PathBuf::from)
}

/// Produces a string with an `--extern` flag for all UI test crate
/// dependencies.
///
/// The dependency files are located by parsing the depinfo file for this test
/// module. This assumes the `-Z binary-dep-depinfo` flag is enabled. All test
/// dependencies must be added to Cargo.toml at the project root. Test
/// dependencies that are not *directly* used by this test module require an
/// `extern crate` declaration.
fn extern_flags() -> String {
    let current_exe_depinfo = {
        let mut path = env::current_exe().unwrap();
        path.set_extension("d");
        std::fs::read_to_string(path).unwrap()
    };
    let mut crates: HashMap<&str, &str> = HashMap::with_capacity(TEST_DEPENDENCIES.len());
    for line in current_exe_depinfo.lines() {
        // each dependency is expected to have a Makefile rule like `/path/to/crate-hash.rlib:`
        let parse_name_path = || {
            if line.starts_with(char::is_whitespace) {
                return None;
            }
            let path_str = line.strip_suffix(':')?;
            let path = Path::new(path_str);
            if !matches!(path.extension()?.to_str()?, "rlib" | "so" | "dylib" | "dll") {
                return None;
            }
            let (name, _hash) = path.file_stem()?.to_str()?.rsplit_once('-')?;
            // the "lib" prefix is not present for dll files
            let name = name.strip_prefix("lib").unwrap_or(name);
            Some((name, path_str))
        };
        if let Some((name, path)) = parse_name_path() {
            if TEST_DEPENDENCIES.contains(&name) {
                // A dependency may be listed twice if it is available in sysroot,
                // and the sysroot dependencies are listed first. As of the writing,
                // this only seems to apply to if_chain.
                crates.insert(name, path);
            }
        }
    }
    let not_found: Vec<&str> = TEST_DEPENDENCIES
        .iter()
        .copied()
        .filter(|n| !crates.contains_key(n))
        .collect();
    if !not_found.is_empty() {
        panic!("dependencies not found in depinfo: {:?}", not_found);
    }
    crates
        .into_iter()
        .map(|(name, path)| format!("--extern {}={} ", name, path))
        .collect()
}

fn default_config() -> compiletest::Config {
    let mut config = compiletest::Config::default();

    if let Ok(filters) = env::var("TESTNAME") {
        config.filters = filters.split(',').map(std::string::ToString::to_string).collect();
    }

    if let Some(path) = option_env!("RUSTC_LIB_PATH") {
        let path = PathBuf::from(path);
        config.run_lib_path = path.clone();
        config.compile_lib_path = path;
    }
    let current_exe_path = std::env::current_exe().unwrap();
    let deps_path = current_exe_path.parent().unwrap();

    // Using `-L dependency={}` enforces that external dependencies are added with `--extern`.
    // This is valuable because a) it allows us to monitor what external dependencies are used
    // and b) it ensures that conflicting rlibs are resolved properly.
    config.target_rustcflags = Some(format!(
        "--emit=metadata -L dependency={} -L dependency={} -Dwarnings -Zui-testing {}",
        host_lib().join("deps").display(),
        deps_path.display(),
        extern_flags(),
    ));

    config.build_base = host_lib().join("test_build_base");
    config.rustc_path = clippy_driver_path();
    config
}

fn run_ui(cfg: &mut compiletest::Config) {
    cfg.mode = TestMode::Ui;
    cfg.src_base = Path::new("tests").join("ui");
    // use tests/clippy.toml
    let _g = VarGuard::set("CARGO_MANIFEST_DIR", std::fs::canonicalize("tests").unwrap());
    compiletest::run_tests(cfg);
}

fn run_internal_tests(cfg: &mut compiletest::Config) {
    // only run internal tests with the internal-tests feature
    if !RUN_INTERNAL_TESTS {
        return;
    }
    cfg.mode = TestMode::Ui;
    cfg.src_base = Path::new("tests").join("ui-internal");
    compiletest::run_tests(cfg);
}

fn run_ui_toml(config: &mut compiletest::Config) {
    fn run_tests(config: &compiletest::Config, mut tests: Vec<tester::TestDescAndFn>) -> Result<bool, io::Error> {
        let mut result = true;
        let opts = compiletest::test_opts(config);
        for dir in fs::read_dir(&config.src_base)? {
            let dir = dir?;
            if !dir.file_type()?.is_dir() {
                continue;
            }
            let dir_path = dir.path();
            let _g = VarGuard::set("CARGO_MANIFEST_DIR", &dir_path);
            for file in fs::read_dir(&dir_path)? {
                let file = file?;
                let file_path = file.path();
                if file.file_type()?.is_dir() {
                    continue;
                }
                if file_path.extension() != Some(OsStr::new("rs")) {
                    continue;
                }
                let paths = compiletest::common::TestPaths {
                    file: file_path,
                    base: config.src_base.clone(),
                    relative_dir: dir_path.file_name().unwrap().into(),
                };
                let test_name = compiletest::make_test_name(config, &paths);
                let index = tests
                    .iter()
                    .position(|test| test.desc.name == test_name)
                    .expect("The test should be in there");
                result &= tester::run_tests_console(&opts, vec![tests.swap_remove(index)])?;
            }
        }
        Ok(result)
    }

    config.mode = TestMode::Ui;
    config.src_base = Path::new("tests").join("ui-toml").canonicalize().unwrap();

    let tests = compiletest::make_tests(config);

    let res = run_tests(config, tests);
    match res {
        Ok(true) => {},
        Ok(false) => panic!("Some tests failed"),
        Err(e) => {
            panic!("I/O failure during tests: {:?}", e);
        },
    }
}

fn run_ui_cargo(config: &mut compiletest::Config) {
    fn run_tests(
        config: &compiletest::Config,
        filters: &[String],
        mut tests: Vec<tester::TestDescAndFn>,
    ) -> Result<bool, io::Error> {
        let mut result = true;
        let opts = compiletest::test_opts(config);

        for dir in fs::read_dir(&config.src_base)? {
            let dir = dir?;
            if !dir.file_type()?.is_dir() {
                continue;
            }

            // Use the filter if provided
            let dir_path = dir.path();
            for filter in filters {
                if !dir_path.ends_with(filter) {
                    continue;
                }
            }

            for case in fs::read_dir(&dir_path)? {
                let case = case?;
                if !case.file_type()?.is_dir() {
                    continue;
                }

                let src_path = case.path().join("src");

                // When switching between branches, if the previous branch had a test
                // that the current branch does not have, the directory is not removed
                // because an ignored Cargo.lock file exists.
                if !src_path.exists() {
                    continue;
                }

                env::set_current_dir(&src_path)?;
                for file in fs::read_dir(&src_path)? {
                    let file = file?;
                    if file.file_type()?.is_dir() {
                        continue;
                    }

                    // Search for the main file to avoid running a test for each file in the project
                    let file_path = file.path();
                    match file_path.file_name().and_then(OsStr::to_str) {
                        Some("main.rs") => {},
                        _ => continue,
                    }
                    let _g = VarGuard::set("CLIPPY_CONF_DIR", case.path());
                    let paths = compiletest::common::TestPaths {
                        file: file_path,
                        base: config.src_base.clone(),
                        relative_dir: src_path.strip_prefix(&config.src_base).unwrap().into(),
                    };
                    let test_name = compiletest::make_test_name(config, &paths);
                    let index = tests
                        .iter()
                        .position(|test| test.desc.name == test_name)
                        .expect("The test should be in there");
                    result &= tester::run_tests_console(&opts, vec![tests.swap_remove(index)])?;
                }
            }
        }
        Ok(result)
    }

    if cargo::is_rustc_test_suite() {
        return;
    }

    config.mode = TestMode::Ui;
    config.src_base = Path::new("tests").join("ui-cargo").canonicalize().unwrap();

    let tests = compiletest::make_tests(config);

    let current_dir = env::current_dir().unwrap();
    let res = run_tests(config, &config.filters, tests);
    env::set_current_dir(current_dir).unwrap();

    match res {
        Ok(true) => {},
        Ok(false) => panic!("Some tests failed"),
        Err(e) => {
            panic!("I/O failure during tests: {:?}", e);
        },
    }
}

fn prepare_env() {
    set_var("CLIPPY_DISABLE_DOCS_LINKS", "true");
    set_var("__CLIPPY_INTERNAL_TESTS", "true");
    //set_var("RUST_BACKTRACE", "0");
}

#[test]
fn compile_test() {
    prepare_env();
    let mut config = default_config();
    run_ui(&mut config);
    run_ui_toml(&mut config);
    run_ui_cargo(&mut config);
    run_internal_tests(&mut config);
}

/// Restores an env var on drop
#[must_use]
struct VarGuard {
    key: &'static str,
    value: Option<OsString>,
}

impl VarGuard {
    fn set(key: &'static str, val: impl AsRef<OsStr>) -> Self {
        let value = var_os(key);
        set_var(key, val);
        Self { key, value }
    }
}

impl Drop for VarGuard {
    fn drop(&mut self) {
        match self.value.as_deref() {
            None => remove_var(self.key),
            Some(value) => set_var(self.key, value),
        }
    }
}
<commit_msg>Make host libs -L flag optional<commit_after>#![feature(test)] // compiletest_rs requires this attribute
#![feature(once_cell)]
#![cfg_attr(feature = "deny-warnings", deny(warnings))]
#![warn(rust_2018_idioms, unused_lifetimes)]

use compiletest_rs as compiletest;
use compiletest_rs::common::Mode as TestMode;

use std::collections::HashMap;
use std::env::{self, remove_var, set_var, var_os};
use std::ffi::{OsStr, OsString};
use std::fs;
use std::io;
use std::path::{Path, PathBuf};

mod cargo;

// whether to run internal tests or not
const RUN_INTERNAL_TESTS: bool = cfg!(feature = "internal-lints");

/// All crates used in UI tests are listed here
static TEST_DEPENDENCIES: &[&str] = &[
    "clippy_utils",
    "derive_new",
    "if_chain",
    "itertools",
    "quote",
    "regex",
    "serde",
    "serde_derive",
    "syn",
];

// Test dependencies may need an `extern crate` here to ensure that they show up
// in the depinfo file (otherwise cargo thinks they are unused)
#[allow(unused_extern_crates)]
extern crate clippy_utils;
#[allow(unused_extern_crates)]
extern crate derive_new;
#[allow(unused_extern_crates)]
extern crate if_chain;
#[allow(unused_extern_crates)]
extern crate itertools;
#[allow(unused_extern_crates)]
extern crate quote;
#[allow(unused_extern_crates)]
extern crate syn;

fn host_lib() -> PathBuf {
    option_env!("HOST_LIBS").map_or(cargo::CARGO_TARGET_DIR.join(env!("PROFILE")), PathBuf::from)
}

fn clippy_driver_path() -> PathBuf {
    option_env!("CLIPPY_DRIVER_PATH").map_or(cargo::TARGET_LIB.join("clippy-driver"), PathBuf::from)
}

/// Produces a string with an `--extern` flag for all UI test crate
/// dependencies.
///
/// The dependency files are located by parsing the depinfo file for this test
/// module. This assumes the `-Z binary-dep-depinfo` flag is enabled. All test
/// dependencies must be added to Cargo.toml at the project root. Test
/// dependencies that are not *directly* used by this test module require an
/// `extern crate` declaration.
fn extern_flags() -> String {
    let current_exe_depinfo = {
        let mut path = env::current_exe().unwrap();
        path.set_extension("d");
        std::fs::read_to_string(path).unwrap()
    };
    let mut crates: HashMap<&str, &str> = HashMap::with_capacity(TEST_DEPENDENCIES.len());
    for line in current_exe_depinfo.lines() {
        // each dependency is expected to have a Makefile rule like `/path/to/crate-hash.rlib:`
        let parse_name_path = || {
            if line.starts_with(char::is_whitespace) {
                return None;
            }
            let path_str = line.strip_suffix(':')?;
            let path = Path::new(path_str);
            if !matches!(path.extension()?.to_str()?, "rlib" | "so" | "dylib" | "dll") {
                return None;
            }
            let (name, _hash) = path.file_stem()?.to_str()?.rsplit_once('-')?;
            // the "lib" prefix is not present for dll files
            let name = name.strip_prefix("lib").unwrap_or(name);
            Some((name, path_str))
        };
        if let Some((name, path)) = parse_name_path() {
            if TEST_DEPENDENCIES.contains(&name) {
                // A dependency may be listed twice if it is available in sysroot,
                // and the sysroot dependencies are listed first. As of the writing,
                // this only seems to apply to if_chain.
                crates.insert(name, path);
            }
        }
    }
    let not_found: Vec<&str> = TEST_DEPENDENCIES
        .iter()
        .copied()
        .filter(|n| !crates.contains_key(n))
        .collect();
    if !not_found.is_empty() {
        panic!("dependencies not found in depinfo: {:?}", not_found);
    }
    crates
        .into_iter()
        .map(|(name, path)| format!(" --extern {}={}", name, path))
        .collect()
}

fn default_config() -> compiletest::Config {
    let mut config = compiletest::Config::default();

    if let Ok(filters) = env::var("TESTNAME") {
        config.filters = filters.split(',').map(std::string::ToString::to_string).collect();
    }

    if let Some(path) = option_env!("RUSTC_LIB_PATH") {
        let path = PathBuf::from(path);
        config.run_lib_path = path.clone();
        config.compile_lib_path = path;
    }
    let current_exe_path = std::env::current_exe().unwrap();
    let deps_path = current_exe_path.parent().unwrap();

    // Using `-L dependency={}` enforces that external dependencies are added with `--extern`.
    // This is valuable because a) it allows us to monitor what external dependencies are used
    // and b) it ensures that conflicting rlibs are resolved properly.
    let host_libs = option_env!("HOST_LIBS")
        .map(|p| format!(" -L dependency={}", Path::new(p).join("deps").display()))
        .unwrap_or_default();
    config.target_rustcflags = Some(format!(
        "--emit=metadata -Dwarnings -Zui-testing -L dependency={}{}{}",
        deps_path.display(),
        host_libs,
        extern_flags(),
    ));

    config.build_base = host_lib().join("test_build_base");
    config.rustc_path = clippy_driver_path();
    config
}

fn run_ui(cfg: &mut compiletest::Config) {
    cfg.mode = TestMode::Ui;
    cfg.src_base = Path::new("tests").join("ui");
    // use tests/clippy.toml
    let _g = VarGuard::set("CARGO_MANIFEST_DIR", std::fs::canonicalize("tests").unwrap());
    compiletest::run_tests(cfg);
}

fn run_internal_tests(cfg: &mut compiletest::Config) {
    // only run internal tests with the internal-tests feature
    if !RUN_INTERNAL_TESTS {
        return;
    }
    cfg.mode = TestMode::Ui;
    cfg.src_base = Path::new("tests").join("ui-internal");
    compiletest::run_tests(cfg);
}

fn run_ui_toml(config: &mut compiletest::Config) {
    fn run_tests(config: &compiletest::Config, mut tests: Vec<tester::TestDescAndFn>) -> Result<bool, io::Error> {
        let mut result = true;
        let opts = compiletest::test_opts(config);
        for dir in fs::read_dir(&config.src_base)? {
            let dir = dir?;
            if !dir.file_type()?.is_dir() {
                continue;
            }
            let dir_path = dir.path();
            let _g = VarGuard::set("CARGO_MANIFEST_DIR", &dir_path);
            for file in fs::read_dir(&dir_path)? {
                let file = file?;
                let file_path = file.path();
                if file.file_type()?.is_dir() {
                    continue;
                }
                if file_path.extension() != Some(OsStr::new("rs")) {
                    continue;
                }
                let paths = compiletest::common::TestPaths {
                    file: file_path,
                    base: config.src_base.clone(),
                    relative_dir: dir_path.file_name().unwrap().into(),
                };
                let test_name = compiletest::make_test_name(config, &paths);
                let index = tests
                    .iter()
                    .position(|test| test.desc.name == test_name)
                    .expect("The test should be in there");
                result &= tester::run_tests_console(&opts, vec![tests.swap_remove(index)])?;
            }
        }
        Ok(result)
    }

    config.mode = TestMode::Ui;
    config.src_base = Path::new("tests").join("ui-toml").canonicalize().unwrap();

    let tests = compiletest::make_tests(config);

    let res = run_tests(config, tests);
    match res {
        Ok(true) => {},
        Ok(false) => panic!("Some tests failed"),
        Err(e) => {
            panic!("I/O failure during tests: {:?}", e);
        },
    }
}

fn run_ui_cargo(config: &mut compiletest::Config) {
    fn run_tests(
        config: &compiletest::Config,
        filters: &[String],
        mut tests: Vec<tester::TestDescAndFn>,
    ) -> Result<bool, io::Error> {
        let mut result = true;
        let opts = compiletest::test_opts(config);

        for dir in fs::read_dir(&config.src_base)? {
            let dir = dir?;
            if !dir.file_type()?.is_dir() {
                continue;
            }

            // Use the filter if provided
            let dir_path = dir.path();
            for filter in filters {
                if !dir_path.ends_with(filter) {
                    continue;
                }
            }

            for case in fs::read_dir(&dir_path)? {
                let case = case?;
                if !case.file_type()?.is_dir() {
                    continue;
                }

                let src_path = case.path().join("src");

                // When switching between branches, if the previous branch had a test
                // that the current branch does not have, the directory is not removed
                // because an ignored Cargo.lock file exists.
                if !src_path.exists() {
                    continue;
                }

                env::set_current_dir(&src_path)?;
                for file in fs::read_dir(&src_path)? {
                    let file = file?;
                    if file.file_type()?.is_dir() {
                        continue;
                    }

                    // Search for the main file to avoid running a test for each file in the project
                    let file_path = file.path();
                    match file_path.file_name().and_then(OsStr::to_str) {
                        Some("main.rs") => {},
                        _ => continue,
                    }
                    let _g = VarGuard::set("CLIPPY_CONF_DIR", case.path());
                    let paths = compiletest::common::TestPaths {
                        file: file_path,
                        base: config.src_base.clone(),
                        relative_dir: src_path.strip_prefix(&config.src_base).unwrap().into(),
                    };
                    let test_name = compiletest::make_test_name(config, &paths);
                    let index = tests
                        .iter()
                        .position(|test| test.desc.name == test_name)
                        .expect("The test should be in there");
                    result &= tester::run_tests_console(&opts, vec![tests.swap_remove(index)])?;
                }
            }
        }
        Ok(result)
    }

    if cargo::is_rustc_test_suite() {
        return;
    }

    config.mode = TestMode::Ui;
    config.src_base = Path::new("tests").join("ui-cargo").canonicalize().unwrap();

    let tests = compiletest::make_tests(config);

    let current_dir = env::current_dir().unwrap();
    let res = run_tests(config, &config.filters, tests);
    env::set_current_dir(current_dir).unwrap();

    match res {
        Ok(true) => {},
        Ok(false) => panic!("Some tests failed"),
        Err(e) => {
            panic!("I/O failure during tests: {:?}", e);
        },
    }
}

fn prepare_env() {
    set_var("CLIPPY_DISABLE_DOCS_LINKS", "true");
    set_var("__CLIPPY_INTERNAL_TESTS", "true");
    //set_var("RUST_BACKTRACE", "0");
}

#[test]
fn compile_test() {
    prepare_env();
    let mut config = default_config();
    run_ui(&mut config);
    run_ui_toml(&mut config);
    run_ui_cargo(&mut config);
    run_internal_tests(&mut config);
}

/// Restores an env var on drop
#[must_use]
struct VarGuard {
    key: &'static str,
    value: Option<OsString>,
}

impl VarGuard {
    fn set(key: &'static str, val: impl AsRef<OsStr>) -> Self {
        let value = var_os(key);
        set_var(key, val);
        Self { key, value }
    }
}

impl Drop for VarGuard {
    fn drop(&mut self) {
        match self.value.as_deref() {
            None => remove_var(self.key),
            Some(value) => set_var(self.key, value),
        }
    }
}
<|endoftext|>


<commit_before>use reproto_core::RpVersionedPackage;
use std::collections::HashMap;
use std::rc::Rc;

struct Root {
    pub package: RpVersionedPackage,
    pub prefixes: HashMap<String, RpVersionedPackage>,
}

/// Model of a scope.
enum Inner {
    Root { root: Rc<Root> },
    Child {
        root: Rc<Root>,
        name: String,
        parent: Rc<Inner>,
    },
}

pub struct Scope {
    inner: Rc<Inner>,
}

impl Scope {
    pub fn new(
        package: RpVersionedPackage,
        prefixes: HashMap<String, RpVersionedPackage>,
    ) -> Scope {
        let root = Rc::new(Root {
            package: package,
            prefixes: prefixes,
        });
        let inner_root = Inner::Root { root: root.clone() };

        Scope { inner: Rc::new(inner_root) }
    }

    pub fn child<S: AsRef<str>>(&self, name: S) -> Scope {
        let root = match *self.inner {
            Inner::Root { ref root, .. } |
            Inner::Child { ref root, .. } => root.clone(),
        };

        Scope {
            inner: Rc::new(Inner::Child {
                root: root,
                name: name.as_ref().to_owned(),
                parent: self.inner.clone(),
            }),
        }
    }

    pub fn lookup_prefix(&self, prefix: &String) -> Option<&RpVersionedPackage> {
        match *self.inner {
            Inner::Root { ref root, .. } |
            Inner::Child { ref root, .. } => root.prefixes.get(prefix),
        }
    }

    pub fn package(&self) -> &RpVersionedPackage {
        match *self.inner {
            Inner::Root { ref root, .. } |
            Inner::Child { ref root, .. } => &root.package,
        }
    }

    pub fn walk(&self) -> ScopeWalker {
        ScopeWalker { current: self.inner.clone() }
    }
}

pub struct ScopeWalker {
    current: Rc<Inner>,
}

impl Iterator for ScopeWalker {
    type Item = String;

    fn next(&mut self) -> Option<String> {
        let (next, current) = match *self.current {
            Inner::Root { .. } => {
                return None;
            }
            Inner::Child {
                ref name,
                ref parent,
                ..
            } => (Some(name.to_owned()), parent.clone()),
        };

        self.current = current;
        next
    }
}

#[cfg(test)]
mod tests {
    use super::Scope;

    #[test]
    pub fn test_scope() {
        let s = Scope::new();
        let s2 = s.child("foo");
        let s3 = s2.child("bar");

        let parts: Vec<_> = s3.walk().collect();

        assert_eq!(vec!["bar".to_owned(), "foo".to_owned()], parts);
    }
}
<commit_msg>[parser] fix tests<commit_after>use reproto_core::RpVersionedPackage;
use std::collections::HashMap;
use std::rc::Rc;

struct Root {
    pub package: RpVersionedPackage,
    pub prefixes: HashMap<String, RpVersionedPackage>,
}

/// Model of a scope.
enum Inner {
    Root { root: Rc<Root> },
    Child {
        root: Rc<Root>,
        name: String,
        parent: Rc<Inner>,
    },
}

pub struct Scope {
    inner: Rc<Inner>,
}

impl Scope {
    pub fn new(
        package: RpVersionedPackage,
        prefixes: HashMap<String, RpVersionedPackage>,
    ) -> Scope {
        let root = Rc::new(Root {
            package: package,
            prefixes: prefixes,
        });
        let inner_root = Inner::Root { root: root.clone() };

        Scope { inner: Rc::new(inner_root) }
    }

    pub fn child<S: AsRef<str>>(&self, name: S) -> Scope {
        let root = match *self.inner {
            Inner::Root { ref root, .. } |
            Inner::Child { ref root, .. } => root.clone(),
        };

        Scope {
            inner: Rc::new(Inner::Child {
                root: root,
                name: name.as_ref().to_owned(),
                parent: self.inner.clone(),
            }),
        }
    }

    pub fn lookup_prefix(&self, prefix: &String) -> Option<&RpVersionedPackage> {
        match *self.inner {
            Inner::Root { ref root, .. } |
            Inner::Child { ref root, .. } => root.prefixes.get(prefix),
        }
    }

    pub fn package(&self) -> &RpVersionedPackage {
        match *self.inner {
            Inner::Root { ref root, .. } |
            Inner::Child { ref root, .. } => &root.package,
        }
    }

    pub fn walk(&self) -> ScopeWalker {
        ScopeWalker { current: self.inner.clone() }
    }
}

pub struct ScopeWalker {
    current: Rc<Inner>,
}

impl Iterator for ScopeWalker {
    type Item = String;

    fn next(&mut self) -> Option<String> {
        let (next, current) = match *self.current {
            Inner::Root { .. } => {
                return None;
            }
            Inner::Child {
                ref name,
                ref parent,
                ..
            } => (Some(name.to_owned()), parent.clone()),
        };

        self.current = current;
        next
    }
}

#[cfg(test)]
mod tests {
    use super::Scope;
    use reproto_core::{RpPackage, RpVersionedPackage};
    use std::collections::HashMap;

    #[test]
    pub fn test_scope() {
        let package = RpVersionedPackage::new(RpPackage::empty(), None);
        let prefixes = HashMap::new();
        let s = Scope::new(package, prefixes);

        let s2 = s.child("foo");
        let s3 = s2.child("bar");

        let parts: Vec<_> = s3.walk().collect();

        assert_eq!(vec!["bar".to_owned(), "foo".to_owned()], parts);
    }
}
<|endoftext|>


<commit_before>//! AST node definitions which will be parsed into. Based off of the
//! `graphql-js` [`ast.js`][1] definitions.
//!
//! [1]: https://github.com/graphql/graphql-js/blob/dfe676c3011efe9560b9fa0fcbd2b7bd87476d02/src/language/ast.js

use source::Source;

/// Contains some character offsets that identify where the source of the AST
/// is from.
pub struct Location<'a> {
  pub start: usize,
  pub end: usize,
  pub source: Option<&'a Source<'a>>
}

/// All AST node types implement this trait.
pub trait Node<'a> {
  fn location(&self) -> &Option<Location<'a>>;
}

macro_rules! impl_node_for {
  ($data:ident) => {
    impl<'a> Node<'a> for $data<'a> {
      fn location(&self) -> &Option<Location<'a>> {
        &self.loc
      }
    }
  }
}

/// Name :: /[_A-Za-z][_0-9A-Za-z]*/
pub struct Name<'a> {
  pub loc: Option<Location<'a>>,
  pub value: &'a str
}

impl_node_for! { Name }

/// IntValue :: IntegerPart
pub struct IntValue<'a> {
  pub loc: Option<Location<'a>>,
  pub value: &'a str
}

impl_node_for! { IntValue }

/// FloatValue ::
///   - IntegerPart FractionalPart
///   - IntegerPart ExponentPart
///   - IntegerPart FractionalPart ExponentPart
pub struct FloatValue<'a> {
  pub loc: Option<Location<'a>>,
  pub value: &'a str
}

impl_node_for! { FloatValue }

/// StringValue ::
///   - `""`
///   - `"` StringCharacter+ `"`
pub struct StringValue<'a> {
  pub loc: Option<Location<'a>>,
  pub value: String
}

impl_node_for! { StringValue }

/// Document : Definition+
pub struct Document<'a> {
  pub loc: Option<Location<'a>>,
  pub definitions: Vec<Definition<'a>>
}

impl_node_for! { Document }

/// Definition :
///   - OperationDefinition
///   - FragmentDefinition
pub enum Definition<'a> {
  Operation(OperationDefinition<'a>),
  Fragment(FragmentDefinition<'a>)
}

/// OperationDefinition :
///   - SelectionSet
///   - OperationType Name? VariableDefinitions? Directives? SelectionSet
pub struct OperationDefinition<'a> {
  pub loc: Option<Location<'a>>,
  pub operation: OperationType,
  pub name: Option<Name<'a>>,
  pub variable_definitions: Option<VariableDefinitions<'a>>,
  pub directives: Option<Directives<'a>>,
  pub selection_set: SelectionSet<'a>
}

impl_node_for! { OperationDefinition }

/// OperationType : one of query mutation
pub enum OperationType {
  Query,
  Mutation
}

/// SelectionSet : { Selection+ }
pub struct SelectionSet<'a> {
  pub loc: Option<Location<'a>>,
  pub selections: Vec<Selection<'a>>
}

impl_node_for! { SelectionSet }

/// Selection :
///   - Field
///   - FragmentSpread
///   - InlineFragment
pub enum Selection<'a> {
  Field(Field<'a>),
  FragmentSpread(FragmentSpread<'a>),
  InlineFragment(InlineFragment<'a>)
}

/// Field : Alias? Name Arguments? Directives? SelectionSet?
pub struct Field<'a> {
  pub loc: Option<Location<'a>>,
  pub alias: Option<Alias<'a>>,
  pub name: Name<'a>,
  pub arguments: Option<Arguments<'a>>,
  pub directives: Option<Directives<'a>>,
  pub selection_set: Option<SelectionSet<'a>>
}

impl_node_for! { Field }

/// Alias : Name :
pub type Alias<'a> = Name<'a>;

/// Arguments : ( Argument+ )
pub type Arguments<'a> = Vec<Argument<'a>>;

/// Argument : Name : Value
pub struct Argument<'a> {
  pub loc: Option<Location<'a>>,
  pub name: Name<'a>,
  pub value: Value<'a>
}

impl_node_for! { Argument }

/// FragmentSpread : ... FragmentName Directives?
pub struct FragmentSpread<'a> {
  pub loc: Option<Location<'a>>,
  pub name: Name<'a>,
  pub directives: Option<Directives<'a>>
}

impl_node_for! { FragmentSpread }

/// InlineFragment : ... TypeCondition? Directives? SelectionSet
pub struct InlineFragment<'a> {
  pub loc: Option<Location<'a>>,
  pub type_condition: Option<TypeCondition<'a>>,
  pub directives: Option<Directives<'a>>,
  pub selection_set: SelectionSet<'a>
}

impl_node_for! { InlineFragment }

/// FragmentDefinition : fragment FragmentName TypeCondition Directives? SelectionSet
pub struct FragmentDefinition<'a> {
  pub loc: Option<Location<'a>>,
  pub name: Name<'a>,
  pub type_condition: TypeCondition<'a>,
  pub directives: Option<Directives<'a>>,
  pub selection_set: SelectionSet<'a>
}

impl_node_for! { FragmentDefinition }

/// FragmentName : Name but not `on`
pub type FragmentName<'a> = Name<'a>;

/// TypeCondition : on NamedType
pub type TypeCondition<'a> = NamedType<'a>;

/// Value[Const] :
///   - [~Const] Variable
///   - IntValue
///   - FloatValue
///   - StringValue
///   - BooleanValue
///   - EnumValue
///   - ListValue[?Const]
///   - ObjectValue[?Const]
pub enum Value<'a> {
  Variable(Variable<'a>),
  Int(IntValue<'a>),
  Float(FloatValue<'a>),
  String(StringValue<'a>),
  Boolean(BooleanValue<'a>),
  Enum(EnumValue<'a>),
  List(ListValue<'a>),
  Object(ObjectValue<'a>)
}

/// BooleanValue : one of `true` `false`
pub struct BooleanValue<'a> {
  pub loc: Option<Location<'a>>,
  pub value: bool
}

impl_node_for! { BooleanValue }

/// EnumValue : Name but not `true`, `false` or `null`
pub struct EnumValue<'a> {
  pub loc: Option<Location<'a>>,
  pub name: Name<'a>
}

impl_node_for! { EnumValue }

/// ListValue[Const] :
///   - [ ]
///   - [ Value[?Const]+ ]
pub struct ListValue<'a> {
  pub loc: Option<Location<'a>>,
  pub values: Vec<Value<'a>>
}

impl_node_for! { ListValue }

/// ObjectValue[Const] :
///   - { }
///   - { ObjectField[?Const]+ }
pub struct ObjectValue<'a> {
  pub loc: Option<Location<'a>>,
  pub fields: Vec<ObjectField<'a>>
}

impl_node_for! { ObjectValue }

/// ObjectField[Const] : Name : Value[?Const]
pub struct ObjectField<'a> {
  pub loc: Option<Location<'a>>,
  pub name: Name<'a>,
  pub value: Value<'a>
}

impl_node_for! { ObjectField }

/// VariableDefinitions : ( VariableDefinition+ )
pub type VariableDefinitions<'a> = Vec<VariableDefinition<'a>>;

/// VariableDefinition : Variable : Type DefaultValue?
pub struct VariableDefinition<'a> {
  pub loc: Option<Location<'a>>,
  pub variable: Variable<'a>,
  pub type_: Type<'a>,
  pub default_value: Option<DefaultValue<'a>>
}

impl_node_for! { VariableDefinition }

/// Variable : $ Name
pub struct Variable<'a> {
  pub loc: Option<Location<'a>>,
  pub name: Name<'a>
}

impl_node_for! { Variable }

/// DefaultValue : = Value[Const]
pub type DefaultValue<'a> = Value<'a>;

/// Type :
///   - NamedType
///   - ListType
///   - NonNullType
pub enum Type<'a> {
  Named(NamedType<'a>),
  List(Box<ListType<'a>>),
  NonNullNamed(Box<NonNullNamedType<'a>>),
  NonNullList(Box<NonNullListType<'a>>)
}

/// NamedType : Name
pub struct NamedType<'a> {
  pub loc: Option<Location<'a>>,
  pub name: Name<'a>
}

impl_node_for! { NamedType }

/// ListType : [ Type ]
pub struct ListType<'a> {
  pub loc: Option<Location<'a>>,
  pub type_: Type<'a>
}

impl_node_for! { ListType }

/// NonNullType :
///   - NamedType !
///   - ListType !
///
/// Are implementation deviates from the spec here. This is because
/// `NonNullType` is expected to be a [node][1], but it is also expected to be
/// a [union][2]. The best way to express this in Rust is with two types.
///
/// [1]: https://github.com/graphql/graphql-js/blob/dfe676c3011efe9560b9fa0fcbd2b7bd87476d02/src/language/ast.js#L49
/// [2]: https://github.com/graphql/graphql-js/blob/dfe676c3011efe9560b9fa0fcbd2b7bd87476d02/src/language/ast.js#L254
pub struct NonNullNamedType<'a> {
  pub loc: Option<Location<'a>>,
  pub type_: NamedType<'a>
}

impl_node_for! { NonNullNamedType }

/// See documentation for the `NonNullNamedType` struct.
pub struct NonNullListType<'a> {
  pub loc: Option<Location<'a>>,
  pub type_: ListType<'a>
}

impl_node_for! { NonNullListType }

/// Directives : Directive+
pub type Directives<'a> = Vec<Directive<'a>>;

/// Directive : @ Name Arguments?
pub struct Directive<'a> {
  pub loc: Option<Location<'a>>,
  pub name: Name<'a>,
  pub arguments: Option<Arguments<'a>>
}

impl_node_for! { Directive }
<commit_msg>fix: as_ref<commit_after>//! AST node definitions which will be parsed into. Based off of the
//! `graphql-js` [`ast.js`][1] definitions.
//!
//! [1]: https://github.com/graphql/graphql-js/blob/dfe676c3011efe9560b9fa0fcbd2b7bd87476d02/src/language/ast.js

use source::Source;

/// Contains some character offsets that identify where the source of the AST
/// is from.
pub struct Location<'a> {
  pub start: usize,
  pub end: usize,
  pub source: Option<&'a Source<'a>>
}

/// All AST node types implement this trait.
pub trait Node<'a> {
  fn location(&self) -> Option<&Location<'a>>;
}

macro_rules! impl_node_for {
  ($data:ident) => {
    impl<'a> Node<'a> for $data<'a> {
      fn location(&self) -> Option<&Location<'a>> {
        self.loc.as_ref()
      }
    }
  }
}

/// Name :: /[_A-Za-z][_0-9A-Za-z]*/
pub struct Name<'a> {
  pub loc: Option<Location<'a>>,
  pub value: &'a str
}

impl_node_for! { Name }

/// IntValue :: IntegerPart
pub struct IntValue<'a> {
  pub loc: Option<Location<'a>>,
  pub value: &'a str
}

impl_node_for! { IntValue }

/// FloatValue ::
///   - IntegerPart FractionalPart
///   - IntegerPart ExponentPart
///   - IntegerPart FractionalPart ExponentPart
pub struct FloatValue<'a> {
  pub loc: Option<Location<'a>>,
  pub value: &'a str
}

impl_node_for! { FloatValue }

/// StringValue ::
///   - `""`
///   - `"` StringCharacter+ `"`
pub struct StringValue<'a> {
  pub loc: Option<Location<'a>>,
  pub value: String
}

impl_node_for! { StringValue }

/// Document : Definition+
pub struct Document<'a> {
  pub loc: Option<Location<'a>>,
  pub definitions: Vec<Definition<'a>>
}

impl_node_for! { Document }

/// Definition :
///   - OperationDefinition
///   - FragmentDefinition
pub enum Definition<'a> {
  Operation(OperationDefinition<'a>),
  Fragment(FragmentDefinition<'a>)
}

/// OperationDefinition :
///   - SelectionSet
///   - OperationType Name? VariableDefinitions? Directives? SelectionSet
pub struct OperationDefinition<'a> {
  pub loc: Option<Location<'a>>,
  pub operation: OperationType,
  pub name: Option<Name<'a>>,
  pub variable_definitions: Option<VariableDefinitions<'a>>,
  pub directives: Option<Directives<'a>>,
  pub selection_set: SelectionSet<'a>
}

impl_node_for! { OperationDefinition }

/// OperationType : one of query mutation
pub enum OperationType {
  Query,
  Mutation
}

/// SelectionSet : { Selection+ }
pub struct SelectionSet<'a> {
  pub loc: Option<Location<'a>>,
  pub selections: Vec<Selection<'a>>
}

impl_node_for! { SelectionSet }

/// Selection :
///   - Field
///   - FragmentSpread
///   - InlineFragment
pub enum Selection<'a> {
  Field(Field<'a>),
  FragmentSpread(FragmentSpread<'a>),
  InlineFragment(InlineFragment<'a>)
}

/// Field : Alias? Name Arguments? Directives? SelectionSet?
pub struct Field<'a> {
  pub loc: Option<Location<'a>>,
  pub alias: Option<Alias<'a>>,
  pub name: Name<'a>,
  pub arguments: Option<Arguments<'a>>,
  pub directives: Option<Directives<'a>>,
  pub selection_set: Option<SelectionSet<'a>>
}

impl_node_for! { Field }

/// Alias : Name :
pub type Alias<'a> = Name<'a>;

/// Arguments : ( Argument+ )
pub type Arguments<'a> = Vec<Argument<'a>>;

/// Argument : Name : Value
pub struct Argument<'a> {
  pub loc: Option<Location<'a>>,
  pub name: Name<'a>,
  pub value: Value<'a>
}

impl_node_for! { Argument }

/// FragmentSpread : ... FragmentName Directives?
pub struct FragmentSpread<'a> {
  pub loc: Option<Location<'a>>,
  pub name: Name<'a>,
  pub directives: Option<Directives<'a>>
}

impl_node_for! { FragmentSpread }

/// InlineFragment : ... TypeCondition? Directives? SelectionSet
pub struct InlineFragment<'a> {
  pub loc: Option<Location<'a>>,
  pub type_condition: Option<TypeCondition<'a>>,
  pub directives: Option<Directives<'a>>,
  pub selection_set: SelectionSet<'a>
}

impl_node_for! { InlineFragment }

/// FragmentDefinition : fragment FragmentName TypeCondition Directives? SelectionSet
pub struct FragmentDefinition<'a> {
  pub loc: Option<Location<'a>>,
  pub name: Name<'a>,
  pub type_condition: TypeCondition<'a>,
  pub directives: Option<Directives<'a>>,
  pub selection_set: SelectionSet<'a>
}

impl_node_for! { FragmentDefinition }

/// FragmentName : Name but not `on`
pub type FragmentName<'a> = Name<'a>;

/// TypeCondition : on NamedType
pub type TypeCondition<'a> = NamedType<'a>;

/// Value[Const] :
///   - [~Const] Variable
///   - IntValue
///   - FloatValue
///   - StringValue
///   - BooleanValue
///   - EnumValue
///   - ListValue[?Const]
///   - ObjectValue[?Const]
pub enum Value<'a> {
  Variable(Variable<'a>),
  Int(IntValue<'a>),
  Float(FloatValue<'a>),
  String(StringValue<'a>),
  Boolean(BooleanValue<'a>),
  Enum(EnumValue<'a>),
  List(ListValue<'a>),
  Object(ObjectValue<'a>)
}

/// BooleanValue : one of `true` `false`
pub struct BooleanValue<'a> {
  pub loc: Option<Location<'a>>,
  pub value: bool
}

impl_node_for! { BooleanValue }

/// EnumValue : Name but not `true`, `false` or `null`
pub struct EnumValue<'a> {
  pub loc: Option<Location<'a>>,
  pub name: Name<'a>
}

impl_node_for! { EnumValue }

/// ListValue[Const] :
///   - [ ]
///   - [ Value[?Const]+ ]
pub struct ListValue<'a> {
  pub loc: Option<Location<'a>>,
  pub values: Vec<Value<'a>>
}

impl_node_for! { ListValue }

/// ObjectValue[Const] :
///   - { }
///   - { ObjectField[?Const]+ }
pub struct ObjectValue<'a> {
  pub loc: Option<Location<'a>>,
  pub fields: Vec<ObjectField<'a>>
}

impl_node_for! { ObjectValue }

/// ObjectField[Const] : Name : Value[?Const]
pub struct ObjectField<'a> {
  pub loc: Option<Location<'a>>,
  pub name: Name<'a>,
  pub value: Value<'a>
}

impl_node_for! { ObjectField }

/// VariableDefinitions : ( VariableDefinition+ )
pub type VariableDefinitions<'a> = Vec<VariableDefinition<'a>>;

/// VariableDefinition : Variable : Type DefaultValue?
pub struct VariableDefinition<'a> {
  pub loc: Option<Location<'a>>,
  pub variable: Variable<'a>,
  pub type_: Type<'a>,
  pub default_value: Option<DefaultValue<'a>>
}

impl_node_for! { VariableDefinition }

/// Variable : $ Name
pub struct Variable<'a> {
  pub loc: Option<Location<'a>>,
  pub name: Name<'a>
}

impl_node_for! { Variable }

/// DefaultValue : = Value[Const]
pub type DefaultValue<'a> = Value<'a>;

/// Type :
///   - NamedType
///   - ListType
///   - NonNullType
pub enum Type<'a> {
  Named(NamedType<'a>),
  List(Box<ListType<'a>>),
  NonNullNamed(Box<NonNullNamedType<'a>>),
  NonNullList(Box<NonNullListType<'a>>)
}

/// NamedType : Name
pub struct NamedType<'a> {
  pub loc: Option<Location<'a>>,
  pub name: Name<'a>
}

impl_node_for! { NamedType }

/// ListType : [ Type ]
pub struct ListType<'a> {
  pub loc: Option<Location<'a>>,
  pub type_: Type<'a>
}

impl_node_for! { ListType }

/// NonNullType :
///   - NamedType !
///   - ListType !
///
/// Are implementation deviates from the spec here. This is because
/// `NonNullType` is expected to be a [node][1], but it is also expected to be
/// a [union][2]. The best way to express this in Rust is with two types.
///
/// [1]: https://github.com/graphql/graphql-js/blob/dfe676c3011efe9560b9fa0fcbd2b7bd87476d02/src/language/ast.js#L49
/// [2]: https://github.com/graphql/graphql-js/blob/dfe676c3011efe9560b9fa0fcbd2b7bd87476d02/src/language/ast.js#L254
pub struct NonNullNamedType<'a> {
  pub loc: Option<Location<'a>>,
  pub type_: NamedType<'a>
}

impl_node_for! { NonNullNamedType }

/// See documentation for the `NonNullNamedType` struct.
pub struct NonNullListType<'a> {
  pub loc: Option<Location<'a>>,
  pub type_: ListType<'a>
}

impl_node_for! { NonNullListType }

/// Directives : Directive+
pub type Directives<'a> = Vec<Directive<'a>>;

/// Directive : @ Name Arguments?
pub struct Directive<'a> {
  pub loc: Option<Location<'a>>,
  pub name: Name<'a>,
  pub arguments: Option<Arguments<'a>>
}

impl_node_for! { Directive }
<|endoftext|>


<commit_before>//
// gash module for ps2 and ps3
//
// University of Virginia - cs4414 Spring 2014
// Weilin Xu, David Evans
// Version 0.1
//

use std::{io, run, os, libc, path};
use std::io::pipe::PipeStream;

pub fn run_cmdline(cmd_line: &str) -> ~str{
    let cmd_line: ~str = cmd_line.trim().to_owned();

    // handle pipelines
    let progs: ~[~str] =
        cmd_line.split('|').filter_map(|x| if x != "" { Some(x.to_owned()) } else { None }).to_owned_vec();

    let mut pipes: ~[os::Pipe] = ~[];

    // create pipes
    pipes.push(os::Pipe { input: 0, out: 0 }); // first pipe is standard input
    for _ in range(0, progs.len() - 1) {
        pipes.push(os::pipe());
    }
    pipes.push(os::pipe()); // last is not necessarily the standard output, for ps3

    for i in range(0, progs.len()) {
        run_single_cmd(progs[i], pipes[i].input, pipes[i+1].out, 2,
                            if (i == progs.len() - 1) { false } else { true }); // all in bg except possibly last one
    }
    // read output from the last pipe.input.

    let mut pipe_stream = PipeStream::open(pipes[progs.len()].input);
    let content = pipe_stream.read_to_str();
    return content;
}

// run a single command line, probably with redirection sign >, definitly without pipelines | and background sign &.
fn run_single_cmd(cmd_line: &str, pipe_in: libc::c_int, pipe_out: libc::c_int, pipe_err: libc::c_int, bg: bool) {
    let mut argv = parse_argv(cmd_line);

    if argv.len() <= 0 {
        // empty command line
        return;
    }

    let mut out_fd = pipe_out;
    let mut in_fd = pipe_in;
    let err_fd = pipe_err;

    let mut i = 0;

    while (i < argv.len()) {
        if (argv[i] == ~">") {
            argv.remove(i);
            out_fd = get_fd(argv.remove(i), "w");
        } else if (argv[i] == ~"<") {
            argv.remove(i);
            in_fd = get_fd(argv.remove(i), "r");
        }
        i += 1;
    }

    let out_fd = out_fd;
    let in_fd = in_fd;

    if argv.len() <= 0 {
        // invalid command line
        return;
    }

    let program = argv.remove(0);
    match program {
        ~"cd"       => { if argv.len()>0 { os::change_dir(&path::Path::new(argv[0])); } }
        _           => { if !cmd_exists(program) {
                             println!("{:s}: command not found", program);
                             return;
                         } else {
                             // To see debug! outputs set the RUST_LOG environment variable, e.g.: export RUST_LOG="gash=debug"
                             debug!("Program: {:s}, in_fd: {:d}, out_fd: {:d}, err_fd: {:d}", program, in_fd, out_fd, err_fd);
                             let opt_prog = run::Process::new(program, argv,
                                                              run::ProcessOptions { env: None, dir: None,
                                                                                in_fd: Some(in_fd), out_fd: Some(out_fd), err_fd: Some(err_fd)
                                                                                });

                             let mut prog = opt_prog.expect("Error: creating process error.");
                             if in_fd != 0 {os::close(in_fd);}
                             if out_fd != 1 {os::close(out_fd);}
                             if err_fd != 2 {os::close(err_fd);}

                             if !bg {
                                 prog.finish();
                                 io::stdio::flush();
                                 debug!("Terminated fg program: {:}", program);
                             } else {
                                 let (p_port, p_chan) = Chan::new();
                                 p_chan.send(prog);
                                 spawn(proc() {
                                    let mut prog: run::Process = p_port.recv();

                                    prog.finish();
                                    io::stdio::flush();
                                    debug!("Terminated bg program: {:}", program);
                                 });
                            }
                        }
                  }
    } // match program
} // run_single_cmd

// input: a single command line
// output: a vector of arguments. The program name is put in the first position.
// notes: arguments can be separated by space(s), ""
fn parse_argv(cmd_line: &str) -> ~[~str] {
    let mut argv: ~[~str] = ~[];
    let group: ~[~str] = cmd_line.split('\"').filter_map(|x| if x != "" { Some(x.to_owned()) } else { None }).to_owned_vec();

    for i in range(0, group.len()) {
        if i % 2 == 0 { // split by " "
            argv.push_all_move(group[i].split(' ').filter_map(|x| if x != "" { Some(x.to_owned()) } else { None }).to_owned_vec());
        } else {
            argv.push(group[i].clone());
        }
    }

    argv
}

fn cmd_exists(cmd_path: &str) -> bool {
    run::process_output("which", [cmd_path.to_owned()]).expect("exit code error.").status.success()
}

fn get_fd(fpath: &str, mode: &str) -> libc::c_int {
    unsafe {
        let fpathbuf = fpath.to_c_str().unwrap();
        let modebuf = mode.to_c_str().unwrap();
        return libc::fileno(libc::fopen(fpathbuf, modebuf));
    }
}

#[cfg(test)]
mod tests {
    use gash;
    #[test]
    fn test_run_cmdline() {
        let ret_str = run_cmdline("echo -e \"abc\nxyz\" | grep ab");
        println(ret_str);
        assert_eq!(ret_str, ~"abc");
    }
}
<commit_msg>Replaced gash with reference solution<commit_after>//
// gash.rs
//
// Reference solution for PS2 (Rust 0.9)
//
// University of Virginia - cs4414 Spring 2014
// Weilin Xu, David Evans
// Version 0.5
//

extern mod extra;

use std::{io, run, os, libc, path};
use std::io::buffered::BufferedReader;
use std::io::stdin;
use extra::getopts;
use std::io::signal::{Listener, Interrupt};

struct Shell {
    history: ~[~str],
    cmd_prompt: ~str,
}

impl Shell {
    fn new(prompt_str: &str) -> Shell {
        Shell {
            history: ~[],
            cmd_prompt: prompt_str.to_owned(),
        }
    }

    fn run(&mut self) {
        self.register_signal_handler();
        let mut stdin = BufferedReader::new(stdin());

        loop {
            print(self.cmd_prompt);
            io::stdio::flush();

            let line = stdin.read_line().unwrap();
            let cmd_line = line.trim().to_owned();

            if cmd_line.len() > 0 {
                self.history.push(cmd_line.to_owned());
            }

            let program = cmd_line.splitn(' ', 1).nth(0).expect("no program");

            match program {
                // no need to parse the arguements for several internal commands.
                ""          =>  { continue; }
                "exit"      =>  { self.exit(0); }
                "help"      =>  { println("This is a new shell implemented in Rust!") }
                "history"   =>  {
                                    for i in range(0, self.history.len()) {
                                        println(format!("{:u} {:s}", i+1, self.history[i]));
                                    }
                                }
                _           =>  { self.run_cmdline(cmd_line); }

            }
        }
    }

    // run command line, called by self.run() or external -c parameter.
    fn run_cmdline(&mut self, cmd_line: &str) {
        // handle background commands using &
        let mut bg_flag;
        let mut cmd_line: ~str = cmd_line.to_owned();
        if cmd_line.ends_with("&") {
            bg_flag = true;
            cmd_line = cmd_line.trim_right_chars(&'&').to_owned();
        } else {
            bg_flag = false;
        }

        // handle pipelines
        let progs: ~[~str] =
            cmd_line.split('|').filter_map(|x| if x != "" { Some(x.to_owned()) } else { None }).to_owned_vec();

        let mut pipes: ~[os::Pipe] = ~[];

        // create pipes
        pipes.push(os::Pipe { input: 0, out: 0 }); // first pipe is standard input
        for _ in range(0, progs.len() - 1) {
            pipes.push(os::pipe());
        }
        pipes.push(os::Pipe { input: 1, out: 1 }); // last is standard output

        for i in range(0, progs.len()) {
            self.run_single_cmd(progs[i], pipes[i].input, pipes[i+1].out, 2,
                                if (i == progs.len() - 1) { bg_flag } else { true }); // all in bg except possibly last one
        }
    }

    // run a single command line, probably with redirection sign >, definitly without pipelines | and background sign &.
    fn run_single_cmd(&mut self, cmd_line: &str, pipe_in: libc::c_int, pipe_out: libc::c_int, pipe_err: libc::c_int, bg: bool) {
        let mut argv = self.parse_argv(cmd_line);

        if argv.len() <= 0 {
            // empty command line
            return;
        }

        let mut out_fd = pipe_out;
        let mut in_fd = pipe_in;
        let err_fd = pipe_err;

        let mut i = 0;
        // found problem on redirection
        // `ping google.com | grep 1 > ping.txt &` didn't work
        // because grep won't flush the buffer until terminated (only) by SIGINT.
        while (i < argv.len()) {
            if (argv[i] == ~">") {
                argv.remove(i);
                out_fd = self.get_fd(argv.remove(i), "w");
            } else if (argv[i] == ~"<") {
                argv.remove(i);
                in_fd = self.get_fd(argv.remove(i), "r");
            }
            i += 1;
        }

        let out_fd = out_fd;
        let in_fd = in_fd;

        if argv.len() <= 0 {
            // invalid command line
            return;
        }

        let program = argv.remove(0);
        match program {
            ~"cd"       => { if argv.len()>0 { os::change_dir(&path::Path::new(argv[0])); } }
            _           => { if !self.cmd_exists(program) {
                                 println!("{:s}: command not found", program);
                                 return;
                             } else {
                                 // To see debug! outputs set the RUST_LOG environment variable, e.g.: export RUST_LOG="gash=debug"
                                 debug!("Program: {:s}, in_fd: {:d}, out_fd: {:d}, err_fd: {:d}", program, in_fd, out_fd, err_fd);
                                 let opt_prog = run::Process::new(program, argv,
                                                                  run::ProcessOptions { env: None, dir: None,
                                                                                in_fd: Some(in_fd), out_fd: Some(out_fd), err_fd: Some(err_fd)
                                                                                });

                                 let mut prog = opt_prog.expect("Error: creating process error.");
                                 if in_fd != 0 {os::close(in_fd);}
                                 if out_fd != 1 {os::close(out_fd);}
                                 if err_fd != 2 {os::close(err_fd);}

                                 if !bg {
                                     prog.finish();
                                     io::stdio::flush();
                                     debug!("Terminated fg program: {:}", program);
                                 } else {
                                     let (p_port, p_chan) = Chan::new();
                                     p_chan.send(prog);
                                     spawn(proc() {
                                        let mut prog: run::Process = p_port.recv();

                                        prog.finish();
                                        io::stdio::flush();
                                        debug!("Terminated bg program: {:}", program);
                                     });
                                }
                            }
                      }
        } // match program
    } // run_single_cmd

    // input: a single command line
    // output: a vector of arguments. The program name is put in the first position.
    // notes: arguments can be separated by space(s), ""
    fn parse_argv(&mut self, cmd_line: &str) -> ~[~str] {
        let mut argv: ~[~str] = ~[];
        let group: ~[~str] = cmd_line.split('\"').filter_map(|x| if x != "" { Some(x.to_owned()) } else { None }).to_owned_vec();

        for i in range(0, group.len()) {
            if i % 2 == 0 { // split by " "
                argv.push_all_move(group[i].split(' ').filter_map(|x| if x != "" { Some(x.to_owned()) } else { None }).to_owned_vec());
            } else {
                argv.push(group[i].clone());
            }

        }

        argv
    }

    fn cmd_exists(&mut self, cmd_path: &str) -> bool {
        run::process_output("which", [cmd_path.to_owned()]).expect("exit code error.").status.success()
    }

    fn get_fd(&mut self, fpath: &str, mode: &str) -> libc::c_int {
        unsafe {
            let fpathbuf = fpath.to_c_str().unwrap();
            let modebuf = mode.to_c_str().unwrap();
            return libc::fileno(libc::fopen(fpathbuf, modebuf));
        }
    }

    fn register_signal_handler(&mut self) {
        spawn(proc() {
            // TODO: Should unregister the listener at exit.
            let mut listener = Listener::new();
            let ret = listener.register(Interrupt);

            if ret {
                loop {
                    match listener.port.recv() {
                        Interrupt => (), // Do nothing, just prevent gash from terminating.
                        _ => (),
                    }
                }
            } else {
                println("Warning: registering signal handler fails.");
            }
       });
    }

    fn exit(&mut self, status: int) {
        unsafe { libc::exit(status as i32); }
    }
}

fn get_cmdline_from_args() -> Option<~str> {
    fn print_usage(program: &str) {
        println!("Usage: {:s} [options]", program);
        println("-c            \tcommand");
        println("-h --help     \tUsage");
    }

    /* Begin processing program arguments and initiate the parameters. */
    let args = os::args();
    let program = args[0].clone();

    let opts = ~[
        getopts::optopt("c"),
        getopts::optflag("h"),
        getopts::optflag("help")
    ];

    let matches = match getopts::getopts(args.tail(), opts) {
        Ok(m) => { m }
        Err(f) => { fail!(f.to_err_msg()) }
    };

    if matches.opt_present("h") || matches.opt_present("help") {
        print_usage(program);
        unsafe { libc::exit(1); }
    }

    if matches.opt_present("c") {
        Some(match matches.opt_str("c") { Some(cmd_str) => {cmd_str.to_owned()},
                                          None => {~""}
                                        })
    } else {
        None
    }
}

fn main() {
    match get_cmdline_from_args() {
        Some(cmd_line) => Shell::new("").run_cmdline(cmd_line),
        None           => Shell::new("gash> ").run()
    }
}
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#![deny(warnings)]

#[macro_use]extern crate style;
extern crate app_units;
extern crate atomic_refcell;
extern crate cssparser;
extern crate env_logger;
extern crate euclid;
extern crate libc;
#[macro_use] extern crate log;
extern crate parking_lot;
extern crate selectors;
extern crate servo_url;
extern crate style_traits;

#[allow(non_snake_case)]
pub mod glue;
mod stylesheet_loader;

// FIXME(bholley): This should probably go away once we harmonize the allocators.
#[no_mangle]
pub extern "C" fn je_malloc_usable_size(_: *const ::libc::c_void) -> ::libc::size_t { 0 }
<commit_msg>stylo: Remove unused macro_use annotation that warns on nightly.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#![deny(warnings)]

extern crate app_units;
extern crate atomic_refcell;
extern crate cssparser;
extern crate env_logger;
extern crate euclid;
extern crate libc;
#[macro_use] extern crate log;
extern crate parking_lot;
extern crate selectors;
extern crate servo_url;
extern crate style;
extern crate style_traits;

#[allow(non_snake_case)]
pub mod glue;
mod stylesheet_loader;

// FIXME(bholley): This should probably go away once we harmonize the allocators.
#[no_mangle]
pub extern "C" fn je_malloc_usable_size(_: *const ::libc::c_void) -> ::libc::size_t { 0 }
<|endoftext|>


<commit_before>fn main() {
    let color = "green";

    // A closure to print `color` which immediately borrows (`&`)
    // `color` and stores the borrow and closure in the `print`
    // variable. It will remain borrowed until `print` goes out of
    // scope. `println!` only requires `by reference` so it doesn't
    // impose anything more restrictive.
    let print = || println!("`color`: {}", color);

    // Call the closure using the borrow.
    print();
    print();

    let mut count = 0;

    // A closure to increment `count` could take either `&mut count`
    // or `count` but `&mut count` is less restrictive so it takes
    // that. Immediately borrows `count`.
    //
    // A `mut` is required on `inc` because a `&mut` is stored inside.
    // Thus, calling the closure mutates the closure which requires
    // a `mut`.
    let mut inc = || {
        count += 1;
        println!("`count`: {}", count);
    };

    // Call the closure.
    inc();
    inc();

    //let reborrow = &mut count;
    // ^ TODO: try uncommenting this line.

    // A non-copy type.
    let movable = Box::new(3);

    // `drop` requires `T` so this must take by value. A copy type
    // would copy into the closure leaving the original untouched.
    // A non-copy must move and so `movable` immediately moves into
    // the closure.
    let consume = || {
        println!("`movable`: {:?}", movable);
        drop(movable);
    };

    // `consume` consumes the variable so this can only be called once.
    consume();
    //consume();
    // ^ TODO: Try uncommenting this line.
}
<commit_msg>Readability update to capture example<commit_after>fn main() {
    use std::mem;

    let color = "green";

    // A closure to print `color` which immediately borrows (`&`)
    // `color` and stores the borrow and closure in the `print`
    // variable. It will remain borrowed until `print` goes out of
    // scope. `println!` only requires `by reference` so it doesn't
    // impose anything more restrictive.
    let print = || println!("`color`: {}", color);

    // Call the closure using the borrow.
    print();
    print();

    let mut count = 0;

    // A closure to increment `count` could take either `&mut count`
    // or `count` but `&mut count` is less restrictive so it takes
    // that. Immediately borrows `count`.
    //
    // A `mut` is required on `inc` because a `&mut` is stored inside.
    // Thus, calling the closure mutates the closure which requires
    // a `mut`.
    let mut inc = || {
        count += 1;
        println!("`count`: {}", count);
    };

    // Call the closure.
    inc();
    inc();

    //let reborrow = &mut count;
    // ^ TODO: try uncommenting this line.

    // A non-copy type.
    let movable = Box::new(3);

    // `mem::drop` requires `T` so this must take by value. A copy type
    // would copy into the closure leaving the original untouched.
    // A non-copy must move and so `movable` immediately moves into
    // the closure.
    let consume = || {
        println!("`movable`: {:?}", movable);
        mem::drop(movable);
    };

    // `consume` consumes the variable so this can only be called once.
    consume();
    //consume();
    // ^ TODO: Try uncommenting this line.
}
<|endoftext|>


<commit_before>//! Utilities for tracking time.
//!
//! This module provides a number of types for executing code after a set period
//! of time.
//!
//! * `Sleep` is a future that does no work and completes at a specific `Instant`
//!   in time.
//!
//! * `Interval` is a stream yielding a value at a fixed period. It is
//!   initialized with a `Duration` and repeatedly yields each time the duration
//!   elapses.
//!
//! * `Timeout`: Wraps a future or stream, setting an upper bound to the amount
//!   of time it is allowed to execute. If the future or stream does not
//!   complete in time, then it is canceled and an error is returned.
//!
//! These types are sufficient for handling a large number of scenarios
//! involving time.
//!
//! These types must be used from within the context of the `Runtime`.
//!
//! # Examples
//!
//! Wait 100ms and print "100 ms have elapsed"
//!
//! ```
//! use tokio::time::sleep;
//!
//! use std::time::Duration;
//!
//!
//! #[tokio::main]
//! async fn main() {
//!     sleep(Duration::from_millis(100)).await;
//!     println!("100 ms have elapsed");
//! }
//! ```
//!
//! Require that an operation takes no more than 300ms.
//!
//! ```
//! use tokio::time::{timeout, Duration};
//!
//! async fn long_future() {
//!     // do work here
//! }
//!
//! # async fn dox() {
//! let res = timeout(Duration::from_secs(1), long_future()).await;
//!
//! if res.is_err() {
//!     println!("operation timed out");
//! }
//! # }
//! ```
//!
//! A simple example using [`interval`] to execute a task every two seconds.
//!
//! The difference between [`interval`] and [`sleep`] is that an
//! [`interval`] measures the time since the last tick, which means that
//! `.tick().await` may wait for a shorter time than the duration specified
//! for the interval if some time has passed between calls to `.tick().await`.
//!
//! If the tick in the example below was replaced with [`sleep`], the task
//! would only be executed once every three seconds, and not every two
//! seconds.
//!
//! ```
//! use tokio::time;
//!
//! async fn task_that_takes_a_second() {
//!     println!("hello");
//!     time::sleep(time::Duration::from_secs(1)).await
//! }
//!
//! #[tokio::main]
//! async fn main() {
//!     let interval = time::interval(time::Duration::from_secs(2));
//!     tokio::pin!(interval);
//!
//!     for _i in 0..5 {
//!         interval.as_mut().tick().await;
//!         task_that_takes_a_second().await;
//!     }
//! }
//! ```
//!
//! [`sleep`]: crate::time::sleep()
//! [`interval`]: crate::time::interval()

mod clock;
pub(crate) use self::clock::Clock;
#[cfg(feature = "test-util")]
pub use clock::{advance, pause, resume};

pub(crate) mod driver;

#[doc(inline)]
pub use driver::sleep::{sleep, sleep_until, Sleep};

pub mod error;

mod instant;
pub use self::instant::Instant;

mod interval;
pub use interval::{interval, interval_at, Interval};

mod timeout;
#[doc(inline)]
pub use timeout::{timeout, timeout_at, Timeout};

#[cfg(test)]
#[cfg(not(loom))]
mod tests;

// Re-export for convenience
#[doc(no_inline)]
pub use std::time::Duration;
<commit_msg>doc: sync interval.rs and time/mod.rs docs (#3533)<commit_after>//! Utilities for tracking time.
//!
//! This module provides a number of types for executing code after a set period
//! of time.
//!
//! * `Sleep` is a future that does no work and completes at a specific `Instant`
//!   in time.
//!
//! * `Interval` is a stream yielding a value at a fixed period. It is
//!   initialized with a `Duration` and repeatedly yields each time the duration
//!   elapses.
//!
//! * `Timeout`: Wraps a future or stream, setting an upper bound to the amount
//!   of time it is allowed to execute. If the future or stream does not
//!   complete in time, then it is canceled and an error is returned.
//!
//! These types are sufficient for handling a large number of scenarios
//! involving time.
//!
//! These types must be used from within the context of the `Runtime`.
//!
//! # Examples
//!
//! Wait 100ms and print "100 ms have elapsed"
//!
//! ```
//! use tokio::time::sleep;
//!
//! use std::time::Duration;
//!
//!
//! #[tokio::main]
//! async fn main() {
//!     sleep(Duration::from_millis(100)).await;
//!     println!("100 ms have elapsed");
//! }
//! ```
//!
//! Require that an operation takes no more than 300ms.
//!
//! ```
//! use tokio::time::{timeout, Duration};
//!
//! async fn long_future() {
//!     // do work here
//! }
//!
//! # async fn dox() {
//! let res = timeout(Duration::from_secs(1), long_future()).await;
//!
//! if res.is_err() {
//!     println!("operation timed out");
//! }
//! # }
//! ```
//!
//! A simple example using [`interval`] to execute a task every two seconds.
//!
//! The difference between [`interval`] and [`sleep`] is that an [`interval`]
//! measures the time since the last tick, which means that `.tick().await`
//! may wait for a shorter time than the duration specified for the interval
//! if some time has passed between calls to `.tick().await`.
//!
//! If the tick in the example below was replaced with [`sleep`], the task
//! would only be executed once every three seconds, and not every two
//! seconds.
//!
//! ```
//! use tokio::time;
//!
//! async fn task_that_takes_a_second() {
//!     println!("hello");
//!     time::sleep(time::Duration::from_secs(1)).await
//! }
//!
//! #[tokio::main]
//! async fn main() {
//!     let mut interval = time::interval(time::Duration::from_secs(2));
//!     for _i in 0..5 {
//!         interval.tick().await;
//!         task_that_takes_a_second().await;
//!     }
//! }
//! ```
//!
//! [`sleep`]: crate::time::sleep()
//! [`interval`]: crate::time::interval()

mod clock;
pub(crate) use self::clock::Clock;
#[cfg(feature = "test-util")]
pub use clock::{advance, pause, resume};

pub(crate) mod driver;

#[doc(inline)]
pub use driver::sleep::{sleep, sleep_until, Sleep};

pub mod error;

mod instant;
pub use self::instant::Instant;

mod interval;
pub use interval::{interval, interval_at, Interval};

mod timeout;
#[doc(inline)]
pub use timeout::{timeout, timeout_at, Timeout};

#[cfg(test)]
#[cfg(not(loom))]
mod tests;

// Re-export for convenience
#[doc(no_inline)]
pub use std::time::Duration;
<|endoftext|>


<commit_before>use std::fmt::Debug;
use std::vec::Vec;

#[derive(Debug)]
pub struct QuadTree<T: Debug> {
    root: Node<T>
}

#[derive(Debug)]
enum Child<T: Sized + Debug> {
    Inner(Box<Node<T>>),
    Leaf(T)
}

impl<T: Debug> Child<T> {
    fn visit(&self) {
        println!("{:?}", self);
        // match self {

        // }
    }
}

#[derive(Debug)]
struct Node<T: Sized + Debug> {
    children: Vec<Child<T>>
}

impl<T: Debug> Node<T> {

    fn new() -> Node<T> {
        return Node {
            children: Vec::with_capacity(4)
        };
    }

    fn visit(&self) {
        for i in 0..4 {
            match self.children.get(i) {
                Some(c) => c.visit(),
                None => println!("None")
            };
        };
    }

    fn add(&mut self, t: T) {
        if self.children.len() < 4 {
            self.children.push(Child::Leaf(t));
        } else {
            match self.children.pop().unwrap() {
                Child::Leaf(old_t) => {
                    let mut new_node = Node::new();
                    new_node.add(t);
                    new_node.add(old_t);
                    self.children.push(Child::Inner(Box::new(new_node)));
                },
                Child::Inner(b) => {

                }
            }
        }

        // if self.children.len() < 1 {

        // } else {
        //     match self.children.pop().unwrap() {
        //         Child::LeafNode(t) => {
        //         },
        //         None => expr,
        //     }

        //     let tmp_t = self.children.pop().unwrap();
        //     let mut new_node = Node::new();
        //     new_node.add(tmp_t);
        //     self.children.push(Child::InnerNode(Box::new(new_node)));
        //     self.children.push(t);
        // }
    }
}

// #[derive(Debug)]
// struct Leaf<T: Sized + Debug> {
//     t: T
// }

impl<T: Debug> QuadTree<T> {
    pub fn new() -> QuadTree<T> {
        return QuadTree { root: Node::new() };
    }

    pub fn visit(&self) {
        println!("{:?}", self.root);
    }

    pub fn add(&mut self, t: T) {
        self.root.add(t);
    }
}

<commit_msg>visit child enum working<commit_after>use std::fmt::Debug;
use std::vec::Vec;
use std::boxed::Box;

#[derive(Debug)]
pub struct QuadTree<T: Debug> {
    root: Node<T>
}

#[derive(Debug)]
enum Child<T: Sized + Debug> {
    Inner(Box<Node<T>>),
    Leaf(T)
}

impl<T: Debug> Child<T> {
    fn visit(&self) {
        match self {
            &Child::Leaf(ref t) => {
                println!("{:?}", t);
            },
            &Child::Inner(ref b) => {
                b.as_ref().visit();
            },
        }
    }
}

#[derive(Debug)]
struct Node<T: Sized + Debug> {
    children: Vec<Child<T>>
}

impl<T: Debug> Node<T> {

    fn new() -> Node<T> {
        return Node {
            children: Vec::with_capacity(4)
        };
    }

    fn visit(&self) {
        for i in 0..4 {
            match self.children.get(i) {
                Some(c) => c.visit(),
                None => println!("None")
            };
        };
    }

    fn add(&mut self, t: T) {
        if self.children.len() < 4 {
            self.children.push(Child::Leaf(t));
        } else {
            match self.children.pop().unwrap() {
                Child::Leaf(old_t) => {
                    let mut new_node = Node::new();
                    new_node.add(t);
                    new_node.add(old_t);
                    self.children.push(Child::Inner(Box::new(new_node)));
                },
                Child::Inner(b) => {

                }
            }
        }
    }
}

impl<T: Debug> QuadTree<T> {
    pub fn new() -> QuadTree<T> {
        return QuadTree { root: Node::new() };
    }

    pub fn visit(&self) {
        // println!("{:?}", self.root);
        self.root.visit();
    }

    pub fn add(&mut self, t: T) {
        self.root.add(t);
    }
}

<|endoftext|>