jhorstmann / compact-thrift

Thrift IDL parser and code generator for the compact protocol
Apache License 2.0
2 stars 0 forks source link

Parse the whole thrift definition using rust macros? #12

Closed jhorstmann closed 5 months ago

jhorstmann commented 5 months ago

Crazy idea, but the thrift grammar should consist of valid rust tokens, so should not even need procedural macros. Proof of concept:

fn skip_field(field_type: u8) {

}

macro_rules! thrift {
    (struct $identifier:ident { $($(#[$($attrss:tt)*])* $field_id:literal : $required_or_optional:ident $field_type:ident $(< $element_type:ident >)? $field_name:ident,)* }) => {
        pub struct $identifier {
            $($(#[$($attrss)*])* pub $field_name: required_or_optional!($required_or_optional field_type!($field_type $($element_type)?))),*
        }

        impl $identifier {
            pub fn fill(&mut self) {
                let mut last_field_id = 0_i16;
                loop {
                    let field_type = 1_u8; // TODO
                    if field_type == 0 {
                        break;
                    }

                    match last_field_id {
                        $($field_id => {
                            self.$field_name.fill();
                        }),*
                        _ => {
                            skip_field(field_type);
                        }
                    }
                }
            }
        }
    }
}

macro_rules! field_type {
    (list $element_type:ident) => { Vec<$element_type> };
    (set $element_type:ident) => { Vec<$element_type> };
    (binary) => { Vec<u8> };
    (string) => { String };
    ($field_type:ident) => { $field_type };
}

macro_rules! required_or_optional {
    (required $field_type:ty) => { $field_type };
    (optional $field_type:ty) => { Option<$field_type> };
}

thrift! {
    struct SomeStructure {
        /** doc */
        1: required i64 offset,
        2: optional i64 length,
        3: optional list<i64> foobar,
        4: optional string data,
    }
}
jhorstmann commented 5 months ago

Benefits:

Limitations