1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
#[macro_use]
extern crate log;
extern crate libc;
extern crate lru_cache;
extern crate wait_timeout;

use lru_cache::LruCache;

use std::io::Write;
use std::io;
use std::process::{Command, ExitStatus, Stdio};
use std::str::FromStr;
use std::sync::Mutex;
use std::time::Duration;

use docker::Container;
pub use branches::Branch;

mod docker;
mod branches;

pub struct Playpen {
    cache: Mutex<LruCache<CacheKey, (ExitStatus, Vec<u8>)>>,
}

#[derive(PartialEq, Eq, Hash)]
struct CacheKey {
    cmd: String,
    args: Vec<String>,
    input: String,
    branch: Branch,
}

impl Playpen {
    pub fn new() -> Playpen {
        Playpen {
            cache: Mutex::new(LruCache::new(256)),
        }
    }

    fn exec(&self,
            branch: Branch,
            cmd: &str,
            args: Vec<String>,
            input: String) -> io::Result<(ExitStatus, Vec<u8>)> {

        // Build key to look up
        let key = CacheKey {
            cmd: cmd.to_string(),
            args: args,
            input: input,
            branch: branch,
        };
        let mut cache = self.cache.lock().unwrap();
        if let Some(prev) = cache.get_mut(&key) {
            return Ok(prev.clone())
        }
        drop(cache);

        let container = try!(Container::new(cmd, &key.args, &[], branch.image()));

        let tuple = try!(container.run(key.input.as_bytes(), Duration::new(5, 0)));
        let (status, mut output, timeout) = tuple;
        if timeout {
            output.extend_from_slice(b"\ntimeout triggered!");
        }
        let mut cache = self.cache.lock().unwrap();
        if status.success() {
            cache.insert(key, (status.clone(), output.clone()));
        }
        Ok((status, output))
    }

    fn parse_output(raw: &[u8]) -> (String, String) {
        let mut split = raw.splitn(2, |b| *b == b'\xff');
        let compiler = String::from_utf8_lossy(split.next().unwrap_or(&[])).into_owned();
        let output = String::from_utf8_lossy(split.next().unwrap_or(&[])).into_owned();

        (compiler, output)
    }

    pub fn evaluate(&self, branch: Branch, code: String) -> io::Result<(ExitStatus, String, String)> {
        let (status, raw_output) = self.exec(branch, "/usr/local/bin/evaluate.sh", vec![], code)?;
        let (compiler, output) = Self::parse_output(&raw_output);
        Ok((status, compiler, output))
    }

    pub fn compile(&self, branch: Branch, code: String, emit: CompileOutput) -> io::Result<(ExitStatus, String, String)> {
        let args = emit.as_opts().iter().map(|x| String::from(*x)).collect();
        let (status, raw_output) = self.exec(branch, "/usr/local/bin/compile.sh", args, code)?;
        let (compiler, output) = Self::parse_output(&raw_output);
        Ok((status, compiler, output))
    }
}

#[derive(Copy, Clone, Debug)]
pub enum CompileOutput {
    Asm,
    Llvm,
}

impl CompileOutput {
    pub fn as_opts(&self) -> &'static [&'static str] {
        match *self {
            CompileOutput::Asm => &["--pass=asm"],
            CompileOutput::Llvm => &["--pass=ir"],
        }
    }
}

impl FromStr for CompileOutput {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "asm" => Ok(CompileOutput::Asm),
            "llvm-ir" => Ok(CompileOutput::Llvm),
            _ => Err(format!("unknown output format {}", s)),
        }
    }
}

/// Highlights compiled rustc output according to the given output format
pub fn highlight(output_format: CompileOutput, output: &str) -> String {
    let lexer = match output_format {
        CompileOutput::Asm => "gas",
        CompileOutput::Llvm => "llvm",
    };

    let mut child = Command::new("pygmentize")
                            .arg("-l")
                            .arg(lexer)
                            .arg("-f")
                            .arg("html")
                            .stdin(Stdio::piped())
                            .stdout(Stdio::piped())
                            .spawn().unwrap();
    child.stdin.take().unwrap().write_all(output.as_bytes()).unwrap();
    let output = child.wait_with_output().unwrap();
    assert!(output.status.success());
    String::from_utf8(output.stdout).unwrap()
}