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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
//! `rust_swig` is a Rust Simplified Wrapper and Interface Generator used
//! to connect other programming languages to Rust.
//! It is designed to be used from
//! [cargo build scripts](https://doc.rust-lang.org/cargo/reference/build-scripts.html).
//! The idea of this softwared based on [swig](http://www.swig.org).
//! For macros expansion it uses [syntex](https://crates.io/crates/syntex).
//! More details can be found at
//! [README](https://github.com/Dushistov/rust_swig/blob/master/README.md)

macro_rules! parse_type {
    ($($tt:tt)*) => {{
        let ty: Type = parse_quote! { $($tt)* };
        ty
    }}
}

mod ast;
mod code_parse;
mod cpp;
mod error;
pub mod file_cache;
mod java_jni;
mod typemap;

use std::{
    cell::RefCell,
    collections::HashSet,
    env,
    io::Write,
    mem,
    path::{Path, PathBuf},
    str::FromStr,
};

use log::{debug, trace};
use proc_macro2::{Ident, Span, TokenStream};
use quote::{quote, ToTokens};
use syn::{parse_quote, spanned::Spanned, Token, Type};

use crate::{
    ast::RustType,
    error::{panic_on_parse_error, DiagnosticError, Result},
    typemap::TypeMap,
};

/// Calculate target pointer width from environment variable
/// that `cargo` inserts
pub fn target_pointer_width_from_env() -> Option<usize> {
    env::var("CARGO_CFG_TARGET_POINTER_WIDTH")
        .ok()
        .map(|p_width| {
            <usize>::from_str(&p_width)
                .expect("Can not convert CARGO_CFG_TARGET_POINTER_WIDTH to usize")
        })
}

/// `LanguageConfig` contains configuration for specific programming language
pub enum LanguageConfig {
    JavaConfig(JavaConfig),
    CppConfig(CppConfig),
}

/// Configuration for Java binding generation
pub struct JavaConfig {
    output_dir: PathBuf,
    package_name: String,
    use_null_annotation: Option<String>,
    optional_package: String,
}

impl JavaConfig {
    /// Create `JavaConfig`
    /// # Arguments
    /// * `output_dir` - directory where place generated java files
    /// * `package_name` - package name for generated java files
    pub fn new(output_dir: PathBuf, package_name: String) -> JavaConfig {
        JavaConfig {
            output_dir,
            package_name,
            use_null_annotation: None,
            optional_package: "java.util".to_string(),
        }
    }
    /// Use @NonNull for types where appropriate
    /// # Arguments
    /// * `import_annotation` - import statement for @NonNull,
    ///                         for example android.support.annotation.NonNull
    pub fn use_null_annotation(mut self, import_annotation: String) -> JavaConfig {
        self.use_null_annotation = Some(import_annotation);
        self
    }
    /// If you use JDK without java.util.Optional*, then you can provide
    /// name of custom package with Optional
    pub fn use_optional_package(mut self, optional_package: String) -> JavaConfig {
        self.optional_package = optional_package;
        self
    }
}

/// Configuration for C++ binding generation
pub struct CppConfig {
    output_dir: PathBuf,
    namespace_name: String,
    cpp_optional: CppOptional,
    cpp_variant: CppVariant,
    generated_helper_files: RefCell<HashSet<PathBuf>>,
    to_generate: RefCell<Vec<TokenStream>>,
}

/// To which `C++` type map `std::option::Option`
pub enum CppOptional {
    /// `std::optional` from C++17 standard
    Std17,
    /// `boost::optional`
    Boost,
}

/// To which `C++` type map `std::result::Result`
pub enum CppVariant {
    /// `std::variant` from C++17 standard
    Std17,
    /// `boost::variant`
    Boost,
}

impl CppConfig {
    /// Create `CppConfig`
    /// # Arguments
    /// * `output_dir` - directory where place generated c++ files
    /// * `namespace_name` - namespace name for generated c++ classes
    pub fn new(output_dir: PathBuf, namespace_name: String) -> CppConfig {
        CppConfig {
            output_dir,
            namespace_name,
            cpp_optional: CppOptional::Std17,
            cpp_variant: CppVariant::Std17,
            generated_helper_files: RefCell::new(HashSet::new()),
            to_generate: RefCell::new(vec![]),
        }
    }
    pub fn cpp_optional(self, cpp_optional: CppOptional) -> CppConfig {
        CppConfig {
            cpp_optional,
            ..self
        }
    }
    pub fn cpp_variant(self, cpp_variant: CppVariant) -> CppConfig {
        CppConfig {
            cpp_variant,
            ..self
        }
    }
    pub fn use_boost(self) -> CppConfig {
        CppConfig {
            cpp_variant: CppVariant::Boost,
            cpp_optional: CppOptional::Boost,
            ..self
        }
    }
}

