1B::Concise(3pm)        Perl Programmers Reference Guide        B::Concise(3pm)
2
3
4

NAME

6       B::Concise - Walk Perl syntax tree, printing concise info about ops
7

SYNOPSIS

9           perl -MO=Concise[,OPTIONS] foo.pl
10
11           use B::Concise qw(set_style add_callback);
12

DESCRIPTION

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

EXAMPLE

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

OPTIONS

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 sequence numbers with the least significant digit first.
188           This 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

ABBREVIATIONS

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

FORMATTING SPECIFICATIONS

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              x$ explicit use/no strict refs
422              x& explicit use/no strict subs
423              x* explicit use/no strict vars
424               i integers
425               l locale
426               b bytes
427               { block scope
428               % localise %^H
429               < open in
430               > open out
431               I overload int
432               F overload float
433               B overload binary
434               S overload string
435               R overload re
436               T taint
437               E eval
438               X filetest access
439               U utf-8
440
441       #hintsval
442           The numeric value of the COP's hint flags, or an empty string if
443           this is not a COP.
444
445       #hyphseq
446           The sequence number of the OP, or a hyphen if it doesn't have one.
447
448       #label
449           'NEXT', 'LAST', or 'REDO' if the OP is a target of one of those in
450           exec mode, or empty otherwise.
451
452       #lastaddr
453           The address of the OP's last child, in hexadecimal.
454
455       #name
456           The OP's name.
457
458       #NAME
459           The OP's name, in all caps.
460
461       #next
462           The sequence number of the OP's next OP.
463
464       #nextaddr
465           The address of the OP's next OP, in hexadecimal.
466
467       #noise
468           A one- or two-character abbreviation for the OP's name.
469
470       #private
471           The OP's private flags, rendered with abbreviated names if
472           possible.
473
474       #privval
475           The numeric value of the OP's private flags.
476
477       #seq
478           The sequence number of the OP. Note that this is a sequence number
479           generated by B::Concise.
480
481       #seqnum
482           5.8.x and earlier only. 5.9 and later do not provide this.
483
484           The real sequence number of the OP, as a regular number and not
485           adjusted to be relative to the start of the real program. (This
486           will generally be a fairly large number because all of B::Concise
487           is compiled before your program is).
488
489       #opt
490           Whether or not the op has been optimised by the peephole optimiser.
491
492           Only available in 5.9 and later.
493
494       #sibaddr
495           The address of the OP's next youngest sibling, in hexadecimal.
496
497       #svaddr
498           The address of the OP's SV, if it has an SV, in hexadecimal.
499
500       #svclass
501           The class of the OP's SV, if it has one, in all caps (e.g., 'IV').
502
503       #svval
504           The value of the OP's SV, if it has one, in a short human-readable
505           format.
506
507       #targ
508           The numeric value of the OP's targ.
509
510       #targarg
511           The name of the variable the OP's targ refers to, if any, otherwise
512           the letter t followed by the OP's targ in decimal.
513
514       #targarglife
515           Same as #targarg, but followed by the COP sequence numbers that
516           delimit the variable's lifetime (or 'end' for a variable in an open
517           scope) for a variable.
518
519       #typenum
520           The numeric value of the OP's type, in decimal.
521

One-Liner Command tips

523       perl -MO=Concise,bar foo.pl
524           Renders only bar() from foo.pl.  To see main, drop the ',bar'.  To
525           see both, add ',-main'
526
527       perl -MDigest::MD5=md5 -MO=Concise,md5 -e1
528           Identifies md5 as an XS function.  The export is needed so that BC
529           can find it in main.
530
531       perl -MPOSIX -MO=Concise,_POSIX_ARG_MAX -e1
532           Identifies _POSIX_ARG_MAX as a constant sub, optimized to an IV.
533           Although POSIX isn't entirely consistent across platforms, this is
534           likely to be present in virtually all of them.
535
536       perl -MPOSIX -MO=Concise,a -e 'print _POSIX_SAVED_IDS'
537           This renders a print statement, which includes a call to the
538           function.  It's identical to rendering a file with a use call and
539           that single statement, except for the filename which appears in the
540           nextstate ops.
541
542       perl -MPOSIX -MO=Concise,a -e 'sub a{_POSIX_SAVED_IDS}'
543           This is very similar to previous, only the first two ops differ.
544           This subroutine rendering is more representative, insofar as a
545           single main program will have many subs.
546
547       perl -MB::Concise -e 'B::Concise::compile("-exec","-src",
548       \%B::Concise::)->()'
549           This renders all functions in the B::Concise package with the
550           source lines.  It eschews the O framework so that the stashref can
551           be passed directly to B::Concise::compile().  See -stash option for
552           a more convenient way to render a package.
553

Using B::Concise outside of the O framework

