aboutsummaryrefslogtreecommitdiff
path: root/patio-to-cranelift/src/lib.rs
blob: 80d228405c6a857fc529d144a61e818f44dfa732 (plain)
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
use std::{path::Path, str::FromStr};

use crate::{errors::CompileError, patio::compilation_unit::PatioCompilationUnit};

#[allow(dead_code, unused_imports)]
#[path = "./gen/patio_generated.rs"]
mod patio_generated;

#[allow(dead_code, unused_imports)]
#[path = "./gen/sources_generated.rs"]
mod sources_generated;

mod codegen;
mod errors;
mod patio;

pub fn compile(
    source_path: &Path,
    target_str: &str,
    main: Option<&str>,
) -> Result<(), CompileError> {
    let source_bytes = std::fs::read(source_path).map_err(CompileError::ReadSourceBytes)?;

    let compilation_unit: PatioCompilationUnit =
        patio_generated::patio::root_as_patio_compilation_unit(&source_bytes)
            .map_err(CompileError::InvalidFlatbuffer)?
            .into();

    let target_triple =
        target_lexicon::Triple::from_str(target_str).map_err(CompileError::ParseTargetTriple)?;

    let object_bytes =
        codegen::compile_compilation_unit(compilation_unit, main, source_path, target_triple)?;

    let destination_path = source_path.with_extension("o");
    std::fs::write(destination_path, object_bytes).map_err(CompileError::WriteObjectFile)?;

    Ok(())
}