develooper Front page | perl.perl5.porters | Postings from September 2009

waiting for sub body

Thread Next
From:
Zefram
Date:
September 1, 2009 03:21
Subject:
waiting for sub body
Message ID:
20090901102113.GA28285@fysh.org
I've been playing with modifying op trees in compiled Perl subroutines, as
a way of augmenting the language.  The first result of this is Sub::Filter
<http://search.cpan.org/perldoc?Sub::Filter>.  In implementing this as
an attribute, I ran into a problem: attributes on a sub definition get
processed before the body is attached to the CV, whereas this attribute
needs to do its thing after.  A further complication is that if the
sub was predeclared then the attribute handler actually runs against a
different CV from the one that later gets the body.  I want to discuss
approaches to these problems.

Firstly, it would be nice to have a proper interface for this sort of
thing in 5.12.  A clean way to request that some code be run when a
subroutine acquires its body.

Until that's done, I need a workaround.  The
workaround that I've developed is in Sub::Mutate
<http://search.cpan.org/perldoc?Sub::Mutate> (the XS is at
<http://cpansearch.perl.org/src/ZEFRAM/Sub-Mutate-0.000/lib/Sub/Mutate.xs>).
It allows the attribute handler to attach a pending action to the
half-built CV, saving it in the pad (where it's safe until the pad
cleaning that occurs at a late stage of CV building).  The module hooks
the peephole optimiser, spots the attached actions, and runs them.
If the sub was predeclared then the half-built pad gets moved to the
final CV, so the pending actions move with it.  This works on 5.10.

On 5.8 the workaround mostly works, but has a problem with predeclaration.
When the pad, flags, and so on get moved to the final CV, PL_compcv isn't
updated.  As a result, I don't see any way for the peephole optimiser
to know the final CV that it's optimising the body for, so any attached
actions get lost.  This is inconvenient.

On 5.6, which I do still try to support, it's not possible to hook the
peephole optimiser, so the workaround fails altogether.  This is a bummer
for all the potential modules that would otherwise work fine on 5.6 and
just need to get round this attribute timing problem.

There are precious few slots in a CV that are subject to reference
counting or similar semantics, that could trigger high-level behavior at
a useful point.  It's quite a challenge to hook anything in CV creation.
I'd welcome suggestions from those people who know the core to an
unhealthy level of detail.

-zefram

Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About