<commit_before><commit_msg>add system call preliminaries<commit_after>use prolog::ast::*;
use prolog::machine::machine_errors::*;
use prolog::machine::machine_state::*;
use prolog::num::{ToPrimitive, Zero};
use prolog::num::bigint::BigInt;

use std::rc::Rc;

struct BrentAlgState {
    hare: usize,
    tortoise: usize,
    power: usize,
    steps: usize
}

impl BrentAlgState {
    fn new(hare: usize) -> Self {
        BrentAlgState { hare, tortoise: hare, power: 2, steps: 1 }
    }
}

impl MachineState {
    // a step in Brent's algorithm.
    fn brents_alg_step(&self, brent_st: &mut BrentAlgState) -> Option<CycleSearchResult>
    {
        match self.heap[brent_st.hare].clone() {
            HeapCellValue::Addr(Addr::Lis(l)) => {
                brent_st.hare = l + 1;
                brent_st.steps += 1;

                if brent_st.tortoise == brent_st.hare {
                    return Some(CycleSearchResult::NotList);
                } else if brent_st.steps == brent_st.power {
                    brent_st.tortoise = brent_st.hare;
                    brent_st.power <<= 1;
                }

                None
            },
            HeapCellValue::NamedStr(..) =>
                Some(CycleSearchResult::NotList),
            HeapCellValue::Addr(addr) =>
                match self.store(self.deref(addr)) {
                    Addr::Con(Constant::EmptyList) =>
                        Some(CycleSearchResult::ProperList(brent_st.steps)),
                    Addr::HeapCell(_) | Addr::StackCell(..) =>
                        Some(CycleSearchResult::PartialList(brent_st.steps, brent_st.hare)),
                    _ =>
                        Some(CycleSearchResult::NotList)
                }
        }
    }

    pub(super) fn detect_cycles_with_max(&self, max_steps: usize, addr: Addr) -> CycleSearchResult
    {
        let addr = self.store(self.deref(addr));

        let mut hare = match addr {
            Addr::Lis(offset) if max_steps > 0 => offset + 1,
            Addr::Lis(offset) => return CycleSearchResult::UntouchedList(offset),
            Addr::Con(Constant::EmptyList) => return CycleSearchResult::EmptyList,
            _ => return CycleSearchResult::NotList
        };

        let mut brent_st = BrentAlgState::new(hare);

        loop {
            if brent_st.steps == max_steps {
                return CycleSearchResult::PartialList(brent_st.steps, brent_st.hare);
            }

            if let Some(result) = self.brents_alg_step(&mut brent_st) {
                return result;
            }
        }
    }

    pub(super) fn detect_cycles(&self, addr: Addr) -> CycleSearchResult
    {
        let addr = self.store(self.deref(addr));

        let mut hare = match addr {
            Addr::Lis(offset) => offset + 1,
            Addr::Con(Constant::EmptyList) => return CycleSearchResult::EmptyList,
            _ => return CycleSearchResult::NotList
        };

        let mut brent_st = BrentAlgState::new(hare);

        loop {
            if let Some(result) = self.brents_alg_step(&mut brent_st) {
                return result;
            }
        }
    }

    fn finalize_skip_max_list(&mut self, n: usize, addr: Addr) {
        let target_n = self[temp_v!(1)].clone();
        self.unify(Addr::Con(integer!(n)), target_n);

        if !self.fail {
            let xs = self[temp_v!(4)].clone();
            self.unify(addr, xs);
        }
    }

    pub(super) fn skip_max_list(&mut self) -> Result<(), MachineError> {
        let max_steps = self.arith_eval_by_metacall(temp_v!(2))?;

        match max_steps {
            Number::Integer(ref max_steps)
                if max_steps.to_isize().map(|i| i >= -1).unwrap_or(false) => {
                    let n = self.store(self.deref(self[temp_v!(1)].clone()));

                    match n {
                        Addr::Con(Constant::Number(Number::Integer(ref n))) if n.is_zero() => {
                            let xs0 = self[temp_v!(3)].clone();
                            let xs  = self[temp_v!(4)].clone();

                            self.unify(xs0, xs);
                        },
                        _ => {
                            let search_result = if let Some(max_steps) = max_steps.to_isize() {
                                if max_steps == -1 {
                                    self.detect_cycles(self[temp_v!(3)].clone())
                                } else {
                                    self.detect_cycles_with_max(max_steps as usize,
                                                                self[temp_v!(3)].clone())
                                }
                            } else {
                                self.detect_cycles(self[temp_v!(3)].clone())
                            };

                            match search_result {
                                CycleSearchResult::UntouchedList(l) =>
                                    self.finalize_skip_max_list(0, Addr::Lis(l)),
                                CycleSearchResult::EmptyList =>
                                    self.finalize_skip_max_list(0, Addr::Con(Constant::EmptyList)),
                                CycleSearchResult::PartialList(n, hc) =>
                                    self.finalize_skip_max_list(n, Addr::HeapCell(hc)),
                                CycleSearchResult::ProperList(n) =>
                                    self.finalize_skip_max_list(n, Addr::Con(Constant::EmptyList)),
                                CycleSearchResult::NotList => {
                                    let xs0 = self[temp_v!(3)].clone();
                                    self.finalize_skip_max_list(0, xs0);
                                }
                            }
                        }
                    }
                },
            _ => self.fail = true
        };

        Ok(())
    }

