<commit_before>#![feature(macro_rules)]
#![feature(default_type_params)]
extern crate arena;
extern crate copygraph;

use arena::TypedArena;
use std::cell::Cell;

use copygraph::ograph::OGraph;

pub use copygraph::{
    MinScored,
    DiGraph,
    Graph,
    Ptr,
    Node,
    NodeCell,
    BreadthFirst,
    DepthFirst,
};

fn make_graph() {
    let root = TypedArena::new();
    let mut g: DiGraph<_, f32> = DiGraph::new();
    let an = g.add_node(Ptr(root.alloc(Node("A"))));
    let bn = g.add_node(Ptr(root.alloc(Node("B"))));
    let cn = g.add_node(Ptr(root.alloc(Node("C"))));
    g.add_edge(an, bn, 1.);
    g.add_edge(an, cn, 2.);
    /*
    println!("{}", g.nodes);

    {
        for node in g.nodes() {
            println!("Node= {}", node);
        }
    }

    for next in g.edges(an) {
        println!("{} is a successor of {}", next, an);
    }

    g.remove_node(bn);
    println!("Removed B, {}", g.nodes);

    g.add_edge(cn, bn, 2.);
    println!("Added edge C to B, {}", g.nodes);
    g.add_edge(bn, an, 1.);
    println!("Added edge B to A, {}", g.nodes);
    g.add_edge(bn, cn, 3.);
    println!("Added edge B to C, {}", g.nodes);
    g.remove_edge(bn, an);
    println!("Removed edge B to A, {}", g.nodes);
    g.remove_edge(bn, an);
    println!("Removed edge B to A, {}", g.nodes);

    println!("Reversed, {}", g.reverse().nodes);

    */
    // Wikipedia example
    let root = TypedArena::<NodeCell<_>>::new();
    let mut g: DiGraph<_, f32> = DiGraph::new();
    let node = |name: &'static str| Ptr(root.alloc(NodeCell(Cell::new(name))));
    let a = g.add_node(node("A"));
    let b = g.add_node(node("B"));
    let c = g.add_node(node("C"));
    let d = g.add_node(node("D"));
    let e = g.add_node(node("E"));
    let f = g.add_node(node("F"));
    g.add_diedge(a, b, 7.);
    g.add_diedge(a, c, 9.);
    g.add_diedge(a, d, 14.);
    g.add_diedge(b, c, 10.);
    g.add_diedge(c, d, 2.);
    g.add_diedge(d, e, 9.);
    g.add_diedge(b, f, 15.);
    g.add_diedge(c, f, 11.);
    g.add_diedge(e, f, 6.);
    println!("{}", g);

    f.set("F'");

    println!("Scores= {}",
        copygraph::dijkstra(&g, a, |gr, n| gr.edges(n).map(|(n, &e)| (n, e)))
    );

    //let x =
    let mut it = BreadthFirst::new(&g, a);
    //let mut it = range(0i, 1);
    for node in it {
        println!("Visit {}", node);
    }
    println!("");
    let mut it = DepthFirst::new(&g, a);
    for node in it {
        println!("Visit {}", node);
    }

    let mut g: DiGraph<_, f32> = DiGraph::new();
    let node = |name: &'static str| name;
    let a = g.add_node(node("A"));
    let b = g.add_node(node("B"));
    let c = g.add_node(node("C"));
    let d = g.add_node(node("D"));
    let e = g.add_node(node("E"));
    let f = g.add_node(node("F"));
    g.add_diedge(a, b, 7.);
    g.add_diedge(a, c, 9.);
    g.add_diedge(a, d, 14.);
    g.add_diedge(b, c, 10.);
    g.add_diedge(c, d, 2.);
    g.add_diedge(d, e, 9.);
    g.add_diedge(b, f, 15.);
    g.add_diedge(c, f, 11.);
    g.add_diedge(e, f, 6.);

    println!("{}", g);

    let root = TypedArena::<Node<_>>::new();
    let mut g: Graph<_, f32> = Graph::new();
    let node = |name: &'static str| Ptr(root.alloc(Node(name.to_string())));
    let a = g.add_node(node("A"));
    let b = g.add_node(node("B"));
    let c = g.add_node(node("C"));
    let d = g.add_node(node("D"));
    let e = g.add_node(node("E"));
    let f = g.add_node(node("F"));
    g.add_edge(a, b, 7.);
    g.add_edge(a, c, 9.);
    g.add_edge(a, d, 14.);
    g.add_edge(b, c, 10.);
    g.add_edge(c, d, 2.);
    g.add_edge(d, e, 9.);
    g.add_edge(b, f, 15.);
    g.add_edge(c, f, 11.);
    g.add_edge(e, f, 6.);
    println!("{}", g);
    println!("{}", copygraph::dijkstra(&g, a, |gr, n| gr.edges(n).map(|(n, &e)| (n, e))));
    for node in DepthFirst::new(&g, a) {
        println!("Visit {}", node);
    }
    println!("");
    for node in BreadthFirst::new(&g, a) {
        println!("Visit {}", node);
    }

    let mut g: Graph<int, int> = Graph::new();
    g.add_node(1);
    g.add_node(2);
    g.add_edge(1, 2, -1);

    println!("{}", g);
    *g.edge_mut(1, 2).unwrap() = 3;
    for elt in g.edges(1) {
        println!("Edge {} => {}", 1i, elt);
    }
    for elt in g.edges(2) {
        println!("Edge {} => {}", 2i, elt);
    }
    for elt in BreadthFirst::new(&g, 2) {
        println!("Visit: {}", elt);
    }
    //g.remove_node(2);
    g.remove_edge(2, 1);
    println!("{}", g);
}

fn main() {
    make_graph();

    let mut og = OGraph::new();
    let a = og.add_node(0i);
    let b = og.add_node(1i);
    let c = og.add_node(2i);
    let ed1 = og.add_edge(a, b);
    let ed2 = og.add_edge(a, c);
    og.add_edge(c, a);
    og.add_edge(a, a);
    og.add_edge(b, c);
    og.add_edge(b, a);
    println!("{}", og);
    println!("Remove {}", a);
    for no in BreadthFirst::new(&og, a) {
        println!("Visit {}", no);
    }
    og.remove_node(a);
    //og.remove_edge(ed1);
    println!("{}", og);
    for no in BreadthFirst::new(&og, a) {
        println!("Visit {}", no);
    }
}
<commit_msg>The A-F graph in OG<commit_after>#![feature(macro_rules)]
#![feature(default_type_params)]
extern crate arena;
extern crate copygraph;

use arena::TypedArena;
use std::cell::Cell;

use copygraph::ograph::OGraph;

pub use copygraph::{
    MinScored,
    DiGraph,
    Graph,
    Ptr,
    Node,
    NodeCell,
    BreadthFirst,
    DepthFirst,
};

