<commit_before>#![feature(deque_extras)]
#![feature(box_syntax)]
#![feature(plugin)]
#![plugin(peg_syntax_ext)]

extern crate glob;

use std::collections::HashMap;
use std::fs::File;
use std::io::{stdout, Read, Write};
use std::env;
use std::process;
use std::thread;

use self::directory_stack::DirectoryStack;
use self::input_editor::readln;
use self::peg::{parse, Job};
use self::variables::Variables;
use self::history::History;
use self::flow_control::{FlowControl, is_flow_control_command, Statement};
use self::status::{SUCCESS, NO_SUCH_COMMAND, TERMINATED};
use self::function::Function;

pub mod directory_stack;
pub mod to_num;
pub mod input_editor;
pub mod peg;
pub mod variables;
pub mod history;
pub mod flow_control;
pub mod status;
pub mod function;

/// This struct will contain all of the data structures related to this
/// instance of the shell.
pub struct Shell {
    variables: Variables,
    flow_control: FlowControl,
    directory_stack: DirectoryStack,
    history: History,
    functions: HashMap<String, Function>
}

impl Shell {
    /// Panics if DirectoryStack construction fails
    pub fn new() -> Self {
        Shell {
            variables: Variables::new(),
            flow_control: FlowControl::new(),
            directory_stack: DirectoryStack::new().expect(""),
            history: History::new(),
            functions: HashMap::new()
        }
    }

    pub fn print_prompt(&self) {
        self.print_prompt_prefix();
        match self.flow_control.current_statement {
            Statement::For(_, _) => self.print_for_prompt(),
            Statement::Function => self.print_function_prompt(),
            _ => self.print_default_prompt(),
        }
        if let Err(message) = stdout().flush() {
            println!("{}: failed to flush prompt to stdout", message);
        }

    }

    // TODO eventually this thing should be gone
    fn print_prompt_prefix(&self) {
        let prompt_prefix = self.flow_control.modes.iter().rev().fold(String::new(), |acc, mode| {
            acc +
            if mode.value {
                "+ "
            } else {
                "- "
            }
        });
        print!("{}", prompt_prefix);
    }

    fn print_for_prompt(&self) {
        print!("for> ");
    }

    fn print_function_prompt(&self) {
        print!("fn> ");
    }

    fn print_default_prompt(&self) {
        let cwd = env::current_dir().ok().map_or("?".to_string(),
                                                 |ref p| p.to_str().unwrap_or("?").to_string());
        print!("ion:{}# ", cwd);
    }

    fn on_command(&mut self, command_string: &str, commands: &HashMap<&str, Command>) {
        self.history.add(command_string.to_string());

        let mut jobs = parse(command_string);

        // Execute commands
        for job in jobs.drain(..) {
            if self.flow_control.collecting_block {
                // TODO move this logic into "end" command
                if job.command == "end" {
                    self.flow_control.collecting_block = false;
                    let block_jobs: Vec<Job> = self.flow_control
                                                   .current_block
                                                   .jobs
                                                   .drain(..)
                                                   .collect();
                    match self.flow_control.current_statement.clone() {
                        Statement::For(ref var, ref vals) => {
                            let variable = var.clone();
                            let values = vals.clone();
                            for value in values {
                                self.variables.set_var(&variable, &value);
                                for job in block_jobs.iter() {
                                    self.run_job(job, commands);
                                }
                            }
                        },
                        Statement::Function(ref name) => {
                            self.functions.insert(name.clone(), Function { name: name.clone(), jobs: block_jobs.clone() });
                        },
                        _ => {}
                    }
                    self.flow_control.current_statement = Statement::Default;
                } else {
                    self.flow_control.current_block.jobs.push(job);
                }
            } else {
                if self.flow_control.skipping() && !is_flow_control_command(&job.command) {
                    continue;
                }
                self.run_job(&job, commands);
            }
        }
    }

    fn run_job(&mut self, job: &Job, commands: &HashMap<&str, Command>) -> Option<i32> {
        let mut job = self.variables.expand_job(job);
        job.expand_globs();
        let exit_status = if let Some(command) = commands.get(job.command.as_str()) {
            Some((*command.main)(job.args.as_slice(), self))
        } else if self.functions.get(job.command.as_str()).is_some() { // Not really idiomatic but I don't know how to clone the value without borrowing self
            let function = self.functions.get(job.command.as_str()).unwrap().clone();
            let mut return_value = None;
            for function_job in function.jobs.iter() {
                return_value = self.run_job(&function_job, commands)
            }
            return_value
        } else {
            self.run_external_commmand(job)
        };
        if let Some(code) = exit_status {
            self.variables.set_var("?", &code.to_string());
            self.history.previous_status = code;
        }
        exit_status
    }

    /// Returns an exit code if a command was run
    fn run_external_commmand(&mut self, job: Job) -> Option<i32> {
        if job.background {
            thread::spawn(move || {
                let mut command = Shell::build_command(&job);
                command.stdin(process::Stdio::null());
                if let Ok(mut child) = command.spawn() {
                    Shell::wait_and_get_status(&mut child, &job.command);
                }
            });
            None
        } else {
            if let Ok(mut child) = Shell::build_command(&job).spawn() {
                Some(Shell::wait_and_get_status(&mut child, &job.command))
            } else {
                println!("ion: command not found: {}", job.command);
                Some(NO_SUCH_COMMAND)
            }
        }
    }

    fn build_command(job: &Job) -> process::Command {
        let mut command = process::Command::new(&job.command);
        for i in 1..job.args.len() {
            if let Some(arg) = job.args.get(i) {
                command.arg(arg);
            }
        }
        command
    }

    // TODO don't pass in command and do printing outside this function
    fn wait_and_get_status(child: &mut process::Child, command: &str) -> i32 {
        match child.wait() {
            Ok(status) => {
                if let Some(code) = status.code() {
                    code
                } else {
                    println!("{}: child ended by signal", command);
                    TERMINATED
                }
            }
            Err(err) => {
                println!("{}: Failed to wait: {}", command, err);
                100 // TODO what should we return here?
            }
        }
    }

    /// Evaluates the source init file in the user's home directory. If the file does not exist,
    /// the file will be created.
    fn evaluate_init_file(&mut self, commands: &HashMap<&'static str, Command>) {
        let mut source_file = std::env::home_dir().unwrap(); // Obtain home directory
        source_file.push(".ionrc");                          // Location of ion init file

        if let Ok(mut file) = File::open(source_file.clone()) {
            let mut command_list = String::new();
            if let Err(message) = file.read_to_string(&mut command_list) {
                println!("{}: Failed to read {:?}", message, source_file.clone());
            } else {
                self.on_command(&command_list, commands);
            }
        } else {
            if let Err(message) = File::create(source_file) {
                println!("{}", message);
            }
        }
    }

    /// Evaluates the given file and returns 'SUCCESS' if it succeeds.
    fn source_command(&mut self, arguments: &[String]) -> i32 {
        let commands = Command::map();
        match arguments.iter().skip(1).next() {
            Some(argument) => {
                if let Ok(mut file) = File::open(&argument) {
                    let mut command_list = String::new();
                    if let Err(message) = file.read_to_string(&mut command_list) {
                        println!("{}: Failed to read {}", message, argument);
                        return status::FAILURE;
                    } else {
                        self.on_command(&command_list, &commands);
                        return status::SUCCESS;
                    }
                } else {
                    println!("Failed to open {}", argument);
                    return status::FAILURE;
                }
            },
            None => {
                self.evaluate_init_file(&commands);
                return status::SUCCESS;
            },
        }
    }
}

/// Structure which represents a Terminal's command.
/// This command structure contains a name, and the code which run the
/// functionnality associated to this one, with zero, one or several argument(s).
/// # Example
/// ```
/// let my_command = Command {
///     name: "my_command",
///     help: "Describe what my_command does followed by a newline showing usage",
///     main: box|args: &[String], &mut Shell| -> i32 {
///         println!("Say 'hello' to my command! :-D");
///     }
/// }
/// ```
pub struct Command {
    pub name: &'static str,
    pub help: &'static str,
    pub main: Box<Fn(&[String], &mut Shell) -> i32>,
}

impl Command {
    /// Return the map from command names to commands
    pub fn map() -> HashMap<&'static str, Self> {
        let mut commands: HashMap<&str, Self> = HashMap::new();