    pub(super) fn execute_system(&mut self, ct: &SystemClauseType) -> Result<(), MachineError> {
        match ct {
            &SystemClauseType::SkipMaxList => self.skip_max_list()
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>fix for not being able to copy files inside a folder<commit_after><|endoftext|>


<commit_before>extern crate core;

use std::io;
use std::fs;
use std::fs::PathExt;
use std::fs::File;
use std::io::Read;
use std::path::Path;
use std::collections::HashMap;
use self::core::str::StrExt;
use std::ffi::OsStr;
use liquid::Value;

use document::Document;
use util;

pub fn build(source: &Path, dest: &Path, layout_str: &str, posts_str: &str) -> io::Result<()>{
    // TODO make configurable
    let template_extensions = [OsStr::new("tpl") /*, OsStr::new("md")*/];

    let layouts_path = source.join(layout_str);
    let posts_path = source.join(posts_str);

    let mut layouts : HashMap<String, String> = HashMap::new();

    // go through the layout directory and add
    // filename -> text content to the layout map
    match fs::walk_dir(&layouts_path) {
        Ok(files) => for layout in files {
            let layout = try!(layout).path();
            if layout.is_file() {
                let mut text = String::new();
                try!(try!(File::open(&layout)).read_to_string(&mut text));
                layouts.insert(layout.as_path().file_name().unwrap().to_str().unwrap().to_string(), text);
            }
        },
        Err(_) => println!("Warning: No layout path found ({})\n", source.display())
    };

    let mut documents = vec![];
    let mut post_data = vec![];

    // walk source directory and find files that are written in
    // a template file extension
    for p in try!(fs::walk_dir(source)) {
        let p = p.unwrap().path();
        let path = p.as_path();
        // check for file extensions
        if template_extensions.contains(&path.extension().unwrap_or(OsStr::new("")))
        // check that file is not in the layouts folder
        && path.parent() != Some(layouts_path.as_path()) {
            let doc = parse_document(&path, source);
            if path.parent() == Some(posts_path.as_path()){
                post_data.push(Value::Object(doc.get_attributes()));
            }
            documents.push(doc);
        }
    }

    for doc in documents.iter() {
        try!(doc.create_file(dest, &layouts, &post_data));
    }

    // copy everything
    if source != dest {
        try!(util::copy_recursive_filter(source, dest, &|p| -> bool {
            !p.file_name().unwrap().to_str().unwrap_or("").starts_with(".")
            && !template_extensions.contains(&p.extension().unwrap_or(OsStr::new("")))
            && p != dest
            && p != layouts_path.as_path()
        }));
    }

    Ok(())
}

fn parse_document(path: &Path, source: &Path) -> Document {
    let attributes = extract_attributes(path);
    let content    = extract_content(path).unwrap();
    let new_path   = path.relative_from(source).unwrap();
    let markdown   = path.extension().unwrap_or(OsStr::new("")) == OsStr::new("md");

    Document::new(
        new_path.to_str().unwrap().to_string(),
        attributes,
        content,
        markdown
    )
}

fn parse_file(path: &Path) -> io::Result<String> {
    let mut file = try!(File::open(path));
    let mut text = String::new();
    try!(file.read_to_string(&mut text));
    Ok(text)
}

fn extract_attributes(path: &Path) -> HashMap<String, String> {
    let mut attributes = HashMap::new();
    attributes.insert("name".to_string(), path.file_stem().unwrap().to_str().unwrap().to_string());

    let content = parse_file(path).unwrap();

    if content.contains("---") {
        let mut content_splits = content.split("---");

        let attribute_string = content_splits.nth(0).unwrap();

        for attribute_line in attribute_string.split("\n") {
            if !attribute_line.contains_char(':') {
                continue;
            }

            let attribute_split: Vec<&str> = attribute_line.split(':').collect();

            let key   = attribute_split[0].trim_matches(' ').to_string();
            let value = attribute_split[1].trim_matches(' ').to_string();

            attributes.insert(key, value);
        }
    }

    return attributes;
}

fn extract_content(path: &Path) -> io::Result<String> {
    let content = try!(parse_file(path));

    if content.contains("---") {
        let mut content_splits = content.split("---");

        return Ok(content_splits.nth(1).unwrap().to_string());
    }

    return Ok(content);
}
<commit_msg>readd md as allowed template_extension, this closes #23<commit_after>extern crate core;

use std::io;
use std::fs;
use std::fs::PathExt;
use std::fs::File;
use std::io::Read;
use std::path::Path;
use std::collections::HashMap;
use self::core::str::StrExt;
use std::ffi::OsStr;
use liquid::Value;

use document::Document;
use util;

pub fn build(source: &Path, dest: &Path, layout_str: &str, posts_str: &str) -> io::Result<()>{
    // TODO make configurable
    let template_extensions = [OsStr::new("tpl"), OsStr::new("md")];

    let layouts_path = source.join(layout_str);
    let posts_path = source.join(posts_str);

    let mut layouts : HashMap<String, String> = HashMap::new();

    // go through the layout directory and add
    // filename -> text content to the layout map
    match fs::walk_dir(&layouts_path) {
        Ok(files) => for layout in files {
            let layout = try!(layout).path();
            if layout.is_file() {
                let mut text = String::new();
                try!(try!(File::open(&layout)).read_to_string(&mut text));
                layouts.insert(layout.as_path().file_name().unwrap().to_str().unwrap().to_string(), text);
            }
        },
        Err(_) => println!("Warning: No layout path found ({})\n", source.display())
    };

    let mut documents = vec![];
    let mut post_data = vec![];

    // walk source directory and find files that are written in
    // a template file extension
    for p in try!(fs::walk_dir(source)) {
        let p = p.unwrap().path();
        let path = p.as_path();
        // check for file extensions
        if template_extensions.contains(&path.extension().unwrap_or(OsStr::new("")))
        // check that file is not in the layouts folder
        && path.parent() != Some(layouts_path.as_path()) {
            let doc = parse_document(&path, source);
            if path.parent() == Some(posts_path.as_path()){
                post_data.push(Value::Object(doc.get_attributes()));
            }
            documents.push(doc);
        }
    }

    for doc in documents.iter() {
        try!(doc.create_file(dest, &layouts, &post_data));
    }

    // copy everything
    if source != dest {
        try!(util::copy_recursive_filter(source, dest, &|p| -> bool {
            !p.file_name().unwrap().to_str().unwrap_or("").starts_with(".")
            && !template_extensions.contains(&p.extension().unwrap_or(OsStr::new("")))
            && p != dest
            && p != layouts_path.as_path()
        }));
    }

    Ok(())
}

fn parse_document(path: &Path, source: &Path) -> Document {
    let attributes = extract_attributes(path);
    let content    = extract_content(path).unwrap();
    let new_path   = path.relative_from(source).unwrap();
    let markdown   = path.extension().unwrap_or(OsStr::new("")) == OsStr::new("md");

    Document::new(
        new_path.to_str().unwrap().to_string(),
        attributes,
        content,
        markdown
    )
}

fn parse_file(path: &Path) -> io::Result<String> {
    let mut file = try!(File::open(path));
    let mut text = String::new();
    try!(file.read_to_string(&mut text));
    Ok(text)
}

fn extract_attributes(path: &Path) -> HashMap<String, String> {
    let mut attributes = HashMap::new();
    attributes.insert("name".to_string(), path.file_stem().unwrap().to_str().unwrap().to_string());

    let content = parse_file(path).unwrap();

    if content.contains("---") {
        let mut content_splits = content.split("---");

        let attribute_string = content_splits.nth(0).unwrap();

        for attribute_line in attribute_string.split("\n") {
            if !attribute_line.contains_char(':') {
                continue;
            }

            let attribute_split: Vec<&str> = attribute_line.split(':').collect();

            let key   = attribute_split[0].trim_matches(' ').to_string();
            let value = attribute_split[1].trim_matches(' ').to_string();

            attributes.insert(key, value);
        }
    }

    return attributes;
}

fn extract_content(path: &Path) -> io::Result<String> {
    let content = try!(parse_file(path));

    if content.contains("---") {
        let mut content_splits = content.split("---");

        return Ok(content_splits.nth(1).unwrap().to_string());
    }

    return Ok(content);
}
<|endoftext|>


<commit_before><commit_msg>tests: add basic_boot<commit_after>#![no_std]
#![no_main]
#![feature(custom_test_frameworks)]
#![test_runner(daedalos::test_runner)]
#![reexport_test_harness_main = "test_main"]

use daedalos::{println, serial_print, serial_println};

#[no_mangle]
pub extern "C" fn _start() -> ! {
    test_main();

    loop {}
}

#[panic_handler]
fn panic(info: &core::panic::PanicInfo) -> ! {
    daedalos::test_panic_handler(info)
}

#[test_case]
fn test_println() {
    serial_print!("test_println... ");
    println!("test_println output");
    serial_println!("[ok]");
}
<|endoftext|>


<commit_before>#![feature(globs)]
#![feature(macro_rules)]
#![feature(phase)]
#![feature(slicing_syntax)]

extern crate gfx;
extern crate wad;
extern crate math;

extern crate getopts;
#[phase(plugin, link)]
extern crate gl;
extern crate libc;
#[phase(plugin, link)]
extern crate log;
extern crate sdl2;
extern crate time;

use ctrl::GameController;
use ctrl::Gesture;
use getopts::{optopt,optflag,getopts, usage};
use gfx::ShaderLoader;
use level::Level;
use libc::c_void;
use math::{Mat4, Vec3};
use player::Player;
use sdl2::scancode::ScanCode;
use sdl2::video::GLAttr;
use sdl2::video::WindowPos;
use std::default::Default;
use std::os;
use wad::TextureDirectory;

pub mod camera;
pub mod ctrl;
pub mod player;
pub mod level;

const WINDOW_TITLE: &'static str = "Rusty Doom v0.0.7 - Toggle mouse with \
                                    backtick key (`))";
const OPENGL_DEPTH_SIZE: int = 24;
const SHADER_ROOT: &'static str = "src/shaders";

pub struct MainWindow {
    window: sdl2::video::Window,
    _context: sdl2::video::GLContext,
}
impl MainWindow {
    pub fn new(width: uint, height: uint) -> MainWindow {
        sdl2::video::gl_set_attribute(GLAttr::GLContextMajorVersion,
                                      gl::platform::GL_MAJOR_VERSION);
        sdl2::video::gl_set_attribute(GLAttr::GLContextMinorVersion,
                                      gl::platform::GL_MINOR_VERSION);
        sdl2::video::gl_set_attribute(GLAttr::GLDepthSize, OPENGL_DEPTH_SIZE);
        sdl2::video::gl_set_attribute(GLAttr::GLDoubleBuffer, 1);
        sdl2::video::gl_set_attribute(
            GLAttr::GLContextProfileMask,
            sdl2::video::ll::SDL_GLprofile::SDL_GL_CONTEXT_PROFILE_CORE as int);

        let window = sdl2::video::Window::new(
            WINDOW_TITLE, WindowPos::PosCentered, WindowPos::PosCentered,
            width as int, height as int,
            sdl2::video::OPENGL | sdl2::video::SHOWN).unwrap();

        let context = window.gl_create_context().unwrap();
        sdl2::clear_error();
        gl::load_with(|name| {
            match sdl2::video::gl_get_proc_address(name) {
                Some(glproc) => glproc as *const libc::c_void,
                None => {
                    warn!("missing GL function: {}", name);
                    std::ptr::null()
                }
            }
        });
        let mut vao_id = 0;
        check_gl_unsafe!(gl::GenVertexArrays(1, &mut vao_id));
        check_gl_unsafe!(gl::BindVertexArray(vao_id));
        MainWindow {
           window: window,
            _context: context,
        }
    }

    pub fn aspect_ratio(&self) -> f32 {
        let (w, h) = self.window.get_size();
        w as f32 / h as f32
    }

    pub fn swap_buffers(&self) {
        self.window.gl_swap_window();
    }
}

pub struct GameConfig<'a> {
    wad: &'a str,
    metadata: &'a str,
    level_index: uint,
    fov: f32,
}

pub struct Game {
    window: MainWindow,
    player: Player,
    level: Level,
}
impl Game {
    pub fn new(window: MainWindow, config: GameConfig) -> Game {
        let mut wad = wad::Archive::open(&Path::new(config.wad),
                                         &Path::new(config.metadata)).unwrap();
        let textures = TextureDirectory::from_archive(&mut wad).unwrap();
        let shader_loader = ShaderLoader::new(gl::platform::GLSL_VERSION_STRING,
                                              Path::new(SHADER_ROOT));
        let level = Level::new(&shader_loader,
                               &mut wad, &textures, config.level_index);

        check_gl_unsafe!(gl::ClearColor(0.06, 0.07, 0.09, 0.0));
        check_gl_unsafe!(gl::Enable(gl::DEPTH_TEST));
        check_gl_unsafe!(gl::DepthFunc(gl::LESS));

        let start = *level.get_start_pos();
        let mut player = Player::new(config.fov, window.aspect_ratio(),
                                     Default::default());
        player.set_position(&Vec3::new(start.x, 0.3, start.y));

        Game {
            window: window,
            player: player,
            level: level
        }
    }

    pub fn run(&mut self) {
        let quit_gesture = Gesture::AnyOf(
            vec![Gesture::QuitTrigger,
                 Gesture::KeyTrigger(ScanCode::Escape)]);
        let grab_toggle_gesture = Gesture::KeyTrigger(ScanCode::Grave);

        let mut cum_time = 0.0;
        let mut cum_updates_time = 0.0;
        let mut num_frames = 0.0;
        let mut t0 = 0.0;
        let mut control = GameController::new();
        let mut mouse_grabbed = true;
        loop {
            check_gl_unsafe!(
                gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT));
            let t1 = time::precise_time_s();
            let mut delta = (t1 - t0) as f32;
            if delta < 1e-10 { delta = 1.0 / 60.0; }
            let delta = delta;
            t0 = t1;

            let updates_t0 = time::precise_time_s();

            control.update();
            if control.poll_gesture(&quit_gesture) {
                break;
            } else if control.poll_gesture(&grab_toggle_gesture) {
                mouse_grabbed = !mouse_grabbed;
                control.set_mouse_enabled(mouse_grabbed);
                control.set_cursor_grabbed(mouse_grabbed);
            }

            self.player.update(delta, &control);
            self.level.render(
                delta,
                &self.player.get_camera()
                .multiply_transform(&Mat4::new_identity()));

            let updates_t1 = time::precise_time_s();
            cum_updates_time += updates_t1 - updates_t0;

            cum_time += delta as f64;
            num_frames += 1.0 as f64;
            if cum_time > 2.0 {
                let fps = num_frames / cum_time;
                let cpums = 1000.0 * cum_updates_time / num_frames as f64;
                info!("Frame time: {:.2}ms ({:.2}ms cpu, FPS: {:.2})",
                      1000.0 / fps, cpums, fps);
                cum_time = 0.0;
                cum_updates_time = 0.0;
                num_frames = 0.0;
            }

            self.window.swap_buffers();
        }
    }
}

#[cfg(not(test))]
pub fn run() {
    let args: Vec<String> = os::args();
    let opts = [
        optopt("i", "iwad",
               "set initial wad file to use wad [default='doom1.wad']", "FILE"),
        optopt("m", "metadata",
               "path to toml toml metadata file [default='doom.toml']", "FILE"),
        optopt("l", "level",
               "the index of the level to render [default=0]", "N"),
        optopt("f", "fov",
               "horizontal field of view to please TotalHalibut [default=65]",
               "FLOAT"),
        optopt("r", "resolution",
               "the resolution at which to render the game [default=1280x720]",
               "WIDTHxHEIGHT"),
        optflag("d", "dump-levels", "list all levels and exit."),
        optflag("", "load-all", "loads all levels and exit; for debugging"),
        optflag("h", "help", "print this help message and exit"),
    ];

    let matches = match getopts(args.tail(), &opts) {
        Ok(m) => m,
        Err(f) => panic!(f.to_string()),
    };

    let wad_filename = matches
        .opt_str("i")
        .unwrap_or("doom1.wad".to_string());
    let meta_filename = matches
        .opt_str("m")
        .unwrap_or("doom.toml".to_string());
    let (width, height) = matches
        .opt_str("r")
        .map(|r| {
            let v = r[].splitn(1, 'x').collect::<Vec<&str>>();
            if v.len() != 2 { None } else { Some(v) }
            .and_then(|v| from_str::<uint>(v[0]).map(|v0| (v0, v[1])))
            .and_then(|(v0, s)| from_str::<uint>(s).map(|v1| (v0, v1)))
            .expect("Invalid format for resolution, please use WIDTHxHEIGHT.")
        })
        .unwrap_or((1280, 720));
    let level_index = matches
        .opt_str("l")
        .map(|l| from_str::<uint>(l[])
            .expect("Invalid value for --level. Expected integer."))
        .unwrap_or(0);
    let fov = matches
        .opt_str("f")
        .map(|f| from_str::<f32>(f[])
             .expect("Invalid value for --fov. Expected float."))
        .unwrap_or(65.0);

    if matches.opt_present("h") {
        println!("{}", usage("A rust doom renderer.", &opts));
        return;
    }

    if matches.opt_present("d") {
        let wad = wad::Archive::open(
            &Path::new(wad_filename[]), &Path::new(meta_filename[])).unwrap();
        for i_level in range(0, wad.num_levels()) {
            println!("{:3} {:8}", i_level, wad.get_level_name(i_level));
        }
        return;
    }

    if matches.opt_present("load-all") {
        if !sdl2::init(sdl2::INIT_VIDEO) {
            panic!("main: sdl video init failed.");
        }
        let _win = MainWindow::new(width, height);
        let t0 = time::precise_time_s();
        let mut wad = wad::Archive::open(
            &Path::new(wad_filename[]), &Path::new(meta_filename[])).unwrap();
        let textures = TextureDirectory::from_archive(&mut wad).unwrap();
        for level_index in range(0, wad.num_levels()) {
            let shader_loader = ShaderLoader::new(
                gl::platform::GLSL_VERSION_STRING, Path::new(SHADER_ROOT));
            Level::new(&shader_loader, &mut wad, &textures, level_index);
        }
        println!("Done, loaded all levels in {:.4}s. Shutting down...",
                 time::precise_time_s() - t0);
        sdl2::quit();
        return;
    }

    if !sdl2::init(sdl2::INIT_VIDEO) { panic!("main: sdl video init failed."); }

    let mut game = Game::new(
        MainWindow::new(width, height),
        GameConfig {
            wad: wad_filename[],
            metadata: meta_filename[],
            level_index: level_index,
            fov: fov,
        });
    game.run();

    info!("Shutting down.");
    drop(game);
    sdl2::quit();
}
<commit_msg>Fix unused warnings for test build of game crate<commit_after>#![feature(globs)]
#![feature(macro_rules)]
#![feature(phase)]
#![feature(slicing_syntax)]

extern crate gfx;
extern crate wad;
extern crate math;

extern crate getopts;
#[phase(plugin, link)]
extern crate gl;
extern crate libc;
#[phase(plugin, link)]
extern crate log;
extern crate sdl2;
extern crate time;

use ctrl::GameController;
use ctrl::Gesture;
use gfx::ShaderLoader;
use level::Level;
use libc::c_void;
use math::{Mat4, Vec3};
use player::Player;
use sdl2::scancode::ScanCode;
use sdl2::video::GLAttr;
use sdl2::video::WindowPos;
use std::default::Default;
use wad::TextureDirectory;

pub mod camera;
pub mod ctrl;
pub mod player;
pub mod level;

const WINDOW_TITLE: &'static str = "Rusty Doom v0.0.7 - Toggle mouse with \
                                    backtick key (`))";
const OPENGL_DEPTH_SIZE: int = 24;
const SHADER_ROOT: &'static str = "src/shaders";

pub struct MainWindow {
    window: sdl2::video::Window,
    _context: sdl2::video::GLContext,
}
impl MainWindow {
    pub fn new(width: uint, height: uint) -> MainWindow {
        sdl2::video::gl_set_attribute(GLAttr::GLContextMajorVersion,
                                      gl::platform::GL_MAJOR_VERSION);
        sdl2::video::gl_set_attribute(GLAttr::GLContextMinorVersion,
                                      gl::platform::GL_MINOR_VERSION);
        sdl2::video::gl_set_attribute(GLAttr::GLDepthSize, OPENGL_DEPTH_SIZE);
        sdl2::video::gl_set_attribute(GLAttr::GLDoubleBuffer, 1);
        sdl2::video::gl_set_attribute(
            GLAttr::GLContextProfileMask,
            sdl2::video::ll::SDL_GLprofile::SDL_GL_CONTEXT_PROFILE_CORE as int);

        let window = sdl2::video::Window::new(
            WINDOW_TITLE, WindowPos::PosCentered, WindowPos::PosCentered,
            width as int, height as int,
            sdl2::video::OPENGL | sdl2::video::SHOWN).unwrap();

        let context = window.gl_create_context().unwrap();
        sdl2::clear_error();
        gl::load_with(|name| {
            match sdl2::video::gl_get_proc_address(name) {
                Some(glproc) => glproc as *const libc::c_void,
                None => {
                    warn!("missing GL function: {}", name);
                    std::ptr::null()
                }
            }
        });
        let mut vao_id = 0;
        check_gl_unsafe!(gl::GenVertexArrays(1, &mut vao_id));
        check_gl_unsafe!(gl::BindVertexArray(vao_id));
        MainWindow {
           window: window,
            _context: context,
        }
    }