/// `Generator` is a main point of `rust_swig`.
/// It expands rust macroses and generates not rust code.
/// It designed to use inside `build.rs`.
pub struct Generator {
    init_done: bool,
    config: LanguageConfig,
    conv_map: TypeMap,
    conv_map_source: Vec<SourceCode>,
    foreign_lang_helpers: Vec<SourceCode>,
    pointer_target_width: usize,
}

struct SourceCode {
    id_of_code: String,
    code: String,
}

static FOREIGNER_CLASS: &str = "foreigner_class";
static FOREIGN_ENUM: &str = "foreign_enum";
static FOREIGN_INTERFACE: &str = "foreign_interface";

impl Generator {
    pub fn new(config: LanguageConfig) -> Generator {
        let pointer_target_width = target_pointer_width_from_env();
        let mut conv_map_source = Vec::new();
        let mut foreign_lang_helpers = Vec::new();
        match config {
            LanguageConfig::JavaConfig(ref java_cfg) => {
                conv_map_source.push(SourceCode {
                    id_of_code: "jni-include.rs".into(),
                    code: include_str!("java_jni/jni-include.rs")
                        .replace(
                            "java.util.Optional",
                            &format!("{}.Optional", java_cfg.optional_package),
                        )
                        .replace(
                            "java/util/Optional",
                            &format!("{}/Optional", java_cfg.optional_package.replace('.', "/")),
                        ),
                });
            }
            LanguageConfig::CppConfig(..) => {
                conv_map_source.push(SourceCode {
                    id_of_code: "cpp-include.rs".into(),
                    code: include_str!("cpp/cpp-include.rs").into(),
                });
                foreign_lang_helpers.push(SourceCode {
                    id_of_code: "rust_str.h".into(),
                    code: include_str!("cpp/rust_str.h").into(),
                });
                foreign_lang_helpers.push(SourceCode {
                    id_of_code: "rust_vec.h".into(),
                    code: include_str!("cpp/rust_vec.h").into(),
                });
                foreign_lang_helpers.push(SourceCode {
                    id_of_code: "rust_result.h".into(),
                    code: include_str!("cpp/rust_result.h").into(),
                });
                foreign_lang_helpers.push(SourceCode {
                    id_of_code: "rust_option.h".into(),
                    code: include_str!("cpp/rust_option.h").into(),
                });
                foreign_lang_helpers.push(SourceCode {
                    id_of_code: "rust_tuple.h".into(),
                    code: include_str!("cpp/rust_tuple.h").into(),
                });
            }
        }
        Generator {
            init_done: false,
            config,
            conv_map: TypeMap::default(),
            conv_map_source,
            foreign_lang_helpers,
            pointer_target_width: pointer_target_width.unwrap_or(0),
        }
    }

    pub fn with_pointer_target_width(mut self, pointer_target_width: usize) -> Generator {
        self.pointer_target_width = pointer_target_width;
        self
    }

    /// Add new foreign langauge type <-> Rust mapping
    pub fn merge_type_map(mut self, id_of_code: &str, code: &str) -> Generator {
        self.conv_map_source.push(SourceCode {
            id_of_code: id_of_code.into(),
            code: code.into(),
        });
        self
    }

    /// process `src` and save result of macro expansion to `dst`
    ///
    /// # Panics
    /// Panics on error
    pub fn expand<S, D>(self, crate_name: &str, src: S, dst: D)
    where
        S: AsRef<Path>,
        D: AsRef<Path>,
    {
        let src_cnt = std::fs::read_to_string(src.as_ref()).unwrap_or_else(|err| {
            panic!(
                "Error during read for file {}: {}",
                src.as_ref().display(),
                err
            )
        });
        if let Err(err) = self.expand_str(crate_name, &src_cnt, dst) {
            panic_on_parse_error(&err);
        }
    }

