X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;ds=inline;f=c-bindings-gen%2Fsrc%2Fblocks.rs;h=dd57a82b5f2d557a188c8a15068d112a5f809afa;hb=refs%2Fheads%2F2021-02-route-bench;hp=076f9373116985d638bcae7411b637b99be11f1c;hpb=23a1d7aab5c2cc6f00636815fa126716456dfcfd;p=rust-lightning diff --git a/c-bindings-gen/src/blocks.rs b/c-bindings-gen/src/blocks.rs index 076f9373..dd57a82b 100644 --- a/c-bindings-gen/src/blocks.rs +++ b/c-bindings-gen/src/blocks.rs @@ -1,7 +1,6 @@ //! Printing logic for basic blocks of Rust-mapped code - parts of functions and declarations but //! not the full mapping logic. -use std::collections::HashMap; use std::fs::File; use std::io::Write; use proc_macro2::{TokenTree, Span}; @@ -17,12 +16,15 @@ pub fn write_cpp_wrapper(cpp_header_file: &mut File, ty: &str, has_destructor: b writeln!(cpp_header_file, "\tLDK{} self;", ty).unwrap(); writeln!(cpp_header_file, "public:").unwrap(); writeln!(cpp_header_file, "\t{}(const {}&) = delete;", ty, ty).unwrap(); + writeln!(cpp_header_file, "\t{}({}&& o) : self(o.self) {{ memset(&o, 0, sizeof({})); }}", ty, ty, ty).unwrap(); + writeln!(cpp_header_file, "\t{}(LDK{}&& m_self) : self(m_self) {{ memset(&m_self, 0, sizeof(LDK{})); }}", ty, ty, ty).unwrap(); + writeln!(cpp_header_file, "\toperator LDK{}() && {{ LDK{} res = self; memset(&self, 0, sizeof(LDK{})); return res; }}", ty, ty, ty).unwrap(); if has_destructor { writeln!(cpp_header_file, "\t~{}() {{ {}_free(self); }}", ty, ty).unwrap(); + writeln!(cpp_header_file, "\t{}& operator=({}&& o) {{ {}_free(self); self = o.self; memset(&o, 0, sizeof({})); return *this; }}", ty, ty, ty, ty).unwrap(); + } else { + writeln!(cpp_header_file, "\t{}& operator=({}&& o) {{ self = o.self; memset(&o, 0, sizeof({})); return *this; }}", ty, ty, ty).unwrap(); } - writeln!(cpp_header_file, "\t{}({}&& o) : self(o.self) {{ memset(&o, 0, sizeof({})); }}", ty, ty, ty).unwrap(); - writeln!(cpp_header_file, "\t{}(LDK{}&& m_self) : self(m_self) {{ memset(&m_self, 0, sizeof(LDK{})); }}", ty, ty, ty).unwrap(); - writeln!(cpp_header_file, "\toperator LDK{}() {{ LDK{} res = self; memset(&self, 0, sizeof(LDK{})); return res; }}", ty, ty, ty).unwrap(); writeln!(cpp_header_file, "\tLDK{}* operator &() {{ return &self; }}", ty).unwrap(); writeln!(cpp_header_file, "\tLDK{}* operator ->() {{ return &self; }}", ty).unwrap(); writeln!(cpp_header_file, "\tconst LDK{}* operator &() const {{ return &self; }}", ty).unwrap(); @@ -30,6 +32,261 @@ pub fn write_cpp_wrapper(cpp_header_file: &mut File, ty: &str, has_destructor: b writeln!(cpp_header_file, "}};").unwrap(); } +/// Writes out a C-callable concrete Result struct and utility methods +pub fn write_result_block(w: &mut W, mangled_container: &str, ok_type: &str, err_type: &str, clonable: bool) { + writeln!(w, "#[repr(C)]").unwrap(); + writeln!(w, "pub union {}Ptr {{", mangled_container).unwrap(); + if ok_type != "()" { + writeln!(w, "\tpub result: *mut {},", ok_type).unwrap(); + } else { + writeln!(w, "\t/// Note that this value is always NULL, as there are no contents in the OK variant").unwrap(); + writeln!(w, "\tpub result: *mut std::ffi::c_void,").unwrap(); + } + if err_type != "()" { + writeln!(w, "\tpub err: *mut {},", err_type).unwrap(); + } else { + writeln!(w, "\t/// Note that this value is always NULL, as there are no contents in the Err variant").unwrap(); + writeln!(w, "\tpub err: *mut std::ffi::c_void,").unwrap(); + } + writeln!(w, "}}").unwrap(); + writeln!(w, "#[repr(C)]").unwrap(); + writeln!(w, "pub struct {} {{", mangled_container).unwrap(); + writeln!(w, "\tpub contents: {}Ptr,", mangled_container).unwrap(); + writeln!(w, "\tpub result_ok: bool,").unwrap(); + writeln!(w, "}}").unwrap(); + + writeln!(w, "#[no_mangle]").unwrap(); + if ok_type != "()" { + writeln!(w, "pub extern \"C\" fn {}_ok(o: {}) -> {} {{", mangled_container, ok_type, mangled_container).unwrap(); + } else { + writeln!(w, "pub extern \"C\" fn {}_ok() -> {} {{", mangled_container, mangled_container).unwrap(); + } + writeln!(w, "\t{} {{", mangled_container).unwrap(); + writeln!(w, "\t\tcontents: {}Ptr {{", mangled_container).unwrap(); + if ok_type != "()" { + writeln!(w, "\t\t\tresult: Box::into_raw(Box::new(o)),").unwrap(); + } else { + writeln!(w, "\t\t\tresult: std::ptr::null_mut(),").unwrap(); + } + writeln!(w, "\t\t}},").unwrap(); + writeln!(w, "\t\tresult_ok: true,").unwrap(); + writeln!(w, "\t}}").unwrap(); + writeln!(w, "}}").unwrap(); + + writeln!(w, "#[no_mangle]").unwrap(); + if err_type != "()" { + writeln!(w, "pub extern \"C\" fn {}_err(e: {}) -> {} {{", mangled_container, err_type, mangled_container).unwrap(); + } else { + writeln!(w, "pub extern \"C\" fn {}_err() -> {} {{", mangled_container, mangled_container).unwrap(); + } + writeln!(w, "\t{} {{", mangled_container).unwrap(); + writeln!(w, "\t\tcontents: {}Ptr {{", mangled_container).unwrap(); + if err_type != "()" { + writeln!(w, "\t\t\terr: Box::into_raw(Box::new(e)),").unwrap(); + } else { + writeln!(w, "\t\t\terr: std::ptr::null_mut(),").unwrap(); + } + writeln!(w, "\t\t}},").unwrap(); + writeln!(w, "\t\tresult_ok: false,").unwrap(); + writeln!(w, "\t}}").unwrap(); + writeln!(w, "}}").unwrap(); + + writeln!(w, "#[no_mangle]").unwrap(); + writeln!(w, "pub extern \"C\" fn {}_free(_res: {}) {{ }}", mangled_container, mangled_container).unwrap(); + writeln!(w, "impl Drop for {} {{", mangled_container).unwrap(); + writeln!(w, "\tfn drop(&mut self) {{").unwrap(); + writeln!(w, "\t\tif self.result_ok {{").unwrap(); + if ok_type != "()" { + writeln!(w, "\t\t\tif unsafe {{ !(self.contents.result as *mut ()).is_null() }} {{").unwrap(); + writeln!(w, "\t\t\t\tlet _ = unsafe {{ Box::from_raw(self.contents.result) }};").unwrap(); + writeln!(w, "\t\t\t}}").unwrap(); + } + writeln!(w, "\t\t}} else {{").unwrap(); + if err_type != "()" { + writeln!(w, "\t\t\tif unsafe {{ !(self.contents.err as *mut ()).is_null() }} {{").unwrap(); + writeln!(w, "\t\t\t\tlet _ = unsafe {{ Box::from_raw(self.contents.err) }};").unwrap(); + writeln!(w, "\t\t\t}}").unwrap(); + } + writeln!(w, "\t\t}}").unwrap(); + writeln!(w, "\t}}").unwrap(); + writeln!(w, "}}").unwrap(); + + // TODO: Templates should use () now that they can, too + let templ_ok_type = if ok_type != "()" { ok_type } else { "u8" }; + let templ_err_type = if err_type != "()" { err_type } else { "u8" }; + + writeln!(w, "impl From> for {} {{", templ_ok_type, templ_err_type, mangled_container).unwrap(); + writeln!(w, "\tfn from(mut o: crate::c_types::CResultTempl<{}, {}>) -> Self {{", templ_ok_type, templ_err_type).unwrap(); + writeln!(w, "\t\tlet contents = if o.result_ok {{").unwrap(); + if ok_type != "()" { + writeln!(w, "\t\t\tlet result = unsafe {{ o.contents.result }};").unwrap(); + writeln!(w, "\t\t\tunsafe {{ o.contents.result = std::ptr::null_mut() }};").unwrap(); + writeln!(w, "\t\t\t{}Ptr {{ result }}", mangled_container).unwrap(); + } else { + writeln!(w, "\t\t\tlet _ = unsafe {{ Box::from_raw(o.contents.result) }};").unwrap(); + writeln!(w, "\t\t\to.contents.result = std::ptr::null_mut();").unwrap(); + writeln!(w, "\t\t\t{}Ptr {{ result: std::ptr::null_mut() }}", mangled_container).unwrap(); + } + writeln!(w, "\t\t}} else {{").unwrap(); + if err_type != "()" { + writeln!(w, "\t\t\tlet err = unsafe {{ o.contents.err }};").unwrap(); + writeln!(w, "\t\t\tunsafe {{ o.contents.err = std::ptr::null_mut(); }}").unwrap(); + writeln!(w, "\t\t\t{}Ptr {{ err }}", mangled_container).unwrap(); + } else { + writeln!(w, "\t\t\tlet _ = unsafe {{ Box::from_raw(o.contents.err) }};").unwrap(); + writeln!(w, "\t\t\to.contents.err = std::ptr::null_mut();").unwrap(); + writeln!(w, "\t\t\t{}Ptr {{ err: std::ptr::null_mut() }}", mangled_container).unwrap(); + } + writeln!(w, "\t\t}};").unwrap(); + writeln!(w, "\t\tSelf {{").unwrap(); + writeln!(w, "\t\t\tcontents,").unwrap(); + writeln!(w, "\t\t\tresult_ok: o.result_ok,").unwrap(); + writeln!(w, "\t\t}}").unwrap(); + writeln!(w, "\t}}").unwrap(); + writeln!(w, "}}").unwrap(); + + if clonable { + writeln!(w, "impl Clone for {} {{", mangled_container).unwrap(); + writeln!(w, "\tfn clone(&self) -> Self {{").unwrap(); + writeln!(w, "\t\tif self.result_ok {{").unwrap(); + writeln!(w, "\t\t\tSelf {{ result_ok: true, contents: {}Ptr {{", mangled_container).unwrap(); + if ok_type != "()" { + writeln!(w, "\t\t\t\tresult: Box::into_raw(Box::new(<{}>::clone(unsafe {{ &*self.contents.result }})))", ok_type).unwrap(); + } else { + writeln!(w, "\t\t\t\tresult: std::ptr::null_mut()").unwrap(); + } + writeln!(w, "\t\t\t}} }}").unwrap(); + writeln!(w, "\t\t}} else {{").unwrap(); + writeln!(w, "\t\t\tSelf {{ result_ok: false, contents: {}Ptr {{", mangled_container).unwrap(); + if err_type != "()" { + writeln!(w, "\t\t\t\terr: Box::into_raw(Box::new(<{}>::clone(unsafe {{ &*self.contents.err }})))", err_type).unwrap(); + } else { + writeln!(w, "\t\t\t\terr: std::ptr::null_mut()").unwrap(); + } + writeln!(w, "\t\t\t}} }}").unwrap(); + writeln!(w, "\t\t}}").unwrap(); + writeln!(w, "\t}}").unwrap(); + writeln!(w, "}}").unwrap(); + writeln!(w, "#[no_mangle]").unwrap(); + writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{ orig.clone() }}", mangled_container, mangled_container, mangled_container).unwrap(); + } +} + +/// Writes out a C-callable concrete Vec struct and utility methods +pub fn write_vec_block(w: &mut W, mangled_container: &str, inner_type: &str, clonable: bool) { + writeln!(w, "#[repr(C)]").unwrap(); + writeln!(w, "pub struct {} {{", mangled_container).unwrap(); + writeln!(w, "\tpub data: *mut {},", inner_type).unwrap(); + writeln!(w, "\tpub datalen: usize").unwrap(); + writeln!(w, "}}").unwrap(); + + writeln!(w, "impl {} {{", mangled_container).unwrap(); + writeln!(w, "\t#[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec<{}> {{", inner_type).unwrap(); + writeln!(w, "\t\tif self.datalen == 0 {{ return Vec::new(); }}").unwrap(); + writeln!(w, "\t\tlet ret = unsafe {{ Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }}.into();").unwrap(); + writeln!(w, "\t\tself.data = std::ptr::null_mut();").unwrap(); + writeln!(w, "\t\tself.datalen = 0;").unwrap(); + writeln!(w, "\t\tret").unwrap(); + writeln!(w, "\t}}").unwrap(); + writeln!(w, "\t#[allow(unused)] pub(crate) fn as_slice(&self) -> &[{}] {{", inner_type).unwrap(); + writeln!(w, "\t\tunsafe {{ std::slice::from_raw_parts_mut(self.data, self.datalen) }}").unwrap(); + writeln!(w, "\t}}").unwrap(); + writeln!(w, "}}").unwrap(); + + writeln!(w, "impl From> for {} {{", inner_type, mangled_container).unwrap(); + writeln!(w, "\tfn from(v: Vec<{}>) -> Self {{", inner_type).unwrap(); + writeln!(w, "\t\tlet datalen = v.len();").unwrap(); + writeln!(w, "\t\tlet data = Box::into_raw(v.into_boxed_slice());").unwrap(); + writeln!(w, "\t\tSelf {{ datalen, data: unsafe {{ (*data).as_mut_ptr() }} }}").unwrap(); + writeln!(w, "\t}}").unwrap(); + writeln!(w, "}}").unwrap(); + + writeln!(w, "#[no_mangle]").unwrap(); + writeln!(w, "pub extern \"C\" fn {}_free(_res: {}) {{ }}", mangled_container, mangled_container).unwrap(); + writeln!(w, "impl Drop for {} {{", mangled_container).unwrap(); + writeln!(w, "\tfn drop(&mut self) {{").unwrap(); + writeln!(w, "\t\tif self.datalen == 0 {{ return; }}").unwrap(); + writeln!(w, "\t\tunsafe {{ Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }};").unwrap(); + writeln!(w, "\t}}").unwrap(); + writeln!(w, "}}").unwrap(); + if clonable { + writeln!(w, "impl Clone for {} {{", mangled_container).unwrap(); + writeln!(w, "\tfn clone(&self) -> Self {{").unwrap(); + writeln!(w, "\t\tlet mut res = Vec::new();").unwrap(); + writeln!(w, "\t\tif self.datalen == 0 {{ return Self::from(res); }}").unwrap(); + writeln!(w, "\t\tres.extend_from_slice(unsafe {{ std::slice::from_raw_parts_mut(self.data, self.datalen) }});").unwrap(); + writeln!(w, "\t\tSelf::from(res)").unwrap(); + writeln!(w, "\t}}").unwrap(); + writeln!(w, "}}").unwrap(); + } +} + +/// Writes out a C-callable concrete (A, B, ...) struct and utility methods +pub fn write_tuple_block(w: &mut W, mangled_container: &str, types: &[String], clonable: bool) { + writeln!(w, "#[repr(C)]").unwrap(); + writeln!(w, "pub struct {} {{", mangled_container).unwrap(); + for (idx, ty) in types.iter().enumerate() { + writeln!(w, "\tpub {}: {},", ('a' as u8 + idx as u8) as char, ty).unwrap(); + } + writeln!(w, "}}").unwrap(); + + let mut tuple_str = "(".to_owned(); + for (idx, ty) in types.iter().enumerate() { + if idx != 0 { tuple_str += ", "; } + tuple_str += ty; + } + tuple_str += ")"; + + writeln!(w, "impl From<{}> for {} {{", tuple_str, mangled_container).unwrap(); + writeln!(w, "\tfn from (tup: {}) -> Self {{", tuple_str).unwrap(); + writeln!(w, "\t\tSelf {{").unwrap(); + for idx in 0..types.len() { + writeln!(w, "\t\t\t{}: tup.{},", ('a' as u8 + idx as u8) as char, idx).unwrap(); + } + writeln!(w, "\t\t}}").unwrap(); + writeln!(w, "\t}}").unwrap(); + writeln!(w, "}}").unwrap(); + writeln!(w, "impl {} {{", mangled_container).unwrap(); + writeln!(w, "\t#[allow(unused)] pub(crate) fn to_rust(mut self) -> {} {{", tuple_str).unwrap(); + write!(w, "\t\t(").unwrap(); + for idx in 0..types.len() { + write!(w, "{}self.{}", if idx != 0 {", "} else {""}, ('a' as u8 + idx as u8) as char).unwrap(); + } + writeln!(w, ")").unwrap(); + writeln!(w, "\t}}").unwrap(); + writeln!(w, "}}").unwrap(); + + if clonable { + writeln!(w, "impl Clone for {} {{", mangled_container).unwrap(); + writeln!(w, "\tfn clone(&self) -> Self {{").unwrap(); + writeln!(w, "\t\tSelf {{").unwrap(); + for idx in 0..types.len() { + writeln!(w, "\t\t\t{}: self.{}.clone(),", ('a' as u8 + idx as u8) as char, ('a' as u8 + idx as u8) as char).unwrap(); + } + writeln!(w, "\t\t}}").unwrap(); + writeln!(w, "\t}}").unwrap(); + writeln!(w, "}}").unwrap(); + writeln!(w, "#[no_mangle]").unwrap(); + writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{ orig.clone() }}", mangled_container, mangled_container, mangled_container).unwrap(); + } + + write!(w, "#[no_mangle]\npub extern \"C\" fn {}_new(", mangled_container).unwrap(); + for (idx, gen) in types.iter().enumerate() { + write!(w, "{}{}: ", if idx != 0 { ", " } else { "" }, ('a' as u8 + idx as u8) as char).unwrap(); + //if !self.write_c_type_intern(&mut created_container, gen, generics, false, false, false) { return false; } + write!(w, "{}", gen).unwrap(); + } + writeln!(w, ") -> {} {{", mangled_container).unwrap(); + write!(w, "\t{} {{ ", mangled_container).unwrap(); + for idx in 0..types.len() { + write!(w, "{}, ", ('a' as u8 + idx as u8) as char).unwrap(); + } + writeln!(w, "}}\n}}\n").unwrap(); + + writeln!(w, "#[no_mangle]").unwrap(); + writeln!(w, "pub extern \"C\" fn {}_free(_res: {}) {{ }}", mangled_container, mangled_container).unwrap(); +} + /// Prints the docs from a given attribute list unless its tagged no export pub fn writeln_docs(w: &mut W, attrs: &[syn::Attribute], prefix: &str) { for attr in attrs.iter() { @@ -77,7 +334,7 @@ pub fn writeln_docs(w: &mut W, attrs: &[syn::Attribute], pref /// /// this_param is used when returning Self or accepting a self parameter, and should be the /// concrete, mapped type. -pub fn write_method_params(w: &mut W, sig: &syn::Signature, associated_types: &HashMap<&syn::Ident, &syn::Ident>, this_param: &str, types: &mut TypeResolver, generics: Option<&GenericTypes>, self_ptr: bool, fn_decl: bool) { +pub fn write_method_params(w: &mut W, sig: &syn::Signature, this_param: &str, types: &mut TypeResolver, generics: Option<&GenericTypes>, self_ptr: bool, fn_decl: bool) { if sig.constness.is_some() || sig.asyncness.is_some() || sig.unsafety.is_some() || sig.abi.is_some() || sig.variadic.is_some() { unimplemented!(); @@ -140,26 +397,16 @@ pub fn write_method_params(w: &mut W, sig: &syn::Signature, a syn::ReturnType::Type(_, rtype) => { write!(w, " -> ").unwrap(); if let Some(mut remaining_path) = first_seg_self(&*rtype) { - if let Some(associated_seg) = get_single_remaining_path_seg(&mut remaining_path) { - // We're returning an associated type in a trait impl. Its probably a safe bet - // that its also a trait, so just return the trait type. - let real_type = associated_types.get(associated_seg).unwrap(); - types.write_c_type(w, &syn::Type::Path(syn::TypePath { qself: None, - path: syn::PathSegment { - ident: (*real_type).clone(), - arguments: syn::PathArguments::None - }.into() - }), generics, true); - } else { + if remaining_path.next().is_none() { write!(w, "{}", this_param).unwrap(); + return; } + } + if let syn::Type::Reference(r) = &**rtype { + // We can't return a reference, cause we allocate things on the stack. + types.write_c_type(w, &*r.elem, generics, true); } else { - if let syn::Type::Reference(r) = &**rtype { - // We can't return a reference, cause we allocate things on the stack. - types.write_c_type(w, &*r.elem, generics, true); - } else { - types.write_c_type(w, &*rtype, generics, true); - } + types.write_c_type(w, &*rtype, generics, true); } }, _ => {}, @@ -222,7 +469,7 @@ pub fn write_method_var_decl_body(w: &mut W, sig: &syn::Signa /// /// The return value is expected to be bound to a variable named `ret` which is available after a /// method-call-ending semicolon. -pub fn write_method_call_params(w: &mut W, sig: &syn::Signature, associated_types: &HashMap<&syn::Ident, &syn::Ident>, extra_indent: &str, types: &TypeResolver, generics: Option<&GenericTypes>, this_type: &str, to_c: bool) { +pub fn write_method_call_params(w: &mut W, sig: &syn::Signature, extra_indent: &str, types: &TypeResolver, generics: Option<&GenericTypes>, this_type: &str, to_c: bool) { let mut first_arg = true; let mut num_unused = 0; for inp in sig.inputs.iter() { @@ -285,26 +532,12 @@ pub fn write_method_call_params(w: &mut W, sig: &syn::Signatu syn::ReturnType::Type(_, rtype) => { write!(w, ";\n\t{}", extra_indent).unwrap(); + let self_segs_iter = first_seg_self(&*rtype); if to_c && first_seg_self(&*rtype).is_some() { // Assume rather blindly that we're returning an associated trait from a C fn call to a Rust trait object. write!(w, "ret").unwrap(); - } else if !to_c && first_seg_self(&*rtype).is_some() { - if let Some(mut remaining_path) = first_seg_self(&*rtype) { - if let Some(associated_seg) = get_single_remaining_path_seg(&mut remaining_path) { - let real_type = associated_types.get(associated_seg).unwrap(); - if let Some(t) = types.crate_types.traits.get(&types.maybe_resolve_ident(&real_type).unwrap()) { - // We're returning an associated trait from a Rust fn call to a C trait - // object. - writeln!(w, "let mut rust_obj = {} {{ inner: Box::into_raw(Box::new(ret)), is_owned: true }};", this_type).unwrap(); - writeln!(w, "\t{}let mut ret = {}_as_{}(&rust_obj);", extra_indent, this_type, t.ident).unwrap(); - writeln!(w, "\t{}// We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn", extra_indent).unwrap(); - writeln!(w, "\t{}rust_obj.inner = std::ptr::null_mut();", extra_indent).unwrap(); - writeln!(w, "\t{}ret.free = Some({}_free_void);", extra_indent, this_type).unwrap(); - writeln!(w, "\t{}ret", extra_indent).unwrap(); - return; - } - } - } + } else if !to_c && self_segs_iter.is_some() && self_segs_iter.unwrap().next().is_none() { + // If we're returning "Self" (and not "Self::X"), just do it manually write!(w, "{} {{ inner: Box::into_raw(Box::new(ret)), is_owned: true }}", this_type).unwrap(); } else if to_c { let new_var = types.write_from_c_conversion_new_var(w, &syn::Ident::new("ret", Span::call_site()), rtype, generics);