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 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
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
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 us use feature 'unicode_strings'
442 fea=NNN feature bundle number
443
444 #hintsval
445 The numeric value of the COP's hint flags, or an empty string if
446 this is not a COP.
447
448 #hyphseq
449 The sequence number of the OP, or a hyphen if it doesn't have one.
450
451 #label
452 'NEXT', 'LAST', or 'REDO' if the OP is a target of one of those in
453 exec mode, or empty otherwise.
454
455 #lastaddr
456 The address of the OP's last child, in hexadecimal.
457
458 #name
459 The OP's name.
460
461 #NAME
462 The OP's name, in all caps.
463
464 #next
465 The sequence number of the OP's next OP.
466
467 #nextaddr
468 The address of the OP's next OP, in hexadecimal.
469
470 #noise
471 A one- or two-character abbreviation for the OP's name.
472
473 #private
474 The OP's private flags, rendered with abbreviated names if
475 possible.
476
477 #privval
478 The numeric value of the OP's private flags.
479
480 #seq
481 The sequence number of the OP. Note that this is a sequence number
482 generated by B::Concise.
483
484 #opt
485 Whether or not the op has been optimized by the peephole optimizer.
486
487 #sibaddr
488 The address of the OP's next youngest sibling, in hexadecimal.
489
490 #svaddr
491 The address of the OP's SV, if it has an SV, in hexadecimal.
492
493 #svclass
494 The class of the OP's SV, if it has one, in all caps (e.g., 'IV').
495
496 #svval
497 The value of the OP's SV, if it has one, in a short human-readable
498 format.
499
500 #targ
501 The numeric value of the OP's targ.
502
503 #targarg
504 The name of the variable the OP's targ refers to, if any, otherwise
505 the letter t followed by the OP's targ in decimal.
506
507 #targarglife
508 Same as #targarg, but followed by the COP sequence numbers that
509 delimit the variable's lifetime (or 'end' for a variable in an open
510 scope) for a variable.
511
512 #typenum
513 The numeric value of the OP's type, in decimal.
514
516 perl -MO=Concise,bar foo.pl
517 Renders only bar() from foo.pl. To see main, drop the ',bar'. To
518 see both, add ',-main'
519
520 perl -MDigest::MD5=md5 -MO=Concise,md5 -e1
521 Identifies md5 as an XS function. The export is needed so that BC
522 can find it in main.
523
524 perl -MPOSIX -MO=Concise,_POSIX_ARG_MAX -e1
525 Identifies _POSIX_ARG_MAX as a constant sub, optimized to an IV.
526 Although POSIX isn't entirely consistent across platforms, this is
527 likely to be present in virtually all of them.
528
529 perl -MPOSIX -MO=Concise,a -e 'print _POSIX_SAVED_IDS'
530 This renders a print statement, which includes a call to the
531 function. It's identical to rendering a file with a use call and
532 that single statement, except for the filename which appears in the
533 nextstate ops.
534
535 perl -MPOSIX -MO=Concise,a -e 'sub a{_POSIX_SAVED_IDS}'
536 This is very similar to previous, only the first two ops differ.
537 This subroutine rendering is more representative, insofar as a
538 single main program will have many subs.
539
540 perl -MB::Concise -e 'B::Concise::compile("-exec","-src",
541 \%B::Concise::)->()'
542 This renders all functions in the B::Concise package with the
543 source lines. It eschews the O framework so that the stashref can
544 be passed directly to B::Concise::compile(). See -stash option for
545 a more convenient way to render a package.
546
548 The common (and original) usage of B::Concise was for command-line
549 renderings of simple code, as given in EXAMPLE. But you can also use
550 B::Concise from your code, and call compile() directly, and repeatedly.
551 By doing so, you can avoid the compile-time only operation of O.pm, and
552 even use the debugger to step through B::Concise::compile() itself.
553
554 Once you're doing this, you may alter Concise output by adding new
555 rendering styles, and by optionally adding callback routines which
556 populate new variables, if such were referenced from those (just added)
557 styles.
558
559 Example: Altering Concise Renderings
560 use B::Concise qw(set_style add_callback);
561 add_style($yourStyleName => $defaultfmt, $gotofmt, $treefmt);
562 add_callback
563 ( sub {
564 my ($h, $op, $format, $level, $stylename) = @_;
565 $h->{variable} = some_func($op);
566 });
567 $walker = B::Concise::compile(@options,@subnames,@subrefs);
568 $walker->();
569
570 set_style()
571 set_style accepts 3 arguments, and updates the three format-specs
572 comprising a line-style (basic-exec, goto, tree). It has one minor
573 drawback though; it doesn't register the style under a new name. This
574 can become an issue if you render more than once and switch styles.
575 Thus you may prefer to use add_style() and/or set_style_standard()
576 instead.
577
578 set_style_standard($name)
579 This restores one of the standard line-styles: "terse", "concise",
580 "linenoise", "debug", "env", into effect. It also accepts style names
581 previously defined with add_style().
582
583 add_style ()
584 This subroutine accepts a new style name and three style arguments as
585 above, and creates, registers, and selects the newly named style. It
586 is an error to re-add a style; call set_style_standard() to switch
587 between several styles.
588
589 add_callback ()
590 If your newly minted styles refer to any new #variables, you'll need to
591 define a callback subroutine that will populate (or modify) those
592 variables. They are then available for use in the style you've chosen.
593
594 The callbacks are called for each opcode visited by Concise, in the
595 same order as they are added. Each subroutine is passed five
596 parameters.
597
598 1. A hashref, containing the variable names and values which are
599 populated into the report-line for the op
600 2. the op, as a B<B::OP> object
601 3. a reference to the format string
602 4. the formatting (indent) level
603 5. the selected stylename
604
605 To define your own variables, simply add them to the hash, or change
606 existing values if you need to. The level and format are passed in as
607 references to scalars, but it is unlikely that they will need to be
608 changed or even used.
609
610 Running B::Concise::compile()
611 compile accepts options as described above in "OPTIONS", and arguments,
612 which are either coderefs, or subroutine names.
613
614 It constructs and returns a $treewalker coderef, which when invoked,
615 traverses, or walks, and renders the optrees of the given arguments to
616 STDOUT. You can reuse this, and can change the rendering style used
617 each time; thereafter the coderef renders in the new style.
618
619 walk_output lets you change the print destination from STDOUT to
620 another open filehandle, or into a string passed as a ref (unless
621 you've built perl with -Uuseperlio).
622
623 my $walker = B::Concise::compile('-terse','aFuncName', \&aSubRef); # 1
624 walk_output(\my $buf);
625 $walker->(); # 1 renders -terse
626 set_style_standard('concise'); # 2
627 $walker->(); # 2 renders -concise
628 $walker->(@new); # 3 renders whatever
629 print "3 different renderings: terse, concise, and @new: $buf\n";
630
631 When $walker is called, it traverses the subroutines supplied when it
632 was created, and renders them using the current style. You can change
633 the style afterwards in several different ways:
634
635 1. call C<compile>, altering style or mode/order
636 2. call C<set_style_standard>
637 3. call $walker, passing @new options
638
639 Passing new options to the $walker is the easiest way to change amongst
640 any pre-defined styles (the ones you add are automatically recognized
641 as options), and is the only way to alter rendering order without
642 calling compile again. Note however that rendering state is still
643 shared amongst multiple $walker objects, so they must still be used in
644 a coordinated manner.
645
646 B::Concise::reset_sequence()
647 This function (not exported) lets you reset the sequence numbers (note
648 that they're numbered arbitrarily, their goal being to be human
649 readable). Its purpose is mostly to support testing, i.e. to compare
650 the concise output from two identical anonymous subroutines (but
651 different instances). Without the reset, B::Concise, seeing that
652 they're separate optrees, generates different sequence numbers in the
653 output.
654
655 Errors
656 Errors in rendering (non-existent function-name, non-existent coderef)
657 are written to the STDOUT, or wherever you've set it via walk_output().
658
659 Errors using the various *style* calls, and bad args to walk_output(),
660 result in die(). Use an eval if you wish to catch these errors and
661 continue processing.
662
664 Stephen McCamant, <smcc@CSUA.Berkeley.EDU>.
665
666
667
668perl v5.32.1 2021-05-31 B::Concise(3pm)