    /// process `src` and save result of macro expansion to `dst`
    ///
    /// # Panics
    /// Panics on I/O errors
    fn expand_str<D>(mut self, crate_name: &str, src: &str, dst: D) -> Result<()>
    where
        D: AsRef<Path>,
    {
        if self.pointer_target_width == 0 {
            panic!(
                r#"pointer target width unknown,
 set env CARGO_CFG_TARGET_POINTER_WIDTH environment variable,
 or use `with_pointer_target_width` function
"#
            );
        }
        let items = self.init_types_map(self.pointer_target_width)?;

        let syn_file = match syn::parse_file(src) {
            Ok(x) => x,
            Err(err) => {
                let mut err: DiagnosticError = err.into();
                err.register_src(crate_name.into(), src.into());
                return Err(err);
            }
        };

        let mut file = file_cache::FileWriteCache::new(dst.as_ref());

        for item in items {
            write!(&mut file, "{}", item.into_token_stream().to_string()).expect("mem I/O failed");
        }

        for item in syn_file.items {
            if let syn::Item::Macro(mut item_macro) = item {
                let is_our_macro = [FOREIGNER_CLASS, FOREIGN_ENUM, FOREIGN_INTERFACE]
                    .iter()
                    .any(|x| item_macro.mac.path.is_ident(x));
                if !is_our_macro {
                    writeln!(&mut file, "{}", item_macro.into_token_stream().to_string())
                        .expect("mem I/O failed");
                    continue;
                }
                trace!("Found {:?}", item_macro.mac.path);
                let mut tts = TokenStream::new();
                mem::swap(&mut tts, &mut item_macro.mac.tts);
                let code;
                if item_macro.mac.path.is_ident(FOREIGNER_CLASS) {
                    let fclass = code_parse::parse_foreigner_class(&self.config, tts)?;
                    debug!(
                        "expand_foreigner_class: self {:?}, this_for_method {:?}, constructor {:?}",
                        fclass.self_type, fclass.this_type_for_method, fclass.constructor_ret_type
                    );
                    self.conv_map.register_foreigner_class(&fclass);
                    code = Generator::language_generator(&self.config).generate(
                        &mut self.conv_map,
                        self.pointer_target_width,
                        &fclass,
                    )?;
                } else if item_macro.mac.path.is_ident(FOREIGN_ENUM) {
                    let fenum = code_parse::parse_foreign_enum(tts)?;
                    code = Generator::language_generator(&self.config).generate_enum(
                        &mut self.conv_map,
                        self.pointer_target_width,
                        &fenum,
                    )?;
                } else if item_macro.mac.path.is_ident(FOREIGN_INTERFACE) {
                    let finterface = code_parse::parse_foreign_interface(tts)?;
                    code = Generator::language_generator(&self.config).generate_interface(
                        &mut self.conv_map,
                        self.pointer_target_width,
                        &finterface,
                    )?;
                } else {
                    unreachable!();
                }
                for elem in code {
                    writeln!(&mut file, "{}", elem.to_string()).expect("mem I/O failed");
                }
            } else {
                writeln!(&mut file, "{}", item.into_token_stream().to_string())
                    .expect("mem I/O failed");
            }
        }

        file.update_file_if_necessary().unwrap_or_else(|err| {
            panic!(
                "Error during write to file {}: {}",
                dst.as_ref().display(),
                err
            );
        });
        Ok(())
    }

    fn init_types_map(&mut self, target_pointer_width: usize) -> Result<Vec<syn::Item>> {
        if self.init_done {
            return Ok(vec![]);
        }
        self.init_done = true;
        for code in &self.conv_map_source {
            self.conv_map
                .merge(&code.id_of_code, &code.code, target_pointer_width)?;
        }

        if self.conv_map.is_empty() {
            return Err(DiagnosticError::new(
                Span::call_site(),
                "After merge all \"types maps\" have no convertion code",
            ));
        }

        Generator::language_generator(&self.config)
            .place_foreign_lang_helpers(&self.foreign_lang_helpers)
            .map_err(|err| {
                DiagnosticError::new(
                    Span::call_site(),
                    format!("Can not put/generate foreign lang helpers: {}", err),
                )
            })?;

        Ok(self.conv_map.take_utils_code())
    }

    fn language_generator(cfg: &LanguageConfig) -> &LanguageGenerator {
        match cfg {
            LanguageConfig::JavaConfig(ref java_cfg) => java_cfg,
            LanguageConfig::CppConfig(ref cpp_cfg) => cpp_cfg,
        }
    }
}

#[derive(Debug, Clone)]
struct ForeignerClassInfo {
    name: Ident,
    methods: Vec<ForeignerMethod>,
    self_type: Option<RustType>,
    /// Not necessarily equal to self_type, may be for example Rc<self_type>
    this_type_for_method: Option<Type>,
    foreigner_code: String,
    /// For example if we have `fn new(x: X) -> Result<Y, Z>`, then Result<Y, Z>
    constructor_ret_type: Option<Type>,
    doc_comments: Vec<String>,
}

