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