This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
B::Concise: Give sequence numbers for null ops
[perl5.git] / ext / B / B / Concise.pm
CommitLineData
c99ca59a 1package B::Concise;
c27ea44e 2# Copyright (C) 2000-2003 Stephen McCamant. All rights reserved.
c99ca59a
SM
3# This program is free software; you can redistribute and/or modify it
4# under the same terms as Perl itself.
5
8ec8fbef
SM
6# Note: we need to keep track of how many use declarations/BEGIN
7# blocks this module uses, so we can avoid printing them when user
8# asks for the BEGIN blocks in her program. Update the comments and
9# the count in concise_specials if you add or delete one. The
10# -MO=Concise counts as use #1.
78ad9108 11
8ec8fbef
SM
12use strict; # use #2
13use warnings; # uses #3 and #4, since warnings uses Carp
78ad9108 14
8ec8fbef
SM
15use Exporter (); # use #5
16
b46e009d 17our $VERSION = "0.994";
78ad9108 18our @ISA = qw(Exporter);
cc02ea56
JC
19our @EXPORT_OK = qw( set_style set_style_standard add_callback
20 concise_subref concise_cv concise_main
21 add_style walk_output compile reset_sequence );
22our %EXPORT_TAGS =
23 ( io => [qw( walk_output compile reset_sequence )],
24 style => [qw( add_style set_style_standard )],
25 cb => [qw( add_callback )],
26 mech => [qw( concise_subref concise_cv concise_main )], );
78ad9108 27
8ec8fbef 28# use #6
c99ca59a 29use B qw(class ppname main_start main_root main_cv cstring svref_2object
6a077020 30 SVf_IOK SVf_NOK SVf_POK SVf_IVisUV SVf_FAKE OPf_KIDS OPf_SPECIAL
4df7f6af 31 CVf_ANON PAD_FAKELEX_ANON PAD_FAKELEX_MULTI SVf_ROK);
c99ca59a 32
f95e3c3c 33my %style =
c99ca59a 34 ("terse" =>
c3caa09d
SM
35 ["(?(#label =>\n)?)(*( )*)#class (#addr) #name (?([#targ])?) "
36 . "#svclass~(?((#svaddr))?)~#svval~(?(label \"#coplabel\")?)\n",
c99ca59a
SM
37 "(*( )*)goto #class (#addr)\n",
38 "#class pp_#name"],
39 "concise" =>
d5ec2987
NC
40 ["#hyphseq2 (*( (x( ;)x))*)<#classsym> #exname#arg(?([#targarglife])?)"
41 . "~#flags(?(/#private)?)(?(:#hints)?)(x(;~->#next)x)\n"
cc02ea56 42 , " (*( )*) goto #seq\n",
c99ca59a
SM
43 "(?(<#seq>)?)#exname#arg(?([#targarglife])?)"],
44 "linenoise" =>
45 ["(x(;(*( )*))x)#noise#arg(?([#targarg])?)(x( ;\n)x)",
46 "gt_#seq ",
47 "(?(#seq)?)#noise#arg(?([#targarg])?)"],
48 "debug" =>
a854082c
MH
49 ["#class (#addr)\n\top_next\t\t#nextaddr\n\t(?(op_other\t#otheraddr\n\t)?)"
50 . "op_sibling\t#sibaddr\n\t"
35633035 51 . "op_ppaddr\tPL_ppaddr[OP_#NAME]\n\top_type\t\t#typenum\n"
d5ec2987 52 . "\top_flags\t#flagval\n\top_private\t#privval\t#hintsval\n"
c99ca59a
SM
53 . "(?(\top_first\t#firstaddr\n)?)(?(\top_last\t\t#lastaddr\n)?)"
54 . "(?(\top_sv\t\t#svaddr\n)?)",
55 " GOTO #addr\n",
56 "#addr"],
57 "env" => [$ENV{B_CONCISE_FORMAT}, $ENV{B_CONCISE_GOTO_FORMAT},
58 $ENV{B_CONCISE_TREE_FORMAT}],
59 );
60
724aa791
JC
61# Renderings, ie how Concise prints, is controlled by these vars
62# primary:
63our $stylename; # selects current style from %style
64my $order = "basic"; # how optree is walked & printed: basic, exec, tree
65
66# rendering mechanics:
67# these 'formats' are the line-rendering templates
68# they're updated from %style when $stylename changes
69my ($format, $gotofmt, $treefmt);
70
71# lesser players:
72my $base = 36; # how <sequence#> is displayed
73my $big_endian = 1; # more <sequence#> display
74my $tree_style = 0; # tree-order details
75my $banner = 1; # print banner before optree is traversed
cc02ea56 76my $do_main = 0; # force printing of main routine
f18deeb9 77my $show_src; # show source code
724aa791 78
cc02ea56 79# another factor: can affect all styles!
724aa791
JC
80our @callbacks; # allow external management
81
82set_style_standard("concise");
83
c99ca59a 84my $curcv;
c27ea44e 85my $cop_seq_base;
78ad9108
PJ
86
87sub set_style {
88 ($format, $gotofmt, $treefmt) = @_;
724aa791 89 #warn "set_style: deprecated, use set_style_standard instead\n"; # someday
f95e3c3c
JC
90 die "expecting 3 style-format args\n" unless @_ == 3;
91}
92
93sub add_style {
94 my ($newstyle,@args) = @_;
95 die "style '$newstyle' already exists, choose a new name\n"
96 if exists $style{$newstyle};
97 die "expecting 3 style-format args\n" unless @args == 3;
98 $style{$newstyle} = [@args];
724aa791 99 $stylename = $newstyle; # update rendering state
78ad9108
PJ
100}
101
31b49ad4 102sub set_style_standard {
724aa791 103 ($stylename) = @_; # update rendering state
f95e3c3c
JC
104 die "err: style '$stylename' unknown\n" unless exists $style{$stylename};
105 set_style(@{$style{$stylename}});
31b49ad4
SM
106}
107
78ad9108
PJ
108sub add_callback {
109 push @callbacks, @_;
110}
c99ca59a 111
f95e3c3c 112# output handle, used with all Concise-output printing
cc02ea56
JC
113our $walkHandle; # public for your convenience
114BEGIN { $walkHandle = \*STDOUT }
f95e3c3c
JC
115
116sub walk_output { # updates $walkHandle
117 my $handle = shift;
cc02ea56
JC
118 return $walkHandle unless $handle; # allow use as accessor
119
f95e3c3c 120 if (ref $handle eq 'SCALAR') {
2ce64696
JC
121 require Config;
122 die "no perlio in this build, can't call walk_output (\\\$scalar)\n"
123 unless $Config::Config{useperlio};
f95e3c3c 124 # in 5.8+, open(FILEHANDLE,MODE,REFERENCE) writes to string
2ce64696 125 open my $tmp, '>', $handle; # but cant re-set existing STDOUT
f95e3c3c 126 $walkHandle = $tmp; # so use my $tmp as intermediate var
cc02ea56 127 return $walkHandle;
f95e3c3c 128 }
cc02ea56 129 my $iotype = ref $handle;
f95e3c3c 130 die "expecting argument/object that can print\n"
cc02ea56
JC
131 unless $iotype eq 'GLOB' or $iotype and $handle->can('print');
132 $walkHandle = $handle;
f95e3c3c
JC
133}
134
8ec8fbef 135sub concise_subref {
c0939cee 136 my($order, $coderef, $name) = @_;
f95e3c3c 137 my $codeobj = svref_2object($coderef);
cc02ea56 138
c0939cee 139 return concise_stashref(@_)
35f75594 140 unless ref($codeobj) =~ '^B::(?:CV|FM)\z';
c0939cee 141 concise_cv_obj($order, $codeobj, $name);
8ec8fbef
SM
142}
143
cc02ea56
JC
144sub concise_stashref {
145 my($order, $h) = @_;
6cc5d258 146 local *s;
cc02ea56 147 foreach my $k (sort keys %$h) {
6cc5d258
JC
148 next unless defined $h->{$k};
149 *s = $h->{$k};
cc02ea56
JC
150 my $coderef = *s{CODE} or next;
151 reset_sequence();
152 print "FUNC: ", *s, "\n";
153 my $codeobj = svref_2object($coderef);
154 next unless ref $codeobj eq 'B::CV';
6cc5d258
JC
155 eval { concise_cv_obj($order, $codeobj, $k) };
156 warn "err $@ on $codeobj" if $@;
cc02ea56
JC
157 }
158}
159
8ec8fbef
SM
160# This should have been called concise_subref, but it was exported
161# under this name in versions before 0.56
c0939cee 162*concise_cv = \&concise_subref;
8ec8fbef
SM
163
164sub concise_cv_obj {
c0939cee
JC
165 my ($order, $cv, $name) = @_;
166 # name is either a string, or a CODE ref (copy of $cv arg??)
167
c99ca59a 168 $curcv = $cv;
d51cf0c9 169
2018a5c3 170 if (ref($cv->XSUBANY) =~ /B::(\w+)/) {
d51cf0c9
JC
171 print $walkHandle "$name is a constant sub, optimized to a $1\n";
172 return;
173 }
c0939cee
JC
174 if ($cv->XSUB) {
175 print $walkHandle "$name is XS code\n";
176 return;
177 }
178 if (class($cv->START) eq "NULL") {
179 no strict 'refs';
180 if (ref $name eq 'CODE') {
181 print $walkHandle "coderef $name has no START\n";
182 }
183 elsif (exists &$name) {
e75702e9 184 print $walkHandle "$name exists in stash, but has no START\n";
c0939cee
JC
185 }
186 else {
187 print $walkHandle "$name not in symbol table\n";
188 }
189 return;
190 }
c27ea44e 191 sequence($cv->START);
c99ca59a
SM
192 if ($order eq "exec") {
193 walk_exec($cv->START);
c0939cee
JC
194 }
195 elsif ($order eq "basic") {
196 # walk_topdown($cv->ROOT, sub { $_[0]->concise($_[1]) }, 0);
197 my $root = $cv->ROOT;
198 unless (ref $root eq 'B::NULL') {
199 walk_topdown($root, sub { $_[0]->concise($_[1]) }, 0);
200 } else {
201 print $walkHandle "B::NULL encountered doing ROOT on $cv. avoiding disaster\n";
202 }
c99ca59a 203 } else {
f95e3c3c 204 print $walkHandle tree($cv->ROOT, 0);
c99ca59a
SM
205 }
206}
207
31b49ad4
SM
208sub concise_main {
209 my($order) = @_;
210 sequence(main_start);
211 $curcv = main_cv;
212 if ($order eq "exec") {
213 return if class(main_start) eq "NULL";
214 walk_exec(main_start);
215 } elsif ($order eq "tree") {
216 return if class(main_root) eq "NULL";
f95e3c3c 217 print $walkHandle tree(main_root, 0);
31b49ad4
SM
218 } elsif ($order eq "basic") {
219 return if class(main_root) eq "NULL";
220 walk_topdown(main_root,
221 sub { $_[0]->concise($_[1]) }, 0);
222 }
223}
224
8ec8fbef
SM
225sub concise_specials {
226 my($name, $order, @cv_s) = @_;
227 my $i = 1;
228 if ($name eq "BEGIN") {
c0939cee 229 splice(@cv_s, 0, 8); # skip 7 BEGIN blocks in this file. NOW 8 ??
8ec8fbef
SM
230 } elsif ($name eq "CHECK") {
231 pop @cv_s; # skip the CHECK block that calls us
232 }
f95e3c3c
JC
233 for my $cv (@cv_s) {
234 print $walkHandle "$name $i:\n";
8ec8fbef 235 $i++;
c0939cee 236 concise_cv_obj($order, $cv, $name);
8ec8fbef
SM
237 }
238}
239
c99ca59a
SM
240my $start_sym = "\e(0"; # "\cN" sometimes also works
241my $end_sym = "\e(B"; # "\cO" respectively
242
f95e3c3c 243my @tree_decorations =
c99ca59a
SM
244 ([" ", "--", "+-", "|-", "| ", "`-", "-", 1],
245 [" ", "-", "+", "+", "|", "`", "", 0],
246 [" ", map("$start_sym$_$end_sym", "qq", "wq", "tq", "x ", "mq", "q"), 1],
247 [" ", map("$start_sym$_$end_sym", "q", "w", "t", "x", "m"), "", 0],
248 );
78ad9108 249
9e0f9750
JC
250my @render_packs; # collect -stash=<packages>
251
cc02ea56
JC
252sub compileOpts {
253 # set rendering state from options and args
c0939cee
JC
254 my (@options,@args);
255 if (@_) {
256 @options = grep(/^-/, @_);
257 @args = grep(!/^-/, @_);
258 }
c99ca59a 259 for my $o (@options) {
cc02ea56 260 # mode/order
c99ca59a
SM
261 if ($o eq "-basic") {
262 $order = "basic";
263 } elsif ($o eq "-exec") {
264 $order = "exec";
265 } elsif ($o eq "-tree") {
266 $order = "tree";
cc02ea56
JC
267 }
268 # tree-specific
269 elsif ($o eq "-compact") {
c99ca59a
SM
270 $tree_style |= 1;
271 } elsif ($o eq "-loose") {
272 $tree_style &= ~1;
273 } elsif ($o eq "-vt") {
274 $tree_style |= 2;
275 } elsif ($o eq "-ascii") {
276 $tree_style &= ~2;
cc02ea56
JC
277 }
278 # sequence numbering
279 elsif ($o =~ /^-base(\d+)$/) {
c99ca59a
SM
280 $base = $1;
281 } elsif ($o eq "-bigendian") {
282 $big_endian = 1;
283 } elsif ($o eq "-littleendian") {
284 $big_endian = 0;
cc02ea56 285 }
9e0f9750 286 # miscellaneous, presentation
cc02ea56 287 elsif ($o eq "-nobanner") {
724aa791 288 $banner = 0;
cc02ea56
JC
289 } elsif ($o eq "-banner") {
290 $banner = 1;
291 }
292 elsif ($o eq "-main") {
293 $do_main = 1;
294 } elsif ($o eq "-nomain") {
295 $do_main = 0;
f18deeb9
JC
296 } elsif ($o eq "-src") {
297 $show_src = 1;
9e0f9750
JC
298 }
299 elsif ($o =~ /^-stash=(.*)/) {
300 my $pkg = $1;
301 no strict 'refs';
902fde96 302 if (! %{$pkg.'::'}) {
f667a15a
NC
303 eval "require $pkg";
304 } else {
305 require Config;
306 if (!$Config::Config{usedl}
307 && keys %{$pkg.'::'} == 1
308 && $pkg->can('bootstrap')) {
b7b1e41b 309 # It is something that we're statically linked to, but hasn't
f667a15a
NC
310 # yet been used.
311 eval "require $pkg";
312 }
313 }
9e0f9750 314 push @render_packs, $pkg;
724aa791 315 }
cc02ea56 316 # line-style options
724aa791 317 elsif (exists $style{substr($o, 1)}) {
f95e3c3c 318 $stylename = substr($o, 1);
724aa791 319 set_style_standard($stylename);
c99ca59a
SM
320 } else {
321 warn "Option $o unrecognized";
322 }
323 }
cc02ea56
JC
324 return (@args);
325}
326
327sub compile {
328 my (@args) = compileOpts(@_);
c27ea44e 329 return sub {
cc02ea56
JC
330 my @newargs = compileOpts(@_); # accept new rendering options
331 warn "disregarding non-options: @newargs\n" if @newargs;
332
333 for my $objname (@args) {
59910b6d
JC
334 next unless $objname; # skip null args to avoid noisy responses
335
cc02ea56
JC
336 if ($objname eq "BEGIN") {
337 concise_specials("BEGIN", $order,
c0939cee
JC
338 B::begin_av->isa("B::AV") ?
339 B::begin_av->ARRAY : ());
cc02ea56
JC
340 } elsif ($objname eq "INIT") {
341 concise_specials("INIT", $order,
c0939cee
JC
342 B::init_av->isa("B::AV") ?
343 B::init_av->ARRAY : ());
cc02ea56
JC
344 } elsif ($objname eq "CHECK") {
345 concise_specials("CHECK", $order,
c0939cee
JC
346 B::check_av->isa("B::AV") ?
347 B::check_av->ARRAY : ());
676456c2
AG
348 } elsif ($objname eq "UNITCHECK") {
349 concise_specials("UNITCHECK", $order,
350 B::unitcheck_av->isa("B::AV") ?
351 B::unitcheck_av->ARRAY : ());
cc02ea56
JC
352 } elsif ($objname eq "END") {
353 concise_specials("END", $order,
c0939cee
JC
354 B::end_av->isa("B::AV") ?
355 B::end_av->ARRAY : ());
cc02ea56
JC
356 }
357 else {
358 # convert function names to subrefs
cc02ea56
JC
359 if (ref $objname) {
360 print $walkHandle "B::Concise::compile($objname)\n"
361 if $banner;
35f75594
FC
362 concise_subref($order, ($objname)x2);
363 next;
8ec8fbef 364 } else {
cc02ea56 365 $objname = "main::" . $objname unless $objname =~ /::/;
cc02ea56 366 no strict 'refs';
35f75594
FC
367 my $glob = \*$objname;
368 unless (*$glob{CODE} || *$glob{FORMAT}) {
369 print $walkHandle "$objname:\n" if $banner;
c0939cee
JC
370 print $walkHandle "err: unknown function ($objname)\n";
371 return;
372 }
35f75594
FC
373 if (my $objref = *$glob{CODE}) {
374 print $walkHandle "$objname:\n" if $banner;
375 concise_subref($order, $objref, $objname);
376 }
377 if (my $objref = *$glob{FORMAT}) {
378 print $walkHandle "$objname (FORMAT):\n"
379 if $banner;
380 concise_subref($order, $objref, $objname);
381 }
8ec8fbef 382 }
c99ca59a
SM
383 }
384 }
9e0f9750
JC
385 for my $pkg (@render_packs) {
386 no strict 'refs';
387 concise_stashref($order, \%{$pkg.'::'});
388 }
389
390 if (!@args or $do_main or @render_packs) {
f95e3c3c 391 print $walkHandle "main program:\n" if $do_main;
31b49ad4 392 concise_main($order);
c99ca59a 393 }
cc02ea56 394 return @args; # something
c99ca59a
SM
395 }
396}
397
398my %labels;
724aa791 399my $lastnext; # remembers op-chain, used to insert gotos
c99ca59a
SM
400
401my %opclass = ('OP' => "0", 'UNOP' => "1", 'BINOP' => "2", 'LOGOP' => "|",
402 'LISTOP' => "@", 'PMOP' => "/", 'SVOP' => "\$", 'GVOP' => "*",
b46e009d 403 'PVOP' => '"', 'LOOP' => "{", 'COP' => ";", 'PADOP' => "#",
404 'METHOP' => '.');
c99ca59a 405
8ec8fbef 406no warnings 'qw'; # "Possible attempt to put comments..."; use #7
35fc55f1
RH
407my @linenoise =
408 qw'# () sc ( @? 1 $* gv *{ m$ m@ m% m? p/ *$ $ $# & a& pt \\ s\\ rf bl
c99ca59a
SM
409 ` *? <> ?? ?/ r/ c/ // qr s/ /c y/ = @= C sC Cp sp df un BM po +1 +I
410 -1 -I 1+ I+ 1- I- ** * i* / i/ %$ i% x + i+ - i- . " << >> < i<
411 > i> <= i, >= i. == i= != i! <? i? s< s> s, s. s= s! s? b& b^ b| -0 -i
412 ! ~ a2 si cs rd sr e^ lg sq in %x %o ab le ss ve ix ri sf FL od ch cy
413 uf lf uc lc qm @ [f [ @[ eh vl ky dl ex % ${ @{ uk pk st jn ) )[ a@
414 a% sl +] -] [- [+ so rv GS GW MS MW .. f. .f && || ^^ ?: &= |= -> s{ s}
415 v} ca wa di rs ;; ; ;d }{ { } {} f{ it {l l} rt }l }n }r dm }g }e ^o
416 ^c ^| ^# um bm t~ u~ ~d DB db ^s se ^g ^r {w }w pf pr ^O ^K ^R ^W ^d ^v
417 ^e ^t ^k t. fc ic fl .s .p .b .c .l .a .h g1 s1 g2 s2 ?. l? -R -W -X -r
418 -w -x -e -o -O -z -s -M -A -C -S -c -b -f -d -p -l -u -g -k -t -T -B cd
419 co cr u. cm ut r. l@ s@ r@ mD uD oD rD tD sD wD cD f$ w$ p$ sh e$ k$ g3
420 g4 s4 g5 s5 T@ C@ L@ G@ A@ S@ Hg Hc Hr Hw Mg Mc Ms Mr Sg Sc So rq do {e
421 e} {t t} g6 G6 6e g7 G7 7e g8 G8 8e g9 G9 9e 6s 7s 8s 9s 6E 7E 8E 9E Pn
c27ea44e 422 Pu GP SP EP Gn Gg GG SG EG g0 c$ lk t$ ;s n> // /= CO';
c99ca59a
SM
423
424my $chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
425
19e169bf 426sub op_flags { # common flags (see BASOP.op_flags in op.h)
c99ca59a
SM
427 my($x) = @_;
428 my(@v);
429 push @v, "v" if ($x & 3) == 1;
430 push @v, "s" if ($x & 3) == 2;
431 push @v, "l" if ($x & 3) == 3;
432 push @v, "K" if $x & 4;
433 push @v, "P" if $x & 8;
434 push @v, "R" if $x & 16;
435 push @v, "M" if $x & 32;
436 push @v, "S" if $x & 64;
437 push @v, "*" if $x & 128;
438 return join("", @v);
439}
440
441sub base_n {
442 my $x = shift;
443 return "-" . base_n(-$x) if $x < 0;
444 my $str = "";
445 do { $str .= substr($chars, $x % $base, 1) } while $x = int($x / $base);
446 $str = reverse $str if $big_endian;
447 return $str;
448}
449
c27ea44e
SM
450my %sequence_num;
451my $seq_max = 1;
452
f95e3c3c
JC
453sub reset_sequence {
454 # reset the sequence
455 %sequence_num = ();
456 $seq_max = 1;
cc02ea56 457 $lastnext = 0;
f95e3c3c
JC
458}
459
c27ea44e
SM
460sub seq {
461 my($op) = @_;
462 return "-" if not exists $sequence_num{$$op};
463 return base_n($sequence_num{$$op});
464}
c99ca59a
SM
465
466sub walk_topdown {
467 my($op, $sub, $level) = @_;
468 $sub->($op, $level);
469 if ($op->flags & OPf_KIDS) {
470 for (my $kid = $op->first; $$kid; $kid = $kid->sibling) {
471 walk_topdown($kid, $sub, $level + 1);
472 }
473 }
98517ccb 474 if (class($op) eq "PMOP") {
c6e79e55
SM
475 my $maybe_root = $op->pmreplroot;
476 if (ref($maybe_root) and $maybe_root->isa("B::OP")) {
477 # It really is the root of the replacement, not something
478 # else stored here for lack of space elsewhere
479 walk_topdown($maybe_root, $sub, $level + 1);
480 }
c99ca59a
SM
481 }
482}
483
484sub walklines {
485 my($ar, $level) = @_;
486 for my $l (@$ar) {
487 if (ref($l) eq "ARRAY") {
488 walklines($l, $level + 1);
489 } else {
490 $l->concise($level);
491 }
492 }
493}
494
495sub walk_exec {
496 my($top, $level) = @_;
497 my %opsseen;
498 my @lines;
499 my @todo = ([$top, \@lines]);
500 while (@todo and my($op, $targ) = @{shift @todo}) {
501 for (; $$op; $op = $op->next) {
502 last if $opsseen{$$op}++;
503 push @$targ, $op;
504 my $name = $op->name;
62e36f8a 505 if (class($op) eq "LOGOP") {
c99ca59a
SM
506 my $ar = [];
507 push @$targ, $ar;
508 push @todo, [$op->other, $ar];
509 } elsif ($name eq "subst" and $ {$op->pmreplstart}) {
510 my $ar = [];
511 push @$targ, $ar;
512 push @todo, [$op->pmreplstart, $ar];
513 } elsif ($name =~ /^enter(loop|iter)$/) {
35633035
DM
514 $labels{${$op->nextop}} = "NEXT";
515 $labels{${$op->lastop}} = "LAST";
516 $labels{${$op->redoop}} = "REDO";
c99ca59a
SM
517 }
518 }
519 }
520 walklines(\@lines, 0);
521}
522
c27ea44e
SM
523# The structure of this routine is purposely modeled after op.c's peep()
524sub sequence {
525 my($op) = @_;
526 my $oldop = 0;
527 return if class($op) eq "NULL" or exists $sequence_num{$$op};
528 for (; $$op; $op = $op->next) {
529 last if exists $sequence_num{$$op};
530 my $name = $op->name;
1cd6d13a
FC
531 $sequence_num{$$op} = $seq_max++;
532 if (class($op) eq "LOGOP") {
533 sequence($op->other);
534 } elsif (class($op) eq "LOOP") {
535 sequence($op->redoop);
536 sequence( $op->nextop);
537 sequence($op->lastop);
538 } elsif ($name eq "subst" and $ {$op->pmreplstart}) {
539 sequence($op->pmreplstart);
c27ea44e
SM
540 }
541 $oldop = $op;
542 }
543}
544
724aa791 545sub fmt_line { # generate text-line for op.
cc02ea56
JC
546 my($hr, $op, $text, $level) = @_;
547
548 $_->($hr, $op, \$text, \$level, $stylename) for @callbacks;
549
724aa791 550 return '' if $hr->{SKIP}; # suppress line if a callback said so
cc02ea56 551 return '' if $hr->{goto} and $hr->{goto} eq '-'; # no goto nowhere
f95e3c3c 552
cc02ea56 553 # spec: (?(text1#varText2)?)
c99ca59a 554 $text =~ s/\(\?\(([^\#]*?)\#(\w+)([^\#]*?)\)\?\)/
f95e3c3c
JC
555 $hr->{$2} ? $1.$hr->{$2}.$3 : ""/eg;
556
cc02ea56 557 # spec: (x(exec_text;basic_text)x)
c99ca59a 558 $text =~ s/\(x\((.*?);(.*?)\)x\)/$order eq "exec" ? $1 : $2/egs;
cc02ea56
JC
559
560 # spec: (*(text)*)
c99ca59a 561 $text =~ s/\(\*\(([^;]*?)\)\*\)/$1 x $level/egs;
cc02ea56
JC
562
563 # spec: (*(text1;text2)*)
c99ca59a 564 $text =~ s/\(\*\((.*?);(.*?)\)\*\)/$1 x ($level - 1) . $2 x ($level>0)/egs;
cc02ea56
JC
565
566 # convert #Var to tag=>val form: Var\t#var
567 $text =~ s/\#([A-Z][a-z]+)(\d+)?/\t\u$1\t\L#$1$2/gs;
568
569 # spec: #varN
724aa791
JC
570 $text =~ s/\#([a-zA-Z]+)(\d+)/sprintf("%-$2s", $hr->{$1})/eg;
571
cc02ea56
JC
572 $text =~ s/\#([a-zA-Z]+)/$hr->{$1}/eg; # populate #var's
573 $text =~ s/[ \t]*~+[ \t]*/ /g; # squeeze tildes
f18deeb9
JC
574
575 $text = "# $hr->{src}\n$text" if $show_src and $hr->{src};
576
f95e3c3c 577 chomp $text;
efef081e 578 return "$text\n" if $text ne "" and $order ne "tree";
f95e3c3c 579 return $text; # suppress empty lines
c99ca59a
SM
580}
581
f3574cc6
DM
582
583
584# use require rather than use here to avoid disturbing tests that dump
585# BEGIN blocks
586require B::Op_private;
587
588
c99ca59a 589
d5ec2987
NC
590our %hints; # used to display each COP's op_hints values
591
592# strict refs, subs, vars
894ea76b 593@hints{2,512,1024,32,64,128} = ('$', '&', '*', 'x$', 'x&', 'x*');
e1dccc0d
Z
594# integers, locale, bytes
595@hints{1,4,8,16} = ('i', 'l', 'b');
8b850bd5
NC
596# block scope, localise %^H, $^OPEN (in), $^OPEN (out)
597@hints{256,131072,262144,524288} = ('{','%','<','>');
d5ec2987
NC
598# overload new integer, float, binary, string, re
599@hints{4096,8192,16384,32768,65536} = ('I', 'F', 'B', 'S', 'R');
600# taint and eval
601@hints{1048576,2097152} = ('T', 'E');
584420f0
RGS
602# filetest access, UTF-8
603@hints{4194304,8388608} = ('X', 'U');
d5ec2987
NC
604
605sub _flags {
606 my($hash, $x) = @_;
c99ca59a 607 my @s;
d5ec2987
NC
608 for my $flag (sort {$b <=> $a} keys %$hash) {
609 if ($hash->{$flag} and $x & $flag and $x >= $flag) {
c99ca59a 610 $x -= $flag;
d5ec2987 611 push @s, $hash->{$flag};
c99ca59a
SM
612 }
613 }
614 push @s, $x if $x;
615 return join(",", @s);
616}
617
f3574cc6
DM
618# return a string like 'LVINTRO,1' for the op $name with op_private
619# value $x
620
d5ec2987
NC
621sub private_flags {
622 my($name, $x) = @_;
f3574cc6
DM
623 my $entry = $B::Op_private::bits{$name};
624 return $x ? "$x" : '' unless $entry;
625
626 my @flags;
627 my $bit;
628 for ($bit = 7; $bit >= 0; $bit--) {
629 next unless exists $entry->{$bit};
630 my $e = $entry->{$bit};
631 if (ref($e) eq 'HASH') {
632 # bit field
633
634 my ($bitmin, $bitmax, $bitmask, $enum, $label) =
635 @{$e}{qw(bitmin bitmax bitmask enum label)};
636 $bit = $bitmin;
637 next if defined $label && $label eq '-'; # display as raw number
638
639 my $val = $x & $bitmask;
640 $x &= ~$bitmask;
641 $val >>= $bitmin;
642
643 if (defined $enum) {
644 # try to convert numeric $val into symbolic
645 my @enum = @$enum;
646 while (@enum) {
647 my $ix = shift @enum;
648 my $name = shift @enum;
649 my $label = shift @enum;
650 if ($val == $ix) {
651 $val = $label;
652 last;
653 }
654 }
655 }
656 next if $val eq '0'; # don't display anonymous zero values
657 push @flags, defined $label ? "$label=$val" : $val;
658
659 }
660 else {
661 # flag bit
662 my $label = $B::Op_private::labels{$e};
663 next if defined $label && $label eq '-'; # display as raw number
664 if ($x & (1<<$bit)) {
665 $x -= (1<<$bit);
666 push @flags, $label;
667 }
668 }
669 }
670
671 push @flags, $x if $x; # display unknown bits numerically
672 return join ",", @flags;
d5ec2987
NC
673}
674
675sub hints_flags {
676 my($x) = @_;
677 _flags(\%hints, $x);
678}
679
c27ea44e 680sub concise_sv {
2db5ca0a 681 my($sv, $hr, $preferpv) = @_;
c27ea44e 682 $hr->{svclass} = class($sv);
31b49ad4
SM
683 $hr->{svclass} = "UV"
684 if $hr->{svclass} eq "IV" and $sv->FLAGS & SVf_IVisUV;
5b493bdf 685 Carp::cluck("bad concise_sv: $sv") unless $sv and $$sv;
c27ea44e 686 $hr->{svaddr} = sprintf("%#x", $$sv);
50786ba8 687 if ($hr->{svclass} eq "GV" && $sv->isGV_with_GP()) {
c27ea44e 688 my $gv = $sv;
7b696247
FC
689 my $stash = $gv->STASH;
690 if (class($stash) eq "SPECIAL") {
691 $stash = "<none>";
692 }
693 else {
694 $stash = $stash->NAME;
695 }
696 if ($stash eq "main") {
c27ea44e
SM
697 $stash = "";
698 } else {
699 $stash = $stash . "::";
700 }
701 $hr->{svval} = "*$stash" . $gv->SAFENAME;
702 return "*$stash" . $gv->SAFENAME;
703 } else {
4df7f6af
NC
704 if ($] >= 5.011) {
705 while (class($sv) eq "IV" && $sv->FLAGS & SVf_ROK) {
706 $hr->{svval} .= "\\";
707 $sv = $sv->RV;
708 }
709 } else {
710 while (class($sv) eq "RV") {
711 $hr->{svval} .= "\\";
712 $sv = $sv->RV;
713 }
c27ea44e
SM
714 }
715 if (class($sv) eq "SPECIAL") {
40b5b14f 716 $hr->{svval} .= ["Null", "sv_undef", "sv_yes", "sv_no"]->[$$sv];
8d919b0a
FC
717 } elsif ($preferpv
718 && ($sv->FLAGS & SVf_POK || class($sv) eq "REGEXP")) {
2db5ca0a 719 $hr->{svval} .= cstring($sv->PV);
c27ea44e 720 } elsif ($sv->FLAGS & SVf_NOK) {
40b5b14f 721 $hr->{svval} .= $sv->NV;
c27ea44e 722 } elsif ($sv->FLAGS & SVf_IOK) {
31b49ad4 723 $hr->{svval} .= $sv->int_value;
8d919b0a 724 } elsif ($sv->FLAGS & SVf_POK || class($sv) eq "REGEXP") {
40b5b14f 725 $hr->{svval} .= cstring($sv->PV);
31b49ad4
SM
726 } elsif (class($sv) eq "HV") {
727 $hr->{svval} .= 'HASH';
c27ea44e 728 }
cc02ea56
JC
729
730 $hr->{svval} = 'undef' unless defined $hr->{svval};
731 my $out = $hr->{svclass};
732 return $out .= " $hr->{svval}" ;
c27ea44e
SM
733 }
734}
735
f18deeb9
JC
736my %srclines;
737
738sub fill_srclines {
9e0f9750
JC
739 my $fullnm = shift;
740 if ($fullnm eq '-e') {
741 $srclines{$fullnm} = [ $fullnm, "-src not supported for -e" ];
742 return;
6cc5d258 743 }
9e0f9750 744 open (my $fh, '<', $fullnm)
6cc5d258 745 or warn "# $fullnm: $!, (chdirs not supported by this feature yet)\n"
f18deeb9
JC
746 and return;
747 my @l = <$fh>;
748 chomp @l;
9e0f9750
JC
749 unshift @l, $fullnm; # like @{_<$fullnm} in debug, array starts at 1
750 $srclines{$fullnm} = \@l;
f18deeb9
JC
751}
752
c99ca59a
SM
753sub concise_op {
754 my ($op, $level, $format) = @_;
755 my %h;
756 $h{exname} = $h{name} = $op->name;
757 $h{NAME} = uc $h{name};
758 $h{class} = class($op);
759 $h{extarg} = $h{targ} = $op->targ;
760 $h{extarg} = "" unless $h{extarg};
f3574cc6 761 $h{privval} = $op->private;
c51d52ee
FC
762 # for null ops, targ holds the old type
763 my $origname = $h{name} eq "null" && $h{targ}
764 ? substr(ppname($h{targ}), 3)
765 : $h{name};
766 $h{private} = private_flags($origname, $op->private);
f3574cc6
DM
767 if ($op->folded) {
768 $h{private} &&= "$h{private},";
769 $h{private} .= "FOLD";
770 }
771
c51d52ee
FC
772 if ($h{name} ne $origname) { # a null op
773 $h{exname} = "ex-$origname";
c99ca59a 774 $h{extarg} = "";
f3574cc6
DM
775 } elsif ($h{private} =~ /\bREFC\b/) {
776 # targ holds a reference count
777 my $refs = "ref" . ($h{targ} != 1 ? "s" : "");
778 $h{targarglife} = $h{targarg} = "$h{targ} $refs";
c99ca59a 779 } elsif ($h{targ}) {
f3574cc6
DM
780 my $count = $h{name} eq 'padrange'
781 ? ($op->private & $B::Op_private::defines{'OPpPADRANGE_COUNTMASK'})
782 : 1;
a7fd8ef6
DM
783 my (@targarg, @targarglife);
784 for my $i (0..$count-1) {
785 my ($targarg, $targarglife);
786 my $padname = (($curcv->PADLIST->ARRAY)[0]->ARRAY)[$h{targ}+$i];
787 if (defined $padname and class($padname) ne "SPECIAL") {
788 $targarg = $padname->PVX;
789 if ($padname->FLAGS & SVf_FAKE) {
790 # These changes relate to the jumbo closure fix.
791 # See changes 19939 and 20005
792 my $fake = '';
793 $fake .= 'a'
794 if $padname->PARENT_FAKELEX_FLAGS & PAD_FAKELEX_ANON;
795 $fake .= 'm'
796 if $padname->PARENT_FAKELEX_FLAGS & PAD_FAKELEX_MULTI;
797 $fake .= ':' . $padname->PARENT_PAD_INDEX
798 if $curcv->CvFLAGS & CVf_ANON;
799 $targarglife = "$targarg:FAKE:$fake";
800 }
801 else {
802 my $intro = $padname->COP_SEQ_RANGE_LOW - $cop_seq_base;
803 my $finish = int($padname->COP_SEQ_RANGE_HIGH) - $cop_seq_base;
804 $finish = "end" if $finish == 999999999 - $cop_seq_base;
805 $targarglife = "$targarg:$intro,$finish";
806 }
807 } else {
808 $targarglife = $targarg = "t" . ($h{targ}+$i);
127212b2 809 }
a7fd8ef6
DM
810 push @targarg, $targarg;
811 push @targarglife, $targarglife;
c99ca59a 812 }
a7fd8ef6
DM
813 $h{targarg} = join '; ', @targarg;
814 $h{targarglife} = join '; ', @targarglife;
c99ca59a
SM
815 }
816 $h{arg} = "";
817 $h{svclass} = $h{svaddr} = $h{svval} = "";
818 if ($h{class} eq "PMOP") {
2721a2ca 819 my $extra = '';
c99ca59a 820 my $precomp = $op->precomp;
7a9b44b9 821 if (defined $precomp) {
c27ea44e
SM
822 $precomp = cstring($precomp); # Escape literal control sequences
823 $precomp = "/$precomp/";
824 } else {
825 $precomp = "";
7a9b44b9 826 }
2721a2ca
DM
827 if ($op->name eq 'subst') {
828 if (class($op->pmreplstart) ne "NULL") {
829 undef $lastnext;
830 $extra = " replstart->" . seq($op->pmreplstart);
831 }
832 }
833 elsif ($op->name eq 'pushre') {
b2a3cfdd 834 # with C<@stash_array = split(/pat/, str);>,
c6e79e55 835 # *stash_array is stored in /pat/'s pmreplroot.
2721a2ca
DM
836 my $gv = $op->pmreplroot;
837 if (!ref($gv)) {
838 # threaded: the value is actually a pad offset for where
839 # the GV is kept (op_pmtargetoff)
840 if ($gv) {
841 $gv = (($curcv->PADLIST->ARRAY)[1]->ARRAY)[$gv]->NAME;
842 }
843 }
844 else {
845 # unthreaded: its a GV (if it exists)
846 $gv = (ref($gv) eq "B::GV") ? $gv->NAME : undef;
847 }
848 $extra = " => \@$gv" if $gv;
c99ca59a 849 }
2721a2ca 850 $h{arg} = "($precomp$extra)";
bb16bae8 851 } elsif ($h{class} eq "PVOP" and $h{name} !~ '^transr?\z') {
c99ca59a
SM
852 $h{arg} = '("' . $op->pv . '")';
853 $h{svval} = '"' . $op->pv . '"';
854 } elsif ($h{class} eq "COP") {
855 my $label = $op->label;
c3caa09d 856 $h{coplabel} = $label;
c99ca59a
SM
857 $label = $label ? "$label: " : "";
858 my $loc = $op->file;
9e0f9750 859 my $pathnm = $loc;
c99ca59a 860 $loc =~ s[.*/][];
9e0f9750
JC
861 my $ln = $op->line;
862 $loc .= ":$ln";
c99ca59a 863 my($stash, $cseq) = ($op->stash->NAME, $op->cop_seq - $cop_seq_base);
e1dccc0d 864 $h{arg} = "($label$stash $cseq $loc)";
f18deeb9 865 if ($show_src) {
9e0f9750 866 fill_srclines($pathnm) unless exists $srclines{$pathnm};
e9c69003
NC
867 # Would love to retain Jim's use of // but this code needs to be
868 # portable to 5.8.x
869 my $line = $srclines{$pathnm}[$ln];
870 $line = "-src unavailable under -e" unless defined $line;
871 $h{src} = "$ln: $line";
f18deeb9 872 }
c99ca59a
SM
873 } elsif ($h{class} eq "LOOP") {
874 $h{arg} = "(next->" . seq($op->nextop) . " last->" . seq($op->lastop)
875 . " redo->" . seq($op->redoop) . ")";
876 } elsif ($h{class} eq "LOGOP") {
877 undef $lastnext;
878 $h{arg} = "(other->" . seq($op->other) . ")";
a854082c 879 $h{otheraddr} = sprintf("%#x", $ {$op->other});
5b493bdf
JC
880 }
881 elsif ($h{class} eq "SVOP" or $h{class} eq "PADOP") {
6a077020 882 unless ($h{name} eq 'aelemfast' and $op->flags & OPf_SPECIAL) {
5b493bdf
JC
883 my $idx = ($h{class} eq "SVOP") ? $op->targ : $op->padix;
884 if ($h{class} eq "PADOP" or !${$op->sv}) {
885 my $sv = (($curcv->PADLIST->ARRAY)[1]->ARRAY)[$idx];
b46e009d 886 $h{arg} = "[" . concise_sv($sv, \%h, 0) . "]";
6a077020
DM
887 $h{targarglife} = $h{targarg} = "";
888 } else {
b46e009d 889 $h{arg} = "(" . concise_sv($op->sv, \%h, 0) . ")";
6a077020 890 }
c99ca59a
SM
891 }
892 }
b46e009d 893 elsif ($h{class} eq "METHOP") {
894 if ($h{name} eq "method_named") {
895 if (${$op->meth_sv}) {
896 $h{arg} = "(" . concise_sv($op->meth_sv, \%h, 1) . ")";
897 } else {
898 my $sv = (($curcv->PADLIST->ARRAY)[1]->ARRAY)[$op->targ];
899 $h{arg} = "[" . concise_sv($sv, \%h, 1) . "]";
900 $h{targarglife} = $h{targarg} = "";
901 }
902 }
903 }
c99ca59a
SM
904 $h{seq} = $h{hyphseq} = seq($op);
905 $h{seq} = "" if $h{seq} eq "-";
35633035
DM
906 $h{opt} = $op->opt;
907 $h{label} = $labels{$$op};
c99ca59a
SM
908 $h{next} = $op->next;
909 $h{next} = (class($h{next}) eq "NULL") ? "(end)" : seq($h{next});
910 $h{nextaddr} = sprintf("%#x", $ {$op->next});
911 $h{sibaddr} = sprintf("%#x", $ {$op->sibling});
912 $h{firstaddr} = sprintf("%#x", $ {$op->first}) if $op->can("first");
913 $h{lastaddr} = sprintf("%#x", $ {$op->last}) if $op->can("last");
914
915 $h{classsym} = $opclass{$h{class}};
916 $h{flagval} = $op->flags;
917 $h{flags} = op_flags($op->flags);
d5ec2987
NC
918 if ($op->can("hints")) {
919 $h{hintsval} = $op->hints;
920 $h{hints} = hints_flags($h{hintsval});
921 } else {
922 $h{hintsval} = $h{hints} = '';
923 }
c99ca59a 924 $h{addr} = sprintf("%#x", $$op);
c99ca59a
SM
925 $h{typenum} = $op->type;
926 $h{noise} = $linenoise[$op->type];
f95e3c3c 927
cc02ea56 928 return fmt_line(\%h, $op, $format, $level);
c99ca59a
SM
929}
930
931sub B::OP::concise {
932 my($op, $level) = @_;
933 if ($order eq "exec" and $lastnext and $$lastnext != $$op) {
724aa791 934 # insert a 'goto' line
cc02ea56
JC
935 my $synth = {"seq" => seq($lastnext), "class" => class($lastnext),
936 "addr" => sprintf("%#x", $$lastnext),
937 "goto" => seq($lastnext), # simplify goto '-' removal
938 };
939 print $walkHandle fmt_line($synth, $op, $gotofmt, $level+1);
c99ca59a
SM
940 }
941 $lastnext = $op->next;
f95e3c3c 942 print $walkHandle concise_op($op, $level, $format);
c99ca59a
SM
943}
944
31b49ad4
SM
945# B::OP::terse (see Terse.pm) now just calls this
946sub b_terse {
947 my($op, $level) = @_;
948
949 # This isn't necessarily right, but there's no easy way to get
950 # from an OP to the right CV. This is a limitation of the
951 # ->terse() interface style, and there isn't much to do about
952 # it. In particular, we can die in concise_op if the main pad
953 # isn't long enough, or has the wrong kind of entries, compared to
954 # the pad a sub was compiled with. The fix for that would be to
955 # make a backwards compatible "terse" format that never even
956 # looked at the pad, just like the old B::Terse. I don't think
957 # that's worth the effort, though.
958 $curcv = main_cv unless $curcv;
959
960 if ($order eq "exec" and $lastnext and $$lastnext != $$op) {
724aa791 961 # insert a 'goto'
31b49ad4
SM
962 my $h = {"seq" => seq($lastnext), "class" => class($lastnext),
963 "addr" => sprintf("%#x", $$lastnext)};
cc02ea56
JC
964 print # $walkHandle
965 fmt_line($h, $op, $style{"terse"}[1], $level+1);
31b49ad4
SM
966 }
967 $lastnext = $op->next;
cc02ea56
JC
968 print # $walkHandle
969 concise_op($op, $level, $style{"terse"}[0]);
31b49ad4
SM
970}
971
c99ca59a
SM
972sub tree {
973 my $op = shift;
974 my $level = shift;
975 my $style = $tree_decorations[$tree_style];
976 my($space, $single, $kids, $kid, $nokid, $last, $lead, $size) = @$style;
977 my $name = concise_op($op, $level, $treefmt);
978 if (not $op->flags & OPf_KIDS) {
979 return $name . "\n";
980 }
981 my @lines;
982 for (my $kid = $op->first; $$kid; $kid = $kid->sibling) {
983 push @lines, tree($kid, $level+1);
984 }
985 my $i;
986 for ($i = $#lines; substr($lines[$i], 0, 1) eq " "; $i--) {
987 $lines[$i] = $space . $lines[$i];
988 }
989 if ($i > 0) {
990 $lines[$i] = $last . $lines[$i];
991 while ($i-- > 1) {
992 if (substr($lines[$i], 0, 1) eq " ") {
993 $lines[$i] = $nokid . $lines[$i];
994 } else {
f95e3c3c 995 $lines[$i] = $kid . $lines[$i];
c99ca59a
SM
996 }
997 }
998 $lines[$i] = $kids . $lines[$i];
999 } else {
1000 $lines[0] = $single . $lines[0];
1001 }
1002 return("$name$lead" . shift @lines,
1003 map(" " x (length($name)+$size) . $_, @lines));
1004}
1005
213a1a26
SM
1006# *** Warning: fragile kludge ahead ***
1007# Because the B::* modules run in the same interpreter as the code
2814eb74
PJ
1008# they're compiling, their presence tends to distort the view we have of
1009# the code we're looking at. In particular, perl gives sequence numbers
1010# to COPs. If the program we're looking at were run on its own, this
1011# would start at 1. Because all of B::Concise and all the modules it
1012# uses are compiled first, though, by the time we get to the user's
1013# program the sequence number is already pretty high, which could be
1014# distracting if you're trying to tell OPs apart. Therefore we'd like to
1015# subtract an offset from all the sequence numbers we display, to
1016# restore the simpler view of the world. The trick is to know what that
1017# offset will be, when we're still compiling B::Concise! If we
213a1a26 1018# hardcoded a value, it would have to change every time B::Concise or
2814eb74
PJ
1019# other modules we use do. To help a little, what we do here is compile
1020# a little code at the end of the module, and compute the base sequence
1021# number for the user's program as being a small offset later, so all we
1022# have to worry about are changes in the offset.
7252851f
NC
1023
1024# [For 5.8.x and earlier perl is generating sequence numbers for all ops,
1025# and using them to reference labels]
1026
1027
213a1a26
SM
1028# When you say "perl -MO=Concise -e '$a'", the output should look like:
1029
1030# 4 <@> leave[t1] vKP/REFC ->(end)
1031# 1 <0> enter ->2
1032 #^ smallest OP sequence number should be 1
1033# 2 <;> nextstate(main 1 -e:1) v ->3
1034 # ^ smallest COP sequence number should be 1
1035# - <1> ex-rv2sv vK/1 ->4
1036# 3 <$> gvsv(*a) s ->4
1037
c27ea44e
SM
1038# If the second of the marked numbers there isn't 1, it means you need
1039# to update the corresponding magic number in the next line.
1040# Remember, this needs to stay the last things in the module.
e69a2255 1041
c27ea44e 1042# Why is this different for MacOS? Does it matter?
8ec8fbef 1043my $cop_seq_mnum = $^O eq 'MacOS' ? 12 : 11;
e69a2255 1044$cop_seq_base = svref_2object(eval 'sub{0;}')->START->cop_seq + $cop_seq_mnum;
c99ca59a
SM
1045
10461;
1047
1048__END__
1049
1050=head1 NAME
1051
1052B::Concise - Walk Perl syntax tree, printing concise info about ops
1053
1054=head1 SYNOPSIS
1055
1056 perl -MO=Concise[,OPTIONS] foo.pl
1057
78ad9108
PJ
1058 use B::Concise qw(set_style add_callback);
1059
c99ca59a
SM
1060=head1 DESCRIPTION
1061
1062This compiler backend prints the internal OPs of a Perl program's syntax
1063tree in one of several space-efficient text formats suitable for debugging
1064the inner workings of perl or other compiler backends. It can print OPs in
1065the order they appear in the OP tree, in the order they will execute, or
1066in a text approximation to their tree structure, and the format of the
3c4b39be 1067information displayed is customizable. Its function is similar to that of
c99ca59a
SM
1068perl's B<-Dx> debugging flag or the B<B::Terse> module, but it is more
1069sophisticated and flexible.
1070
f8a679e6
RGS
1071=head1 EXAMPLE
1072
f9f861ec
JC
1073Here's two outputs (or 'renderings'), using the -exec and -basic
1074(i.e. default) formatting conventions on the same code snippet.
19e169bf
JC
1075
1076 % perl -MO=Concise,-exec -e '$a = $b + 42'
1077 1 <0> enter
1078 2 <;> nextstate(main 1 -e:1) v
1079 3 <#> gvsv[*b] s
1080 4 <$> const[IV 42] s
1081 * 5 <2> add[t3] sK/2
1082 6 <#> gvsv[*a] s
1083 7 <2> sassign vKS/2
1084 8 <@> leave[1 ref] vKP/REFC
1085
f9f861ec
JC
1086In this -exec rendering, each opcode is executed in the order shown.
1087The add opcode, marked with '*', is discussed in more detail.
19e169bf
JC
1088
1089The 1st column is the op's sequence number, starting at 1, and is
f9f861ec
JC
1090displayed in base 36 by default. Here they're purely linear; the
1091sequences are very helpful when looking at code with loops and
1092branches.
19e169bf
JC
1093
1094The symbol between angle brackets indicates the op's type, for
1095example; <2> is a BINOP, <@> a LISTOP, and <#> is a PADOP, which is
1096used in threaded perls. (see L</"OP class abbreviations">).
1097
f9f861ec 1098The opname, as in B<'add[t1]'>, may be followed by op-specific
19e169bf
JC
1099information in parentheses or brackets (ex B<'[t1]'>).
1100
f9f861ec 1101The op-flags (ex B<'sK/2'>) are described in (L</"OP flags
19e169bf 1102abbreviations">).
f8a679e6
RGS
1103
1104 % perl -MO=Concise -e '$a = $b + 42'
8ec8fbef 1105 8 <@> leave[1 ref] vKP/REFC ->(end)
f8a679e6
RGS
1106 1 <0> enter ->2
1107 2 <;> nextstate(main 1 -e:1) v ->3
1108 7 <2> sassign vKS/2 ->8
19e169bf 1109 * 5 <2> add[t1] sK/2 ->6
f8a679e6
RGS
1110 - <1> ex-rv2sv sK/1 ->4
1111 3 <$> gvsv(*b) s ->4
1112 4 <$> const(IV 42) s ->5
1113 - <1> ex-rv2sv sKRM*/1 ->7
1114 6 <$> gvsv(*a) s ->7
1115
19e169bf
JC
1116The default rendering is top-down, so they're not in execution order.
1117This form reflects the way the stack is used to parse and evaluate
1118expressions; the add operates on the two terms below it in the tree.
f8a679e6 1119
19e169bf
JC
1120Nullops appear as C<ex-opname>, where I<opname> is an op that has been
1121optimized away by perl. They're displayed with a sequence-number of
1122'-', because they are not executed (they don't appear in previous
1123example), they're printed here because they reflect the parse.
f8a679e6 1124
19e169bf
JC
1125The arrow points to the sequence number of the next op; they're not
1126displayed in -exec mode, for obvious reasons.
f8a679e6 1127
19e169bf
JC
1128Note that because this rendering was done on a non-threaded perl, the
1129PADOPs in the previous examples are now SVOPs, and some (but not all)
1130of the square brackets have been replaced by round ones. This is a
1131subtle feature to provide some visual distinction between renderings
1132on threaded and un-threaded perls.
f8a679e6 1133
f8a679e6 1134
c99ca59a
SM
1135=head1 OPTIONS
1136
1137Arguments that don't start with a hyphen are taken to be the names of
710ba574
FC
1138subroutines or formats to render; if no
1139such functions are specified, the main
9e0f9750
JC
1140body of the program (outside any subroutines, and not including use'd
1141or require'd files) is rendered. Passing C<BEGIN>, C<UNITCHECK>,
1142C<CHECK>, C<INIT>, or C<END> will cause all of the corresponding
1143special blocks to be printed. Arguments must follow options.
c99ca59a 1144
724aa791
JC
1145Options affect how things are rendered (ie printed). They're presented
1146here by their visual effect, 1st being strongest. They're grouped
1147according to how they interrelate; within each group the options are
1148mutually exclusive (unless otherwise stated).
1149
1150=head2 Options for Opcode Ordering
1151
1152These options control the 'vertical display' of opcodes. The display
1153'order' is also called 'mode' elsewhere in this document.
1154
c99ca59a
SM
1155=over 4
1156
1157=item B<-basic>
1158
1159Print OPs in the order they appear in the OP tree (a preorder
1160traversal, starting at the root). The indentation of each OP shows its
19e169bf
JC
1161level in the tree, and the '->' at the end of the line indicates the
1162next opcode in execution order. This mode is the default, so the flag
1163is included simply for completeness.
c99ca59a
SM
1164
1165=item B<-exec>
1166
1167Print OPs in the order they would normally execute (for the majority
1168of constructs this is a postorder traversal of the tree, ending at the
1169root). In most cases the OP that usually follows a given OP will
1170appear directly below it; alternate paths are shown by indentation. In
1171cases like loops when control jumps out of a linear path, a 'goto'
1172line is generated.
1173
1174=item B<-tree>
1175
1176Print OPs in a text approximation of a tree, with the root of the tree
1177at the left and 'left-to-right' order of children transformed into
1178'top-to-bottom'. Because this mode grows both to the right and down,
1179it isn't suitable for large programs (unless you have a very wide
1180terminal).
1181
724aa791
JC
1182=back
1183
1184=head2 Options for Line-Style
1185
1186These options select the line-style (or just style) used to render
1187each opcode, and dictates what info is actually printed into each line.
1188
1189=over 4
1190
1191=item B<-concise>
1192
1193Use the author's favorite set of formatting conventions. This is the
1194default, of course.
1195
1196=item B<-terse>
1197
1198Use formatting conventions that emulate the output of B<B::Terse>. The
1199basic mode is almost indistinguishable from the real B<B::Terse>, and the
1200exec mode looks very similar, but is in a more logical order and lacks
1201curly brackets. B<B::Terse> doesn't have a tree mode, so the tree mode
1202is only vaguely reminiscent of B<B::Terse>.
1203
1204=item B<-linenoise>
1205
1206Use formatting conventions in which the name of each OP, rather than being
1207written out in full, is represented by a one- or two-character abbreviation.
1208This is mainly a joke.
1209
1210=item B<-debug>
1211
1212Use formatting conventions reminiscent of B<B::Debug>; these aren't
1213very concise at all.
1214
1215=item B<-env>
1216
1217Use formatting conventions read from the environment variables
1218C<B_CONCISE_FORMAT>, C<B_CONCISE_GOTO_FORMAT>, and C<B_CONCISE_TREE_FORMAT>.
1219
1220=back
1221
1222=head2 Options for tree-specific formatting
1223
1224=over 4
1225
c99ca59a
SM
1226=item B<-compact>
1227
1228Use a tree format in which the minimum amount of space is used for the
1229lines connecting nodes (one character in most cases). This squeezes out
1230a few precious columns of screen real estate.
1231
1232=item B<-loose>
1233
1234Use a tree format that uses longer edges to separate OP nodes. This format
1235tends to look better than the compact one, especially in ASCII, and is
1236the default.
1237
1238=item B<-vt>
1239
1240Use tree connecting characters drawn from the VT100 line-drawing set.
1241This looks better if your terminal supports it.
1242
1243=item B<-ascii>
1244
1245Draw the tree with standard ASCII characters like C<+> and C<|>. These don't
1246look as clean as the VT100 characters, but they'll work with almost any
1247terminal (or the horizontal scrolling mode of less(1)) and are suitable
1248for text documentation or email. This is the default.
1249
724aa791 1250=back
c99ca59a 1251
724aa791
JC
1252These are pairwise exclusive, i.e. compact or loose, vt or ascii.
1253
1254=head2 Options controlling sequence numbering
1255
1256=over 4
c99ca59a
SM
1257
1258=item B<-base>I<n>
1259
1260Print OP sequence numbers in base I<n>. If I<n> is greater than 10, the
1261digit for 11 will be 'a', and so on. If I<n> is greater than 36, the digit
1262for 37 will be 'A', and so on until 62. Values greater than 62 are not
1263currently supported. The default is 36.
1264
1265=item B<-bigendian>
1266
1267Print sequence numbers with the most significant digit first. This is the
1268usual convention for Arabic numerals, and the default.
1269
1270=item B<-littleendian>
1271
1c2e8cca 1272Print sequence numbers with the least significant digit first. This is
724aa791 1273obviously mutually exclusive with bigendian.
c99ca59a 1274
724aa791 1275=back
c99ca59a 1276
724aa791 1277=head2 Other options
c99ca59a 1278
f18deeb9
JC
1279=over 4
1280
1281=item B<-src>
1282
e6665613
JC
1283With this option, the rendering of each statement (starting with the
1284nextstate OP) will be preceded by the 1st line of source code that
1285generates it. For example:
f18deeb9
JC
1286
1287 1 <0> enter
1288 # 1: my $i;
1289 2 <;> nextstate(main 1 junk.pl:1) v:{
1290 3 <0> padsv[$i:1,10] vM/LVINTRO
1291 # 3: for $i (0..9) {
1292 4 <;> nextstate(main 3 junk.pl:3) v:{
1293 5 <0> pushmark s
1294 6 <$> const[IV 0] s
1295 7 <$> const[IV 9] s
1296 8 <{> enteriter(next->j last->m redo->9)[$i:1,10] lKS
1297 k <0> iter s
1298 l <|> and(other->9) vK/1
1299 # 4: print "line ";
1300 9 <;> nextstate(main 2 junk.pl:4) v
1301 a <0> pushmark s
1302 b <$> const[PV "line "] s
1303 c <@> print vK
1304 # 5: print "$i\n";
e6665613 1305 ...
f18deeb9 1306
9e0f9750
JC
1307=item B<-stash="somepackage">
1308
1309With this, "somepackage" will be required, then the stash is
1310inspected, and each function is rendered.
1311
f18deeb9
JC
1312=back
1313
1314The following options are pairwise exclusive.
cc02ea56 1315
724aa791 1316=over 4
c99ca59a 1317
724aa791 1318=item B<-main>
c99ca59a 1319
724aa791 1320Include the main program in the output, even if subroutines were also
cc02ea56
JC
1321specified. This rendering is normally suppressed when a subroutine
1322name or reference is given.
1323
1324=item B<-nomain>
1325
1326This restores the default behavior after you've changed it with '-main'
1327(it's not normally needed). If no subroutine name/ref is given, main is
1328rendered, regardless of this flag.
1329
1330=item B<-nobanner>
1331
1332Renderings usually include a banner line identifying the function name
1333or stringified subref. This suppresses the printing of the banner.
1334
1335TBC: Remove the stringified coderef; while it provides a 'cookie' for
1336each function rendered, the cookies used should be 1,2,3.. not a
1337random hex-address. It also complicates string comparison of two
1338different trees.
c99ca59a 1339
724aa791 1340=item B<-banner>
c99ca59a 1341
cc02ea56
JC
1342restores default banner behavior.
1343
1344=item B<-banneris> => subref
1345
1346TBC: a hookpoint (and an option to set it) for a user-supplied
1347function to produce a banner appropriate for users needs. It's not
1348ideal, because the rendering-state variables, which are a natural
1349candidate for use in concise.t, are unavailable to the user.
c99ca59a 1350
724aa791 1351=back
c99ca59a 1352
724aa791 1353=head2 Option Stickiness
c99ca59a 1354
724aa791
JC
1355If you invoke Concise more than once in a program, you should know that
1356the options are 'sticky'. This means that the options you provide in
1357the first call will be remembered for the 2nd call, unless you
1358re-specify or change them.
c99ca59a 1359
cc02ea56
JC
1360=head1 ABBREVIATIONS
1361
1362The concise style uses symbols to convey maximum info with minimal
1363clutter (like hex addresses). With just a little practice, you can
1364start to see the flowers, not just the branches, in the trees.
1365
1366=head2 OP class abbreviations
1367
1368These symbols appear before the op-name, and indicate the
1369B:: namespace that represents the ops in your Perl code.
1370
1371 0 OP (aka BASEOP) An OP with no children
1372 1 UNOP An OP with one child
1373 2 BINOP An OP with two children
1374 | LOGOP A control branch OP
1375 @ LISTOP An OP that could have lots of children
1376 / PMOP An OP with a regular expression
1377 $ SVOP An OP with an SV
1378 " PVOP An OP with a string
1379 { LOOP An OP that holds pointers for a loop
1380 ; COP An OP that marks the start of a statement
1381 # PADOP An OP with a GV on the pad
b46e009d 1382 . METHOP An OP with method call info
cc02ea56
JC
1383
1384=head2 OP flags abbreviations
1385
19e169bf
JC
1386OP flags are either public or private. The public flags alter the
1387behavior of each opcode in consistent ways, and are represented by 0
1388or more single characters.
cc02ea56
JC
1389
1390 v OPf_WANT_VOID Want nothing (void context)
1391 s OPf_WANT_SCALAR Want single value (scalar context)
1392 l OPf_WANT_LIST Want list of any length (list context)
19e169bf 1393 Want is unknown
cc02ea56
JC
1394 K OPf_KIDS There is a firstborn child.
1395 P OPf_PARENS This operator was parenthesized.
1396 (Or block needs explicit scope entry.)
1397 R OPf_REF Certified reference.
1398 (Return container, not containee).
1399 M OPf_MOD Will modify (lvalue).
1400 S OPf_STACKED Some arg is arriving on the stack.
1401 * OPf_SPECIAL Do something weird for this op (see op.h)
1402
19e169bf
JC
1403Private flags, if any are set for an opcode, are displayed after a '/'
1404
1405 8 <@> leave[1 ref] vKP/REFC ->(end)
1406 7 <2> sassign vKS/2 ->8
1407
1408They're opcode specific, and occur less often than the public ones, so
1409they're represented by short mnemonics instead of single-chars; see
f3574cc6 1410B::Op_private and F<regen/op_private> for more details.
19e169bf 1411
c99ca59a
SM
1412=head1 FORMATTING SPECIFICATIONS
1413
724aa791
JC
1414For each line-style ('concise', 'terse', 'linenoise', etc.) there are
14153 format-specs which control how OPs are rendered.
1416
1417The first is the 'default' format, which is used in both basic and exec
1418modes to print all opcodes. The 2nd, goto-format, is used in exec
1419mode when branches are encountered. They're not real opcodes, and are
1420inserted to look like a closing curly brace. The tree-format is tree
1421specific.
1422
cc02ea56
JC
1423When a line is rendered, the correct format-spec is copied and scanned
1424for the following items; data is substituted in, and other
1425manipulations like basic indenting are done, for each opcode rendered.
1426
1427There are 3 kinds of items that may be populated; special patterns,
1428#vars, and literal text, which is copied verbatim. (Yes, it's a set
1429of s///g steps.)
1430
1431=head2 Special Patterns
1432
1433These items are the primitives used to perform indenting, and to
1434select text from amongst alternatives.
c99ca59a
SM
1435
1436=over 4
1437
1438=item B<(x(>I<exec_text>B<;>I<basic_text>B<)x)>
1439
1440Generates I<exec_text> in exec mode, or I<basic_text> in basic mode.
1441
1442=item B<(*(>I<text>B<)*)>
1443
1444Generates one copy of I<text> for each indentation level.
1445
1446=item B<(*(>I<text1>B<;>I<text2>B<)*)>
1447
1448Generates one fewer copies of I<text1> than the indentation level, followed
1449by one copy of I<text2> if the indentation level is more than 0.
1450
1451=item B<(?(>I<text1>B<#>I<var>I<Text2>B<)?)>
1452
1453If the value of I<var> is true (not empty or zero), generates the
1454value of I<var> surrounded by I<text1> and I<Text2>, otherwise
1455nothing.
1456
cc02ea56
JC
1457=item B<~>
1458
1459Any number of tildes and surrounding whitespace will be collapsed to
1460a single space.
1461
1462=back
1463
1464=head2 # Variables
1465
1466These #vars represent opcode properties that you may want as part of
1467your rendering. The '#' is intended as a private sigil; a #var's
1468value is interpolated into the style-line, much like "read $this".
1469
1470These vars take 3 forms:
1471
1472=over 4
1473
c99ca59a
SM
1474=item B<#>I<var>
1475
cc02ea56
JC
1476A property named 'var' is assumed to exist for the opcodes, and is
1477interpolated into the rendering.
c99ca59a
SM
1478
1479=item B<#>I<var>I<N>
1480
cc02ea56
JC
1481Generates the value of I<var>, left justified to fill I<N> spaces.
1482Note that this means while you can have properties 'foo' and 'foo2',
1483you cannot render 'foo2', but you could with 'foo2a'. You would be
1484wise not to rely on this behavior going forward ;-)
c99ca59a 1485
cc02ea56 1486=item B<#>I<Var>
c99ca59a 1487
cc02ea56
JC
1488This ucfirst form of #var generates a tag-value form of itself for
1489display; it converts '#Var' into a 'Var => #var' style, which is then
1490handled as described above. (Imp-note: #Vars cannot be used for
1491conditional-fills, because the => #var transform is done after the check
1492for #Var's value).
c99ca59a
SM
1493
1494=back
1495
cc02ea56
JC
1496The following variables are 'defined' by B::Concise; when they are
1497used in a style, their respective values are plugged into the
1498rendering of each opcode.
1499
1500Only some of these are used by the standard styles, the others are
1501provided for you to delve into optree mechanics, should you wish to
1502add a new style (see L</add_style> below) that uses them. You can
00baac8f 1503also add new ones using L</add_callback>.
c99ca59a
SM
1504
1505=over 4
1506
1507=item B<#addr>
1508
cc02ea56 1509The address of the OP, in hexadecimal.
c99ca59a
SM
1510
1511=item B<#arg>
1512
1513The OP-specific information of the OP (such as the SV for an SVOP, the
cc02ea56 1514non-local exit pointers for a LOOP, etc.) enclosed in parentheses.
c99ca59a
SM
1515
1516=item B<#class>
1517
1518The B-determined class of the OP, in all caps.
1519
f8a679e6 1520=item B<#classsym>
c99ca59a
SM
1521
1522A single symbol abbreviating the class of the OP.
1523
c3caa09d
SM
1524=item B<#coplabel>
1525
1526The label of the statement or block the OP is the start of, if any.
1527
c99ca59a
SM
1528=item B<#exname>
1529
1530The name of the OP, or 'ex-foo' if the OP is a null that used to be a foo.
1531
1532=item B<#extarg>
1533
1534The target of the OP, or nothing for a nulled OP.
1535
1536=item B<#firstaddr>
1537
19e169bf 1538The address of the OP's first child, in hexadecimal.
c99ca59a
SM
1539
1540=item B<#flags>
1541
1542The OP's flags, abbreviated as a series of symbols.
1543
1544=item B<#flagval>
1545
1546The numeric value of the OP's flags.
1547
d5ec2987
NC
1548=item B<#hints>
1549
1550The COP's hint flags, rendered with abbreviated names if possible. An empty
4f948f3a
RGS
1551string if this is not a COP. Here are the symbols used:
1552
1553 $ strict refs
1554 & strict subs
1555 * strict vars
d1718a7c
FC
1556 x$ explicit use/no strict refs
1557 x& explicit use/no strict subs
1558 x* explicit use/no strict vars
4f948f3a
RGS
1559 i integers
1560 l locale
1561 b bytes
4f948f3a
RGS
1562 { block scope
1563 % localise %^H
1564 < open in
1565 > open out
1566 I overload int
1567 F overload float
1568 B overload binary
1569 S overload string
1570 R overload re
1571 T taint
1572 E eval
1573 X filetest access
1574 U utf-8
d5ec2987
NC
1575
1576=item B<#hintsval>
1577
1578The numeric value of the COP's hint flags, or an empty string if this is not
1579a COP.
1580
f8a679e6 1581=item B<#hyphseq>
c99ca59a
SM
1582
1583The sequence number of the OP, or a hyphen if it doesn't have one.
1584
1585=item B<#label>
1586
1587'NEXT', 'LAST', or 'REDO' if the OP is a target of one of those in exec
1588mode, or empty otherwise.
1589
1590=item B<#lastaddr>
1591
19e169bf 1592The address of the OP's last child, in hexadecimal.
c99ca59a
SM
1593
1594=item B<#name>
1595
1596The OP's name.
1597
1598=item B<#NAME>
1599
1600The OP's name, in all caps.
1601
1602=item B<#next>
1603
1604The sequence number of the OP's next OP.
1605
1606=item B<#nextaddr>
1607
19e169bf 1608The address of the OP's next OP, in hexadecimal.
c99ca59a
SM
1609
1610=item B<#noise>
1611
c27ea44e 1612A one- or two-character abbreviation for the OP's name.
c99ca59a
SM
1613
1614=item B<#private>
1615
1616The OP's private flags, rendered with abbreviated names if possible.
1617
1618=item B<#privval>
1619
1620The numeric value of the OP's private flags.
1621
1622=item B<#seq>
1623
2814eb74
PJ
1624The sequence number of the OP. Note that this is a sequence number
1625generated by B::Concise.
c99ca59a 1626
7252851f
NC
1627=item B<#seqnum>
1628
16295.8.x and earlier only. 5.9 and later do not provide this.
1630
1631The real sequence number of the OP, as a regular number and not adjusted
1632to be relative to the start of the real program. (This will generally be
1633a fairly large number because all of B<B::Concise> is compiled before
1634your program is).
1635
2814eb74 1636=item B<#opt>
c99ca59a 1637
b84c7839 1638Whether or not the op has been optimized by the peephole optimizer.
2814eb74 1639
7252851f
NC
1640Only available in 5.9 and later.
1641
c99ca59a
SM
1642=item B<#sibaddr>
1643
19e169bf 1644The address of the OP's next youngest sibling, in hexadecimal.
c99ca59a
SM
1645
1646=item B<#svaddr>
1647
19e169bf 1648The address of the OP's SV, if it has an SV, in hexadecimal.
c99ca59a
SM
1649
1650=item B<#svclass>
1651
1652The class of the OP's SV, if it has one, in all caps (e.g., 'IV').
1653
1654=item B<#svval>
1655
1656The value of the OP's SV, if it has one, in a short human-readable format.
1657
1658=item B<#targ>
1659
1660The numeric value of the OP's targ.
1661
1662=item B<#targarg>
1663
1664The name of the variable the OP's targ refers to, if any, otherwise the
1665letter t followed by the OP's targ in decimal.
1666
1667=item B<#targarglife>
1668
1669Same as B<#targarg>, but followed by the COP sequence numbers that delimit
1670the variable's lifetime (or 'end' for a variable in an open scope) for a
1671variable.
1672
1673=item B<#typenum>
1674
1675The numeric value of the OP's type, in decimal.
1676
1677=back
1678
f9f861ec
JC
1679=head1 One-Liner Command tips
1680
1681=over 4
1682
1683=item perl -MO=Concise,bar foo.pl
1684
1685Renders only bar() from foo.pl. To see main, drop the ',bar'. To see
1686both, add ',-main'
1687
1688=item perl -MDigest::MD5=md5 -MO=Concise,md5 -e1
1689
1690Identifies md5 as an XS function. The export is needed so that BC can
1691find it in main.
1692
1693=item perl -MPOSIX -MO=Concise,_POSIX_ARG_MAX -e1
1694
1695Identifies _POSIX_ARG_MAX as a constant sub, optimized to an IV.
1696Although POSIX isn't entirely consistent across platforms, this is
1697likely to be present in virtually all of them.
1698
1699=item perl -MPOSIX -MO=Concise,a -e 'print _POSIX_SAVED_IDS'
1700
1701This renders a print statement, which includes a call to the function.
1702It's identical to rendering a file with a use call and that single
1703statement, except for the filename which appears in the nextstate ops.
1704
1705=item perl -MPOSIX -MO=Concise,a -e 'sub a{_POSIX_SAVED_IDS}'
1706
1707This is B<very> similar to previous, only the first two ops differ. This
1708subroutine rendering is more representative, insofar as a single main
1709program will have many subs.
1710
6cc5d258
JC
1711=item perl -MB::Concise -e 'B::Concise::compile("-exec","-src", \%B::Concise::)->()'
1712
1713This renders all functions in the B::Concise package with the source
1714lines. It eschews the O framework so that the stashref can be passed
9e0f9750
JC
1715directly to B::Concise::compile(). See -stash option for a more
1716convenient way to render a package.
f9f861ec 1717
d5e42f17 1718=back
f9f861ec 1719
78ad9108
PJ
1720=head1 Using B::Concise outside of the O framework
1721
cc02ea56
JC
1722The common (and original) usage of B::Concise was for command-line
1723renderings of simple code, as given in EXAMPLE. But you can also use
1724B<B::Concise> from your code, and call compile() directly, and
724aa791 1725repeatedly. By doing so, you can avoid the compile-time only
cc02ea56
JC
1726operation of O.pm, and even use the debugger to step through
1727B::Concise::compile() itself.
f95e3c3c 1728
cc02ea56
JC
1729Once you're doing this, you may alter Concise output by adding new
1730rendering styles, and by optionally adding callback routines which
1731populate new variables, if such were referenced from those (just
1732added) styles.
f95e3c3c 1733
724aa791 1734=head2 Example: Altering Concise Renderings
78ad9108
PJ
1735
1736 use B::Concise qw(set_style add_callback);
cc02ea56 1737 add_style($yourStyleName => $defaultfmt, $gotofmt, $treefmt);
78ad9108 1738 add_callback
f95e3c3c
JC
1739 ( sub {
1740 my ($h, $op, $format, $level, $stylename) = @_;
78ad9108 1741 $h->{variable} = some_func($op);
cc02ea56
JC
1742 });
1743 $walker = B::Concise::compile(@options,@subnames,@subrefs);
1744 $walker->();
78ad9108 1745
f95e3c3c
JC
1746=head2 set_style()
1747
724aa791
JC
1748B<set_style> accepts 3 arguments, and updates the three format-specs
1749comprising a line-style (basic-exec, goto, tree). It has one minor
1750drawback though; it doesn't register the style under a new name. This
1751can become an issue if you render more than once and switch styles.
1752Thus you may prefer to use add_style() and/or set_style_standard()
1753instead.
1754
1755=head2 set_style_standard($name)
1756
1757This restores one of the standard line-styles: C<terse>, C<concise>,
1758C<linenoise>, C<debug>, C<env>, into effect. It also accepts style
1759names previously defined with add_style().
f95e3c3c 1760
345e2394 1761=head2 add_style ()
78ad9108 1762
f95e3c3c
JC
1763This subroutine accepts a new style name and three style arguments as
1764above, and creates, registers, and selects the newly named style. It is
1765an error to re-add a style; call set_style_standard() to switch between
1766several styles.
1767
345e2394 1768=head2 add_callback ()
f95e3c3c 1769
19e169bf
JC
1770If your newly minted styles refer to any new #variables, you'll need
1771to define a callback subroutine that will populate (or modify) those
1772variables. They are then available for use in the style you've
1773chosen.
f95e3c3c
JC
1774
1775The callbacks are called for each opcode visited by Concise, in the
1776same order as they are added. Each subroutine is passed five
1777parameters.
1778
1779 1. A hashref, containing the variable names and values which are
1780 populated into the report-line for the op
1781 2. the op, as a B<B::OP> object
1782 3. a reference to the format string
1783 4. the formatting (indent) level
1784 5. the selected stylename
78ad9108
PJ
1785
1786To define your own variables, simply add them to the hash, or change
1787existing values if you need to. The level and format are passed in as
1788references to scalars, but it is unlikely that they will need to be
1789changed or even used.
1790
724aa791 1791=head2 Running B::Concise::compile()
f95e3c3c
JC
1792
1793B<compile> accepts options as described above in L</OPTIONS>, and
1794arguments, which are either coderefs, or subroutine names.
1795
cc02ea56
JC
1796It constructs and returns a $treewalker coderef, which when invoked,
1797traverses, or walks, and renders the optrees of the given arguments to
1798STDOUT. You can reuse this, and can change the rendering style used
1799each time; thereafter the coderef renders in the new style.
f95e3c3c
JC
1800
1801B<walk_output> lets you change the print destination from STDOUT to
19e169bf
JC
1802another open filehandle, or into a string passed as a ref (unless
1803you've built perl with -Uuseperlio).
f95e3c3c 1804
555bd962
BG
1805 my $walker = B::Concise::compile('-terse','aFuncName', \&aSubRef); # 1
1806 walk_output(\my $buf);
1807 $walker->(); # 1 renders -terse
1808 set_style_standard('concise'); # 2
1809 $walker->(); # 2 renders -concise
1810 $walker->(@new); # 3 renders whatever
1811 print "3 different renderings: terse, concise, and @new: $buf\n";
cc02ea56
JC
1812
1813When $walker is called, it traverses the subroutines supplied when it
1814was created, and renders them using the current style. You can change
1815the style afterwards in several different ways:
1816
1817 1. call C<compile>, altering style or mode/order
1818 2. call C<set_style_standard>
1819 3. call $walker, passing @new options
1820
1821Passing new options to the $walker is the easiest way to change
1822amongst any pre-defined styles (the ones you add are automatically
1823recognized as options), and is the only way to alter rendering order
1824without calling compile again. Note however that rendering state is
1825still shared amongst multiple $walker objects, so they must still be
1826used in a coordinated manner.
f95e3c3c
JC
1827
1828=head2 B::Concise::reset_sequence()
1829
1830This function (not exported) lets you reset the sequence numbers (note
1831that they're numbered arbitrarily, their goal being to be human
1832readable). Its purpose is mostly to support testing, i.e. to compare
1833the concise output from two identical anonymous subroutines (but
1834different instances). Without the reset, B::Concise, seeing that
1835they're separate optrees, generates different sequence numbers in
1836the output.
1837
1838=head2 Errors
1839
9a3b3024
JC
1840Errors in rendering (non-existent function-name, non-existent coderef)
1841are written to the STDOUT, or wherever you've set it via
1842walk_output().
31b49ad4 1843
9a3b3024
JC
1844Errors using the various *style* calls, and bad args to walk_output(),
1845result in die(). Use an eval if you wish to catch these errors and
1846continue processing.
78ad9108 1847
c99ca59a
SM
1848=head1 AUTHOR
1849
31b49ad4 1850Stephen McCamant, E<lt>smcc@CSUA.Berkeley.EDUE<gt>.
c99ca59a
SM
1851
1852=cut