This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
default warnLevel and dieLevel to 0 in debugger (from Tom
[perl5.git] / lib / Dumpvalue.pm
CommitLineData
17f410f9 1use 5.005_64; # for (defined ref) and $#$v and our
230a5be7
IZ
2package Dumpvalue;
3use strict;
17f410f9 4our(%address, $stab, @stab, %stab, %subs);
230a5be7
IZ
5
6# translate control chars to ^X - Randal Schwartz
7# Modifications to print types by Peter Gordon v1.0
8
9# Ilya Zakharevich -- patches after 5.001 (and some before ;-)
10
11# Won't dump symbol tables and contents of debugged files by default
12
13# (IZ) changes for objectification:
14# c) quote() renamed to method set_quote();
15# d) unctrlSet() renamed to method set_unctrl();
16# f) Compiles with `use strict', but in two places no strict refs is needed:
17# maybe more problems are waiting...
18
19my %defaults = (
20 globPrint => 0,
21 printUndef => 1,
22 tick => "auto",
23 unctrl => 'quote',
24 subdump => 1,
25 dumpReused => 0,
26 bareStringify => 1,
27 hashDepth => '',
28 arrayDepth => '',
29 dumpDBFiles => '',
30 dumpPackages => '',
31 quoteHighBit => '',
32 usageOnly => '',
33 compactDump => '',
34 veryCompact => '',
35 stopDbSignal => '',
36 );
37
38sub new {
39 my $class = shift;
40 my %opt = (%defaults, @_);
41 bless \%opt, $class;
42}
43
44sub set {
45 my $self = shift;
46 my %opt = @_;
47 @$self{keys %opt} = values %opt;
48}
49
50sub get {
51 my $self = shift;
52 wantarray ? @$self{@_} : $$self{pop @_};
53}
54
55sub dumpValue {
56 my $self = shift;
57 die "usage: \$dumper->dumpValue(value)" unless @_ == 1;
58 local %address;
59 local $^W=0;
60 (print "undef\n"), return unless defined $_[0];
61 (print $self->stringify($_[0]), "\n"), return unless ref $_[0];
62 $self->unwrap($_[0],0);
63}
64
65sub dumpValues {
66 my $self = shift;
67 local %address;
68 local $^W=0;
69 (print "undef\n"), return unless defined $_[0];
70 $self->unwrap(\@_,0);
71}
72
73# This one is good for variable names:
74
75sub unctrl {
76 local($_) = @_;
77
78 return \$_ if ref \$_ eq "GLOB";
79 s/([\001-\037\177])/'^'.pack('c',ord($1)^64)/eg;
80 $_;
81}
82
83sub stringify {
84 my $self = shift;
85 local $_ = shift;
86 my $noticks = shift;
87 my $tick = $self->{tick};
88
89 return 'undef' unless defined $_ or not $self->{printUndef};
90 return $_ . "" if ref \$_ eq 'GLOB';
91 { no strict 'refs';
92 $_ = &{'overload::StrVal'}($_)
93 if $self->{bareStringify} and ref $_
2c2d71f5 94 and %overload:: and defined &{'overload::StrVal'};
230a5be7
IZ
95 }
96
97 if ($tick eq 'auto') {
98 if (/[\000-\011\013-\037\177]/) {
99 $tick = '"';
100 } else {
101 $tick = "'";
102 }
103 }
104 if ($tick eq "'") {
105 s/([\'\\])/\\$1/g;
106 } elsif ($self->{unctrl} eq 'unctrl') {
107 s/([\"\\])/\\$1/g ;
108 s/([\000-\037\177])/'^'.pack('c',ord($1)^64)/eg;
109 s/([\200-\377])/'\\0x'.sprintf('%2X',ord($1))/eg
110 if $self->{quoteHighBit};
111 } elsif ($self->{unctrl} eq 'quote') {
112 s/([\"\\\$\@])/\\$1/g if $tick eq '"';
113 s/\033/\\e/g;
114 s/([\000-\037\177])/'\\c'.chr(ord($1)^64)/eg;
115 }
116 s/([\200-\377])/'\\'.sprintf('%3o',ord($1))/eg if $self->{quoteHighBit};
117 ($noticks || /^\d+(\.\d*)?\Z/)
118 ? $_
119 : $tick . $_ . $tick;
120}
121
122sub DumpElem {
123 my ($self, $v) = (shift, shift);
124 my $short = $self->stringify($v, ref $v);
125 my $shortmore = '';
126 if ($self->{veryCompact} && ref $v
127 && (ref $v eq 'ARRAY' and !grep(ref $_, @$v) )) {
128 my $depth = $#$v;
129 ($shortmore, $depth) = (' ...', $self->{arrayDepth} - 1)
130 if $self->{arrayDepth} and $depth >= $self->{arrayDepth};
131 my @a = map $self->stringify($_), @$v[0..$depth];
132 print "0..$#{$v} @a$shortmore\n";
133 } elsif ($self->{veryCompact} && ref $v
134 && (ref $v eq 'HASH') and !grep(ref $_, values %$v)) {
135 my @a = sort keys %$v;
136 my $depth = $#a;
137 ($shortmore, $depth) = (' ...', $self->{hashDepth} - 1)
138 if $self->{hashDepth} and $depth >= $self->{hashDepth};
139 my @b = map {$self->stringify($_) . " => " . $self->stringify($$v{$_})}
140 @a[0..$depth];
141 local $" = ', ';
142 print "@b$shortmore\n";
143 } else {
144 print "$short\n";
145 $self->unwrap($v,shift);
146 }
147}
148
149sub unwrap {
150 my $self = shift;
151 return if $DB::signal and $self->{stopDbSignal};
152 my ($v) = shift ;
153 my ($s) = shift ; # extra no of spaces
154 my $sp;
155 my (%v,@v,$address,$short,$fileno);
156
157 $sp = " " x $s ;
158 $s += 3 ;
159
160 # Check for reused addresses
161 if (ref $v) {
162 my $val = $v;
163 { no strict 'refs';
164 $val = &{'overload::StrVal'}($v)
2c2d71f5 165 if %overload:: and defined &{'overload::StrVal'};
230a5be7
IZ
166 }
167 ($address) = $val =~ /(0x[0-9a-f]+)\)$/ ;
168 if (!$self->{dumpReused} && defined $address) {
169 $address{$address}++ ;
170 if ( $address{$address} > 1 ) {
171 print "${sp}-> REUSED_ADDRESS\n" ;
172 return ;
173 }
174 }
175 } elsif (ref \$v eq 'GLOB') {
176 $address = "$v" . ""; # To avoid a bug with globs
177 $address{$address}++ ;
178 if ( $address{$address} > 1 ) {
179 print "${sp}*DUMPED_GLOB*\n" ;
180 return ;
181 }
182 }
183
f6b3007c
JH
184 if (ref $v eq 'Regexp') {
185 my $re = "$v";
186 $re =~ s,/,\\/,g;
187 print "$sp-> qr/$re/\n";
188 return;
189 }
190
230a5be7
IZ
191 if ( UNIVERSAL::isa($v, 'HASH') ) {
192 my @sortKeys = sort keys(%$v) ;
193 my $more;
194 my $tHashDepth = $#sortKeys ;
195 $tHashDepth = $#sortKeys < $self->{hashDepth}-1 ? $#sortKeys : $self->{hashDepth}-1
196 unless $self->{hashDepth} eq '' ;
197 $more = "....\n" if $tHashDepth < $#sortKeys ;
198 my $shortmore = "";
199 $shortmore = ", ..." if $tHashDepth < $#sortKeys ;
200 $#sortKeys = $tHashDepth ;
201 if ($self->{compactDump} && !grep(ref $_, values %{$v})) {
202 $short = $sp;
203 my @keys;
204 for (@sortKeys) {
205 push @keys, $self->stringify($_) . " => " . $self->stringify($v->{$_});
206 }
207 $short .= join ', ', @keys;
208 $short .= $shortmore;
209 (print "$short\n"), return if length $short <= $self->{compactDump};
210 }
211 for my $key (@sortKeys) {
212 return if $DB::signal and $self->{stopDbSignal};
213 my $value = $ {$v}{$key} ;
214 print $sp, $self->stringify($key), " => ";
215 $self->DumpElem($value, $s);
216 }
217 print "$sp empty hash\n" unless @sortKeys;
218 print "$sp$more" if defined $more ;
219 } elsif ( UNIVERSAL::isa($v, 'ARRAY') ) {
220 my $tArrayDepth = $#{$v} ;
221 my $more ;
222 $tArrayDepth = $#$v < $self->{arrayDepth}-1 ? $#$v : $self->{arrayDepth}-1
223 unless $self->{arrayDepth} eq '' ;
224 $more = "....\n" if $tArrayDepth < $#{$v} ;
225 my $shortmore = "";
226 $shortmore = " ..." if $tArrayDepth < $#{$v} ;
227 if ($self->{compactDump} && !grep(ref $_, @{$v})) {
228 if ($#$v >= 0) {
229 $short = $sp . "0..$#{$v} " .
230 join(" ",
231 map {$self->stringify($_)} @{$v}[0..$tArrayDepth])
232 . "$shortmore";
233 } else {
234 $short = $sp . "empty array";
235 }
236 (print "$short\n"), return if length $short <= $self->{compactDump};
237 }
238 for my $num ($[ .. $tArrayDepth) {
239 return if $DB::signal and $self->{stopDbSignal};
240 print "$sp$num ";
241 $self->DumpElem($v->[$num], $s);
242 }
243 print "$sp empty array\n" unless @$v;
244 print "$sp$more" if defined $more ;
245 } elsif ( UNIVERSAL::isa($v, 'SCALAR') or ref $v eq 'REF' ) {
246 print "$sp-> ";
247 $self->DumpElem($$v, $s);
248 } elsif ( UNIVERSAL::isa($v, 'CODE') ) {
249 print "$sp-> ";
250 $self->dumpsub(0, $v);
251 } elsif ( UNIVERSAL::isa($v, 'GLOB') ) {
252 print "$sp-> ",$self->stringify($$v,1),"\n";
253 if ($self->{globPrint}) {
254 $s += 3;
255 $self->dumpglob('', $s, "{$$v}", $$v, 1);
256 } elsif (defined ($fileno = fileno($v))) {
257 print( (' ' x ($s+3)) . "FileHandle({$$v}) => fileno($fileno)\n" );
258 }
259 } elsif (ref \$v eq 'GLOB') {
260 if ($self->{globPrint}) {
261 $self->dumpglob('', $s, "{$v}", $v, 1);
262 } elsif (defined ($fileno = fileno(\$v))) {
263 print( (' ' x $s) . "FileHandle({$v}) => fileno($fileno)\n" );
264 }
265 }
266}
267
268sub matchvar {
269 $_[0] eq $_[1] or
270 ($_[1] =~ /^([!~])(.)([\x00-\xff]*)/) and
271 ($1 eq '!') ^ (eval {($_[2] . "::" . $_[0]) =~ /$2$3/});
272}
273
274sub compactDump {
275 my $self = shift;
276 $self->{compactDump} = shift if @_;
277 $self->{compactDump} = 6*80-1
278 if $self->{compactDump} and $self->{compactDump} < 2;
279 $self->{compactDump};
280}
281
282sub veryCompact {
283 my $self = shift;
284 $self->{veryCompact} = shift if @_;
285 $self->compactDump(1) if !$self->{compactDump} and $self->{veryCompact};
286 $self->{veryCompact};
287}
288
289sub set_unctrl {
290 my $self = shift;
291 if (@_) {
292 my $in = shift;
293 if ($in eq 'unctrl' or $in eq 'quote') {
294 $self->{unctrl} = $in;
295 } else {
296 print "Unknown value for `unctrl'.\n";
297 }
298 }
299 $self->{unctrl};
300}
301
302sub set_quote {
303 my $self = shift;
304 if (@_ and $_[0] eq '"') {
305 $self->{tick} = '"';
306 $self->{unctrl} = 'quote';
307 } elsif (@_ and $_[0] eq 'auto') {
308 $self->{tick} = 'auto';
309 $self->{unctrl} = 'quote';
310 } elsif (@_) { # Need to set
311 $self->{tick} = "'";
312 $self->{unctrl} = 'unctrl';
313 }
314 $self->{tick};
315}
316
317sub dumpglob {
318 my $self = shift;
319 return if $DB::signal and $self->{stopDbSignal};
320 my ($package, $off, $key, $val, $all) = @_;
321 local(*stab) = $val;
322 my $fileno;
323 if (($key !~ /^_</ or $self->{dumpDBFiles}) and defined $stab) {
324 print( (' ' x $off) . "\$", &unctrl($key), " = " );
325 $self->DumpElem($stab, 3+$off);
326 }
2c2d71f5 327 if (($key !~ /^_</ or $self->{dumpDBFiles}) and @stab) {
230a5be7
IZ
328 print( (' ' x $off) . "\@$key = (\n" );
329 $self->unwrap(\@stab,3+$off) ;
330 print( (' ' x $off) . ")\n" );
331 }
2c2d71f5 332 if ($key ne "main::" && $key ne "DB::" && %stab
230a5be7
IZ
333 && ($self->{dumpPackages} or $key !~ /::$/)
334 && ($key !~ /^_</ or $self->{dumpDBFiles})
335 && !($package eq "Dumpvalue" and $key eq "stab")) {
336 print( (' ' x $off) . "\%$key = (\n" );
337 $self->unwrap(\%stab,3+$off) ;
338 print( (' ' x $off) . ")\n" );
339 }
340 if (defined ($fileno = fileno(*stab))) {
341 print( (' ' x $off) . "FileHandle($key) => fileno($fileno)\n" );
342 }
343 if ($all) {
344 if (defined &stab) {
345 $self->dumpsub($off, $key);
346 }
347 }
348}
349
83ee9e09
GS
350sub CvGV_name {
351 my $self = shift;
352 my $in = shift;
353 return if $self->{skipCvGV}; # Backdoor to avoid problems if XS broken...
354 $in = \&$in; # Hard reference...
355 eval {require Devel::Peek; 1} or return;
356 my $gv = Devel::Peek::CvGV($in) or return;
357 *$gv{PACKAGE} . '::' . *$gv{NAME};
358}
359
230a5be7
IZ
360sub dumpsub {
361 my $self = shift;
362 my ($off,$sub) = @_;
83ee9e09
GS
363 my $ini = $sub;
364 my $s;
230a5be7 365 $sub = $1 if $sub =~ /^\{\*(.*)\}$/;
83ee9e09
GS
366 my $subref = defined $1 ? \&$sub : \&$ini;
367 my $place = $DB::sub{$sub} || (($s = $subs{"$subref"}) && $DB::sub{$s})
368 || (($s = $self->CvGV_name($subref)) && $DB::sub{$s})
369 || ($self->{subdump} && ($s = $self->findsubs("$subref"))
370 && $DB::sub{$s});
371 $s = $sub unless defined $s;
230a5be7 372 $place = '???' unless defined $place;
83ee9e09 373 print( (' ' x $off) . "&$s in $place\n" );
230a5be7
IZ
374}
375
376sub findsubs {
377 my $self = shift;
2c2d71f5 378 return undef unless %DB::sub;
230a5be7
IZ
379 my ($addr, $name, $loc);
380 while (($name, $loc) = each %DB::sub) {
381 $addr = \&$name;
382 $subs{"$addr"} = $name;
383 }
384 $self->{subdump} = 0;
385 $subs{ shift() };
386}
387
388sub dumpvars {
389 my $self = shift;
390 my ($package,@vars) = @_;
391 local(%address,$^W);
392 my ($key,$val);
393 $package .= "::" unless $package =~ /::$/;
394 *stab = *main::;
395
396 while ($package =~ /(\w+?::)/g) {
397 *stab = $ {stab}{$1};
398 }
399 $self->{TotalStrings} = 0;
400 $self->{Strings} = 0;
401 $self->{CompleteTotal} = 0;
402 while (($key,$val) = each(%stab)) {
403 return if $DB::signal and $self->{stopDbSignal};
404 next if @vars && !grep( matchvar($key, $_), @vars );
405 if ($self->{usageOnly}) {
406 $self->globUsage(\$val, $key)
4c82ae22
GS
407 if ($package ne 'Dumpvalue' or $key ne 'stab')
408 and ref(\$val) eq 'GLOB';
230a5be7
IZ
409 } else {
410 $self->dumpglob($package, 0,$key, $val);
411 }
412 }
413 if ($self->{usageOnly}) {
414 print <<EOP;
415String space: $self->{TotalStrings} bytes in $self->{Strings} strings.
416EOP
417 $self->{CompleteTotal} += $self->{TotalStrings};
418 print <<EOP;
419Grand total = $self->{CompleteTotal} bytes (1 level deep) + overhead.
420EOP
421 }
422}
423
424sub scalarUsage {
425 my $self = shift;
426 my $size = length($_[0]);
427 $self->{TotalStrings} += $size;
428 $self->{Strings}++;
429 $size;
430}
431
432sub arrayUsage { # array ref, name
433 my $self = shift;
434 my $size = 0;
435 map {$size += $self->scalarUsage($_)} @{$_[0]};
436 my $len = @{$_[0]};
437 print "\@$_[1] = $len item", ($len > 1 ? "s" : ""), " (data: $size bytes)\n"
438 if defined $_[1];
439 $self->{CompleteTotal} += $size;
440 $size;
441}
442
443sub hashUsage { # hash ref, name
444 my $self = shift;
445 my @keys = keys %{$_[0]};
446 my @values = values %{$_[0]};
447 my $keys = $self->arrayUsage(\@keys);
448 my $values = $self->arrayUsage(\@values);
449 my $len = @keys;
450 my $total = $keys + $values;
451 print "\%$_[1] = $len item", ($len > 1 ? "s" : ""),
452 " (keys: $keys; values: $values; total: $total bytes)\n"
453 if defined $_[1];
454 $total;
455}
456
457sub globUsage { # glob ref, name
458 my $self = shift;
459 local *stab = *{$_[0]};
460 my $total = 0;
461 $total += $self->scalarUsage($stab) if defined $stab;
2c2d71f5 462 $total += $self->arrayUsage(\@stab, $_[1]) if @stab;
230a5be7 463 $total += $self->hashUsage(\%stab, $_[1])
2c2d71f5 464 if %stab and $_[1] ne "main::" and $_[1] ne "DB::";
230a5be7
IZ
465 #and !($package eq "Dumpvalue" and $key eq "stab"));
466 $total;
467}
468
4691;
470
471=head1 NAME
472
473Dumpvalue - provides screen dump of Perl data.
474
ca24dfc6 475=head1 SYNOPSIS
230a5be7
IZ
476
477 use Dumpvalue;
478 my $dumper = new Dumpvalue;
479 $dumper->set(globPrint => 1);
480 $dumper->dumpValue(\*::);
481 $dumper->dumpvars('main');
482
483=head1 DESCRIPTION
484
485=head2 Creation
486
487A new dumper is created by a call
488
489 $d = new Dumpvalue(option1 => value1, option2 => value2)
490
491Recognized options:
492
493=over
494
495=item C<arrayDepth>, C<hashDepth>
496
497Print only first N elements of arrays and hashes. If false, prints all the
498elements.
499
500=item C<compactDump>, C<veryCompact>
501
502Change style of array and hash dump. If true, short array
503may be printed on one line.
504
505=item C<globPrint>
506
507Whether to print contents of globs.
508
509=item C<DumpDBFiles>
510
511Dump arrays holding contents of debugged files.
512
513=item C<DumpPackages>
514
515Dump symbol tables of packages.
516
517=item C<DumpReused>
518
519Dump contents of "reused" addresses.
520
521=item C<tick>, C<HighBit>, C<printUndef>
522
523Change style of string dump. Default value of C<tick> is C<auto>, one
524can enable either double-quotish dump, or single-quotish by setting it
525to C<"> or C<'>. By default, characters with high bit set are printed
526I<as is>.
527
528=item C<UsageOnly>
529
530I<very> rudimentally per-package memory usage dump. If set,
531C<dumpvars> calculates total size of strings in variables in the package.
532
533=item unctrl
534
535Changes the style of printout of strings. Possible values are
536C<unctrl> and C<quote>.
537
538=item subdump
539
540Whether to try to find the subroutine name given the reference.
541
542=item bareStringify
543
544Whether to write the non-overloaded form of the stringify-overloaded objects.
545
546=item quoteHighBit
547
548Whether to print chars with high bit set in binary or "as is".
549
550=item stopDbSignal
551
552Whether to abort printing if debugger signal flag is raised.
553
554=back
555
556Later in the life of the object the methods may be queries with get()
557method and set() method (which accept multiple arguments).
558
559=head2 Methods
560
561=over
562
563=item dumpValue
564
565 $dumper->dumpValue($value);
566 $dumper->dumpValue([$value1, $value2]);
567
568=item dumpValues
569
570 $dumper->dumpValues($value1, $value2);
571
572=item dumpvars
573
574 $dumper->dumpvars('my_package');
575 $dumper->dumpvars('my_package', 'foo', '~bar$', '!......');
576
577The optional arguments are considered as literal strings unless they
578start with C<~> or C<!>, in which case they are interpreted as regular
579expressions (possibly negated).
580
581The second example prints entries with names C<foo>, and also entries
582with names which ends on C<bar>, or are shorter than 5 chars.
583
584=item set_quote
585
586 $d->set_quote('"');
587
588Sets C<tick> and C<unctrl> options to suitable values for printout with the
589given quote char. Possible values are C<auto>, C<'> and C<">.
590
591=item set_unctrl
592
593 $d->set_unctrl('"');
594
595Sets C<unctrl> option with checking for an invalid argument.
596Possible values are C<unctrl> and C<quote>.
597
598=item compactDump
599
600 $d->compactDump(1);
601
602Sets C<compactDump> option. If the value is 1, sets to a reasonable
603big number.
604
605=item veryCompact
606
607 $d->veryCompact(1);
608
609Sets C<compactDump> and C<veryCompact> options simultaneously.
610
611=item set
612
613 $d->set(option1 => value1, option2 => value2);
614
615=item get
616
617 @values = $d->get('option1', 'option2');
618
619=back
620
621=cut
622