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

Native/FFI Support #4

Open
nikhilr612 opened this issue Jul 5, 2024 · 0 comments
Open

Native/FFI Support #4

nikhilr612 opened this issue Jul 5, 2024 · 0 comments

Comments

@nikhilr612
Copy link
Owner

Is your feature request related to a problem? Please describe.
Support for calling external functions from shared libraries is very valuable, as it allows for interoperability between the VM and arbitrary native code which is desirable not only for the sake of efficiency but also for functionality.

Describe the solution you'd like
Create a simple API exposing 'primitive' types like Int, Flt, Chr, along with an additional type NativeHandle (which is merely an opaque pointer managed by the native library) which can be accessed from a 'Context/Environment'-type structure by the underlying method, e.g.

/// An FFI function for sin(x)
#[no_mangle]
extern "C" fn sin(env: &mut CallContext) {
    let x = fr_env_get_positional_flt(env, 0);
    let r = f64::sin(x);
    fr_env_set_return_flt(env, r);
} // Suppose this function has been compiled into libtrig

The existing ExternDecl apparatus can be hijacked to include an additional flag that indicates if an ExternDecl is a native function.
The corresponding assembly syntax could simply use .nf, as in

.cpool 1
 f64 1.5707, $PI_2
.extern 1
# v------ This is the only change ..
  .nf libtrig:sin, @libtrig_sin
# .ef libtrig:sin, @libtrig_sin

# ...

.code
main:
   ldx @libtrig_sin, %0
   ldc $PI_2, %1
   stdcall %2, %2, %1
   print %1
   ret 

The VM should make use of this type of function, by invoking it with a suitable CallContext/CallEnvironment populated with parameters passed from stdcall on an FRef.

Describe alternatives you've considered
The native methods could alternatively be registered through the use of a hook method, which also supplies meta-information about the functions (parameter types, arity, etc.) alongside their pointers. The FFI interface then converts VM types based on this information, and invokes the function. The good thing about this approach is that for libraries which supply more or less the same function types like libmath, a large number of native functions can be implemented in a 'non-intrusive' way.

Additional context
Errors occurring in native context need to be reported to the environment so that they can propagate up the stack.

nikhilr612 added a commit that referenced this issue Jul 11, 2024
…rring complete implementation until #4 lands.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant