Skip to content

Commit

Permalink
Merge branch 'feat/12218' into feat/12204
Browse files Browse the repository at this point in the history
# Conflicts:
#	frb_dart/lib/src/manual_impl/_io.dart
#	frb_dart/lib/src/manual_impl/_web.dart
#	frb_example/dart_minimal/lib/src/rust/frb_generated.dart
#	frb_example/dart_minimal/lib/src/rust/frb_generated.io.dart
#	frb_example/dart_minimal/lib/src/rust/frb_generated.web.dart
#	frb_example/dart_minimal/rust/src/frb_generated.rs
  • Loading branch information
fzyzcjy committed Jun 12, 2024
2 parents 0ae4ec6 + 5ecc511 commit 9988668
Show file tree
Hide file tree
Showing 123 changed files with 13,033 additions and 3,017 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::codegen::ir::mir::default::MirDefaultValue;
use crate::codegen::ir::mir::field::MirField;
use crate::codegen::ir::mir::ty::delegate::MirTypeDelegate;
use crate::codegen::ir::mir::ty::MirType;
use crate::utils::dart_keywords::make_string_keyword_safe;
use crate::utils::dart_keywords;
use convert_case::{Case, Casing};
use std::borrow::Cow;

Expand Down Expand Up @@ -61,7 +61,7 @@ fn default_value_to_dart_style(value: &str) -> String {
format!(
"{}.{}",
enum_name,
make_string_keyword_safe(variant_name.to_string()).to_case(Case::Camel)
dart_keywords::escape(variant_name.to_case(Case::Camel))
)
}
_ => value.to_string(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ impl<'a> EnumRefApiDartGenerator<'a> {

fn generate_implements_exception(&self, variant: &MirEnumVariant) -> &str {
let has_backtrace = matches!(&variant.kind,
MirVariantKind::Struct(MirStruct {is_fields_named: true, fields, ..}) if fields.iter().any(|field| field.name.raw == BACKTRACE_IDENT));
MirVariantKind::Struct(MirStruct {is_fields_named: true, fields, ..}) if fields.iter().any(|field| field.name.rust_style() == BACKTRACE_IDENT));
if self.mir.is_exception && has_backtrace {
"@Implements<FrbBacktracedException>()"
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use crate::codegen::generator::api_dart::spec_generator::misc::generate_dart_com
use crate::codegen::ir::mir::ty::enumeration::{MirEnum, MirEnumVariant};
use crate::library::codegen::generator::api_dart::spec_generator::base::*;
use crate::utils::basic_code::dart_header_code::DartHeaderCode;
use crate::utils::dart_keywords::make_string_keyword_safe;
use crate::utils::dart_keywords;
use itertools::Itertools;

impl<'a> EnumRefApiDartGenerator<'a> {
Expand Down Expand Up @@ -41,7 +41,7 @@ impl<'a> EnumRefApiDartGenerator<'a> {

fn generate_mode_simple_variant(&self, variant: &MirEnumVariant) -> String {
let variant_name = if self.context.config.dart_enums_style {
make_string_keyword_safe(variant.name.dart_style())
dart_keywords::escape(variant.name.dart_style())
} else {
variant.name.rust_style().to_string()
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,15 @@ impl<'a> ApiDartGeneratorInfoTrait for DelegateApiDartGenerator<'a> {
ApiDartGenerator::new(*mir.inner_ok.clone(), self.context).dart_api_type(),
),
MirTypeDelegate::BigPrimitive(_) => "BigInt".to_owned(),
MirTypeDelegate::CastedPrimitive(mir) => match mir.inner {
MirTypePrimitive::U64
| MirTypePrimitive::I64
| MirTypePrimitive::Usize
| MirTypePrimitive::Isize => "int".to_owned(),
// frb-coverage:ignore-start
_ => unreachable!(),
// frb-coverage:ignore-end
},
MirTypeDelegate::RustAutoOpaqueExplicit(mir) => {
ApiDartGenerator::new(mir.inner.clone(), self.context).dart_api_type()
}
Expand All @@ -96,6 +105,7 @@ impl<'a> ApiDartGeneratorInfoTrait for DelegateApiDartGenerator<'a> {
ApiDartGenerator::new(mir.original.clone(), self.context).dart_api_type()
}
MirTypeDelegate::DynTrait(mir) => mir.trait_def_name.name.clone(),
MirTypeDelegate::CustomSerDes(mir) => mir.info.dart_api_type.clone(),
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ fn compute_skips(mir_pack: &MirPack, namespace: &Namespace) -> Vec<MirSkip> {
.filter(|t| &t.namespace == namespace)
.map(|name| MirSkip {
name: name.clone(),
reason: MirSkipReason::IgnoredTypeNotUsedByPub,
reason: MirSkipReason::IgnoreBecauseTypeNotUsedByPub,
})
.collect_vec();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -129,14 +129,15 @@ fn compute_skips(item: &ApiDartOutputSpecItem) -> String {
.into_group_map_by(|t| t.reason)
.into_iter()
.sorted_by_key(|(reason, _)| *reason)
.map(|(reason, names)| {
format!(
"// {}: {}\n",
reason.explanation_prefix(),
(names.iter().map(|x| format!("`{}`", x.name.name)))
.sorted()
.join(", "),
)
.filter_map(|(reason, names)| {
reason.explanation_prefix().map(|explanation_prefix| {
format!(
"// {explanation_prefix}: {}\n",
(names.iter().map(|x| format!("`{}`", x.name.name)))
.sorted()
.join(", "),
)
})
})
.join("")
}
Expand Down
29 changes: 27 additions & 2 deletions frb_codegen/src/library/codegen/generator/codec/sse/ty/delegate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,26 @@ impl<'a> CodecSseTyTrait for DelegateCodecSseTy<'a> {
generate_stream_sink_setup_and_serialize(mir, "self")
}
MirTypeDelegate::BigPrimitive(_) => "self.toString()".to_owned(),
MirTypeDelegate::CastedPrimitive(mir) => {
let postfix = match mir.inner {
MirTypePrimitive::Isize | MirTypePrimitive::I64 => "I64",
MirTypePrimitive::Usize | MirTypePrimitive::U64 => "U64",
// frb-coverage:ignore-start
_ => unreachable!(),
// frb-coverage:ignore-end
};
format!("sseEncodeCastedPrimitive{postfix}(self)")
}
MirTypeDelegate::RustAutoOpaqueExplicit(_ir) => "self".to_owned(),
MirTypeDelegate::ProxyEnum(mir) => {
generate_proxy_enum_dart_encode(mir, self.context.as_api_dart_context())
}
MirTypeDelegate::DynTrait(mir) => {
generate_dyn_trait_dart_encode(mir, self.context.as_api_dart_context())
}
MirTypeDelegate::CustomSerDes(mir) => {
mir.info.dart2rust.dart_code.replace("{}", "self")
}
},
Lang::RustLang(_) => match &self.mir {
MirTypeDelegate::Array(_) => {
Expand Down Expand Up @@ -97,7 +110,11 @@ impl<'a> CodecSseTyTrait for DelegateCodecSseTy<'a> {
}
MirTypeDelegate::ProxyVariant(_)
| MirTypeDelegate::ProxyEnum(_)
| MirTypeDelegate::DynTrait(_) => return None,
| MirTypeDelegate::DynTrait(_)
| MirTypeDelegate::CastedPrimitive(_) => return None,
MirTypeDelegate::CustomSerDes(mir) => {
format!("{}(self)", mir.info.rust2dart.rust_function.rust_style())
}
},
};
Some(simple_delegate_encode(
Expand Down Expand Up @@ -155,10 +172,14 @@ impl<'a> CodecSseTyTrait for DelegateCodecSseTy<'a> {
return Some(format!("{};", lang.throw_unreachable("")));
}
MirTypeDelegate::BigPrimitive(_) => "BigInt.parse(inner)".to_owned(),
MirTypeDelegate::CastedPrimitive(_) => "inner.toInt()".to_owned(),
MirTypeDelegate::RustAutoOpaqueExplicit(_ir) => "inner".to_owned(),
MirTypeDelegate::DynTrait(_) => {
return Some(format!("{};", lang.throw_unimplemented("")))
}
MirTypeDelegate::CustomSerDes(mir) => {
mir.info.rust2dart.dart_code.replace("{}", "inner")
}
}
}
Lang::RustLang(_) => match &self.mir {
Expand Down Expand Up @@ -203,7 +224,11 @@ impl<'a> CodecSseTyTrait for DelegateCodecSseTy<'a> {
}
MirTypeDelegate::ProxyVariant(_)
| MirTypeDelegate::ProxyEnum(_)
| MirTypeDelegate::DynTrait(_) => return None,
| MirTypeDelegate::DynTrait(_)
| MirTypeDelegate::CastedPrimitive(_) => return None,
MirTypeDelegate::CustomSerDes(mir) => {
format!("{}(inner)", mir.info.dart2rust.rust_function.rust_style())
}
},
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ impl<'a> WireDartCodecCstGeneratorEncoderTrait for DelegateWireDartCodecCstGener
"return cst_encode_{}(raw);",
self.mir.get_delegate().safe_ident(),
))),
MirTypeDelegate::ProxyVariant(_) | MirTypeDelegate::ProxyEnum(_) =>
MirTypeDelegate::ProxyVariant(_) | MirTypeDelegate::ProxyEnum(_) | MirTypeDelegate::CastedPrimitive(_) | MirTypeDelegate::CustomSerDes(_) =>
Acc::distribute(Some("throw UnimplementedError('Not implemented in this codec, please use the other one');".to_string()))
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ impl<'a> WireDartCodecDcoGeneratorDecoderTrait for DelegateWireDartCodecDcoGener
"return BigInt.parse(raw);".to_owned()
}
MirTypeDelegate::RustAutoOpaqueExplicit(mir) => format!(r"return dco_decode_{}(raw);", mir.inner.safe_ident()),
MirTypeDelegate::ProxyVariant(_) | MirTypeDelegate::ProxyEnum(_) =>
MirTypeDelegate::ProxyVariant(_) | MirTypeDelegate::ProxyEnum(_) | MirTypeDelegate::CastedPrimitive(_) | MirTypeDelegate::CustomSerDes(_) =>
"throw UnimplementedError('Not implemented in this codec, please use the other one');".into(),
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,12 @@ impl<'a> WireRustCodecCstGeneratorDecoderTrait for DelegateWireRustCodecCstGener
io: Some("flutter_rust_bridge::for_generated::rust_auto_opaque_explicit_decode(self.cst_decode())".into()),
..Default::default()
},
// Do not care about these unimplemented things
// frb-coverage:ignore-start
MirTypeDelegate::ProxyVariant(_) | MirTypeDelegate::ProxyEnum(_) =>
Acc::distribute(Some(r#"unimplemented!("Not implemented in this codec, please use the other one")"#.to_string()))
Acc::distribute(Some(r#"unimplemented!("Not implemented in this codec, please use the other one")"#.to_string())),
MirTypeDelegate::CastedPrimitive(_) | MirTypeDelegate::CustomSerDes(_) => Acc::distribute(None),
// frb-coverage:ignore-end
}
}

Expand Down Expand Up @@ -143,8 +147,12 @@ impl<'a> WireRustCodecCstGeneratorDecoderTrait for DelegateWireRustCodecCstGener
MirTypeDelegate::BigPrimitive(_) => "CstDecode::<String>::cst_decode(self).parse().unwrap()".into(),
MirTypeDelegate::RustAutoOpaqueExplicit(_) =>
"flutter_rust_bridge::for_generated::rust_auto_opaque_explicit_decode(self.cst_decode())".into(),
// Do not care about these unimplemented things
// frb-coverage:ignore-start
MirTypeDelegate::ProxyVariant(_) | MirTypeDelegate::ProxyEnum(_) =>
r#"unimplemented!("Not implemented in this codec, please use the other one")"#.into(),
MirTypeDelegate::CastedPrimitive(_) | MirTypeDelegate::CustomSerDes(_) => return None,
// frb-coverage:ignore-end
})
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ fn generate_decode_statement(
)
}

fn get_variable_name(field: &MirFuncInput) -> &str {
fn get_variable_name(field: &MirFuncInput) -> String {
field.inner.name.rust_style()
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,22 @@ use crate::codegen::generator::wire::rust::spec_generator::base::*;
use crate::codegen::generator::wire::rust::spec_generator::misc::ty::WireRustGeneratorMiscTrait;
use crate::codegen::ir::mir::ty::delegate::MirTypeDelegate;
use crate::library::codegen::ir::mir::ty::MirTypeTrait;
use itertools::Itertools;

impl<'a> WireRustGeneratorMiscTrait for DelegateWireRustGenerator<'a> {
fn generate_imports(&self) -> Option<Vec<String>> {
if let MirTypeDelegate::CustomSerDes(mir) = &self.mir {
Some(
[&mir.info.rust2dart, &mir.info.dart2rust]
.into_iter()
.map(|x| format!("use {}::*;", x.rust_function.namespace.joined_path))
.collect_vec(),
)
} else {
None
}
}

// the function signature is not covered while the whole body is covered - looks like a bug in coverage tool
// frb-coverage:ignore-start
fn wrapper_struct_name(&self) -> Option<String> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ impl<'a> WireRustGeneratorMiscTrait for StructRefWireRustGenerator<'a> {
.enumerate()
.map(|(i, field)| {
let field_access = if src.is_fields_named {
field.name.raw.clone()
field.name.rust_style().to_owned()
} else {
i.to_string()
};
Expand Down
17 changes: 17 additions & 0 deletions frb_codegen/src/library/codegen/ir/mir/custom_ser_des.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
use crate::codegen::ir::mir::ty::MirType;
use crate::utils::namespace::NamespacedName;

crate::mir! {
pub struct MirCustomSerDes {
pub inner_type: Box<MirType>,
pub rust_api_type: Box<MirType>,
pub dart_api_type: String,
pub dart2rust: MirCustomSerDesHalf,
pub rust2dart: MirCustomSerDesHalf,
}

pub struct MirCustomSerDesHalf {
pub dart_code: String,
pub rust_function: NamespacedName,
}
}
47 changes: 32 additions & 15 deletions frb_codegen/src/library/codegen/ir/mir/ident.rs
Original file line number Diff line number Diff line change
@@ -1,28 +1,32 @@
use crate::codegen::generator::codec::sse::lang::Lang;
use crate::utils::cbindgen_keywords;
use crate::utils::{cbindgen_keywords, dart_keywords};
use convert_case::{Case, Casing};

crate::mir! {
#[serde(transparent)]
pub struct MirIdent {
pub raw: String,
rust_style: String,
dart_style: Option<String>,
}
}

impl MirIdent {
pub fn new(raw: String) -> MirIdent {
MirIdent { raw }
pub fn new(rust_style: String, dart_style: Option<String>) -> MirIdent {
MirIdent {
rust_style,
dart_style,
}
}

pub fn rust_style(&self) -> &str {
&self.raw
pub fn rust_style(&self) -> String {
self.rust_style.clone()
}

pub fn c_style(&self) -> String {
convert_rust_to_c_style(&self.raw)
convert_rust_to_c_style(&self.rust_style)
}

pub fn dart_style(&self) -> String {
(self.raw.strip_prefix("r#").unwrap_or(self.raw.as_str())).to_case(Case::Camel)
(self.dart_style.clone()).unwrap_or_else(|| convert_rust_to_dart_style(&self.rust_style))
}

pub fn style(&self, lang: &Lang) -> String {
Expand All @@ -35,24 +39,37 @@ impl MirIdent {

impl std::fmt::Display for MirIdent {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
fmt.write_str(&self.raw)
fmt.write_str(&self.rust_style)?;
if let Some(dart_style) = &self.dart_style {
write!(fmt, "(dart_style={})", dart_style)?;
}
Ok(())
}
}

fn convert_rust_to_c_style(raw: &str) -> String {
let mut ans = raw.to_owned();

if let Some(stripped) = ans.strip_prefix("r#") {
ans = stripped.to_owned();
}
let mut ans = strip_prefix_rhash(raw).to_owned();

// match behavior of ffigen
if &ans == "async" {
ans = "async1".to_owned();
}
if &ans == "interface" {
ans = "interface1".to_owned();
}

// match behavior of cbindgen
cbindgen_keywords::escape(&mut ans);

ans
}

fn convert_rust_to_dart_style(raw: &str) -> String {
let ans = strip_prefix_rhash(raw).to_case(Case::Camel);

dart_keywords::escape(ans)
}

fn strip_prefix_rhash(raw: &str) -> &str {
raw.strip_prefix("r#").unwrap_or(raw)
}
1 change: 1 addition & 0 deletions frb_codegen/src/library/codegen/ir/mir/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
pub(crate) mod annotation;
pub(crate) mod comment;
pub(crate) mod custom_ser_des;
pub(crate) mod default;
pub(crate) mod field;
pub(crate) mod func;
Expand Down
Loading

0 comments on commit 9988668

Please sign in to comment.