read morphism body definitions from morphism-base file and generate instantiations based on type-variable substitutions

This commit is contained in:
Michael Sippel 2025-02-16 17:08:55 +01:00
parent 3f4a99ad79
commit cea1f36e63
Signed by: senvas
GPG key ID: F96CF119C34B64A6
8 changed files with 244 additions and 255 deletions

View file

@ -51,7 +51,7 @@ pub fn get_c_repr_type(dict: &mut impl TypeDict, t: laddertypes::TypeTerm, skip_
_ => None
}
}
else if args[0] == laddertypes::TypeTerm::TypeID(dict.get_typeid(&"ValueDelim".into()).unwrap())
else if args[0] == laddertypes::TypeTerm::TypeID(dict.get_typeid(&"ValueTerminated".into()).unwrap())
{
let _delim_val = args[1].clone();
let c_type = get_c_repr_type(dict, args[2].clone(), false)?;
@ -78,7 +78,24 @@ struct LdmcPrimCMorphism {
type_args: Vec<(laddertypes::TypeID, String)>,
src_type: laddertypes::TypeTerm,
dst_type: laddertypes::TypeTerm,
locations: Vec<String>
c_source: String
}
fn encode_type_to_symbol(dict: &mut impl TypeDict, t: &laddertypes::TypeTerm)-> String {
match t {
laddertypes::TypeTerm::Char(c) => {
match *c {
'\0' => { "NULL".into() },
'\t' => { "TAB".into() },
c => { format!("{}", c) }
}
},
t => dict.unparse(t)
}
}
fn encode_type_to_value(dict: &mut impl TypeDict, t: &laddertypes::TypeTerm) -> String {
dict.unparse(t)
}
impl LdmcPrimCMorphism {
@ -89,7 +106,7 @@ impl LdmcPrimCMorphism {
if let Some(val_trm) = σ.get(k_id) {
if let laddertypes::TypeID::Var(var_id) = k_id {
let name = dict.get_varname(*var_id).unwrap();
let val_str = dict.unparse(val_trm);
let val_str = encode_type_to_symbol(dict, val_trm);
s.push_str(&format!("_{}_{}", name, val_str));
}
} else {
@ -110,6 +127,34 @@ impl LdmcPrimCMorphism {
get_c_repr_type(dict, self.src_type.clone(), true).expect("cant get c-repr type for src type"),
get_c_repr_type(dict, self.dst_type.clone(), true).expect("cant get c-repr type for dst type"))
}
pub fn generate_instantiation(&self, dict: &mut impl TypeDict, σ: &std::collections::HashMap<laddertypes::TypeID, laddertypes::TypeTerm>) -> Option<String> {
let mut s = String::new();
s.push_str(&format!(r#"
int {} ( {} const * restrict src, {} * restrict dst ) {{
"#,
self.instantiated_symbol_name(dict, &σ),
get_c_repr_type(dict, self.src_type.clone().apply_substitution(&|k| σ.get(k).cloned()).clone(), true).expect("cant get c-repr-type"),
get_c_repr_type(dict, self.dst_type.clone().apply_substitution(&|k| σ.get(k).cloned()).clone(), true).expect("cant get c-repr-type"),
));
for (ty_id, kind) in self.type_args.iter() {
if let Some(val) = σ.get(ty_id) {
s.push_str(&format!(" #define {} {}\n", dict.get_typename(&ty_id).unwrap(), encode_type_to_value(dict, val)));
}
}
s.push_str(&self.c_source);
for (ty_id, kind) in self.type_args.iter() {
s.push_str(&format!("\n #undef {}", dict.get_typename(&ty_id).unwrap()));
}
s.push_str(&format!(r#"
}}
"#));
Some(s)
}
}
#[derive(Clone)]
@ -259,36 +304,45 @@ impl Morphism for LdmcMorphism {
* NAME '(' [TYPE-ARG-NAME ':' KIND] ')'
* SRC-TYPE
* '-->' DST-TYPE
* '@' [ LOCATION ':' ]
* ```
* TEMPLATE-CODE
* ```
*/
fn parser(
type_dict: Arc<RwLock< BimapTypeDict >>
) -> impl Parser<char, Vec<LdmcPrimCMorphism>, Error = Simple<char>> {
// morph name
ident().padded()
// type args
.then(
ident().padded()
.then_ignore(just(':').padded())
.then_ignore(just(":").padded())
.then(none_of(",)").repeated().padded())
.separated_by(just(',').padded())
.delimited_by(just('('), just(')'))
.separated_by(just(",").padded())
.delimited_by(just("("), just(")"))
)
// newline
.then_ignore(just('\n'))
.then(
take_until(just("-->").ignored())
.then(take_until(just('@').ignored()))
)
.then(
none_of(":\n").repeated().separated_by(just(':'))
)
// src type
.then(take_until(just("-->").ignored()))
// dst_type
.then(take_until(just("```")))
// c sourcecode template
.then(take_until(just("```")))
.map(
move |(((symbol, type_args), ((src_type, _), (dst_type, _))), locations)| {
move |((((symbol, type_args), (src_type, _)), (dst_type, _)), (c_source, _))| {
let c_source = c_source.iter().collect();
let mut type_dict = type_dict.write().unwrap();
let type_args : Vec<_> = type_args.into_iter().map(|(v,k)| (v,k.into_iter().collect())).collect();
let mut ty_args = Vec::new();
for (var, kind) in type_args.into_iter() {
let var_id = type_dict.add_varname(var.clone());
eprintln!("parser: add varname {} -> {:?}", var, type_dict.get_typeid(&var));
ty_args.push((var_id, kind));
}
@ -300,7 +354,7 @@ fn parser(
type_args: ty_args,
src_type,
dst_type,
locations: locations.into_iter().map(|l| l.into_iter().collect()).collect()
c_source
}
})
.separated_by(text::newline())
@ -309,7 +363,7 @@ fn parser(
fn main() {
let mut type_dict = Arc::new(RwLock::new(BimapTypeDict::new()));
let mut morphism_base = laddertypes::MorphismBase::<LdmcMorphism>::new(vec![
type_dict.parse("Seq~<ValueDelim '\\0'>").expect(""),
type_dict.parse("Seq~<ValueTerminated '\\0'>").expect(""),
type_dict.parse("Seq~<LengthPrefix x86.UInt64>").expect("")
]);
@ -345,23 +399,53 @@ fn main() {
}
let path = morphism_base.find_morphism_path(MorphismType {
src_type: type_dict.parse( src_type_arg.as_str() ).expect(""),
dst_type: type_dict.parse( dst_type_arg.as_str() ).expect(""),
}//,
// &mut *type_dict.write().unwrap()
);
});
match path {
Some(path) => {
let mut i = 0;
/* todo: collect include files from morphism base */
println!(r#"
#include <stdio.h>
#include <stdint.h>
#include <morphisms/length-prefix.h>
#include <morphisms/posint.h>
#include <array/length-prefix.h>
"#);
let mut existing_instantiations = Vec::new();
for morph_inst in path.iter() {
match &morph_inst.m {
LdmcMorphism::Primitive( item_morph ) => {
let name = item_morph.instantiated_symbol_name(&mut type_dict, &morph_inst.σ);
if ! existing_instantiations.contains(&name) {
if let Some(s) = item_morph.generate_instantiation(&mut type_dict, &morph_inst.σ) {
println!("{}", s);
} else {
eprintln!("couldnt generate instance {}", name);
}
existing_instantiations.push( name );
}
}
LdmcMorphism::LengthPrefixMap { length_prefix_type, item_morph } => {
let name = item_morph.instantiated_symbol_name(&mut type_dict, &morph_inst.σ);
if ! existing_instantiations.contains(&name) {
if let Some(s) = item_morph.generate_instantiation(&mut type_dict, &morph_inst.σ) {
println!("{}", s);
} else {
eprintln!("couldnt generate instance {}", name);
}
existing_instantiations.push( name );
}
}
_ => {}
}
}
println!(r#"
int main() {{
uint8_t bufA[1024];
uint8_t bufB[1024];