555       The common (and original) usage of B::Concise was for command-line
556       renderings of simple code, as given in EXAMPLE.  But you can also use
557       B::Concise from your code, and call compile() directly, and repeatedly.
558       By doing so, you can avoid the compile-time only operation of O.pm, and
559       even use the debugger to step through B::Concise::compile() itself.
560
561       Once you're doing this, you may alter Concise output by adding new
562       rendering styles, and by optionally adding callback routines which
563       populate new variables, if such were referenced from those (just added)
564       styles.
565
566   Example: Altering Concise Renderings
567           use B::Concise qw(set_style add_callback);
568           add_style($yourStyleName => $defaultfmt, $gotofmt, $treefmt);
569           add_callback
570             ( sub {
571                   my ($h, $op, $format, $level, $stylename) = @_;
572                   $h->{variable} = some_func($op);
573               });
574           $walker = B::Concise::compile(@options,@subnames,@subrefs);
575           $walker->();
576
577   set_style()
578       set_style accepts 3 arguments, and updates the three format-specs
579       comprising a line-style (basic-exec, goto, tree).  It has one minor
580       drawback though; it doesn't register the style under a new name.  This
581       can become an issue if you render more than once and switch styles.
582       Thus you may prefer to use add_style() and/or set_style_standard()
583       instead.
584
585   set_style_standard($name)
586       This restores one of the standard line-styles: "terse", "concise",
587       "linenoise", "debug", "env", into effect.  It also accepts style names
588       previously defined with add_style().
589
590   add_style ()
591       This subroutine accepts a new style name and three style arguments as
592       above, and creates, registers, and selects the newly named style.  It
593       is an error to re-add a style; call set_style_standard() to switch
594       between several styles.
595
596   add_callback ()
597       If your newly minted styles refer to any new #variables, you'll need to
598       define a callback subroutine that will populate (or modify) those
599       variables.  They are then available for use in the style you've chosen.
600
601       The callbacks are called for each opcode visited by Concise, in the
602       same order as they are added.  Each subroutine is passed five
603       parameters.
604
605         1. A hashref, containing the variable names and values which are
606            populated into the report-line for the op
607         2. the op, as a B<B::OP> object
608         3. a reference to the format string
609         4. the formatting (indent) level
610         5. the selected stylename
611
612       To define your own variables, simply add them to the hash, or change
613       existing values if you need to.  The level and format are passed in as
614       references to scalars, but it is unlikely that they will need to be
615       changed or even used.
616
617   Running B::Concise::compile()
618       compile accepts options as described above in "OPTIONS", and arguments,
619       which are either coderefs, or subroutine names.
620
621       It constructs and returns a $treewalker coderef, which when invoked,
622       traverses, or walks, and renders the optrees of the given arguments to
623       STDOUT.  You can reuse this, and can change the rendering style used
624       each time; thereafter the coderef renders in the new style.
625
626       walk_output lets you change the print destination from STDOUT to
627       another open filehandle, or into a string passed as a ref (unless
628       you've built perl with -Uuseperlio).
629
630           my $walker = B::Concise::compile('-terse','aFuncName', \&aSubRef);  # 1
631           walk_output(\my $buf);
632           $walker->();                        # 1 renders -terse
633           set_style_standard('concise');      # 2
634           $walker->();                        # 2 renders -concise
635           $walker->(@new);                    # 3 renders whatever
636           print "3 different renderings: terse, concise, and @new: $buf\n";
637
638       When $walker is called, it traverses the subroutines supplied when it
639       was created, and renders them using the current style.  You can change
640       the style afterwards in several different ways:
641
642         1. call C<compile>, altering style or mode/order
643         2. call C<set_style_standard>
644         3. call $walker, passing @new options
645
646       Passing new options to the $walker is the easiest way to change amongst
647       any pre-defined styles (the ones you add are automatically recognized
648       as options), and is the only way to alter rendering order without
649       calling compile again.  Note however that rendering state is still
650       shared amongst multiple $walker objects, so they must still be used in
651       a coordinated manner.
652
653   B::Concise::reset_sequence()
654       This function (not exported) lets you reset the sequence numbers (note
655       that they're numbered arbitrarily, their goal being to be human
656       readable).  Its purpose is mostly to support testing, i.e. to compare
657       the concise output from two identical anonymous subroutines (but
658       different instances).  Without the reset, B::Concise, seeing that
659       they're separate optrees, generates different sequence numbers in the
660       output.
661
662   Errors
663       Errors in rendering (non-existent function-name, non-existent coderef)
664       are written to the STDOUT, or wherever you've set it via walk_output().
665
666       Errors using the various *style* calls, and bad args to walk_output(),
667       result in die().  Use an eval if you wish to catch these errors and
668       continue processing.
669

AUTHOR

671       Stephen McCamant, <smcc@CSUA.Berkeley.EDU>.
672
673
674
675perl v5.16.3                      2013-03-04                   B::Concise(3pm)
Impressum