flutter_rust_bridge_codegen 2.13.0-beta.2

Flutter/Dart <-> Rust binding generator, feature-rich, but seamless and simple
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
use crate::codegen::ConfigDumpContent;
use clap::{Args, Parser, Subcommand, ValueEnum};
use lib_flutter_rust_bridge_codegen::{
    codegen::RustOpaqueCodecMode,
    misc::{IntegrationBackend, Template},
};
use std::path::PathBuf;

// The name `Cli`, `Commands` come from https://docs.rs/clap/latest/clap/_derive/_tutorial/chapter_0/index.html
#[derive(Debug, Parser)]
#[command(author, version, about, long_about = None)]
pub(crate) struct Cli {
    /// Show debug messages.
    #[arg(short, long)]
    pub verbose: bool,

    #[command(subcommand)]
    pub(crate) command: Commands,
}

#[allow(clippy::large_enum_variant)]
#[derive(Debug, Subcommand)]
pub(crate) enum Commands {
    /// Execute the main code generator
    Generate(GenerateCommandArgs),

    /// Create a new Flutter + Rust project
    Create(CreateCommandArgs),

    /// Integrate Rust into existing Flutter project
    Integrate(IntegrateCommandArgs),

    /// Compile for the Web (WASM)
    BuildWeb(BuildWebCommandArgs),

    /// Generate internally used code
    #[clap(hide = true)]
    InternalGenerate(InternalGenerateCommandArgs),
}

#[derive(Debug, Args, Default, Eq, PartialEq)]
pub(crate) struct GenerateCommandArgs {
    /// Automatically re-generate the output whenever the changes are detected on the input files
    #[arg(long)]
    pub watch: bool,

    #[clap(flatten)]
    pub primary: GenerateCommandArgsPrimary,

    /// Skip fvm installation
    #[clap(long)]
    pub skip_fvm_install: bool,
}

// Deliberately decoupled from `codegen::Config`,
// because the command line arguments contains extra things like `--config-file`,
// which is not a config to the real codegen.
#[derive(Debug, Args, Default, Eq, PartialEq, Clone)]
pub(crate) struct GenerateCommandArgsPrimary {
    /// Path to a YAML config file.
    ///
    /// If present, other options and flags will be ignored.
    /// Accepts the same options as the CLI, but uses snake_case keys.
    #[arg(long)]
    pub config_file: Option<String>,

    /// Input Rust files, such as `crate::api,crate::hello::world,another-third-party-crate`
    #[arg(short, long)]
    pub rust_input: Option<String>,

    /// Directory of output generated Dart code
    #[arg(short, long)]
    pub dart_output: Option<String>,

    /// Output path of generated C header
    #[arg(short, long)]
    pub c_output: Option<String>,

    /// Duplicate the files generated at the location `--c-output` specifies
    #[arg(long)]
    pub duplicated_c_output: Option<Vec<String>>,

    /// Crate directory for your Rust project
    #[arg(long)]
    pub rust_root: Option<String>,

    /// Output path of generated Rust code
    #[arg(long)]
    pub rust_output: Option<String>,

    /// Generated dart entrypoint class name
    #[arg(long)]
    pub dart_entrypoint_class_name: Option<String>,

    /// Line length for Dart formatting
    #[arg(long)]
    pub dart_format_line_length: Option<u32>,

    /// Raw header of output generated Dart code, pasted as-it-is.
    #[arg(long)]
    pub dart_preamble: Option<String>,

    /// Raw header of output generated Rust code, pasted as-it-is.
    #[arg(long)]
    pub rust_preamble: Option<String>,

    /// Use deep equality for Dart collection fields in generated non-freezed classes.
    #[arg(long)]
    pub dart_collection_deep_equality: bool,

    /// The generated Dart enums will not have their variant names camelCased.
    #[arg(long)]
    pub no_dart_enums_style: bool,

    /// Skip automatically adding `mod frb_generated;` to `lib.rs`
    #[arg(long)]
    pub no_add_mod_to_lib: bool,

    /// Path to the installed LLVM
    #[arg(long, num_args = 1..)]
    pub llvm_path: Option<Vec<String>>,

    /// LLVM compiler opts
    #[arg(long)]
    pub llvm_compiler_opts: Option<String>,

    /// Path to root of Dart project, otherwise inferred from --dart-output
    #[arg(long, num_args = 1..)]
    pub dart_root: Option<String>,

    /// Skip running build_runner even when codegen-required code is detected
    #[arg(long)]
    pub no_build_runner: bool,

    /// extra_headers is used to add dependencies header
    #[arg(long)]
    pub extra_headers: Option<String>,

    /// Disable web module generation.
    #[arg(long)]
    pub no_web: bool,

    /// Skip dependencies check.
    #[arg(long)]
    pub no_deps_check: bool,

