[mercury-users] Abstraction barrier

David Overton dmo at cs.mu.OZ.AU
Tue May 13 15:05:53 AEST 2003


On Tue, May 13, 2003 at 03:18:52PM +1000, Michael Day wrote:
> 
> I wish to call a predicate that returns a value and pass in some data for
> that predicate to access. However, I do not wish the predicate to return
> any of the data that I passed in, as it will unexpectedly go out of scope
> leaving dangling pointers to randomness.
> 
> :- pred foo(magic_data, T, T).
> :- mode foo(in, in, out) is det.
> 
> In the example above, the return T must not contain any references to
> magic_data, or bad things will happen later. But how to enforce that?

One thing you might be able to do is give the `magic_data' argument a
mode of `ui'.  This ensures that that argument will be a unique
reference to the data after foo/3 exits.

Unfortunately, there are some limitations to the current mode system
that mean that this may not always work.  In particular, if magic_data
is a type implemented in Mercury and foo/3 needs to deconstruct it then
the mode checker will not be able to prove that it still has a unique
reference to all the data it contains at the end of the call.  However,
if magic_data is a foreign type with a set of accessor predicates
implemented as foreign_procs then you just need to give them a mode with
`ui' argument (and ensure that their implementations match that mode).

> 
> :- pred foo(magic_data, magic_token, magic_token, T, T).
> :- mode foo(in, di, uo, in, out) is det.
> 
> Perhaps this way, and only provide accessor functions for magic_data that
> require a magic_token to operate, such that even if the function returns
> magic_data nothing can be done with it later?
> 
> For those who care, the trickiest part of using the Win32 API from Mercury
> is managing the expectations of when pointers go out of scope. It's very
> easy to keep references to strings and other data provided by the
> operating system that go out of scope unexpectedly, leading to trouble.


If a string can go out of scope unexpectedly then you probably should
make a copy of it on the Mercury heap.


David
-- 
David Overton                  Uni of Melbourne     +61 3 8344 1354
dmo at cs.mu.oz.au                Monash Uni (Clayton) +61 3 9905 5779
http://www.cs.mu.oz.au/~dmo    Mobile Phone         +61 4 0337 4393
--------------------------------------------------------------------------
mercury-users mailing list
post:  mercury-users at cs.mu.oz.au
administrative address: owner-mercury-users at cs.mu.oz.au
unsubscribe: Address: mercury-users-request at cs.mu.oz.au Message: unsubscribe
subscribe:   Address: mercury-users-request at cs.mu.oz.au Message: subscribe
--------------------------------------------------------------------------



More information about the users mailing list