    pub fn aspect_ratio(&self) -> f32 {
        let (w, h) = self.window.get_size();
        w as f32 / h as f32
    }

    pub fn swap_buffers(&self) {
        self.window.gl_swap_window();
    }
}

pub struct GameConfig<'a> {
    wad: &'a str,
    metadata: &'a str,
    level_index: uint,
    fov: f32,
}

pub struct Game {
    window: MainWindow,
    player: Player,
    level: Level,
}
impl Game {
    pub fn new(window: MainWindow, config: GameConfig) -> Game {
        let mut wad = wad::Archive::open(&Path::new(config.wad),
                                         &Path::new(config.metadata)).unwrap();
        let textures = TextureDirectory::from_archive(&mut wad).unwrap();
        let shader_loader = ShaderLoader::new(gl::platform::GLSL_VERSION_STRING,
                                              Path::new(SHADER_ROOT));
        let level = Level::new(&shader_loader,
                               &mut wad, &textures, config.level_index);

        check_gl_unsafe!(gl::ClearColor(0.06, 0.07, 0.09, 0.0));
        check_gl_unsafe!(gl::Enable(gl::DEPTH_TEST));
        check_gl_unsafe!(gl::DepthFunc(gl::LESS));

        let start = *level.get_start_pos();
        let mut player = Player::new(config.fov, window.aspect_ratio(),
                                     Default::default());
        player.set_position(&Vec3::new(start.x, 0.3, start.y));

        Game {
            window: window,
            player: player,
            level: level
        }
    }