fn make_graph() {
    let root = TypedArena::new();
    let mut g: DiGraph<_, f32> = DiGraph::new();
    let an = g.add_node(Ptr(root.alloc(Node("A"))));
    let bn = g.add_node(Ptr(root.alloc(Node("B"))));
    let cn = g.add_node(Ptr(root.alloc(Node("C"))));
    g.add_edge(an, bn, 1.);
    g.add_edge(an, cn, 2.);
    /*
    println!("{}", g.nodes);

    {
        for node in g.nodes() {
            println!("Node= {}", node);
        }
    }

    for next in g.edges(an) {
        println!("{} is a successor of {}", next, an);
    }

    g.remove_node(bn);
    println!("Removed B, {}", g.nodes);

    g.add_edge(cn, bn, 2.);
    println!("Added edge C to B, {}", g.nodes);
    g.add_edge(bn, an, 1.);
    println!("Added edge B to A, {}", g.nodes);
    g.add_edge(bn, cn, 3.);
    println!("Added edge B to C, {}", g.nodes);
    g.remove_edge(bn, an);
    println!("Removed edge B to A, {}", g.nodes);
    g.remove_edge(bn, an);
    println!("Removed edge B to A, {}", g.nodes);

    println!("Reversed, {}", g.reverse().nodes);

    */
    // Wikipedia example
    let root = TypedArena::<NodeCell<_>>::new();
    let mut g: DiGraph<_, f32> = DiGraph::new();
    let node = |name: &'static str| Ptr(root.alloc(NodeCell(Cell::new(name))));
    let a = g.add_node(node("A"));
    let b = g.add_node(node("B"));
    let c = g.add_node(node("C"));
    let d = g.add_node(node("D"));
    let e = g.add_node(node("E"));
    let f = g.add_node(node("F"));
    g.add_diedge(a, b, 7.);
    g.add_diedge(a, c, 9.);
    g.add_diedge(a, d, 14.);
    g.add_diedge(b, c, 10.);
    g.add_diedge(c, d, 2.);
    g.add_diedge(d, e, 9.);
    g.add_diedge(b, f, 15.);
    g.add_diedge(c, f, 11.);
    g.add_diedge(e, f, 6.);
    println!("{}", g);

    f.set("F'");

    println!("Scores= {}",
        copygraph::dijkstra(&g, a, |gr, n| gr.edges(n).map(|(n, &e)| (n, e)))
    );

    //let x =
    let mut it = BreadthFirst::new(&g, a);
    //let mut it = range(0i, 1);
    for node in it {
        println!("Visit {}", node);
    }
    println!("");
    let mut it = DepthFirst::new(&g, a);
    for node in it {
        println!("Visit {}", node);
    }

    let mut g: DiGraph<_, f32> = DiGraph::new();
    let node = |name: &'static str| name;
    let a = g.add_node(node("A"));
    let b = g.add_node(node("B"));
    let c = g.add_node(node("C"));
    let d = g.add_node(node("D"));
    let e = g.add_node(node("E"));
    let f = g.add_node(node("F"));
    g.add_diedge(a, b, 7.);
    g.add_diedge(a, c, 9.);
    g.add_diedge(a, d, 14.);
    g.add_diedge(b, c, 10.);
    g.add_diedge(c, d, 2.);
    g.add_diedge(d, e, 9.);
    g.add_diedge(b, f, 15.);
    g.add_diedge(c, f, 11.);
    g.add_diedge(e, f, 6.);

    println!("{}", g);

    let root = TypedArena::<Node<_>>::new();
    let mut g: Graph<_, f32> = Graph::new();
    let node = |name: &'static str| Ptr(root.alloc(Node(name.to_string())));
    let a = g.add_node(node("A"));
    let b = g.add_node(node("B"));
    let c = g.add_node(node("C"));
    let d = g.add_node(node("D"));
    let e = g.add_node(node("E"));
    let f = g.add_node(node("F"));
    g.add_edge(a, b, 7.);
    g.add_edge(a, c, 9.);
    g.add_edge(a, d, 14.);
    g.add_edge(b, c, 10.);
    g.add_edge(c, d, 2.);
    g.add_edge(d, e, 9.);
    g.add_edge(b, f, 15.);
    g.add_edge(c, f, 11.);
    g.add_edge(e, f, 6.);
    println!("{}", g);
    println!("{}", copygraph::dijkstra(&g, a, |gr, n| gr.edges(n).map(|(n, &e)| (n, e))));
    for node in DepthFirst::new(&g, a) {
        println!("Visit {}", node);
    }
    println!("");
    for node in BreadthFirst::new(&g, a) {
        println!("Visit {}", node);
    }

    let mut g: Graph<int, int> = Graph::new();
    g.add_node(1);
    g.add_node(2);
    g.add_edge(1, 2, -1);

    println!("{}", g);
    *g.edge_mut(1, 2).unwrap() = 3;
    for elt in g.edges(1) {
        println!("Edge {} => {}", 1i, elt);
    }
    for elt in g.edges(2) {
        println!("Edge {} => {}", 2i, elt);
    }
    for elt in BreadthFirst::new(&g, 2) {
        println!("Visit: {}", elt);
    }
    //g.remove_node(2);
    g.remove_edge(2, 1);
    println!("{}", g);
}

fn main() {
    make_graph();

    let mut og = OGraph::new();
    let a = og.add_node(0i);
    let b = og.add_node(1i);
    let c = og.add_node(2i);
    let ed1 = og.add_edge(a, b);
    let ed2 = og.add_edge(a, c);
    og.add_edge(c, a);
    og.add_edge(a, a);
    og.add_edge(b, c);
    og.add_edge(b, a);
    println!("{}", og);
    println!("Remove {}", a);
    for no in BreadthFirst::new(&og, a) {
        println!("Visit {}", no);
    }
    og.remove_node(a);
    //og.remove_edge(ed1);
    println!("{}", og);
    for no in BreadthFirst::new(&og, a) {
        println!("Visit {}", no);
    }

    let mut g = OGraph::new();
    let a = g.add_node("A");
    let b = g.add_node("B");
    let c = g.add_node("C");
    let d = g.add_node("D");
    let e = g.add_node("E");
    let f = g.add_node("F");
    g.add_edge(a, b); //, 7.);
    g.add_edge(a, c); //, 9.);
    g.add_edge(a, d); //, 14.);
    g.add_edge(b, c); //, 10.);
    g.add_edge(c, d); //, 2.);
    g.add_edge(d, e); //, 9.);
    g.add_edge(b, f); //, 15.);
    g.add_edge(c, f); //, 11.);
    g.add_edge(e, f); //, 6.);
    println!("{}", g);
    for no in BreadthFirst::new(&g, a) {
        println!("Visit {} = {}", no, g.node(no));
    }
}
<|endoftext|>


<commit_before>use std::os;
use std::io::fs;
use std::io::File;
use std::path::Path;

use document::Document;

pub struct Runner;

impl Runner {
    pub fn run(path_string: &str) {
        let base_path = os::make_absolute(&Path::new(path_string));
        let document_path = os::make_absolute(&Path::new((path_string.to_string() + "/_posts").as_slice()));

        println!("Generating site in {}", base_path.as_str().unwrap());

        let documents = Runner::parse_documents(document_path);
    }

    fn parse_documents(document_path: Path) {
        let paths = fs::readdir(&document_path);
        let mut document_vec = vec!();

        if paths.is_ok() {
            for path in paths.unwrap().iter() {
                document_vec.push(Document::new(path));
            }
        } else {
            println!("Path {} doesn't exist", document_path.as_str().unwrap());
        }
    }
}
<commit_msg>implement basic Runner::extract_attributes and Runner::extract_content private static methods<commit_after>use std::os;
use std::io::fs;
use std::io::File;
use std::path::Path;

use document::Document;

pub struct Runner;

impl Runner {
    pub fn run(path_string: &str) {
        let base_path = os::make_absolute(&Path::new(path_string));
        let documents_path = os::make_absolute(&Path::new((path_string.to_string() + "/_posts").as_slice()));

        println!("Generating site in {}", base_path.as_str().unwrap());

        let documents = Runner::parse_documents(documents_path);
    }

    fn parse_documents(documents_path: Path) -> Vec<Document> {
        let paths = fs::readdir(&documents_path);
        let mut documents = vec!();

        if paths.is_ok() {
            for path in paths.unwrap().iter() {
                let attributes   = Runner::extract_attributes(path);
                let content      = Runner::extract_content(path);

                for attribute in attributes.iter() {
                    println!("{}", attribute);
                }

                documents.push(Document::new(attributes, content));
            }
        } else {
            println!("Path {} doesn't exist", documents_path.as_str().unwrap());
        }

        return documents;
    }

    fn extract_attributes(document_path: &Path) -> Vec<(String, String)> {
        let content = File::open(document_path).read_to_string().unwrap();

        // TODO: Regex matching for retrieving the attributes

        vec![
            ("Test Key".to_string(), "Test Value".to_string()),
            ("Test Key2".to_string(), "Test Value2".to_string())
        ]
    }

    fn extract_content(document_path: &Path) -> String {
        let content = File::open(document_path).read_to_string().unwrap();

        // TODO: Regex matching for retrieving the content

        return "Test".to_string();
    }
}
<|endoftext|>


<commit_before>use std::io::{Read, BufRead, Write, stdin, stdout, BufReader, BufWriter};
use std::env;
use std::fs::File;

const TAPE_SIZE: usize = 30000;

struct Interpreter<'a> {
    pub input: Box<BufRead + 'a>,
    pub output: Box<Write + 'a>,
    pub loops: Vec<usize>,
    pub tape: [u8; TAPE_SIZE],
    pub tape_index: usize,
    pub pos: usize
}

impl<'a> Interpreter<'a> {
    fn new(input: Box<BufRead + 'a>, output: Box<Write + 'a>) -> Interpreter<'a> {
        Interpreter {
            input: input,
            output: output,
            loops: Vec::new(),
            tape: [0; TAPE_SIZE],
            tape_index: 0,
            pos: 0
        }
    }

    fn run(&mut self, program: &[u8]) -> Result<(), &'static str> {
        while let Some(&c) = program.get(self.pos) {
            self.pos += 1;

            match c {
                b'<' => {
                    let amount = count_leading_chars(&program[self.pos..], b'<');
                    self.pos += amount;

                    self.tape_index = self.tape_index.wrapping_sub(amount + 1);
                    while self.tape_index >= TAPE_SIZE {
                        self.tape_index = self.tape_index.wrapping_add(TAPE_SIZE);
                    }
                },
                b'>' => {
                    let amount = count_leading_chars(&program[self.pos..], b'>');
                    self.pos += amount;

                    self.tape_index += amount + 1;
                    while self.tape_index >= TAPE_SIZE {
                        self.tape_index -= TAPE_SIZE;
                    }
                },
                b'+' => {
                    let amount = count_leading_chars(&program[self.pos..], b'+');
                    self.pos += amount;
                    if let Some(a) = self.tape[self.tape_index].checked_add(amount as u8 + 1) {
                        self.tape[self.tape_index] = a;
                    } else {
                        return Err("An overflow occurred");
                    }
                },
                b'-' => {
                    let amount = count_leading_chars(&program[self.pos..], b'-');
                    self.pos += amount;
                    if let Some(a) = self.tape[self.tape_index].checked_sub(amount as u8 + 1) {
                        self.tape[self.tape_index] = a;
                    } else {
                        return Err("An overflow occurred");
                    }
                },
                b',' => {
                    let err = self.output.flush().is_err();
                    if self.input.read_exact(&mut self.tape[self.tape_index..self.tape_index + 1]).is_err() || err {
                        return Err("IO error");
                    }
                },
                b'.' => {
                    if self.output.write_all(&self.tape[self.tape_index..self.tape_index + 1]).is_err() {
                        return Err("IO error");
                    }
                },
                b'[' => {
                    if self.tape[self.tape_index] == 0 {
                        let mut nesting = 1;
                        let amount = program[self.pos..].iter().take_while(|x| match **x {
                            b'[' => {nesting += 1; true},
                            b']' => {nesting -= 1; nesting != 0},
                            _ => true
                        }).count() + 1;
                        if nesting != 0 {
                            return Err("[ without matching ]");
                        }
                        self.pos += amount;
                    } else {
                        self.loops.push(self.pos);
                    }
                },
                b']' => {
                    if self.tape[self.tape_index] == 0 {
                        self.loops.pop();
                    } else if let Some(&loc) = self.loops.last() {
                        self.pos = loc;
                    } else {
                        return Err("] without matching [");
                    }
                },
                _ => ()
            }
        }

        if self.loops.len() != 0 {
            return Err("[ without matching ]");
        }
        Ok(())
    }
}

