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 syn‐
15       tax 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 an example of 2 outputs (aka 'renderings'), using the -exec and
25       -basic (i.e. 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       Each line corresponds to an opcode. The opcode marked with '*' is used
38       in a few examples below.
39
40       The 1st column is the op's sequence number, starting at 1, and is dis‐
41       played in base 36 by default.  This rendering is in -exec (i.e.  execu‐
42       tion) order.
43
44       The symbol between angle brackets indicates the op's type, for example;
45       <2> is a BINOP, <@> a LISTOP, and <#> is a PADOP, which is used in
46       threaded perls. (see "OP class abbreviations").
47
48       The opname, as in 'add[t1]', which may be followed by op-specific
49       information in parentheses or brackets (ex '[t1]').
50
51       The op-flags (ex 'sK/2') follow, and are described in ("OP flags abbre‐
52       viations").
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 exam‐
73       ple), 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 print the OPs of; if no such functions are specified,
87       the main body of the program (outside any subroutines, and not includ‐
88       ing use'd or require'd files) is rendered.  Passing "BEGIN", "CHECK",
89       "INIT", or "END" will cause all of the corresponding special blocks to
90       be printed.
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
99       These options control the 'vertical display' of opcodes.  The display
100       'order' is also called 'mode' elsewhere in this document.
101
102       -basic
103           Print OPs in the order they appear in the OP tree (a preorder tra‐
104           versal, starting at the root). The indentation of each OP shows its
105           level in the tree, and the '->' at the end of the line indicates
106           the next opcode in execution order.  This mode is the default, so
107           the flag is included simply for completeness.
108
109       -exec
110           Print OPs in the order they would normally execute (for the major‐
111           ity of constructs this is a postorder traversal of the tree, ending
112           at the root). In most cases the OP that usually follows a given OP
113           will appear directly below it; alternate paths are shown by inden‐
114           tation. In cases like loops when control jumps out of a linear
115           path, a 'goto' line is generated.
116
117       -tree
118           Print OPs in a text approximation of a tree, with the root of the
119           tree at the left and 'left-to-right' order of children transformed
120           into 'top-to-bottom'. Because this mode grows both to the right and
121           down, it isn't suitable for large programs (unless you have a very
122           wide terminal).
123
124       Options for Line-Style
125
126       These options select the line-style (or just style) used to render each
127       opcode, and dictates what info is actually printed into each line.
128
129       -concise
130           Use the author's favorite set of formatting conventions. This is
131           the default, of course.
132
133       -terse
134           Use formatting conventions that emulate the output of B::Terse. The
135           basic mode is almost indistinguishable from the real B::Terse, and
136           the exec mode looks very similar, but is in a more logical order
137           and lacks curly brackets. B::Terse doesn't have a tree mode, so the
138           tree mode is only vaguely reminiscent of B::Terse.
139
140       -linenoise
141           Use formatting conventions in which the name of each OP, rather
142           than being written out in full, is represented by a one- or two-
143           character abbreviation.  This is mainly a joke.
144
145       -debug
146           Use formatting conventions reminiscent of B::Debug; these aren't
147           very concise at all.
148
149       -env
150           Use formatting conventions read from the environment variables
151           "B_CONCISE_FORMAT", "B_CONCISE_GOTO_FORMAT", and "B_CON‐
152           CISE_TREE_FORMAT".
153
154       Options for tree-specific formatting
155
156       -compact
157           Use a tree format in which the minimum amount of space is used for
158           the lines connecting nodes (one character in most cases). This
159           squeezes out a few precious columns of screen real estate.
160
161       -loose
162           Use a tree format that uses longer edges to separate OP nodes. This
163           format tends to look better than the compact one, especially in
164           ASCII, and is the default.
165
166       -vt Use tree connecting characters drawn from the VT100 line-drawing
167           set.  This looks better if your terminal supports it.
168
169       -ascii
170           Draw the tree with standard ASCII characters like "+" and "⎪".
171           These don't look as clean as the VT100 characters, but they'll work
172           with almost any terminal (or the horizontal scrolling mode of
173           less(1)) and are suitable for text documentation or email. This is
174           the default.
175
176       These are pairwise exclusive, i.e. compact or loose, vt or ascii.
177
178       Options controlling sequence numbering
179
180       -basen
181           Print OP sequence numbers in base n. If n is greater than 10, the
182           digit for 11 will be 'a', and so on. If n is greater than 36, the
183           digit for 37 will be 'A', and so on until 62. Values greater than
184           62 are not currently supported. The default is 36.
185
186       -bigendian
187           Print sequence numbers with the most significant digit first. This
188           is the usual convention for Arabic numerals, and the default.
189
190       -littleendian
191           Print seqence numbers with the least significant digit first.  This
192           is obviously mutually exclusive with bigendian.
193
194       Other options
195
196       These are pairwise exclusive.
197
198       -main
199           Include the main program in the output, even if subroutines were
200           also specified.  This rendering is normally suppressed when a sub‐
201           routine name or reference is given.
202
203       -nomain
204           This restores the default behavior after you've changed it with
205           '-main' (it's not normally needed).  If no subroutine name/ref is
206           given, main is rendered, regardless of this flag.
207
208       -nobanner
209           Renderings usually include a banner line identifying the function
210           name or stringified subref.  This suppresses the printing of the
211           banner.
212
213           TBC: Remove the stringified coderef; while it provides a 'cookie'
214           for each function rendered, the cookies used should be 1,2,3.. not
215           a random hex-address.  It also complicates string comparison of two
216           different trees.
217
218       -banner
219           restores default banner behavior.
220
221       -banneris => subref
222           TBC: a hookpoint (and an option to set it) for a user-supplied
223           function to produce a banner appropriate for users needs.  It's not
224           ideal, because the rendering-state variables, which are a natural
225           candidate for use in concise.t, are unavailable to the user.
226
227       Option Stickiness
228
229       If you invoke Concise more than once in a program, you should know that
230       the options are 'sticky'.  This means that the options you provide in
231       the first call will be remembered for the 2nd call, unless you re-spec‐
232       ify or change them.
233

ABBREVIATIONS

235       The concise style uses symbols to convey maximum info with minimal
236       clutter (like hex addresses).  With just a little practice, you can
237       start to see the flowers, not just the branches, in the trees.
238
239       OP class abbreviations
240
241       These symbols appear before the op-name, and indicate the B:: namespace
242       that represents the ops in your Perl code.
243
244           0      OP (aka BASEOP)  An OP with no children
245           1      UNOP             An OP with one child
246           2      BINOP            An OP with two children
247           ⎪      LOGOP            A control branch OP
248           @      LISTOP           An OP that could have lots of children
249           /      PMOP             An OP with a regular expression
250           $      SVOP             An OP with an SV
251           "      PVOP             An OP with a string
252           {      LOOP             An OP that holds pointers for a loop
253           ;      COP              An OP that marks the start of a statement
254           #      PADOP            An OP with a GV on the pad
255
256       OP flags abbreviations
257
258       OP flags are either public or private.  The public flags alter the
259       behavior of each opcode in consistent ways, and are represented by 0 or
260       more single characters.
261
262           v      OPf_WANT_VOID    Want nothing (void context)
263           s      OPf_WANT_SCALAR  Want single value (scalar context)
264           l      OPf_WANT_LIST    Want list of any length (list context)
265                                   Want is unknown
266           K      OPf_KIDS         There is a firstborn child.
267           P      OPf_PARENS       This operator was parenthesized.
268                                    (Or block needs explicit scope entry.)
269           R      OPf_REF          Certified reference.
270                                    (Return container, not containee).
271           M      OPf_MOD          Will modify (lvalue).
272           S      OPf_STACKED      Some arg is arriving on the stack.
273           *      OPf_SPECIAL      Do something weird for this op (see op.h)
274
275       Private flags, if any are set for an opcode, are displayed after a '/'
276
277           8  <@> leave[1 ref] vKP/REFC ->(end)
278           7     <2> sassign vKS/2 ->8
279
280       They're opcode specific, and occur less often than the public ones, so
281       they're represented by short mnemonics instead of single-chars; see
282       op.h for gory details, or try this quick 2-liner:
283
284         $> perl -MB::Concise -de 1
285         DB<1> ⎪x \%B::Concise::priv
286

FORMATTING SPECIFICATIONS

288       For each line-style ('concise', 'terse', 'linenoise', etc.) there are 3
289       format-specs which control how OPs are rendered.
290
291       The first is the 'default' format, which is used in both basic and exec
292       modes to print all opcodes.  The 2nd, goto-format, is used in exec mode
293       when branches are encountered.  They're not real opcodes, and are
294       inserted to look like a closing curly brace.  The tree-format is tree
295       specific.
296
297       When a line is rendered, the correct format-spec is copied and scanned
298       for the following items; data is substituted in, and other manipula‐
299       tions like basic indenting are done, for each opcode rendered.
300
301       There are 3 kinds of items that may be populated; special patterns,
302       #vars, and literal text, which is copied verbatim.  (Yes, it's a set of
303       s///g steps.)
304
305       Special Patterns
306
307       These items are the primitives used to perform indenting, and to select
308       text from amongst alternatives.
309
310       (x(exec_text;basic_text)x)
311           Generates exec_text in exec mode, or basic_text in basic mode.
312
313       (*(text)*)
314           Generates one copy of text for each indentation level.
315
316       (*(text1;text2)*)
317           Generates one fewer copies of text1 than the indentation level,
318           followed by one copy of text2 if the indentation level is more than
319           0.
320
321       (?(text1#varText2)?)
322           If the value of var is true (not empty or zero), generates the
323           value of var surrounded by text1 and Text2, otherwise nothing.
324
325       ~   Any number of tildes and surrounding whitespace will be collapsed
326           to a single space.
327
328       # Variables
329
330       These #vars represent opcode properties that you may want as part of
331       your rendering.  The '#' is intended as a private sigil; a #var's value
332       is interpolated into the style-line, much like "read $this".
333
334       These vars take 3 forms:
335
336       #var
337           A property named 'var' is assumed to exist for the opcodes, and is
338           interpolated into the rendering.
339
340       #varN
341           Generates the value of var, left justified to fill N spaces.  Note
342           that this means while you can have properties 'foo' and 'foo2', you
343           cannot render 'foo2', but you could with 'foo2a'.  You would be
344           wise not to rely on this behavior going forward ;-)
345
346       #Var
347           This ucfirst form of #var generates a tag-value form of itself for
348           display; it converts '#Var' into a 'Var => #var' style, which is
349           then handled as described above.  (Imp-note: #Vars cannot be used
350           for conditional-fills, because the => #var transform is done after
351           the check for #Var's value).
352
353       The following variables are 'defined' by B::Concise; when they are used
354       in a style, their respective values are plugged into the rendering of
355       each opcode.
356
357       Only some of these are used by the standard styles, the others are pro‐
358       vided for you to delve into optree mechanics, should you wish to add a
359       new style (see "add_style" below) that uses them.  You can also add new
360       ones using "add_callback".
361
362       #addr
363           The address of the OP, in hexadecimal.
364
365       #arg
366           The OP-specific information of the OP (such as the SV for an SVOP,
367           the non-local exit pointers for a LOOP, etc.) enclosed in parenthe‐
368           ses.
369
370       #class
371           The B-determined class of the OP, in all caps.
372
373       #classsym
374           A single symbol abbreviating the class of the OP.
375
376       #coplabel
377           The label of the statement or block the OP is the start of, if any.
378
379       #exname
380           The name of the OP, or 'ex-foo' if the OP is a null that used to be
381           a foo.
382
383       #extarg
384           The target of the OP, or nothing for a nulled OP.
385
386       #firstaddr
387           The address of the OP's first child, in hexadecimal.
388
389       #flags
390           The OP's flags, abbreviated as a series of symbols.
391
392       #flagval
393           The numeric value of the OP's flags.
394
395       #hyphseq
396           The sequence number of the OP, or a hyphen if it doesn't have one.
397
398       #label
399           'NEXT', 'LAST', or 'REDO' if the OP is a target of one of those in
400           exec mode, or empty otherwise.
401
402       #lastaddr
403           The address of the OP's last child, in hexadecimal.
404
405       #name
406           The OP's name.
407
408       #NAME
409           The OP's name, in all caps.
410
411       #next
412           The sequence number of the OP's next OP.
413
414       #nextaddr
415           The address of the OP's next OP, in hexadecimal.
416
417       #noise
418           A one- or two-character abbreviation for the OP's name.
419
420       #private
421           The OP's private flags, rendered with abbreviated names if possi‐
422           ble.
423
424       #privval
425           The numeric value of the OP's private flags.
426
427       #seq
428           The sequence number of the OP. Note that this is a sequence number
429           generated by B::Concise.
430
431       #seqnum
432           5.8.x and earlier only. 5.9 and later do not provide this.
433
434           The real sequence number of the OP, as a regular number and not
435           adjusted to be relative to the start of the real program. (This
436           will generally be a fairly large number because all of B::Concise
437           is compiled before your program is).
438
439       #opt
440           Whether or not the op has been optimised by the peephole optimiser.
441
442           Only available in 5.9 and later.
443
444       #static
445           Whether or not the op is statically defined.  This flag is used by
446           the B::C compiler backend and indicates that the op should not be
447           freed.
448
449           Only available in 5.9 and later.
450
451       #sibaddr
452           The address of the OP's next youngest sibling, in hexadecimal.
453
454       #svaddr
455           The address of the OP's SV, if it has an SV, in hexadecimal.
456
457       #svclass
458           The class of the OP's SV, if it has one, in all caps (e.g., 'IV').
459
460       #svval
461           The value of the OP's SV, if it has one, in a short human-readable
462           format.
463
464       #targ
465           The numeric value of the OP's targ.
466
467       #targarg
468           The name of the variable the OP's targ refers to, if any, otherwise
469           the letter t followed by the OP's targ in decimal.
470
471       #targarglife
472           Same as #targarg, but followed by the COP sequence numbers that
473           delimit the variable's lifetime (or 'end' for a variable in an open
474           scope) for a variable.
475
476       #typenum
477           The numeric value of the OP's type, in decimal.
478

Using B::Concise outside of the O framework

480       The common (and original) usage of B::Concise was for command-line ren‐
481       derings of simple code, as given in EXAMPLE.  But you can also use
482       B::Concise from your code, and call compile() directly, and repeatedly.
483       By doing so, you can avoid the compile-time only operation of O.pm, and
484       even use the debugger to step through B::Concise::compile() itself.
485
486       Once you're doing this, you may alter Concise output by adding new ren‐
487       dering styles, and by optionally adding callback routines which popu‐
488       late new variables, if such were referenced from those (just added)
489       styles.
490
491       Example: Altering Concise Renderings
492
493           use B::Concise qw(set_style add_callback);
494           add_style($yourStyleName => $defaultfmt, $gotofmt, $treefmt);
495           add_callback
496             ( sub {
497                   my ($h, $op, $format, $level, $stylename) = @_;
498                   $h->{variable} = some_func($op);
499               });
500           $walker = B::Concise::compile(@options,@subnames,@subrefs);
501           $walker->();
502
503       set_style()
504
505       set_style accepts 3 arguments, and updates the three format-specs com‐
506       prising a line-style (basic-exec, goto, tree).  It has one minor draw‐
507       back though; it doesn't register the style under a new name.  This can
508       become an issue if you render more than once and switch styles.  Thus
509       you may prefer to use add_style() and/or set_style_standard() instead.
510
511       set_style_standard($name)
512
513       This restores one of the standard line-styles: "terse", "concise",
514       "linenoise", "debug", "env", into effect.  It also accepts style names
515       previously defined with add_style().
516
517       add_style()
518
519       This subroutine accepts a new style name and three style arguments as
520       above, and creates, registers, and selects the newly named style.  It
521       is an error to re-add a style; call set_style_standard() to switch
522       between several styles.
523
524       add_callback()
525
526       If your newly minted styles refer to any new #variables, you'll need to
527       define a callback subroutine that will populate (or modify) those vari‐
528       ables.  They are then available for use in the style you've chosen.
529
530       The callbacks are called for each opcode visited by Concise, in the
531       same order as they are added.  Each subroutine is passed five parame‐
532       ters.
533
534         1. A hashref, containing the variable names and values which are
535            populated into the report-line for the op
536         2. the op, as a B<B::OP> object
537         3. a reference to the format string
538         4. the formatting (indent) level
539         5. the selected stylename
540
541       To define your own variables, simply add them to the hash, or change
542       existing values if you need to.  The level and format are passed in as
543       references to scalars, but it is unlikely that they will need to be
544       changed or even used.
545
546       Running B::Concise::compile()
547
548       compile accepts options as described above in "OPTIONS", and arguments,
549       which are either coderefs, or subroutine names.
550
551       It constructs and returns a $treewalker coderef, which when invoked,
552       traverses, or walks, and renders the optrees of the given arguments to
553       STDOUT.  You can reuse this, and can change the rendering style used
554       each time; thereafter the coderef renders in the new style.
555
556       walk_output lets you change the print destination from STDOUT to
557       another open filehandle, or into a string passed as a ref (unless
558       you've built perl with -Uuseperlio).
559
560           my $walker = B::Concise::compile('-terse','aFuncName', \&aSubRef);  # 1
561           walk_output(\my $buf);
562           $walker->();                        # 1 renders -terse
563           set_style_standard('concise');      # 2
564           $walker->();                        # 2 renders -concise
565           $walker->(@new);                    # 3 renders whatever
566           print "3 different renderings: terse, concise, and @new: $buf\n";
567
568       When $walker is called, it traverses the subroutines supplied when it
569       was created, and renders them using the current style.  You can change
570       the style afterwards in several different ways:
571
572         1. call C<compile>, altering style or mode/order
573         2. call C<set_style_standard>
574         3. call $walker, passing @new options
575
576       Passing new options to the $walker is the easiest way to change amongst
577       any pre-defined styles (the ones you add are automatically recognized
578       as options), and is the only way to alter rendering order without call‐
579       ing compile again.  Note however that rendering state is still shared
580       amongst multiple $walker objects, so they must still be used in a coor‐
581       dinated manner.
582
583       B::Concise::reset_sequence()
584
585       This function (not exported) lets you reset the sequence numbers (note
586       that they're numbered arbitrarily, their goal being to be human read‐
587       able).  Its purpose is mostly to support testing, i.e. to compare the
588       concise output from two identical anonymous subroutines (but different
589       instances).  Without the reset, B::Concise, seeing that they're sepa‐
590       rate optrees, generates different sequence numbers in the output.
591
592       Errors
593
594       Errors in rendering (non-existent function-name, non-existent coderef)
595       are written to the STDOUT, or wherever you've set it via walk_output().
596
597       Errors using the various *style* calls, and bad args to walk_output(),
598       result in die().  Use an eval if you wish to catch these errors and
599       continue processing.
600

AUTHOR

602       Stephen McCamant, <smcc@CSUA.Berkeley.EDU>.
603
604
605
606perl v5.8.8                       2001-09-21                   B::Concise(3pm)
Impressum