    pub fn run(&mut self) {
        let quit_gesture = Gesture::AnyOf(
            vec![Gesture::QuitTrigger,
                 Gesture::KeyTrigger(ScanCode::Escape)]);
        let grab_toggle_gesture = Gesture::KeyTrigger(ScanCode::Grave);

        let mut cum_time = 0.0;
        let mut cum_updates_time = 0.0;
        let mut num_frames = 0.0;
        let mut t0 = 0.0;
        let mut control = GameController::new();
        let mut mouse_grabbed = true;
        loop {
            check_gl_unsafe!(
                gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT));
            let t1 = time::precise_time_s();
            let mut delta = (t1 - t0) as f32;
            if delta < 1e-10 { delta = 1.0 / 60.0; }
            let delta = delta;
            t0 = t1;

            let updates_t0 = time::precise_time_s();

            control.update();
            if control.poll_gesture(&quit_gesture) {
                break;
            } else if control.poll_gesture(&grab_toggle_gesture) {
                mouse_grabbed = !mouse_grabbed;
                control.set_mouse_enabled(mouse_grabbed);
                control.set_cursor_grabbed(mouse_grabbed);
            }

            self.player.update(delta, &control);
            self.level.render(
                delta,
                &self.player.get_camera()
                .multiply_transform(&Mat4::new_identity()));

            let updates_t1 = time::precise_time_s();
            cum_updates_time += updates_t1 - updates_t0;

            cum_time += delta as f64;
            num_frames += 1.0 as f64;
            if cum_time > 2.0 {
                let fps = num_frames / cum_time;
                let cpums = 1000.0 * cum_updates_time / num_frames as f64;
                info!("Frame time: {:.2}ms ({:.2}ms cpu, FPS: {:.2})",
                      1000.0 / fps, cpums, fps);
                cum_time = 0.0;
                cum_updates_time = 0.0;
                num_frames = 0.0;
            }

            self.window.swap_buffers();
        }
    }
}

#[cfg(not(test))]
pub fn run() {
    use getopts::{optopt,optflag,getopts, usage};
    use std::os;

    let args: Vec<String> = os::args();
    let opts = [
        optopt("i", "iwad",
               "set initial wad file to use wad [default='doom1.wad']", "FILE"),
        optopt("m", "metadata",
               "path to toml toml metadata file [default='doom.toml']", "FILE"),
        optopt("l", "level",
               "the index of the level to render [default=0]", "N"),
        optopt("f", "fov",
               "horizontal field of view to please TotalHalibut [default=65]",
               "FLOAT"),
        optopt("r", "resolution",
               "the resolution at which to render the game [default=1280x720]",
               "WIDTHxHEIGHT"),
        optflag("d", "dump-levels", "list all levels and exit."),
        optflag("", "load-all", "loads all levels and exit; for debugging"),
        optflag("h", "help", "print this help message and exit"),
    ];

    let matches = match getopts(args.tail(), &opts) {
        Ok(m) => m,
        Err(f) => panic!(f.to_string()),
    };

    let wad_filename = matches
        .opt_str("i")
        .unwrap_or("doom1.wad".to_string());
    let meta_filename = matches
        .opt_str("m")
        .unwrap_or("doom.toml".to_string());
    let (width, height) = matches
        .opt_str("r")
        .map(|r| {
            let v = r[].splitn(1, 'x').collect::<Vec<&str>>();
            if v.len() != 2 { None } else { Some(v) }
            .and_then(|v| from_str::<uint>(v[0]).map(|v0| (v0, v[1])))
            .and_then(|(v0, s)| from_str::<uint>(s).map(|v1| (v0, v1)))
            .expect("Invalid format for resolution, please use WIDTHxHEIGHT.")
        })
        .unwrap_or((1280, 720));
    let level_index = matches
        .opt_str("l")
        .map(|l| from_str::<uint>(l[])
            .expect("Invalid value for --level. Expected integer."))
        .unwrap_or(0);
    let fov = matches
        .opt_str("f")
        .map(|f| from_str::<f32>(f[])
             .expect("Invalid value for --fov. Expected float."))
        .unwrap_or(65.0);

    if matches.opt_present("h") {
        println!("{}", usage("A rust doom renderer.", &opts));
        return;
    }

    if matches.opt_present("d") {
        let wad = wad::Archive::open(
            &Path::new(wad_filename[]), &Path::new(meta_filename[])).unwrap();
        for i_level in range(0, wad.num_levels()) {
            println!("{:3} {:8}", i_level, wad.get_level_name(i_level));
        }
        return;
    }

    if matches.opt_present("load-all") {
        if !sdl2::init(sdl2::INIT_VIDEO) {
            panic!("main: sdl video init failed.");
        }
        let _win = MainWindow::new(width, height);
        let t0 = time::precise_time_s();
        let mut wad = wad::Archive::open(
            &Path::new(wad_filename[]), &Path::new(meta_filename[])).unwrap();
        let textures = TextureDirectory::from_archive(&mut wad).unwrap();
        for level_index in range(0, wad.num_levels()) {
            let shader_loader = ShaderLoader::new(
                gl::platform::GLSL_VERSION_STRING, Path::new(SHADER_ROOT));
            Level::new(&shader_loader, &mut wad, &textures, level_index);
        }
        println!("Done, loaded all levels in {:.4}s. Shutting down...",
                 time::precise_time_s() - t0);
        sdl2::quit();
        return;
    }

    if !sdl2::init(sdl2::INIT_VIDEO) { panic!("main: sdl video init failed."); }

    let mut game = Game::new(
        MainWindow::new(width, height),
        GameConfig {
            wad: wad_filename[],
            metadata: meta_filename[],
            level_index: level_index,
            fov: fov,
        });
    game.run();

    info!("Shutting down.");
    drop(game);
    sdl2::quit();
}
<|endoftext|>


<commit_before><commit_msg>Add missing example for testing the drop/ memory leakage<commit_after>extern crate libmodbus_sys as raw;
extern crate libmodbus_rs;

use libmodbus_rs::modbus::{Modbus};

fn main() {
    // 1. Parameter Serial Interface `/dev/ttyUSB0`
    let device: String = std::env::args().nth(1).unwrap();
    // 2. Parameter SlaveID
    let slave_id: i32 = std::env::args().nth(2).unwrap().parse().unwrap();

    let mut modbus = Modbus::new_rtu(&device, 9600, 'N', 8, 1);
    let _ = modbus.set_slave(slave_id);
    let _ = modbus.set_debug(true);

    match modbus.connect() {
        Err(_) => { modbus.free(); }
        Ok(_) => {}
    }
}
<|endoftext|>


<commit_before><commit_msg>Added negative matching example<commit_after>/*

This example shows how to use negative matching on tokens.

For example:

    !"hi":"hi_did_not_occured"

This rule generates:

    "hi_did_not_occured":true

when "hi" was *not* parsed.

One can also use double negative for simplicity:

    !"hi":!"hi"

This will generate:

    "hi":false

*/

extern crate piston_meta;

use piston_meta::*;

fn main() {
    let text = r#"hello!"#;
    let rules = r#"
        1 document = [!"hi":"hi_did_not_occured" ...""?]
    "#;
    // Parse rules with meta language and convert to rules for parsing text.
    let rules = match syntax_errstr(rules) {
        Err(err) => {
            println!("{}", err);
            return;
        }
        Ok(rules) => rules
    };
    let mut data = vec![];
    match parse_errstr(&rules, text, &mut data) {
        Err(err) => {
            println!("{}", err);
        }
        Ok(()) => {}
    };
    // Prints `"hi_did_not_occured":true`.
    json::print(&data);
}
<|endoftext|>


