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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
//! csharpbindgen is a library for generating low-level C# bindings
//! from Rust code.
//! 
//! It is currently in a very primitive state, largely designed for use by the
//! [Unity Pathfinder plugin][plugin] and missing many features.
//! 
//! ## Quick start
//! 
//! The library is intended for use via a [Cargo build script][build].
//! 
//! Here's an example of a simple program that converts some simple Rust code
//! into C#:
//! 
//! ```
//! let rust = r#"
//!   pub unsafe extern "C" fn my_func(foo: i32) -> f32 { /* ... */ }
//! "#;
//! 
//! let code = csharpbindgen::Builder::new("MyDll", rust.to_string())
//!     .class_name("MyStuff")
//!     .generate()
//!     .unwrap();
//!
//! println!("{}", code);
//! ```
//!
//! This will print out something like the following C# code:
//! 
//! ```csharp
//! // This file has been auto-generated, please do not edit it.
//!
//! using System;
//! using System.Runtime.InteropServices;
//!
//! internal class MyStuff {
//!     [DllImport("MyDll")]
//!     internal static extern float my_func(Int32 foo);
//! }
//! ```
//! 
//! For a more complete example, see the Unity Pathfinder plugin's [`build.rs`][].
//! 
//! 
//! [plugin]: https://github.com/toolness/pathfinder-unity-fun
//! [build]: https://doc.rust-lang.org/cargo/reference/build-scripts.html
//! [`build.rs`]: https://github.com/toolness/pathfinder-unity-fun/blob/master/build.rs

use std::collections::HashMap;
use std::borrow::Borrow;
use std::fmt::{Formatter, Display};
use std::fmt;
use std::rc::Rc;
use syn::Item;

mod error;
mod symbol_config;
mod ignores;

use symbol_config::{SymbolConfigManager, SymbolConfig};
use error::Result;
pub use error::Error;

const INDENT: &'static str = "    ";

/// Enumeration for C#'s access modifiers.
#[derive(Clone, Copy)]
pub enum CSAccess {
    Private,
    Protected,
    Internal,
    Public
}

impl Display for CSAccess {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "{}", match self {
            CSAccess::Private => "private",
            CSAccess::Protected => "protected",
            CSAccess::Internal => "internal",
            CSAccess::Public => "public"
        })
    }
}

impl Default for CSAccess {
    fn default() -> Self {
        CSAccess::Internal
    }
}

struct CSTypeDef {
    name: String,
    ty: CSType
}

impl CSTypeDef {
    pub fn from_rust_type_def(rust_type_def: &syn::ItemType) -> Result<Self> {
        Ok(CSTypeDef {
            name: rust_type_def.ident.to_string(),
            ty: CSType::from_rust_type(&rust_type_def.ty)?
        })
    }
}

#[derive(Clone)]
struct CSType {
    name: String,
    is_ptr: bool,
    st: Option<Rc<CSStruct>>
}

impl CSType {
    pub fn from_rust_type(rust_type: &syn::Type) -> Result<Self> {
        match rust_type {
            syn::Type::Path(type_path) => {
                let last = type_path.path.segments.last()
                  .expect("expected at least one path segment on type!");
                Ok(CSType {
                    name: last.value().ident.to_string(),
                    is_ptr: false,
                    st: None
                })
            },
            syn::Type::Ptr(type_ptr) => {
                let mut wrapped_type = CSType::from_rust_type(&type_ptr.elem)?;
                if wrapped_type.is_ptr {
                    return unsupported(format!(
                        "double pointers for {} are unsupported!", wrapped_type.name
                    ));
                }
                wrapped_type.is_ptr = true;
                Ok(wrapped_type)
            },
            _ => {
                unsupported(format!("the type is unsupported"))
            }
        }
    }
}

impl Display for CSType {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        let name = to_cs_primitive(&self.name);
        if self.is_ptr {
            if self.st.is_some() {
                write!(f, "ref {}", name)
            } else {
                write!(f, "IntPtr /* {} */", name)
            }
        } else {
            write!(f, "{}", name)
        }
    }
}

struct CSConst {
    name: String,
    ty: CSType,
    value: String,
    cfg: SymbolConfig
}