fn count_leading_chars(program: &[u8], c: u8) -> usize {
    program.iter().take_while(|x| **x == c).count()
}

fn main() {
    let mut args: Vec<_> = env::args().collect();
    if args.len() != 2 {
        println!("Expected 1 argument, got {}", args.len());
        return;
    }
    let path = args.pop().unwrap();

    let mut f = if let Ok(f) = File::open(&path) { f } else {
        println!("Could not open file {}", path);
        return;
    };

    let mut buf = Vec::new();
    if let Err(_) = f.read_to_end(&mut buf) {
        println!("Failed to read from file");
        return;
    }

    let mut interp = Interpreter::new(
        Box::new(BufReader::new(stdin())),
        Box::new(BufWriter::new(stdout()))
    );
    if let Err(e) = interp.run(&buf) {
        println!("{}", e);
    }
}
<commit_msg>Fix missing dyn in bf-interpreter example<commit_after>use std::io::{Read, BufRead, Write, stdin, stdout, BufReader, BufWriter};
use std::env;
use std::fs::File;

const TAPE_SIZE: usize = 30000;

struct Interpreter<'a> {
    pub input: Box<dyn BufRead + 'a>,
    pub output: Box<dyn Write + 'a>,
    pub loops: Vec<usize>,
    pub tape: [u8; TAPE_SIZE],
    pub tape_index: usize,
    pub pos: usize
}

impl<'a> Interpreter<'a> {
    fn new(input: Box<dyn BufRead + 'a>, output: Box<dyn Write + 'a>) -> Interpreter<'a> {
        Interpreter {
            input: input,
            output: output,
            loops: Vec::new(),
            tape: [0; TAPE_SIZE],
            tape_index: 0,
            pos: 0
        }
    }

    fn run(&mut self, program: &[u8]) -> Result<(), &'static str> {
        while let Some(&c) = program.get(self.pos) {
            self.pos += 1;

            match c {
                b'<' => {
                    let amount = count_leading_chars(&program[self.pos..], b'<');
                    self.pos += amount;

                    self.tape_index = self.tape_index.wrapping_sub(amount + 1);
                    while self.tape_index >= TAPE_SIZE {
                        self.tape_index = self.tape_index.wrapping_add(TAPE_SIZE);
                    }
                },
                b'>' => {
                    let amount = count_leading_chars(&program[self.pos..], b'>');
                    self.pos += amount;

                    self.tape_index += amount + 1;
                    while self.tape_index >= TAPE_SIZE {
                        self.tape_index -= TAPE_SIZE;
                    }
                },
                b'+' => {
                    let amount = count_leading_chars(&program[self.pos..], b'+');
                    self.pos += amount;
                    if let Some(a) = self.tape[self.tape_index].checked_add(amount as u8 + 1) {
                        self.tape[self.tape_index] = a;
                    } else {
                        return Err("An overflow occurred");
                    }
                },
                b'-' => {
                    let amount = count_leading_chars(&program[self.pos..], b'-');
                    self.pos += amount;
                    if let Some(a) = self.tape[self.tape_index].checked_sub(amount as u8 + 1) {
                        self.tape[self.tape_index] = a;
                    } else {
                        return Err("An overflow occurred");
                    }
                },
                b',' => {
                    let err = self.output.flush().is_err();
                    if self.input.read_exact(&mut self.tape[self.tape_index..self.tape_index + 1]).is_err() || err {
                        return Err("IO error");
                    }
                },
                b'.' => {
                    if self.output.write_all(&self.tape[self.tape_index..self.tape_index + 1]).is_err() {
                        return Err("IO error");
                    }
                },
                b'[' => {
                    if self.tape[self.tape_index] == 0 {
                        let mut nesting = 1;
                        let amount = program[self.pos..].iter().take_while(|x| match **x {
                            b'[' => {nesting += 1; true},
                            b']' => {nesting -= 1; nesting != 0},
                            _ => true
                        }).count() + 1;
                        if nesting != 0 {
                            return Err("[ without matching ]");
                        }
                        self.pos += amount;
                    } else {
                        self.loops.push(self.pos);
                    }
                },
                b']' => {
                    if self.tape[self.tape_index] == 0 {
                        self.loops.pop();
                    } else if let Some(&loc) = self.loops.last() {
                        self.pos = loc;
                    } else {
                        return Err("] without matching [");
                    }
                },
                _ => ()
            }
        }

        if self.loops.len() != 0 {
            return Err("[ without matching ]");
        }
        Ok(())
    }
}

fn count_leading_chars(program: &[u8], c: u8) -> usize {
    program.iter().take_while(|x| **x == c).count()
}

fn main() {
    let mut args: Vec<_> = env::args().collect();
    if args.len() != 2 {
        println!("Expected 1 argument, got {}", args.len());
        return;
    }
    let path = args.pop().unwrap();

    let mut f = if let Ok(f) = File::open(&path) { f } else {
        println!("Could not open file {}", path);
        return;
    };

    let mut buf = Vec::new();
    if let Err(_) = f.read_to_end(&mut buf) {
        println!("Failed to read from file");
        return;
    }

    let mut interp = Interpreter::new(
        Box::new(BufReader::new(stdin())),
        Box::new(BufWriter::new(stdout()))
    );
    if let Err(e) = interp.run(&buf) {
        println!("{}", e);
    }
}
<|endoftext|>


<commit_before>use core::mem;
use int::{Int, LargeInt};

/// Returns `n / d`
#[cfg(not(all(feature = "c", target_arch = "arm", not(target_os = "ios"), not(thumbv6m))))]
#[cfg_attr(not(test), no_mangle)]
pub extern "C" fn __udivsi3(n: u32, d: u32) -> u32 {
    // Special cases
    if d == 0 {
        panic!("Division by zero");
    }

    if n == 0 {
        return 0;
    }

    let mut sr = d.leading_zeros().wrapping_sub(n.leading_zeros());

    // d > n
    if sr > u32::bits() - 1 {
        return 0;
    }

    // d == 1
    if sr == u32::bits() - 1 {
        return n;
    }

    sr += 1;

    // 1 <= sr <= u32::bits() - 1
    let mut q = n << (u32::bits() - sr);
    let mut r = n >> sr;

    let mut carry = 0;
    for _ in 0..sr {
        // r:q = ((r:q) << 1) | carry
        r = (r << 1) | (q >> (u32::bits() - 1));
        q = (q << 1) | carry;

        // carry = 0;
        // if r > d {
        //     r -= d;
        //     carry = 1;
        // }

        let s = (d.wrapping_sub(r).wrapping_sub(1)) as i32 >> (u32::bits() - 1);
        carry = (s & 1) as u32;
        r -= d & s as u32;
    }

    (q << 1) | carry
}

/// Returns `n % d`
#[cfg(not(all(feature = "c", target_arch = "arm", not(target_os = "ios"))))]
#[cfg_attr(not(test), no_mangle)]
pub extern "C" fn __umodsi3(n: u32, d: u32) -> u32 {
    #[cfg(all(feature = "c", target_arch = "arm", not(target_os = "ios")))]
    extern "C" {
        fn __udivsi3(n: u32, d: u32) -> u32;
    }

    n - unsafe { __udivsi3(n, d) * d }
}

/// Returns `n / d` and sets `*rem = n % d`
#[cfg(not(all(feature = "c", target_arch = "arm", not(target_os = "ios"), not(thumbv6m))))]
#[cfg_attr(not(test), no_mangle)]
pub extern "C" fn __udivmodsi4(n: u32, d: u32, rem: Option<&mut u32>) -> u32 {
    #[cfg(all(feature = "c", target_arch = "arm", not(target_os = "ios")))]
    extern "C" {
        fn __udivsi3(n: u32, d: u32) -> u32;
    }

    let q = unsafe { __udivsi3(n, d) };
    if let Some(rem) = rem {
        *rem = n - (q * d);
    }
    q
}

/// Returns `n / d`
#[cfg_attr(not(test), no_mangle)]
#[cfg(not(all(feature = "c", target_arch = "x86")))]
pub extern "C" fn __udivdi3(n: u64, d: u64) -> u64 {
    __udivmoddi4(n, d, None)
}

/// Returns `n % d`
#[cfg(not(all(feature = "c", target_arch = "x86")))]
#[cfg_attr(not(test), no_mangle)]
pub extern "C" fn __umoddi3(a: u64, b: u64) -> u64 {
    let mut rem = unsafe { mem::uninitialized() };
    __udivmoddi4(a, b, Some(&mut rem));
    rem
}