        commands.insert("cd",
                        Command {
                            name: "cd",
                            help: "Change the current directory\n    cd <path>",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.directory_stack.cd(args)
                            },
                        });

        commands.insert("dirs",
                        Command {
                            name: "dirs",
                            help: "Display the current directory stack",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.directory_stack.dirs(args)
                            },
                        });

        commands.insert("exit",
                        Command {
                            name: "exit",
                            help: "To exit the curent session",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                if let Some(status) = args.get(1) {
                                    if let Ok(status) = status.parse::<i32>() {
                                        process::exit(status);
                                    }
                                }
                                process::exit(shell.history.previous_status);
                            },
                        });

        commands.insert("let",
                        Command {
                            name: "let",
                            help: "View, set or unset variables",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.variables.let_(args)
                            },
                        });

        commands.insert("read",
                        Command {
                            name: "read",
                            help: "Read some variables\n    read <variable>",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.variables.read(args)
                            },
                        });

        commands.insert("pushd",
                        Command {
                            name: "pushd",
                            help: "Push a directory to the stack",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.directory_stack.pushd(args)
                            },
                        });

        commands.insert("popd",
                        Command {
                            name: "popd",
                            help: "Pop a directory from the stack",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.directory_stack.popd(args)
                            },
                        });

        commands.insert("history",
                        Command {
                            name: "history",
                            help: "Display a log of all commands previously executed",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.history.history(args)
                            },
                        });

        commands.insert("if",
                        Command {
                            name: "if",
                            help: "Conditionally execute code",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.flow_control.if_(args)
                            },
                        });

        commands.insert("else",
                        Command {
                            name: "else",
                            help: "Execute code if a previous condition was false",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.flow_control.else_(args)
                            },
                        });

        commands.insert("end",
                        Command {
                            name: "end",
                            help: "End a code block",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.flow_control.end(args)
                            },
                        });

        commands.insert("for",
                        Command {
                            name: "for",
                            help: "Iterate through a list",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.flow_control.for_(args)
                            },
                        });

        commands.insert("source",
                        Command {
                            name: "source",
                            help: "Evaluate the file following the command or re-initialize the init file",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.source_command(args)

                            },
                        });

        commands.insert("fn",
                        Command {
                            name: "fn",
                            help: "Create a function",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.flow_control.fn_(args)
                            },
                        });

        let command_helper: HashMap<&'static str, &'static str> = commands.iter()
                                                                          .map(|(k, v)| {
                                                                              (*k, v.help)
                                                                          })
                                                                          .collect();

        commands.insert("help",
                        Command {
                            name: "help",
                            help: "Display helpful information about a given command, or list \
                                   commands if none specified\n    help <command>",
                            main: box move |args: &[String], _: &mut Shell| -> i32 {
                                if let Some(command) = args.get(1) {
                                    if command_helper.contains_key(command.as_str()) {
                                        match command_helper.get(command.as_str()) {
                                            Some(help) => println!("{}", help),
                                            None => {
                                                println!("Command helper not found [run 'help']...")
                                            }
                                        }
                                    } else {
                                        println!("Command helper not found [run 'help']...");
                                    }
                                } else {
                                    for (command, _help) in command_helper.iter() {
                                        println!("{}", command);
                                    }
                                }
                                SUCCESS
                            },
                        });

        commands
    }
}

fn main() {
    let commands = Command::map();
    let mut shell = Shell::new();
    shell.evaluate_init_file(&commands);

    for arg in env::args().skip(1) {
        let mut command_list = String::new();
        if let Ok(mut file) = File::open(&arg) {
            if let Err(message) = file.read_to_string(&mut command_list) {
                println!("{}: Failed to read {}", message, arg);
            }
        }
        shell.on_command(&command_list, &commands);

        // Exit with the previous command's exit status.
        process::exit(shell.history.previous_status);
    }

    shell.print_prompt();
    while let Some(command) = readln() {
        let command = command.trim();
        if !command.is_empty() {
            shell.on_command(command, &commands);
        }
        shell.print_prompt()
    }

    // Exit with the previous command's exit status.
    process::exit(shell.history.previous_status);
}
<commit_msg>Add dash c<commit_after>#![feature(deque_extras)]
#![feature(box_syntax)]
#![feature(plugin)]
#![plugin(peg_syntax_ext)]

extern crate glob;

use std::collections::HashMap;
use std::fs::File;
use std::io::{stdout, Read, Write};
use std::env;
use std::process;
use std::thread;

use self::directory_stack::DirectoryStack;
use self::input_editor::readln;
use self::peg::{parse, Job};
use self::variables::Variables;
use self::history::History;
use self::flow_control::{FlowControl, is_flow_control_command, Statement};
use self::status::{SUCCESS, NO_SUCH_COMMAND, TERMINATED};
use self::function::Function;

pub mod directory_stack;
pub mod to_num;
pub mod input_editor;
pub mod peg;
pub mod variables;
pub mod history;
pub mod flow_control;
pub mod status;
pub mod function;

/// This struct will contain all of the data structures related to this
/// instance of the shell.
pub struct Shell {
    variables: Variables,
    flow_control: FlowControl,
    directory_stack: DirectoryStack,
    history: History,
    functions: HashMap<String, Function>
}

impl Shell {
    /// Panics if DirectoryStack construction fails
    pub fn new() -> Self {
        Shell {
            variables: Variables::new(),
            flow_control: FlowControl::new(),
            directory_stack: DirectoryStack::new().expect(""),
            history: History::new(),
            functions: HashMap::new()
        }
    }

    pub fn print_prompt(&self) {
        self.print_prompt_prefix();
        match self.flow_control.current_statement {
            Statement::For(_, _) => self.print_for_prompt(),
            Statement::Function => self.print_function_prompt(),
            _ => self.print_default_prompt(),
        }
        if let Err(message) = stdout().flush() {
            println!("{}: failed to flush prompt to stdout", message);
        }

    }

    // TODO eventually this thing should be gone
    fn print_prompt_prefix(&self) {
        let prompt_prefix = self.flow_control.modes.iter().rev().fold(String::new(), |acc, mode| {
            acc +
            if mode.value {
                "+ "
            } else {
                "- "
            }
        });
        print!("{}", prompt_prefix);
    }

    fn print_for_prompt(&self) {
        print!("for> ");
    }

    fn print_function_prompt(&self) {
        print!("fn> ");
    }

    fn print_default_prompt(&self) {
        let cwd = env::current_dir().ok().map_or("?".to_string(),
                                                 |ref p| p.to_str().unwrap_or("?").to_string());
        print!("ion:{}# ", cwd);
    }

    fn on_command(&mut self, command_string: &str, commands: &HashMap<&str, Command>) {
        self.history.add(command_string.to_string());

        let mut jobs = parse(command_string);

        // Execute commands
        for job in jobs.drain(..) {
            if self.flow_control.collecting_block {
                // TODO move this logic into "end" command
                if job.command == "end" {
                    self.flow_control.collecting_block = false;
                    let block_jobs: Vec<Job> = self.flow_control
                                                   .current_block
                                                   .jobs
                                                   .drain(..)
                                                   .collect();
                    match self.flow_control.current_statement.clone() {
                        Statement::For(ref var, ref vals) => {
                            let variable = var.clone();
                            let values = vals.clone();
                            for value in values {
                                self.variables.set_var(&variable, &value);
                                for job in block_jobs.iter() {
                                    self.run_job(job, commands);
                                }
                            }
                        },
                        Statement::Function(ref name) => {
                            self.functions.insert(name.clone(), Function { name: name.clone(), jobs: block_jobs.clone() });
                        },
                        _ => {}
                    }
                    self.flow_control.current_statement = Statement::Default;
                } else {
                    self.flow_control.current_block.jobs.push(job);
                }
            } else {
                if self.flow_control.skipping() && !is_flow_control_command(&job.command) {
                    continue;
                }
                self.run_job(&job, commands);
            }
        }
    }

    fn run_job(&mut self, job: &Job, commands: &HashMap<&str, Command>) -> Option<i32> {
        let mut job = self.variables.expand_job(job);
        job.expand_globs();
        let exit_status = if let Some(command) = commands.get(job.command.as_str()) {
            Some((*command.main)(job.args.as_slice(), self))
        } else if self.functions.get(job.command.as_str()).is_some() { // Not really idiomatic but I don't know how to clone the value without borrowing self
            let function = self.functions.get(job.command.as_str()).unwrap().clone();
            let mut return_value = None;
            for function_job in function.jobs.iter() {
                return_value = self.run_job(&function_job, commands)
            }
            return_value
        } else {
            self.run_external_commmand(job)
        };
        if let Some(code) = exit_status {
            self.variables.set_var("?", &code.to_string());
            self.history.previous_status = code;
        }
        exit_status
    }

    /// Returns an exit code if a command was run
    fn run_external_commmand(&mut self, job: Job) -> Option<i32> {
        if job.background {
            thread::spawn(move || {
                let mut command = Shell::build_command(&job);
                command.stdin(process::Stdio::null());
                if let Ok(mut child) = command.spawn() {
                    Shell::wait_and_get_status(&mut child, &job.command);
                }
            });
            None
        } else {
            if let Ok(mut child) = Shell::build_command(&job).spawn() {
                Some(Shell::wait_and_get_status(&mut child, &job.command))
            } else {
                println!("ion: command not found: {}", job.command);
                Some(NO_SUCH_COMMAND)
            }
        }
    }

