Skip to content

Commit 26d603f

Browse files
committed
Add a *Ref struct for traits and Deref to it rather than Self
Because LDK often takes `Deref<Target=Trait>` as type parameters, we'd implemented `Deref { type Target=Self; .. }` for the traits defined in the bindings crate. This worked well, but because Rust auto-`Deref`s, it can lead to spurious compilation failures due to infinite recursion trying to deref. In the past we've worked around this by coming up with alternative compilation strategies when faced with `Deref` recursion, but we don't strictly need to. Instead, here, we introduce duplicates of all our `Trait` structs which become the `Deref` `Target`. This way, we can `Deref` into the `Trait` and maintain LDK compatibility, without having any infinite `Deref` recursion issues. One complication is traits which contain associated types to define `Deref`s to another associated type, e.g. trait A { type B; type C: Deref<Target = Self::B>; } In this case, `B` needs to be the `TraitRef` and `C` needs to be the `Trait`. We add code specifically to detect this case.
1 parent f7f26a1 commit 26d603f

File tree

1 file changed

+74
-3
lines changed

1 file changed

+74
-3
lines changed

c-bindings-gen/src/main.rs

Lines changed: 74 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,11 @@ fn do_write_impl_trait<W: std::io::Write>(w: &mut W, trait_path: &str, _trait_na
225225
writeln!(w, "\t\tlet vec = (self.write)(self.this_arg);").unwrap();
226226
writeln!(w, "\t\tw.write_all(vec.as_slice())").unwrap();
227227
writeln!(w, "\t}}\n}}").unwrap();
228+
writeln!(w, "impl {} for {}Ref {{", trait_path, for_obj).unwrap();
229+
writeln!(w, "\tfn write<W: lightning::util::ser::Writer>(&self, w: &mut W) -> Result<(), crate::c_types::io::Error> {{").unwrap();
230+
writeln!(w, "\t\tlet vec = (self.0.write)(self.0.this_arg);").unwrap();
231+
writeln!(w, "\t\tw.write_all(vec.as_slice())").unwrap();
232+
writeln!(w, "\t}}\n}}").unwrap();
228233
},
229234
_ => panic!(),
230235
}
@@ -450,6 +455,47 @@ fn writeln_trait<'a, 'b, W: std::io::Write>(w: &mut W, t: &'a syn::ItemTrait, ty
450455
($t: expr, $impl_accessor: expr, $type_resolver: expr, $generic_impls: expr) => {
451456
let mut trait_gen_types = gen_types.push_ctx();
452457
assert!(trait_gen_types.learn_generics_with_impls(&$t.generics, $generic_impls, $type_resolver));
458+
459+
let mut ref_types = HashSet::new();
460+
for item in $t.items.iter() {
461+
if let syn::TraitItem::Type(ref t) = &item {
462+
if t.default.is_some() || t.generics.lt_token.is_some() { panic!("10"); }
463+
let mut bounds_iter = t.bounds.iter();
464+
loop {
465+
match bounds_iter.next().unwrap() {
466+
syn::TypeParamBound::Trait(tr) => {
467+
match $type_resolver.resolve_path(&tr.path, None).as_str() {
468+
"core::ops::Deref"|"core::ops::DerefMut"|"std::ops::Deref"|"std::ops::DerefMut" => {
469+
// Handle cases like
470+
// trait A {
471+
// type B;
472+
// type C: Deref<Target = Self::B>;
473+
// }
474+
// by tracking if we have any B's here and making them
475+
// the *Ref types below.
476+
if let syn::PathArguments::AngleBracketed(args) = &tr.path.segments.iter().last().unwrap().arguments {
477+
if let syn::GenericArgument::Binding(bind) = args.args.iter().last().unwrap() {
478+
assert_eq!(format!("{}", bind.ident), "Target");
479+
if let syn::Type::Path(p) = &bind.ty {
480+
assert!(p.qself.is_none());
481+
let mut segs = p.path.segments.iter();
482+
assert_eq!(format!("{}", segs.next().unwrap().ident), "Self");
483+
ref_types.insert(format!("{}", segs.next().unwrap().ident));
484+
assert!(segs.next().is_none());
485+
} else { panic!(); }
486+
}
487+
}
488+
},
489+
_ => {},
490+
}
491+
break;
492+
}
493+
syn::TypeParamBound::Lifetime(_) => {},
494+
}
495+
}
496+
}
497+
}
498+
453499
for item in $t.items.iter() {
454500
match item {
455501
syn::TraitItem::Method(m) => {
@@ -538,7 +584,11 @@ fn writeln_trait<'a, 'b, W: std::io::Write>(w: &mut W, t: &'a syn::ItemTrait, ty
538584
loop {
539585
match bounds_iter.next().unwrap() {
540586
syn::TypeParamBound::Trait(tr) => {
541-
writeln!(w, "\ttype {} = crate::{};", t.ident, $type_resolver.resolve_path(&tr.path, Some(&gen_types))).unwrap();
587+
write!(w, "\ttype {} = crate::{}", t.ident, $type_resolver.resolve_path(&tr.path, Some(&gen_types))).unwrap();
588+
if ref_types.contains(&format!("{}", t.ident)) {
589+
write!(w, "Ref").unwrap();
590+
}
591+
writeln!(w, ";").unwrap();
542592
for bound in bounds_iter {
543593
if let syn::TypeParamBound::Trait(t) = bound {
544594
// We only allow for `Sized` here.
@@ -581,10 +631,15 @@ fn writeln_trait<'a, 'b, W: std::io::Write>(w: &mut W, t: &'a syn::ItemTrait, ty
581631
writeln!(w, "impl core::cmp::Eq for {} {{}}", trait_name).unwrap();
582632
writeln!(w, "impl core::cmp::PartialEq for {} {{", trait_name).unwrap();
583633
writeln!(w, "\tfn eq(&self, o: &Self) -> bool {{ (self.eq)(self.this_arg, o) }}\n}}").unwrap();
634+
writeln!(w, "impl core::cmp::Eq for {}Ref {{}}", trait_name).unwrap();
635+
writeln!(w, "impl core::cmp::PartialEq for {}Ref {{", trait_name).unwrap();
636+
writeln!(w, "\tfn eq(&self, o: &Self) -> bool {{ (self.0.eq)(self.0.this_arg, &o.0) }}\n}}").unwrap();
584637
},
585638
("std::hash::Hash", _, _)|("core::hash::Hash", _, _) => {
586639
writeln!(w, "impl core::hash::Hash for {} {{", trait_name).unwrap();
587640
writeln!(w, "\tfn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {{ hasher.write_u64((self.hash)(self.this_arg)) }}\n}}").unwrap();
641+
writeln!(w, "impl core::hash::Hash for {}Ref {{", trait_name).unwrap();
642+
writeln!(w, "\tfn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {{ hasher.write_u64((self.0.hash)(self.0.this_arg)) }}\n}}").unwrap();
588643
},
589644
("Send", _, _) => {}, ("Sync", _, _) => {},
590645
("Clone", _, _) => {
@@ -598,13 +653,22 @@ fn writeln_trait<'a, 'b, W: std::io::Write>(w: &mut W, t: &'a syn::ItemTrait, ty
598653
writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
599654
writeln!(w, "\t\t{}_clone(self)", trait_name).unwrap();
600655
writeln!(w, "\t}}\n}}").unwrap();
656+
writeln!(w, "impl Clone for {}Ref {{", trait_name).unwrap();
657+
writeln!(w, "\tfn clone(&self) -> Self {{").unwrap();
658+
writeln!(w, "\t\tSelf({}_clone(&self.0))", trait_name).unwrap();
659+
writeln!(w, "\t}}\n}}").unwrap();
601660
},
602661
("std::fmt::Debug", _, _)|("core::fmt::Debug", _, _) => {
603662
writeln!(w, "impl core::fmt::Debug for {} {{", trait_name).unwrap();
604663
writeln!(w, "\tfn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {{").unwrap();
605664
writeln!(w, "\t\tf.write_str((self.debug_str)(self.this_arg).into_str())").unwrap();
606665
writeln!(w, "\t}}").unwrap();
607666
writeln!(w, "}}").unwrap();
667+
writeln!(w, "impl core::fmt::Debug for {}Ref {{", trait_name).unwrap();
668+
writeln!(w, "\tfn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {{").unwrap();
669+
writeln!(w, "\t\tf.write_str((self.0.debug_str)(self.0.this_arg).into_str())").unwrap();
670+
writeln!(w, "\t}}").unwrap();
671+
writeln!(w, "}}").unwrap();
608672
},
609673
(s, i, generic_args) => {
610674
if let Some(supertrait) = types.crate_types.traits.get(s) {
@@ -621,9 +685,16 @@ fn writeln_trait<'a, 'b, W: std::io::Write>(w: &mut W, t: &'a syn::ItemTrait, ty
621685
write!(w, " {}", $s).unwrap();
622686
maybe_write_generics(w, &$supertrait.generics, $generic_args, types, false);
623687
writeln!(w, " for {} {{", trait_name).unwrap();
624-
625688
impl_trait_for_c!($supertrait, format!(".{}", $i), &resolver, $generic_args);
626689
writeln!(w, "}}").unwrap();
690+
691+
write!(w, "impl").unwrap();
692+
maybe_write_lifetime_generics(w, &$supertrait.generics, types);
693+
write!(w, " {}", $s).unwrap();
694+
maybe_write_generics(w, &$supertrait.generics, $generic_args, types, false);
695+
writeln!(w, " for {}Ref {{", trait_name).unwrap();
696+
impl_trait_for_c!($supertrait, format!(".0.{}", $i), &resolver, $generic_args);
697+
writeln!(w, "}}").unwrap();
627698
}
628699
}
629700
impl_supertrait!(s, supertrait, i, generic_args);
@@ -651,7 +722,7 @@ fn writeln_trait<'a, 'b, W: std::io::Write>(w: &mut W, t: &'a syn::ItemTrait, ty
651722
impl_trait_for_c!(t, "", types, &syn::PathArguments::None);
652723
writeln!(w, "}}\n").unwrap();
653724

654-
writeln!(w, "struct {}Ref({});", trait_name, trait_name).unwrap();
725+
writeln!(w, "pub struct {}Ref({});", trait_name, trait_name).unwrap();
655726
write!(w, "impl").unwrap();
656727
maybe_write_lifetime_generics(w, &t.generics, types);
657728
write!(w, " rust{}", t.ident).unwrap();

0 commit comments

Comments
 (0)