Use `parse_quote!()` to build complex syn::* objects
authorAlekos Filini <alekos.filini@gmail.com>
Mon, 26 Apr 2021 10:01:09 +0000 (12:01 +0200)
committerAlekos Filini <alekos.filini@gmail.com>
Mon, 26 Apr 2021 10:03:14 +0000 (12:03 +0200)
c-bindings-gen/src/main.rs
c-bindings-gen/src/types.rs

index e217bab57aa97723ed7389e480fa092842333118..e30bb160247b3de02957ec89b8192db38bfee53c 100644 (file)
@@ -25,6 +25,7 @@ use std::io::{Read, Write};
 use std::process;
 
 use proc_macro2::Span;
+use syn::parse_quote;
 
 mod types;
 mod blocks;
@@ -63,9 +64,7 @@ fn maybe_convert_trait_impl<W: std::io::Write>(w: &mut W, trait_path: &syn::Path
                                writeln!(w, "/// Serialize the {} object into a byte array which can be read by {}_read", for_obj, for_obj).unwrap();
                                writeln!(w, "pub extern \"C\" fn {}_write(obj: &{}) -> crate::c_types::derived::CVec_u8Z {{", for_obj, full_obj_path).unwrap();
 
-                               let ref_type = syn::Type::Reference(syn::TypeReference {
-                                       and_token: syn::Token!(&)(Span::call_site()), lifetime: None, mutability: None,
-                                       elem: Box::new(for_ty.clone()) });
+                               let ref_type: syn::Type = syn::parse_quote!(&#for_ty);
                                assert!(!types.write_from_c_conversion_new_var(w, &syn::Ident::new("obj", Span::call_site()), &ref_type, Some(generics)));
 
                                write!(w, "\tcrate::c_types::serialize_obj(").unwrap();
@@ -84,26 +83,7 @@ fn maybe_convert_trait_impl<W: std::io::Write>(w: &mut W, trait_path: &syn::Path
                        },
                        "lightning::util::ser::Readable"|"lightning::util::ser::ReadableArgs" => {
                                // Create the Result<Object, DecodeError> syn::Type
-                               let mut err_segs = syn::punctuated::Punctuated::new();
-                               err_segs.push(syn::PathSegment { ident: syn::Ident::new("ln", Span::call_site()), arguments: syn::PathArguments::None });
-                               err_segs.push(syn::PathSegment { ident: syn::Ident::new("msgs", Span::call_site()), arguments: syn::PathArguments::None });
-                               err_segs.push(syn::PathSegment { ident: syn::Ident::new("DecodeError", Span::call_site()), arguments: syn::PathArguments::None });
-                               let mut args = syn::punctuated::Punctuated::new();
-                               args.push(syn::GenericArgument::Type(for_ty.clone()));
-                               args.push(syn::GenericArgument::Type(syn::Type::Path(syn::TypePath {
-                                       qself: None, path: syn::Path {
-                                               leading_colon: Some(syn::Token![::](Span::call_site())), segments: err_segs,
-                                       }
-                               })));
-                               let mut res_segs = syn::punctuated::Punctuated::new();
-                               res_segs.push(syn::PathSegment {
-                                       ident: syn::Ident::new("Result", Span::call_site()),
-                                       arguments: syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments {
-                                               colon2_token: None, lt_token: syn::Token![<](Span::call_site()), args, gt_token: syn::Token![>](Span::call_site()),
-                                       })
-                               });
-                               let res_ty = syn::Type::Path(syn::TypePath { qself: None, path: syn::Path {
-                                       leading_colon: None, segments: res_segs } });
+                               let res_ty: syn::Type = parse_quote!(Result<#for_ty, ::ln::msgs::DecodeError>);
 
                                writeln!(w, "#[no_mangle]").unwrap();
                                writeln!(w, "/// Read a {} from a byte array, created by {}_write", for_obj, for_obj).unwrap();
index 80ad2af4247c2657aec06b8dbf17d7a3075d71c6..85fd01c9e6bf2e7efdb90248e47ad1d8e5dad409 100644 (file)
@@ -15,6 +15,7 @@ use std::hash;
 use crate::blocks::*;
 
 use proc_macro2::{TokenTree, Span};
+use syn::parse_quote;
 
 // The following utils are used purely to build our known types maps - they break down all the
 // types we need to resolve to include the given object, and no more.
@@ -1457,15 +1458,7 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                                let tail_str = split.next().unwrap();
                                assert!(split.next().is_none());
                                let len = &tail_str[..tail_str.len() - 1];
-                               Some(syn::Type::Array(syn::TypeArray {
-                                               bracket_token: syn::token::Bracket { span: Span::call_site() },
-                                               elem: Box::new(syn::Type::Path(syn::TypePath {
-                                                       qself: None,
-                                                       path: syn::Path::from(syn::PathSegment::from(syn::Ident::new("u8", Span::call_site()))),
-                                               })),
-                                               semi_token: syn::Token!(;)(Span::call_site()),
-                                               len: syn::Expr::Lit(syn::ExprLit { attrs: Vec::new(), lit: syn::Lit::Int(syn::LitInt::new(len, Span::call_site())) }),
-                                       }))
+                               Some(parse_quote!([u8; #len]))
                        } else { None }
                } else { None }
        }
@@ -2397,15 +2390,10 @@ impl<'a, 'c: 'a> TypeResolver<'a, 'c> {
                                                self.check_create_container(mangled_container, "Vec", vec![&*r.elem], generics, false)
                                        } else { false }
                                } else if let syn::Type::Tuple(_) = &*s.elem {
-                                       let mut args = syn::punctuated::Punctuated::new();
+                                       let mut args = syn::punctuated::Punctuated::<_, syn::token::Comma>::new();
                                        args.push(syn::GenericArgument::Type((*s.elem).clone()));
                                        let mut segments = syn::punctuated::Punctuated::new();
-                                       segments.push(syn::PathSegment {
-                                               ident: syn::Ident::new("Vec", Span::call_site()),
-                                               arguments: syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments {
-                                                       colon2_token: None, lt_token: syn::Token![<](Span::call_site()), args, gt_token: syn::Token![>](Span::call_site()),
-                                               })
-                                       });
+                                       segments.push(parse_quote!(Vec<#args>));
                                        self.write_c_type_intern(w, &syn::Type::Path(syn::TypePath { qself: None, path: syn::Path { leading_colon: None, segments } }), generics, false, is_mut, ptr_for_ref)
                                } else { false }
                        },