2 # Copyright (C) 2000-2003 Stephen McCamant. All rights reserved.
3 # This program is free software; you can redistribute and/or modify it
4 # under the same terms as Perl itself.
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.
13 use warnings; # uses #3 and #4, since warnings uses Carp
15 use Exporter (); # use #5
17 our $VERSION = "0.56";
18 our @ISA = qw(Exporter);
19 our @EXPORT_OK = qw(set_style set_style_standard add_callback
20 concise_subref concise_cv concise_main);
23 use B qw(class ppname main_start main_root main_cv cstring svref_2object
24 SVf_IOK SVf_NOK SVf_POK SVf_IVisUV SVf_FAKE OPf_KIDS CVf_ANON);
28 ["(?(#label =>\n)?)(*( )*)#class (#addr) #name (?([#targ])?) "
29 . "#svclass~(?((#svaddr))?)~#svval~(?(label \"#coplabel\")?)\n",
30 "(*( )*)goto #class (#addr)\n",
33 ["#hyphseq2 (*( (x( ;)x))*)<#classsym> "
34 . "#exname#arg(?([#targarglife])?)~#flags(?(/#private)?)(x(;~->#next)x)\n",
35 " (*( )*) goto #seq\n",
36 "(?(<#seq>)?)#exname#arg(?([#targarglife])?)"],
38 ["(x(;(*( )*))x)#noise#arg(?([#targarg])?)(x( ;\n)x)",
40 "(?(#seq)?)#noise#arg(?([#targarg])?)"],
42 ["#class (#addr)\n\top_next\t\t#nextaddr\n\top_sibling\t#sibaddr\n\t"
43 . "op_ppaddr\tPL_ppaddr[OP_#NAME]\n\top_type\t\t#typenum\n\top_seq\t\t"
44 . "#seqnum\n\top_flags\t#flagval\n\top_private\t#privval\n"
45 . "(?(\top_first\t#firstaddr\n)?)(?(\top_last\t\t#lastaddr\n)?)"
46 . "(?(\top_sv\t\t#svaddr\n)?)",
49 "env" => [$ENV{B_CONCISE_FORMAT}, $ENV{B_CONCISE_GOTO_FORMAT},
50 $ENV{B_CONCISE_TREE_FORMAT}],
53 my($format, $gotofmt, $treefmt);
59 ($format, $gotofmt, $treefmt) = @_;
62 sub set_style_standard {
64 set_style(@{$style{$name}});
72 my($order, $subref) = @_;
73 concise_cv_obj($order, svref_2object($subref));
76 # This should have been called concise_subref, but it was exported
77 # under this name in versions before 0.56
78 sub concise_cv { concise_subref(@_); }
81 my ($order, $cv) = @_;
84 if ($order eq "exec") {
85 walk_exec($cv->START);
86 } elsif ($order eq "basic") {
87 walk_topdown($cv->ROOT, sub { $_[0]->concise($_[1]) }, 0);
89 print tree($cv->ROOT, 0)
97 if ($order eq "exec") {
98 return if class(main_start) eq "NULL";
99 walk_exec(main_start);
100 } elsif ($order eq "tree") {
101 return if class(main_root) eq "NULL";
102 print tree(main_root, 0);
103 } elsif ($order eq "basic") {
104 return if class(main_root) eq "NULL";
105 walk_topdown(main_root,
106 sub { $_[0]->concise($_[1]) }, 0);
110 sub concise_specials {
111 my($name, $order, @cv_s) = @_;
113 if ($name eq "BEGIN") {
114 splice(@cv_s, 0, 7); # skip 7 BEGIN blocks in this file
115 } elsif ($name eq "CHECK") {
116 pop @cv_s; # skip the CHECK block that calls us
121 concise_cv_obj($order, $cv);
125 my $start_sym = "\e(0"; # "\cN" sometimes also works
126 my $end_sym = "\e(B"; # "\cO" respectively
128 my @tree_decorations =
129 ([" ", "--", "+-", "|-", "| ", "`-", "-", 1],
130 [" ", "-", "+", "+", "|", "`", "", 0],
131 [" ", map("$start_sym$_$end_sym", "qq", "wq", "tq", "x ", "mq", "q"), 1],
132 [" ", map("$start_sym$_$end_sym", "q", "w", "t", "x", "m"), "", 0],
141 set_style_standard("concise");
144 my @options = grep(/^-/, @_);
145 my @args = grep(!/^-/, @_);
147 for my $o (@options) {
148 if ($o eq "-basic") {
150 } elsif ($o eq "-exec") {
152 } elsif ($o eq "-tree") {
154 } elsif ($o eq "-compact") {
156 } elsif ($o eq "-loose") {
158 } elsif ($o eq "-vt") {
160 } elsif ($o eq "-ascii") {
162 } elsif ($o eq "-main") {
164 } elsif ($o =~ /^-base(\d+)$/) {
166 } elsif ($o eq "-bigendian") {
168 } elsif ($o eq "-littleendian") {
170 } elsif (exists $style{substr($o, 1)}) {
171 set_style(@{$style{substr($o, 1)}});
173 warn "Option $o unrecognized";
178 for my $objname (@args) {
179 if ($objname eq "BEGIN") {
180 concise_specials("BEGIN", $order,
181 B::begin_av->isa("B::AV") ?
182 B::begin_av->ARRAY : ());
183 } elsif ($objname eq "INIT") {
184 concise_specials("INIT", $order,
185 B::init_av->isa("B::AV") ?
186 B::init_av->ARRAY : ());
187 } elsif ($objname eq "CHECK") {
188 concise_specials("CHECK", $order,
189 B::check_av->isa("B::AV") ?
190 B::check_av->ARRAY : ());
191 } elsif ($objname eq "END") {
192 concise_specials("END", $order,
193 B::end_av->isa("B::AV") ?
194 B::end_av->ARRAY : ());
196 $objname = "main::" . $objname unless $objname =~ /::/;
198 eval "concise_subref(\$order, \\&$objname)";
199 die "concise_subref($order, \\&$objname) failed: $@" if $@;
203 if (!@args or $do_main) {
204 print "main program:\n" if $do_main;
205 concise_main($order);
213 my %opclass = ('OP' => "0", 'UNOP' => "1", 'BINOP' => "2", 'LOGOP' => "|",
214 'LISTOP' => "@", 'PMOP' => "/", 'SVOP' => "\$", 'GVOP' => "*",
215 'PVOP' => '"', 'LOOP' => "{", 'COP' => ";", 'PADOP' => "#");
217 no warnings 'qw'; # "Possible attempt to put comments..."; use #7
219 qw'# () sc ( @? 1 $* gv *{ m$ m@ m% m? p/ *$ $ $# & a& pt \\ s\\ rf bl
220 ` *? <> ?? ?/ r/ c/ // qr s/ /c y/ = @= C sC Cp sp df un BM po +1 +I
221 -1 -I 1+ I+ 1- I- ** * i* / i/ %$ i% x + i+ - i- . " << >> < i<
222 > i> <= i, >= i. == i= != i! <? i? s< s> s, s. s= s! s? b& b^ b| -0 -i
223 ! ~ a2 si cs rd sr e^ lg sq in %x %o ab le ss ve ix ri sf FL od ch cy
224 uf lf uc lc qm @ [f [ @[ eh vl ky dl ex % ${ @{ uk pk st jn ) )[ a@
225 a% sl +] -] [- [+ so rv GS GW MS MW .. f. .f && || ^^ ?: &= |= -> s{ s}
226 v} ca wa di rs ;; ; ;d }{ { } {} f{ it {l l} rt }l }n }r dm }g }e ^o
227 ^c ^| ^# um bm t~ u~ ~d DB db ^s se ^g ^r {w }w pf pr ^O ^K ^R ^W ^d ^v
228 ^e ^t ^k t. fc ic fl .s .p .b .c .l .a .h g1 s1 g2 s2 ?. l? -R -W -X -r
229 -w -x -e -o -O -z -s -M -A -C -S -c -b -f -d -p -l -u -g -k -t -T -B cd
230 co cr u. cm ut r. l@ s@ r@ mD uD oD rD tD sD wD cD f$ w$ p$ sh e$ k$ g3
231 g4 s4 g5 s5 T@ C@ L@ G@ A@ S@ Hg Hc Hr Hw Mg Mc Ms Mr Sg Sc So rq do {e
232 e} {t t} g6 G6 6e g7 G7 7e g8 G8 8e g9 G9 9e 6s 7s 8s 9s 6E 7E 8E 9E Pn
233 Pu GP SP EP Gn Gg GG SG EG g0 c$ lk t$ ;s n> // /= CO';
235 my $chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
240 push @v, "v" if ($x & 3) == 1;
241 push @v, "s" if ($x & 3) == 2;
242 push @v, "l" if ($x & 3) == 3;
243 push @v, "K" if $x & 4;
244 push @v, "P" if $x & 8;
245 push @v, "R" if $x & 16;
246 push @v, "M" if $x & 32;
247 push @v, "S" if $x & 64;
248 push @v, "*" if $x & 128;
254 return "-" . base_n(-$x) if $x < 0;
256 do { $str .= substr($chars, $x % $base, 1) } while $x = int($x / $base);
257 $str = reverse $str if $big_endian;
266 return "-" if not exists $sequence_num{$$op};
267 return base_n($sequence_num{$$op});
271 my($op, $sub, $level) = @_;
273 if ($op->flags & OPf_KIDS) {
274 for (my $kid = $op->first; $$kid; $kid = $kid->sibling) {
275 walk_topdown($kid, $sub, $level + 1);
278 if (class($op) eq "PMOP" and $op->pmreplroot and $ {$op->pmreplroot}
279 and $op->pmreplroot->isa("B::OP")) {
280 walk_topdown($op->pmreplroot, $sub, $level + 1);
285 my($ar, $level) = @_;
287 if (ref($l) eq "ARRAY") {
288 walklines($l, $level + 1);
296 my($top, $level) = @_;
299 my @todo = ([$top, \@lines]);
300 while (@todo and my($op, $targ) = @{shift @todo}) {
301 for (; $$op; $op = $op->next) {
302 last if $opsseen{$$op}++;
304 my $name = $op->name;
305 if (class($op) eq "LOGOP") {
308 push @todo, [$op->other, $ar];
309 } elsif ($name eq "subst" and $ {$op->pmreplstart}) {
312 push @todo, [$op->pmreplstart, $ar];
313 } elsif ($name =~ /^enter(loop|iter)$/) {
314 $labels{$op->nextop->seq} = "NEXT";
315 $labels{$op->lastop->seq} = "LAST";
316 $labels{$op->redoop->seq} = "REDO";
320 walklines(\@lines, 0);
323 # The structure of this routine is purposely modeled after op.c's peep()
327 return if class($op) eq "NULL" or exists $sequence_num{$$op};
328 for (; $$op; $op = $op->next) {
329 last if exists $sequence_num{$$op};
330 my $name = $op->name;
331 if ($name =~ /^(null|scalar|lineseq|scope)$/) {
332 next if $oldop and $ {$op->next};
334 $sequence_num{$$op} = $seq_max++;
335 if (class($op) eq "LOGOP") {
336 my $other = $op->other;
337 $other = $other->next while $other->name eq "null";
339 } elsif (class($op) eq "LOOP") {
340 my $redoop = $op->redoop;
341 $redoop = $redoop->next while $redoop->name eq "null";
343 my $nextop = $op->nextop;
344 $nextop = $nextop->next while $nextop->name eq "null";
346 my $lastop = $op->lastop;
347 $lastop = $lastop->next while $lastop->name eq "null";
349 } elsif ($name eq "subst" and $ {$op->pmreplstart}) {
350 my $replstart = $op->pmreplstart;
351 $replstart = $replstart->next while $replstart->name eq "null";
352 sequence($replstart);
360 my($hr, $fmt, $level) = @_;
362 $text =~ s/\(\?\(([^\#]*?)\#(\w+)([^\#]*?)\)\?\)/
363 $hr->{$2} ? $1.$hr->{$2}.$3 : ""/eg;
364 $text =~ s/\(x\((.*?);(.*?)\)x\)/$order eq "exec" ? $1 : $2/egs;
365 $text =~ s/\(\*\(([^;]*?)\)\*\)/$1 x $level/egs;
366 $text =~ s/\(\*\((.*?);(.*?)\)\*\)/$1 x ($level - 1) . $2 x ($level>0)/egs;
367 $text =~ s/#([a-zA-Z]+)(\d+)/sprintf("%-$2s", $hr->{$1})/eg;
368 $text =~ s/#([a-zA-Z]+)/$hr->{$1}/eg;
369 $text =~ s/[ \t]*~+[ \t]*/ /g;
374 $priv{$_}{128} = "LVINTRO"
375 for ("pos", "substr", "vec", "threadsv", "gvsv", "rv2sv", "rv2hv", "rv2gv",
376 "rv2av", "rv2arylen", "aelem", "helem", "aslice", "hslice", "padsv",
377 "padav", "padhv", "enteriter");
378 $priv{$_}{64} = "REFC" for ("leave", "leavesub", "leavesublv", "leavewrite");
379 $priv{"aassign"}{64} = "COMMON";
380 $priv{"sassign"}{64} = "BKWARD";
381 $priv{$_}{64} = "RTIME" for ("match", "subst", "substcont");
382 @{$priv{"trans"}}{1,2,4,8,16,64} = ("<UTF", ">UTF", "IDENT", "SQUASH", "DEL",
384 $priv{"repeat"}{64} = "DOLIST";
385 $priv{"leaveloop"}{64} = "CONT";
386 @{$priv{$_}}{32,64,96} = ("DREFAV", "DREFHV", "DREFSV")
387 for ("entersub", map("rv2${_}v", "a", "s", "h", "g"), "aelem", "helem");
388 $priv{"entersub"}{16} = "DBG";
389 $priv{"entersub"}{32} = "TARG";
390 @{$priv{$_}}{4,8,128} = ("INARGS","AMPER","NO()") for ("entersub", "rv2cv");
391 $priv{"gv"}{32} = "EARLYCV";
392 $priv{"aelem"}{16} = $priv{"helem"}{16} = "LVDEFER";
393 $priv{$_}{16} = "OURINTR" for ("gvsv", "rv2sv", "rv2av", "rv2hv", "r2gv",
395 $priv{$_}{16} = "TARGMY"
396 for (map(($_,"s$_"),"chop", "chomp"),
397 map(($_,"i_$_"), "postinc", "postdec", "multiply", "divide", "modulo",
398 "add", "subtract", "negate"), "pow", "concat", "stringify",
399 "left_shift", "right_shift", "bit_and", "bit_xor", "bit_or",
400 "complement", "atan2", "sin", "cos", "rand", "exp", "log", "sqrt",
401 "int", "hex", "oct", "abs", "length", "index", "rindex", "sprintf",
402 "ord", "chr", "crypt", "quotemeta", "join", "push", "unshift", "flock",
403 "chdir", "chown", "chroot", "unlink", "chmod", "utime", "rename",
404 "link", "symlink", "mkdir", "rmdir", "wait", "waitpid", "system",
405 "exec", "kill", "getppid", "getpgrp", "setpgrp", "getpriority",
406 "setpriority", "time", "sleep");
407 @{$priv{"const"}}{8,16,32,64,128} = ("STRICT","ENTERED", '$[', "BARE", "WARN");
408 $priv{"flip"}{64} = $priv{"flop"}{64} = "LINENUM";
409 $priv{"list"}{64} = "GUESSED";
410 $priv{"delete"}{64} = "SLICE";
411 $priv{"exists"}{64} = "SUB";
412 $priv{$_}{64} = "LOCALE"
413 for ("sort", "prtf", "sprintf", "slt", "sle", "seq", "sne", "sgt", "sge",
414 "scmp", "lc", "uc", "lcfirst", "ucfirst");
415 @{$priv{"sort"}}{1,2,4} = ("NUM", "INT", "REV");
416 $priv{"threadsv"}{64} = "SVREFd";
417 @{$priv{$_}}{16,32,64,128} = ("INBIN","INCR","OUTBIN","OUTCR")
418 for ("open", "backtick");
419 $priv{"exit"}{128} = "VMS";
420 $priv{$_}{2} = "FTACCESS"
421 for ("ftrread", "ftrwrite", "ftrexec", "fteread", "ftewrite", "fteexec");
426 for my $flag (128, 96, 64, 32, 16, 8, 4, 2, 1) {
427 if ($priv{$name}{$flag} and $x & $flag and $x >= $flag) {
429 push @s, $priv{$name}{$flag};
433 return join(",", @s);
438 $hr->{svclass} = class($sv);
439 $hr->{svclass} = "UV"
440 if $hr->{svclass} eq "IV" and $sv->FLAGS & SVf_IVisUV;
441 $hr->{svaddr} = sprintf("%#x", $$sv);
442 if ($hr->{svclass} eq "GV") {
444 my $stash = $gv->STASH->NAME;
445 if ($stash eq "main") {
448 $stash = $stash . "::";
450 $hr->{svval} = "*$stash" . $gv->SAFENAME;
451 return "*$stash" . $gv->SAFENAME;
453 while (class($sv) eq "RV") {
454 $hr->{svval} .= "\\";
457 if (class($sv) eq "SPECIAL") {
458 $hr->{svval} .= ["Null", "sv_undef", "sv_yes", "sv_no"]->[$$sv];
459 } elsif ($sv->FLAGS & SVf_NOK) {
460 $hr->{svval} .= $sv->NV;
461 } elsif ($sv->FLAGS & SVf_IOK) {
462 $hr->{svval} .= $sv->int_value;
463 } elsif ($sv->FLAGS & SVf_POK) {
464 $hr->{svval} .= cstring($sv->PV);
465 } elsif (class($sv) eq "HV") {
466 $hr->{svval} .= 'HASH';
468 return $hr->{svclass} . " " . $hr->{svval};
473 my ($op, $level, $format) = @_;
475 $h{exname} = $h{name} = $op->name;
476 $h{NAME} = uc $h{name};
477 $h{class} = class($op);
478 $h{extarg} = $h{targ} = $op->targ;
479 $h{extarg} = "" unless $h{extarg};
480 if ($h{name} eq "null" and $h{targ}) {
481 # targ holds the old type
482 $h{exname} = "ex-" . substr(ppname($h{targ}), 3);
484 } elsif ($op->name =~ /^leave(sub(lv)?|write)?$/) {
485 # targ potentially holds a reference count
486 if ($op->private & 64) {
487 my $refs = "ref" . ($h{targ} != 1 ? "s" : "");
488 $h{targarglife} = $h{targarg} = "$h{targ} $refs";
491 my $padname = (($curcv->PADLIST->ARRAY)[0]->ARRAY)[$h{targ}];
492 if (defined $padname and class($padname) ne "SPECIAL") {
493 $h{targarg} = $padname->PVX;
494 if ($padname->FLAGS & SVf_FAKE) {
496 $fake .= 'a' if $padname->IVX & 1; # PAD_FAKELEX_ANON
497 $fake .= 'm' if $padname->IVX & 2; # PAD_FAKELEX_MULTI
498 $fake .= ':' . $padname->NVX if $curcv->CvFLAGS & CVf_ANON;
499 $h{targarglife} = "$h{targarg}:FAKE:$fake";
502 my $intro = $padname->NVX - $cop_seq_base;
503 my $finish = int($padname->IVX) - $cop_seq_base;
504 $finish = "end" if $finish == 999999999 - $cop_seq_base;
505 $h{targarglife} = "$h{targarg}:$intro,$finish";
508 $h{targarglife} = $h{targarg} = "t" . $h{targ};
512 $h{svclass} = $h{svaddr} = $h{svval} = "";
513 if ($h{class} eq "PMOP") {
514 my $precomp = $op->precomp;
515 if (defined $precomp) {
516 $precomp = cstring($precomp); # Escape literal control sequences
517 $precomp = "/$precomp/";
521 my $pmreplroot = $op->pmreplroot;
523 if ($pmreplroot && $$pmreplroot && $pmreplroot->isa("B::GV")) {
524 # with C<@stash_array = split(/pat/, str);>,
525 # *stash_array is stored in pmreplroot.
526 $h{arg} = "($precomp => \@" . $pmreplroot->NAME . ")";
527 } elsif ($ {$op->pmreplstart}) {
529 $pmreplstart = "replstart->" . seq($op->pmreplstart);
530 $h{arg} = "(" . join(" ", $precomp, $pmreplstart) . ")";
532 $h{arg} = "($precomp)";
534 } elsif ($h{class} eq "PVOP" and $h{name} ne "trans") {
535 $h{arg} = '("' . $op->pv . '")';
536 $h{svval} = '"' . $op->pv . '"';
537 } elsif ($h{class} eq "COP") {
538 my $label = $op->label;
539 $h{coplabel} = $label;
540 $label = $label ? "$label: " : "";
543 $loc .= ":" . $op->line;
544 my($stash, $cseq) = ($op->stash->NAME, $op->cop_seq - $cop_seq_base);
545 my $arybase = $op->arybase;
546 $arybase = $arybase ? ' $[=' . $arybase : "";
547 $h{arg} = "($label$stash $cseq $loc$arybase)";
548 } elsif ($h{class} eq "LOOP") {
549 $h{arg} = "(next->" . seq($op->nextop) . " last->" . seq($op->lastop)
550 . " redo->" . seq($op->redoop) . ")";
551 } elsif ($h{class} eq "LOGOP") {
553 $h{arg} = "(other->" . seq($op->other) . ")";
554 } elsif ($h{class} eq "SVOP") {
556 my $sv = (($curcv->PADLIST->ARRAY)[1]->ARRAY)[$op->targ];
557 $h{arg} = "[" . concise_sv($sv, \%h) . "]";
558 $h{targarglife} = $h{targarg} = "";
560 $h{arg} = "(" . concise_sv($op->sv, \%h) . ")";
562 } elsif ($h{class} eq "PADOP") {
563 my $sv = (($curcv->PADLIST->ARRAY)[1]->ARRAY)[$op->padix];
564 $h{arg} = "[" . concise_sv($sv, \%h) . "]";
566 $h{seq} = $h{hyphseq} = seq($op);
567 $h{seq} = "" if $h{seq} eq "-";
568 $h{seqnum} = $op->seq;
569 $h{next} = $op->next;
570 $h{next} = (class($h{next}) eq "NULL") ? "(end)" : seq($h{next});
571 $h{nextaddr} = sprintf("%#x", $ {$op->next});
572 $h{sibaddr} = sprintf("%#x", $ {$op->sibling});
573 $h{firstaddr} = sprintf("%#x", $ {$op->first}) if $op->can("first");
574 $h{lastaddr} = sprintf("%#x", $ {$op->last}) if $op->can("last");
576 $h{classsym} = $opclass{$h{class}};
577 $h{flagval} = $op->flags;
578 $h{flags} = op_flags($op->flags);
579 $h{privval} = $op->private;
580 $h{private} = private_flags($h{name}, $op->private);
581 $h{addr} = sprintf("%#x", $$op);
582 $h{label} = $labels{$op->seq};
583 $h{typenum} = $op->type;
584 $h{noise} = $linenoise[$op->type];
585 $_->(\%h, $op, \$format, \$level) for @callbacks;
586 return fmt_line(\%h, $format, $level);
590 my($op, $level) = @_;
591 if ($order eq "exec" and $lastnext and $$lastnext != $$op) {
592 my $h = {"seq" => seq($lastnext), "class" => class($lastnext),
593 "addr" => sprintf("%#x", $$lastnext)};
594 print fmt_line($h, $gotofmt, $level+1);
596 $lastnext = $op->next;
597 print concise_op($op, $level, $format);
600 # B::OP::terse (see Terse.pm) now just calls this
602 my($op, $level) = @_;
604 # This isn't necessarily right, but there's no easy way to get
605 # from an OP to the right CV. This is a limitation of the
606 # ->terse() interface style, and there isn't much to do about
607 # it. In particular, we can die in concise_op if the main pad
608 # isn't long enough, or has the wrong kind of entries, compared to
609 # the pad a sub was compiled with. The fix for that would be to
610 # make a backwards compatible "terse" format that never even
611 # looked at the pad, just like the old B::Terse. I don't think
612 # that's worth the effort, though.
613 $curcv = main_cv unless $curcv;
615 if ($order eq "exec" and $lastnext and $$lastnext != $$op) {
616 my $h = {"seq" => seq($lastnext), "class" => class($lastnext),
617 "addr" => sprintf("%#x", $$lastnext)};
618 print fmt_line($h, $style{"terse"}[1], $level+1);
620 $lastnext = $op->next;
621 print concise_op($op, $level, $style{"terse"}[0]);
627 my $style = $tree_decorations[$tree_style];
628 my($space, $single, $kids, $kid, $nokid, $last, $lead, $size) = @$style;
629 my $name = concise_op($op, $level, $treefmt);
630 if (not $op->flags & OPf_KIDS) {
634 for (my $kid = $op->first; $$kid; $kid = $kid->sibling) {
635 push @lines, tree($kid, $level+1);
638 for ($i = $#lines; substr($lines[$i], 0, 1) eq " "; $i--) {
639 $lines[$i] = $space . $lines[$i];
642 $lines[$i] = $last . $lines[$i];
644 if (substr($lines[$i], 0, 1) eq " ") {
645 $lines[$i] = $nokid . $lines[$i];
647 $lines[$i] = $kid . $lines[$i];
650 $lines[$i] = $kids . $lines[$i];
652 $lines[0] = $single . $lines[0];
654 return("$name$lead" . shift @lines,
655 map(" " x (length($name)+$size) . $_, @lines));
658 # *** Warning: fragile kludge ahead ***
659 # Because the B::* modules run in the same interpreter as the code
660 # they're compiling, their presence tends to distort the view we have
661 # of the code we're looking at. In particular, perl gives sequence
662 # numbers to both OPs in general and COPs in particular. If the
663 # program we're looking at were run on its own, these numbers would
664 # start at 1. Because all of B::Concise and all the modules it uses
665 # are compiled first, though, by the time we get to the user's program
666 # the sequence numbers are alreay at pretty high numbers, which would
667 # be distracting if you're trying to tell OPs apart. Therefore we'd
668 # like to subtract an offset from all the sequence numbers we display,
669 # to restore the simpler view of the world. The trick is to know what
670 # that offset will be, when we're still compiling B::Concise! If we
671 # hardcoded a value, it would have to change every time B::Concise or
672 # other modules we use do. To help a little, what we do here is
673 # compile a little code at the end of the module, and compute the base
674 # sequence number for the user's program as being a small offset
675 # later, so all we have to worry about are changes in the offset.
676 # (Note that we now only play this game with COP sequence numbers. OP
677 # sequence numbers aren't used to refer to OPs from a distance, and
678 # they don't have much significance, so we just generate our own
679 # sequence numbers which are easier to control. This way we also don't
680 # stand in the way of a possible future removal of OP sequence
683 # When you say "perl -MO=Concise -e '$a'", the output should look like:
685 # 4 <@> leave[t1] vKP/REFC ->(end)
687 #^ smallest OP sequence number should be 1
688 # 2 <;> nextstate(main 1 -e:1) v ->3
689 # ^ smallest COP sequence number should be 1
690 # - <1> ex-rv2sv vK/1 ->4
691 # 3 <$> gvsv(*a) s ->4
693 # If the second of the marked numbers there isn't 1, it means you need
694 # to update the corresponding magic number in the next line.
695 # Remember, this needs to stay the last things in the module.
697 # Why is this different for MacOS? Does it matter?
698 my $cop_seq_mnum = $^O eq 'MacOS' ? 12 : 11;
699 $cop_seq_base = svref_2object(eval 'sub{0;}')->START->cop_seq + $cop_seq_mnum;
707 B::Concise - Walk Perl syntax tree, printing concise info about ops
711 perl -MO=Concise[,OPTIONS] foo.pl
713 use B::Concise qw(set_style add_callback);
717 This compiler backend prints the internal OPs of a Perl program's syntax
718 tree in one of several space-efficient text formats suitable for debugging
719 the inner workings of perl or other compiler backends. It can print OPs in
720 the order they appear in the OP tree, in the order they will execute, or
721 in a text approximation to their tree structure, and the format of the
722 information displyed is customizable. Its function is similar to that of
723 perl's B<-Dx> debugging flag or the B<B::Terse> module, but it is more
724 sophisticated and flexible.
728 Here's is a short example of output, using the default formatting
731 % perl -MO=Concise -e '$a = $b + 42'
732 8 <@> leave[1 ref] vKP/REFC ->(end)
734 2 <;> nextstate(main 1 -e:1) v ->3
735 7 <2> sassign vKS/2 ->8
736 5 <2> add[t1] sK/2 ->6
737 - <1> ex-rv2sv sK/1 ->4
739 4 <$> const(IV 42) s ->5
740 - <1> ex-rv2sv sKRM*/1 ->7
743 Each line corresponds to an operator. Null ops appear as C<ex-opname>,
744 where I<opname> is the op that has been optimized away by perl.
746 The number on the first row indicates the op's sequence number. It's
747 given in base 36 by default.
749 The symbol between angle brackets indicates the op's type : for example,
750 <2> is a BINOP, <@> a LISTOP, etc. (see L</"OP class abbreviations">).
752 The opname may be followed by op-specific information in parentheses
753 (e.g. C<gvsv(*b)>), and by targ information in brackets (e.g.
756 Next come the op flags. The common flags are listed below
757 (L</"OP flags abbreviations">). The private flags follow, separated
758 by a slash. For example, C<vKP/REFC> means that the leave op has
759 public flags OPf_WANT_VOID, OPf_KIDS, and OPf_PARENS, and the private
762 Finally an arrow points to the sequence number of the next op.
766 Arguments that don't start with a hyphen are taken to be the names of
767 subroutines to print the OPs of; if no such functions are specified,
768 the main body of the program (outside any subroutines, and not
769 including use'd or require'd files) is printed. Passing C<BEGIN>,
770 C<CHECK>, C<INIT>, or C<END> will cause all of the corresponding
771 special blocks to be printed.
777 Print OPs in the order they appear in the OP tree (a preorder
778 traversal, starting at the root). The indentation of each OP shows its
779 level in the tree. This mode is the default, so the flag is included
780 simply for completeness.
784 Print OPs in the order they would normally execute (for the majority
785 of constructs this is a postorder traversal of the tree, ending at the
786 root). In most cases the OP that usually follows a given OP will
787 appear directly below it; alternate paths are shown by indentation. In
788 cases like loops when control jumps out of a linear path, a 'goto'
793 Print OPs in a text approximation of a tree, with the root of the tree
794 at the left and 'left-to-right' order of children transformed into
795 'top-to-bottom'. Because this mode grows both to the right and down,
796 it isn't suitable for large programs (unless you have a very wide
801 Use a tree format in which the minimum amount of space is used for the
802 lines connecting nodes (one character in most cases). This squeezes out
803 a few precious columns of screen real estate.
807 Use a tree format that uses longer edges to separate OP nodes. This format
808 tends to look better than the compact one, especially in ASCII, and is
813 Use tree connecting characters drawn from the VT100 line-drawing set.
814 This looks better if your terminal supports it.
818 Draw the tree with standard ASCII characters like C<+> and C<|>. These don't
819 look as clean as the VT100 characters, but they'll work with almost any
820 terminal (or the horizontal scrolling mode of less(1)) and are suitable
821 for text documentation or email. This is the default.
825 Include the main program in the output, even if subroutines were also
830 Print OP sequence numbers in base I<n>. If I<n> is greater than 10, the
831 digit for 11 will be 'a', and so on. If I<n> is greater than 36, the digit
832 for 37 will be 'A', and so on until 62. Values greater than 62 are not
833 currently supported. The default is 36.
837 Print sequence numbers with the most significant digit first. This is the
838 usual convention for Arabic numerals, and the default.
840 =item B<-littleendian>
842 Print seqence numbers with the least significant digit first.
846 Use the author's favorite set of formatting conventions. This is the
851 Use formatting conventions that emulate the output of B<B::Terse>. The
852 basic mode is almost indistinguishable from the real B<B::Terse>, and the
853 exec mode looks very similar, but is in a more logical order and lacks
854 curly brackets. B<B::Terse> doesn't have a tree mode, so the tree mode
855 is only vaguely reminiscient of B<B::Terse>.
859 Use formatting conventions in which the name of each OP, rather than being
860 written out in full, is represented by a one- or two-character abbreviation.
861 This is mainly a joke.
865 Use formatting conventions reminiscient of B<B::Debug>; these aren't
870 Use formatting conventions read from the environment variables
871 C<B_CONCISE_FORMAT>, C<B_CONCISE_GOTO_FORMAT>, and C<B_CONCISE_TREE_FORMAT>.
875 =head1 FORMATTING SPECIFICATIONS
877 For each general style ('concise', 'terse', 'linenoise', etc.) there are
878 three specifications: one of how OPs should appear in the basic or exec
879 modes, one of how 'goto' lines should appear (these occur in the exec
880 mode only), and one of how nodes should appear in tree mode. Each has the
881 same format, described below. Any text that doesn't match a special
882 pattern is copied verbatim.
886 =item B<(x(>I<exec_text>B<;>I<basic_text>B<)x)>
888 Generates I<exec_text> in exec mode, or I<basic_text> in basic mode.
890 =item B<(*(>I<text>B<)*)>
892 Generates one copy of I<text> for each indentation level.
894 =item B<(*(>I<text1>B<;>I<text2>B<)*)>
896 Generates one fewer copies of I<text1> than the indentation level, followed
897 by one copy of I<text2> if the indentation level is more than 0.
899 =item B<(?(>I<text1>B<#>I<var>I<Text2>B<)?)>
901 If the value of I<var> is true (not empty or zero), generates the
902 value of I<var> surrounded by I<text1> and I<Text2>, otherwise
907 Generates the value of the variable I<var>.
911 Generates the value of I<var>, left jutified to fill I<N> spaces.
915 Any number of tildes and surrounding whitespace will be collapsed to
920 The following variables are recognized:
926 The address of the OP, in hexidecimal.
930 The OP-specific information of the OP (such as the SV for an SVOP, the
931 non-local exit pointers for a LOOP, etc.) enclosed in paretheses.
935 The B-determined class of the OP, in all caps.
939 A single symbol abbreviating the class of the OP.
943 The label of the statement or block the OP is the start of, if any.
947 The name of the OP, or 'ex-foo' if the OP is a null that used to be a foo.
951 The target of the OP, or nothing for a nulled OP.
955 The address of the OP's first child, in hexidecimal.
959 The OP's flags, abbreviated as a series of symbols.
963 The numeric value of the OP's flags.
967 The sequence number of the OP, or a hyphen if it doesn't have one.
971 'NEXT', 'LAST', or 'REDO' if the OP is a target of one of those in exec
972 mode, or empty otherwise.
976 The address of the OP's last child, in hexidecimal.
984 The OP's name, in all caps.
988 The sequence number of the OP's next OP.
992 The address of the OP's next OP, in hexidecimal.
996 A one- or two-character abbreviation for the OP's name.
1000 The OP's private flags, rendered with abbreviated names if possible.
1004 The numeric value of the OP's private flags.
1008 The sequence number of the OP. Note that this is now a sequence number
1009 generated by B::Concise, rather than the real op_seq value (for which
1014 The real sequence number of the OP, as a regular number and not adjusted
1015 to be relative to the start of the real program. (This will generally be
1016 a fairly large number because all of B<B::Concise> is compiled before
1021 The address of the OP's next youngest sibling, in hexidecimal.
1025 The address of the OP's SV, if it has an SV, in hexidecimal.
1029 The class of the OP's SV, if it has one, in all caps (e.g., 'IV').
1033 The value of the OP's SV, if it has one, in a short human-readable format.
1037 The numeric value of the OP's targ.
1041 The name of the variable the OP's targ refers to, if any, otherwise the
1042 letter t followed by the OP's targ in decimal.
1044 =item B<#targarglife>
1046 Same as B<#targarg>, but followed by the COP sequence numbers that delimit
1047 the variable's lifetime (or 'end' for a variable in an open scope) for a
1052 The numeric value of the OP's type, in decimal.
1056 =head1 ABBREVIATIONS
1058 =head2 OP flags abbreviations
1060 v OPf_WANT_VOID Want nothing (void context)
1061 s OPf_WANT_SCALAR Want single value (scalar context)
1062 l OPf_WANT_LIST Want list of any length (list context)
1063 K OPf_KIDS There is a firstborn child.
1064 P OPf_PARENS This operator was parenthesized.
1065 (Or block needs explicit scope entry.)
1066 R OPf_REF Certified reference.
1067 (Return container, not containee).
1068 M OPf_MOD Will modify (lvalue).
1069 S OPf_STACKED Some arg is arriving on the stack.
1070 * OPf_SPECIAL Do something weird for this op (see op.h)
1072 =head2 OP class abbreviations
1074 0 OP (aka BASEOP) An OP with no children
1075 1 UNOP An OP with one child
1076 2 BINOP An OP with two children
1077 | LOGOP A control branch OP
1078 @ LISTOP An OP that could have lots of children
1079 / PMOP An OP with a regular expression
1080 $ SVOP An OP with an SV
1081 " PVOP An OP with a string
1082 { LOOP An OP that holds pointers for a loop
1083 ; COP An OP that marks the start of a statement
1084 # PADOP An OP with a GV on the pad
1086 =head1 Using B::Concise outside of the O framework
1088 It is possible to extend B<B::Concise> by using it outside of the B<O>
1089 framework and providing new styles and new variables.
1091 use B::Concise qw(set_style add_callback);
1092 set_style($format, $gotofmt, $treefmt);
1097 my ($h, $op, $level, $format) = @_;
1098 $h->{variable} = some_func($op);
1101 B::Concise::compile(@options)->();
1103 You can specify a style by calling the B<set_style> subroutine. If you
1104 have a new variable in your style, or you want to change the value of an
1105 existing variable, you will need to add a callback to specify the value
1108 This is done by calling B<add_callback> passing references to any
1109 callback subroutines. The subroutines are called in the same order as
1110 they are added. Each subroutine is passed four parameters. These are a
1111 reference to a hash, the keys of which are the names of the variables
1112 and the values of which are their values, the op, the level and the
1115 To define your own variables, simply add them to the hash, or change
1116 existing values if you need to. The level and format are passed in as
1117 references to scalars, but it is unlikely that they will need to be
1118 changed or even used.
1120 To switch back to one of the standard styles like C<concise> or
1121 C<terse>, use C<set_style_standard>.
1123 To see the output, call the subroutine returned by B<compile> in the
1124 same way that B<O> does.
1128 Stephen McCamant, E<lt>smcc@CSUA.Berkeley.EDUE<gt>.