/// Returns `n / d` and sets `*rem = n % d`
#[cfg_attr(not(test), no_mangle)]
pub extern "C" fn __udivmoddi4(n: u64, d: u64, rem: Option<&mut u64>) -> u64 {
    // NOTE X is unknown, K != 0
    if n.high() == 0 {
        if d.high() == 0 {
            // 0 X
            // ---
            // 0 X
            if let Some(rem) = rem {
                *rem = u64::from(n.low() % d.low());
            }
            return u64::from(n.low() / d.low());
        } else {
            // 0 X
            // ---
            // K X
            if let Some(rem) = rem {
                *rem = n;
            }
            return 0;
        };
    }

    let mut sr;
    let mut q;
    let mut r;

    if d.low() == 0 {
        if d.high() == 0 {
            // K X
            // ---
            // 0 0
            panic!("Division by zero");
        }

        if n.low() == 0 {
            // K 0
            // ---
            // K 0
            if let Some(rem) = rem {
                *rem = u64::from_parts(0, n.high() % d.high());
            }
            return u64::from(n.high() / d.high());
        }

        // K K
        // ---
        // K 0

        if d.high().is_power_of_two() {
            if let Some(rem) = rem {
                *rem = u64::from_parts(n.low(), n.high() & (d.high() - 1));
            }
            return u64::from(n.high() >> d.high().trailing_zeros());
        }

        sr = d.high().leading_zeros().wrapping_sub(n.high().leading_zeros());

        // D > N
        if sr > u32::bits() - 2 {
            if let Some(rem) = rem {
                *rem = n;
            }
            return 0;
        }

        sr += 1;

        // 1 <= sr <= u32::bits() - 1
        q = n << (u64::bits() - sr);
        r = n >> sr;
    } else {
        if d.high() == 0 {
            // K X
            // ---
            // 0 K
            if d.low().is_power_of_two() {
                if let Some(rem) = rem {
                    *rem = u64::from(n.low() & (d.low() - 1));
                }

                if d.low() == 1 {
                    return n;
                } else {
                    let sr = d.low().trailing_zeros();
                    return n >> sr;
                };
            }

            sr = 1 + u32::bits() + d.low().leading_zeros() - n.high().leading_zeros();

            // 2 <= sr <= u64::bits() - 1
            q = n << (u64::bits() - sr);
            r = n >> sr;
        } else {
            // K X
            // ---
            // K K
            sr = d.high().leading_zeros().wrapping_sub(n.high().leading_zeros());

            // D > N
            if sr > u32::bits() - 1 {
                if let Some(rem) = rem {
                    *rem = n;
                }
                return 0;
            }

            sr += 1;

            // 1 <= sr <= u32::bits()
            q = n << (u64::bits() - sr);
            r = n >> sr;
        }
    }

    // Not a special case
    // q and r are initialized with
    // q = n << (u64::bits() - sr)
    // r = n >> sr
    // 1 <= sr <= u64::bits() - 1
    let mut carry = 0;

    for _ in 0..sr {
        // r:q = ((r:q) << 1) | carry
        r = (r << 1) | (q >> (u64::bits() - 1));
        q = (q << 1) | carry as u64;

        // carry = 0
        // if r >= d {
        //     r -= d;
        //     carry = 1;
        // }
        let s = (d.wrapping_sub(r).wrapping_sub(1)) as i64 >> (u64::bits() - 1);
        carry = (s & 1) as u32;
        r -= d & s as u64;
    }

    if let Some(rem) = rem {
        *rem = r;
    }
    (q << 1) | carry as u64
}

#[cfg(test)]
mod tests {
    use qc::{U32, U64};

    check! {
        fn __udivdi3(f: extern fn(u64, u64) -> u64, n: U64, d: U64) -> Option<u64> {
            let (n, d) = (n.0, d.0);
            if d == 0 {
                None
            } else {
                Some(f(n, d))
            }
        }

        fn __umoddi3(f: extern fn(u64, u64) -> u64, n: U64, d: U64) -> Option<u64> {
            let (n, d) = (n.0, d.0);
            if d == 0 {
                None
            } else {
                Some(f(n, d))
            }
        }

        fn __udivmoddi4(f: extern fn(u64, u64, Option<&mut u64>) -> u64,
                        n: U64,
                        d: U64) -> Option<(u64, u64)> {
            let (n, d) = (n.0, d.0);
            if d == 0 {
                None
            } else {
                let mut r = 0;
                let q = f(n, d, Some(&mut r));
                Some((q, r))
            }
        }

        fn __udivsi3(f: extern fn(u32, u32) -> u32, n: U32, d: U32) -> Option<u32> {
            let (n, d) = (n.0, d.0);
            if d == 0 {
                None
            } else {
                Some(f(n, d))
            }
        }

        fn __umodsi3(f: extern fn(u32, u32) -> u32, n: U32, d: U32) -> Option<u32> {
            let (n, d) = (n.0, d.0);
            if d == 0 {
                None
            } else {
                Some(f(n, d))
            }
        }

        fn __udivmodsi4(f: extern fn(u32, u32, Option<&mut u32>) -> u32,
                        n: U32,
                        d: U32) -> Option<(u32, u32)> {
            let (n, d) = (n.0, d.0);
            if d == 0 {
                None
            } else {
                let mut r = 0;
                let q = f(n, d, Some(&mut r));
                Some((q, r))
            }
        }
    }
}
<commit_msg>panic! -> abort<commit_after>use core::{intrinsics, mem};
use int::{Int, LargeInt};

/// Returns `n / d`
#[cfg(not(all(feature = "c", target_arch = "arm", not(target_os = "ios"), not(thumbv6m))))]
#[cfg_attr(not(test), no_mangle)]
pub extern "C" fn __udivsi3(n: u32, d: u32) -> u32 {
    // Special cases
    if d == 0 {
        // NOTE This should be unreachable in safe Rust because the program will panic before
        // this intrinsic is called
        unsafe {
            intrinsics::abort()
        }
    }

    if n == 0 {
        return 0;
    }

    let mut sr = d.leading_zeros().wrapping_sub(n.leading_zeros());

    // d > n
    if sr > u32::bits() - 1 {
        return 0;
    }

    // d == 1
    if sr == u32::bits() - 1 {
        return n;
    }

    sr += 1;

    // 1 <= sr <= u32::bits() - 1
    let mut q = n << (u32::bits() - sr);
    let mut r = n >> sr;

    let mut carry = 0;
    for _ in 0..sr {
        // r:q = ((r:q) << 1) | carry
        r = (r << 1) | (q >> (u32::bits() - 1));
        q = (q << 1) | carry;

        // carry = 0;
        // if r > d {
        //     r -= d;
        //     carry = 1;
        // }

        let s = (d.wrapping_sub(r).wrapping_sub(1)) as i32 >> (u32::bits() - 1);
        carry = (s & 1) as u32;
        r -= d & s as u32;
    }

    (q << 1) | carry
}

/// Returns `n % d`
#[cfg(not(all(feature = "c", target_arch = "arm", not(target_os = "ios"))))]
#[cfg_attr(not(test), no_mangle)]
pub extern "C" fn __umodsi3(n: u32, d: u32) -> u32 {
    #[cfg(all(feature = "c", target_arch = "arm", not(target_os = "ios")))]
    extern "C" {
        fn __udivsi3(n: u32, d: u32) -> u32;
    }

    n - unsafe { __udivsi3(n, d) * d }
}

/// Returns `n / d` and sets `*rem = n % d`
#[cfg(not(all(feature = "c", target_arch = "arm", not(target_os = "ios"), not(thumbv6m))))]
#[cfg_attr(not(test), no_mangle)]
pub extern "C" fn __udivmodsi4(n: u32, d: u32, rem: Option<&mut u32>) -> u32 {
    #[cfg(all(feature = "c", target_arch = "arm", not(target_os = "ios")))]
    extern "C" {
        fn __udivsi3(n: u32, d: u32) -> u32;
    }

    let q = unsafe { __udivsi3(n, d) };
    if let Some(rem) = rem {
        *rem = n - (q * d);
    }
    q
}

/// Returns `n / d`
#[cfg_attr(not(test), no_mangle)]
#[cfg(not(all(feature = "c", target_arch = "x86")))]
pub extern "C" fn __udivdi3(n: u64, d: u64) -> u64 {
    __udivmoddi4(n, d, None)
}

/// Returns `n % d`
#[cfg(not(all(feature = "c", target_arch = "x86")))]
#[cfg_attr(not(test), no_mangle)]
pub extern "C" fn __umoddi3(a: u64, b: u64) -> u64 {
    let mut rem = unsafe { mem::uninitialized() };
    __udivmoddi4(a, b, Some(&mut rem));
    rem
}

