1B::Concise(3pm) Perl Programmers Reference Guide B::Concise(3pm)
2
3
4
6 B::Concise - Walk Perl syntax tree, printing concise info about ops
7
9 perl -MO=Concise[,OPTIONS] foo.pl
10
11 use B::Concise qw(set_style add_callback);
12
14 This compiler backend prints the internal OPs of a Perl program's
15 syntax tree in one of several space-efficient text formats suitable for
16 debugging the inner workings of perl or other compiler backends. It can
17 print OPs in the order they appear in the OP tree, in the order they
18 will execute, or in a text approximation to their tree structure, and
19 the format of the information displayed is customizable. Its function
20 is similar to that of perl's -Dx debugging flag or the B::Terse module,
21 but it is more sophisticated and flexible.
22
24 Here's two outputs (or 'renderings'), using the -exec and -basic (i.e.
25 default) formatting conventions on the same code snippet.
26
27 % perl -MO=Concise,-exec -e '$a = $b + 42'
28 1 <0> enter
29 2 <;> nextstate(main 1 -e:1) v
30 3 <#> gvsv[*b] s
31 4 <$> const[IV 42] s
32 * 5 <2> add[t3] sK/2
33 6 <#> gvsv[*a] s
34 7 <2> sassign vKS/2
35 8 <@> leave[1 ref] vKP/REFC
36
37 In this -exec rendering, each opcode is executed in the order shown.
38 The add opcode, marked with '*', is discussed in more detail.
39
40 The 1st column is the op's sequence number, starting at 1, and is
41 displayed in base 36 by default. Here they're purely linear; the
42 sequences are very helpful when looking at code with loops and
43 branches.
44
45 The symbol between angle brackets indicates the op's type, for example;
46 <2> is a BINOP, <@> a LISTOP, and <#> is a PADOP, which is used in
47 threaded perls. (see "OP class abbreviations").
48
49 The opname, as in 'add[t1]', may be followed by op-specific information
50 in parentheses or brackets (ex '[t1]').
51
52 The op-flags (ex 'sK/2') are described in ("OP flags abbreviations").
53
54 % perl -MO=Concise -e '$a = $b + 42'
55 8 <@> leave[1 ref] vKP/REFC ->(end)
56 1 <0> enter ->2
57 2 <;> nextstate(main 1 -e:1) v ->3
58 7 <2> sassign vKS/2 ->8
59 * 5 <2> add[t1] sK/2 ->6
60 - <1> ex-rv2sv sK/1 ->4
61 3 <$> gvsv(*b) s ->4
62 4 <$> const(IV 42) s ->5
63 - <1> ex-rv2sv sKRM*/1 ->7
64 6 <$> gvsv(*a) s ->7
65
66 The default rendering is top-down, so they're not in execution order.
67 This form reflects the way the stack is used to parse and evaluate
68 expressions; the add operates on the two terms below it in the tree.
69
70 Nullops appear as "ex-opname", where opname is an op that has been
71 optimized away by perl. They're displayed with a sequence-number of
72 '-', because they are not executed (they don't appear in previous
73 example), they're printed here because they reflect the parse.
74
75 The arrow points to the sequence number of the next op; they're not
76 displayed in -exec mode, for obvious reasons.
77
78 Note that because this rendering was done on a non-threaded perl, the
79 PADOPs in the previous examples are now SVOPs, and some (but not all)
80 of the square brackets have been replaced by round ones. This is a
81 subtle feature to provide some visual distinction between renderings on
82 threaded and un-threaded perls.
83
85 Arguments that don't start with a hyphen are taken to be the names of
86 subroutines to render; if no such functions are specified, the main
87 body of the program (outside any subroutines, and not including use'd
88 or require'd files) is rendered. Passing "BEGIN", "UNITCHECK",
89 "CHECK", "INIT", or "END" will cause all of the corresponding special
90 blocks to be printed. Arguments must follow options.
91
92 Options affect how things are rendered (ie printed). They're presented
93 here by their visual effect, 1st being strongest. They're grouped
94 according to how they interrelate; within each group the options are
95 mutually exclusive (unless otherwise stated).
96
97 Options for Opcode Ordering
98 These options control the 'vertical display' of opcodes. The display
99 'order' is also called 'mode' elsewhere in this document.
100
101 -basic
102 Print OPs in the order they appear in the OP tree (a preorder
103 traversal, starting at the root). The indentation of each OP shows
104 its level in the tree, and the '->' at the end of the line
105 indicates the next opcode in execution order. This mode is the
106 default, so the flag is included simply for completeness.
107
108 -exec
109 Print OPs in the order they would normally execute (for the
110 majority of constructs this is a postorder traversal of the tree,
111 ending at the root). In most cases the OP that usually follows a
112 given OP will appear directly below it; alternate paths are shown
113 by indentation. In cases like loops when control jumps out of a
114 linear path, a 'goto' line is generated.
115
116 -tree
117 Print OPs in a text approximation of a tree, with the root of the
118 tree at the left and 'left-to-right' order of children transformed
119 into 'top-to-bottom'. Because this mode grows both to the right and
120 down, it isn't suitable for large programs (unless you have a very
121 wide terminal).
122
123 Options for Line-Style
124 These options select the line-style (or just style) used to render each
125 opcode, and dictates what info is actually printed into each line.
126
127 -concise
128 Use the author's favorite set of formatting conventions. This is
129 the default, of course.
130
131 -terse
132 Use formatting conventions that emulate the output of B::Terse. The
133 basic mode is almost indistinguishable from the real B::Terse, and
134 the exec mode looks very similar, but is in a more logical order
135 and lacks curly brackets. B::Terse doesn't have a tree mode, so the
136 tree mode is only vaguely reminiscent of B::Terse.
137
138 -linenoise
139 Use formatting conventions in which the name of each OP, rather
140 than being written out in full, is represented by a one- or two-
141 character abbreviation. This is mainly a joke.
142
143 -debug
144 Use formatting conventions reminiscent of B::Debug; these aren't
145 very concise at all.
146
147 -env
148 Use formatting conventions read from the environment variables
149 "B_CONCISE_FORMAT", "B_CONCISE_GOTO_FORMAT", and
150 "B_CONCISE_TREE_FORMAT".
151
152 Options for tree-specific formatting
153 -compact
154 Use a tree format in which the minimum amount of space is used for
155 the lines connecting nodes (one character in most cases). This
156 squeezes out a few precious columns of screen real estate.
157
158 -loose
159 Use a tree format that uses longer edges to separate OP nodes. This
160 format tends to look better than the compact one, especially in
161 ASCII, and is the default.
162
163 -vt Use tree connecting characters drawn from the VT100 line-drawing
164 set. This looks better if your terminal supports it.
165
166 -ascii
167 Draw the tree with standard ASCII characters like "+" and "|".
168 These don't look as clean as the VT100 characters, but they'll work
169 with almost any terminal (or the horizontal scrolling mode of
170 less(1)) and are suitable for text documentation or email. This is
171 the default.
172
173 These are pairwise exclusive, i.e. compact or loose, vt or ascii.
174
175 Options controlling sequence numbering
176 -basen
177 Print OP sequence numbers in base n. If n is greater than 10, the
178 digit for 11 will be 'a', and so on. If n is greater than 36, the
179 digit for 37 will be 'A', and so on until 62. Values greater than
180 62 are not currently supported. The default is 36.
181
182 -bigendian
183 Print sequence numbers with the most significant digit first. This
184 is the usual convention for Arabic numerals, and the default.
185
186 -littleendian
187 Print seqence numbers with the least significant digit first. This
188 is obviously mutually exclusive with bigendian.
189
190 Other options
191 -src
192 With this option, the rendering of each statement (starting with
193 the nextstate OP) will be preceded by the 1st line of source code
194 that generates it. For example:
195
196 1 <0> enter
197 # 1: my $i;
198 2 <;> nextstate(main 1 junk.pl:1) v:{
199 3 <0> padsv[$i:1,10] vM/LVINTRO
200 # 3: for $i (0..9) {
201 4 <;> nextstate(main 3 junk.pl:3) v:{
202 5 <0> pushmark s
203 6 <$> const[IV 0] s
204 7 <$> const[IV 9] s
205 8 <{> enteriter(next->j last->m redo->9)[$i:1,10] lKS
206 k <0> iter s
207 l <|> and(other->9) vK/1
208 # 4: print "line ";
209 9 <;> nextstate(main 2 junk.pl:4) v
210 a <0> pushmark s
211 b <$> const[PV "line "] s
212 c <@> print vK
213 # 5: print "$i\n";
214 ...
215
216 -stash="somepackage"
217 With this, "somepackage" will be required, then the stash is
218 inspected, and each function is rendered.
219
220 The following options are pairwise exclusive.
221
222 -main
223 Include the main program in the output, even if subroutines were
224 also specified. This rendering is normally suppressed when a
225 subroutine name or reference is given.
226
227 -nomain
228 This restores the default behavior after you've changed it with
229 '-main' (it's not normally needed). If no subroutine name/ref is
230 given, main is rendered, regardless of this flag.
231
232 -nobanner
233 Renderings usually include a banner line identifying the function
234 name or stringified subref. This suppresses the printing of the
235 banner.
236
237 TBC: Remove the stringified coderef; while it provides a 'cookie'
238 for each function rendered, the cookies used should be 1,2,3.. not
239 a random hex-address. It also complicates string comparison of two
240 different trees.
241
242 -banner
243 restores default banner behavior.
244
245 -banneris => subref
246 TBC: a hookpoint (and an option to set it) for a user-supplied
247 function to produce a banner appropriate for users needs. It's not
248 ideal, because the rendering-state variables, which are a natural
249 candidate for use in concise.t, are unavailable to the user.
250
251 Option Stickiness
252 If you invoke Concise more than once in a program, you should know that
253 the options are 'sticky'. This means that the options you provide in
254 the first call will be remembered for the 2nd call, unless you re-
255 specify or change them.
256
258 The concise style uses symbols to convey maximum info with minimal
259 clutter (like hex addresses). With just a little practice, you can
260 start to see the flowers, not just the branches, in the trees.
261
262 OP class abbreviations
263 These symbols appear before the op-name, and indicate the B:: namespace
264 that represents the ops in your Perl code.
265
266 0 OP (aka BASEOP) An OP with no children
267 1 UNOP An OP with one child
268 2 BINOP An OP with two children
269 | LOGOP A control branch OP
270 @ LISTOP An OP that could have lots of children
271 / PMOP An OP with a regular expression
272 $ SVOP An OP with an SV
273 " PVOP An OP with a string
274 { LOOP An OP that holds pointers for a loop
275 ; COP An OP that marks the start of a statement
276 # PADOP An OP with a GV on the pad
277
278 OP flags abbreviations
279 OP flags are either public or private. The public flags alter the
280 behavior of each opcode in consistent ways, and are represented by 0 or
281 more single characters.
282
283 v OPf_WANT_VOID Want nothing (void context)
284 s OPf_WANT_SCALAR Want single value (scalar context)
285 l OPf_WANT_LIST Want list of any length (list context)
286 Want is unknown
287 K OPf_KIDS There is a firstborn child.
288 P OPf_PARENS This operator was parenthesized.
289 (Or block needs explicit scope entry.)
290 R OPf_REF Certified reference.
291 (Return container, not containee).
292 M OPf_MOD Will modify (lvalue).
293 S OPf_STACKED Some arg is arriving on the stack.
294 * OPf_SPECIAL Do something weird for this op (see op.h)
295
296 Private flags, if any are set for an opcode, are displayed after a '/'
297
298 8 <@> leave[1 ref] vKP/REFC ->(end)
299 7 <2> sassign vKS/2 ->8
300
301 They're opcode specific, and occur less often than the public ones, so
302 they're represented by short mnemonics instead of single-chars; see
303 op.h for gory details, or try this quick 2-liner:
304
305 $> perl -MB::Concise -de 1
306 DB<1> |x \%B::Concise::priv
307
309 For each line-style ('concise', 'terse', 'linenoise', etc.) there are 3
310 format-specs which control how OPs are rendered.
311
312 The first is the 'default' format, which is used in both basic and exec
313 modes to print all opcodes. The 2nd, goto-format, is used in exec mode
314 when branches are encountered. They're not real opcodes, and are
315 inserted to look like a closing curly brace. The tree-format is tree
316 specific.
317
318 When a line is rendered, the correct format-spec is copied and scanned
319 for the following items; data is substituted in, and other
320 manipulations like basic indenting are done, for each opcode rendered.
321
322 There are 3 kinds of items that may be populated; special patterns,
323 #vars, and literal text, which is copied verbatim. (Yes, it's a set of
324 s///g steps.)
325
326 Special Patterns
327 These items are the primitives used to perform indenting, and to select
328 text from amongst alternatives.
329
330 (x(exec_text;basic_text)x)
331 Generates exec_text in exec mode, or basic_text in basic mode.
332
333 (*(text)*)
334 Generates one copy of text for each indentation level.
335
336 (*(text1;text2)*)
337 Generates one fewer copies of text1 than the indentation level,
338 followed by one copy of text2 if the indentation level is more than
339 0.
340
341 (?(text1#varText2)?)
342 If the value of var is true (not empty or zero), generates the
343 value of var surrounded by text1 and Text2, otherwise nothing.
344
345 ~ Any number of tildes and surrounding whitespace will be collapsed
346 to a single space.
347
348 # Variables
349 These #vars represent opcode properties that you may want as part of
350 your rendering. The '#' is intended as a private sigil; a #var's value
351 is interpolated into the style-line, much like "read $this".
352
353 These vars take 3 forms:
354
355 #var
356 A property named 'var' is assumed to exist for the opcodes, and is
357 interpolated into the rendering.
358
359 #varN
360 Generates the value of var, left justified to fill N spaces. Note
361 that this means while you can have properties 'foo' and 'foo2', you
362 cannot render 'foo2', but you could with 'foo2a'. You would be
363 wise not to rely on this behavior going forward ;-)
364
365 #Var
366 This ucfirst form of #var generates a tag-value form of itself for
367 display; it converts '#Var' into a 'Var => #var' style, which is
368 then handled as described above. (Imp-note: #Vars cannot be used
369 for conditional-fills, because the => #var transform is done after
370 the check for #Var's value).
371
372 The following variables are 'defined' by B::Concise; when they are used
373 in a style, their respective values are plugged into the rendering of
374 each opcode.
375
376 Only some of these are used by the standard styles, the others are
377 provided for you to delve into optree mechanics, should you wish to add
378 a new style (see "add_style" below) that uses them. You can also add
379 new ones using "add_callback".
380
381 #addr
382 The address of the OP, in hexadecimal.
383
384 #arg
385 The OP-specific information of the OP (such as the SV for an SVOP,
386 the non-local exit pointers for a LOOP, etc.) enclosed in
387 parentheses.
388
389 #class
390 The B-determined class of the OP, in all caps.
391
392 #classsym
393 A single symbol abbreviating the class of the OP.
394
395 #coplabel
396 The label of the statement or block the OP is the start of, if any.
397
398 #exname
399 The name of the OP, or 'ex-foo' if the OP is a null that used to be
400 a foo.
401
402 #extarg
403 The target of the OP, or nothing for a nulled OP.
404
405 #firstaddr
406 The address of the OP's first child, in hexadecimal.
407
408 #flags
409 The OP's flags, abbreviated as a series of symbols.
410
411 #flagval
412 The numeric value of the OP's flags.
413
414 #hints
415 The COP's hint flags, rendered with abbreviated names if possible.
416 An empty string if this is not a COP. Here are the symbols used:
417
418 $ strict refs
419 & strict subs
420 * strict vars
421 i integers
422 l locale
423 b bytes
424 [ arybase
425 { block scope
426 % localise %^H
427 < open in
428 > open out
429 I overload int
430 F overload float
431 B overload binary
432 S overload string
433 R overload re
434 T taint
435 E eval
436 X filetest access
437 U utf-8
438
439 #hintsval
440 The numeric value of the COP's hint flags, or an empty string if
441 this is not a COP.
442
443 #hyphseq
444 The sequence number of the OP, or a hyphen if it doesn't have one.
445
446 #label
447 'NEXT', 'LAST', or 'REDO' if the OP is a target of one of those in
448 exec mode, or empty otherwise.
449
450 #lastaddr
451 The address of the OP's last child, in hexadecimal.
452
453 #name
454 The OP's name.
455
456 #NAME
457 The OP's name, in all caps.
458
459 #next
460 The sequence number of the OP's next OP.
461
462 #nextaddr
463 The address of the OP's next OP, in hexadecimal.
464
465 #noise
466 A one- or two-character abbreviation for the OP's name.
467
468 #private
469 The OP's private flags, rendered with abbreviated names if
470 possible.
471
472 #privval
473 The numeric value of the OP's private flags.
474
475 #seq
476 The sequence number of the OP. Note that this is a sequence number
477 generated by B::Concise.
478
479 #seqnum
480 5.8.x and earlier only. 5.9 and later do not provide this.
481
482 The real sequence number of the OP, as a regular number and not
483 adjusted to be relative to the start of the real program. (This
484 will generally be a fairly large number because all of B::Concise
485 is compiled before your program is).
486
487 #opt
488 Whether or not the op has been optimised by the peephole optimiser.
489
490 Only available in 5.9 and later.
491
492 #sibaddr
493 The address of the OP's next youngest sibling, in hexadecimal.
494
495 #svaddr
496 The address of the OP's SV, if it has an SV, in hexadecimal.
497
498 #svclass
499 The class of the OP's SV, if it has one, in all caps (e.g., 'IV').
500
501 #svval
502 The value of the OP's SV, if it has one, in a short human-readable
503 format.
504
505 #targ
506 The numeric value of the OP's targ.
507
508 #targarg
509 The name of the variable the OP's targ refers to, if any, otherwise
510 the letter t followed by the OP's targ in decimal.
511
512 #targarglife
513 Same as #targarg, but followed by the COP sequence numbers that
514 delimit the variable's lifetime (or 'end' for a variable in an open
515 scope) for a variable.
516
517 #typenum
518 The numeric value of the OP's type, in decimal.
519
521 perl -MO=Concise,bar foo.pl
522 Renders only bar() from foo.pl. To see main, drop the ',bar'. To
523 see both, add ',-main'
524
525 perl -MDigest::MD5=md5 -MO=Concise,md5 -e1
526 Identifies md5 as an XS function. The export is needed so that BC
527 can find it in main.
528
529 perl -MPOSIX -MO=Concise,_POSIX_ARG_MAX -e1
530 Identifies _POSIX_ARG_MAX as a constant sub, optimized to an IV.
531 Although POSIX isn't entirely consistent across platforms, this is
532 likely to be present in virtually all of them.
533
534 perl -MPOSIX -MO=Concise,a -e 'print _POSIX_SAVED_IDS'
535 This renders a print statement, which includes a call to the
536 function. It's identical to rendering a file with a use call and
537 that single statement, except for the filename which appears in the
538 nextstate ops.
539
540 perl -MPOSIX -MO=Concise,a -e 'sub a{_POSIX_SAVED_IDS}'
541 This is very similar to previous, only the first two ops differ.
542 This subroutine rendering is more representative, insofar as a
543 single main program will have many subs.
544
545 perl -MB::Concise -e 'B::Concise::compile("-exec","-src",
546 \%B::Concise::)->()'
547 This renders all functions in the B::Concise package with the
548 source lines. It eschews the O framework so that the stashref can
549 be passed directly to B::Concise::compile(). See -stash option for
550 a more convenient way to render a package.
551
553 The common (and original) usage of B::Concise was for command-line
554 renderings of simple code, as given in EXAMPLE. But you can also use
555 B::Concise from your code, and call compile() directly, and repeatedly.
556 By doing so, you can avoid the compile-time only operation of O.pm, and
557 even use the debugger to step through B::Concise::compile() itself.
558
559 Once you're doing this, you may alter Concise output by adding new
560 rendering styles, and by optionally adding callback routines which
561 populate new variables, if such were referenced from those (just added)
562 styles.
563
564 Example: Altering Concise Renderings
565 use B::Concise qw(set_style add_callback);
566 add_style($yourStyleName => $defaultfmt, $gotofmt, $treefmt);
567 add_callback
568 ( sub {
569 my ($h, $op, $format, $level, $stylename) = @_;
570 $h->{variable} = some_func($op);
571 });
572 $walker = B::Concise::compile(@options,@subnames,@subrefs);
573 $walker->();
574
575 set_style()
576 set_style accepts 3 arguments, and updates the three format-specs
577 comprising a line-style (basic-exec, goto, tree). It has one minor
578 drawback though; it doesn't register the style under a new name. This
579 can become an issue if you render more than once and switch styles.
580 Thus you may prefer to use add_style() and/or set_style_standard()
581 instead.
582
583 set_style_standard($name)
584 This restores one of the standard line-styles: "terse", "concise",
585 "linenoise", "debug", "env", into effect. It also accepts style names
586 previously defined with add_style().
587
588 add_style()
589 This subroutine accepts a new style name and three style arguments as
590 above, and creates, registers, and selects the newly named style. It
591 is an error to re-add a style; call set_style_standard() to switch
592 between several styles.
593
594 add_callback()
595 If your newly minted styles refer to any new #variables, you'll need to
596 define a callback subroutine that will populate (or modify) those
597 variables. They are then available for use in the style you've chosen.
598
599 The callbacks are called for each opcode visited by Concise, in the
600 same order as they are added. Each subroutine is passed five
601 parameters.
602
603 1. A hashref, containing the variable names and values which are
604 populated into the report-line for the op
605 2. the op, as a B<B::OP> object
606 3. a reference to the format string
607 4. the formatting (indent) level
608 5. the selected stylename
609
610 To define your own variables, simply add them to the hash, or change
611 existing values if you need to. The level and format are passed in as
612 references to scalars, but it is unlikely that they will need to be
613 changed or even used.
614
615 Running B::Concise::compile()
616 compile accepts options as described above in "OPTIONS", and arguments,
617 which are either coderefs, or subroutine names.
618
619 It constructs and returns a $treewalker coderef, which when invoked,
620 traverses, or walks, and renders the optrees of the given arguments to
621 STDOUT. You can reuse this, and can change the rendering style used
622 each time; thereafter the coderef renders in the new style.
623
624 walk_output lets you change the print destination from STDOUT to
625 another open filehandle, or into a string passed as a ref (unless
626 you've built perl with -Uuseperlio).
627
628 my $walker = B::Concise::compile('-terse','aFuncName', \&aSubRef); # 1
629 walk_output(\my $buf);
630 $walker->(); # 1 renders -terse
631 set_style_standard('concise'); # 2
632 $walker->(); # 2 renders -concise
633 $walker->(@new); # 3 renders whatever
634 print "3 different renderings: terse, concise, and @new: $buf\n";
635
636 When $walker is called, it traverses the subroutines supplied when it
637 was created, and renders them using the current style. You can change
638 the style afterwards in several different ways:
639
640 1. call C<compile>, altering style or mode/order
641 2. call C<set_style_standard>
642 3. call $walker, passing @new options
643
644 Passing new options to the $walker is the easiest way to change amongst
645 any pre-defined styles (the ones you add are automatically recognized
646 as options), and is the only way to alter rendering order without
647 calling compile again. Note however that rendering state is still
648 shared amongst multiple $walker objects, so they must still be used in
649 a coordinated manner.
650
651 B::Concise::reset_sequence()
652 This function (not exported) lets you reset the sequence numbers (note
653 that they're numbered arbitrarily, their goal being to be human
654 readable). Its purpose is mostly to support testing, i.e. to compare
655 the concise output from two identical anonymous subroutines (but
656 different instances). Without the reset, B::Concise, seeing that
657 they're separate optrees, generates different sequence numbers in the
658 output.
659
660 Errors
661 Errors in rendering (non-existent function-name, non-existent coderef)
662 are written to the STDOUT, or wherever you've set it via walk_output().
663
664 Errors using the various *style* calls, and bad args to walk_output(),
665 result in die(). Use an eval if you wish to catch these errors and
666 continue processing.
667
669 Stephen McCamant, <smcc@CSUA.Berkeley.EDU>.
670
671
672
673perl v5.10.1 2009-02-12 B::Concise(3pm)