Subject: bug#24102: Use guile variable objects as SRFI-111 boxes.

From: "Glenn Michaels" <[email-masked]>
Date: Thu, 18 Aug 2016 09:07:26 -0400

Sorry for the delayed response.

Mark H Weaver <[email-masked]> writes:
> > Moreover, SRFI-111 boxes and guile variable objects are clearly
> > semantically the same thing.

> Unfortunately, they are not quite the same thing.  Unlike SRFI-111
> boxes, Guile variables are a union type: they contain an arbitrary
> Scheme value, *or* they may be "unbound".  For such a simple data type,
> this added complication is semantically quite significant.
> As a result, some important properties of SRFI-111 boxes do not hold for
> your proposed implementation.  For example, in SRFI-111, (box? x)
> implies that (box-ref x) will not raise an exception

You're right. They aren't exactly the same, it would be more correct
to say that boxes are equivalent to bound variables. Thus box? should
be defined as:

(define (box? o) (and (variable? o) (variable-bound? o)))

That way, (box-ref o) is guaranteed to work whenever (box? o) holds.

I'm suggesting that in current versions of Guile, implementing
SRFI-111 boxes via variables is faster that the current implementation
using records. With the definition of box? as above, it would be
semantically correct.

If a future guile compiler can implement boxes more efficiently in a
different representation, there's nothing to stop you switching to
that representation when the time comes. Making this simple change now
doesn't prevent you from doing something different in future. I'm not
suggesting that you should necessarily *guarantee* that boxes will always 
be implemented using variables.

> this fact can be exploited by a compiler to produce better native code for
> 'box-ref' when the type of its argument is known to be a box.  In such cases,
> I guess 'box-ref' can be implemented as a single load instruction, whereas
> 'variable-ref' will require a conditional branch.

With respect to what you say about compiler optimizations: In order to
implement a given call to unbox with a single load instruction, the
compiler would have to prove that the argument is a box, i.e. that it
satisfies the box? predicate.

You could also implement calls to variable-ref with a single
load instruction in cases where the compiler can prove that the
argument is a bound variable, i.e. that it satisfies
(and (variable? o) (variable-bound? o)) -- precisely the definition of
box? above.

Therefore it seems to me that whether you can perform this
optimization or not in a given case depends not so much on whether
boxes and variables are distinct types, but on how much information the
compiler can infer statically about each variable (in the general sense)
reference at a given point the program.

However, this discussing is academic insomuch as AFAICT the
current guile compiler currently performs neither optimization.