/// Returns `n / d` and sets `*rem = n % d`
#[cfg_attr(not(test), no_mangle)]
pub extern "C" fn __udivmoddi4(n: u64, d: u64, rem: Option<&mut u64>) -> u64 {
    // NOTE X is unknown, K != 0
    if n.high() == 0 {
        if d.high() == 0 {
            // 0 X
            // ---
            // 0 X
            if let Some(rem) = rem {
                *rem = u64::from(n.low() % d.low());
            }
            return u64::from(n.low() / d.low());
        } else {
            // 0 X
            // ---
            // K X
            if let Some(rem) = rem {
                *rem = n;
            }
            return 0;
        };
    }

    let mut sr;
    let mut q;
    let mut r;

    if d.low() == 0 {
        if d.high() == 0 {
            // K X
            // ---
            // 0 0
            // NOTE This should be unreachable in safe Rust because the program will panic before
            // this intrinsic is called
            unsafe {
                intrinsics::abort()
            }
        }

        if n.low() == 0 {
            // K 0
            // ---
            // K 0
            if let Some(rem) = rem {
                *rem = u64::from_parts(0, n.high() % d.high());
            }
            return u64::from(n.high() / d.high());
        }

        // K K
        // ---
        // K 0

        if d.high().is_power_of_two() {
            if let Some(rem) = rem {
                *rem = u64::from_parts(n.low(), n.high() & (d.high() - 1));
            }
            return u64::from(n.high() >> d.high().trailing_zeros());
        }

        sr = d.high().leading_zeros().wrapping_sub(n.high().leading_zeros());

        // D > N
        if sr > u32::bits() - 2 {
            if let Some(rem) = rem {
                *rem = n;
            }
            return 0;
        }

        sr += 1;

        // 1 <= sr <= u32::bits() - 1
        q = n << (u64::bits() - sr);
        r = n >> sr;
    } else {
        if d.high() == 0 {
            // K X
            // ---
            // 0 K
            if d.low().is_power_of_two() {
                if let Some(rem) = rem {
                    *rem = u64::from(n.low() & (d.low() - 1));
                }

                if d.low() == 1 {
                    return n;
                } else {
                    let sr = d.low().trailing_zeros();
                    return n >> sr;
                };
            }

            sr = 1 + u32::bits() + d.low().leading_zeros() - n.high().leading_zeros();

            // 2 <= sr <= u64::bits() - 1
            q = n << (u64::bits() - sr);
            r = n >> sr;
        } else {
            // K X
            // ---
            // K K
            sr = d.high().leading_zeros().wrapping_sub(n.high().leading_zeros());

            // D > N
            if sr > u32::bits() - 1 {
                if let Some(rem) = rem {
                    *rem = n;
                }
                return 0;
            }

            sr += 1;

            // 1 <= sr <= u32::bits()
            q = n << (u64::bits() - sr);
            r = n >> sr;
        }
    }

    // Not a special case
    // q and r are initialized with
    // q = n << (u64::bits() - sr)
    // r = n >> sr
    // 1 <= sr <= u64::bits() - 1
    let mut carry = 0;

    for _ in 0..sr {
        // r:q = ((r:q) << 1) | carry
        r = (r << 1) | (q >> (u64::bits() - 1));
        q = (q << 1) | carry as u64;

        // carry = 0
        // if r >= d {
        //     r -= d;
        //     carry = 1;
        // }
        let s = (d.wrapping_sub(r).wrapping_sub(1)) as i64 >> (u64::bits() - 1);
        carry = (s & 1) as u32;
        r -= d & s as u64;
    }

    if let Some(rem) = rem {
        *rem = r;
    }
    (q << 1) | carry as u64
}

#[cfg(test)]
mod tests {
    use qc::{U32, U64};

    check! {
        fn __udivdi3(f: extern fn(u64, u64) -> u64, n: U64, d: U64) -> Option<u64> {
            let (n, d) = (n.0, d.0);
            if d == 0 {
                None
            } else {
                Some(f(n, d))
            }
        }

        fn __umoddi3(f: extern fn(u64, u64) -> u64, n: U64, d: U64) -> Option<u64> {
            let (n, d) = (n.0, d.0);
            if d == 0 {
                None
            } else {
                Some(f(n, d))
            }
        }

        fn __udivmoddi4(f: extern fn(u64, u64, Option<&mut u64>) -> u64,
                        n: U64,
                        d: U64) -> Option<(u64, u64)> {
            let (n, d) = (n.0, d.0);
            if d == 0 {
                None
            } else {
                let mut r = 0;
                let q = f(n, d, Some(&mut r));
                Some((q, r))
            }
        }

        fn __udivsi3(f: extern fn(u32, u32) -> u32, n: U32, d: U32) -> Option<u32> {
            let (n, d) = (n.0, d.0);
            if d == 0 {
                None
            } else {
                Some(f(n, d))
            }
        }

        fn __umodsi3(f: extern fn(u32, u32) -> u32, n: U32, d: U32) -> Option<u32> {
            let (n, d) = (n.0, d.0);
            if d == 0 {
                None
            } else {
                Some(f(n, d))
            }
        }

        fn __udivmodsi4(f: extern fn(u32, u32, Option<&mut u32>) -> u32,
                        n: U32,
                        d: U32) -> Option<(u32, u32)> {
            let (n, d) = (n.0, d.0);
            if d == 0 {
                None
            } else {
                let mut r = 0;
                let q = f(n, d, Some(&mut r));
                Some((q, r))
            }
        }
    }
}
<|endoftext|>


<commit_before>#[macro_use(assert_diff)]
extern crate difference;
extern crate env_logger;
#[macro_use]
extern crate pretty_assertions;

extern crate gluon;
extern crate gluon_base as base;
extern crate gluon_format as format;

use std::env;
use std::fs::File;
use std::io::{Read, Write};
use std::path::Path;

use gluon::{Compiler, VmBuilder};

fn format_expr(expr: &str) -> gluon::Result<String> {
    let mut compiler = Compiler::new();
    let thread = VmBuilder::new()
        .import_paths(Some(vec!["..".into()]))
        .build();
    format::format_expr(&mut compiler, &thread, "test", expr)
}

fn format_expr_expanded(expr: &str) -> gluon::Result<String> {
    let mut compiler = Compiler::new();
    let thread = VmBuilder::new()
        .import_paths(Some(vec!["..".into()]))
        .build();
    format::Formatter { expanded: true }.format_expr(&mut compiler, &thread, "test", expr)
}

fn test_format(name: &str) {
    let _ = env_logger::try_init();

    let mut contents = String::new();
    File::open(Path::new("../").join(name))
        .unwrap()
        .read_to_string(&mut contents)
        .unwrap();

    let mut compiler = Compiler::new();
    let thread = VmBuilder::new()
        .import_paths(Some(vec!["..".into()]))
        .build();
    let out_str = format::format_expr(&mut compiler, &thread, name, &contents)
        .unwrap_or_else(|err| panic!("{}", err));

    if contents != out_str {
        let args: Vec<_> = env::args().collect();
        let out_path = Path::new(&args[0][..])
            .parent()
            .and_then(|p| p.parent())
            .expect("folder")
            .join(Path::new(name).file_name().unwrap());
        File::create(out_path)
            .unwrap()
            .write_all(out_str.as_bytes())
            .unwrap();

        assert_diff!(&contents, &out_str, " ", 0);
    }
}

#[test]
fn bool() {
    test_format("std/bool.glu");
}

#[test]
fn char() {
    test_format("std/char.glu");
}

#[test]
fn function() {
    test_format("std/function.glu");
}

#[test]
fn map() {
    test_format("std/map.glu");
}

#[test]
fn option() {
    test_format("std/option.glu");
}

#[test]
fn prelude() {
    test_format("std/prelude.glu");
}

#[test]
fn result() {
    test_format("std/result.glu");
}

#[test]
fn state() {
    test_format("std/state.glu");
}

#[test]
fn stream() {
    test_format("std/stream.glu");
}

#[test]
fn string() {
    test_format("std/string.glu");
}

#[test]
fn test() {
    test_format("std/test.glu");
}

#[test]
fn types() {
    test_format("std/types.glu");
}

#[test]
fn unit() {
    test_format("std/unit.glu");
}

#[test]
fn writer() {
    test_format("std/writer.glu");
}

#[test]
fn parser() {
    test_format("std/parser.glu");
}

#[test]
fn random() {
    test_format("std/random.glu");
}

#[test]
fn repl() {
    test_format("repl/src/repl.glu");
}

#[test]
fn dont_add_newline_for_let_literal() {
    let expr = r#"
let x = 1
x
"#;
    assert_eq!(
        &format_expr(expr).unwrap(),
        r#"
let x = 1
x
"#
    );
}

#[test]
fn dont_lose_information_in_literals() {
    let expr = r#"
3.14 "\t\n\r\""
"#;
    assert_eq!(&format_expr(expr).unwrap(), expr);
}

#[test]
fn raw_string_literal() {
    let expr = r####"
r##"abc
    "  "##
"####;
    assert_eq!(&format_expr(expr).unwrap(), expr);
}

#[test]
fn implicit_arg() {
    let expr = r#"
f ?32 ""
"#;
    assert_eq!(&format_expr(expr).unwrap(), expr);
}

#[test]
fn preserve_comment_between_let_in() {
    let expr = r#"
// test1
let x = 1
// test2
type Test = Int
// test3
1
// test4
"#;
    assert_diff!(&format_expr(expr).unwrap(), expr, " ", 0);
}

#[test]
fn preserve_whitespace_in_record() {
    let expr = r#"
{
    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaax = 1,

    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbby = 2,
}
"#;
    assert_diff!(&format_expr(expr).unwrap(), expr, " ", 0);
}

#[test]
fn preserve_block_comments() {
    let expr = r#"
/* test */
let x = { field = f /* test */ 123 /* doc */ }
/* test */
x
"#;
    assert_eq!(&format_expr(expr).unwrap(), expr);
}