impl CSConst {
    pub fn from_rust_const(rust_const: &syn::ItemConst, cfg: SymbolConfig) -> Result<Self> {
        let value = if let syn::Expr::Lit(expr_lit) = &rust_const.expr.borrow() {
            if let syn::Lit::Int(lit_int) = &expr_lit.lit {
                lit_int.value().to_string()
            } else {
                return unsupported(format!(
                    "Unsupported const expression literal value: {:?}", expr_lit))
            }
        } else {
            return unsupported(format!(
                "Unsupported const expression value: {:?}", rust_const.expr))
        };
        Ok(CSConst {
            name: munge_cs_name(rust_const.ident.to_string()),
            ty: CSType::from_rust_type(&rust_const.ty)?,
            value,
            cfg
        })
    }
}

struct CSStructField {
    name: String,
    ty: CSType,
}

impl CSStructField {
    pub fn from_named_rust_field(rust_field: &syn::Field) -> Result<Self> {
        Ok(CSStructField {
            name: munge_cs_name(rust_field.ident.as_ref().unwrap().to_string()),
            ty: CSType::from_rust_type(&rust_field.ty)?
        })
    }

    pub fn to_string(&self) -> String {
        to_cs_var_decl(&self.ty, &self.name)
    }
}

struct CSStruct {
    name: String,
    fields: Vec<CSStructField>,
    cfg: SymbolConfig
}

impl CSStruct {
    pub fn from_rust_struct(rust_struct: &syn::ItemStruct, cfg: SymbolConfig) -> Result<Self> {
        let mut fields = vec![];

        if let syn::Fields::Named(rust_fields) = &rust_struct.fields {
            for rust_field in rust_fields.named.iter() {
                fields.push(CSStructField::from_named_rust_field(rust_field)?);
            }
        }
        Ok(CSStruct {
            name: rust_struct.ident.to_string(),
            fields,
            cfg
        })
    }
}

impl Display for CSStruct {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        writeln!(f, "[Serializable]")?;
        writeln!(f, "[StructLayout(LayoutKind.Sequential)]")?;
        writeln!(f, "{} struct {} {{", self.cfg.access, self.name)?;
        for field in self.fields.iter() {
            writeln!(f, "{}{} {};", INDENT, self.cfg.access, field.to_string())?;
        }

        let constructor_args: Vec<String> = self.fields
          .iter()
          .map(|field| field.to_string())
          .collect();
        writeln!(f, "\n{}{} {}({}) {{", INDENT, self.cfg.access, self.name, constructor_args.join(", "))?;
        for field in self.fields.iter() {
            writeln!(f, "{}{}this.{} = {};", INDENT, INDENT, field.name, field.name)?;
        }
        writeln!(f, "{}}}", INDENT)?;

        writeln!(f, "}}")
    }
}

struct CSFuncArg {
    name: String,
    ty: CSType
}

impl CSFuncArg {
    pub fn from_rust_arg_captured(rust_arg: &syn::ArgCaptured) -> Result<Self> {
        if let syn::Pat::Ident(pat_ident) = &rust_arg.pat {
            Ok(CSFuncArg {
                name: munge_cs_name(pat_ident.ident.to_string()),
                ty: CSType::from_rust_type(&rust_arg.ty)?
            })
        } else {
            unsupported(format!("captured arg pattern is unsupported: {:?}", rust_arg.pat))
        }
    }

    pub fn to_string(&self) -> String {
        to_cs_var_decl(&self.ty, &self.name)
    }
}

struct CSFunc {
    name: String,
    args: Vec<CSFuncArg>,
    return_ty: Option<CSType>,
    cfg: SymbolConfig
}

impl CSFunc {
    pub fn from_rust_fn(rust_fn: &syn::ItemFn, cfg: SymbolConfig) -> Result<Self> {
        let mut args = vec![];

        for input in rust_fn.decl.inputs.iter() {
            if let syn::FnArg::Captured(cap) = input {
                args.push(CSFuncArg::from_rust_arg_captured(&cap)?);
            } else {
                return unsupported(format!(
                    "Input for function '{}' is unsupported: {:?}",
                    rust_fn.ident.to_string(),
                    input
                ));
            }
        }

        let return_ty = match &rust_fn.decl.output {
            syn::ReturnType::Default => None,
            syn::ReturnType::Type(_, ty) => {
                Some(CSType::from_rust_type(&ty)?)
            }
        };

        Ok(CSFunc {
            name: rust_fn.ident.to_string(),
            args,
            return_ty,
            cfg
        })
    }
}