    /// The value for defaultExternalLibraryLoader.webPrefix
    #[arg(long)]
    pub default_external_library_loader_web_prefix: Option<String>,

    /// The name of the wasm_bindgen module.
    #[arg(long)]
    pub wasm_bindgen_name: Option<String>,

    /// Disable language features introduced in Dart 3.
    #[arg(long)]
    pub no_dart3: bool,

    /// Enable full dependencies
    #[arg(long)]
    pub full_dep: bool,

    /// Default implementation of rust opaque
    #[arg(long)]
    pub default_rust_opaque_codec: Option<RustOpaqueCodecModeArg>,

    /// Use local version instead of the release version
    #[arg(long, hide = true)]
    pub local: bool,

    /// Enable parsing types with lifetimes (e.g. references and borrows)
    #[arg(long)]
    pub enable_lifetime: bool,

    /// Let 64 bit types be translated to `int`s instead of types like `BigInt`s
    #[arg(long)]
    pub type_64bit_int: bool,

    /// Whether default Dart code is asynchronous or synchronous
    #[arg(long)]
    pub no_default_dart_async: bool,

    /// Whether to skip auto upgrading the dependencies
    #[arg(long)]
    pub no_auto_upgrade_dependency: bool,

    /// Whether to automatically parse constants
    #[arg(long)]
    pub parse_const: bool,

    /// Whether to disable automatic Dart formatting
    #[arg(long)]
    pub no_dart_format: bool,

    /// Whether to disable automatic Dart fix
    #[arg(long)]
    pub no_dart_fix: bool,

    /// Whether to disable automatic Rust formatting
    #[arg(long)]
    pub no_rust_format: bool,

    /// If having error when, for example, parsing a function, directly stop instead of continue and skip it
    #[arg(long)]
    pub stop_on_error: bool,

    /// A list of data to be dumped. If specified without a value, defaults to all.
    #[arg(long, value_enum, num_args = 0.., default_missing_values = ["config", "ir"])]
    pub dump: Option<Vec<ConfigDumpContent>>,

    /// Dump all internal data. Same as `--dump` with all possible choices chosen.
    #[arg(long)]
    pub dump_all: bool,

    /// List of cargo feature flags to enable when generating
    #[arg(long)]
    pub rust_features: Option<Vec<String>>,
}

#[derive(Debug, Args)]
pub(crate) struct CreateCommandArgs {
    /// Name of the new project
    pub(crate) name: String,

    /// The organization responsible for your new Flutter project, in reverse domain name notation.
    #[clap(long)]
    pub(crate) org: Option<String>,

    #[clap(flatten)]
    pub common: CreateOrIntegrateCommandCommonArgs,

    /// The template type to use to generate the flutter files.
    #[clap(short, long, value_enum, default_value = "app")]
    pub template: TemplateArg,

    /// The integration backend used to compile and bundle Rust.
    #[clap(long, value_enum, default_value = "cargokit")]
    pub integration_backend: IntegrationBackendArg,

    /// Specify the platforms to be supported.
    #[clap(long)]
    pub platforms: Option<String>,

    /// Skip fvm installation
    #[clap(long)]
    pub skip_fvm_install: bool,
}

#[derive(Debug, Args)]
pub(crate) struct IntegrateCommandArgs {
    /// Do not generate code related to lib/example etc.
    #[arg(long)]
    pub(crate) no_write_lib: bool,

    /// Do not generate code related to integration test
    #[arg(long)]
    pub(crate) no_integration_test: bool,

    /// Do not apply dart fix after generating code.
    #[arg(long)]
    pub(crate) no_dart_fix: bool,

    /// Do not format dart code after generating code.
    #[arg(long)]
    pub(crate) no_dart_format: bool,

    #[clap(flatten)]
    pub common: CreateOrIntegrateCommandCommonArgs,

    /// The template type to use for integration. This should usually match the type of flutter project
    /// being integrating with.
    #[clap(short, long, value_enum, default_value = "app")]
    pub template: TemplateArg,

    /// The integration backend used to compile and bundle Rust.
    #[clap(long, value_enum, default_value = "cargokit")]
    pub integration_backend: IntegrationBackendArg,

    /// Specify the platforms to be supported.
    #[clap(long)]
    pub platforms: Option<String>,

    /// Skip fvm installation
    #[clap(long)]
    pub skip_fvm_install: bool,
}

#[derive(Debug, Copy, Clone, ValueEnum)]
pub(crate) enum TemplateArg {
    /// (default) a Flutter application
    App,
    /// A shareable Flutter project that can be used across multiple Flutter applications.
    Plugin,
}