// TODO
#[test]
fn preserve_more_block_comments() {
    let expr = r#"
{ /* abc */ field /* abc */ = /* test */ 123 }
"#;
    assert_eq!(&format_expr(expr).unwrap(), expr);
}

#[test]
fn preserve_shebang_line() {
    let expr = r#"#!/bin/gluon
/* test */
let x = { field = f /* test */ 123 /* doc */ }
/* test */
x
"#;
    assert_eq!(&format_expr(expr).unwrap(), expr);
}

#[test]
fn nested_constructor_pattern() {
    let expr = r#"
match None with
| Some (Some x) -> x
| _ -> 123
"#;
    assert_eq!(&format_expr(expr).unwrap(), expr);
}

#[test]
fn long_pattern_match() {
    let expr = r#"
let {
    CCCCCCCCCCCCCC,
    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,
    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
} =
    test
123
"#;
    assert_eq!(&format_expr(expr).unwrap(), expr);
}

#[test]
fn preserve_comments_in_function_types() {
    let expr = r#"#!/bin/gluon
let x : /* first */ Int /* Int */ ->
        // Float
        Float /* last */ = ()
x
"#;
    assert_diff!(&format_expr(expr).unwrap(), expr, " ", 0);
}

#[test]
fn preserve_comments_app_types() {
    let expr = r#"#!/bin/gluon
let x : Test /* first */ Int
        // middle
        Float /* last */ = ()
x
"#;
    assert_diff!(&format_expr(expr).unwrap(), expr, " ", 0);
}

#[test]
fn preserve_doc_comments_in_record_types() {
    let expr = r#"#!/bin/gluon
type Test = {
    /// test
    field1 : Int,
    /**
     middle
    */
    field2 : Float
}
x
"#;
    assert_diff!(&format_expr(expr).unwrap(), expr, " ", 0);
}

#[test]
fn doc_comment_in_record_expr() {
    let expr = r#"
{
    /// test
    /// test
    field1 = 1,
}
"#;
    assert_diff!(&format_expr(expr).unwrap(), expr, " ", 0);
}

#[test]
fn preserve_comments_in_empty_record() {
    let expr = r#"
{
// 123
}
"#;
    assert_diff!(&format_expr(expr).unwrap(), expr, " ", 0);
}

#[test]
fn preserve_comments_in_record_base() {
    let expr = r#"
{
    // 123
    ..
    // abc
    test
/* x */
}
"#;
    assert_diff!(&format_expr(expr).unwrap(), expr, " ", 0);
}

#[test]
fn small_record_in_let() {
    let expr = r#"
let semigroup =
    { append }
()
"#;
    assert_diff!(&format_expr(expr).unwrap(), expr, " ", 0);
}

#[test]
fn do_expression() {
    let expr = r#"
do /* x1 */ x /* x2 */ = Some 1
// test
test abc 1232 ""
"#;
    assert_diff!(&format_expr(expr).unwrap(), expr, " ", 0);
}

#[test]
fn if_else_multiple() {
    let expr = r#"
if x
then y
else if z
then w
else 0
"#;
    assert_diff!(&format_expr(expr).unwrap(), expr, " ", 0);
}

#[test]
fn fully_break_function_type() {
    let expr = r#"
let traverse_with_key f m x : [Ord k]
        -> Applicative t
        -> (k -> a -> t b)
        -> Map k a
        -> ()
        -> ()
    =
    ()
()
"#;
    assert_diff!(&format_expr(expr).unwrap(), expr, " ", 0);
}

#[test]
fn comments_in_block_exprs() {
    let expr = r#"
// test
test 123

// test1

// test1

abc ""
// test2
"#;
    assert_diff!(&format_expr(expr).unwrap(), expr, " ", 0);
}

#[test]
#[ignore] // TODO
fn function_type_with_comments() {
    let expr = r#"
type Handler a =
    // Success continuation
    (a -> HttpState -> IO Response)
    // Failure continuation
    -> (Failure -> HttpState -> IO Response)
    -> IO Response
()
"#;
    assert_diff!(&format_expr(expr).unwrap(), expr, " ", 0);
}

#[test]
fn variant_type() {
    let expr = r#"
type TestCase a =
    | LoooooooooooooooooongTest String (() -> std.test.Test a)
    | LoooooooooooooooooooooooongGroup String (Array (std.test.TestCase a))
()
"#;
    assert_diff!(
        &format_expr(expr).unwrap_or_else(|err| panic!("{}", err)),
        expr,
        " ",
        0
    );
}

#[test]
fn multiline_string() {
    let expr = r#"
let x = "abc
        123
    "
x
"#;
    assert_diff!(&format_expr(expr).unwrap(), expr, " ", 0);
}

#[test]
fn derive_simple() {
    let expr = r#"
#[derive(Show)]
type Test =
    | Test
Test
"#;
    assert_diff!(&format_expr(expr).unwrap(), expr, " ", 0);
}

#[test]
fn derive_parameterized() {
    let expr = r#"
#[derive(Show)]
type Test a =
    | Test a
Test 1
"#;
    assert_diff!(&format_expr(expr).unwrap(), expr, " ", 0);
}

#[test]
fn derive_expanded() {
    let expr = r#"
#[derive(Show)]
type Test =
    | Test
Test
"#;
    let expected = r#"
#[derive(Show)]
type Test =
    | Test
let show_Test : Show Test =
    let show_ x : Test -> String =
        match x with
        | Test -> "Test"
    { show = show_ }
Test
"#;
    assert_diff!(&format_expr_expanded(expr).unwrap(), expected, "\n", 0);
}

#[test]
fn derive_eq_recursive_expanded() {
    let expr = r#"
#[derive(Eq)]
type Recursive = | End | Rec Recursive
End
"#;
    let expected = r#"
#[derive(Eq)]
type Recursive =
    | End
    | Rec Recursive
let eq_Recursive : Eq Recursive =
    let eq l r : Recursive -> Recursive -> _ =
        match (l, r) with
        | (End, End) -> True
        | (Rec arg_l, Rec arg_r) -> eq arg_l arg_r
        | _ -> False
    { (==) = eq }
End
"#;
    assert_diff!(&format_expr_expanded(expr).unwrap(), expected, "\n", 0);
}

#[test]
fn derive_parameterized_expended() {
    let expr = r#"
#[derive(Show)]
type Test a =
    | Test a
Test 1
"#;
    let expected = r#"
#[derive(Show)]
type Test a =
    | Test a
let show_Test : [Show a] -> Show (Test a) =
    let show_ x : Test a -> String =
        match x with
        | Test arg_0 -> "Test" ++ " " ++ "(" ++ show arg_0 ++ ")"
    { show = show_ }
Test 1
"#;
    assert_diff!(&format_expr_expanded(expr).unwrap(), expected, "\n", 0);
}

#[test]
fn derive_deserialize1() {
    let expr = r#"
#[derive(Deserialize)]
type Record = { x : Int }
()
"#;
    let expected = r#"
#[derive(Deserialize)]
type Record = { x : Int }
let deserialize_Record : Deserialize Record =
    let { ValueDeserializer } = import! std.serialization.de
    let { map } = import! std.functor
    let { (<*>) } = import! std.applicative
    let { (<|>) } = import! std.alternative
    let deserializer : ValueDeserializer Record = map (\x -> { x }) (field "x" deserializer)
    { deserializer = deserializer }
()
"#;
    assert_diff!(&format_expr_expanded(expr).unwrap(), expected, "\n", 0);
}

#[test]
fn derive_deserialize2() {
    let expr = r#"
#[derive(Deserialize)]
type Record = { x : Int, y : Float }
()
"#;
    let expected = r#"
#[derive(Deserialize)]
type Record = { x : Int, y : Float }
let deserialize_Record : Deserialize Record =
    let { ValueDeserializer } = import! std.serialization.de
    let { map } = import! std.functor
    let { (<*>) } = import! std.applicative
    let { (<|>) } = import! std.alternative
    let deserializer : ValueDeserializer Record
        = map (\x y -> { x, y }) (field "x" deserializer)
            <*> field "y" deserializer
    { deserializer = deserializer }
()
"#;
    assert_diff!(&format_expr_expanded(expr).unwrap(), expected, "\n", 0);
}
<commit_msg>test: Make format tests runnable from the root<commit_after>#[macro_use(assert_diff)]
extern crate difference;
extern crate env_logger;
#[macro_use]
extern crate pretty_assertions;

extern crate gluon;
extern crate gluon_base as base;
extern crate gluon_format as format;

use std::env;
use std::fs::File;
use std::io::{Read, Write};
use std::path::Path;

use gluon::{Compiler, RootedThread, VmBuilder};

fn new_vm() -> RootedThread {
    VmBuilder::new()
        .import_paths(Some(vec![".".into(), "..".into()]))
        .build()
}

fn format_expr(expr: &str) -> gluon::Result<String> {
    let mut compiler = Compiler::new();
    let thread = new_vm();
    format::format_expr(&mut compiler, &thread, "test", expr)
}

fn format_expr_expanded(expr: &str) -> gluon::Result<String> {
    let mut compiler = Compiler::new();
    let thread = new_vm();
    format::Formatter { expanded: true }.format_expr(&mut compiler, &thread, "test", expr)
}

