//! It also generates relevant memory-management functions and free-standing functions with
//! parameters mapped.
-use std::collections::{HashMap, hash_map, HashSet};
+use std::collections::{HashMap, hash_map};
use std::env;
use std::fs::File;
use std::io::{Read, Write};
use std::process;
-use proc_macro2::{TokenTree, TokenStream, Span};
+use proc_macro2::Span;
mod types;
mod blocks;
// *** Manually-expanded conversions ***
// *************************************
-/// Because we don't expand macros, any code that we need to generated based on their contents has
-/// to be completely manual. In this case its all just serialization, so its not too hard.
-fn convert_macro<W: std::io::Write>(w: &mut W, macro_path: &syn::Path, stream: &TokenStream, types: &TypeResolver) {
- assert_eq!(macro_path.segments.len(), 1);
- match &format!("{}", macro_path.segments.iter().next().unwrap().ident) as &str {
- "impl_writeable" | "impl_writeable_len_match" => {
- let struct_for = if let TokenTree::Ident(i) = stream.clone().into_iter().next().unwrap() { i } else { unimplemented!(); };
- if let Some(s) = types.maybe_resolve_ident(&struct_for) {
- if !types.crate_types.opaques.get(&s).is_some() { return; }
- writeln!(w, "#[no_mangle]").unwrap();
- writeln!(w, "/// Serialize the {} into a byte array which can be read by {}_read", struct_for, struct_for).unwrap();
- writeln!(w, "pub extern \"C\" fn {}_write(obj: &{}) -> crate::c_types::derived::CVec_u8Z {{", struct_for, struct_for).unwrap();
- writeln!(w, "\tcrate::c_types::serialize_obj(unsafe {{ &(*(*obj).inner) }})").unwrap();
- writeln!(w, "}}").unwrap();
- writeln!(w, "#[no_mangle]").unwrap();
- writeln!(w, "pub(crate) extern \"C\" fn {}_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {{", struct_for).unwrap();
- writeln!(w, "\tcrate::c_types::serialize_obj(unsafe {{ &*(obj as *const native{}) }})", struct_for).unwrap();
- writeln!(w, "}}").unwrap();
- writeln!(w, "#[no_mangle]").unwrap();
- writeln!(w, "/// Read a {} from a byte array, created by {}_write", struct_for, struct_for).unwrap();
- writeln!(w, "pub extern \"C\" fn {}_read(ser: crate::c_types::u8slice) -> {} {{", struct_for, struct_for).unwrap();
- writeln!(w, "\tif let Ok(res) = crate::c_types::deserialize_obj(ser) {{").unwrap();
- writeln!(w, "\t\t{} {{ inner: Box::into_raw(Box::new(res)), is_owned: true }}", struct_for).unwrap();
- writeln!(w, "\t}} else {{").unwrap();
- writeln!(w, "\t\t{} {{ inner: std::ptr::null_mut(), is_owned: true }}", struct_for).unwrap();
- writeln!(w, "\t}}\n}}").unwrap();
- }
- },
- _ => {},
- }
-}
-
/// Convert "impl trait_path for for_ty { .. }" for manually-mapped types (ie (de)serialization)
fn maybe_convert_trait_impl<W: std::io::Write>(w: &mut W, trait_path: &syn::Path, for_ty: &syn::Type, types: &mut TypeResolver, generics: &GenericTypes) {
if let Some(t) = types.maybe_resolve_path(&trait_path, Some(generics)) {
}
/// Write out the impl block for a defined trait struct which has a supertrait
-fn do_write_impl_trait<W: std::io::Write>(w: &mut W, trait_path: &str, trait_name: &syn::Ident, for_obj: &str) {
+fn do_write_impl_trait<W: std::io::Write>(w: &mut W, trait_path: &str, _trait_name: &syn::Ident, for_obj: &str) {
+eprintln!("{}", trait_path);
match trait_path {
- "util::events::MessageSendEventsProvider" => {
- writeln!(w, "impl lightning::{} for {} {{", trait_path, for_obj).unwrap();
- writeln!(w, "\tfn get_and_clear_pending_msg_events(&self) -> Vec<lightning::util::events::MessageSendEvent> {{").unwrap();
- writeln!(w, "\t\t<crate::{} as lightning::{}>::get_and_clear_pending_msg_events(&self.{})", trait_path, trait_path, trait_name).unwrap();
- writeln!(w, "\t}}\n}}").unwrap();
- },
"util::ser::Writeable" => {
writeln!(w, "impl lightning::{} for {} {{", trait_path, for_obj).unwrap();
writeln!(w, "\tfn write<W: lightning::util::ser::Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {{").unwrap();
// ********************************
// *** File/Crate Walking Logic ***
// ********************************
-/// A public module
-struct ASTModule {
- pub attrs: Vec<syn::Attribute>,
- pub items: Vec<syn::Item>,
- pub submods: Vec<String>,
-}
-/// A struct containing the syn::File AST for each file in the crate.
-struct FullLibraryAST {
- modules: HashMap<String, ASTModule, NonRandomHash>,
-}
-impl FullLibraryAST {
- fn load_module(&mut self, module: String, attrs: Vec<syn::Attribute>, mut items: Vec<syn::Item>) {
- let mut non_mod_items = Vec::with_capacity(items.len());
- let mut submods = Vec::with_capacity(items.len());
- for item in items.drain(..) {
- match item {
- syn::Item::Mod(m) if m.content.is_some() => {
- if export_status(&m.attrs) == ExportStatus::Export {
- if let syn::Visibility::Public(_) = m.vis {
- let modident = format!("{}", m.ident);
- let modname = if module != "" {
- module.clone() + "::" + &modident
- } else {
- modident.clone()
- };
- self.load_module(modname, m.attrs, m.content.unwrap().1);
- submods.push(modident);
- } else {
- non_mod_items.push(syn::Item::Mod(m));
- }
- }
- },
- syn::Item::Mod(_) => panic!("--pretty=expanded output should never have non-body modules"),
- _ => { non_mod_items.push(item); }
- }
- }
- self.modules.insert(module, ASTModule { attrs, items: non_mod_items, submods });
- }
-
- pub fn load_lib(lib: syn::File) -> Self {
- assert_eq!(export_status(&lib.attrs), ExportStatus::Export);
- let mut res = Self { modules: HashMap::default() };
- res.load_module("".to_owned(), lib.attrs, lib.items);
- res
- }
-}
/// Do the Real Work of mapping an original file to C-callable wrappers. Creates a new file at
/// `out_path` and fills it with wrapper structs/functions to allow calling the things in the AST
/// at `module` from C.
-fn convert_file<'a, 'b>(libast: &'a FullLibraryAST, crate_types: &mut CrateTypes<'a>, out_dir: &str, orig_crate: &str, header_file: &mut File, cpp_header_file: &mut File) {
+fn convert_file<'a, 'b>(libast: &'a FullLibraryAST, crate_types: &CrateTypes<'a>, out_dir: &str, orig_crate: &str, header_file: &mut File, cpp_header_file: &mut File) {
for (module, astmod) in libast.modules.iter() {
let ASTModule { ref attrs, ref items, ref submods } = astmod;
assert_eq!(export_status(&attrs), ExportStatus::Export);
writeln_fn(&mut out, &f, &mut type_resolver);
}
},
- syn::Item::Macro(m) => {
- if m.ident.is_none() { // If its not a macro definition
- convert_macro(&mut out, &m.mac.path, &m.mac.tokens, &type_resolver);
- }
- },
+ syn::Item::Macro(_) => {},
syn::Item::Verbatim(_) => {},
syn::Item::ExternCrate(_) => {},
_ => unimplemented!(),
let trait_path = format!("{}::{}", module, t.ident);
walk_supertraits!(t, None, (
("Clone", _) => {
- crate_types.clonable_types.insert("crate::".to_owned() + &trait_path);
+ crate_types.set_clonable("crate::".to_owned() + &trait_path);
},
(_, _) => {}
) );
if let Some(trait_path) = i.trait_.as_ref() {
if path_matches_nongeneric(&trait_path.1, &["core", "clone", "Clone"]) {
if let Some(full_path) = import_resolver.maybe_resolve_path(&p.path, None) {
- crate_types.clonable_types.insert("crate::".to_owned() + &full_path);
+ crate_types.set_clonable("crate::".to_owned() + &full_path);
}
}
if let Some(tp) = import_resolver.maybe_resolve_path(&trait_path.1, None) {
// ...then walk the ASTs tracking what types we will map, and how, so that we can resolve them
// when parsing other file ASTs...
- let mut libtypes = CrateTypes { traits: HashMap::new(), opaques: HashMap::new(), mirrored_enums: HashMap::new(),
- type_aliases: HashMap::new(), reverse_alias_map: HashMap::new(), templates_defined: HashMap::default(),
- template_file: &mut derived_templates,
- clonable_types: HashSet::new(), trait_impls: HashMap::new() };
+ let mut libtypes = CrateTypes::new(&mut derived_templates, &libast);
walk_ast(&libast, &mut libtypes);
// ... finally, do the actual file conversion/mapping, writing out types as we go.
- convert_file(&libast, &mut libtypes, &args[1], &args[2], &mut header_file, &mut cpp_header_file);
+ convert_file(&libast, &libtypes, &args[1], &args[2], &mut header_file, &mut cpp_header_file);
// For container templates which we created while walking the crate, make sure we add C++
// mapped types so that C++ users can utilize the auto-destructors available.
- for (ty, has_destructor) in libtypes.templates_defined.iter() {
+ for (ty, has_destructor) in libtypes.templates_defined.borrow().iter() {
write_cpp_wrapper(&mut cpp_header_file, ty, *has_destructor);
}
writeln!(cpp_header_file, "}}").unwrap();