<commit_before><commit_msg>update log logic<commit_after><|endoftext|>


<commit_before><commit_msg>Convert access (client) to Tokio<commit_after><|endoftext|>


<commit_before><commit_msg>start to set up messages<commit_after><|endoftext|>


<commit_before><commit_msg>Allow configuring deque capacity<commit_after><|endoftext|>


<commit_before><commit_msg>Delete unnecessary mut<commit_after><|endoftext|>


<commit_before><commit_msg>Implement file_shared<commit_after><|endoftext|>


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

#![feature(rustc_private)]

// We're testing linkage visibility; the compiler warns us, but we want to
// do the runtime check that these functions aren't exported.
#![allow(private_no_mangle_fns)]

extern crate rustc_metadata;

use rustc_metadata::dynamic_lib::DynamicLibrary;

#[no_mangle]
pub fn foo() { bar(); }

pub fn foo2<T>() {
    fn bar2() {
        bar();
    }
    bar2();
}

#[no_mangle]
fn bar() { }

#[allow(dead_code)]
#[no_mangle]
fn baz() { }

pub fn test() {
    let lib = DynamicLibrary::open(None).unwrap();
    unsafe {
        assert!(lib.symbol::<isize>("foo").is_ok());
        assert!(lib.symbol::<isize>("baz").is_ok());
        assert!(lib.symbol::<isize>("bar").is_ok());
    }
}
<commit_msg>Rollup merge of #55564 - smaeul:test-fixes-2, r=alexcrichton<commit_after>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// ignore-musl - dlsym doesn't see symbols without "-C link-arg=-Wl,--export-dynamic"

#![feature(rustc_private)]

// We're testing linkage visibility; the compiler warns us, but we want to
// do the runtime check that these functions aren't exported.
#![allow(private_no_mangle_fns)]

extern crate rustc_metadata;

use rustc_metadata::dynamic_lib::DynamicLibrary;

#[no_mangle]
pub fn foo() { bar(); }

pub fn foo2<T>() {
    fn bar2() {
        bar();
    }
    bar2();
}

#[no_mangle]
fn bar() { }

#[allow(dead_code)]
#[no_mangle]
fn baz() { }

pub fn test() {
    let lib = DynamicLibrary::open(None).unwrap();
    unsafe {
        assert!(lib.symbol::<isize>("foo").is_ok());
        assert!(lib.symbol::<isize>("baz").is_ok());
        assert!(lib.symbol::<isize>("bar").is_ok());
    }
}
<|endoftext|>


<commit_before><commit_msg>Updated config<commit_after><|endoftext|>


<commit_before><commit_msg>Move format functions<commit_after>pub fn format_union(node: &Union) -> String {
    let mut s = String::new();
    for field in &node.fields {
        s += &format_type(&field.type_name);
        s += " ";
        s += &format_form(&field.form);
        s += ";\n";
    }
    return format!(
        "union {{\n{}\n}} {};\n",
        indent(&s),
        format_form(&node.form)
    );
}

pub fn format_type(node: &Type) -> String {
    let mut s = String::new();
    if node.is_const {
        s += "const ";
    }
    s += &node.type_name;
    return s;
}

pub fn format_form(node: &Form) -> String {
    let mut s = String::new();
    s += &node.stars;
    s += &node.name;
    for expr in &node.indexes {
        match expr {
            Some(e) => s += &format!("[{}]", format_expression(&e)),
            None => s += "[]",
        }
    }
    return s;
}

pub fn format_expression(expr: &Expression) -> String {
    match expr {
        Expression::BinaryOp(x) => format_binary_op(x),
        Expression::Cast(x) => format_cast(x),
        Expression::FunctionCall(x) => format_function_call(x),
        Expression::Expression(x) => format_expression(x),
        Expression::Literal(x) => format_literal(x),
        Expression::Identifier(x) => x.name.clone(),
        Expression::StructLiteral(x) => format_struct_literal(x),
        Expression::ArrayLiteral(x) => format_array_literal(x),
        Expression::Sizeof(x) => format_sizeof(x),
        Expression::PrefixOperator(x) => format_prefix_operator(x),
        Expression::PostfixOperator(x) => format_postfix_operator(x),
        Expression::ArrayIndex(x) => format_array_index(x),
    }
}

pub fn format_cast(node: &Cast) -> String {
    return format!(
        "({}) {}",
        format_anonymous_typeform(&node.type_name),
        format_expression(&node.operand)
    );
}

pub fn format_sizeof(node: &Sizeof) -> String {
    let arg = match &node.argument {
        SizeofArgument::Type(x) => format_type(&x),
        SizeofArgument::Expression(x) => format_expression(&x),
    };
    return format!("sizeof({})", arg);
}

pub fn format_anonymous_typeform(node: &AnonymousTypeform) -> String {
    let mut s = format_type(&node.type_name);
    for op in &node.ops {
        s += &op;
    }
    return s;
}

pub fn format_array_index(node: &ArrayIndex) -> String {
    return format!(
        "{}[{}]",
        format_expression(&node.array),
        format_expression(&node.index)
    );
}

pub fn format_anonymous_parameters(node: &AnonymousParameters) -> String {
    let mut s = String::from("(");
    for (i, form) in node.forms.iter().enumerate() {
        if i > 0 {
            s += ", ";
        }
        s += &format_anonymous_typeform(form);
    }
    s += ")";
    return s;
}

pub fn format_array_literal(node: &ArrayLiteral) -> String {
    let mut s = String::from("{");
    if !node.values.is_empty() {
        for (i, entry) in node.values.iter().enumerate() {
            if i > 0 {
                s += ", ";
            }
            s += &match &entry.index {
                ArrayLiteralKey::None => String::from(""),
                ArrayLiteralKey::Identifier(x) => format!("[{}] = ", x.name),
                ArrayLiteralKey::Literal(x) => format!("[{}] = ", format_literal(&x)),
            };
            s += &match &entry.value {
                ArrayLiteralValue::ArrayLiteral(x) => format_array_literal(&x),
                ArrayLiteralValue::Identifier(x) => x.name.clone(),
                ArrayLiteralValue::Literal(x) => format_literal(&x),
            };
        }
    } else {
        s += "0";
    }
    s += "}";
    return s;
}

pub fn brace_if_needed(node: &BinaryOp, operand: &Expression) -> String {
    match operand {
        Expression::BinaryOp(x) => {
            if operator_strength(&x.op) < operator_strength(&node.op) {
                return format!("({})", format_binary_op(&*x));
            } else {
                return format_binary_op(&*x);
            }
        }
        _ => format_expression(operand),
    }
}

pub fn format_binary_op(node: &BinaryOp) -> String {
    let parts = vec![
        brace_if_needed(node, &node.a),
        node.op.clone(),
        brace_if_needed(node, &node.b),
    ];
    if node.op == "." || node.op == "->" {
        return parts.join("");
    }
    return parts.join(" ");
}

fn indent(text: &str) -> String {
    if text.ends_with("\n") {
        return indent(&text[0..text.len() - 1]) + "\n";
    }
    return String::from("\t") + &text.replace("\n", "n\t");
}

pub fn format_body(node: &Body) -> String {
    let mut s = String::new();
    for statement in &node.statements {
        s += &format_statement(&statement);
        s += ";\n";
    }
    return format!("{{\n{}}}\n", indent(&s));
}

// pub fn format_compat_function_declaration(node)
// {
//     let mut s = String::new();
//     if (node['static'] && format_node(node['form']) != 'main') {
//         s += "static ";
//     }
//     s += format_node(node['type_name'])
//         . ' ' . format_node(node['form'])
//         . format_pub fn_parameters(node['parameters'])
//         . ' ' . format_node(node['body']);
//     return s;
// }

// pub fn format_compat_function_forward_declaration($node)
// {
//     $s = '';
//     if ($node['static'] && format_node($node['form']) != 'main') {
//         $s += 'static ';
//     }
//     $s += format_node($node['type_name'])
//         . ' ' . format_node($node['form'])
//         . format_pub fn_parameters($node['parameters']) . ";\n";
//     return $s;
// }

// pub fn format_compat_include($node)
// {
//     return "#include $node[name]\n";
// }

// pub fn format_compat_module($node)
// {
//     $s = '';
//     foreach ($node['elements'] as $node) {
//         $s += format_node($node);
//     }
//     return $s;
// }

// pub fn format_compat_struct_definition($node)
// {
//     return 'struct ' . $node['name'] . ' ' . format_node($node['fields']) . ";\n";
// }

// pub fn format_compat_struct_forward_declaration($node)
// {
//     return 'struct ' . $node['name'] . ";\n";
// }