    fn build_command(job: &Job) -> process::Command {
        let mut command = process::Command::new(&job.command);
        for i in 1..job.args.len() {
            if let Some(arg) = job.args.get(i) {
                command.arg(arg);
            }
        }
        command
    }

    // TODO don't pass in command and do printing outside this function
    fn wait_and_get_status(child: &mut process::Child, command: &str) -> i32 {
        match child.wait() {
            Ok(status) => {
                if let Some(code) = status.code() {
                    code
                } else {
                    println!("{}: child ended by signal", command);
                    TERMINATED
                }
            }
            Err(err) => {
                println!("{}: Failed to wait: {}", command, err);
                100 // TODO what should we return here?
            }
        }
    }

    /// Evaluates the source init file in the user's home directory. If the file does not exist,
    /// the file will be created.
    fn evaluate_init_file(&mut self, commands: &HashMap<&'static str, Command>) {
        let mut source_file = std::env::home_dir().unwrap(); // Obtain home directory
        source_file.push(".ionrc");                          // Location of ion init file

        if let Ok(mut file) = File::open(source_file.clone()) {
            let mut command_list = String::new();
            if let Err(message) = file.read_to_string(&mut command_list) {
                println!("{}: Failed to read {:?}", message, source_file.clone());
            } else {
                self.on_command(&command_list, commands);
            }
        } else {
            if let Err(message) = File::create(source_file) {
                println!("{}", message);
            }
        }
    }

    /// Evaluates the given file and returns 'SUCCESS' if it succeeds.
    fn source_command(&mut self, arguments: &[String]) -> i32 {
        let commands = Command::map();
        match arguments.iter().skip(1).next() {
            Some(argument) => {
                if let Ok(mut file) = File::open(&argument) {
                    let mut command_list = String::new();
                    if let Err(message) = file.read_to_string(&mut command_list) {
                        println!("{}: Failed to read {}", message, argument);
                        return status::FAILURE;
                    } else {
                        self.on_command(&command_list, &commands);
                        return status::SUCCESS;
                    }
                } else {
                    println!("Failed to open {}", argument);
                    return status::FAILURE;
                }
            },
            None => {
                self.evaluate_init_file(&commands);
                return status::SUCCESS;
            },
        }
    }
}

/// Structure which represents a Terminal's command.
/// This command structure contains a name, and the code which run the
/// functionnality associated to this one, with zero, one or several argument(s).
/// # Example
/// ```
/// let my_command = Command {
///     name: "my_command",
///     help: "Describe what my_command does followed by a newline showing usage",
///     main: box|args: &[String], &mut Shell| -> i32 {
///         println!("Say 'hello' to my command! :-D");
///     }
/// }
/// ```
pub struct Command {
    pub name: &'static str,
    pub help: &'static str,
    pub main: Box<Fn(&[String], &mut Shell) -> i32>,
}

impl Command {
    /// Return the map from command names to commands
    pub fn map() -> HashMap<&'static str, Self> {
        let mut commands: HashMap<&str, Self> = HashMap::new();

        commands.insert("cd",
                        Command {
                            name: "cd",
                            help: "Change the current directory\n    cd <path>",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.directory_stack.cd(args)
                            },
                        });

        commands.insert("dirs",
                        Command {
                            name: "dirs",
                            help: "Display the current directory stack",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.directory_stack.dirs(args)
                            },
                        });

        commands.insert("exit",
                        Command {
                            name: "exit",
                            help: "To exit the curent session",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                if let Some(status) = args.get(1) {
                                    if let Ok(status) = status.parse::<i32>() {
                                        process::exit(status);
                                    }
                                }
                                process::exit(shell.history.previous_status);
                            },
                        });

        commands.insert("let",
                        Command {
                            name: "let",
                            help: "View, set or unset variables",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.variables.let_(args)
                            },
                        });

        commands.insert("read",
                        Command {
                            name: "read",
                            help: "Read some variables\n    read <variable>",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.variables.read(args)
                            },
                        });

        commands.insert("pushd",
                        Command {
                            name: "pushd",
                            help: "Push a directory to the stack",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.directory_stack.pushd(args)
                            },
                        });

        commands.insert("popd",
                        Command {
                            name: "popd",
                            help: "Pop a directory from the stack",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.directory_stack.popd(args)
                            },
                        });

        commands.insert("history",
                        Command {
                            name: "history",
                            help: "Display a log of all commands previously executed",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.history.history(args)
                            },
                        });

        commands.insert("if",
                        Command {
                            name: "if",
                            help: "Conditionally execute code",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.flow_control.if_(args)
                            },
                        });

        commands.insert("else",
                        Command {
                            name: "else",
                            help: "Execute code if a previous condition was false",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.flow_control.else_(args)
                            },
                        });

        commands.insert("end",
                        Command {
                            name: "end",
                            help: "End a code block",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.flow_control.end(args)
                            },
                        });

        commands.insert("for",
                        Command {
                            name: "for",
                            help: "Iterate through a list",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.flow_control.for_(args)
                            },
                        });

        commands.insert("source",
                        Command {
                            name: "source",
                            help: "Evaluate the file following the command or re-initialize the init file",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.source_command(args)

                            },
                        });

        commands.insert("fn",
                        Command {
                            name: "fn",
                            help: "Create a function",
                            main: box |args: &[String], shell: &mut Shell| -> i32 {
                                shell.flow_control.fn_(args)
                            },
                        });

        let command_helper: HashMap<&'static str, &'static str> = commands.iter()
                                                                          .map(|(k, v)| {
                                                                              (*k, v.help)
                                                                          })
                                                                          .collect();

        commands.insert("help",
                        Command {
                            name: "help",
                            help: "Display helpful information about a given command, or list \
                                   commands if none specified\n    help <command>",
                            main: box move |args: &[String], _: &mut Shell| -> i32 {
                                if let Some(command) = args.get(1) {
                                    if command_helper.contains_key(command.as_str()) {
                                        match command_helper.get(command.as_str()) {
                                            Some(help) => println!("{}", help),
                                            None => {
                                                println!("Command helper not found [run 'help']...")
                                            }
                                        }
                                    } else {
                                        println!("Command helper not found [run 'help']...");
                                    }
                                } else {
                                    for (command, _help) in command_helper.iter() {
                                        println!("{}", command);
                                    }
                                }
                                SUCCESS
                            },
                        });

        commands
    }
}

fn main() {
    let commands = Command::map();
    let mut shell = Shell::new();
    shell.evaluate_init_file(&commands);

    let mut dash_c = false;
    for arg in env::args().skip(1) {
        if arg == "-c" {
            dash_c = true;
        } else {
            if dash_c {
                shell.on_command(&arg, &commands);
            } else {
                match File::open(&arg) {
                    Ok(mut file) => {
                        let mut command_list = String::new();
                        match file.read_to_string(&mut command_list) {
                            Ok(_) => shell.on_command(&command_list, &commands),
                            Err(err) => println!("ion: failed to read {}: {}", arg, err)
                        }
                    },
                    Err(err) => println!("ion: failed to open {}: {}", arg, err)
                }
            }

            // Exit with the previous command's exit status.
            process::exit(shell.history.previous_status);
        }
    }

    shell.print_prompt();
    while let Some(command) = readln() {
        let command = command.trim();
        if !command.is_empty() {
            shell.on_command(command, &commands);
        }
        shell.print_prompt()
    }

    // Exit with the previous command's exit status.
    process::exit(shell.history.previous_status);
}
<|endoftext|>


<commit_before><commit_msg>added a glider test<commit_after><|endoftext|>


<commit_before>mod css;
mod dom;
mod html;
mod style;

