edlang/lib/edlang_driver/tests/common.rs

71 lines
2 KiB
Rust
Raw Normal View History

2024-02-14 07:53:47 +00:00
use std::{
path::{Path, PathBuf},
2024-02-16 10:48:15 +00:00
process::Child,
2024-02-14 07:53:47 +00:00
};
use ariadne::Source;
2024-03-11 11:02:14 +00:00
use edlang_driver::linker::{link_binary, link_shared_lib};
2024-02-14 07:53:47 +00:00
use edlang_lowering::lower_modules;
use edlang_session::{DebugInfo, OptLevel, Session};
use tempfile::TempDir;
#[derive(Debug)]
pub struct CompileResult {
pub folder: TempDir,
pub object_file: PathBuf,
pub binary_file: PathBuf,
}
pub fn compile_program(
source: &str,
name: &str,
library: bool,
) -> Result<CompileResult, Box<dyn std::error::Error>> {
2024-03-13 10:12:36 +00:00
let module = edlang_parser::parse_ast(source, name).unwrap();
2024-02-14 07:53:47 +00:00
2024-03-11 11:02:14 +00:00
let test_dir = tempfile::tempdir().unwrap();
let test_dir_path = test_dir.path().canonicalize()?;
let output_file = test_dir_path.join(PathBuf::from(name));
2024-02-14 07:53:47 +00:00
let output_file = if library {
output_file.with_extension(Session::get_platform_library_ext())
} else if cfg!(target_os = "windows") {
output_file.with_extension("exe")
} else {
output_file.with_extension("")
};
2024-03-11 11:02:14 +00:00
let input_file = output_file.with_extension("ed");
std::fs::write(&input_file, source)?;
2024-02-14 07:53:47 +00:00
let session = Session {
2024-03-11 11:02:14 +00:00
file_paths: vec![input_file],
2024-02-14 07:53:47 +00:00
debug_info: DebugInfo::Full,
optlevel: OptLevel::Default,
2024-03-11 11:02:14 +00:00
sources: vec![Source::from(source.to_string())],
2024-02-14 07:53:47 +00:00
library,
output_file,
output_llvm: false,
output_asm: false,
};
2024-03-13 10:12:36 +00:00
let program_ir = lower_modules(&[module]).unwrap();
2024-02-14 07:53:47 +00:00
2024-03-11 11:02:14 +00:00
let object_path = edlang_codegen_llvm::compile(&session, &program_ir).unwrap();
2024-02-14 07:53:47 +00:00
if library {
2024-03-11 11:02:14 +00:00
link_shared_lib(&[object_path.clone()], &session.output_file).unwrap();
2024-02-14 07:53:47 +00:00
} else {
2024-03-11 11:02:14 +00:00
link_binary(&[object_path.clone()], &session.output_file).unwrap();
2024-02-14 07:53:47 +00:00
}
Ok(CompileResult {
folder: test_dir,
object_file: object_path,
binary_file: session.output_file,
})
}
2024-02-16 10:48:15 +00:00
pub fn run_program(program: &Path, args: &[&str]) -> Result<Child, std::io::Error> {
2024-03-11 11:02:14 +00:00
std::process::Command::new(program).args(args).spawn()
2024-02-14 07:53:47 +00:00
}