fn test_format(name: &str) {
    let _ = env_logger::try_init();

    let mut contents = String::new();
    File::open(Path::new("../").join(name))
        .or_else(|_| File::open(name))
        .unwrap()
        .read_to_string(&mut contents)
        .unwrap();

    let mut compiler = Compiler::new();
    let thread = new_vm();
    let out_str = format::format_expr(&mut compiler, &thread, name, &contents)
        .unwrap_or_else(|err| panic!("{}", err));

    if contents != out_str {
        let args: Vec<_> = env::args().collect();
        let out_path = Path::new(&args[0][..])
            .parent()
            .and_then(|p| p.parent())
            .expect("folder")
            .join(Path::new(name).file_name().unwrap());
        File::create(out_path)
            .unwrap()
            .write_all(out_str.as_bytes())
            .unwrap();

        assert_diff!(&contents, &out_str, " ", 0);
    }
}

#[test]
fn bool() {
    test_format("std/bool.glu");
}

#[test]
fn char() {
    test_format("std/char.glu");
}

#[test]
fn function() {
    test_format("std/function.glu");
}

#[test]
fn map() {
    test_format("std/map.glu");
}

#[test]
fn option() {
    test_format("std/option.glu");
}

#[test]
fn prelude() {
    test_format("std/prelude.glu");
}

#[test]
fn result() {
    test_format("std/result.glu");
}

#[test]
fn state() {
    test_format("std/state.glu");
}

#[test]
fn stream() {
    test_format("std/stream.glu");
}

#[test]
fn string() {
    test_format("std/string.glu");
}

#[test]
fn test() {
    test_format("std/test.glu");
}

#[test]
fn types() {
    test_format("std/types.glu");
}

#[test]
fn unit() {
    test_format("std/unit.glu");
}

#[test]
fn writer() {
    test_format("std/writer.glu");
}

#[test]
fn parser() {
    test_format("std/parser.glu");
}

#[test]
fn random() {
    test_format("std/random.glu");
}

#[test]
fn repl() {
    test_format("repl/src/repl.glu");
}

#[test]
fn dont_add_newline_for_let_literal() {
    let expr = r#"
let x = 1
x
"#;
    assert_eq!(
        &format_expr(expr).unwrap(),
        r#"
let x = 1
x
"#
    );
}

#[test]
fn dont_lose_information_in_literals() {
    let expr = r#"
3.14 "\t\n\r\""
"#;
    assert_eq!(&format_expr(expr).unwrap(), expr);
}

#[test]
fn raw_string_literal() {
    let expr = r####"
r##"abc
    "  "##
"####;
    assert_eq!(&format_expr(expr).unwrap(), expr);
}

#[test]
fn implicit_arg() {
    let expr = r#"
f ?32 ""
"#;
    assert_eq!(&format_expr(expr).unwrap(), expr);
}

#[test]
fn preserve_comment_between_let_in() {
    let expr = r#"
// test1
let x = 1
// test2
type Test = Int
// test3
1
// test4
"#;
    assert_diff!(&format_expr(expr).unwrap(), expr, " ", 0);
}

#[test]
fn preserve_whitespace_in_record() {
    let expr = r#"
{
    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaax = 1,

    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbby = 2,
}
"#;
    assert_diff!(&format_expr(expr).unwrap(), expr, " ", 0);
}

#[test]
fn preserve_block_comments() {
    let expr = r#"
/* test */
let x = { field = f /* test */ 123 /* doc */ }
/* test */
x
"#;
    assert_eq!(&format_expr(expr).unwrap(), expr);
}

// TODO
#[test]
fn preserve_more_block_comments() {
    let expr = r#"
{ /* abc */ field /* abc */ = /* test */ 123 }
"#;
    assert_eq!(&format_expr(expr).unwrap(), expr);
}

#[test]
fn preserve_shebang_line() {
    let expr = r#"#!/bin/gluon
/* test */
let x = { field = f /* test */ 123 /* doc */ }
/* test */
x
"#;
    assert_eq!(&format_expr(expr).unwrap(), expr);
}

#[test]
fn nested_constructor_pattern() {
    let expr = r#"
match None with
| Some (Some x) -> x
| _ -> 123
"#;
    assert_eq!(&format_expr(expr).unwrap(), expr);
}

#[test]
fn long_pattern_match() {
    let expr = r#"
let {
    CCCCCCCCCCCCCC,
    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,
    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
} =
    test
123
"#;
    assert_eq!(&format_expr(expr).unwrap(), expr);
}

#[test]
fn preserve_comments_in_function_types() {
    let expr = r#"#!/bin/gluon
let x : /* first */ Int /* Int */ ->
        // Float
        Float /* last */ = ()
x
"#;
    assert_diff!(&format_expr(expr).unwrap(), expr, " ", 0);
}

#[test]
fn preserve_comments_app_types() {
    let expr = r#"#!/bin/gluon
let x : Test /* first */ Int
        // middle
        Float /* last */ = ()
x
"#;
    assert_diff!(&format_expr(expr).unwrap(), expr, " ", 0);
}

#[test]
fn preserve_doc_comments_in_record_types() {
    let expr = r#"#!/bin/gluon
type Test = {
    /// test
    field1 : Int,
    /**
     middle
    */
    field2 : Float
}
x
"#;
    assert_diff!(&format_expr(expr).unwrap(), expr, " ", 0);
}

#[test]
fn doc_comment_in_record_expr() {
    let expr = r#"
{
    /// test
    /// test
    field1 = 1,
}
"#;
    assert_diff!(&format_expr(expr).unwrap(), expr, " ", 0);
}

#[test]
fn preserve_comments_in_empty_record() {
    let expr = r#"
{
// 123
}
"#;
    assert_diff!(&format_expr(expr).unwrap(), expr, " ", 0);
}

#[test]
fn preserve_comments_in_record_base() {
    let expr = r#"
{
    // 123
    ..
    // abc
    test
/* x */
}
"#;
    assert_diff!(&format_expr(expr).unwrap(), expr, " ", 0);
}

#[test]
fn small_record_in_let() {
    let expr = r#"
let semigroup =
    { append }
()
"#;
    assert_diff!(&format_expr(expr).unwrap(), expr, " ", 0);
}

#[test]
fn do_expression() {
    let expr = r#"
do /* x1 */ x /* x2 */ = Some 1
// test
test abc 1232 ""
"#;
    assert_diff!(&format_expr(expr).unwrap(), expr, " ", 0);
}

#[test]
fn if_else_multiple() {
    let expr = r#"
if x
then y
else if z
then w
else 0
"#;
    assert_diff!(&format_expr(expr).unwrap(), expr, " ", 0);
}

#[test]
fn fully_break_function_type() {
    let expr = r#"
let traverse_with_key f m x : [Ord k]
        -> Applicative t
        -> (k -> a -> t b)
        -> Map k a
        -> ()
        -> ()
    =
    ()
()
"#;
    assert_diff!(&format_expr(expr).unwrap(), expr, " ", 0);
}

#[test]
fn comments_in_block_exprs() {
    let expr = r#"
// test
test 123

// test1

// test1

abc ""
// test2
"#;
    assert_diff!(&format_expr(expr).unwrap(), expr, " ", 0);
}

#[test]
#[ignore] // TODO
fn function_type_with_comments() {
    let expr = r#"
type Handler a =
    // Success continuation
    (a -> HttpState -> IO Response)
    // Failure continuation
    -> (Failure -> HttpState -> IO Response)
    -> IO Response
()
"#;
    assert_diff!(&format_expr(expr).unwrap(), expr, " ", 0);
}

#[test]
fn variant_type() {
    let expr = r#"
type TestCase a =
    | LoooooooooooooooooongTest String (() -> std.test.Test a)
    | LoooooooooooooooooooooooongGroup String (Array (std.test.TestCase a))
()
"#;
    assert_diff!(
        &format_expr(expr).unwrap_or_else(|err| panic!("{}", err)),
        expr,
        " ",
        0
    );
}

#[test]
fn multiline_string() {
    let expr = r#"
let x = "abc
        123
    "
x
"#;
    assert_diff!(&format_expr(expr).unwrap(), expr, " ", 0);
}

#[test]
fn derive_simple() {
    let expr = r#"
#[derive(Show)]
type Test =
    | Test
Test
"#;
    assert_diff!(&format_expr(expr).unwrap(), expr, " ", 0);
}

#[test]
fn derive_parameterized() {
    let expr = r#"
#[derive(Show)]
type Test a =
    | Test a
Test 1
"#;
    assert_diff!(&format_expr(expr).unwrap(), expr, " ", 0);
}

#[test]
fn derive_expanded() {
    let expr = r#"
#[derive(Show)]
type Test =
    | Test
Test
"#;
    let expected = r#"
#[derive(Show)]
type Test =
    | Test
let show_Test : Show Test =
    let show_ x : Test -> String =
        match x with
        | Test -> "Test"
    { show = show_ }
Test
"#;
    assert_diff!(&format_expr_expanded(expr).unwrap(), expected, "\n", 0);
}

#[test]
fn derive_eq_recursive_expanded() {
    let expr = r#"
#[derive(Eq)]
type Recursive = | End | Rec Recursive
End
"#;
    let expected = r#"
#[derive(Eq)]
type Recursive =
    | End
    | Rec Recursive
let eq_Recursive : Eq Recursive =
    let eq l r : Recursive -> Recursive -> _ =
        match (l, r) with
        | (End, End) -> True
        | (Rec arg_l, Rec arg_r) -> eq arg_l arg_r
        | _ -> False
    { (==) = eq }
End
"#;
    assert_diff!(&format_expr_expanded(expr).unwrap(), expected, "\n", 0);
}

