Supporting vtables for closures #871
Closed
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR adds support for vtable instantiation for closures.
The implementation involves two main steps:
Matching a closure implementation
Instantiating the corresponding vtable
Step 1 is implemented in
translate_body.rs, while Step 2 is implemented intranslate_trait_objects.rs.The modifications in each file are described below.
translate_rvalueSupports registering closure trait implementations. For example, in the test file
dyn-fn.rs, the closure|counter| { ... }is matched in thehax::ImplExprAtom::Builtincase and registered as aVTableInstance.add_method_to_vtable_defAdds additional checks for
FnOncewhen constructing the method field in theFnOncevtable, due to the incompatibility ofFnOnce::call_oncewith dyn-compatibility.get_vtable_instance_infoSupports retrieving the vtable struct reference and the corresponding trait declaration reference for closures, based on their kind (Fn, FnMut, or FnOnce).
add_supertraits_to_vtable_valueSupports filling vtable fields with built-in supertraits. For closures supertraits, they are translated as VTableInstance with
TraitImplSource::Closure(kind), generating a vtable according to the closurekind. For other built-in supertraits, they are translated as VTableInstance withTraitImplSource::Normal, whose trait reference itself is used as the impl reference (e.g.@2 := &core::marker::MetaSized::{vtable}).gen_vtable_instance_init_bodySupports generating the vtable body for closures. Closure implementations are treated as trait implementations with no associated items and a single specialized closure method (
callorcall_mut).call_onceis ignored due to the incompatibility mentioned above. Based on this design, the function retrieves(trait_pred, items)for closures and usesmk_fieldto add the specialized closure method.generate_closure_method_shim_refImplements the generation of the closure method shim reference used in the
mk_fieldingen_vtable_instance_init_body.