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
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
use interoptopus::writer::IndentWriter;
use interoptopus::{Error, Library};
use interoptopus::lang::c::{ConstantValue, PrimitiveValue, CType, EnumType};

#[derive(Clone, Debug)]
pub struct Config {
    init_api_function_name: String,
    get_cffi_function_name: String,
}

impl Default for Config {
    fn default() -> Self {
        Self { init_api_function_name: "init_api".to_string(), get_cffi_function_name: "ffi".to_string() }
    }
}

pub struct Generator {
    c_generator: interoptopus_backend_c::Generator,
    config: Config,
    library: Library,
}

impl Generator {
    pub fn new(config: Config, library: Library) -> Self {
        let c_generator = interoptopus_backend_c::Generator::new(
            interoptopus_backend_c::Config {
                directives: false,
                imports: false,
                file_header_comment: "".to_string(),
                ..interoptopus_backend_c::Config::default()
            },
            library.clone(),
        );

        Self { c_generator, config, library }
    }
}

pub trait Interop {
    /// Returns the user config.
    fn config(&self) -> &Config;

    /// Returns the library to produce bindings for.
    fn library(&self) -> &Library;

    /// Returns the C-generator
    fn c_generator(&self) -> &interoptopus_backend_c::Generator;

    fn constant_value_to_value(&self, value: &ConstantValue) -> String {
        match value {
            ConstantValue::Primitive(x) => match x {
                PrimitiveValue::Bool(x) => format!("{}", x),
                PrimitiveValue::U8(x) => format!("{}", x),
                PrimitiveValue::U16(x) => format!("{}", x),
                PrimitiveValue::U32(x) => format!("{}", x),
                PrimitiveValue::U64(x) => format!("{}", x),
                PrimitiveValue::I8(x) => format!("{}", x),
                PrimitiveValue::I16(x) => format!("{}", x),
                PrimitiveValue::I32(x) => format!("{}", x),
                PrimitiveValue::I64(x) => format!("{}", x),
                PrimitiveValue::F32(x) => format!("{}", x),
                PrimitiveValue::F64(x) => format!("{}", x),
            },
        }
    }

    fn write_to(&self, w: &mut IndentWriter) -> Result<(), Error> {
        self.write_imports(w)?;
        w.newline()?;

        self.write_c_header(w)?;
        w.newline()?;
        w.newline()?;

        self.write_api_load_fuction(w)?;
        w.newline()?;
        w.newline()?;

        self.write_constants(w)?;
        w.newline()?;
        w.newline()?;

        self.write_types(w)?;
        w.newline()?;
        w.newline()?;

        self.write_function_proxies(w)?;
        w.newline()?;
        w.newline()?;

        Ok(())
    }

    fn write_imports(&self, w: &mut IndentWriter) -> Result<(), Error> {
        w.indented(|w| writeln!(w, r#"from cffi import FFI"#))?;
        Ok(())
    }

    fn write_api_load_fuction(&self, w: &mut IndentWriter) -> Result<(), Error> {
        w.indented(|w| writeln!(w, r#"_ffi = FFI()"#))?;
        w.indented(|w| writeln!(w, r#"_ffi.cdef(api_definition)"#))?;
        w.indented(|w| writeln!(w, r#"_api = None"#))?;
        w.newline()?;
        w.newline()?;

        w.indented(|w| writeln!(w, r#"def {}(dll):"#, self.config().init_api_function_name))?;
        w.indent();
        w.indented(|w| writeln!(w, r#""""Initializes this library, call with path to DLL.""""#))?;
        w.indented(|w| writeln!(w, r#"global _api"#))?;
        w.indented(|w| writeln!(w, r#"_api = _ffi.dlopen(dll)"#))?;
        w.unindent();
        w.newline()?;
        w.newline()?;

        w.indented(|w| writeln!(w, r#"def {}():"#, self.config().get_cffi_function_name))?;
        w.indent();
        w.indented(|w| writeln!(w, r#""""Returns the FFI object, e.g., to create types.""""#))?;
        w.indented(|w| writeln!(w, r#"global _ffi"#))?;
        w.indented(|w| writeln!(w, r#"return _ffi"#))?;
        w.unindent();

        Ok(())
    }


    fn write_constants(&self, w: &mut IndentWriter) -> Result<(), Error> {
        for constant in self.library().constants() {
            let docs = constant.documentation().lines().iter().map(|x| format!("# {}", x)).collect::<Vec<_>>().join("\n");
            w.indented(|w| writeln!(w, r#"{}"#, docs))?;
            w.indented(|w| writeln!(w, r#"{} = {}"#, constant.name(), self.constant_value_to_value(constant.value())))?;
        }

        Ok(())
    }

    fn write_types(&self, w: &mut IndentWriter) -> Result<(), Error> {
        for the_type in self.library().types() {
            match the_type {
                CType::Enum(e) => self.write_enum(w, e)?,
                _ => {}
            }
        }

        Ok(())
    }


    fn write_enum(&self, w: &mut IndentWriter, e: &EnumType) -> Result<(), Error> {
        let docs = e.documentation().lines().join("\n");

        w.indented(|w| writeln!(w, r#"class {}:"#, e.name()))?;
        w.indent();
        w.indented(|w| writeln!(w, r#""""{}""""#, docs))?;
        for v in e.variants() {
            w.indented(|w| writeln!(w, r#"{} = {}"#, v.name(), v.value()))?;
        }
        w.unindent();
        w.newline()?;
        w.newline()?;

        Ok(())
    }



    fn write_function_proxies(&self, w: &mut IndentWriter) -> Result<(), Error> {
        for function in self.library().functions() {
            let args = function.signature().params().iter().map(|x| x.name().to_string()).collect::<Vec<_>>().join(", ");
            let docs = function.documentation().lines().join("\n");

            w.indented(|w| writeln!(w, r#"def {}({}):"#, function.name(), &args))?;
            w.indent();
            w.indented(|w| writeln!(w, r#""""{}""""#, docs))?;
            w.indented(|w| writeln!(w, r#"return _api.{}({})"#, function.name(), &args))?;
            w.unindent();

            w.newline()?;
            w.newline()?;
        }

        Ok(())
    }


    fn write_c_header(&self, w: &mut IndentWriter) -> Result<(), Error> {
        use interoptopus_backend_c::Interop as _;

        w.indented(|w| writeln!(w, r#"api_definition = """"#))?;
        self.c_generator().write_to(w)?;
        w.indented(|w| writeln!(w, r#"""""#))?;
        Ok(())
    }
}

impl Interop for Generator {
    fn config(&self) -> &Config {
        &self.config
    }

    fn library(&self) -> &Library {
        &self.library
    }

    fn c_generator(&self) -> &interoptopus_backend_c::Generator {
        &self.c_generator
    }
}