fn main() {
    let root_node = html::parse("
Hello there
".to_string());
    println!("{}\n", root_node);

    let stylesheet = css::parse("div, *, span#foo.bar { display: block; height: 1px; }".to_string());
    println!("{}\n", stylesheet);

    let style_tree = style::style_tree(&root_node, &stylesheet);
    println!("{}\n", style_tree);
}
<commit_msg>Add command-line args and file input<commit_after>extern crate getopts;

use getopts::{optopt,getopts};
use std::os::args;
use std::io::fs::File;

mod css;
mod dom;
mod html;
mod style;

fn main() {
    // Parse command-line options:
    let opts = [
        optopt("h", "html", "HTML document", "FILENAME"),
        optopt("c", "css", "CSS stylesheet", "FILENAME"),
    ];
    let matches = match getopts(args().tail(), opts) {
        Ok(m) => m,
        Err(f) => fail!(f.to_string())
    };

    // Read input files:
    let read_source = |arg_filename: Option<String>, default_filename: &str| {
        let path = match arg_filename {
            Some(ref filename) => filename.as_slice(),
            None => default_filename,
        };
        File::open(&Path::new(path)).read_to_string().unwrap()
    };
    let html = read_source(matches.opt_str("h"), "examples/test.html");
    let css  = read_source(matches.opt_str("c"), "examples/test.css");

    // Parsing and rendering:
    let root_node = html::parse(html);
    let stylesheet = css::parse(css);
    let style_tree = style::style_tree(&root_node, &stylesheet);

    // Debug output:
    println!("{}\n", style_tree);
}
<|endoftext|>


<commit_before>use std::iter::FromIterator;

use serde::{
    Deserialize,
    Serialize,
};

use thiserror::Error;

use rnc_core::{
    urs,
    urs_taxid,
};

use crate::normalize::utils;

use crate::normalize::ds::{
    accession::{
        AccessionVec,
        CrossReference,
        RawAccession,
        ReferenceVec,
    },
    basic::Basic,
    crs::{
        Crs,
        CrsVec,
    },
    feedback::{
        Feedback,
        FeedbackVec,
    },
    go_annotation::GoAnnotation,
    interacting_protein::{
        InteractingProtein,
        InteractingProteinVec,
    },
    interacting_rna::{
        InteractingRna,
        InteractingRnaVec,
    },
    precompute::{
        Precompute,
        PrecomputeSummary,
    },
    qa_status::QaStatus,
    r2dt::R2dt,
    rfam_hit::{
        RfamHit,
        RfamHitVec,
    },
    so_tree,
};

#[derive(Error, Debug)]
pub enum NormalizationError {
    #[error("Could not ungroup {0}")]
    CountError(#[from] utils::Error),

    #[error("Could not parse {0}")]
    UrsParsingError(#[from] urs::Error),

    #[error("Could not parse {0}")]
    UrsTaxidParsingError(#[from] urs_taxid::Error),
}

#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Raw {
    pub id: usize,
    pub base: Basic,
    pub crs: Vec<Crs>,
    pub feedback: Vec<Feedback>,
    pub go_annotations: Vec<GoAnnotation>,
    pub interacting_proteins: Vec<InteractingProtein>,
    pub interacting_rnas: Vec<InteractingRna>,
    pub precompute: Precompute,
    pub qa_status: QaStatus,
    pub r2dt: Option<R2dt>,
    pub rfam_hits: Vec<RfamHit>,
    pub so_tree: so_tree::SoTree,
}

#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct Normalized {
    urs: String,
    taxid: usize,
    urs_taxid: String,
    short_urs: String,
    deleted: String,

    so_rna_type_tree: so_tree::SoTree,

    #[serde(flatten)]
    pre_summary: PrecomputeSummary,

    #[serde(flatten)]
    basic: Basic,

    // #[serde(flatten)]
    // dates: Dates,
    qa_status: QaStatus,
    secondary_structure: Option<R2dt>,

    accessions: AccessionVec,
    cross_references: Vec<CrossReference>,
    crs: CrsVec,
    feedback: FeedbackVec,
    go_annotations: Vec<GoAnnotation>,
    interacting_proteins: InteractingProteinVec,
    interacting_rnas: InteractingRnaVec,
    references: ReferenceVec,
    rfam_hits: RfamHitVec,
}

impl Raw {
    pub fn urs_taxid(&self) -> String {
        return self.base.urs_taxid.to_owned();
    }

    pub fn urs(&self) -> Result<String, urs_taxid::Error> {
        let ut: urs_taxid::UrsTaxid = self.urs_taxid().parse()?;
        let urs: urs::Urs = ut.into();
        Ok(urs.to_string())
    }

    pub fn taxid(&self) -> Result<u64, urs_taxid::Error> {
        let ut: urs_taxid::UrsTaxid = self.urs_taxid().parse()?;
        Ok(ut.taxid())
    }

    pub fn short_urs(&self) -> Result<String, urs_taxid::Error> {
        let ut: urs_taxid::UrsTaxid = self.urs_taxid().parse()?;
        let urs: urs::Urs = ut.into();
        Ok(urs.short_urs())
    }

    pub fn short_urs_taxid(&self) -> Result<String, urs_taxid::Error> {
        let ut: urs_taxid::UrsTaxid = self.urs_taxid().parse()?;
        Ok(ut.short())
    }
}

impl Normalized {
    pub fn new(
        raw: Raw,
        accessions: Vec<RawAccession>,
    ) -> Result<Self, NormalizationError> {
        let pre_summary = PrecomputeSummary::from(raw.precompute);
        let base = raw.base.clone();

        let urs_taxid = base.urs_taxid.to_owned();
        assert!(urs_taxid == accessions[0].urs_taxid);
        let parts: Vec<&str> = urs_taxid.split("_").collect();
        let urs = parts[0].to_owned();
        let taxid = parts[1].parse::<usize>().unwrap();
        let parsed: urs_taxid::UrsTaxid = urs_taxid.parse()?;
        let references = ReferenceVec::from_iter(accessions.clone());

        Ok(Self {
            urs_taxid,
            urs,
            taxid,
            short_urs: parsed.short(),
            deleted: String::from("N"),

            so_rna_type_tree: raw.so_tree,

            pre_summary,
            basic: base,
            qa_status: raw.qa_status,
            secondary_structure: raw.r2dt.into(),

            accessions: AccessionVec::from_iter(accessions.clone()),
            cross_references: accessions.into_iter().map(CrossReference::from).collect(),
            crs: CrsVec::from_iter(raw.crs.clone()),
            feedback: FeedbackVec::from_iter(raw.feedback.clone()),
            go_annotations: raw.go_annotations.clone(),
            interacting_proteins: InteractingProteinVec::from_iter(
                raw.interacting_proteins.clone(),
            ),
            interacting_rnas: InteractingRnaVec::from_iter(raw.interacting_rnas.clone()),
            references,
            rfam_hits: RfamHitVec::from_iter(raw.rfam_hits.clone()),
        })
    }
}
<commit_msg>Fix data schema<commit_after>use std::iter::FromIterator;

use serde::{
    Deserialize,
    Serialize,
};

use thiserror::Error;

use rnc_core::{
    urs,
    urs_taxid,
};

use crate::normalize::utils;

use crate::normalize::ds::{
    accession::{
        AccessionVec,
        CrossReference,
        RawAccession,
        ReferenceVec,
    },
    basic::Basic,
    crs::{
        Crs,
        CrsVec,
    },
    feedback::{
        Feedback,
        FeedbackVec,
    },
    go_annotation::GoAnnotation,
    interacting_protein::InteractingProtein,
    interacting_rna::InteractingRna,
    precompute::{
        Precompute,
        PrecomputeSummary,
    },
    qa_status::QaStatus,
    r2dt::R2dt,
    rfam_hit::{
        RfamHit,
        RfamHitVec,
    },
    so_tree,
};

#[derive(Error, Debug)]
pub enum NormalizationError {
    #[error("Could not ungroup {0}")]
    CountError(#[from] utils::Error),

    #[error("Could not parse {0}")]
    UrsParsingError(#[from] urs::Error),

    #[error("Could not parse {0}")]
    UrsTaxidParsingError(#[from] urs_taxid::Error),
}

#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Raw {
    pub id: usize,
    pub base: Basic,
    pub crs: Vec<Crs>,
    pub feedback: Vec<Feedback>,
    pub go_annotations: Vec<GoAnnotation>,
    pub interacting_proteins: Vec<InteractingProtein>,
    pub interacting_rnas: Vec<InteractingRna>,
    pub precompute: Precompute,
    pub qa_status: QaStatus,
    pub r2dt: Option<R2dt>,
    pub rfam_hits: Vec<RfamHit>,
    pub so_tree: so_tree::SoTree,
}

#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct Normalized {
    urs: String,
    taxid: usize,
    urs_taxid: String,
    short_urs: String,
    deleted: String,

    so_rna_type_tree: so_tree::SoTree,

    #[serde(flatten)]
    pre_summary: PrecomputeSummary,

    #[serde(flatten)]
    basic: Basic,

    // #[serde(flatten)]
    // dates: Dates,
    qa_status: QaStatus,

    secondary: Option<R2dt>,

    #[serde(flatten)]
    accessions: AccessionVec,
    cross_references: Vec<CrossReference>,
    crs: CrsVec,
    overlaps: FeedbackVec,
    go_annotations: Vec<GoAnnotation>,

    interacting_proteins: Vec<InteractingProtein>,

    interacting_rnas: Vec<InteractingRna>,

    #[serde(flatten)]
    references: ReferenceVec,

    #[serde(flatten)]
    rfam_hits: RfamHitVec,
}

impl Raw {
    pub fn urs_taxid(&self) -> String {
        return self.base.urs_taxid.to_owned();
    }

    pub fn urs(&self) -> Result<String, urs_taxid::Error> {
        let ut: urs_taxid::UrsTaxid = self.urs_taxid().parse()?;
        let urs: urs::Urs = ut.into();
        Ok(urs.to_string())
    }

    pub fn taxid(&self) -> Result<u64, urs_taxid::Error> {
        let ut: urs_taxid::UrsTaxid = self.urs_taxid().parse()?;
        Ok(ut.taxid())
    }

    pub fn short_urs(&self) -> Result<String, urs_taxid::Error> {
        let ut: urs_taxid::UrsTaxid = self.urs_taxid().parse()?;
        let urs: urs::Urs = ut.into();
        Ok(urs.short_urs())
    }

    pub fn short_urs_taxid(&self) -> Result<String, urs_taxid::Error> {
        let ut: urs_taxid::UrsTaxid = self.urs_taxid().parse()?;
        Ok(ut.short())
    }
}

impl Normalized {
    pub fn new(raw: Raw, accessions: Vec<RawAccession>) -> Result<Self, NormalizationError> {
        let pre_summary = PrecomputeSummary::from(raw.precompute);
        let base = raw.base.clone();

        let urs_taxid = base.urs_taxid.to_owned();
        assert!(urs_taxid == accessions[0].urs_taxid);
        let parts: Vec<&str> = urs_taxid.split("_").collect();
        let urs = parts[0].to_owned();
        let taxid = parts[1].parse::<usize>().unwrap();
        let parsed: urs_taxid::UrsTaxid = urs_taxid.parse()?;
        let references = ReferenceVec::from_iter(accessions.clone());

        Ok(Self {
            urs_taxid,
            urs,
            taxid,
            short_urs: parsed.short(),
            deleted: String::from("N"),

            so_rna_type_tree: raw.so_tree,

            pre_summary,
            basic: base,
            qa_status: raw.qa_status,
            secondary: raw.r2dt,

            accessions: AccessionVec::from_iter(accessions.clone()),
            cross_references: accessions.into_iter().map(CrossReference::from).collect(),
            crs: CrsVec::from_iter(raw.crs.clone()),
            overlaps: FeedbackVec::from_iter(raw.feedback.clone()),
            go_annotations: raw.go_annotations.clone(),
            interacting_proteins: raw.interacting_proteins,
            interacting_rnas: raw.interacting_rnas,
            references,
            rfam_hits: RfamHitVec::from_iter(raw.rfam_hits.clone()),
        })
    }
}
<|endoftext|>


<commit_before><commit_msg>basic algorithm defined<commit_after>extern crate nalgebra as na;
#[allow(unused_imports)]
use na::{Vector,Dim,Real,Vector4,Vector3,Vector2,U1,Matrix,DVector,Dynamic,VecStorage};
use na::storage::{Storage};
use std::cmp;

// evum CovvolveMode{
//     Full,
//     Valid,
//     Same
// }

#[allow(non_snake_case)]
fn Convolve1D<R: Real, D: Dim, E: Dim, S: Storage<R, D>, Q: Storage<R, E>>(
    Vector : Vector<R,D,S>,
    Kernel : Vector<R,E,Q>
    ) -> Matrix<R, Dynamic, U1, VecStorage<R, Dynamic, U1>>
    {
        //
        // Vector is the vector, Kervel is the kervel
        // C is the returv vector
        //
        if Kernel.len() > Vector.len(){
            return Convolve1D(Kernel, Vector);
        }

        let V = Vector.len();
        let K = Kernel.len();
        let L = V + K - 1;
        let v = V as i8;
        let k = K as i8;
        let l = L as i8;
        let mut C = DVector::<R>::zeros(L);

        for i in 0..l{
            let u_i = cmp::max(0, i - k);
            let u_f = cmp::min(i, v - 1);
            if u_i == u_f{
                C[i as usize] += Vector[u_i as usize] * Kernel[(i - u_i) as usize];
            }
            else{
                for u in u_i..(u_f+1){
                    if i - u < k{
                        C[i as usize] += Vector[u as usize] * Kernel[(i - u ) as usize];
                    }
                }
            }
        }
        C
    }

fn main() {
    let v1 = Vector2::new(3.0,3.0);
    let v2 = Vector4::new(1.0,2.0,5.0,9.0);
    let x = Convolve1D(v1,v2);
    println!("{:?}",x)
}<|endoftext|>


<commit_before><commit_msg>Adapt flag forwarding to new runtime flags<commit_after><|endoftext|>


<commit_before><commit_msg>Add ARM decode for coprocessor instructions<commit_after><|endoftext|>


<commit_before><commit_msg>updated to check/remove dirty file<commit_after><|endoftext|>


<commit_before><commit_msg>Update per collections renaming<commit_after><|endoftext|>


<commit_before><commit_msg>Enabling Microsoft Bitmap Version 4 as valid bitmap version.<commit_after><|endoftext|>


<commit_before><commit_msg>num-macros: port from ast::VariantKind to ast::VariantData<commit_after><|endoftext|>


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

// Just check if we don't get an ICE for the _S type.

use std::cell::Cell;
use std::mem;

pub struct S {
    s: Cell<usize>
}

pub type _S = [usize; 0 - (mem::size_of::<S>() != 4) as usize];
<commit_msg>Update rustdoc test<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.

// Just check if we don't get an ICE for the _S type.

use std::cell::Cell;
use std::mem;

pub struct S {
    s: Cell<usize>
}

pub const N: usize = 0 - (mem::size_of::<S>() != 4) as usize;
<|endoftext|>


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

// compile-flags: -Z identify_regions -Z span_free_formats
// ignore-tidy-linelength

// Regression test for #43457: an `EndRegion` was missing from output
// because compiler was using a faulty means for region map lookup.

use std::cell::RefCell;

fn rc_refcell_test(r: RefCell<i32>) {
    r.borrow_mut();
}

fn main() { }

// END RUST SOURCE
// START rustc.node5.SimplifyCfg-qualify-consts.after.mir
//
// fn rc_refcell_test(_1: std::cell::RefCell<i32>) -> () {
//     let mut _0: ();
//     scope 1 {
//         let _2: std::cell::RefCell<i32>;
//     }
//     let mut _3: std::cell::RefMut<'17dce, i32>;
//     let mut _4: &'17dce std::cell::RefCell<i32>;
//
//     bb0: {
//         StorageLive(_2);
//         _2 = _1;
//         StorageLive(_4);
//         _4 = &'17dce _2;
//         _3 = const <std::cell::RefCell<T>>::borrow_mut(_4) -> bb1;
//     }
//
//     bb1: {
//         drop(_3) -> bb2;
//     }
//
//     bb2: {
//         StorageDead(_4);
//         EndRegion('17dce);
//         _0 = ();
//         StorageDead(_2);
//         return;
//     }
// }
<|endoftext|>


<commit_before><commit_msg>access: print error on decrypt/decode failure<commit_after><|endoftext|>


<commit_before><commit_msg>Add scroll example<commit_after>extern crate cursive;

use cursive::traits::Boxable;
use cursive::views::{Canvas, Dialog, ScrollView, LinearLayout, Button};
use cursive::Printer;

fn main() {
    let mut siv = cursive::Cursive::default();

    siv.add_layer(Dialog::around(
            ScrollView::new(
                LinearLayout::vertical()
                .child(Button::new("Foo", |s| s.add_layer(Dialog::info("Ah"))))
                .child(Canvas::new(()).with_draw(draw).fixed_size((120, 40)))
                .child(Button::new("Bar", |s| s.add_layer(Dialog::info("Uh"))))
                ).scroll_x(true),
            ).fixed_size((60, 30)));

    siv.add_global_callback('q', |s| s.quit());

    siv.run();
}

fn draw(_: &(), p: &Printer) {
    for x in 0..p.size.x {
        for y in 0..p.size.y {
            let c = (x + 6*y) % 10;
            p.print((x, y), &format!("{}", c));
        }
    }
}
<|endoftext|>


<commit_before>extern crate glutin;
#[macro_use]
extern crate glium;

use glium::{Texture, Surface};

mod support;

#[test]
fn texture_1d_creation() {
    let display = support::build_display();

    let texture = glium::texture::Texture1d::new(&display, vec![
        (0, 0, 0, 0),
        (0, 0, 0, 0),
        (0, 0, 0, 0u8),
    ]);

    assert_eq!(texture.get_width(), 3);
    assert_eq!(texture.get_height(), None);
    assert_eq!(texture.get_depth(), None);
    assert_eq!(texture.get_array_size(), None);

    display.assert_no_error();
}

#[test]
fn empty_texture1d_u8u8u8u8() {
    let display = support::build_display();

    let texture = glium::texture::Texture1d::new_empty(&display,
                                                       glium::texture::UncompressedFloatFormat::
                                                           U8U8U8U8, 128);

    display.assert_no_error();
    drop(texture);
    display.assert_no_error();
}

#[test]
fn depth_texture_1d_creation() {
    let display = support::build_display();

    let texture = match glium::texture::DepthTexture1d::new_if_supported(&display, vec![0.0, 0.0, 0.0, 0.0f32]) {
        None => return,
        Some(t) => t
    };

    assert_eq!(texture.get_width(), 4);
    assert_eq!(texture.get_height(), None);
    assert_eq!(texture.get_depth(), None);
    assert_eq!(texture.get_array_size(), None);

    display.assert_no_error();
}

#[test]
fn texture_2d_creation() {
    let display = support::build_display();

    let texture = glium::texture::Texture2d::new(&display, vec![
        vec![(0, 0, 0, 0), (0, 0, 0, 0)],
        vec![(0, 0, 0, 0), (0, 0, 0, 0)],
        vec![(0, 0, 0, 0), (0, 0, 0, 0u8)],
    ]);

    assert_eq!(texture.get_width(), 2);
    assert_eq!(texture.get_height(), Some(3));
    assert_eq!(texture.get_depth(), None);
    assert_eq!(texture.get_array_size(), None);

    display.assert_no_error();
}

#[test]
fn empty_texture2d_u8u8u8u8() {
    let display = support::build_display();

    let texture = glium::texture::Texture2d::new_empty(&display,
                                                       glium::texture::UncompressedFloatFormat::
                                                           U8U8U8U8,
                                                       128, 128);

    display.assert_no_error();
    drop(texture);
    display.assert_no_error();
}

#[test]
fn depth_texture_2d_creation() {
    let display = support::build_display();

    let texture = glium::texture::DepthTexture2d::new_if_supported(&display, vec![
        vec![0.0, 0.0, 0.0, 0.0f32],
        vec![0.0, 0.0, 0.0, 0.0f32],
        vec![0.0, 0.0, 0.0, 0.0f32],
    ]);

    let texture = match texture {
        None => return,
        Some(t) => t
    };

    assert_eq!(texture.get_width(), 4);
    assert_eq!(texture.get_height(), Some(3));
    assert_eq!(texture.get_depth(), None);
    assert_eq!(texture.get_array_size(), None);

    display.assert_no_error();
}

#[test]
#[ignore]   // `thread 'empty_depth_texture2d_f32' panicked at 'assertion failed: version >= &GlVersion(3, 0)'`
fn empty_depth_texture2d_f32() {
    let display = support::build_display();

    let texture = glium::texture::DepthTexture2d::new_empty(&display,
                                                            glium::texture::DepthFormat::F32,
                                                            128, 128);

    display.assert_no_error();
    drop(texture);
    display.assert_no_error();
}

#[test]
fn texture_3d_creation() {
    let display = support::build_display();

    let texture = glium::texture::Texture3d::new(&display, vec![
        vec![
            vec![(0, 0, 0, 0)],
            vec![(0, 0, 0, 0)],
        ],
        vec![
            vec![(0, 0, 0, 0)],
            vec![(0, 0, 0, 0)],
        ],
        vec![
            vec![(0, 0, 0, 0)],
            vec![(0, 0, 0, 0u8)],
        ],
    ]);

    assert_eq!(texture.get_width(), 1);
    assert_eq!(texture.get_height(), Some(2));
    assert_eq!(texture.get_depth(), Some(3));
    assert_eq!(texture.get_array_size(), None);

    display.assert_no_error();
}

#[test]
fn compressed_texture_2d_creation() {
    let display = support::build_display();

    let texture = glium::texture::CompressedTexture2d::new(&display, vec![
        vec![(0, 0, 0, 0), (0, 0, 0, 0)],
        vec![(0, 0, 0, 0), (0, 0, 0, 0)],
        vec![(0, 0, 0, 0), (0, 0, 0, 0u8)],
    ]);

    assert_eq!(texture.get_width(), 2);
    assert_eq!(texture.get_height(), Some(3));
    assert_eq!(texture.get_depth(), None);
    assert_eq!(texture.get_array_size(), None);

    display.assert_no_error();
}

macro_rules! empty_texture_test {
    ($test_name:ident, $tex_ty:ident, [$($dims:expr),+],
     $w:expr, $h:expr, $d:expr, $s:expr) =>
    (
        #[test]
        fn $test_name() {
            let display = support::build_display();

            let texture = glium::texture::$tex_ty::empty(&display, $($dims),+);

            assert_eq!(texture.get_width(), $w);
            assert_eq!(texture.get_height(), $h);
            assert_eq!(texture.get_depth(), $d);
            assert_eq!(texture.get_array_size(), $s);

            assert_eq!(texture.get_mipmap_levels(), 1);

            display.assert_no_error();
            drop(texture);
            display.assert_no_error();
        }
    );

    ($test_name:ident, maybe $tex_ty:ident, [$($dims:expr),+],
     $w:expr, $h:expr, $d:expr, $s:expr) =>
    (
        #[test]
        fn $test_name() {
            let display = support::build_display();

            let texture = match glium::texture::$tex_ty::empty_if_supported(&display, $($dims),+) {
                None => return,
                Some(t) => t
            };

            assert_eq!(texture.get_width(), $w);
            assert_eq!(texture.get_height(), $h);
            assert_eq!(texture.get_depth(), $d);
            assert_eq!(texture.get_array_size(), $s);

            assert_eq!(texture.get_mipmap_levels(), 1);

            display.assert_no_error();
            drop(texture);
            display.assert_no_error();
        }
    );
}

// TODO: compressed textures don't have "empty" yet
/*empty_texture_test!(empty_compressedtexture1d, CompressedTexture1d, [64], 64, None, None, None);
empty_texture_test!(empty_compressedtexture1darray, CompressedTexture1dArray, [64, 32], 64, None, None, Some(32));
empty_texture_test!(empty_compressedtexture2d, CompressedTexture2d, [64, 32], 64, Some(32), None, None);
empty_texture_test!(empty_compressedtexture2darray, CompressedTexture2dArray, [64, 32, 16], 64, Some(32), None, Some(16));
empty_texture_test!(empty_compressedtexture3d, CompressedTexture3d, [64, 32, 16], 64, Some(32), Some(16), None);*/
empty_texture_test!(empty_depthstenciltexture1d, maybe DepthStencilTexture1d, [64], 64, None, None, None);
empty_texture_test!(empty_depthstenciltexture1darray, maybe DepthStencilTexture1dArray, [64, 32], 64, None, None, Some(32));
empty_texture_test!(empty_depthstenciltexture2d, maybe DepthStencilTexture2d, [64, 32], 64, Some(32), None, None);
empty_texture_test!(empty_depthstenciltexture2darray, maybe DepthStencilTexture2dArray, [64, 32, 16], 64, Some(32), None, Some(16));
// TODO: non-working
//empty_texture_test!(empty_depthstenciltexture3d, DepthStencilTexture3d, [64, 32, 16], 64, Some(32), Some(16), None);
empty_texture_test!(empty_depthtexture1d, maybe DepthTexture1d, [64], 64, None, None, None);
empty_texture_test!(empty_depthtexture1darray, maybe DepthTexture1dArray, [64, 32], 64, None, None, Some(32));
empty_texture_test!(empty_depthtexture2d, maybe DepthTexture2d, [64, 32], 64, Some(32), None, None);
empty_texture_test!(empty_depthtexture2darray, maybe DepthTexture2dArray, [64, 32, 16], 64, Some(32), None, Some(16));
// TODO: non-working
//empty_texture_test!(empty_depthtexture3d, DepthTexture3d, [64, 32, 16], 64, Some(32), Some(16), None);
empty_texture_test!(empty_integraltexture1d, maybe IntegralTexture1d, [64], 64, None, None, None);
empty_texture_test!(empty_integraltexture1darray,maybe  IntegralTexture1dArray, [64, 32], 64, None, None, Some(32));
empty_texture_test!(empty_integraltexture2d, maybe IntegralTexture2d, [64, 32], 64, Some(32), None, None);
empty_texture_test!(empty_integraltexture2darray, maybe IntegralTexture2dArray, [64, 32, 16], 64, Some(32), None, Some(16));
empty_texture_test!(empty_integraltexture3d, maybe IntegralTexture3d, [64, 32, 16], 64, Some(32), Some(16), None);
empty_texture_test!(empty_stenciltexture1d, maybe StencilTexture1d, [64], 64, None, None, None);
empty_texture_test!(empty_stenciltexture1darray, maybe StencilTexture1dArray, [64, 32], 64, None, None, Some(32));
empty_texture_test!(empty_stenciltexture2d, maybe StencilTexture2d, [64, 32], 64, Some(32), None, None);
empty_texture_test!(empty_stenciltexture2darray, maybe StencilTexture2dArray, [64, 32, 16], 64, Some(32), None, Some(16));
empty_texture_test!(empty_stenciltexture3d, maybe StencilTexture3d, [64, 32, 16], 64, Some(32), Some(16), None);
empty_texture_test!(empty_texture1d, Texture1d, [64], 64, None, None, None);
empty_texture_test!(empty_texture1darray, Texture1dArray, [64, 32], 64, None, None, Some(32));
empty_texture_test!(empty_texture2d, Texture2d, [64, 32], 64, Some(32), None, None);
empty_texture_test!(empty_texture2darray, Texture2dArray, [64, 32, 16], 64, Some(32), None, Some(16));
empty_texture_test!(empty_texture3d, Texture3d, [64, 32, 16], 64, Some(32), Some(16), None);
empty_texture_test!(empty_unsignedtexture1d, maybe UnsignedTexture1d, [64], 64, None, None, None);
empty_texture_test!(empty_unsignedtexture1darray, maybe UnsignedTexture1dArray, [64, 32], 64, None, None, Some(32));
empty_texture_test!(empty_unsignedtexture2d, maybe UnsignedTexture2d, [64, 32], 64, Some(32), None, None);
empty_texture_test!(empty_unsignedtexture2darray, maybe UnsignedTexture2dArray, [64, 32, 16], 64, Some(32), None, Some(16));
empty_texture_test!(empty_unsignedtexture3d, maybe UnsignedTexture3d, [64, 32, 16], 64, Some(32), Some(16), None);
<commit_msg>Fix texture creation tests<commit_after>extern crate glutin;
#[macro_use]
extern crate glium;

use glium::{Texture, Surface};

mod support;

#[test]
fn empty_texture1d_u8u8u8u8() {
    let display = support::build_display();

    let texture = glium::texture::Texture1d::new_empty(&display,
                                                       glium::texture::UncompressedFloatFormat::
                                                           U8U8U8U8, 128);

    display.assert_no_error();
    drop(texture);
    display.assert_no_error();
}

#[test]
fn depth_texture_1d_creation() {
    let display = support::build_display();

    let texture = match glium::texture::DepthTexture1d::new_if_supported(&display, vec![0.0, 0.0, 0.0, 0.0f32]) {
        None => return,
        Some(t) => t
    };

    assert_eq!(texture.get_width(), 4);
    assert_eq!(texture.get_height(), None);
    assert_eq!(texture.get_depth(), None);
    assert_eq!(texture.get_array_size(), None);

    display.assert_no_error();
}

#[test]
fn texture_2d_creation() {
    let display = support::build_display();

    let texture = glium::texture::Texture2d::new(&display, vec![
        vec![(0, 0, 0, 0), (0, 0, 0, 0)],
        vec![(0, 0, 0, 0), (0, 0, 0, 0)],
        vec![(0, 0, 0, 0), (0, 0, 0, 0u8)],
    ]);

    assert_eq!(texture.get_width(), 2);
    assert_eq!(texture.get_height(), Some(3));
    assert_eq!(texture.get_depth(), None);
    assert_eq!(texture.get_array_size(), None);

    display.assert_no_error();
}

#[test]
fn empty_texture2d_u8u8u8u8() {
    let display = support::build_display();

    let texture = glium::texture::Texture2d::new_empty(&display,
                                                       glium::texture::UncompressedFloatFormat::
                                                           U8U8U8U8,
                                                       128, 128);

    display.assert_no_error();
    drop(texture);
    display.assert_no_error();
}

#[test]
fn depth_texture_2d_creation() {
    let display = support::build_display();

    let texture = glium::texture::DepthTexture2d::new_if_supported(&display, vec![
        vec![0.0, 0.0, 0.0, 0.0f32],
        vec![0.0, 0.0, 0.0, 0.0f32],
        vec![0.0, 0.0, 0.0, 0.0f32],
    ]);

    let texture = match texture {
        None => return,
        Some(t) => t
    };

    assert_eq!(texture.get_width(), 4);
    assert_eq!(texture.get_height(), Some(3));
    assert_eq!(texture.get_depth(), None);
    assert_eq!(texture.get_array_size(), None);

    display.assert_no_error();
}

#[test]
#[ignore]   // `thread 'empty_depth_texture2d_f32' panicked at 'assertion failed: version >= &GlVersion(3, 0)'`
fn empty_depth_texture2d_f32() {
    let display = support::build_display();

    let texture = glium::texture::DepthTexture2d::new_empty(&display,
                                                            glium::texture::DepthFormat::F32,
                                                            128, 128);

    display.assert_no_error();
    drop(texture);
    display.assert_no_error();
}

#[test]
fn compressed_texture_2d_creation() {
    let display = support::build_display();

    let texture = glium::texture::CompressedTexture2d::new(&display, vec![
        vec![(0, 0, 0, 0), (0, 0, 0, 0)],
        vec![(0, 0, 0, 0), (0, 0, 0, 0)],
        vec![(0, 0, 0, 0), (0, 0, 0, 0u8)],
    ]);

    assert_eq!(texture.get_width(), 2);
    assert_eq!(texture.get_height(), Some(3));
    assert_eq!(texture.get_depth(), None);
    assert_eq!(texture.get_array_size(), None);

    display.assert_no_error();
}

macro_rules! empty_texture_test {
    ($test_name:ident, $tex_ty:ident, [$($dims:expr),+],
     $w:expr, $h:expr, $d:expr, $s:expr) =>
    (
        #[test]
        fn $test_name() {
            let display = support::build_display();

            let texture = glium::texture::$tex_ty::empty(&display, $($dims),+);

            assert_eq!(texture.get_width(), $w);
            assert_eq!(texture.get_height(), $h);
            assert_eq!(texture.get_depth(), $d);
            assert_eq!(texture.get_array_size(), $s);

            assert_eq!(texture.get_mipmap_levels(), 1);

            display.assert_no_error();
            drop(texture);
            display.assert_no_error();
        }
    );

    ($test_name:ident, maybe $tex_ty:ident, [$($dims:expr),+],
     $w:expr, $h:expr, $d:expr, $s:expr) =>
    (
        #[test]
        fn $test_name() {
            let display = support::build_display();

            let texture = match glium::texture::$tex_ty::empty_if_supported(&display, $($dims),+) {
                None => return,
                Some(t) => t
            };

            assert_eq!(texture.get_width(), $w);
            assert_eq!(texture.get_height(), $h);
            assert_eq!(texture.get_depth(), $d);
            assert_eq!(texture.get_array_size(), $s);

            assert_eq!(texture.get_mipmap_levels(), 1);

            display.assert_no_error();
            drop(texture);
            display.assert_no_error();
        }
    );
}

// TODO: compressed textures don't have "empty" yet
/*empty_texture_test!(empty_compressedtexture1d, CompressedTexture1d, [64], 64, None, None, None);
empty_texture_test!(empty_compressedtexture1darray, CompressedTexture1dArray, [64, 32], 64, None, None, Some(32));
empty_texture_test!(empty_compressedtexture2d, CompressedTexture2d, [64, 32], 64, Some(32), None, None);
empty_texture_test!(empty_compressedtexture2darray, CompressedTexture2dArray, [64, 32, 16], 64, Some(32), None, Some(16));
empty_texture_test!(empty_compressedtexture3d, CompressedTexture3d, [64, 32, 16], 64, Some(32), Some(16), None);*/
empty_texture_test!(empty_depthstenciltexture1d, maybe DepthStencilTexture1d, [64], 64, None, None, None);
empty_texture_test!(empty_depthstenciltexture1darray, maybe DepthStencilTexture1dArray, [64, 32], 64, None, None, Some(32));
empty_texture_test!(empty_depthstenciltexture2d, maybe DepthStencilTexture2d, [64, 32], 64, Some(32), None, None);
empty_texture_test!(empty_depthstenciltexture2darray, maybe DepthStencilTexture2dArray, [64, 32, 16], 64, Some(32), None, Some(16));
// TODO: non-working
//empty_texture_test!(empty_depthstenciltexture3d, DepthStencilTexture3d, [64, 32, 16], 64, Some(32), Some(16), None);
empty_texture_test!(empty_depthtexture1d, maybe DepthTexture1d, [64], 64, None, None, None);
empty_texture_test!(empty_depthtexture1darray, maybe DepthTexture1dArray, [64, 32], 64, None, None, Some(32));
empty_texture_test!(empty_depthtexture2d, maybe DepthTexture2d, [64, 32], 64, Some(32), None, None);
empty_texture_test!(empty_depthtexture2darray, maybe DepthTexture2dArray, [64, 32, 16], 64, Some(32), None, Some(16));
// TODO: non-working
//empty_texture_test!(empty_depthtexture3d, DepthTexture3d, [64, 32, 16], 64, Some(32), Some(16), None);
empty_texture_test!(empty_integraltexture1d, maybe IntegralTexture1d, [64], 64, None, None, None);
empty_texture_test!(empty_integraltexture1darray, maybe IntegralTexture1dArray, [64, 32], 64, None, None, Some(32));
empty_texture_test!(empty_integraltexture2d, maybe IntegralTexture2d, [64, 32], 64, Some(32), None, None);
empty_texture_test!(empty_integraltexture2darray, maybe IntegralTexture2dArray, [64, 32, 16], 64, Some(32), None, Some(16));
empty_texture_test!(empty_integraltexture3d, maybe IntegralTexture3d, [64, 32, 16], 64, Some(32), Some(16), None);
empty_texture_test!(empty_stenciltexture1d, maybe StencilTexture1d, [64], 64, None, None, None);
empty_texture_test!(empty_stenciltexture1darray, maybe StencilTexture1dArray, [64, 32], 64, None, None, Some(32));
empty_texture_test!(empty_stenciltexture2d, maybe StencilTexture2d, [64, 32], 64, Some(32), None, None);
empty_texture_test!(empty_stenciltexture2darray, maybe StencilTexture2dArray, [64, 32, 16], 64, Some(32), None, Some(16));
empty_texture_test!(empty_stenciltexture3d, maybe StencilTexture3d, [64, 32, 16], 64, Some(32), Some(16), None);
empty_texture_test!(empty_texture1d, maybe Texture1d, [64], 64, None, None, None);
empty_texture_test!(empty_texture1darray, maybe Texture1dArray, [64, 32], 64, None, None, Some(32));
empty_texture_test!(empty_texture2d, Texture2d, [64, 32], 64, Some(32), None, None);
empty_texture_test!(empty_texture2darray, maybe Texture2dArray, [64, 32, 16], 64, Some(32), None, Some(16));
empty_texture_test!(empty_texture3d, maybe Texture3d, [64, 32, 16], 64, Some(32), Some(16), None);
empty_texture_test!(empty_unsignedtexture1d, maybe UnsignedTexture1d, [64], 64, None, None, None);
empty_texture_test!(empty_unsignedtexture1darray, maybe UnsignedTexture1dArray, [64, 32], 64, None, None, Some(32));
empty_texture_test!(empty_unsignedtexture2d, maybe UnsignedTexture2d, [64, 32], 64, Some(32), None, None);
empty_texture_test!(empty_unsignedtexture2darray, maybe UnsignedTexture2dArray, [64, 32, 16], 64, Some(32), None, Some(16));
empty_texture_test!(empty_unsignedtexture3d, maybe UnsignedTexture3d, [64, 32, 16], 64, Some(32), Some(16), None);
<|endoftext|>


<commit_before><commit_msg>More WebIDL implementations.<commit_after><|endoftext|>


<commit_before><commit_msg>Can only read directories.<commit_after><|endoftext|>


<commit_before><commit_msg>Removed cmake cargo build<commit_after><|endoftext|>


<commit_before><commit_msg>Add decode logic to sort opcodes into Operations<commit_after><|endoftext|>


<commit_before><commit_msg>Make launchtestxlw use constant.<commit_after><|endoftext|>


<commit_before><commit_msg>Change at calls to get on capture groups<commit_after><|endoftext|>


<commit_before><commit_msg>add dumb Env<commit_after>//
// Copyright (c) 2016, Boris Popov <popov@whitekefir.ru>
//
// 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/.
//

use logger;

pub struct Env {
    device: String,
    dir:    String,
    script: String
}

impl Env {

    pub fn new() -> Env {
        return Env{device: "".to_string(),
                   dir:    "".to_string(),
                   script: "".to_string()}
    }

    pub fn load(&self, l: &logger::Logger) {
        self.load_device(l);
        self.load_dir(l);
        self.load_script(l);
    }

    fn load_device(&self, l: &logger::Logger) {
        //
        //TODO
        //
    }

    fn load_dir(&self, l: &logger::Logger) {
        //
        //TODO
        //
    }

    fn load_script(&self, l: &logger::Logger) {
        //
        //TODO
        //
    }
}
<|endoftext|>


<commit_before><commit_msg>use real fps to record<commit_after><|endoftext|>


<commit_before><commit_msg>`IXAudio2Voice::SetOutputMatrix()`<commit_after><|endoftext|>


<commit_before><commit_msg>Fix grammar<commit_after><|endoftext|>


<commit_before><commit_msg>Added log module<commit_after>extern crate time;

use std::fmt;
use std::io;
use std::io::{Error, Write};
use std::cmp::{Ord, Ordering};

pub enum LogLevel {
    ERROR,
    WARN,
    INFO,
    VERBOSE
}

// ERROR > WARN > INFO > VERBOSE
impl Ord for LogLevel {
    fn cmp(&self, other: &Self) -> Ordering {
        match *self {
            LogLevel::ERROR => match *other {
                        LogLevel::ERROR => Ordering::Equal,
                        _ => Ordering::Greater,
                    },
            LogLevel::WARN => match *other {
                        LogLevel::ERROR => Ordering::Less,
                        LogLevel::WARN => Ordering::Equal,
                        _ => Ordering::Greater,
                    },
            LogLevel::INFO => match *other {
                        LogLevel::VERBOSE => Ordering::Greater,
                        LogLevel::INFO => Ordering::Equal,
                        _ => Ordering::Less,
                    },
            LogLevel::VERBOSE => match *other {
                        LogLevel::VERBOSE => Ordering::Equal,
                        _ => Ordering::Less,
                    },
        }
    }
}

impl Eq for LogLevel {}

impl PartialEq for LogLevel {

    fn eq(&self, other: &Self) -> bool {
        self.cmp(other) == Ordering::Equal
    }

    fn ne(&self, other: &Self) -> bool {
        !self.eq(other)
    }

}

impl PartialOrd for LogLevel {

    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }

    fn lt(&self, other: &Self) -> bool {
        self.cmp(other) == Ordering::Less
    }

    fn le(&self, other: &Self) -> bool {
        self.cmp(other) != Ordering::Greater
    }

    fn gt(&self, other: &Self) -> bool {
        self.cmp(other) == Ordering::Greater
    }

    fn ge(&self, other: &Self) -> bool {
        self.cmp(other) != Ordering::Less
    }
}

/// Set global log level here
static LOG_LEVEL: LogLevel = LogLevel::INFO;

/// the log function returning a result
///
/// # Examples
/// '''
/// log(LogLevel::ERROR, format_args!("This is bad!")).unwrap();
/// '''
pub fn log(level: LogLevel, args: fmt::Arguments) -> Result<(), Error> {

    if level < LOG_LEVEL {
        return Ok(());
    }

    let stderr = io::stderr();
    let stdout = io::stdout();

    let mut stderr_lock = stderr.lock();
    let mut stdout_lock = stdout.lock();

    let cur_time = time::now();

    match level {
        LogLevel::ERROR => writeln!(stderr_lock, "[ERROR] {}:{}:{} - {}", cur_time.tm_hour, cur_time.tm_min, cur_time.tm_sec, args),
        LogLevel::WARN => writeln!(stdout_lock, "[WARN] {}:{}:{} - {}", cur_time.tm_hour, cur_time.tm_min, cur_time.tm_sec, args),
        LogLevel::INFO => writeln!(stdout_lock, "[INFO] {}:{}:{} - {}", cur_time.tm_hour, cur_time.tm_min, cur_time.tm_sec, args),
        LogLevel::VERBOSE => writeln!(stdout_lock, "[VERBOSE] {}:{}:{} - {}", cur_time.tm_hour, cur_time.tm_min, cur_time.tm_sec, args),
    }

}

/// a log function ignoring any failure
/// "log something, if possible"
///
/// # Examples
/// '''
/// try_log(LogLevel::ERROR, format_args!("This is bad!"));
/// '''
pub fn try_log(level: LogLevel, args: fmt::Arguments) {
    let _ = log(level, args);
}

// Helper Macro

/// Error Macro
///
/// # Examples
/// '''
/// error!("This is bad!");
/// '''
macro_rules! error {
    ($($arg:tt)*) => (::utils::log::try_log(::utils::log::LogLevel::ERROR, format_args!($($arg)*)));
}

/// Warning Macro
///
/// # Examples
/// '''
/// error!("This is maybe bad?!");
/// '''
macro_rules! warn {
    ($($arg:tt)*) => (::utils::log::try_log(::utils::log::LogLevel::WARN, format_args!($($arg)*)));
}

/// Info Macro
///
/// # Examples
/// '''
/// error!("This is just to let you know!");
/// '''
macro_rules! info {
    ($($arg:tt)*) => (::utils::log::try_log(::utils::log::LogLevel::INFO, format_args!($($arg)*)));
}

/// Verbose Macro
///
/// # Examples
/// '''
/// error!("You must really like spam!");
/// '''
macro_rules! verbose {
    ($($arg:tt)*) => (::utils::log::try_log(::utils::log::LogLevel::VERBOSE, format_args!($($arg)*)));
}

#[test]
fn test() {
    info!("Test!");
}

//To-Do add a way to check the result automatically
#[test]
fn multi_thread_test() {
    let mut joins = Vec::new();
    for _ in 0..10 {
        joins.push(std::thread::spawn(move || {
            info!("No corruption should happen in this ultra-extra-super-long string output even if run in multiple threads.");
        }));
    }
    for handle in joins {
        let _ = handle.join();
    }
}
<|endoftext|>


<commit_before><commit_msg>use BitConvertible trait<commit_after><|endoftext|>