flutter_rust_bridge_codegen 1.62.0

High-level memory-safe binding generator for Flutter/Dart <-> Rust
Documentation
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
/*
    Things this doesn't currently support that it might need to later:

    - Import parsing is unfinished and so is currently disabled
    - When import parsing is enabled:
        - Import renames (use a::b as c) - these are silently ignored
        - Imports that start with two colons (use ::a::b) - these are also silently ignored
*/

use std::{
    collections::HashMap,
    fmt::Debug,
    fs,
    path::{Path, PathBuf},
};

use cargo_metadata::MetadataCommand;
use log::{debug, warn};
use syn::{Attribute, Ident, ItemEnum, ItemStruct, PathArguments, Type, UseTree};

use crate::markers;

/// Represents a crate, including a map of its modules, imports, structs and
/// enums.
#[derive(Debug, Clone)]
pub struct Crate {
    pub name: String,
    pub manifest_path: PathBuf,
    pub root_src_file: PathBuf,
    pub root_module: Module,
}

impl Crate {
    pub fn new(manifest_path: &str) -> Self {
        let mut cmd = MetadataCommand::new();
        cmd.manifest_path(manifest_path);

        let metadata = cmd.exec().unwrap();

        let root_package = metadata.root_package().unwrap();
        let root_src_file = {
            let lib_file = root_package
                .manifest_path
                .parent()
                .unwrap()
                .join("src/lib.rs");
            let main_file = root_package
                .manifest_path
                .parent()
                .unwrap()
                .join("src/main.rs");

            if lib_file.exists() {
                fs::canonicalize(lib_file).unwrap()
            } else if main_file.exists() {
                fs::canonicalize(main_file).unwrap()
            } else {
                panic!("No src/lib.rs or src/main.rs found for this Cargo.toml file");
            }
        };

        let source_rust_content = fs::read_to_string(&root_src_file).unwrap();
        let file_ast = syn::parse_file(&source_rust_content).unwrap();

        let mut result = Crate {
            name: root_package.name.clone(),
            manifest_path: fs::canonicalize(manifest_path).unwrap(),
            root_src_file: root_src_file.clone(),
            root_module: Module {
                visibility: Visibility::Public,
                file_path: root_src_file,
                module_path: vec!["crate".to_string()],
                source: Some(ModuleSource::File(file_ast)),
                scope: None,
            },
        };

        result.resolve();

        result
    }

    /// Create a map of the modules for this crate
    pub fn resolve(&mut self) {
        self.root_module.resolve();
    }
}

/// Mirrors syn::Visibility, but can be created without a token
#[derive(Debug, Clone)]
pub enum Visibility {
    Public,
    Crate,
    Restricted, // Not supported
    Inherited,  // Usually means private
}

fn syn_vis_to_visibility(vis: &syn::Visibility) -> Visibility {
    match vis {
        syn::Visibility::Public(_) => Visibility::Public,
        syn::Visibility::Crate(_) => Visibility::Crate,
        syn::Visibility::Restricted(_) => Visibility::Restricted,
        syn::Visibility::Inherited => Visibility::Inherited,
    }
}

#[derive(Debug, Clone)]
pub struct Import {
    pub path: Vec<String>,
    pub visibility: Visibility,
}

#[derive(Debug, Clone)]
pub enum ModuleSource {
    File(syn::File),
    ModuleInFile(Vec<syn::Item>),
}

#[derive(Clone)]
pub struct Struct {
    pub ident: Ident,
    pub src: ItemStruct,
    pub visibility: Visibility,
    pub path: Vec<String>,
    pub mirror: bool,
}

impl Debug for Struct {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Struct")
            .field("ident", &self.ident)
            .field("src", &"omitted")
            .field("visibility", &self.visibility)
            .field("path", &self.path)
            .field("mirror", &self.mirror)
            .finish()
    }
}

#[derive(Clone)]
pub struct Enum {
    pub ident: Ident,
    pub src: ItemEnum,
    pub visibility: Visibility,
    pub path: Vec<String>,
    pub mirror: bool,
}

impl Debug for Enum {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Enum")
            .field("ident", &self.ident)
            .field("src", &"omitted")
            .field("visibility", &self.visibility)
            .field("path", &self.path)
            .field("mirror", &self.mirror)
            .finish()
    }
}

#[derive(Clone, Debug)]
pub struct TypeAlias {
    pub ident: String,
    pub target: Type,
}

#[derive(Debug, Clone)]
pub struct ModuleScope {
    pub modules: Vec<Module>,
    pub enums: Vec<Enum>,
    pub structs: Vec<Struct>,
    pub imports: Vec<Import>,
    pub type_alias: Vec<TypeAlias>,
}