impl Display for CSFunc {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        let return_ty = match &self.return_ty {
            None => String::from("void"),
            Some(ty) => ty.to_string()
        };
        let args: Vec<String> = self.args
          .iter()
          .map(|arg| arg.to_string())
          .collect();
        write!(f, "{} static extern {} {}({});", self.cfg.access, return_ty, self.name, args.join(", "))
    }
}

struct CSFile {
    class_name: String,
    dll_name: String,
    consts: Vec<CSConst>,
    structs: Vec<Rc<CSStruct>>,
    funcs: Vec<CSFunc>,
    type_defs: HashMap<String, CSTypeDef>
}

impl CSFile {
    pub fn new(class_name: String, dll_name: String) -> Self {
        CSFile {
            class_name,
            dll_name,
            consts: vec![],
            structs: vec![],
            funcs: vec![],
            type_defs: HashMap::new()
        }
    }

    pub fn populate_from_rust_file(
        &mut self,
        rust_file: &syn::File,
        cfg_mgr: &SymbolConfigManager
    ) -> Result<()> {
        for item in rust_file.items.iter() {
            match item {
                Item::Const(item_const) => {
                    if let Some(cfg) = cfg_mgr.get(&item_const.ident) {
                        let cs_const = error::add_ident(
                            CSConst::from_rust_const(&item_const, cfg), &item_const.ident)?;
                        self.consts.push(cs_const);
                    }
                },
                Item::Struct(item_struct) => {
                    if let Some(cfg) = cfg_mgr.get(&item_struct.ident) {
                        let cs_struct = error::add_ident(
                            CSStruct::from_rust_struct(&item_struct, cfg), &item_struct.ident)?;
                        self.structs.push(Rc::new(cs_struct));
                    }
                },
                Item::Fn(item_fn) => {
                    if item_fn.abi.is_some() {
                        if let Some(cfg) = cfg_mgr.get(&item_fn.ident) {
                            let cs_func = error::add_ident(
                                CSFunc::from_rust_fn(&item_fn, cfg), &item_fn.ident)?;
                            self.funcs.push(cs_func);
                        }
                    }
                },
                Item::Type(item_type) => {
                    if let Some(_cfg) = cfg_mgr.get(&item_type.ident) {
                        let type_def = error::add_ident(
                            CSTypeDef::from_rust_type_def(&item_type), &item_type.ident)?;
                        self.type_defs.insert(type_def.name.clone(), type_def);
                    }
                },
                _ => {}
            }
        }

        Ok(())
    }

    fn resolve_types(&mut self) -> Result<()> {
        let mut struct_map: HashMap<&str, &Rc<CSStruct>> = HashMap::new();

        for st in self.structs.iter() {
            struct_map.insert(&st.name, &st);
        }

        for func in self.funcs.iter_mut() {
            for arg in func.args.iter_mut() {
                if let Some(ty) = resolve_type_def(&arg.ty, &self.type_defs)? {
                    arg.ty = ty;
                }
                if let Some(st) = struct_map.get(&arg.ty.name.as_ref()) {
                    arg.ty.st = Some((*st).clone());
                }
            }
            if let Some(return_ty) = &func.return_ty {
                if let Some(ty) = resolve_type_def(return_ty, &self.type_defs)? {
                    func.return_ty = Some(ty);
                }
            }
        }

        Ok(())
    }
}

impl Display for CSFile {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        writeln!(f, "// This file has been auto-generated, please do not edit it.\n")?;
        writeln!(f, "using System;")?;
        writeln!(f, "using System.Runtime.InteropServices;\n")?;

        for st in self.structs.iter() {
            writeln!(f, "{}", st)?;
        }
        writeln!(f, "{} class {} {{", CSAccess::default(), self.class_name)?;
        for con in self.consts.iter() {
            writeln!(f, "{}{} const {} {} = {};\n", INDENT, con.cfg.access, con.ty, con.name, con.value)?;
        }
        for func in self.funcs.iter() {
            writeln!(f, "{}[DllImport(\"{}\")]", INDENT, self.dll_name)?;
            writeln!(f, "{}{}\n", INDENT, func)?;
        }
        writeln!(f, "}}")
    }
}

/// A [builder pattern] for the Rust-to-C# conversion process.
/// 
/// [builder pattern]: https://doc.rust-lang.org/1.0.0/style/ownership/builders.html
pub struct Builder {
    class_name: String,
    dll_name: String,
    rust_code: String,
    sconfig: SymbolConfigManager
}

