Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add dart_type_rename to customize Dart names of opaque types #2006

Merged
merged 34 commits into from
Jun 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions frb_codegen/src/binary/commands_parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ fn compute_codegen_config_from_naive_command_args(
full_dep: Some(args.full_dep),
local: Some(args.local),
default_external_library_loader_web_prefix: args.default_external_library_loader_web_prefix,
dart_type_rename: None, // complex type, not supported on command line yet
dump: args.dump,
dump_all: Some(args.dump_all),
})
Expand Down
2 changes: 2 additions & 0 deletions frb_codegen/src/library/codegen/config/config.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::codegen::dumper::internal_config::ConfigDumpContent;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Configuration for code generation
/// Refer to `GenerateCommandArgs` for documentations
Expand Down Expand Up @@ -29,6 +30,7 @@ pub struct Config {
pub full_dep: Option<bool>,
pub local: Option<bool>,
pub default_external_library_loader_web_prefix: Option<String>,
pub dart_type_rename: Option<HashMap<String, String>>,
pub dump: Option<Vec<ConfigDumpContent>>,
pub dump_all: Option<bool>,
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,11 @@ use crate::codegen::Config;
use crate::library::commands::cargo_metadata::execute_cargo_metadata;
use crate::utils::dart_repository::get_dart_package_name;
use crate::utils::path_utils::path_to_string;
use crate::utils::syn_utils::canonicalize_rust_type;
use anyhow::Context;
use itertools::Itertools;
use pathdiff::diff_paths;
use std::collections::HashMap;
use std::path::{Path, PathBuf};

pub(super) struct Args<'a> {
Expand Down Expand Up @@ -63,6 +65,7 @@ pub(super) fn parse(args: Args) -> anyhow::Result<GeneratorInternalConfig> {
dart_decl_base_output_path: dart_output_path_pack.dart_decl_base_output_path.clone(),
dart_entrypoint_class_name: dart_output_class_name_pack.entrypoint_class_name.clone(),
dart_preamble: config.dart_preamble.clone().unwrap_or_default(),
dart_type_rename: compute_dart_type_rename(config)?,
},
wire: GeneratorWireInternalConfig {
dart: GeneratorWireDartInternalConfig {
Expand Down Expand Up @@ -168,3 +171,31 @@ fn compute_default_external_library_relative_directory(
let diff = diff_paths(rust_crate_dir, dart_root).context("cannot diff path")?;
Ok(path_to_string(&diff.join("target").join("release/"))?.replace('\\', "/"))
}

fn compute_dart_type_rename(config: &Config) -> anyhow::Result<HashMap<String, String>> {
fn convert_rust_type(raw: &str) -> anyhow::Result<Vec<String>> {
Ok(vec![
canonicalize_rust_type(raw)?,
canonicalize_rust_type(&format!(
"flutter_rust_bridge::for_generated::RustAutoOpaqueInner<{}>",
raw
))?,
])
}

Ok(config
.dart_type_rename
.clone()
.unwrap_or_default()
.iter()
.map(|(k, v)| {
Ok(convert_rust_type(k)?
.into_iter()
.map(|parsed_k| (parsed_k, v.to_owned()))
.collect_vec())
})
.collect::<anyhow::Result<Vec<_>>>()?
.into_iter()
.flatten()
.collect())
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
Expand All @@ -8,4 +9,5 @@ pub(crate) struct GeneratorApiDartInternalConfig {
pub dart_decl_base_output_path: PathBuf,
pub dart_entrypoint_class_name: String,
pub dart_preamble: String,
pub dart_type_rename: HashMap<String, String>,
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use crate::codegen::ir::mir::ty::delegate::{
use crate::codegen::ir::mir::ty::general_list::MirTypeGeneralList;
use crate::codegen::ir::mir::ty::primitive::MirTypePrimitive;
use crate::codegen::ir::mir::ty::{MirType, MirTypeTrait};
use crate::utils::syn_utils::canonicalize_rust_type;
use convert_case::{Case, Casing};
use enum_dispatch::enum_dispatch;
use itertools::Itertools;
Expand Down Expand Up @@ -217,7 +218,12 @@ impl<'a> ApiDartGeneratorInfoTrait for RustAutoOpaqueImplicitApiDartGenerator<'a

impl<'a> ApiDartGeneratorInfoTrait for RustOpaqueApiDartGenerator<'a> {
fn dart_api_type(&self) -> String {
self.mir.sanitized_type()
self.context
.config
.dart_type_rename
.get(&canonicalize_rust_type(&self.mir.inner.0).unwrap())
.cloned()
.unwrap_or_else(|| self.mir.sanitized_type())
}
}

Expand Down
1 change: 1 addition & 0 deletions frb_codegen/src/library/utils/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,6 @@ pub mod logs;
pub(crate) mod path_utils;
pub(crate) mod rust_project_utils;
pub(crate) mod simple_cache;
pub(crate) mod syn_utils;
#[cfg(test)]
pub(crate) mod test_utils;
4 changes: 4 additions & 0 deletions frb_codegen/src/library/utils/syn_utils.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
pub(crate) fn canonicalize_rust_type(raw: &str) -> anyhow::Result<String> {
let ast: syn::Type = syn::parse_str(raw)?;
Ok(quote::quote!(#ast).to_string())
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@
"dart_decl_base_output_path": "{the-working-directory}/my_dart_folder",
"dart_entrypoint_class_name": "RustLib",
"dart_enums_style": true,
"dart_preamble": ""
"dart_preamble": "",
"dart_type_rename": {}
},
"wire": {
"c": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@
"dart_decl_base_output_path": "{the-working-directory}/my_dart_folder",
"dart_entrypoint_class_name": "RustLib",
"dart_enums_style": true,
"dart_preamble": ""
"dart_preamble": "",
"dart_type_rename": {}
},
"wire": {
"c": {
Expand Down
4 changes: 4 additions & 0 deletions frb_example/pure_dart/flutter_rust_bridge.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ dart_output: lib/src/rust
c_output: frb_generated.h
full_dep: true

# this config, together with usage of that type, tests the feature of type rename
dart_type_rename:
Box<dyn Any + Send + Sync + 'static>: BoxAnyMyDartTypeRename

# only for development of flutter_rust_bridge, not for normal users (dump all debug information)
dump_all: true
# only for development of flutter_rust_bridge, not for normal users (use local dependency)
Expand Down
10 changes: 10 additions & 0 deletions frb_example/pure_dart/frb_generated.h
Original file line number Diff line number Diff line change
Expand Up @@ -3937,6 +3937,9 @@ WireSyncRust2DartDco frbgen_frb_example_pure_dart_wire__crate__api__misc_no_twin
WireSyncRust2DartDco frbgen_frb_example_pure_dart_wire__crate__api__misc_no_twin_example_a__StructWithSimpleSetterTwinNormal_simple_setter(uintptr_t that,
int32_t value);

void frbgen_frb_example_pure_dart_wire__crate__api__misc_no_twin_example_a__function_with_arg_type_name_override(int64_t port_,
uintptr_t a);

void frbgen_frb_example_pure_dart_wire__crate__api__misc_no_twin_example_a__function_with_custom_name_twin_normal(int64_t port_);

void frbgen_frb_example_pure_dart_wire__crate__api__misc_no_twin_example_a__item_container_solution_two_twin_normal_create_twin_normal(int64_t port_);
Expand Down Expand Up @@ -13410,6 +13413,10 @@ void frbgen_frb_example_pure_dart_rust_arc_increment_strong_count_RustOpaque_RwL

void frbgen_frb_example_pure_dart_rust_arc_decrement_strong_count_RustOpaque_RwLockHideDataTwinSyncSseMoi(const void *ptr);

void frbgen_frb_example_pure_dart_rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerBoxdynAnySendSyncstatic(const void *ptr);

void frbgen_frb_example_pure_dart_rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerBoxdynAnySendSyncstatic(const void *ptr);

void frbgen_frb_example_pure_dart_rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerBoxdynFnStringStringSendSync(const void *ptr);

void frbgen_frb_example_pure_dart_rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerBoxdynFnStringStringSendSync(const void *ptr);
Expand Down Expand Up @@ -15197,6 +15204,7 @@ static int64_t dummy_method_to_enforce_bundling(void) {
dummy_var ^= ((int64_t) (void*) frbgen_frb_example_pure_dart_rust_arc_decrement_strong_count_RustOpaque_RwLockHideDataTwinSyncMoi);
dummy_var ^= ((int64_t) (void*) frbgen_frb_example_pure_dart_rust_arc_decrement_strong_count_RustOpaque_RwLockHideDataTwinSyncSse);
dummy_var ^= ((int64_t) (void*) frbgen_frb_example_pure_dart_rust_arc_decrement_strong_count_RustOpaque_RwLockHideDataTwinSyncSseMoi);
dummy_var ^= ((int64_t) (void*) frbgen_frb_example_pure_dart_rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerBoxdynAnySendSyncstatic);
dummy_var ^= ((int64_t) (void*) frbgen_frb_example_pure_dart_rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerBoxdynFnStringStringSendSync);
dummy_var ^= ((int64_t) (void*) frbgen_frb_example_pure_dart_rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerBoxdynHelloTraitTwinMoi);
dummy_var ^= ((int64_t) (void*) frbgen_frb_example_pure_dart_rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerBoxdynHelloTraitTwinNormal);
Expand Down Expand Up @@ -15399,6 +15407,7 @@ static int64_t dummy_method_to_enforce_bundling(void) {
dummy_var ^= ((int64_t) (void*) frbgen_frb_example_pure_dart_rust_arc_increment_strong_count_RustOpaque_RwLockHideDataTwinSyncMoi);
dummy_var ^= ((int64_t) (void*) frbgen_frb_example_pure_dart_rust_arc_increment_strong_count_RustOpaque_RwLockHideDataTwinSyncSse);
dummy_var ^= ((int64_t) (void*) frbgen_frb_example_pure_dart_rust_arc_increment_strong_count_RustOpaque_RwLockHideDataTwinSyncSseMoi);
dummy_var ^= ((int64_t) (void*) frbgen_frb_example_pure_dart_rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerBoxdynAnySendSyncstatic);
dummy_var ^= ((int64_t) (void*) frbgen_frb_example_pure_dart_rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerBoxdynFnStringStringSendSync);
dummy_var ^= ((int64_t) (void*) frbgen_frb_example_pure_dart_rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerBoxdynHelloTraitTwinMoi);
dummy_var ^= ((int64_t) (void*) frbgen_frb_example_pure_dart_rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerBoxdynHelloTraitTwinNormal);
Expand Down Expand Up @@ -15750,6 +15759,7 @@ static int64_t dummy_method_to_enforce_bundling(void) {
dummy_var ^= ((int64_t) (void*) frbgen_frb_example_pure_dart_wire__crate__api__misc_no_twin_example_a__StructWithSimpleSetterTwinNormal_new);
dummy_var ^= ((int64_t) (void*) frbgen_frb_example_pure_dart_wire__crate__api__misc_no_twin_example_a__StructWithSimpleSetterTwinNormal_simple_getter);
dummy_var ^= ((int64_t) (void*) frbgen_frb_example_pure_dart_wire__crate__api__misc_no_twin_example_a__StructWithSimpleSetterTwinNormal_simple_setter);
dummy_var ^= ((int64_t) (void*) frbgen_frb_example_pure_dart_wire__crate__api__misc_no_twin_example_a__function_with_arg_type_name_override);
dummy_var ^= ((int64_t) (void*) frbgen_frb_example_pure_dart_wire__crate__api__misc_no_twin_example_a__function_with_custom_name_twin_normal);
dummy_var ^= ((int64_t) (void*) frbgen_frb_example_pure_dart_wire__crate__api__misc_no_twin_example_a__item_container_solution_two_twin_normal_create_twin_normal);
dummy_var ^= ((int64_t) (void*) frbgen_frb_example_pure_dart_wire__crate__api__misc_no_twin_example_a__item_container_solution_two_twin_normal_get_item_contents_twin_normal);
Expand Down
27 changes: 27 additions & 0 deletions frb_example/pure_dart/lib/src/rust/api/misc_no_twin_example_a.dart
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,33 @@ Future<void> sameFunctionNameInDifferentFiles() => RustLib.instance.api
Future<void> renamedFunction() => RustLib.instance.api
.crateApiMiscNoTwinExampleAFunctionWithCustomNameTwinNormal();

Future<void> functionWithArgTypeNameOverride(
{required BoxAnyMyDartTypeRename a}) =>
RustLib.instance.api
.crateApiMiscNoTwinExampleAFunctionWithArgTypeNameOverride(a: a);

// Rust type: RustOpaqueNom<flutter_rust_bridge::for_generated::RustAutoOpaqueInner<Box < dyn Any + Send + Sync + 'static >>>
@sealed
class BoxAnyMyDartTypeRename extends RustOpaque {
// Not to be used by end users
BoxAnyMyDartTypeRename.frbInternalDcoDecode(List<dynamic> wire)
: super.frbInternalDcoDecode(wire, _kStaticData);

// Not to be used by end users
BoxAnyMyDartTypeRename.frbInternalSseDecode(
BigInt ptr, int externalSizeOnNative)
: super.frbInternalSseDecode(ptr, externalSizeOnNative, _kStaticData);

static final _kStaticData = RustArcStaticData(
rustArcIncrementStrongCount: RustLib
.instance.api.rust_arc_increment_strong_count_BoxAnyMyDartTypeRename,
rustArcDecrementStrongCount: RustLib
.instance.api.rust_arc_decrement_strong_count_BoxAnyMyDartTypeRename,
rustArcDecrementStrongCountPtr: RustLib
.instance.api.rust_arc_decrement_strong_count_BoxAnyMyDartTypeRenamePtr,
);
}

// Rust type: RustOpaqueNom<flutter_rust_bridge::for_generated::RustAutoOpaqueInner<DeliberateFailSanityCheckTwinNormal>>
@sealed
class DeliberateFailSanityCheckTwinNormal extends RustOpaque {
Expand Down
Loading
Loading