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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
//! `rust_swig` is a Rust Simplified Wrapper and Interface Generator used
//! to connect other programming languages to Rust.
//! 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_use]
extern crate bitflags;
#[cfg(test)]
extern crate env_logger;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate petgraph;
extern crate syntex;
extern crate syntex_errors;
extern crate syntex_pos;
extern crate syntex_syntax;

macro_rules! unwrap_presult {
    ($presult_epxr:expr) => {
        match $presult_epxr {
            Ok(x) => x,
            Err(mut err) => {
                err.emit();
                panic!("rust_swig fatal error, see above");
            }
        }
    };
    ($presult_epxr:expr, $conv_map:expr) => {
        match $presult_epxr {
            Ok(x) => x,
            Err(mut err) => {
                debug!("{}", $conv_map);
                err.emit();
                panic!("rust_swig fatal error, see above");
            }
        }
    };
}

mod types_conv_map;
mod java_jni;
mod errors;
mod parsing;
mod my_ast;
mod cpp;

use std::path::PathBuf;
use std::cell::RefCell;
use std::rc::Rc;
use std::env;
use std::str::FromStr;

use syntex_syntax::parse::ParseSess;
use syntex_syntax::codemap::Span;
use syntex::Registry;
use syntex_syntax::tokenstream::TokenTree;
use syntex_syntax::ext::base::{ExtCtxt, MacEager, MacResult, TTMacroExpander};
use syntex_syntax::parse::PResult;
use syntex_syntax::ptr::P;
use syntex_syntax::ast;
use syntex_pos::DUMMY_SP;
use syntex_syntax::symbol::Symbol;
use syntex_syntax::util::small_vector::SmallVector;

use types_conv_map::TypesConvMap;
use errors::fatal_error;
use parsing::{parse_foreign_enum, parse_foreign_interface, parse_foreigner_class};

/// 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
#[derive(Clone)]
pub enum LanguageConfig {
    #[deprecated(since = "0.1.0", note = "please use `JavaConfig` instead")]
    Java {
        /// directory where place generated java files
        output_dir: PathBuf,
        /// package name for generated java files
        package_name: String,
    },
    JavaConfig(JavaConfig),
    CppConfig(CppConfig),
}

trait LanguageGenerator {
    fn generate<'a>(
        &self,
        sess: &'a ParseSess,
        conv_map: &mut TypesConvMap,
        pointer_target_width: usize,
        class: &ForeignerClassInfo,
    ) -> PResult<'a, Vec<P<ast::Item>>>;

    fn generate_enum<'a>(
        &self,
        sess: &'a ParseSess,
        conv_map: &mut TypesConvMap,
        pointer_target_width: usize,
        enum_info: &ForeignEnumInfo,
    ) -> PResult<'a, Vec<P<ast::Item>>>;

    fn generate_interface<'a>(
        &self,
        sess: &'a ParseSess,
        conv_map: &mut TypesConvMap,
        pointer_target_width: usize,
        interace: &ForeignInterface,
    ) -> PResult<'a, Vec<P<ast::Item>>>;

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

/// `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 {
    pointer_target_width: Option<usize>,
    // Because of API of syntex, to register for several macroses
    data: Rc<RefCell<GeneratorData>>,
}

struct GeneratorData {
    init_done: bool,
    config: LanguageConfig,
    conv_map: TypesConvMap,
    conv_map_source: Vec<SourceCode>,
    foreign_lang_helpers: Vec<SourceCode>,
    pointer_target_width: usize,
}

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

#[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(PartialEq, Clone, Copy, Debug)]
enum MethodVariant {
    Constructor,
    Method(SelfTypeVariant),
    StaticMethod,
}

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

