The formatting function of Carp::Heavy has problem with utf8 strings.
[p5sagit/p5-mst-13.2.git] / lib / Carp / Heavy.pm
1 # Carp::Heavy uses some variables in common with Carp.
2 package Carp;
3
4 =head1 NAME
5
6 Carp::Heavy - heavy machinery, no user serviceable parts inside
7
8 =cut
9
10 # On one line so MakeMaker will see it.
11 use Carp;  our $VERSION = $Carp::VERSION;
12 # use strict; # not yet
13
14 # 'use Carp' just installs some very lightweight stubs; the first time
15 # these are called, they require Carp::Heavy which installs the real
16 # routines.
17
18 # Comments added by Andy Wardley <abw@kfs.org> 09-Apr-98, based on an
19 # _almost_ complete understanding of the package.  Corrections and
20 # comments are welcome.
21
22 # The members of %Internal are packages that are internal to perl.
23 # Carp will not report errors from within these packages if it
24 # can.  The members of %CarpInternal are internal to Perl's warning
25 # system.  Carp will not report errors from within these packages
26 # either, and will not report calls *to* these packages for carp and
27 # croak.  They replace $CarpLevel, which is deprecated.    The
28 # $Max(EvalLen|(Arg(Len|Nums)) variables are used to specify how the eval
29 # text and function arguments should be formatted when printed.
30
31 # Comments added by Jos I. Boumans <kane@dwim.org> 11-Aug-2004
32 # I can not get %CarpInternal or %Internal to work as advertised,
33 # therefore leaving it out of the below documentation.
34 # $CarpLevel may be decprecated according to the last comment, but
35 # after 6 years, it's still around and in heavy use ;)
36
37 # disable these by default, so they can live w/o require Carp
38 $CarpInternal{Carp}++;
39 $CarpInternal{warnings}++;
40 $Internal{Exporter}++;
41 $Internal{'Exporter::Heavy'}++;
42
43
44 our ($CarpLevel, $MaxArgNums, $MaxEvalLen, $MaxArgLen, $Verbose);
45
46 # XXX longmess_real and shortmess_real should really be merged into
47 # XXX {long|sort}mess_heavy at some point
48
49 sub  longmess_real {
50     # Icky backwards compatibility wrapper. :-(
51     my $call_pack = caller();
52     if ($Internal{$call_pack} or $CarpInternal{$call_pack}) {
53       return longmess_heavy(@_);
54     }
55     else {
56       local $CarpLevel = $CarpLevel + 1;
57       return longmess_heavy(@_);
58     }
59 };
60
61 sub shortmess_real {
62     # Icky backwards compatibility wrapper. :-(
63     my $call_pack = caller();
64     local @CARP_NOT = caller();
65     shortmess_heavy(@_);
66 };
67
68 # replace the two hooks added by Carp
69
70 # aliasing the whole glob rather than just the CV slot avoids 'redefined'
71 # warnings, even in the presence of perl -W (as used by lib/warnings.t !)
72
73 *longmess_jmp  = *longmess_real;
74 *shortmess_jmp = *shortmess_real;
75
76
77 sub caller_info {
78   my $i = shift(@_) + 1;
79   package DB;
80   my %call_info;
81   @call_info{
82     qw(pack file line sub has_args wantarray evaltext is_require)
83   } = caller($i);
84   
85   unless (defined $call_info{pack}) {
86     return ();
87   }
88
89   my $sub_name = Carp::get_subname(\%call_info);
90   if ($call_info{has_args}) {
91     my @args = map {Carp::format_arg($_)} @DB::args;
92     if ($MaxArgNums and @args > $MaxArgNums) { # More than we want to show?
93       $#args = $MaxArgNums;
94       push @args, '...';
95     }
96     # Push the args onto the subroutine
97     $sub_name .= '(' . join (', ', @args) . ')';
98   }
99   $call_info{sub_name} = $sub_name;
100   return wantarray() ? %call_info : \%call_info;
101 }
102
103 # Transform an argument to a function into a string.
104 sub format_arg {
105   my $arg = shift;
106   if (not defined($arg)) {
107     $arg = 'undef';
108   }
109   elsif (ref($arg)) {
110       $arg = defined($overload::VERSION) ? overload::StrVal($arg) : "$arg";
111   }
112   $arg =~ s/'/\\'/g;
113   $arg = str_len_trim($arg, $MaxArgLen);
114   
115   # Quote it?
116   $arg = "'$arg'" unless $arg =~ /^-?[\d.]+\z/;
117
118   # The following handling of "control chars" is direct from
119   # the original code - it is broken on Unicode though.
120   # Suggestions?
121   utf8::is_utf8($arg)
122     or $arg =~ s/([[:cntrl:]]|[[:^ascii:]])/sprintf("\\x{%x}",ord($1))/eg;
123   return $arg;
124 }
125
126 # Takes an inheritance cache and a package and returns
127 # an anon hash of known inheritances and anon array of
128 # inheritances which consequences have not been figured
129 # for.
130 sub get_status {
131     my $cache = shift;
132     my $pkg = shift;
133     $cache->{$pkg} ||= [{$pkg => $pkg}, [trusts_directly($pkg)]];
134     return @{$cache->{$pkg}};
135 }
136
137 # Takes the info from caller() and figures out the name of
138 # the sub/require/eval
139 sub get_subname {
140   my $info = shift;
141   if (defined($info->{evaltext})) {
142     my $eval = $info->{evaltext};
143     if ($info->{is_require}) {
144       return "require $eval";
145     }
146     else {
147       $eval =~ s/([\\\'])/\\$1/g;
148       return "eval '" . str_len_trim($eval, $MaxEvalLen) . "'";
149     }
150   }
151
152   return ($info->{sub} eq '(eval)') ? 'eval {...}' : $info->{sub};
153 }
154
155 # Figures out what call (from the point of view of the caller)
156 # the long error backtrace should start at.
157 sub long_error_loc {
158   my $i;
159   my $lvl = $CarpLevel;
160   {
161     my $pkg = caller(++$i);
162     unless(defined($pkg)) {
163       # This *shouldn't* happen.
164       if (%Internal) {
165         local %Internal;
166         $i = long_error_loc();
167         last;
168       }
169       else {
170         # OK, now I am irritated.
171         return 2;
172       }
173     }
174     redo if $CarpInternal{$pkg};
175     redo unless 0 > --$lvl;
176     redo if $Internal{$pkg};
177   }
178   return $i - 1;
179 }
180
181
182 sub longmess_heavy {
183   return @_ if ref($_[0]); # don't break references as exceptions
184   my $i = long_error_loc();
185   return ret_backtrace($i, @_);
186 }
187
188 # Returns a full stack backtrace starting from where it is
189 # told.
190 sub ret_backtrace {
191   my ($i, @error) = @_;
192   my $mess;
193   my $err = join '', @error;
194   $i++;
195
196   my $tid_msg = '';
197   if (defined &Thread::tid) {
198     my $tid = Thread->self->tid;
199     $tid_msg = " thread $tid" if $tid;
200   }
201
202   my %i = caller_info($i);
203   $mess = "$err at $i{file} line $i{line}$tid_msg\n";
204
205   while (my %i = caller_info(++$i)) {
206       $mess .= "\t$i{sub_name} called at $i{file} line $i{line}$tid_msg\n";
207   }
208   
209   return $mess;
210 }
211
212 sub ret_summary {
213   my ($i, @error) = @_;
214   my $err = join '', @error;
215   $i++;
216
217   my $tid_msg = '';
218   if (defined &Thread::tid) {
219     my $tid = Thread->self->tid;
220     $tid_msg = " thread $tid" if $tid;
221   }
222
223   my %i = caller_info($i);
224   return "$err at $i{file} line $i{line}$tid_msg\n";
225 }
226
227
228 sub short_error_loc {
229   my $cache;
230   my $i = 1;
231   my $lvl = $CarpLevel;
232   {
233     my $called = caller($i++);
234     my $caller = caller($i);
235
236     return 0 unless defined($caller); # What happened?
237     redo if $Internal{$caller};
238     redo if $CarpInternal{$called};
239     redo if trusts($called, $caller, $cache);
240     redo if trusts($caller, $called, $cache);
241     redo unless 0 > --$lvl;
242   }
243   return $i - 1;
244 }
245
246
247 sub shortmess_heavy {
248   return longmess_heavy(@_) if $Verbose;
249   return @_ if ref($_[0]); # don't break references as exceptions
250   my $i = short_error_loc();
251   if ($i) {
252     ret_summary($i, @_);
253   }
254   else {
255     longmess_heavy(@_);
256   }
257 }
258
259 # If a string is too long, trims it with ...
260 sub str_len_trim {
261   my $str = shift;
262   my $max = shift || 0;
263   if (2 < $max and $max < length($str)) {
264     substr($str, $max - 3) = '...';
265   }
266   return $str;
267 }
268
269 # Takes two packages and an optional cache.  Says whether the
270 # first inherits from the second.
271 #
272 # Recursive versions of this have to work to avoid certain
273 # possible endless loops, and when following long chains of
274 # inheritance are less efficient.
275 sub trusts {
276     my $child = shift;
277     my $parent = shift;
278     my $cache = shift || {};
279     my ($known, $partial) = get_status($cache, $child);
280     # Figure out consequences until we have an answer
281     while (@$partial and not exists $known->{$parent}) {
282         my $anc = shift @$partial;
283         next if exists $known->{$anc};
284         $known->{$anc}++;
285         my ($anc_knows, $anc_partial) = get_status($cache, $anc);
286         my @found = keys %$anc_knows;
287         @$known{@found} = ();
288         push @$partial, @$anc_partial;
289     }
290     return exists $known->{$parent};
291 }
292
293 # Takes a package and gives a list of those trusted directly
294 sub trusts_directly {
295     my $class = shift;
296     no strict 'refs';
297     no warnings 'once'; 
298     return @{"$class\::CARP_NOT"}
299       ? @{"$class\::CARP_NOT"}
300       : @{"$class\::ISA"};
301 }
302
303 1;
304