Skip to content

Commit

Permalink
Add option to select feature flags for codegen
Browse files Browse the repository at this point in the history
  • Loading branch information
fmeef committed Sep 20, 2024
1 parent 17fdf93 commit 26f152b
Show file tree
Hide file tree
Showing 40 changed files with 2,246 additions and 2,007 deletions.
4 changes: 4 additions & 0 deletions frb_codegen/src/binary/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,10 @@ pub(crate) struct GenerateCommandArgsPrimary {
/// 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)]
Expand Down
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 @@ -60,6 +60,7 @@ fn compute_codegen_config_from_naive_command_args(args: GenerateCommandArgsPrima
stop_on_error: positive_bool_arg(args.stop_on_error),
dump: args.dump,
dump_all: positive_bool_arg(args.dump_all),
rust_features: args.rust_features,
}
}

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
Expand Up @@ -38,6 +38,7 @@ pub struct Config {
pub stop_on_error: Option<bool>,
pub dump: Option<Vec<ConfigDumpContent>>,
pub dump_all: Option<bool>,
pub rust_features: Option<Vec<String>>,
}

#[derive(Debug, Serialize, Deserialize, Default)]
Expand Down Expand Up @@ -93,4 +94,5 @@ generate_merge!(
stop_on_error,
dump,
dump_all,
rust_features,
);
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ impl InternalConfig {
rust_crate_dir: rust_crate_dir.clone(),
rust_input_namespace_pack: rust_input_namespace_pack.clone(),
third_party_crate_names,
rust_features: config.rust_features.clone(),
},
mir: ParserMirInternalConfig {
rust_input_namespace_pack: rust_input_namespace_pack.clone(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@ pub(crate) struct ParserHirInternalConfig {
pub rust_input_namespace_pack: RustInputNamespacePack,
pub rust_crate_dir: PathBuf,
pub third_party_crate_names: Vec<CrateName>,
pub rust_features: Option<Vec<String>>,
}
1 change: 1 addition & 0 deletions frb_codegen/src/library/codegen/parser/hir/raw/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ pub(crate) fn parse(
&config.rust_crate_dir,
(!crate_name.is_self_crate()).then_some(crate_name),
dumper,
config.rust_features.as_deref(),
)?,
})
})
Expand Down
1 change: 1 addition & 0 deletions frb_codegen/src/library/codegen/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@ mod tests {
rust_input_namespace_pack: rust_input_namespace_pack.clone(),
rust_crate_dir: rust_crate_dir.clone(),
third_party_crate_names: vec![],
rust_features: None,
},
mir: ParserMirInternalConfig {
rust_input_namespace_pack: rust_input_namespace_pack.clone(),
Expand Down
3 changes: 2 additions & 1 deletion frb_codegen/src/library/commands/cargo_expand/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@ pub(crate) fn run_cargo_expand(
rust_crate_dir: &Path,
interest_crate_name: Option<&CrateName>,
dumper: &Dumper,
features: Option<&[String]>,
) -> Result<syn::File> {
if can_execute_real(rust_crate_dir)? {
real::run(rust_crate_dir, interest_crate_name, dumper)
real::run(rust_crate_dir, interest_crate_name, dumper, features)
} else {
pseudo::run(rust_crate_dir, interest_crate_name)
}
Expand Down
26 changes: 23 additions & 3 deletions frb_codegen/src/library/commands/cargo_expand/real.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,27 +10,31 @@ use log::{debug, info};
use regex::{Captures, Regex};
use std::borrow::Cow;
use std::env;
use std::path::Path;
use std::path::{Path, PathBuf};
use std::str::FromStr;

pub(super) fn run(
rust_crate_dir: &Path,
interest_crate_name: Option<&CrateName>,
dumper: &Dumper,
features: Option<&[String]>,
) -> Result<syn::File> {
let text = run_with_frb_aware(rust_crate_dir, interest_crate_name)?;
let text = run_with_frb_aware(rust_crate_dir, interest_crate_name, features)?;
(dumper.with_content(ConfigDumpContent::Source)).dump_str("cargo_expand.rs", &text)?;
Ok(syn::parse_file(&text)?)
}

fn run_with_frb_aware(
rust_crate_dir: &Path,
interest_crate_name: Option<&CrateName>,
features: Option<&[String]>,
) -> Result<String> {
Ok(decode_macro_frb_encoded_comments(&run_raw(
rust_crate_dir,
interest_crate_name,
"--cfg frb_expand",
true,
features,
)?)
.into_owned())
}
Expand All @@ -55,6 +59,7 @@ fn run_raw(
interest_crate_name: Option<&CrateName>,
extra_rustflags: &str,
allow_auto_install: bool,
features: Option<&[String]>,
) -> Result<String> {
// let _pb = simple_progress("Run cargo-expand".to_owned(), 1);
debug!("Running cargo expand in '{rust_crate_dir:?}'");
Expand All @@ -65,13 +70,22 @@ fn run_raw(
vec![]
};

let args_features: Vec<PathBuf> = features
.unwrap_or_default()
.iter()
.flat_map(|feature| vec!["--features", feature])
.map(PathBuf::from_str)
.try_collect()?;

let args = command_args!(
"expand",
"--lib",
"--theme=none",
"--ugly",
*args_choosing_crate,
*args_features
);

let extra_env = [(
"RUSTFLAGS".to_owned(),
env::var("RUSTFLAGS").map(|x| x + " ").unwrap_or_default() + extra_rustflags,
Expand All @@ -88,7 +102,13 @@ fn run_raw(
if stderr.contains("no such command: `expand`") && allow_auto_install {
info!("Cargo expand is not installed. Automatically install and re-run.");
install_cargo_expand()?;
return run_raw(rust_crate_dir, interest_crate_name, extra_rustflags, false);
return run_raw(
rust_crate_dir,
interest_crate_name,
extra_rustflags,
false,
features,
);
}
// This will stop the whole generator and tell the users, so we do not care about testing it
// frb-coverage:ignore-start
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,9 @@
{
"controller": {
"exclude_paths": [
"{the-working-directory}/src/frb_generated.rs"
],
"exclude_paths": ["{the-working-directory}/src/frb_generated.rs"],
"max_count": null,
"watch": false,
"watching_paths": [
"{the-working-directory}/src"
]
"watching_paths": ["{the-working-directory}/src"]
},
"dumper": {
"dump_contents": [],
Expand Down Expand Up @@ -91,12 +87,11 @@
"hir": {
"rust_crate_dir": "{the-working-directory}",
"rust_input_namespace_pack": {
"rust_input_namespace_prefixes": [
"crate::api"
],
"rust_input_namespace_prefixes": ["crate::api"],
"rust_output_path_namespace": "crate::frb_generated"
},
"third_party_crate_names": []
"third_party_crate_names": [],
"rust_features": null
},
"mir": {
"default_dart_async": true,
Expand All @@ -108,9 +103,7 @@
"rust2dart": "Pde"
},
"rust_input_namespace_pack": {
"rust_input_namespace_prefixes": [
"crate::api"
],
"rust_input_namespace_prefixes": ["crate::api"],
"rust_output_path_namespace": "crate::frb_generated"
},
"stop_on_error": false,
Expand All @@ -134,4 +127,4 @@
"deps_check": true,
"needs_ffigen": false
}
}
}
Original file line number Diff line number Diff line change
@@ -1,13 +1,9 @@
{
"controller": {
"exclude_paths": [
"{the-working-directory}/src/frb_generated.rs"
],
"exclude_paths": ["{the-working-directory}/src/frb_generated.rs"],
"max_count": null,
"watch": false,
"watching_paths": [
"{the-working-directory}/src"
]
"watching_paths": ["{the-working-directory}/src"]
},
"dumper": {
"dump_contents": [],
Expand Down Expand Up @@ -91,12 +87,11 @@
"hir": {
"rust_crate_dir": "{the-working-directory}",
"rust_input_namespace_pack": {
"rust_input_namespace_prefixes": [
"crate::api"
],
"rust_input_namespace_prefixes": ["crate::api"],
"rust_output_path_namespace": "crate::frb_generated"
},
"third_party_crate_names": []
"third_party_crate_names": [],
"rust_features": null
},
"mir": {
"default_dart_async": true,
Expand All @@ -108,9 +103,7 @@
"rust2dart": "Pde"
},
"rust_input_namespace_pack": {
"rust_input_namespace_prefixes": [
"crate::api"
],
"rust_input_namespace_prefixes": ["crate::api"],
"rust_output_path_namespace": "crate::frb_generated"
},
"stop_on_error": false,
Expand All @@ -134,4 +127,4 @@
"deps_check": true,
"needs_ffigen": false
}
}
}
25 changes: 14 additions & 11 deletions frb_dart/lib/src/cli/build_web/executor.dart
Original file line number Diff line number Diff line change
Expand Up @@ -36,17 +36,20 @@ class BuildWebArgs {
final String? dartCompileJsEntrypoint;

/// {@macro flutter_rust_bridge.cli}
const BuildWebArgs({
required this.output,
required this.release,
required this.verbose,
required this.rustCrateDir,
required this.cargoBuildArgs,
required this.wasmBindgenArgs,
required this.wasmPackRustupToolchain,
required this.wasmPackRustflags,
required this.dartCompileJsEntrypoint,
});
final List<String> features;

/// {@macro flutter_rust_bridge.cli}
const BuildWebArgs(
{required this.output,
required this.release,
required this.verbose,
required this.rustCrateDir,
required this.cargoBuildArgs,
required this.wasmBindgenArgs,
required this.wasmPackRustupToolchain,
required this.wasmPackRustflags,
required this.dartCompileJsEntrypoint,
this.features = const []});
}

extension on BuildWebArgs {
Expand Down
4 changes: 3 additions & 1 deletion frb_example/pure_dart/build.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import 'package:flutter_rust_bridge_utils/flutter_rust_bridge_utils.dart';

void main(List<String> args) async => simpleBuild(args);
void main(List<String> args) async => simpleBuild(args,
// This is solely used for testing
features: ['internal_feature_for_testing']);
2 changes: 2 additions & 0 deletions frb_example/pure_dart/flutter_rust_bridge.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,5 @@ enable_lifetime: true
dump_all: true
# only for development of flutter_rust_bridge, not for normal users (use local dependency)
local: true
rust_features:
- internal_feature_for_testing
3 changes: 3 additions & 0 deletions frb_example/pure_dart/frb_generated.h
Original file line number Diff line number Diff line change
Expand Up @@ -4291,6 +4291,8 @@ 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__feature_gated_function(int64_t port_);

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);

Expand Down Expand Up @@ -16404,6 +16406,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_set_something);
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__feature_gated_function);
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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ Future<void> functionWithArgTypeNameOverride(
RustLib.instance.api
.crateApiMiscNoTwinExampleAFunctionWithArgTypeNameOverride(a: a);

Future<String> featureGatedFunction() =>
RustLib.instance.api.crateApiMiscNoTwinExampleAFeatureGatedFunction();

// Rust type: RustOpaqueNom<flutter_rust_bridge::for_generated::RustAutoOpaqueInner<Box < dyn Any + Send + Sync + 'static >>>
abstract class BoxAnyMyDartTypeRename implements RustOpaqueInterface {}

Expand Down
28 changes: 27 additions & 1 deletion frb_example/pure_dart/lib/src/rust/frb_generated.dart
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,7 @@ class RustLib extends BaseEntrypoint<RustLibApi, RustLibApiImpl, RustLibWire> {
String get codegenVersion => '2.4.0';

@override
int get rustContentHash => -952199392;
int get rustContentHash => 1091011874;

static const kDefaultExternalLibraryLoaderConfig =
ExternalLibraryLoaderConfig(
Expand Down Expand Up @@ -1246,6 +1246,8 @@ abstract class RustLibApi extends BaseApi {
void crateApiMiscNoTwinExampleAStructWithSimpleSetterTwinNormalSimpleSetter(
{required StructWithSimpleSetterTwinNormal that, required int value});

Future<String> crateApiMiscNoTwinExampleAFeatureGatedFunction();

Future<void> crateApiMiscNoTwinExampleAFunctionWithArgTypeNameOverride(
{required BoxAnyMyDartTypeRename a});

Expand Down Expand Up @@ -20244,6 +20246,30 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
argNames: ["that", "value"],
);

@override
Future<String> crateApiMiscNoTwinExampleAFeatureGatedFunction() {
return handler.executeNormal(NormalTask(
callFfi: (port_) {
return wire
.wire__crate__api__misc_no_twin_example_a__feature_gated_function(
port_);
},
codec: DcoCodec(
decodeSuccessData: dco_decode_String,
decodeErrorData: null,
),
constMeta: kCrateApiMiscNoTwinExampleAFeatureGatedFunctionConstMeta,
argValues: [],
apiImpl: this,
));
}

TaskConstMeta get kCrateApiMiscNoTwinExampleAFeatureGatedFunctionConstMeta =>
const TaskConstMeta(
debugName: "feature_gated_function",
argNames: [],
);

@override
Future<void> crateApiMiscNoTwinExampleAFunctionWithArgTypeNameOverride(
{required BoxAnyMyDartTypeRename a}) {
Expand Down
15 changes: 15 additions & 0 deletions frb_example/pure_dart/lib/src/rust/frb_generated.io.dart
Original file line number Diff line number Diff line change
Expand Up @@ -48266,6 +48266,21 @@ class RustLibWire implements BaseWire {
_wire__crate__api__misc_no_twin_example_a__StructWithSimpleSetterTwinNormal_simple_setterPtr
.asFunction<WireSyncRust2DartDco Function(int, int)>();

void wire__crate__api__misc_no_twin_example_a__feature_gated_function(
int port_,
) {
return _wire__crate__api__misc_no_twin_example_a__feature_gated_function(
port_,
);
}

late final _wire__crate__api__misc_no_twin_example_a__feature_gated_functionPtr =
_lookup<ffi.NativeFunction<ffi.Void Function(ffi.Int64)>>(
'frbgen_frb_example_pure_dart_wire__crate__api__misc_no_twin_example_a__feature_gated_function');
late final _wire__crate__api__misc_no_twin_example_a__feature_gated_function =
_wire__crate__api__misc_no_twin_example_a__feature_gated_functionPtr
.asFunction<void Function(int)>();

void
wire__crate__api__misc_no_twin_example_a__function_with_arg_type_name_override(
int port_,
Expand Down
Loading

0 comments on commit 26f152b

Please sign in to comment.