impl ForeignerMethod {
    fn short_name(&self) -> Symbol {
        if let Some(name) = self.name_alias {
            name
        } else {
            match self.rust_id.segments.len() {
                0 => Symbol::intern(""),
                n => self.rust_id.segments[n - 1].identifier.name,
            }
        }
    }

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

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

#[derive(Debug, Clone)]
struct ForeignEnumItem {
    name: Symbol,
    span: Span,
    rust_name: ast::Path,
    doc_comments: Vec<Symbol>,
}

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

impl ForeignEnumInfo {
    fn rust_enum_name(&self) -> Symbol {
        self.name
    }
}

struct ForeignInterfaceMethod {
    name: Symbol,
    rust_name: ast::Path,
    fn_decl: P<ast::FnDecl>,
    doc_comments: Vec<Symbol>,
}

struct ForeignInterface {
    name: Symbol,
    self_type: ast::Path,
    doc_comments: Vec<Symbol>,
    items: Vec<ForeignInterfaceMethod>,
    span: Span,
}

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();
        #[allow(deprecated)]
        match config {
            LanguageConfig::Java { .. } | LanguageConfig::JavaConfig(..) => {
                conv_map_source.push(SourceCode {
                    id_of_code: "jni-include.rs".into(),
                    code: include_str!("java_jni/jni-include.rs").into(),
                });
            }
            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(),
                });
            }
        }
        Generator {
            pointer_target_width,
            data: Rc::new(RefCell::new(GeneratorData {
                init_done: false,
                config,
                conv_map: TypesConvMap::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 = Some(pointer_target_width);
        self.data.borrow_mut().pointer_target_width = pointer_target_width;
        self
    }

    pub fn register(self, registry: &mut Registry) {
        self.pointer_target_width.unwrap_or_else(|| {
            panic!(
                r#"pointer target width unknown,
 set env CARGO_CFG_TARGET_POINTER_WIDTH environment variable,
 or use `with_pointer_target_width` function
"#
            )
        });
        registry.add_macro("foreign_enum", EnumHandler(self.data.clone()));
        registry.add_macro("foreign_interface", InterfaceHandler(self.data.clone()));
        registry.add_macro("foreigner_class", self);
    }

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

impl TTMacroExpander for Generator {
    fn expand<'a>(
        &self,
        cx: &'a mut ExtCtxt,
        _: Span,
        tokens: &[TokenTree],
    ) -> Box<MacResult + 'a> {
        self.data.borrow_mut().expand_foreigner_class(cx, tokens)
    }
}

struct EnumHandler(Rc<RefCell<GeneratorData>>);

impl TTMacroExpander for EnumHandler {
    fn expand<'a>(
        &self,
        cx: &'a mut ExtCtxt,
        _: Span,
        tokens: &[TokenTree],
    ) -> Box<MacResult + 'a> {
        self.0.borrow_mut().expand_foreign_enum(cx, tokens)
    }
}

struct InterfaceHandler(Rc<RefCell<GeneratorData>>);
impl TTMacroExpander for InterfaceHandler {
    fn expand<'a>(
        &self,
        cx: &'a mut ExtCtxt,
        _: Span,
        tokens: &[TokenTree],
    ) -> Box<MacResult + 'a> {
        self.0.borrow_mut().expand_foreign_interface(cx, tokens)
    }
}

