use super::*;
use std::path::Path;
use std::fs;
pub struct Source {
source: String
}
impl Source {
pub fn open(path: &String) -> Result<Source, mtk::IOError> {
let mut source = Source {
source: String::new()
};
if !Path::new(&path).is_file() {
return Err(mtk::IOError::with_string(format!("'{}' is not a file", path)));
}
source.source = match fs::read_to_string(path) {
Ok(ok) => ok,
Err(err) => return Err(mtk::IOError::with_string(format!("could not read from file '{}': {}", path, err.to_string())))
};
Ok(source)
}
pub fn compile(&mut self) -> Result<Vec<u8>, CompilationError> {
let mut lexer = match Lexer::new(&self.source) {
Ok(ok) => ok,
Err(err) => return Err(CompilationError::with_string(format!("failed to create the lexer: {}", err.to_string())))
};
match lexer.res() {
Ok(_ok) => (),
Err(err) => return Err(CompilationError::with_string(format!("failed to lex the source ('{}'): {}", self.source, err.to_string())))
};
let res = compile(&lexer)?;
Ok(res)
}
pub fn to_string(&self) -> String {
format!("{}", self.source)
}
}