1B::Utils(3)           User Contributed Perl Documentation          B::Utils(3)
2
3
4

NAME

6       B::Utils - Helper functions for op tree manipulation
7

VERSION

9       0.11
10

INSTALLATION

12       To install this module, run the following commands:
13
14           perl Makefile.PL
15           make
16           make test
17           make install
18

SYNOPSIS

20         use B::Utils;
21

OP METHODS

23       "$op->oldname"
24           Returns the name of the op, even if it is currently optimized to
25           null.  This helps you understand the stucture of the op tree.
26
27       "$op->kids"
28           Returns an array of all this op's non-null children, in order.
29
30       "$op->parent"
31           Returns the parent node in the op tree, if possible. Currently
32           "possible" means "if the tree has already been optimized"; that is,
33           if we're during a "CHECK" block. (and hence, if we have valid
34           "next" pointers.)
35
36           In the future, it may be possible to search for the parent before
37           we have the "next" pointers in place, but it'll take me a while to
38           figure out how to do that.
39
40       "$op->ancestors"
41           Returns all parents of this node, recursively. The list is ordered
42           from younger/closer parents to older/farther parents.
43
44       "$op->descendants"
45           Returns all children of this node, recursively. The list is
46           unordered.
47
48       "$op->siblings"
49           Returns all younger siblings of this node. The list is ordered from
50           younger/closer siblings to older/farther siblings.
51
52       "$op->previous"
53           Like " $op->next ", but not quite.
54
55       "$op->stringify"
56           Returns a nice stringification of an opcode.
57
58       "$op->as_opgrep_pattern(%options)"
59           From the op tree it is called on, "as_opgrep_pattern()" generates a
60           data structure suitable for use as a condition pattern for the
61           "opgrep()" function described below in detail.  Beware: When using
62           such generated patterns, there may be false positives: The pattern
63           will most likely not match only the op tree it was generated from
64           since by default, not all properties of the op are reproduced.
65
66           You can control which properties of the op to include in the
67           pattern by passing named arguments. The default behaviour is as if
68           you passed in the following options:
69
70             my $pattern = $op->as_opgrep_pattern(
71               attributes          => [qw(name flags)],
72               max_recursion_depth => undef,
73             );
74
75           So obviously, you can set "max_recursion_depth" to a number to
76           limit the maximum depth of recursion into the op tree. Setting it
77           to 0 will limit the dump to the current op.
78
79           "attributes" is a list of attributes to include in the produced
80           pattern. The attributes that can be checked against in this way are
81
82             name targ type seq flags private pmflags pmpermflags.
83

EXPORTABLE FUNCTIONS