impl Builder {
    /// Creates a new instance with the following arguments:
    /// 
    /// * `dll_name` is the name of the DLL that the C# `DllImport` attribute
    ///   will be bound to for all exported functions.
    /// 
    /// * `rust_code` is the source Rust code to convert into C#.
    pub fn new<T: AsRef<str>>(
        dll_name: T,
        rust_code: String
    ) -> Self {
        Builder {
            class_name: String::from("RustExports"),
            dll_name: String::from(dll_name.as_ref()),
            rust_code,
            sconfig: SymbolConfigManager::new()
        }
    }

    /// Sets the name of the C# class that will contain all exported functions.
    /// If never called, the C# class will be called `RustExports`.
    pub fn class_name<T: AsRef<str>>(mut self, class_name: T) -> Self {
        self.class_name = String::from(class_name.as_ref());
        self
    }

    /// Specifies a list of Rust identifier patterns to be ignored (i.e., not
    /// exported to C#).
    /// 
    /// The pattern syntax is currently very simple: if it ends with a `*`, it
    /// matches any Rust identifier that starts with the part of the pattern before
    /// the `*` (e.g., `Boop*` matches `BoopJones` and `BoopFoo`). Otherwise, it
    /// represents an exact match to a Rust identifier.
    pub fn ignore(mut self, ignores: &[&str]) -> Self {
        self.sconfig.ignores.add_static_array(ignores);
        self
    }

    /// Specifies that the given Rust identifier should be exported to C# with the
    /// given C# access modifier. By default, all exports are given the `internal`
    /// access modifier.
    pub fn access<T: AsRef<str>>(mut self, symbol_name: T, access: CSAccess) -> Self {
        self.sconfig.config_map.insert(String::from(symbol_name.as_ref()), SymbolConfig {
            access
        });
        self
    }

    /// Performs the conversion of source Rust code to C#.
    pub fn generate(self) -> Result<String> {
        let syntax = parse_file(&self.rust_code)?;
        let mut program = CSFile::new(self.class_name, self.dll_name);
        program.populate_from_rust_file(&syntax, &self.sconfig)?;
        program.resolve_types()?;
        Ok(format!("{}", program))
    }
}

fn parse_file(rust_code: &String) -> Result<syn::File> {
    match syn::parse_file(rust_code) {
        Ok(result) => Ok(result),
        Err(err) => Err(Error::SynError(err))
    }
}

fn resolve_type_def(ty: &CSType, type_defs: &HashMap<String, CSTypeDef>) -> Result<Option<CSType>> {
    if let Some(type_def) = type_defs.get(&ty.name) {
        if ty.is_ptr && type_def.ty.is_ptr {
            unsupported(format!(
                "double pointer to {} via type {} is unsupported!",
                type_def.ty.name,
                type_def.name
            ))
        } else {
            Ok(Some(type_def.ty.clone()))
        }
    } else {
        Ok(None)
    }
}

fn munge_cs_name(name: String) -> String {
    match name.as_ref() {
        "string" => String::from("str"),
        _ => name
    }
}

fn to_cs_primitive<'a>(type_name: &'a str) -> &'a str {
    match type_name {
        "u8" => "byte",
        "f32" => "float",
        "i32" => "Int32",
        "u32" => "UInt32",
        "usize" => "UIntPtr",
        _ => type_name
    }
}

fn to_cs_var_decl<T: AsRef<str>>(ty: &CSType, name: T) -> String {
    format!("{} {}", ty, name.as_ref())
}

fn unsupported<T>(msg: String) -> Result<T> {
    Err(Error::UnsupportedError(msg, None))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_it_errors_on_invalid_rust_code() {
        let err = Builder::new("Blarg", String::from("HELLO THERE"))
          .generate()
          .unwrap_err();
        let err_msg = format!("{}", err);
        assert_eq!(err_msg, "Couldn't parse Rust code: expected `!`");
    }

    #[test]
    fn test_it_errors_on_unsupported_rust_code() {
        let err = Builder::new("Blarg", String::from(r#"
            pub type MyFunkyThing = fn() -> void;
        "#)).generate().unwrap_err();
        assert_eq!(
            format!("{}", err),
            "Unable to export C# code while processing symbol \"MyFunkyThing\" because the type is unsupported"
        );
    }
}