impl GeneratorData {
    fn generate_code_for_foreign_interface<'a>(
        &mut self,
        cx: &'a mut ExtCtxt,
        foreign_interface: &ForeignInterface,
        lang_gen: &LanguageGenerator,
        mut items: Vec<P<ast::Item>>,
    ) -> Box<MacResult + 'a> {
        let mut gen_items = unwrap_presult!(
            lang_gen.generate_interface(
                cx.parse_sess(),
                &mut self.conv_map,
                self.pointer_target_width,
                foreign_interface
            ),
            self.conv_map
        );
        items.append(&mut gen_items);
        MacEager::items(SmallVector::many(items))
    }

    fn expand_foreign_interface<'a>(
        &mut self,
        cx: &'a mut ExtCtxt,
        tokens: &[TokenTree],
    ) -> Box<MacResult + 'a> {
        let pointer_target_width = self.pointer_target_width;
        let items = unwrap_presult!(
            self.init_types_map(cx.parse_sess(), pointer_target_width),
            self.conv_map
        );
        let foreign_interface =
            parse_foreign_interface(cx, tokens).expect("Can not parse foreign_interface");
        #[allow(deprecated)]
        match self.config.clone() {
            LanguageConfig::Java {
                ref output_dir,
                ref package_name,
            } => {
                let java_cfg = JavaConfig::new(output_dir.clone(), package_name.clone());
                self.generate_code_for_foreign_interface(cx, &foreign_interface, &java_cfg, items)
            }
            LanguageConfig::JavaConfig(ref java_cfg) => {
                self.generate_code_for_foreign_interface(cx, &foreign_interface, java_cfg, items)
            }
            LanguageConfig::CppConfig(ref cpp_cfg) => {
                self.generate_code_for_foreign_interface(cx, &foreign_interface, cpp_cfg, items)
            }
        }
    }

    fn generate_code_for_enum<'a>(
        &mut self,
        cx: &'a mut ExtCtxt,
        foreign_enum: &ForeignEnumInfo,
        lang_gen: &LanguageGenerator,
        mut items: Vec<P<ast::Item>>,
    ) -> Box<MacResult + 'a> {
        let mut gen_items = unwrap_presult!(
            lang_gen.generate_enum(
                cx.parse_sess(),
                &mut self.conv_map,
                self.pointer_target_width,
                foreign_enum
            ),
            self.conv_map
        );
        items.append(&mut gen_items);
        MacEager::items(SmallVector::many(items))
    }

    fn expand_foreign_enum<'a>(
        &mut self,
        cx: &'a mut ExtCtxt,
        tokens: &[TokenTree],
    ) -> Box<MacResult + 'a> {
        let pointer_target_width = self.pointer_target_width;
        let items = unwrap_presult!(
            self.init_types_map(cx.parse_sess(), pointer_target_width),
            self.conv_map
        );
        let foreign_enum = parse_foreign_enum(cx, tokens).expect("Can not parse foreign_enum");

        #[allow(deprecated)]
        match self.config.clone() {
            LanguageConfig::Java {
                ref output_dir,
                ref package_name,
            } => {
                let java_cfg = JavaConfig::new(output_dir.clone(), package_name.clone());
                self.generate_code_for_enum(cx, &foreign_enum, &java_cfg, items)
            }
            LanguageConfig::JavaConfig(ref java_cfg) => {
                self.generate_code_for_enum(cx, &foreign_enum, java_cfg, items)
            }
            LanguageConfig::CppConfig(ref cpp_cfg) => {
                self.generate_code_for_enum(cx, &foreign_enum, cpp_cfg, items)
            }
        }
    }

    fn generate_code_for_class<'a>(
        &mut self,
        cx: &'a mut ExtCtxt,
        foreign_class: &ForeignerClassInfo,
        lang_gen: &LanguageGenerator,
        mut items: Vec<P<ast::Item>>,
    ) -> Box<MacResult + 'a> {
        let mut gen_items = unwrap_presult!(
            lang_gen.generate(
                cx.parse_sess(),
                &mut self.conv_map,
                self.pointer_target_width,
                foreign_class,
            ),
            self.conv_map
        );
        items.append(&mut gen_items);
        MacEager::items(SmallVector::many(items))
    }

    fn expand_foreigner_class<'a>(
        &mut self,
        cx: &'a mut ExtCtxt,
        tokens: &[TokenTree],
    ) -> Box<MacResult + 'a> {
        let pointer_target_width = self.pointer_target_width;
        let items = unwrap_presult!(
            self.init_types_map(cx.parse_sess(), pointer_target_width),
            self.conv_map
        );
        let foreigner_class = match parse_foreigner_class(cx, tokens) {
            Ok(x) => x,
            Err(_) => {
                panic!("Can not parse foreigner_class");
                //return DummyResult::any(span);
            }
        };
        self.conv_map.register_foreigner_class(&foreigner_class);
        #[allow(deprecated)]
        match self.config.clone() {
            LanguageConfig::Java {
                ref output_dir,
                ref package_name,
            } => {
                let java_cfg = JavaConfig::new(output_dir.clone(), package_name.clone());
                self.generate_code_for_class(cx, &foreigner_class, &java_cfg, items)
            }
            LanguageConfig::JavaConfig(ref java_cfg) => {
                self.generate_code_for_class(cx, &foreigner_class, java_cfg, items)
            }
            LanguageConfig::CppConfig(ref cpp_cfg) => {
                self.generate_code_for_class(cx, &foreigner_class, cpp_cfg, items)
            }
        }
    }

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

        if self.conv_map.is_empty() {
            return Err(fatal_error(
                sess,
                DUMMY_SP,
                "After merge all types maps with have no convertion code",
            ));
        }

        #[allow(deprecated)]
        match self.config.clone() {
            LanguageConfig::Java {
                ref output_dir,
                ref package_name,
            } => {
                let java_cfg = JavaConfig::new(output_dir.clone(), package_name.clone());
                java_cfg.place_foreign_lang_helpers(&self.foreign_lang_helpers)
            }
            LanguageConfig::JavaConfig(ref java_cfg) => {
                java_cfg.place_foreign_lang_helpers(&self.foreign_lang_helpers)
            }
            LanguageConfig::CppConfig(ref cpp_cfg) => {
                cpp_cfg.place_foreign_lang_helpers(&self.foreign_lang_helpers)
            }
        }.map_err(|err| {
            fatal_error(
                sess,
                DUMMY_SP,
                &format!("Can not put/generate foreign lang helpers: {}", err),
            )
        })?;

        Ok(self.conv_map.take_utils_code())
    }
}

/// Configuration for Java
#[derive(Clone)]
pub struct JavaConfig {
    output_dir: PathBuf,
    package_name: String,
    use_null_annotation: Option<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,
        }
    }
    /// 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
    }
}

/// To which `C++` type map `std::option::Option`
#[derive(Clone)]
pub enum CppOptional {
    /// `std::optional` from C++17 standard
    Std17,
    /// `boost::optional`
    Boost,
}

/// To which `C++` type map `std::result::Result`
#[derive(Clone)]
pub enum CppVariant {
    /// `std::variant` from C++17 standard
    Std17,
    /// `boost::variant`
    Boost,
}

#[derive(Clone)]
pub struct CppConfig {
    output_dir: PathBuf,
    namespace_name: String,
    cpp_optional: CppOptional,
    cpp_variant: CppVariant,
}

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,
        }
    }
    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
        }
    }
}