From e561c272cdfcac8ce979172686b14dbe331dc1b6 Mon Sep 17 00:00:00 2001 From: Andrew Hayzen Date: Thu, 15 Dec 2022 11:13:37 +0000 Subject: [PATCH] cxx-qt-gen: add support for Fn pointer in C++ generation Related to #328 --- crates/cxx-qt-gen/src/generator/cpp/types.rs | 41 ++++++++++++++++++-- 1 file changed, 38 insertions(+), 3 deletions(-) diff --git a/crates/cxx-qt-gen/src/generator/cpp/types.rs b/crates/cxx-qt-gen/src/generator/cpp/types.rs index ee48fbf8f..55d7f1a7c 100644 --- a/crates/cxx-qt-gen/src/generator/cpp/types.rs +++ b/crates/cxx-qt-gen/src/generator/cpp/types.rs @@ -5,8 +5,8 @@ use std::collections::BTreeMap; use syn::{ - spanned::Spanned, Error, Expr, GenericArgument, Lit, PathArguments, PathSegment, Result, Type, - TypeArray, TypeReference, TypeSlice, + spanned::Spanned, Error, Expr, GenericArgument, Lit, PathArguments, PathSegment, Result, + ReturnType, Type, TypeArray, TypeBareFn, TypeReference, TypeSlice, }; /// A helper for describing a C++ type @@ -73,6 +73,24 @@ fn to_cpp_string(ty: &Type, cxx_names_map: &BTreeMap) -> Result< len = len )) } + Type::BareFn(TypeBareFn { inputs, output, .. }) => { + let ret = if let ReturnType::Type(_, ty) = output { + to_cpp_string(ty, cxx_names_map)? + } else { + "void".to_owned() + }; + + let args = inputs + .iter() + .map(|arg| to_cpp_string(&arg.ty, cxx_names_map)) + .collect::>>()?; + + Ok(format!( + "::rust::Fn<{ret}, ({args})>", + ret = ret, + args = args.join(", ") + )) + } Type::Path(ty_path) => { let ty_strings = ty_path .path @@ -226,7 +244,6 @@ fn possible_built_in_template_base(ty: &str) -> String { "SharedPtr" => "::std::shared_ptr", "WeakPtr" => "::std::weak_ptr", "CxxVector" => "::std::vector", - // TODO: handle Fn pointer others => others, // TODO: what happens with Result ? } @@ -465,4 +482,22 @@ mod tests { let ty = tokens_to_syn(quote! { [i32; String] }); assert!(to_cpp_string(&ty, &cxx_names_map_default()).is_err()); } + + #[test] + fn test_to_cpp_string_fn() { + let ty = tokens_to_syn(quote! { fn(i32, i32) -> bool }); + assert_eq!( + to_cpp_string(&ty, &cxx_names_map_default()).unwrap(), + "::rust::Fn" + ); + } + + #[test] + fn test_to_cpp_string_fn_void() { + let ty = tokens_to_syn(quote! { fn() }); + assert_eq!( + to_cpp_string(&ty, &cxx_names_map_default()).unwrap(), + "::rust::Fn" + ); + } }