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
use std::{
    error::Error,
    fmt::{self, Display, Formatter},
    ops::Deref,
    path::PathBuf,
    process::ExitStatus,
    sync::Arc,
};

#[derive(Debug, Clone, PartialEq)]
pub struct CompiledBinary(pub Arc<[u8]>);

impl From<Vec<u8>> for CompiledBinary {
    fn from(bytes: Vec<u8>) -> Self { CompiledBinary(bytes.into()) }
}

impl AsRef<[u8]> for CompiledBinary {
    fn as_ref(&self) -> &[u8] { &self.0 }
}

impl Deref for CompiledBinary {
    type Target = Arc<[u8]>;

    fn deref(&self) -> &Self::Target { &self.0 }
}

/// The result from compiling... Essentially a newtype'd `Result`.
#[derive(Debug)]
pub struct CompilationResult(pub Result<CompiledBinary, CompileError>);

#[derive(Debug)]
pub enum CompileError {
    BuildFailed(ExitStatus),
    DidntStart(std::io::Error),
    UnableToReadBinary {
        path: PathBuf,
        error: std::io::Error,
    },
}

impl Display for CompileError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            CompileError::BuildFailed(exit) => match exit.code() {
                Some(code) => {
                    write!(f, "Compilation failed with exit code {}", code,)
                },
                None => f.write_str("Compilation failed"),
            },
            CompileError::DidntStart(_) => {
                f.write_str("Unable to run the compiler. Is cargo installed?")
            },
            CompileError::UnableToReadBinary { path, .. } => {
                write!(f, "Unable to read \"{}\"", path.display())
            },
        }
    }
}

impl Error for CompileError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            CompileError::BuildFailed(_) => None,
            CompileError::DidntStart(e) => Some(e),
            CompileError::UnableToReadBinary { error, .. } => Some(error),
        }
    }
}