// pub fn format_compat_enum($node)
// {
//     $s = "enum {\n";
//     foreach ($node['members'] as $i => $member) {
//         if ($i > 0) {
//             $s += ",\n";
//         }
//         $s += "\t" . format_node($member);
//     }
//     $s += "\n};\n";
//     return $s;
// }

pub fn format_anonymous_struct(node: &AnonymousStruct) -> String {
    let mut s = String::new();
    for fieldlist in &node.fieldlists {
        s += &match fieldlist {
            StructEntry::StructFieldlist(x) => format_struct_fieldlist(&x),
            StructEntry::Union(x) => format_union(&x),
        };
        s += "\n";
    }
    return format!("{{\n{}}}", indent(&s));
}

pub fn format_enum(node: &Enum) -> String {
    let mut s = String::new();
    if node.is_pub {
        s += "pub ";
    }
    s += "enum {\n";
    for id in &node.members {
        s += &format!("\t{},\n", format_enum_member(&id));
    }
    s += "}\n";
    return s;
}

pub fn format_enum_member(node: &EnumMember) -> String {
    let mut s = node.id.name.clone();
    if node.value.is_some() {
        s += " = ";
        s += &format_literal(node.value.as_ref().unwrap());
    }
    return s;
}

pub fn format_for(node: &For) -> String {
    let init = match &node.init {
        ForInit::Expression(x) => format_expression(&x),
        ForInit::LoopCounterDeclaration(x) => format!(
            "{} {} = {}",
            format_type(&x.type_name),
            x.name.name,
            format_expression(&x.value)
        ),
    };
    return format!(
        "for ({}; {}; {}) {}",
        init,
        format_expression(&node.condition),
        format_expression(&node.action),
        format_body(&node.body)
    );
}

pub fn format_function_call(node: &FunctionCall) -> String {
    let mut s1 = String::from("(");
    for (i, argument) in node.arguments.iter().enumerate() {
        if i > 0 {
            s1 += ", ";
        }
        s1 += &format_expression(&argument);
    }
    s1 += ")";
    return format!("{}{}", format_expression(&node.function), s1);
}

pub fn format_function_declaration(node: &FunctionDeclaration) -> String {
    let s = format!(
        "{} {}{} {}\n\n",
        format_type(&node.type_name),
        format_form(&node.form),
        format_function_parameters(&node.parameters),
        format_body(&node.body)
    );
    if node.is_pub {
        return format!("pub {}", s);
    }
    return s;
}

pub fn format_function_parameters(parameters: &FunctionParameters) -> String {
    let mut s = String::from("(");
    for (i, parameter) in parameters.list.iter().enumerate() {
        if i > 0 {
            s += ", ";
        }
        s += &format_type(&parameter.type_name);
        s += " ";
        for (i, form) in parameter.forms.iter().enumerate() {
            if i > 0 {
                s += ", ";
            }
            s += &format_form(&form);
        }
    }
    if parameters.variadic {
        s += ", ...";
    }
    s += ")";
    return s;
}

pub fn format_if(node: &If) -> String {
    let mut s = format!(
        "if ({}) {}",
        format_expression(&node.condition),
        format_body(&node.body)
    );
    if node.else_body.is_some() {
        s += &format!(" else {}", format_body(node.else_body.as_ref().unwrap()));
    }
    return s;
}

pub fn format_import(node: &Import) -> String {
    format!("import {}\n", node.path)
}

pub fn format_literal(node: &Literal) -> String {
    match node.type_name.as_str() {
        "string" => format!("\"{}\"", node.value),
        "char" => format!("\'{}\'", node.value),
        _ => node.value.clone(),
    }
}

pub fn format_compat_macro(node: &CompatMacro) -> String {
    format!("#{} {}\n", node.name, node.value)
}

pub fn format_module(node: &Module) -> String {
    let mut s = String::new();
    for cnode in &node.elements {
        s += &match cnode {
            ModuleObject::ModuleVariable(x) => format_module_variable(&x),
            ModuleObject::Enum(x) => format_enum(&x),
            ModuleObject::FunctionDeclaration(x) => format_function_declaration(&x),
            ModuleObject::Import(x) => format_import(&x),
            ModuleObject::Typedef(x) => format_typedef(&x),
            ModuleObject::CompatMacro(x) => format_compat_macro(&x),
        }
    }
    return s;
}

pub fn format_module_variable(node: &ModuleVariable) -> String {
    return format!(
        "{} {} = {};\n",
        format_type(&node.type_name),
        format_form(&node.form),
        format_expression(&node.value)
    );
}

pub fn format_postfix_operator(node: &PostfixOperator) -> String {
    return format_expression(&node.operand) + &node.operator;
}

pub fn format_prefix_operator(node: &PrefixOperator) -> String {
    let operand = &node.operand;
    let operator = &node.operator;
    match operand {
        Expression::BinaryOp(x) => format!("{}({})", operator, format_binary_op(&*x)),
        Expression::Cast(x) => format!("{}({})", operator, format_cast(&*x)),
        _ => format!("{}{}", operator, format_expression(&operand)),
    }
}

pub fn format_return(node: &Return) -> String {
    match &node.expression {
        None => String::from("return;"),
        Some(x) => format!("return {};", format_expression(&x)),
    }
}

pub fn format_struct_fieldlist(node: &StructFieldlist) -> String {
    let mut s = format_type(&node.type_name) + " ";
    for (i, form) in node.forms.iter().enumerate() {
        if i > 0 {
            s += ", ";
        }
        s += &format_form(&form);
    }
    s += ";";
    return s;
}

pub fn format_struct_literal(node: &StructLiteral) -> String {
    let mut s = String::from("{\n");
    for member in &node.members {
        s += &format!(
            "\t.{} = {},\n",
            member.name.name,
            format_expression(&member.value)
        );
    }
    s += "}\n";
    return s;
}

pub fn format_statement(node: &Statement) -> String {
    match node {
        Statement::VariableDeclaration(x) => format_variable_declaration(x),
        Statement::If(x) => format_if(x),
        Statement::For(x) => format_for(x),
        Statement::While(x) => format_while(x),
        Statement::Return(x) => format_return(x),
        Statement::Switch(x) => format_switch(x),
        Statement::Expression(x) => format_expression(&x),
    }
}

pub fn format_switch(node: &Switch) -> String {
    let mut s = String::new();
    for case in &node.cases {
        let val = match &case.value {
            SwitchCaseValue::Identifier(x) => x.name.clone(),
            SwitchCaseValue::Literal(x) => format_literal(&x),
        };
        s += &format!("case {}: {{\n", val);
        for statement in &case.statements {
            s += &format_statement(&statement);
            s += ";\n";
        }
        s += "}\n";
    }
    if node.default.is_some() {
        s += "default: {\n";
        for statement in node.default.as_ref().unwrap() {
            s += &format_statement(&statement);
            s += ";\n";
        }
        s += "}\n";
    }
    return format!(
        "switch ({}) {{\n{}\n}}",
        format_expression(&node.value),
        indent(&s)
    );
}

pub fn format_typedef(node: &Typedef) -> String {
    let mut form = node.form.stars.clone() + &node.form.alias.name;
    if node.form.params.is_some() {
        form += &format_anonymous_parameters(&node.form.params.as_ref().unwrap());
    }
    if node.form.size > 0 {
        form += &format!("[{}]", node.form.size);
    }
    let t = match &node.type_name {
        TypedefTarget::AnonymousStruct(x) => format_anonymous_struct(&x),
        TypedefTarget::Type(x) => format_type(&x),
    };
    return format!("typedef {} {};\n", t, form);
}

pub fn format_variable_declaration(node: &VariableDeclaration) -> String {
    let mut s = String::from(format_type(&node.type_name)) + " ";
    for (i, form) in node.forms.iter().enumerate() {
        let value = &node.values[i];
        if i > 0 {
            s += ", ";
        }
        s += &format_form(&form);
        s += " = ";
        s += &format_expression(value);
    }
    s += ";\n";
    return s;
}

pub fn format_while(node: &While) -> String {
    return format!(
        "while ({}) {}",
        format_expression(&node.condition),
        format_body(&node.body)
    );
}
<|endoftext|>


<commit_before><commit_msg>sprite cycling now cycles through any amount<commit_after><|endoftext|>


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

// xfail-test #2443
// exec-env:RUST_POISON_ON_FREE

fn it_takes_two(x: @int, -y: @int) -> int {
    free(y);
    debug!("about to deref");
    *x
}

fn free<T>(-_t: T) {
}

pub fn main() {
    let z = @3;
    assert!(3 == it_takes_two(z, z));
}
<commit_msg>removed test referring to WONTFIX bug #2443<commit_after><|endoftext|>


<commit_before><commit_msg>add a comma<commit_after><|endoftext|>


<commit_before><commit_msg>Add helper to recompose Event data as &str<commit_after><|endoftext|>


<commit_before>extern crate sodiumoxide;
extern crate num_traits;
extern crate env_logger;
extern crate godcoin;
extern crate tokio;
extern crate ctrlc;
extern crate dirs;
extern crate clap;

#[macro_use]
extern crate log;

