ldmc/src/c_gen/gen_lib.rs

79 lines
3 KiB
Rust

use {
super::types::get_c_repr_arg_type, crate::{c_gen::LdmcCTargetMorph, LdmcPrimMorph}, laddertypes::{morphism::MorphismInstance, parser::*, TypeDict}, std::collections::HashMap
};
pub fn generate_lib(
dict: &mut impl TypeDict,
morphisms: Vec< (String, MorphismInstance<LdmcPrimMorph>) >
) -> Result<String, ()> {
let mut target = LdmcCTargetMorph::new();
let mut wrappers = String::new();
for (name, morph) in morphisms {
match target.add_instantiation(dict, morph) {
Ok(inst) => {
if name == "main" {
let mut c_source = String::new();
c_source.push_str(&format!(r#"
#include <unistd.h>
int main() {{
uint8_t bufIn[4096];
uint8_t bufOut[4096];"#));
if let Ok(_) = laddertypes::subtype_unify(
&inst.ty.src_type,
&dict.parse("<Seq~<ValueTerminated 0> Char~Ascii~native.UInt8>").expect("")
) {
c_source.push_str("scanf(\"%s\", bufIn);");
} else {
c_source.push_str("read(0, bufIn, sizeof(bufIn));");
}
c_source.push_str(
&format!(r#"FUSE( {}, (void const*)bufIn, (void*)bufOut );"#,
inst.instantiated_symbol_name(dict, &HashMap::new()))
);
if let Ok(ψ) = laddertypes::subtype_unify(
&inst.ty.dst_type,
&dict.parse("<Seq~<ValueTerminated 0> native.UInt8>").expect("")
) {
c_source.push_str("printf(\"%s\\n\", bufOut);");
} else {
c_source.push_str("write(1, bufOut, sizeof(bufOut));");
}
c_source.push_str("
return 0;
}");
wrappers.push_str(&c_source);
} else {
target.add_type(dict, inst.ty.src_type.clone());
target.add_type(dict, inst.ty.dst_type.clone());
wrappers.push_str(&format!("
int {} (
{} const * restrict src,
{} * restrict dst
) {{
return {}( (void*)src, (void*)dst );
}}
", name,
get_c_repr_arg_type(dict, &inst.ty.src_type),
get_c_repr_arg_type(dict, &inst.ty.dst_type),
inst.instantiated_symbol_name(dict, &HashMap::new())
));
}
}
Err(_err) => {
eprintln!("failed to create morphism instatiation");
return Err(());
}
}
}
let mut c_source = target.into_c_source(dict);
c_source.push_str(&wrappers);
Ok(c_source)
}