#[derive(Clone)]
pub struct Module {
    pub visibility: Visibility,
    pub file_path: PathBuf,
    pub module_path: Vec<String>,
    pub source: Option<ModuleSource>,
    pub scope: Option<ModuleScope>,
}

impl Debug for Module {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Module")
            .field("visibility", &self.visibility)
            .field("module_path", &self.module_path)
            .field("file_path", &self.file_path)
            .field("source", &"omitted")
            .field("scope", &self.scope)
            .finish()
    }
}

/// Get a struct or enum ident, possibly remapped by a mirror marker
fn get_ident(ident: &Ident, attrs: &[Attribute]) -> (Vec<Ident>, bool) {
    let res = markers::extract_mirror_marker(attrs)
        .into_iter()
        .filter_map(|path| {
            // eq: path.get_ident().map(Clone::clone)
            if path.leading_colon.is_none()
                && path.segments.len() == 1
                && path.segments[0].arguments == PathArguments::None
            {
                Some(path.segments.into_iter().next().unwrap().ident)
            } else {
                None
            }
        })
        .collect::<Vec<_>>();
    let mirror = !res.is_empty();
    if mirror {
        (res, mirror)
    } else {
        (vec![ident.clone()], mirror)
    }
}

fn try_get_module_file_path(
    folder_path: &Path,
    module_name: &str,
    tried: &mut Vec<PathBuf>,
) -> Option<PathBuf> {
    let file_path = folder_path.join(module_name).with_extension("rs");
    if file_path.exists() {
        return Some(file_path);
    }
    tried.push(file_path);

    let file_path = folder_path.join(module_name).join("mod.rs");
    if file_path.exists() {
        return Some(file_path);
    }
    tried.push(file_path);

    None
}

fn get_module_file_path(
    module_name: String,
    parent_module_file_path: &Path,
) -> Result<PathBuf, Vec<PathBuf>> {
    let mut tried = Vec::new();

    if let Some(file_path) = try_get_module_file_path(
        parent_module_file_path.parent().unwrap(),
        &module_name,
        &mut tried,
    ) {
        return Ok(file_path);
    }
    if let Some(file_path) = try_get_module_file_path(
        &parent_module_file_path.with_extension(""),
        &module_name,
        &mut tried,
    ) {
        return Ok(file_path);
    }
    Err(tried)
}

impl Module {
    pub fn resolve(&mut self) {
        self.resolve_modules();
        // self.resolve_imports();
    }

    /// Maps out modules, structs and enums within the scope of this module
    fn resolve_modules(&mut self) {
        let mut scope_modules = Vec::new();
        let mut scope_structs = Vec::new();
        let mut scope_enums = Vec::new();
        let mut scope_types = Vec::new();

        let items = match self.source.as_ref().unwrap() {
            ModuleSource::File(file) => &file.items,
            ModuleSource::ModuleInFile(items) => items,
        };

        for item in items.iter() {
            match item {
                syn::Item::Struct(item_struct) => {
                    let (idents, mirror) = get_ident(&item_struct.ident, &item_struct.attrs);

                    scope_structs.extend(idents.into_iter().map(|ident| {
                        let ident_str = ident.to_string();
                        Struct {
                            ident,
                            src: item_struct.clone(),
                            visibility: syn_vis_to_visibility(&item_struct.vis),
                            path: {
                                let mut path = self.module_path.clone();
                                path.push(ident_str);
                                path
                            },
                            mirror,
                        }
                    }));
                }
                syn::Item::Enum(item_enum) => {
                    let (idents, mirror) = get_ident(&item_enum.ident, &item_enum.attrs);

                    scope_enums.extend(idents.into_iter().map(|ident| {
                        let ident_str = ident.to_string();
                        Enum {
                            ident,
                            src: item_enum.clone(),
                            visibility: syn_vis_to_visibility(&item_enum.vis),
                            path: {
                                let mut path = self.module_path.clone();
                                path.push(ident_str);
                                path
                            },
                            mirror,
                        }
                    }));
                }
                syn::Item::Type(item_type) => {
                    if item_type.generics.where_clause.is_none()
                        && item_type.generics.lt_token.is_none()
                    {
                        scope_types.push(TypeAlias {
                            ident: item_type.ident.to_string(),
                            target: *item_type.ty.clone(),
                        });
                    }
                }
                syn::Item::Mod(item_mod) => {
                    let ident = item_mod.ident.clone();

                    let mut module_path = self.module_path.clone();
                    module_path.push(ident.to_string());

                    scope_modules.push(match &item_mod.content {
                        Some(content) => {
                            let mut child_module = Module {
                                visibility: syn_vis_to_visibility(&item_mod.vis),
                                file_path: self.file_path.clone(),
                                module_path,
                                source: Some(ModuleSource::ModuleInFile(content.1.clone())),
                                scope: None,
                            };

                            child_module.resolve();

                            child_module
                        }
                        None => {
                            let file_path =
                                get_module_file_path(ident.to_string(), &self.file_path);

                            match file_path {
                                Ok(file_path) => {
                                    let source = {
                                        let source_rust_content =
                                            fs::read_to_string(&file_path).unwrap();
                                        debug!("Trying to parse {:?}", file_path);
                                        Some(ModuleSource::File(
                                            syn::parse_file(&source_rust_content).unwrap(),
                                        ))
                                    };
                                    let mut child_module = Module {
                                        visibility: syn_vis_to_visibility(&item_mod.vis),
                                        file_path,
                                        module_path,
                                        source,
                                        scope: None,
                                    };

                                    child_module.resolve();
                                    child_module
                                }
                                Err(tried) => {
                                    warn!(
                                        "Skipping unresolvable module {} (tried {})",
                                        &ident,
                                        tried
                                            .into_iter()
                                            .map(|it| it.to_string_lossy().to_string())
                                            .fold(String::new(), |mut a, b| {
                                                a.push_str(&b);
                                                a.push_str(", ");
                                                a
                                            })
                                    );
                                    continue;
                                }
                            }
                        }
                    });
                }
                _ => {}
            }
        }

        self.scope = Some(ModuleScope {
            modules: scope_modules,
            enums: scope_enums,
            structs: scope_structs,
            imports: vec![], // Will be filled in by resolve_imports()
            type_alias: scope_types,
        });
    }