#[test]
fn derive_parameterized_expended() {
    let expr = r#"
#[derive(Show)]
type Test a =
    | Test a
Test 1
"#;
    let expected = r#"
#[derive(Show)]
type Test a =
    | Test a
let show_Test : [Show a] -> Show (Test a) =
    let show_ x : Test a -> String =
        match x with
        | Test arg_0 -> "Test" ++ " " ++ "(" ++ show arg_0 ++ ")"
    { show = show_ }
Test 1
"#;
    assert_diff!(&format_expr_expanded(expr).unwrap(), expected, "\n", 0);
}

#[test]
fn derive_deserialize1() {
    let expr = r#"
#[derive(Deserialize)]
type Record = { x : Int }
()
"#;
    let expected = r#"
#[derive(Deserialize)]
type Record = { x : Int }
let deserialize_Record : Deserialize Record =
    let { ValueDeserializer } = import! std.serialization.de
    let { map } = import! std.functor
    let { (<*>) } = import! std.applicative
    let { (<|>) } = import! std.alternative
    let deserializer : ValueDeserializer Record = map (\x -> { x }) (field "x" deserializer)
    { deserializer = deserializer }
()
"#;
    assert_diff!(&format_expr_expanded(expr).unwrap(), expected, "\n", 0);
}

#[test]
fn derive_deserialize2() {
    let expr = r#"
#[derive(Deserialize)]
type Record = { x : Int, y : Float }
()
"#;
    let expected = r#"
#[derive(Deserialize)]
type Record = { x : Int, y : Float }
let deserialize_Record : Deserialize Record =
    let { ValueDeserializer } = import! std.serialization.de
    let { map } = import! std.functor
    let { (<*>) } = import! std.applicative
    let { (<|>) } = import! std.alternative
    let deserializer : ValueDeserializer Record
        = map (\x y -> { x, y }) (field "x" deserializer)
            <*> field "y" deserializer
    { deserializer = deserializer }
()
"#;
    assert_diff!(&format_expr_expanded(expr).unwrap(), expected, "\n", 0);
}
<|endoftext|>


<commit_before>use std::io::Write;
use hyper::header::{ContentLength, ContentType};
use hyper::server::{Request, Response};
use hyper::status::StatusCode;
use hyper::uri::RequestUri;

macro_rules! dispatch {
    ($m0:expr => $h0:expr, $($m1:expr => $h1:expr,)*) => {{
        if $m0 { $h0 } $( else if $m1 { $h1 } )*
    }}
}

trait MakeResponse {
    fn status(&self) -> StatusCode {
        StatusCode::Ok
    }

    fn content_type(&self) -> ContentType {
        ContentType::plaintext()
    }

    fn content_length(&self) -> ContentLength {
        ContentLength(0)
    }

    fn content(&self) -> &[u8] {
        &[]
    }

    fn make_response(&self, mut response: Response) {
        *response.status_mut() = self.status();
        response.headers_mut().set(self.content_type());
        response.headers_mut().set(self.content_length());
        response.start().unwrap().write(self.content()).unwrap();
    }
}

impl MakeResponse for StatusCode {
    fn status(&self) -> StatusCode {
        *self
    }
}

impl MakeResponse for String {
    fn content_type(&self) -> ContentType {
        ContentType::html()
    }

    fn content_length(&self) -> ContentLength {
        ContentLength(self.as_bytes().len() as u64)
    }

    fn content(&self) -> &[u8] {
        self.as_bytes()
    }
}

pub fn get(request: Request, response: Response) {
    println!("** Handling GET {}", request.uri);
    println!("** Incoming headers {:?}", request.headers);
    if let RequestUri::AbsolutePath(ref path) = request.uri {
        dispatch![
            path == "/" => index().make_response(response),
            path == "/ip" => origin(&request).make_response(response),
            path.starts_with("/status/") => status(path).make_response(response),
            path.starts_with("/test") => test(&request).make_response(response),
            true => notfound404().make_response(response),
        ];
    }
}

struct Text(String);

impl MakeResponse for Text {
    fn content_type(&self) -> ContentType {
        ContentType::plaintext()
    }

    fn content_length(&self) -> ContentLength {
        ContentLength(self.0.as_bytes().len() as u64)
    }

    fn content(&self) -> &[u8] {
        self.0.as_bytes()
    }
}

fn notfound404() -> String {
    String::from("<!DOCTYPE html>

            <title>404 Not Found</title>

Not Found

The requested URL was not found on the server.
        If you entered the URL manually please check your spelling and try again.

    ")
}

fn index() -> String {
    String::from("<!DOCTYPE html>

            <link
                rel=\"icon\"
                href=\"http://investorintel.com/wp-content/uploads/2014/03/tin-can.jpg\"/>
            <title>HTTPTIN</title>

HTTPTIN - HTTP tester in Rust and Rocket

    ")
}

fn status(path: &str) -> StatusCode {
    // /status/xx
    // 0123456789
    let (_, param) = path.split_at(8);
    match param.parse::<u16>() {
        Ok(status) => StatusCode::from_u16(status),
        Err(_) => StatusCode::BadRequest,
    }
}

fn origin(request: &Request) -> Text {
    Text(format!("origin: {}", request.remote_addr))
}

fn test(request: &Request) -> String {
    format!("<!DOCTYPE html>

            <title>HTTPTIN TEST</title>

            Remote Address: {}

            Method: {}

            HTTPVersion: {}

            Headers: {}

            URI: {}

    ",
            request.remote_addr,
            request.method,
            request.version,
            request.headers,
            request.uri)
}
<commit_msg>Change output type handling<commit_after>use std::io::Write;
use hyper::header::{ContentLength, ContentType};
use hyper::server::{Request, Response};
use hyper::status::StatusCode;
use hyper::uri::RequestUri;

macro_rules! dispatch {
    ($m0:expr => $h0:expr, $($m1:expr => $h1:expr,)*) => {{
        if $m0 { $h0 } $( else if $m1 { $h1 } )*
    }}
}

trait MakeResponse {
    fn status(&self) -> StatusCode {
        StatusCode::Ok
    }

    fn content_type(&self) -> ContentType {
        ContentType::plaintext()
    }

    fn content_length(&self) -> ContentLength {
        ContentLength(0)
    }

    fn content(&self) -> &[u8] {
        &[]
    }

    fn make_response(&self, mut response: Response) {
        *response.status_mut() = self.status();
        response.headers_mut().set(self.content_type());
        response.headers_mut().set(self.content_length());
        response.start().unwrap().write(self.content()).unwrap();
    }
}

impl MakeResponse for StatusCode {
    fn status(&self) -> StatusCode {
        *self
    }
}

struct Html(String);

impl MakeResponse for Html {
    fn content_type(&self) -> ContentType {
        ContentType::html()
    }

    fn content_length(&self) -> ContentLength {
        ContentLength(self.0.as_bytes().len() as u64)
    }

    fn content(&self) -> &[u8] {
        self.0.as_bytes()
    }
}

impl MakeResponse for String {
    fn content_type(&self) -> ContentType {
        ContentType::plaintext()
    }

    fn content_length(&self) -> ContentLength {
        ContentLength(self.as_bytes().len() as u64)
    }

    fn content(&self) -> &[u8] {
        self.as_bytes()
    }
}

pub fn get(request: Request, response: Response) {
    println!("** Handling GET {}", request.uri);
    println!("** Incoming headers {:?}", request.headers);
    if let RequestUri::AbsolutePath(ref path) = request.uri {
        dispatch![
            path == "/" => index().make_response(response),
            path == "/ip" => origin(&request).make_response(response),
            path.starts_with("/status/") => status(path).make_response(response),
            path.starts_with("/test") => test(&request).make_response(response),
            true => notfound404().make_response(response),
        ];
    }
}

fn notfound404() -> Html {
    Html(String::from("<!DOCTYPE html>

            <title>404 Not Found</title>

Not Found

The requested URL was not found on the server.
        If you entered the URL manually please check your spelling and try again.

    "))
}

fn index() -> Html {
    Html(String::from("<!DOCTYPE html>

            <link
                rel=\"icon\"
                href=\"http://investorintel.com/wp-content/uploads/2014/03/tin-can.jpg\"/>
            <title>HTTPTIN</title>

HTTPTIN - HTTP tester in Rust and Rocket

    "))
}

fn status(path: &str) -> StatusCode {
    // /status/xx
    // 0123456789
    let (_, param) = path.split_at(8);
    match param.parse::<u16>() {
        Ok(status) => StatusCode::from_u16(status),
        Err(_) => StatusCode::BadRequest,
    }
}

fn origin(request: &Request) -> String {
    format!("origin: {}", request.remote_addr)
}

fn test(request: &Request) -> Html {
    Html(format!("<!DOCTYPE html>

            <title>HTTPTIN TEST</title>

            Remote Address: {}

            Method: {}

            HTTPVersion: {}

            Headers: {}

            URI: {}

    ",
                 request.remote_addr,
                 request.method,
                 request.version,
                 request.headers,
                 request.uri))
}
<|endoftext|>