Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Subtype polymorphism #1392

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions engine/src/conversion/analysis/fun/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -606,6 +606,7 @@ impl<'a> FnAnalyzer<'a> {
TypeConversionSophistication::SimpleForSubclasses,
Some(analysis.rust_name.clone()),
);

for sub in self.subclasses_by_superclass(sup) {
// For each subclass, we need to create a plain-C++ method to call its superclass
// and a Rust/C++ bridge API to call _that_.
Expand Down Expand Up @@ -676,7 +677,7 @@ impl<'a> FnAnalyzer<'a> {
}
}
}

results.push(Api::Function {
fun,
analysis,
Expand Down Expand Up @@ -1279,7 +1280,7 @@ impl<'a> FnAnalyzer<'a> {
// C++ API and we need to create a C++ wrapper function which is more cxx-compliant.
// That wrapper function is included in the cxx::bridge, and calls through to the
// original function.
let wrapper_function_needed = match kind {
let mut wrapper_function_needed = match kind {
FnKind::Method {
method_kind:
MethodKind::Static
Expand All @@ -1303,6 +1304,9 @@ impl<'a> FnAnalyzer<'a> {
_ if self.force_wrapper_generation => true,
_ => false,
};
if param_details.iter_mut().filter(|p| p.has_lifetime).count() != 0 {
wrapper_function_needed = true;
}

let cpp_wrapper = if wrapper_function_needed {
// Generate a new layer of C++ code to wrap/unwrap parameters
Expand Down
1 change: 1 addition & 0 deletions engine/src/conversion/analysis/fun/subclass.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ pub(super) fn subclasses_by_superclass(
let mut subclasses_per_superclass: HashMap<QualifiedName, Vec<SubclassName>> = HashMap::new();

for api in apis.iter() {

if let Api::Subclass { name, superclass } = api {
subclasses_per_superclass
.entry(superclass.clone())
Expand Down
7 changes: 6 additions & 1 deletion engine/src/conversion/codegen_rs/fun_codegen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,11 +150,12 @@ pub(super) fn gen_function(
ref method_kind,
..
} => {
// Method, or static method.
impl_entry = Some(fn_generator.generate_method_impl(
matches!(method_kind, MethodKind::Constructor { .. }),
matches!(method_kind, MethodKind::Virtual { .. }),
impl_for,
));

}
FnKind::TraitMethod { ref details, .. } => {
trait_impl_entry = Some(fn_generator.generate_trait_impl(details));
Expand Down Expand Up @@ -216,6 +217,7 @@ pub(super) fn gen_function(
#(#doc_attrs)*
#vis #bridge_unsafety fn #cxxbridge_name #lifetime_tokens ( #params ) #ret_type;
));

RsCodegenResult {
extern_c_mod_items: vec![extern_c_mod_item],
bindgen_mod_items,
Expand Down Expand Up @@ -387,6 +389,7 @@ impl<'a> FnGenerator<'a> {
fn generate_method_impl(
&self,
avoid_self: bool,
virt: bool,
impl_block_type_name: &QualifiedName,
) -> Box<ImplBlockDetails> {
let (lifetime_tokens, wrapper_params, ret_type, call_body) =
Expand Down Expand Up @@ -427,6 +430,7 @@ impl<'a> FnGenerator<'a> {
}
}),
ty,
virt
})
}

Expand Down Expand Up @@ -470,6 +474,7 @@ impl<'a> FnGenerator<'a> {
Box::new(ImplBlockDetails {
item: ImplItem::Fn(parse_quote! { #stuff }),
ty: ImplBlockKey { ty, lifetime: None },
virt: false,
})
}

Expand Down
45 changes: 35 additions & 10 deletions engine/src/conversion/codegen_rs/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,18 @@ mod lifetime;
mod namespace_organizer;
mod non_pod_struct;
pub(crate) mod unqualify;
mod polymorphism;

use indexmap::map::IndexMap as HashMap;
use indexmap::set::IndexSet as HashSet;

use autocxx_parser::{ExternCppType, IncludeCppConfig, RustFun, UnsafePolicy};

use itertools::Itertools;
use polymorphism::{conv_ref_args, polymorphise};
use proc_macro2::{Span, TokenStream};
use syn::{
parse_quote, punctuated::Punctuated, token::Comma, Attribute, Expr, FnArg, ForeignItem,
ForeignItemFn, Ident, ImplItem, Item, ItemForeignMod, ItemMod, Lifetime, TraitItem, Type,
TypePath,
parse_quote, punctuated::Punctuated, token::Comma, Attribute, Expr, FnArg, ForeignItem, ForeignItemFn, Ident, ImplItem, Item, ItemForeignMod, ItemMod, Lifetime, TraitItem, Type, TypePath
};

use crate::{
Expand All @@ -47,7 +47,7 @@ use super::{
fun::{FnPhase, PodAndDepAnalysis, ReceiverMutability},
pod::PodAnalysis,
},
api::{AnalysisPhase, Api, SubclassName, TypeKind, TypedefKind},
api::{AnalysisPhase, Api, SubclassName, TypeKind, TypedefKind, Virtualness},
convert_error::ErrorContextType,
doc_attr::get_doc_attrs,
};
Expand All @@ -69,6 +69,7 @@ struct ImplBlockKey {
struct ImplBlockDetails {
item: ImplItem,
ty: ImplBlockKey,
virt: bool,
}

struct TraitImplBlockDetails {
Expand Down Expand Up @@ -167,16 +168,17 @@ impl<'a> RsCodeGenerator<'a> {
c.rs_codegen(all_apis)
}

fn rs_codegen(mut self, all_apis: ApiVec<FnPhase>) -> Vec<Item> {
fn rs_codegen(mut self, mut all_apis: ApiVec<FnPhase>) -> Vec<Item> {
// ... and now let's start to generate the output code.
// First off, when we generate structs we may need to add some methods
// if they're superclasses.
let methods_by_superclass = self.accumulate_superclass_methods(&all_apis);
let subclasses_with_a_single_trivial_constructor =
find_trivially_constructed_subclasses(&all_apis);
let non_pod_types = find_non_pod_types(&all_apis);

// Now let's generate the Rust code.
let (rs_codegen_results_and_namespaces, additional_cpp_needs): (Vec<_>, Vec<_>) = all_apis
let (mut rs_codegen_results_and_namespaces, additional_cpp_needs): (Vec<_>, Vec<_>) = all_apis
.into_iter()
.map(|api| {
let more_cpp_needed = api.needs_cpp_codegen();
Expand All @@ -190,6 +192,9 @@ impl<'a> RsCodeGenerator<'a> {
((name, gen), more_cpp_needed)
})
.unzip();

polymorphise(&mut rs_codegen_results_and_namespaces);

// First, the hierarchy of mods containing lots of 'use' statements
// which is the final API exposed as 'ffi'.
let mut use_statements =
Expand Down Expand Up @@ -220,7 +225,7 @@ impl<'a> RsCodeGenerator<'a> {
// Items for the [cxx::bridge] mod...
let mut bridge_items: Vec<Item> = bridge_items.into_iter().flatten().collect();
// Things to include in the "extern "C"" mod passed within the cxx::bridge
let mut extern_c_mod_items: Vec<ForeignItem> =
let mut extern_c_mod_items: Vec<_> =
extern_c_mod_items.into_iter().flatten().collect();
// The same for extern "Rust"
let mut extern_rust_mod_items = extern_rust_mod_items.into_iter().flatten().collect();
Expand Down Expand Up @@ -420,6 +425,7 @@ impl<'a> RsCodeGenerator<'a> {
}
}))
}
let mut unique_types = HashSet::new();
for (key, entries) in trait_impl_entries_by_trait_and_ty.into_iter() {
let unsafety = key.unsafety;
let ty = key.ty;
Expand All @@ -428,7 +434,17 @@ impl<'a> RsCodeGenerator<'a> {
#unsafety impl #trt for #ty {
#(#entries)*
}
}))
}));
unique_types.insert(ty.clone());
}
for ty in unique_types {
output_items.push(Item::Impl(parse_quote! {
impl AsRef< #ty > for #ty {
fn as_ref(self: & #ty) -> & #ty {
self
}
}
}));
}
for (child_name, child_ns_entries) in ns_entries.children() {
let new_ns = ns.push((*child_name).clone());
Expand Down Expand Up @@ -682,7 +698,7 @@ impl<'a> RsCodeGenerator<'a> {
}
},
];
let mut extern_c_mod_items = vec![
let mut extern_c_mod_items: Vec<ForeignItem> = vec![
self.generate_cxxbridge_type(&full_cpp, false, Vec::new()),
parse_quote! {
fn #relinquish_ownership_call(self: &#cpp_id);
Expand Down Expand Up @@ -812,9 +828,17 @@ impl<'a> RsCodeGenerator<'a> {
let ret = details.ret;
let unsafe_token = details.requires_unsafe.wrapper_token();
let global_def = quote! { #unsafe_token fn #api_name(#params) #ret };
let params = unqualify_params(minisynize_punctuated(params));
let mut params = unqualify_params(minisynize_punctuated(params));
let ret = unqualify_ret_type(ret.into());
let method_name = details.method_name;
for p in &mut params {
match p {
FnArg::Typed(ref mut pt) => {
conv_ref_args(pt, true)
},
_ => {},
}
}
let cxxbridge_decl: ForeignItemFn =
parse_quote! { #unsafe_token fn #api_name(#params) #ret; };
let args: Punctuated<Expr, Comma> =
Expand Down Expand Up @@ -1099,6 +1123,7 @@ impl<'a> RsCodeGenerator<'a> {
ty: parse_quote! { #self_ty },
lifetime: None,
},
virt: false,
})),
None,
None,
Expand Down
Loading
Loading