#[derive(Debug, Copy, Clone, Eq, PartialEq, ValueEnum)]
pub(crate) enum IntegrationBackendArg {
    /// (default) Use Cargokit and generated platform scaffold.
    Cargokit,
    /// Use Dart/Flutter Native Assets build hooks.
    NativeAssets,
}

#[derive(Debug, Copy, Clone, Eq, PartialEq, ValueEnum)]
pub(crate) enum RustOpaqueCodecModeArg {
    /// Use moi codec
    Moi,
    /// Use nom codec
    Nom,
}

#[derive(Debug, Args)]
pub(crate) struct CreateOrIntegrateCommandCommonArgs {
    /// The name of the generated Rust crate
    #[arg(long)]
    pub rust_crate_name: Option<String>,

    /// The directory of the generated Rust crate, relative to the project path
    #[arg(long)]
    pub rust_crate_dir: Option<String>,

    /// Use local version instead of the release version
    #[arg(long, hide = true)]
    pub local: bool,
}

#[derive(Debug, Args)]
#[command(disable_help_flag = true)]
pub(crate) struct BuildWebCommandArgs {
    /// Path to root of Dart project, otherwise inferred from current working directory
    #[arg(long)]
    pub dart_root: Option<PathBuf>,

    /// Run Dart code with coverage
    #[arg(long, hide = true)]
    pub dart_coverage: bool,

    // https://stackoverflow.com/questions/72399790/clap-capture-all-remaining-arguments-in-one-field-in-derive-api
    #[arg(trailing_var_arg = true, allow_hyphen_values = true, hide = true)]
    pub(crate) args: Vec<String>,

    /// Skip fvm installation
    #[clap(long)]
    pub skip_fvm_install: bool,
}

#[derive(Debug, Args)]
pub(crate) struct InternalGenerateCommandArgs {}

impl From<TemplateArg> for Template {
    fn from(value: TemplateArg) -> Self {
        match value {
            TemplateArg::App => Template::App,
            TemplateArg::Plugin => Template::Plugin,
        }
    }
}

impl From<IntegrationBackendArg> for IntegrationBackend {
    fn from(value: IntegrationBackendArg) -> Self {
        match value {
            IntegrationBackendArg::Cargokit => IntegrationBackend::Cargokit,
            IntegrationBackendArg::NativeAssets => IntegrationBackend::NativeAssets,
        }
    }
}

impl From<RustOpaqueCodecModeArg> for RustOpaqueCodecMode {
    fn from(value: RustOpaqueCodecModeArg) -> Self {
        match value {
            RustOpaqueCodecModeArg::Moi => RustOpaqueCodecMode::Moi,
            RustOpaqueCodecModeArg::Nom => RustOpaqueCodecMode::Nom,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{Cli, Commands, IntegrationBackendArg};
    use clap::Parser;

    #[test]
    fn test_create_command_parses_platforms() {
        let cli = Cli::parse_from([
            "",
            "create",
            "demo",
            "--platforms",
            "android,ios",
            "--skip-fvm-install",
        ]);
        let Commands::Create(args) = cli.command else {
            panic!("expected create command");
        };

        assert_eq!(args.platforms, Some("android,ios".to_owned()));
        assert_eq!(args.integration_backend, IntegrationBackendArg::Cargokit);
    }

    #[test]
    fn test_integrate_command_parses_platforms() {
        let cli = Cli::parse_from([
            "",
            "integrate",
            "--platforms",
            "android,ohos",
            "--skip-fvm-install",
        ]);
        let Commands::Integrate(args) = cli.command else {
            panic!("expected integrate command");
        };

        assert_eq!(args.platforms, Some("android,ohos".to_owned()));
        assert_eq!(args.integration_backend, IntegrationBackendArg::Cargokit);
    }

    #[test]
    fn test_create_command_parses_native_assets_backend() {
        let cli = Cli::parse_from([
            "",
            "create",
            "demo",
            "--integration-backend",
            "native-assets",
            "--skip-fvm-install",
        ]);
        let Commands::Create(args) = cli.command else {
            // The assertion branch only guards the test setup.
            // frb-coverage:ignore-start
            panic!("expected create command");
            // frb-coverage:ignore-end
        };

        assert_eq!(
            args.integration_backend,
            IntegrationBackendArg::NativeAssets
        );
    }

    #[test]
    fn test_integrate_command_parses_native_assets_backend() {
        let cli = Cli::parse_from([
            "",
            "integrate",
            "--integration-backend",
            "native-assets",
            "--skip-fvm-install",
        ]);
        let Commands::Integrate(args) = cli.command else {
            // The assertion branch only guards the test setup.
            // frb-coverage:ignore-start
            panic!("expected integrate command");
            // frb-coverage:ignore-end
        };

        assert_eq!(
            args.integration_backend,
            IntegrationBackendArg::NativeAssets
        );
    }
}