use clap::{Arg, App, AppSettings, SubCommand};
use tokio::prelude::*;
use std::sync::Arc;
use godcoin::*;

struct StartNode<'a> {
    bind_address: Option<&'a str>,
    minter_key: Option<KeyPair>
}

fn generate_keypair() {
    let pair = KeyPair::gen_keypair();
    info!("~~ Keys have been generated ~~");
    info!("Private key WIF: {}", pair.1.to_wif());
    info!("Public key WIF: {}", pair.0.to_wif());
    info!("- Make sure the keys are securely stored");
    info!("- Coins cannot be recovered if you lose your private key");
    info!("- Never give private keys to anyone");
}

fn start_node(node_opts: StartNode) {
    use godcoin::blockchain::*;
    use std::{env, path::*};

    let home: PathBuf = {
        use dirs;
        let home = env::var("GODCOIN_HOME").map(|s| {
            PathBuf::from(s)
        }).unwrap_or_else(|_| {
            Path::join(&dirs::data_local_dir().unwrap(), "godcoin")
        });
        if !Path::is_dir(&home) {
            let res = std::fs::create_dir(&home);
            res.expect(&format!("Failed to create dir at {:?}", &home));
            info!("Created GODcoin home at {:?}", &home);
        } else {
            info!("Found GODcoin home at {:?}", &home);
        }
        home
    };

    let mut blockchain = Blockchain::new(&home);
    {
        let create_genesis = blockchain.get_block(0).is_none();
        if create_genesis && node_opts.minter_key.is_some() {
            if let Some(ref key) = node_opts.minter_key {
                blockchain.create_genesis_block(key);
            }
        }
    }

    info!("Using height in block log at {}", blockchain.get_chain_height());

    if let Some(ref key) = node_opts.minter_key {
        let bond = blockchain.get_bond(&key.0).expect("No bond found for minter key");
        let minter = key.clone();
        let staker = bond.staker;
        let producer = producer::Producer::new(Arc::new(blockchain), minter, staker);
        producer.start_timer();
    }

    if let Some(bind) = node_opts.bind_address {
        let addr = bind.parse()
                        .expect(&format!("Failed to parse address: {:?}", bind));
        net::start_server(&addr);
    }
}

fn main() {
    let env = env_logger::Env::new().filter_or(env_logger::DEFAULT_FILTER_ENV, "godcoin=info");
    env_logger::init_from_env(env);

    godcoin::init().unwrap();
    let app = App::new("godcoin")
                .about("GODcoin core CLI")
                .version(env!("CARGO_PKG_VERSION"))
                .setting(AppSettings::VersionlessSubcommands)
                .setting(AppSettings::SubcommandRequiredElseHelp)
                .subcommand(SubCommand::with_name("keygen")
                            .about("Generates a keypair"))
                .subcommand(SubCommand::with_name("node")
                            .about("Starts the blockchain node service")
                            .arg(Arg::with_name("bind_address")
                                .help("Bind address endpoint (i.e 0.0.0.0:7777)")
                                .long("bind")
                                .value_name("address"))
                            .arg(Arg::with_name("minter_key")
                                .help("Private minting key required to mint")
                                .long("minter-key")
                                .value_name("key")));
    let matches = app.get_matches();

    let mut rt = tokio::runtime::Runtime::new().unwrap();
    rt.block_on(future::lazy(move || {
        use ::std::io::{Error, ErrorKind};

        if let Some(_) = matches.subcommand_matches("keygen") {
            generate_keypair();
        } else if let Some(matches) = matches.subcommand_matches("node") {
            start_node(StartNode {
                bind_address: matches.value_of("bind_address"),
                minter_key: matches.value_of("minter_key").map(|s| {
                    godcoin::PrivateKey::from_wif(s)
                        .expect("Failed to parse minter key argument")
                })
            });
        } else {
            return Err(Error::new(ErrorKind::Other, "Failed to match subcommand"))
        }

        Ok(())
    }).map_err(|err| {
        error!("Startup failure: {:?}", err);
    })).unwrap();

    let (tx, rx) = ::std::sync::mpsc::channel::<()>();
    ctrlc::set_handler(move || {
        println!("Received ctrl-c signal, shutting down...");
        tx.send(()).unwrap();
    }).unwrap();

    rx.recv().unwrap();
    rt.shutdown_now().wait().ok().unwrap();
}
<commit_msg>Shutdown the threadpool when executing the keygen command<commit_after>extern crate sodiumoxide;
extern crate num_traits;
extern crate env_logger;
extern crate godcoin;
extern crate tokio;
extern crate ctrlc;
extern crate dirs;
extern crate clap;

#[macro_use]
extern crate log;

use clap::{Arg, App, AppSettings, SubCommand};
use std::sync::{Arc, mpsc};
use tokio::prelude::*;
use godcoin::*;

struct StartNode<'a> {
    bind_address: Option<&'a str>,
    minter_key: Option<KeyPair>
}

fn generate_keypair(shutdown_handle: mpsc::Sender<()>) {
    let pair = KeyPair::gen_keypair();
    info!("~~ Keys have been generated ~~");
    info!("Private key WIF: {}", pair.1.to_wif());
    info!("Public key WIF: {}", pair.0.to_wif());
    info!("- Make sure the keys are securely stored");
    info!("- Coins cannot be recovered if you lose your private key");
    info!("- Never give private keys to anyone");
    shutdown_handle.send(()).unwrap();
}

fn start_node(node_opts: StartNode) {
    use godcoin::blockchain::*;
    use std::{env, path::*};

    let home: PathBuf = {
        use dirs;
        let home = env::var("GODCOIN_HOME").map(|s| {
            PathBuf::from(s)
        }).unwrap_or_else(|_| {
            Path::join(&dirs::data_local_dir().unwrap(), "godcoin")
        });
        if !Path::is_dir(&home) {
            let res = std::fs::create_dir(&home);
            res.expect(&format!("Failed to create dir at {:?}", &home));
            info!("Created GODcoin home at {:?}", &home);
        } else {
            info!("Found GODcoin home at {:?}", &home);
        }
        home
    };

    let mut blockchain = Blockchain::new(&home);
    {
        let create_genesis = blockchain.get_block(0).is_none();
        if create_genesis && node_opts.minter_key.is_some() {
            if let Some(ref key) = node_opts.minter_key {
                blockchain.create_genesis_block(key);
            }
        }
    }

    info!("Using height in block log at {}", blockchain.get_chain_height());

    if let Some(ref key) = node_opts.minter_key {
        let bond = blockchain.get_bond(&key.0).expect("No bond found for minter key");
        let minter = key.clone();
        let staker = bond.staker;
        let producer = producer::Producer::new(Arc::new(blockchain), minter, staker);
        producer.start_timer();
    }

    if let Some(bind) = node_opts.bind_address {
        let addr = bind.parse()
                        .expect(&format!("Failed to parse address: {:?}", bind));
        net::start_server(&addr);
    }
}

fn main() {
    let env = env_logger::Env::new().filter_or(env_logger::DEFAULT_FILTER_ENV, "godcoin=info");
    env_logger::init_from_env(env);

    godcoin::init().unwrap();
    let app = App::new("godcoin")
                .about("GODcoin core CLI")
                .version(env!("CARGO_PKG_VERSION"))
                .setting(AppSettings::VersionlessSubcommands)
                .setting(AppSettings::SubcommandRequiredElseHelp)
                .subcommand(SubCommand::with_name("keygen")
                            .about("Generates a keypair"))
                .subcommand(SubCommand::with_name("node")
                            .about("Starts the blockchain node service")
                            .arg(Arg::with_name("bind_address")
                                .help("Bind address endpoint (i.e 0.0.0.0:7777)")
                                .long("bind")
                                .value_name("address"))
                            .arg(Arg::with_name("minter_key")
                                .help("Private minting key required to mint")
                                .long("minter-key")
                                .value_name("key")));
    let matches = app.get_matches();

    let (tx, rx) = mpsc::channel::<()>();
    let mut rt = tokio::runtime::Runtime::new().unwrap();

    {
        let tx = tx.clone();
        rt.block_on(future::lazy(move || {
            use ::std::io::{Error, ErrorKind};

            if let Some(_) = matches.subcommand_matches("keygen") {
                generate_keypair(tx);
            } else if let Some(matches) = matches.subcommand_matches("node") {
                start_node(StartNode {
                    bind_address: matches.value_of("bind_address"),
                    minter_key: matches.value_of("minter_key").map(|s| {
                        godcoin::PrivateKey::from_wif(s)
                            .expect("Failed to parse minter key argument")
                    })
                });
            } else {
                return Err(Error::new(ErrorKind::Other, "Failed to match subcommand"))
            }

            Ok(())
        }).map_err(|err| {
            error!("Startup failure: {:?}", err);
        })).unwrap();
    }

    ctrlc::set_handler(move || {
        println!("Received ctrl-c signal, shutting down...");
        tx.send(()).unwrap();
    }).unwrap();

    rx.recv().unwrap();
    rt.shutdown_now().wait().ok().unwrap();
}
<|endoftext|>