85       "all_starts"
86       "all_roots"
87           Returns a hash of all of the starting ops or root ops of optrees,
88           keyed to subroutine name; the optree for main program is simply
89           keyed to "__MAIN__".
90
91           Note: Certain "dangerous" stashes are not scanned for subroutines:
92           the list of such stashes can be found in @B::Utils::bad_stashes.
93           Feel free to examine and/or modify this to suit your needs. The
94           intention is that a simple program which uses no modules other than
95           "B" and "B::Utils" would show no addition symbols.
96
97           This does not return the details of ops in anonymous subroutines
98           compiled at compile time. For instance, given
99
100               $a = sub { ... };
101
102           the subroutine will not appear in the hash. This is just as well,
103           since they're anonymous... If you want to get at them, use...
104
105       "anon_subs"
106           This returns an array of hash references. Each element has the keys
107           "start" and "root". These are the starting and root ops of all of
108           the anonymous subroutines in the program.
109
110       "recalc_sub_cache"
111           If PL_sub_generation has changed or you have some other reason to
112           want to force the re-examination of the optrees, everywhere, call
113           this function.
114
115       "walkoptree_simple($op, \&callback, [$data])"
116           The "B" module provides various functions to walk the op tree, but
117           they're all rather difficult to use, requiring you to inject
118           methods into the "B::OP" class. This is a very simple op tree
119           walker with more expected semantics.
120
121           All the "walk" functions set $B::Utils::file, $B::Utils::line, and
122           $B::Utils::sub to the appropriate values of file, line number, and
123           sub name in the program being examined.
124
125       "walkoptree_filtered($op, \&filter, \&callback, [$data])"
126           This is much the same as "walkoptree_simple", but will only call
127           the callback if the "filter" returns true. The "filter" is passed
128           the op in question as a parameter; the "opgrep" function is
129           fantastic for building your own filters.
130
131       "walkallops_simple(\&callback, [$data])"
132           This combines "walkoptree_simple" with "all_roots" and "anon_subs"
133           to examine every op in the program. $B::Utils::sub is set to the
134           subroutine name if you're in a subroutine, "__MAIN__" if you're in
135           the main program and "__ANON__" if you're in an anonymous
136           subroutine.
137
138       "walkallops_filtered(\&filter, \&callback, [$data])"
139           Same as above, but filtered.
140
141       "opgrep(\%conditions, @ops)"
142           Returns the ops which meet the given conditions. The conditions
143           should be specified like this:
144
145               @barewords = opgrep(
146                                   { name => "const", private => OPpCONST_BARE },
147                                   @ops
148                                  );
149
150           where the first argument to "opgrep()" is the condition to be
151           matched against the op structure. We'll henceforth refer to it as
152           an op-pattern.
153
154           You can specify alternation by giving an arrayref of values:
155
156               @svs = opgrep ( { name => ["padsv", "gvsv"] }, @ops)
157
158           And you can specify inversion by making the first element of the
159           arrayref a "!". (Hint: if you want to say "anything", say "not
160           nothing": "["!"]")
161
162           You may also specify the conditions to be matched in nearby ops as
163           nested patterns.
164
165               walkallops_filtered(
166                   sub { opgrep( {name => "exec",
167                                  next => {
168                                            name    => "nextstate",
169                                            sibling => { name => [qw(! exit warn die)] }
170                                          }
171                                 }, @_)},
172                   sub {
173                         carp("Statement unlikely to be reached");
174                         carp("\t(Maybe you meant system() when you said exec()?)\n");
175                   }
176               )
177
178           Get that?
179
180           Here are the things that can be tested in this way:
181
182                   name targ type seq flags private pmflags pmpermflags
183                   first other last sibling next pmreplroot pmreplstart pmnext
184
185           Additionally, you can use the "kids" keyword with an array
186           reference to match the result of a call to "$op->kids()". An
187           example use is given in the documentation for "op_or" below.
188
189           For debugging, you can have many properties of an op that is
190           currently being matched against a given condition dumped to STDERR
191           by specifying "dump =" 1> in the condition's hash reference.
192
193           If you match a complex condition against an op tree, you may want
194           to extract a specific piece of information from the tree if the
195           condition matches.  This normally entails manually walking the tree
196           a second time down to the op you wish to extract, investigate or
197           modify. Since this is tedious duplication of code and information,
198           you can specify a special property in the pattern of the op you
199           wish to extract to capture the sub-op of interest. Example:
200
201             my ($result) = opgrep(
202               { name => "exec",
203                 next => { name    => "nextstate",
204                           sibling => { name => [qw(! exit warn die)]
205                                        capture => "notreached",
206                                      },
207                         }
208               },
209               $root_op
210             );
211
212             if ($result) {
213               my $name = $result->{notreached}->name; # result is *not* the root op
214               carp("Statement unlikely to be reached (op name: $name)");
215               carp("\t(Maybe you meant system() when you said exec()?)\n");
216             }
217
218           While the above is a terribly contrived example, consider the win
219           for a deeply nested pattern or worse yet, a pattern with many
220           disjunctions.  If a "capture" property is found anywhere in the op
221           pattern, "opgrep()" returns an unblessed hash reference on success
222           instead of the tested op. You can tell them apart using
223           Scalar::Util's "blessed()". That hash reference contains all
224           captured ops plus the tested root up as the hash entry
225           "$result->{op}". Note that you cannot use this feature with
226           "walkoptree_filtered" since that function was specifically
227           documented to pass the tested op itself to the callback.
228
229           You cannot capture disjunctions, but that doesn't really make sense
230           anyway.
231
232       "opgrep( \@conditions, @ops )"
233           Same as above, except that you don't have to chain the conditions
234           yourself.  If you pass an array-ref, opgrep will chain the
235           conditions for you using "next".  The conditions can either be
236           strings (taken as op-names), or hash-refs, with the same testable
237           conditions as given above.
238
239       "op_or( @conditions )"
240           Unlike the chaining of conditions done by "opgrep" itself if there
241           are multiple conditions, this function creates a disjunction
242           ("$cond1 || $cond2 || ...") of the conditions and returns a
243           structure (hash reference) that can be passed to opgrep as a single
244           condition.
245
246           Example:
247
248             my $sub_structure = {
249               name => 'helem',
250               first => { name => 'rv2hv', },
251               'last' => { name => 'const', },
252             };
253
254             my @ops = opgrep( {
255                 name => 'leavesub',
256                 first => {
257                   name => 'lineseq',
258                   kids => [,
259                     { name => 'nextstate', },
260                     op_or(
261                       {
262                         name => 'return',
263                         first => { name => 'pushmark' },
264                         last => $sub_structure,
265                       },
266                       $sub_structure,
267                     ),
268                   ],
269                 },
270             }, $op_obj );
271
272           This example matches the code in a typical simplest-possible
273           accessor method (albeit not down to the last bit):
274
275             sub get_foo { $_[0]->{foo} }
276
277           But by adding an alternation we can also match optional op layers.
278           In this case, we optionally match a return statement, so the
279           following implementation is also recognized:
280
281             sub get_foo { return $_[0]->{foo} }
282
283           Essentially, this is syntactic sugar for the following structure
284           recognized by "opgrep()":
285
286             { disjunction => [@conditions] }
287
288       "carp(@args)"
289       "croak(@args)"
290           Warn and die, respectively, from the perspective of the position of
291           the op in the program. Sounds complicated, but it's exactly the
292           kind of error reporting you expect when you're grovelling through
293           an op tree.
294
295   EXPORT
296       None by default.
297
298   XS EXPORT
299       This modules uses ExtUtils::Depends to export some useful functions for
300       XS modules to use.  To use those, include in your Makefile.PL:
301
302         my $pkg = ExtUtils::Depends->new("Your::XSModule", "B::Utils");
303         WriteMakefile(
304           ... # your normal makefile flags
305           $pkg->get_makefile_vars,
306         );
307
308       Your XS module can now include BUtils.h and BUtils_op.h.  To see
309       document for the functions provided, use:
310
311         perldoc -m B::Utils::Install::BUtils.h
312         perldoc -m B::Utils::Install::BUtils_op.h
313

AUTHOR

315       Originally written by Simon Cozens, "simon@cpan.org" Maintained by
316       Joshua ben Jore, "jjore@cpan.org"
317
318       Contributions from Mattia Barbon, Jim Cromie, Steffen Mueller, and
319       Chia-liang Kao, Alexandr Ciornii.
320

LICENSE

322       This module is free software; you can redistribute it and/or modify it
323       under the same terms as Perl itself.
324

SEE ALSO

326       B, B::Generate.
327
328
329
330perl v5.12.0                      2010-01-12                       B::Utils(3)
Impressum