[foreign] Pulling the string on Scope

Jorn Vernee jbvernee at xs4all.nl
Wed Dec 19 15:08:23 UTC 2018


Hi,

I have been thinking for a while that there could be some improvements 
made to the Scope API. (And I'm currently in the process of debugging 
what seems to be a life-cycle problem)

* Scopes could optionally have names. If an exception is thrown because 
a Resource's scope is closed, and don't know where this scope/resource 
is coming from, you have to debug that. By allowing scopes to have 
optional names, we can add additional debugging information to a scope 
which can be displayed in the exception message; "Scope is not alive" 
vs. "Scope 'MyScope' is not alive".

* There should imho be a way to transfer resources between scopes. I 
suggest adding a `void transferTo(Scope scope)` method to Resource for 
this. Transferring resources between scopes could be useful for instance 
in the case where a Resource is returned from a native function and it's 
up to the caller to manage that resource. Currently the resource is 
leaked, which makes sense when the return value is not supposed to be 
managed by the caller, but for the former case it's nice to be able to 
transfer the resource into some other, non-leaked, scope. (From what I 
can tell the allocation strategy of NativeScope would have to be changed 
to allow for this).

* boxing/unboxing code should take a Scope as an argument. When 
returning values they can be put into this scope, or in the case of 
Windows a copy of a struct might be needed for the duration of the call. 
For upcalls the boxed arguments can also be added to this scope. Each 
call will have 2 scopes, one for the duration of the call and one for 
return values, which is 'leaked', and it's up to the caller to manage 
this scope and it's resources. Which of the two is passed to box/unbox 
depends on if we're doing an upcall or downcall. So in abstract you'd 
have this;

```
try(var callScope = Scope.newNativeScope()) {
     var returnScope = Scope.newNativeScope(); // leaked to caller

     unbox(callScope, ...);

     // do call

     box(returnScope, ...);
}
```

Where for upcalls box and unbox are switched.

What do you think about about Scope?

Thanks,
Jorn


More information about the panama-dev mailing list