    #[allow(dead_code)]
    fn resolve_imports(&mut self) {
        let imports = &mut self.scope.as_mut().unwrap().imports;

        let items = match self.source.as_ref().unwrap() {
            ModuleSource::File(file) => &file.items,
            ModuleSource::ModuleInFile(items) => items,
        };

        for item in items.iter() {
            if let syn::Item::Use(item_use) = item {
                let flattened_imports = flatten_use_tree(&item_use.tree);

                for import in flattened_imports {
                    imports.push(Import {
                        path: import,
                        visibility: syn_vis_to_visibility(&item_use.vis),
                    });
                }
            }
        }
    }

    pub fn collect_structs<'a>(&'a self, container: &mut HashMap<String, &'a Struct>) {
        let scope = self.scope.as_ref().unwrap();
        for scope_struct in &scope.structs {
            container.insert(scope_struct.ident.to_string(), scope_struct);
        }
        for scope_module in &scope.modules {
            scope_module.collect_structs(container);
        }
    }

    pub fn collect_structs_to_vec(&self) -> HashMap<String, &Struct> {
        let mut ans = HashMap::new();
        self.collect_structs(&mut ans);
        ans
    }

    pub fn collect_enums<'a>(&'a self, container: &mut HashMap<String, &'a Enum>) {
        let scope = self.scope.as_ref().unwrap();
        for scope_enum in &scope.enums {
            container.insert(scope_enum.ident.to_string(), scope_enum);
        }
        for scope_module in &scope.modules {
            scope_module.collect_enums(container);
        }
    }

    pub fn collect_enums_to_vec(&self) -> HashMap<String, &Enum> {
        let mut ans = HashMap::new();
        self.collect_enums(&mut ans);
        ans
    }
    pub fn collect_types(&self, container: &mut HashMap<String, Type>) {
        let scope = self.scope.as_ref().unwrap();
        for scope_type in &scope.type_alias {
            container.insert(scope_type.ident.to_string(), scope_type.target.clone());
        }
        for scope_module in &scope.modules {
            scope_module.collect_types(container);
        }
    }

    pub fn collect_types_to_pool(&self) -> HashMap<String, Type> {
        let mut ans = HashMap::new();
        self.collect_types(&mut ans);
        ans
    }
}

fn flatten_use_tree_rename_abort_warning(use_tree: &UseTree) {
    debug!("WARNING: flatten_use_tree() found an import rename (use a::b as c). flatten_use_tree() will now abort.");
    debug!("WARNING: This happened while parsing {:?}", use_tree);
    debug!("WARNING: This use statement will be ignored.");
}