<commit_before><commit_msg>example webserver<commit_after>use std::fs;
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;

fn main() {
    let listener = TcpListener::bind("127.0.0.1:7878").unwrap();

    for stream in listener.incoming() {
        let stream = stream.unwrap();

        handle_connection(stream);
    }
}

fn handle_connection(mut stream: TcpStream) {
    let mut buffer = [0; 1024];
    stream.read(&mut buffer).unwrap();

    let get = b"GET / HTTP/1.1\r\n";

    let (status_line, filename) = if buffer.starts_with(get) {
        ("HTTP/1.1 200 OK\r\n\r\n", "hello.html")
    } else {
        ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html")
    };

    let contents = fs::read_to_string(filename).unwrap();

    let response = format!(
            "{}{}", status_line, contents
        );

    stream.write(response.as_bytes()).unwrap();
    stream.flush().unwrap();

}
<|endoftext|>


<commit_before><commit_msg>int literal; float literal; char literal; string literal;<commit_after><|endoftext|>


<commit_before><commit_msg>Add missed structfields on Anime and Manga structs<commit_after><|endoftext|>


<commit_before><commit_msg>Adds prototype registering<commit_after><|endoftext|>


<commit_before><commit_msg>Replace entry.value.unwrap() with match.<commit_after><|endoftext|>


<commit_before><commit_msg>tweak usage of result objects and adjust repo fetch flow<commit_after>use std::result::Result;
use rusqlite::SqliteError;
use std::convert::From;
use db;

pub type RepoResult<T> = Result<T, RepoError>;

#[derive(Debug)]
pub enum RepoError {
    DbError(db::DbError),
    SqlError(SqliteError),
    NoRemote,
    NotCloned,
}

impl From<SqliteError> for RepoError {
    fn from(err: SqliteError) -> RepoError {
        RepoError::SqlError(err)
    }
}

impl From<db::DbError> for RepoError {
    fn from(err: db::DbError) -> RepoError {
        RepoError::DbError(err)
    }
}

<|endoftext|>


<commit_before><commit_msg>Add iter and into_iter methods for List<T> and add test cases for them<commit_after><|endoftext|>


<commit_before><commit_msg>We now separate constant and variable declations again, and check while loops.<commit_after><|endoftext|>


<commit_before><commit_msg>add more b_tree::tests<commit_after><|endoftext|>


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

//! Runtime services
//!
//! The `rt` module provides a narrow set of runtime services,
//! including the global heap (exported in `heap`) and unwinding and
//! backtrace support. The APIs in this module are highly unstable,
//! and should be considered as private implementation details for the
//! time being.

#![unstable(feature = "rt",
            reason = "this public module should not exist and is highly likely \
                      to disappear",
            issue = "0")]
#![doc(hidden)]

// Reexport some of our utilities which are expected by other crates.
pub use panicking::{begin_panic, begin_panic_fmt, update_panic_count};

#[cfg(not(any(test, stage0)))]
#[lang = "start"]
fn lang_start<T: ::termination::Termination + 'static>
    (main: fn() -> T, argc: isize, argv: *const *const u8) -> !
{
    use panic;
    use sys;
    use sys_common;
    use sys_common::thread_info;
    use thread::Thread;
    use process;
    #[cfg(not(feature = "backtrace"))]
    use mem;

    sys::init();

    process::exit(unsafe {
        let main_guard = sys::thread::guard::init();
        sys::stack_overflow::init();

        // Next, set up the current Thread with the guard information we just
        // created. Note that this isn't necessary in general for new threads,
        // but we just do this to name the main thread and to give it correct
        // info about the stack bounds.
        let thread = Thread::new(Some("main".to_owned()));
        thread_info::set(main_guard, thread);

        // Store our args if necessary in a squirreled away location
        sys::args::init(argc, argv);

        // Let's run some code!
        #[cfg(feature = "backtrace")]
        let exit_code = panic::catch_unwind(|| {
            ::sys_common::backtrace::__rust_begin_short_backtrace(move || main().report())
        });
        #[cfg(not(feature = "backtrace"))]
        let exit_code = panic::catch_unwind(move || main().report());

        sys_common::cleanup();
        exit_code.unwrap_or(101)
    });
}

#[cfg(all(not(test), stage0))]
#[lang = "start"]
fn lang_start(main: fn(), argc: isize, argv: *const *const u8) -> isize {
    use panic;
    use sys;
    use sys_common;
    use sys_common::thread_info;
    use thread::Thread;
    #[cfg(not(feature = "backtrace"))]
    use mem;

    sys::init();

    let failed = unsafe {
        let main_guard = sys::thread::guard::init();
        sys::stack_overflow::init();

        // Next, set up the current Thread with the guard information we just
        // created. Note that this isn't necessary in general for new threads,
        // but we just do this to name the main thread and to give it correct
        // info about the stack bounds.
        let thread = Thread::new(Some("main".to_owned()));
        thread_info::set(main_guard, thread);

        // Store our args if necessary in a squirreled away location
        sys::args::init(argc, argv);

        // Let's run some code!
        #[cfg(feature = "backtrace")]
        let res = panic::catch_unwind(|| {
            ::sys_common::backtrace::__rust_begin_short_backtrace(main)
        });
        #[cfg(not(feature = "backtrace"))]
        let res = panic::catch_unwind(mem::transmute::<_, fn()>(main));
        sys_common::cleanup();
        res.is_err()
    };

    if failed {
        101
    } else {
        0
    }
}
<commit_msg>Split `lang_start` in two functions to reduce generated code<commit_after>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Runtime services
//!
//! The `rt` module provides a narrow set of runtime services,
//! including the global heap (exported in `heap`) and unwinding and
//! backtrace support. The APIs in this module are highly unstable,
//! and should be considered as private implementation details for the
//! time being.

#![unstable(feature = "rt",
            reason = "this public module should not exist and is highly likely \
                      to disappear",
            issue = "0")]
#![doc(hidden)]

// Reexport some of our utilities which are expected by other crates.
pub use panicking::{begin_panic, begin_panic_fmt, update_panic_count};

// To reduce the generated code of the new `lang_start`, this function is doing
// the real work.
#[cfg(not(any(test, stage0)))]
fn lang_start_real<F>(main: F, argc: isize, argv: *const *const u8) -> !
    where F: FnOnce() -> i32 + Send + ::panic::UnwindSafe + 'static
{
    use panic;
    use sys;
    use sys_common;
    use sys_common::thread_info;
    use thread::Thread;
    use process;
    #[cfg(not(feature = "backtrace"))]
    use mem;

    sys::init();

    process::exit(unsafe {
        let main_guard = sys::thread::guard::init();
        sys::stack_overflow::init();

        // Next, set up the current Thread with the guard information we just
        // created. Note that this isn't necessary in general for new threads,
        // but we just do this to name the main thread and to give it correct
        // info about the stack bounds.
        let thread = Thread::new(Some("main".to_owned()));
        thread_info::set(main_guard, thread);

        // Store our args if necessary in a squirreled away location
        sys::args::init(argc, argv);

        // Let's run some code!
        #[cfg(feature = "backtrace")]
        let exit_code = panic::catch_unwind(|| {
            ::sys_common::backtrace::__rust_begin_short_backtrace(move || main())
        });
        #[cfg(not(feature = "backtrace"))]
        let exit_code = panic::catch_unwind(move || main());

        sys_common::cleanup();
        exit_code.unwrap_or(101)
    });
}

#[cfg(not(any(test, stage0)))]
#[lang = "start"]
fn lang_start<T: ::termination::Termination + 'static>
    (main: fn() -> T, argc: isize, argv: *const *const u8) -> !
{
    lang_start_real(move || main().report(), argc, argv)
}

#[cfg(all(not(test), stage0))]
#[lang = "start"]
fn lang_start(main: fn(), argc: isize, argv: *const *const u8) -> isize {
    use panic;
    use sys;
    use sys_common;
    use sys_common::thread_info;
    use thread::Thread;
    #[cfg(not(feature = "backtrace"))]
    use mem;

    sys::init();

    let failed = unsafe {
        let main_guard = sys::thread::guard::init();
        sys::stack_overflow::init();

        // Next, set up the current Thread with the guard information we just
        // created. Note that this isn't necessary in general for new threads,
        // but we just do this to name the main thread and to give it correct
        // info about the stack bounds.
        let thread = Thread::new(Some("main".to_owned()));
        thread_info::set(main_guard, thread);

        // Store our args if necessary in a squirreled away location
        sys::args::init(argc, argv);

        // Let's run some code!
        #[cfg(feature = "backtrace")]
        let res = panic::catch_unwind(|| {
            ::sys_common::backtrace::__rust_begin_short_backtrace(main)
        });
        #[cfg(not(feature = "backtrace"))]
        let res = panic::catch_unwind(mem::transmute::<_, fn()>(main));
        sys_common::cleanup();
        res.is_err()
    };

    if failed {
        101
    } else {
        0
    }
}
<|endoftext|>