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 or formats to render; if no such functions are specified,
87       the main body of the program (outside any subroutines, and not
88       including use'd or require'd files) is rendered.  Passing "BEGIN",
89       "UNITCHECK", "CHECK", "INIT", or "END" will cause all of the
90       corresponding special blocks to be printed.  Arguments must follow
91       options.
92
93       Options affect how things are rendered (ie printed).  They're presented
94       here by their visual effect, 1st being strongest.  They're grouped
95       according to how they interrelate; within each group the options are
96       mutually exclusive (unless otherwise stated).
97
98   Options for Opcode Ordering
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
104           traversal, starting at the root). The indentation of each OP shows
105           its level in the tree, and the '->' at the end of the line
106           indicates the next opcode in execution order.  This mode is the
107           default, so the flag is included simply for completeness.
108
109       -exec
110           Print OPs in the order they would normally execute (for the
111           majority of constructs this is a postorder traversal of the tree,
112           ending at the root). In most cases the OP that usually follows a
113           given OP will appear directly below it; alternate paths are shown
114           by indentation. In cases like loops when control jumps out of a
115           linear 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       These options select the line-style (or just style) used to render each
126       opcode, and dictates what info is actually printed into each line.
127
128       -concise
129           Use the author's favorite set of formatting conventions. This is
130           the default, of course.
131
132       -terse
133           Use formatting conventions that emulate the output of B::Terse. The
134           basic mode is almost indistinguishable from the real B::Terse, and
135           the exec mode looks very similar, but is in a more logical order
136           and lacks curly brackets. B::Terse doesn't have a tree mode, so the
137           tree mode is only vaguely reminiscent of B::Terse.
138
139       -linenoise
140           Use formatting conventions in which the name of each OP, rather
141           than being written out in full, is represented by a one- or two-
142           character abbreviation.  This is mainly a joke.
143
144       -debug
145           Use formatting conventions reminiscent of CPAN module B::Debug;
146           these aren't very concise at all.
147
148       -env
149           Use formatting conventions read from the environment variables
150           "B_CONCISE_FORMAT", "B_CONCISE_GOTO_FORMAT", and
151           "B_CONCISE_TREE_FORMAT".
152
153   Options for tree-specific formatting
154       -compact
155           Use a tree format in which the minimum amount of space is used for
156           the lines connecting nodes (one character in most cases). This
157           squeezes out a few precious columns of screen real estate.
158
159       -loose
160           Use a tree format that uses longer edges to separate OP nodes. This
161           format tends to look better than the compact one, especially in
162           ASCII, and is the default.
163
164       -vt Use tree connecting characters drawn from the VT100 line-drawing
165           set.  This looks better if your terminal supports it.
166
167       -ascii
168           Draw the tree with standard ASCII characters like "+" and "|".
169           These don't look as clean as the VT100 characters, but they'll work
170           with almost any terminal (or the horizontal scrolling mode of
171           less(1)) and are suitable for text documentation or email. This is
172           the default.
173
174       These are pairwise exclusive, i.e. compact or loose, vt or ascii.
175
176   Options controlling sequence numbering
177       -basen
178           Print OP sequence numbers in base n. If n is greater than 10, the
179           digit for 11 will be 'a', and so on. If n is greater than 36, the
180           digit for 37 will be 'A', and so on until 62. Values greater than
181           62 are not currently supported. The default is 36.
182
183       -bigendian
184           Print sequence numbers with the most significant digit first. This
185           is the usual convention for Arabic numerals, and the default.
186
187       -littleendian
188           Print sequence numbers with the least significant digit first.
189           This is obviously mutually exclusive with bigendian.
190
191   Other options
192       -src
193           With this option, the rendering of each statement (starting with
194           the nextstate OP) will be preceded by the 1st line of source code
195           that generates it.  For example:
196
197               1  <0> enter
198               # 1: my $i;
199               2  <;> nextstate(main 1 junk.pl:1) v:{
200               3  <0> padsv[$i:1,10] vM/LVINTRO
201               # 3: for $i (0..9) {
202               4  <;> nextstate(main 3 junk.pl:3) v:{
203               5  <0> pushmark s
204               6  <$> const[IV 0] s
205               7  <$> const[IV 9] s
206               8  <{> enteriter(next->j last->m redo->9)[$i:1,10] lKS
207               k  <0> iter s
208               l  <|> and(other->9) vK/1
209               # 4:     print "line ";
210               9      <;> nextstate(main 2 junk.pl:4) v
211               a      <0> pushmark s
212               b      <$> const[PV "line "] s
213               c      <@> print vK
214               # 5:     print "$i\n";
215               ...
216
217       -stash="somepackage"
218           With this, "somepackage" will be required, then the stash is
219           inspected, and each function is rendered.
220
221       The following options are pairwise exclusive.
222
223       -main
224           Include the main program in the output, even if subroutines were
225           also specified.  This rendering is normally suppressed when a
226           subroutine name or reference is given.
227
228       -nomain
229           This restores the default behavior after you've changed it with
230           '-main' (it's not normally needed).  If no subroutine name/ref is
231           given, main is rendered, regardless of this flag.
232
233       -nobanner
234           Renderings usually include a banner line identifying the function
235           name or stringified subref.  This suppresses the printing of the
236           banner.
237
238           TBC: Remove the stringified coderef; while it provides a 'cookie'
239           for each function rendered, the cookies used should be 1,2,3.. not
240           a random hex-address.  It also complicates string comparison of two
241           different trees.
242
243       -banner
244           restores default banner behavior.
245
246       -banneris => subref
247           TBC: a hookpoint (and an option to set it) for a user-supplied
248           function to produce a banner appropriate for users needs.  It's not
249           ideal, because the rendering-state variables, which are a natural
250           candidate for use in concise.t, are unavailable to the user.
251
252   Option Stickiness
253       If you invoke Concise more than once in a program, you should know that
254       the options are 'sticky'.  This means that the options you provide in
255       the first call will be remembered for the 2nd call, unless you re-
256       specify or change them.
257

ABBREVIATIONS

259       The concise style uses symbols to convey maximum info with minimal
260       clutter (like hex addresses).  With just a little practice, you can
261       start to see the flowers, not just the branches, in the trees.
262
263   OP class abbreviations
264       These symbols appear before the op-name, and indicate the B:: namespace
265       that represents the ops in your Perl code.
266
267           0      OP (aka BASEOP)  An OP with no children
268           1      UNOP             An OP with one child
269           +      UNOP_AUX         A UNOP with auxillary fields
270           2      BINOP            An OP with two children
271           |      LOGOP            A control branch OP
272           @      LISTOP           An OP that could have lots of children
273           /      PMOP             An OP with a regular expression
274           $      SVOP             An OP with an SV
275           "      PVOP             An OP with a string
276           {      LOOP             An OP that holds pointers for a loop
277           ;      COP              An OP that marks the start of a statement
278           #      PADOP            An OP with a GV on the pad
279           .      METHOP           An OP with method call info
280
281   OP flags abbreviations
282       OP flags are either public or private.  The public flags alter the
283       behavior of each opcode in consistent ways, and are represented by 0 or
284       more single characters.
285
286           v      OPf_WANT_VOID    Want nothing (void context)
287           s      OPf_WANT_SCALAR  Want single value (scalar context)
288           l      OPf_WANT_LIST    Want list of any length (list context)
289                                   Want is unknown
290           K      OPf_KIDS         There is a firstborn child.
291           P      OPf_PARENS       This operator was parenthesized.
292                                    (Or block needs explicit scope entry.)
293           R      OPf_REF          Certified reference.
294                                    (Return container, not containee).
295           M      OPf_MOD          Will modify (lvalue).
296           S      OPf_STACKED      Some arg is arriving on the stack.
297           *      OPf_SPECIAL      Do something weird for this op (see op.h)
298
299       Private flags, if any are set for an opcode, are displayed after a '/'
300
301           8  <@> leave[1 ref] vKP/REFC ->(end)
302           7     <2> sassign vKS/2 ->8
303
304       They're opcode specific, and occur less often than the public ones, so
305       they're represented by short mnemonics instead of single-chars; see
306       B::Op_private and regen/op_private for more details.
307
308       Note that a number after a '/' often indicates the number of arguments.
309       In the sassign example above, the OP takes 2 arguments. These values
310       are sometimes used at runtime: in particular, the MAXARG macro makes
311       use of them.
312

FORMATTING SPECIFICATIONS

314       For each line-style ('concise', 'terse', 'linenoise', etc.) there are 3
315       format-specs which control how OPs are rendered.
316
317       The first is the 'default' format, which is used in both basic and exec
318       modes to print all opcodes.  The 2nd, goto-format, is used in exec mode
319       when branches are encountered.  They're not real opcodes, and are
320       inserted to look like a closing curly brace.  The tree-format is tree
321       specific.
322
323       When a line is rendered, the correct format-spec is copied and scanned
324       for the following items; data is substituted in, and other
325       manipulations like basic indenting are done, for each opcode rendered.
326
327       There are 3 kinds of items that may be populated; special patterns,
328       #vars, and literal text, which is copied verbatim.  (Yes, it's a set of
329       s///g steps.)
330
331   Special Patterns
332       These items are the primitives used to perform indenting, and to select
333       text from amongst alternatives.
334
335       (x(exec_text;basic_text)x)
336           Generates exec_text in exec mode, or basic_text in basic mode.
337
338       (*(text)*)
339           Generates one copy of text for each indentation level.
340
341       (*(text1;text2)*)
342           Generates one fewer copies of text1 than the indentation level,
343           followed by one copy of text2 if the indentation level is more than
344           0.
345
346       (?(text1#varText2)?)
347           If the value of var is true (not empty or zero), generates the
348           value of var surrounded by text1 and Text2, otherwise nothing.
349
350       ~   Any number of tildes and surrounding whitespace will be collapsed
351           to a single space.
352
353   # Variables
354       These #vars represent opcode properties that you may want as part of
355       your rendering.  The '#' is intended as a private sigil; a #var's value
356       is interpolated into the style-line, much like "read $this".
357
358       These vars take 3 forms:
359
360       #var
361           A property named 'var' is assumed to exist for the opcodes, and is
362           interpolated into the rendering.
363
364       #varN
365           Generates the value of var, left justified to fill N spaces.  Note
366           that this means while you can have properties 'foo' and 'foo2', you
367           cannot render 'foo2', but you could with 'foo2a'.  You would be
368           wise not to rely on this behavior going forward ;-)
369
370       #Var
371           This ucfirst form of #var generates a tag-value form of itself for
372           display; it converts '#Var' into a 'Var => #var' style, which is
373           then handled as described above.  (Imp-note: #Vars cannot be used
374           for conditional-fills, because the => #var transform is done after
375           the check for #Var's value).
376
377       The following variables are 'defined' by B::Concise; when they are used
378       in a style, their respective values are plugged into the rendering of
379       each opcode.
380
381       Only some of these are used by the standard styles, the others are
382       provided for you to delve into optree mechanics, should you wish to add
383       a new style (see "add_style" below) that uses them.  You can also add
384       new ones using "add_callback".
385
386       #addr
387           The address of the OP, in hexadecimal.
388
389       #arg
390           The OP-specific information of the OP (such as the SV for an SVOP,
391           the non-local exit pointers for a LOOP, etc.) enclosed in
392           parentheses.
393
394       #class
395           The B-determined class of the OP, in all caps.
396
397       #classsym
398           A single symbol abbreviating the class of the OP.
399
400       #coplabel
401           The label of the statement or block the OP is the start of, if any.
402
403       #exname
404           The name of the OP, or 'ex-foo' if the OP is a null that used to be
405           a foo.
406
407       #extarg
408           The target of the OP, or nothing for a nulled OP.
409
410       #firstaddr
411           The address of the OP's first child, in hexadecimal.
412
413       #flags
414           The OP's flags, abbreviated as a series of symbols.
415
416       #flagval
417           The numeric value of the OP's flags.
418
419       #hints
420           The COP's hint flags, rendered with abbreviated names if possible.
421           An empty string if this is not a COP. Here are the symbols used:
422
423               $ strict refs
424               & strict subs
425               * strict vars
426              x$ explicit use/no strict refs
427              x& explicit use/no strict subs
428              x* explicit use/no strict vars
429               i integers
430               l locale
431               b bytes
432               { block scope
433               % localise %^H
434               < open in
435               > open out
436               I overload int
437               F overload float
438               B overload binary
439               S overload string
440               R overload re
441               T taint
442               E eval
443               X filetest access
444               U utf-8
445
446               us      use feature 'unicode_strings'
447               fea=NNN feature bundle number
448
449       #hintsval
450           The numeric value of the COP's hint flags, or an empty string if
451           this is not a COP.
452
453       #hyphseq
454           The sequence number of the OP, or a hyphen if it doesn't have one.
455
456       #label
457           'NEXT', 'LAST', or 'REDO' if the OP is a target of one of those in
458           exec mode, or empty otherwise.
459
460       #lastaddr
461           The address of the OP's last child, in hexadecimal.
462
463       #name
464           The OP's name.
465
466       #NAME
467           The OP's name, in all caps.
468
469       #next
470           The sequence number of the OP's next OP.
471
472       #nextaddr
473           The address of the OP's next OP, in hexadecimal.
474
475       #noise
476           A one- or two-character abbreviation for the OP's name.
477
478       #private
479           The OP's private flags, rendered with abbreviated names if
480           possible.
481
482       #privval
483           The numeric value of the OP's private flags.
484
485       #seq
486           The sequence number of the OP. Note that this is a sequence number
487           generated by B::Concise.
488
489       #opt
490           Whether or not the op has been optimized by the peephole optimizer.
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

One-Liner Command tips

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

Using B::Concise outside of the O framework

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

AUTHOR

669       Stephen McCamant, <smcc@CSUA.Berkeley.EDU>.
670
671
672
673perl v5.38.2                      2023-11-30                   B::Concise(3pm)
Impressum