/// Takes a use tree and returns a flat list of use paths (list of string tokens)
///
/// Example:
///     use a::{b::c, d::e};
/// becomes
///     [
///         ["a", "b", "c"],
///         ["a", "d", "e"]
///     ]
///
/// Warning: As of writing, import renames (import a::b as c) are silently
/// ignored.
fn flatten_use_tree(use_tree: &UseTree) -> Vec<Vec<String>> {
    // Vec<(path, is_complete)>
    let mut result = vec![(vec![], false)];

    let mut counter: usize = 0;

    loop {
        counter += 1;

        if counter > 10000 {
            panic!("flatten_use_tree: Use statement complexity limit exceeded. This is probably a bug.");
        }

        // If all paths are complete, break from the loop
        if result.iter().all(|result_item| result_item.1) {
            break;
        }

        let mut items_to_push = Vec::new();

        for path_tuple in &mut result {
            let path = &mut path_tuple.0;
            let is_complete = &mut path_tuple.1;

            if *is_complete {
                continue;
            }

            let mut tree_cursor = use_tree;

            for path_item in path.iter() {
                match tree_cursor {
                    UseTree::Path(use_path) => {
                        let ident = use_path.ident.to_string();
                        if *path_item != ident {
                            panic!("This ident did not match the one we already collected. This is a bug.");
                        }
                        tree_cursor = use_path.tree.as_ref();
                    }
                    UseTree::Group(use_group) => {
                        let mut moved_tree_cursor = false;

                        for tree in use_group.items.iter() {
                            match tree {
                                UseTree::Path(use_path) => {
                                    if path_item == &use_path.ident.to_string() {
                                        tree_cursor = use_path.tree.as_ref();
                                        moved_tree_cursor = true;
                                        break;
                                    }
                                }
                                // Since we're not matching UseTree::Group here, a::b::{{c}, {d}} might
                                // break. But also why would anybody do that
                                _ => unreachable!(),
                            }
                        }

                        if !moved_tree_cursor {
                            unreachable!();
                        }
                    }
                    _ => unreachable!(),
                }
            }

            match tree_cursor {
                UseTree::Name(use_name) => {
                    path.push(use_name.ident.to_string());
                    *is_complete = true;
                }
                UseTree::Path(use_path) => {
                    path.push(use_path.ident.to_string());
                }
                UseTree::Glob(_) => {
                    path.push("*".to_string());
                    *is_complete = true;
                }
                UseTree::Group(use_group) => {
                    // We'll modify the first one in-place, and make clones for
                    // all subsequent ones
                    let mut first: bool = true;
                    // Capture the path in this state, since we're about to
                    // modify it
                    let path_copy = path.clone();
                    for tree in use_group.items.iter() {
                        let mut new_path_tuple = if first {
                            None
                        } else {
                            let new_path = path_copy.clone();
                            items_to_push.push((new_path, false));
                            Some(items_to_push.iter_mut().last().unwrap())
                        };

                        match tree {
                            UseTree::Path(use_path) => {
                                let ident = use_path.ident.to_string();

                                if first {
                                    path.push(ident);
                                } else {
                                    new_path_tuple.unwrap().0.push(ident);
                                }
                            }
                            UseTree::Name(use_name) => {
                                let ident = use_name.ident.to_string();

                                if first {
                                    path.push(ident);
                                    *is_complete = true;
                                } else {
                                    let path_tuple = new_path_tuple.as_mut().unwrap();
                                    path_tuple.0.push(ident);
                                    path_tuple.1 = true;
                                }
                            }
                            UseTree::Glob(_) => {
                                if first {
                                    path.push("*".to_string());
                                    *is_complete = true;
                                } else {
                                    let path_tuple = new_path_tuple.as_mut().unwrap();
                                    path_tuple.0.push("*".to_string());
                                    path_tuple.1 = true;
                                }
                            }
                            UseTree::Group(_) => {
                                panic!(
                                    "Directly-nested use groups ({}) are not supported by flutter_rust_bridge. Use {} instead.",
                                    "use a::{{b}, c}",
                                    "a::{b, c}"
                                );
                            }
                            // UseTree::Group(_) => panic!(),
                            UseTree::Rename(_) => {
                                flatten_use_tree_rename_abort_warning(use_tree);
                                return vec![];
                            }
                        }

                        first = false;
                    }
                }
                UseTree::Rename(_) => {
                    flatten_use_tree_rename_abort_warning(use_tree);
                    return vec![];
                }
            }
        }

        for item in items_to_push {
            result.push(item);
        }
    }

    result.into_iter().map(|val| val.0).collect()
}