impl ForeignerClassInfo {
    fn span(&self) -> Span {
        self.name.span()
    }
    fn self_type_name(&self) -> &str {
        self.self_type
            .as_ref()
            .map(|x| x.normalized_name.as_str())
            .unwrap_or("")
    }
    fn self_type_as_ty(&self) -> Type {
        self.self_type
            .as_ref()
            .map(|x| x.ty.clone())
            .unwrap_or_else(|| parse_quote! { () })
    }
    /// common for several language binding generator code
    fn validate_class(&self) -> Result<()> {
        let mut has_constructor = false;
        let mut has_methods = false;
        for x in &self.methods {
            match x.variant {
                MethodVariant::Constructor => has_constructor = true,
                MethodVariant::Method(_) => has_methods = true,
                _ => {}
            }
        }
        if self.self_type.is_none() && has_constructor {
            Err(DiagnosticError::new(
                self.span(),
                format!(
                    "class {} has constructor, but no self_type defined",
                    self.name
                ),
            ))
        } else if self.self_type.is_none() && has_methods {
            Err(DiagnosticError::new(
                self.span(),
                format!("class {} has methods, but no self_type defined", self.name),
            ))
        } else {
            Ok(())
        }
    }
}

#[derive(Debug, Clone)]
struct ForeignerMethod {
    variant: MethodVariant,
    rust_id: syn::Path,
    fn_decl: FnDecl,
    name_alias: Option<Ident>,
    /// cache if rust_fn_decl.output == Result
    may_return_error: bool,
    access: MethodAccess,
    doc_comments: Vec<String>,
}

#[derive(Debug, Clone)]
struct FnDecl {
    span: Span,
    inputs: syn::punctuated::Punctuated<syn::FnArg, Token![,]>,
    output: syn::ReturnType,
}

impl FnDecl {
    fn span(&self) -> Span {
        self.span
    }
}

impl From<syn::FnDecl> for crate::FnDecl {
    fn from(x: syn::FnDecl) -> Self {
        crate::FnDecl {
            span: x.fn_token.span(),
            inputs: x.inputs,
            output: x.output,
        }
    }
}

impl ForeignerMethod {
    fn short_name(&self) -> String {
        if let Some(ref name) = self.name_alias {
            name.to_string()
        } else {
            match self.rust_id.segments.len() {
                0 => String::new(),
                n => self.rust_id.segments[n - 1].ident.to_string(),
            }
        }
    }

    fn span(&self) -> Span {
        self.rust_id.span()
    }

    fn is_dummy_constructor(&self) -> bool {
        self.rust_id.segments.is_empty()
    }
}

#[derive(PartialEq, Clone, Copy, Debug)]
enum MethodAccess {
    Private,
    Public,
    Protected,
}
#[derive(PartialEq, Clone, Copy, Debug)]
enum MethodVariant {
    Constructor,
    Method(SelfTypeVariant),
    StaticMethod,
}

#[derive(PartialEq, Clone, Copy, Debug)]
enum SelfTypeVariant {
    RptrMut,
    Rptr,
    Mut,
    Default,
}

impl SelfTypeVariant {
    fn is_read_only(self) -> bool {
        match self {
            SelfTypeVariant::RptrMut | SelfTypeVariant::Mut => false,
            SelfTypeVariant::Default | SelfTypeVariant::Rptr => true,
        }
    }
}

#[derive(Debug, Clone)]
struct ForeignEnumInfo {
    name: Ident,
    items: Vec<ForeignEnumItem>,
    doc_comments: Vec<String>,
}

impl ForeignEnumInfo {
    fn rust_enum_name(&self) -> String {
        self.name.to_string()
    }
    fn span(&self) -> Span {
        self.name.span()
    }
}

#[derive(Debug, Clone)]
struct ForeignEnumItem {
    name: Ident,
    rust_name: syn::Path,
    doc_comments: Vec<String>,
}

struct ForeignInterface {
    name: Ident,
    self_type: syn::Path,
    doc_comments: Vec<String>,
    items: Vec<ForeignInterfaceMethod>,
}

impl ForeignInterface {
    fn span(&self) -> Span {
        self.name.span()
    }
}

struct ForeignInterfaceMethod {
    name: Ident,
    rust_name: syn::Path,
    fn_decl: FnDecl,
    doc_comments: Vec<String>,
}

trait LanguageGenerator {
    fn generate(
        &self,
        conv_map: &mut TypeMap,
        pointer_target_width: usize,
        class: &ForeignerClassInfo,
    ) -> Result<Vec<TokenStream>>;

    fn generate_enum(
        &self,
        conv_map: &mut TypeMap,
        pointer_target_width: usize,
        enum_info: &ForeignEnumInfo,
    ) -> Result<Vec<TokenStream>>;

    fn generate_interface(
        &self,
        conv_map: &mut TypeMap,
        pointer_target_width: usize,
        interace: &ForeignInterface,
    ) -> Result<Vec<TokenStream>>;

    fn place_foreign_lang_helpers(&self, _: &[SourceCode]) -> std::result::Result<(), String> {
        Ok(())
    }
}