Carp.pm 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923
  1. package Carp;
  2. { use 5.006; }
  3. use strict;
  4. use warnings;
  5. BEGIN {
  6. # Very old versions of warnings.pm load Carp. This can go wrong due
  7. # to the circular dependency. If warnings is invoked before Carp,
  8. # then warnings starts by loading Carp, then Carp (above) tries to
  9. # invoke warnings, and gets nothing because warnings is in the process
  10. # of loading and hasn't defined its import method yet. If we were
  11. # only turning on warnings ("use warnings" above) this wouldn't be too
  12. # bad, because Carp would just gets the state of the -w switch and so
  13. # might not get some warnings that it wanted. The real problem is
  14. # that we then want to turn off Unicode warnings, but "no warnings
  15. # 'utf8'" won't be effective if we're in this circular-dependency
  16. # situation. So, if warnings.pm is an affected version, we turn
  17. # off all warnings ourselves by directly setting ${^WARNING_BITS}.
  18. # On unaffected versions, we turn off just Unicode warnings, via
  19. # the proper API.
  20. if(!defined($warnings::VERSION) || eval($warnings::VERSION) < 1.06) {
  21. ${^WARNING_BITS} = "";
  22. } else {
  23. "warnings"->unimport("utf8");
  24. }
  25. }
  26. sub _fetch_sub { # fetch sub without autovivifying
  27. my($pack, $sub) = @_;
  28. $pack .= '::';
  29. # only works with top-level packages
  30. return unless exists($::{$pack});
  31. for ($::{$pack}) {
  32. return unless ref \$_ eq 'GLOB' && *$_{HASH} && exists $$_{$sub};
  33. for ($$_{$sub}) {
  34. return ref \$_ eq 'GLOB' ? *$_{CODE} : undef
  35. }
  36. }
  37. }
  38. # UTF8_REGEXP_PROBLEM is a compile-time constant indicating whether Carp
  39. # must avoid applying a regular expression to an upgraded (is_utf8)
  40. # string. There are multiple problems, on different Perl versions,
  41. # that require this to be avoided. All versions prior to 5.13.8 will
  42. # load utf8_heavy.pl for the swash system, even if the regexp doesn't
  43. # use character classes. Perl 5.6 and Perls [5.11.2, 5.13.11) exhibit
  44. # specific problems when Carp is being invoked in the aftermath of a
  45. # syntax error.
  46. BEGIN {
  47. if("$]" < 5.013011) {
  48. *UTF8_REGEXP_PROBLEM = sub () { 1 };
  49. } else {
  50. *UTF8_REGEXP_PROBLEM = sub () { 0 };
  51. }
  52. }
  53. # is_utf8() is essentially the utf8::is_utf8() function, which indicates
  54. # whether a string is represented in the upgraded form (using UTF-8
  55. # internally). As utf8::is_utf8() is only available from Perl 5.8
  56. # onwards, extra effort is required here to make it work on Perl 5.6.
  57. BEGIN {
  58. if(defined(my $sub = _fetch_sub utf8 => 'is_utf8')) {
  59. *is_utf8 = $sub;
  60. } else {
  61. # black magic for perl 5.6
  62. *is_utf8 = sub { unpack("C", "\xaa".$_[0]) != 170 };
  63. }
  64. }
  65. # The downgrade() function defined here is to be used for attempts to
  66. # downgrade where it is acceptable to fail. It must be called with a
  67. # second argument that is a true value.
  68. BEGIN {
  69. if(defined(my $sub = _fetch_sub utf8 => 'downgrade')) {
  70. *downgrade = \&{"utf8::downgrade"};
  71. } else {
  72. *downgrade = sub {
  73. my $r = "";
  74. my $l = length($_[0]);
  75. for(my $i = 0; $i != $l; $i++) {
  76. my $o = ord(substr($_[0], $i, 1));
  77. return if $o > 255;
  78. $r .= chr($o);
  79. }
  80. $_[0] = $r;
  81. };
  82. }
  83. }
  84. our $VERSION = '1.36';
  85. our $MaxEvalLen = 0;
  86. our $Verbose = 0;
  87. our $CarpLevel = 0;
  88. our $MaxArgLen = 64; # How much of each argument to print. 0 = all.
  89. our $MaxArgNums = 8; # How many arguments to print. 0 = all.
  90. our $RefArgFormatter = undef; # allow caller to format reference arguments
  91. require Exporter;
  92. our @ISA = ('Exporter');
  93. our @EXPORT = qw(confess croak carp);
  94. our @EXPORT_OK = qw(cluck verbose longmess shortmess);
  95. our @EXPORT_FAIL = qw(verbose); # hook to enable verbose mode
  96. # The members of %Internal are packages that are internal to perl.
  97. # Carp will not report errors from within these packages if it
  98. # can. The members of %CarpInternal are internal to Perl's warning
  99. # system. Carp will not report errors from within these packages
  100. # either, and will not report calls *to* these packages for carp and
  101. # croak. They replace $CarpLevel, which is deprecated. The
  102. # $Max(EvalLen|(Arg(Len|Nums)) variables are used to specify how the eval
  103. # text and function arguments should be formatted when printed.
  104. our %CarpInternal;
  105. our %Internal;
  106. # disable these by default, so they can live w/o require Carp
  107. $CarpInternal{Carp}++;
  108. $CarpInternal{warnings}++;
  109. $Internal{Exporter}++;
  110. $Internal{'Exporter::Heavy'}++;
  111. # if the caller specifies verbose usage ("perl -MCarp=verbose script.pl")
  112. # then the following method will be called by the Exporter which knows
  113. # to do this thanks to @EXPORT_FAIL, above. $_[1] will contain the word
  114. # 'verbose'.
  115. sub export_fail { shift; $Verbose = shift if $_[0] eq 'verbose'; @_ }
  116. sub _cgc {
  117. no strict 'refs';
  118. return \&{"CORE::GLOBAL::caller"} if defined &{"CORE::GLOBAL::caller"};
  119. return;
  120. }
  121. sub longmess {
  122. local($!, $^E);
  123. # Icky backwards compatibility wrapper. :-(
  124. #
  125. # The story is that the original implementation hard-coded the
  126. # number of call levels to go back, so calls to longmess were off
  127. # by one. Other code began calling longmess and expecting this
  128. # behaviour, so the replacement has to emulate that behaviour.
  129. my $cgc = _cgc();
  130. my $call_pack = $cgc ? $cgc->() : caller();
  131. if ( $Internal{$call_pack} or $CarpInternal{$call_pack} ) {
  132. return longmess_heavy(@_);
  133. }
  134. else {
  135. local $CarpLevel = $CarpLevel + 1;
  136. return longmess_heavy(@_);
  137. }
  138. }
  139. our @CARP_NOT;
  140. sub shortmess {
  141. local($!, $^E);
  142. my $cgc = _cgc();
  143. # Icky backwards compatibility wrapper. :-(
  144. local @CARP_NOT = $cgc ? $cgc->() : caller();
  145. shortmess_heavy(@_);
  146. }
  147. sub croak { die shortmess @_ }
  148. sub confess { die longmess @_ }
  149. sub carp { warn shortmess @_ }
  150. sub cluck { warn longmess @_ }
  151. BEGIN {
  152. if("$]" >= 5.015002 || ("$]" >= 5.014002 && "$]" < 5.015) ||
  153. ("$]" >= 5.012005 && "$]" < 5.013)) {
  154. *CALLER_OVERRIDE_CHECK_OK = sub () { 1 };
  155. } else {
  156. *CALLER_OVERRIDE_CHECK_OK = sub () { 0 };
  157. }
  158. }
  159. sub caller_info {
  160. my $i = shift(@_) + 1;
  161. my %call_info;
  162. my $cgc = _cgc();
  163. {
  164. # Some things override caller() but forget to implement the
  165. # @DB::args part of it, which we need. We check for this by
  166. # pre-populating @DB::args with a sentinel which no-one else
  167. # has the address of, so that we can detect whether @DB::args
  168. # has been properly populated. However, on earlier versions
  169. # of perl this check tickles a bug in CORE::caller() which
  170. # leaks memory. So we only check on fixed perls.
  171. @DB::args = \$i if CALLER_OVERRIDE_CHECK_OK;
  172. package DB;
  173. @call_info{
  174. qw(pack file line sub has_args wantarray evaltext is_require) }
  175. = $cgc ? $cgc->($i) : caller($i);
  176. }
  177. unless ( defined $call_info{file} ) {
  178. return ();
  179. }
  180. my $sub_name = Carp::get_subname( \%call_info );
  181. if ( $call_info{has_args} ) {
  182. my @args;
  183. if (CALLER_OVERRIDE_CHECK_OK && @DB::args == 1
  184. && ref $DB::args[0] eq ref \$i
  185. && $DB::args[0] == \$i ) {
  186. @DB::args = (); # Don't let anyone see the address of $i
  187. local $@;
  188. my $where = eval {
  189. my $func = $cgc or return '';
  190. my $gv =
  191. (_fetch_sub B => 'svref_2object' or return '')
  192. ->($func)->GV;
  193. my $package = $gv->STASH->NAME;
  194. my $subname = $gv->NAME;
  195. return unless defined $package && defined $subname;
  196. # returning CORE::GLOBAL::caller isn't useful for tracing the cause:
  197. return if $package eq 'CORE::GLOBAL' && $subname eq 'caller';
  198. " in &${package}::$subname";
  199. } || '';
  200. @args
  201. = "** Incomplete caller override detected$where; \@DB::args were not set **";
  202. }
  203. else {
  204. @args = @DB::args;
  205. my $overflow;
  206. if ( $MaxArgNums and @args > $MaxArgNums )
  207. { # More than we want to show?
  208. $#args = $MaxArgNums;
  209. $overflow = 1;
  210. }
  211. @args = map { Carp::format_arg($_) } @args;
  212. if ($overflow) {
  213. push @args, '...';
  214. }
  215. }
  216. # Push the args onto the subroutine
  217. $sub_name .= '(' . join( ', ', @args ) . ')';
  218. }
  219. $call_info{sub_name} = $sub_name;
  220. return wantarray() ? %call_info : \%call_info;
  221. }
  222. # Transform an argument to a function into a string.
  223. our $in_recurse;
  224. sub format_arg {
  225. my $arg = shift;
  226. if ( ref($arg) ) {
  227. # legitimate, let's not leak it.
  228. if (!$in_recurse &&
  229. do {
  230. local $@;
  231. local $in_recurse = 1;
  232. local $SIG{__DIE__} = sub{};
  233. eval {$arg->can('CARP_TRACE') }
  234. })
  235. {
  236. return $arg->CARP_TRACE();
  237. }
  238. elsif (!$in_recurse &&
  239. defined($RefArgFormatter) &&
  240. do {
  241. local $@;
  242. local $in_recurse = 1;
  243. local $SIG{__DIE__} = sub{};
  244. eval {$arg = $RefArgFormatter->($arg); 1}
  245. })
  246. {
  247. return $arg;
  248. }
  249. else
  250. {
  251. my $sub = _fetch_sub(overload => 'StrVal');
  252. return $sub ? &$sub($arg) : "$arg";
  253. }
  254. }
  255. return "undef" if !defined($arg);
  256. downgrade($arg, 1);
  257. return $arg if !(UTF8_REGEXP_PROBLEM && is_utf8($arg)) &&
  258. $arg =~ /\A-?[0-9]+(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?\z/;
  259. my $suffix = "";
  260. if ( 2 < $MaxArgLen and $MaxArgLen < length($arg) ) {
  261. substr ( $arg, $MaxArgLen - 3 ) = "";
  262. $suffix = "...";
  263. }
  264. if(UTF8_REGEXP_PROBLEM && is_utf8($arg)) {
  265. for(my $i = length($arg); $i--; ) {
  266. my $c = substr($arg, $i, 1);
  267. my $x = substr($arg, 0, 0); # work around bug on Perl 5.8.{1,2}
  268. if($c eq "\"" || $c eq "\\" || $c eq "\$" || $c eq "\@") {
  269. substr $arg, $i, 0, "\\";
  270. next;
  271. }
  272. my $o = ord($c);
  273. # This code is repeated in Regexp::CARP_TRACE()
  274. if ($] ge 5.007_003) {
  275. substr $arg, $i, 1, sprintf("\\x{%x}", $o)
  276. if utf8::native_to_unicode($o) < utf8::native_to_unicode(0x20)
  277. || utf8::native_to_unicode($o) > utf8::native_to_unicode(0x7e);
  278. } elsif (ord("A") == 65) {
  279. substr $arg, $i, 1, sprintf("\\x{%x}", $o)
  280. if $o < 0x20 || $o > 0x7e;
  281. } else { # Early EBCDIC
  282. # 3 EBCDIC code pages supported then; all controls but one
  283. # are the code points below SPACE. The other one is 0x5F on
  284. # POSIX-BC; FF on the other two.
  285. substr $arg, $i, 1, sprintf("\\x{%x}", $o)
  286. if $o < ord(" ") || ((ord ("^") == 106)
  287. ? $o == 0x5f
  288. : $o == 0xff);
  289. }
  290. }
  291. } else {
  292. $arg =~ s/([\"\\\$\@])/\\$1/g;
  293. # This is all the ASCII printables spelled-out. It is portable to all
  294. # Perl versions and platforms (such as EBCDIC). There are other more
  295. # compact ways to do this, but may not work everywhere every version.
  296. $arg =~ s/([^ !"\$\%#'()*+,\-.\/0123456789:;<=>?\@ABCDEFGHIJKLMNOPQRSTUVWXYZ\[\\\]^_`abcdefghijklmnopqrstuvwxyz\{|}~])/sprintf("\\x{%x}",ord($1))/eg;
  297. }
  298. downgrade($arg, 1);
  299. return "\"".$arg."\"".$suffix;
  300. }
  301. sub Regexp::CARP_TRACE {
  302. my $arg = "$_[0]";
  303. downgrade($arg, 1);
  304. if(UTF8_REGEXP_PROBLEM && is_utf8($arg)) {
  305. for(my $i = length($arg); $i--; ) {
  306. my $o = ord(substr($arg, $i, 1));
  307. my $x = substr($arg, 0, 0); # work around bug on Perl 5.8.{1,2}
  308. # This code is repeated in format_arg()
  309. if ($] ge 5.007_003) {
  310. substr $arg, $i, 1, sprintf("\\x{%x}", $o)
  311. if utf8::native_to_unicode($o) < utf8::native_to_unicode(0x20)
  312. || utf8::native_to_unicode($o) > utf8::native_to_unicode(0x7e);
  313. } elsif (ord("A") == 65) {
  314. substr $arg, $i, 1, sprintf("\\x{%x}", $o)
  315. if $o < 0x20 || $o > 0x7e;
  316. } else { # Early EBCDIC
  317. substr $arg, $i, 1, sprintf("\\x{%x}", $o)
  318. if $o < ord(" ") || ((ord ("^") == 106)
  319. ? $o == 0x5f
  320. : $o == 0xff);
  321. }
  322. }
  323. } else {
  324. # See comment in format_arg() about this same regex.
  325. $arg =~ s/([^ !"\$\%#'()*+,\-.\/0123456789:;<=>?\@ABCDEFGHIJKLMNOPQRSTUVWXYZ\[\\\]^_`abcdefghijklmnopqrstuvwxyz\{|}~])/sprintf("\\x{%x}",ord($1))/eg;
  326. }
  327. downgrade($arg, 1);
  328. my $suffix = "";
  329. if($arg =~ /\A\(\?\^?([a-z]*)(?:-[a-z]*)?:(.*)\)\z/s) {
  330. ($suffix, $arg) = ($1, $2);
  331. }
  332. if ( 2 < $MaxArgLen and $MaxArgLen < length($arg) ) {
  333. substr ( $arg, $MaxArgLen - 3 ) = "";
  334. $suffix = "...".$suffix;
  335. }
  336. return "qr($arg)$suffix";
  337. }
  338. # Takes an inheritance cache and a package and returns
  339. # an anon hash of known inheritances and anon array of
  340. # inheritances which consequences have not been figured
  341. # for.
  342. sub get_status {
  343. my $cache = shift;
  344. my $pkg = shift;
  345. $cache->{$pkg} ||= [ { $pkg => $pkg }, [ trusts_directly($pkg) ] ];
  346. return @{ $cache->{$pkg} };
  347. }
  348. # Takes the info from caller() and figures out the name of
  349. # the sub/require/eval
  350. sub get_subname {
  351. my $info = shift;
  352. if ( defined( $info->{evaltext} ) ) {
  353. my $eval = $info->{evaltext};
  354. if ( $info->{is_require} ) {
  355. return "require $eval";
  356. }
  357. else {
  358. $eval =~ s/([\\\'])/\\$1/g;
  359. return "eval '" . str_len_trim( $eval, $MaxEvalLen ) . "'";
  360. }
  361. }
  362. # this can happen on older perls when the sub (or the stash containing it)
  363. # has been deleted
  364. if ( !defined( $info->{sub} ) ) {
  365. return '__ANON__::__ANON__';
  366. }
  367. return ( $info->{sub} eq '(eval)' ) ? 'eval {...}' : $info->{sub};
  368. }
  369. # Figures out what call (from the point of view of the caller)
  370. # the long error backtrace should start at.
  371. sub long_error_loc {
  372. my $i;
  373. my $lvl = $CarpLevel;
  374. {
  375. ++$i;
  376. my $cgc = _cgc();
  377. my @caller = $cgc ? $cgc->($i) : caller($i);
  378. my $pkg = $caller[0];
  379. unless ( defined($pkg) ) {
  380. # This *shouldn't* happen.
  381. if (%Internal) {
  382. local %Internal;
  383. $i = long_error_loc();
  384. last;
  385. }
  386. elsif (defined $caller[2]) {
  387. # this can happen when the stash has been deleted
  388. # in that case, just assume that it's a reasonable place to
  389. # stop (the file and line data will still be intact in any
  390. # case) - the only issue is that we can't detect if the
  391. # deleted package was internal (so don't do that then)
  392. # -doy
  393. redo unless 0 > --$lvl;
  394. last;
  395. }
  396. else {
  397. return 2;
  398. }
  399. }
  400. redo if $CarpInternal{$pkg};
  401. redo unless 0 > --$lvl;
  402. redo if $Internal{$pkg};
  403. }
  404. return $i - 1;
  405. }
  406. sub longmess_heavy {
  407. return @_ if ref( $_[0] ); # don't break references as exceptions
  408. my $i = long_error_loc();
  409. return ret_backtrace( $i, @_ );
  410. }
  411. # Returns a full stack backtrace starting from where it is
  412. # told.
  413. sub ret_backtrace {
  414. my ( $i, @error ) = @_;
  415. my $mess;
  416. my $err = join '', @error;
  417. $i++;
  418. my $tid_msg = '';
  419. if ( defined &threads::tid ) {
  420. my $tid = threads->tid;
  421. $tid_msg = " thread $tid" if $tid;
  422. }
  423. my %i = caller_info($i);
  424. $mess = "$err at $i{file} line $i{line}$tid_msg";
  425. if( defined $. ) {
  426. local $@ = '';
  427. local $SIG{__DIE__};
  428. eval {
  429. CORE::die;
  430. };
  431. if($@ =~ /^Died at .*(, <.*?> line \d+).$/ ) {
  432. $mess .= $1;
  433. }
  434. }
  435. $mess .= "\.\n";
  436. while ( my %i = caller_info( ++$i ) ) {
  437. $mess .= "\t$i{sub_name} called at $i{file} line $i{line}$tid_msg\n";
  438. }
  439. return $mess;
  440. }
  441. sub ret_summary {
  442. my ( $i, @error ) = @_;
  443. my $err = join '', @error;
  444. $i++;
  445. my $tid_msg = '';
  446. if ( defined &threads::tid ) {
  447. my $tid = threads->tid;
  448. $tid_msg = " thread $tid" if $tid;
  449. }
  450. my %i = caller_info($i);
  451. return "$err at $i{file} line $i{line}$tid_msg\.\n";
  452. }
  453. sub short_error_loc {
  454. # You have to create your (hash)ref out here, rather than defaulting it
  455. # inside trusts *on a lexical*, as you want it to persist across calls.
  456. # (You can default it on $_[2], but that gets messy)
  457. my $cache = {};
  458. my $i = 1;
  459. my $lvl = $CarpLevel;
  460. {
  461. my $cgc = _cgc();
  462. my $called = $cgc ? $cgc->($i) : caller($i);
  463. $i++;
  464. my $caller = $cgc ? $cgc->($i) : caller($i);
  465. if (!defined($caller)) {
  466. my @caller = $cgc ? $cgc->($i) : caller($i);
  467. if (@caller) {
  468. # if there's no package but there is other caller info, then
  469. # the package has been deleted - treat this as a valid package
  470. # in this case
  471. redo if defined($called) && $CarpInternal{$called};
  472. redo unless 0 > --$lvl;
  473. last;
  474. }
  475. else {
  476. return 0;
  477. }
  478. }
  479. redo if $Internal{$caller};
  480. redo if $CarpInternal{$caller};
  481. redo if $CarpInternal{$called};
  482. redo if trusts( $called, $caller, $cache );
  483. redo if trusts( $caller, $called, $cache );
  484. redo unless 0 > --$lvl;
  485. }
  486. return $i - 1;
  487. }
  488. sub shortmess_heavy {
  489. return longmess_heavy(@_) if $Verbose;
  490. return @_ if ref( $_[0] ); # don't break references as exceptions
  491. my $i = short_error_loc();
  492. if ($i) {
  493. ret_summary( $i, @_ );
  494. }
  495. else {
  496. longmess_heavy(@_);
  497. }
  498. }
  499. # If a string is too long, trims it with ...
  500. sub str_len_trim {
  501. my $str = shift;
  502. my $max = shift || 0;
  503. if ( 2 < $max and $max < length($str) ) {
  504. substr( $str, $max - 3 ) = '...';
  505. }
  506. return $str;
  507. }
  508. # Takes two packages and an optional cache. Says whether the
  509. # first inherits from the second.
  510. #
  511. # Recursive versions of this have to work to avoid certain
  512. # possible endless loops, and when following long chains of
  513. # inheritance are less efficient.
  514. sub trusts {
  515. my $child = shift;
  516. my $parent = shift;
  517. my $cache = shift;
  518. my ( $known, $partial ) = get_status( $cache, $child );
  519. # Figure out consequences until we have an answer
  520. while ( @$partial and not exists $known->{$parent} ) {
  521. my $anc = shift @$partial;
  522. next if exists $known->{$anc};
  523. $known->{$anc}++;
  524. my ( $anc_knows, $anc_partial ) = get_status( $cache, $anc );
  525. my @found = keys %$anc_knows;
  526. @$known{@found} = ();
  527. push @$partial, @$anc_partial;
  528. }
  529. return exists $known->{$parent};
  530. }
  531. # Takes a package and gives a list of those trusted directly
  532. sub trusts_directly {
  533. my $class = shift;
  534. no strict 'refs';
  535. my $stash = \%{"$class\::"};
  536. for my $var (qw/ CARP_NOT ISA /) {
  537. # Don't try using the variable until we know it exists,
  538. # to avoid polluting the caller's namespace.
  539. if ( $stash->{$var} && *{$stash->{$var}}{ARRAY} && @{$stash->{$var}} ) {
  540. return @{$stash->{$var}}
  541. }
  542. }
  543. return;
  544. }
  545. if(!defined($warnings::VERSION) ||
  546. do { no warnings "numeric"; $warnings::VERSION < 1.03 }) {
  547. # Very old versions of warnings.pm import from Carp. This can go
  548. # wrong due to the circular dependency. If Carp is invoked before
  549. # warnings, then Carp starts by loading warnings, then warnings
  550. # tries to import from Carp, and gets nothing because Carp is in
  551. # the process of loading and hasn't defined its import method yet.
  552. # So we work around that by manually exporting to warnings here.
  553. no strict "refs";
  554. *{"warnings::$_"} = \&$_ foreach @EXPORT;
  555. }
  556. 1;
  557. __END__
  558. =head1 NAME
  559. Carp - alternative warn and die for modules
  560. =head1 SYNOPSIS
  561. use Carp;
  562. # warn user (from perspective of caller)
  563. carp "string trimmed to 80 chars";
  564. # die of errors (from perspective of caller)
  565. croak "We're outta here!";
  566. # die of errors with stack backtrace
  567. confess "not implemented";
  568. # cluck, longmess and shortmess not exported by default
  569. use Carp qw(cluck longmess shortmess);
  570. cluck "This is how we got here!";
  571. $long_message = longmess( "message from cluck() or confess()" );
  572. $short_message = shortmess( "message from carp() or croak()" );
  573. =head1 DESCRIPTION
  574. The Carp routines are useful in your own modules because
  575. they act like C<die()> or C<warn()>, but with a message which is more
  576. likely to be useful to a user of your module. In the case of
  577. C<cluck()> and C<confess()>, that context is a summary of every
  578. call in the call-stack; C<longmess()> returns the contents of the error
  579. message.
  580. For a shorter message you can use C<carp()> or C<croak()> which report the
  581. error as being from where your module was called. C<shortmess()> returns the
  582. contents of this error message. There is no guarantee that that is where the
  583. error was, but it is a good educated guess.
  584. C<Carp> takes care not to clobber the status variables C<$!> and C<$^E>
  585. in the course of assembling its error messages. This means that a
  586. C<$SIG{__DIE__}> or C<$SIG{__WARN__}> handler can capture the error
  587. information held in those variables, if it is required to augment the
  588. error message, and if the code calling C<Carp> left useful values there.
  589. Of course, C<Carp> can't guarantee the latter.
  590. You can also alter the way the output and logic of C<Carp> works, by
  591. changing some global variables in the C<Carp> namespace. See the
  592. section on C<GLOBAL VARIABLES> below.
  593. Here is a more complete description of how C<carp> and C<croak> work.
  594. What they do is search the call-stack for a function call stack where
  595. they have not been told that there shouldn't be an error. If every
  596. call is marked safe, they give up and give a full stack backtrace
  597. instead. In other words they presume that the first likely looking
  598. potential suspect is guilty. Their rules for telling whether
  599. a call shouldn't generate errors work as follows:
  600. =over 4
  601. =item 1.
  602. Any call from a package to itself is safe.
  603. =item 2.
  604. Packages claim that there won't be errors on calls to or from
  605. packages explicitly marked as safe by inclusion in C<@CARP_NOT>, or
  606. (if that array is empty) C<@ISA>. The ability to override what
  607. @ISA says is new in 5.8.
  608. =item 3.
  609. The trust in item 2 is transitive. If A trusts B, and B
  610. trusts C, then A trusts C. So if you do not override C<@ISA>
  611. with C<@CARP_NOT>, then this trust relationship is identical to,
  612. "inherits from".
  613. =item 4.
  614. Any call from an internal Perl module is safe. (Nothing keeps
  615. user modules from marking themselves as internal to Perl, but
  616. this practice is discouraged.)
  617. =item 5.
  618. Any call to Perl's warning system (eg Carp itself) is safe.
  619. (This rule is what keeps it from reporting the error at the
  620. point where you call C<carp> or C<croak>.)
  621. =item 6.
  622. C<$Carp::CarpLevel> can be set to skip a fixed number of additional
  623. call levels. Using this is not recommended because it is very
  624. difficult to get it to behave correctly.
  625. =back
  626. =head2 Forcing a Stack Trace
  627. As a debugging aid, you can force Carp to treat a croak as a confess
  628. and a carp as a cluck across I<all> modules. In other words, force a
  629. detailed stack trace to be given. This can be very helpful when trying
  630. to understand why, or from where, a warning or error is being generated.
  631. This feature is enabled by 'importing' the non-existent symbol
  632. 'verbose'. You would typically enable it by saying
  633. perl -MCarp=verbose script.pl
  634. or by including the string C<-MCarp=verbose> in the PERL5OPT
  635. environment variable.
  636. Alternately, you can set the global variable C<$Carp::Verbose> to true.
  637. See the C<GLOBAL VARIABLES> section below.
  638. =head2 Stack Trace formatting
  639. At each stack level, the subroutine's name is displayed along with
  640. its parameters. For simple scalars, this is sufficient. For complex
  641. data types, such as objects and other references, this can simply
  642. display C<'HASH(0x1ab36d8)'>.
  643. Carp gives two ways to control this.
  644. =over 4
  645. =item 1.
  646. For objects, a method, C<CARP_TRACE>, will be called, if it exists. If
  647. this method doesn't exist, or it recurses into C<Carp>, or it otherwise
  648. throws an exception, this is skipped, and Carp moves on to the next option,
  649. otherwise checking stops and the string returned is used. It is recommended
  650. that the object's type is part of the string to make debugging easier.
  651. =item 2.
  652. For any type of reference, C<$Carp::RefArgFormatter> is checked (see below).
  653. This variable is expected to be a code reference, and the current parameter
  654. is passed in. If this function doesn't exist (the variable is undef), or
  655. it recurses into C<Carp>, or it otherwise throws an exception, this is
  656. skipped, and Carp moves on to the next option, otherwise checking stops
  657. and the string returned is used.
  658. =item 3.
  659. Otherwise, if neither C<CARP_TRACE> nor C<$Carp::RefArgFormatter> is
  660. available, stringify the value ignoring any overloading.
  661. =back
  662. =head1 GLOBAL VARIABLES
  663. =head2 $Carp::MaxEvalLen
  664. This variable determines how many characters of a string-eval are to
  665. be shown in the output. Use a value of C<0> to show all text.
  666. Defaults to C<0>.
  667. =head2 $Carp::MaxArgLen
  668. This variable determines how many characters of each argument to a
  669. function to print. Use a value of C<0> to show the full length of the
  670. argument.
  671. Defaults to C<64>.
  672. =head2 $Carp::MaxArgNums
  673. This variable determines how many arguments to each function to show.
  674. Use a value of C<0> to show all arguments to a function call.
  675. Defaults to C<8>.
  676. =head2 $Carp::Verbose
  677. This variable makes C<carp()> and C<croak()> generate stack backtraces
  678. just like C<cluck()> and C<confess()>. This is how C<use Carp 'verbose'>
  679. is implemented internally.
  680. Defaults to C<0>.
  681. =head2 $Carp::RefArgFormatter
  682. This variable sets a general argument formatter to display references.
  683. Plain scalars and objects that implement C<CARP_TRACE> will not go through
  684. this formatter. Calling C<Carp> from within this function is not supported.
  685. local $Carp::RefArgFormatter = sub {
  686. require Data::Dumper;
  687. Data::Dumper::Dump($_[0]); # not necessarily safe
  688. };
  689. =head2 @CARP_NOT
  690. This variable, I<in your package>, says which packages are I<not> to be
  691. considered as the location of an error. The C<carp()> and C<cluck()>
  692. functions will skip over callers when reporting where an error occurred.
  693. NB: This variable must be in the package's symbol table, thus:
  694. # These work
  695. our @CARP_NOT; # file scope
  696. use vars qw(@CARP_NOT); # package scope
  697. @My::Package::CARP_NOT = ... ; # explicit package variable
  698. # These don't work
  699. sub xyz { ... @CARP_NOT = ... } # w/o declarations above
  700. my @CARP_NOT; # even at top-level
  701. Example of use:
  702. package My::Carping::Package;
  703. use Carp;
  704. our @CARP_NOT;
  705. sub bar { .... or _error('Wrong input') }
  706. sub _error {
  707. # temporary control of where'ness, __PACKAGE__ is implicit
  708. local @CARP_NOT = qw(My::Friendly::Caller);
  709. carp(@_)
  710. }
  711. This would make C<Carp> report the error as coming from a caller not
  712. in C<My::Carping::Package>, nor from C<My::Friendly::Caller>.
  713. Also read the L</DESCRIPTION> section above, about how C<Carp> decides
  714. where the error is reported from.
  715. Use C<@CARP_NOT>, instead of C<$Carp::CarpLevel>.
  716. Overrides C<Carp>'s use of C<@ISA>.
  717. =head2 %Carp::Internal
  718. This says what packages are internal to Perl. C<Carp> will never
  719. report an error as being from a line in a package that is internal to
  720. Perl. For example:
  721. $Carp::Internal{ (__PACKAGE__) }++;
  722. # time passes...
  723. sub foo { ... or confess("whatever") };
  724. would give a full stack backtrace starting from the first caller
  725. outside of __PACKAGE__. (Unless that package was also internal to
  726. Perl.)
  727. =head2 %Carp::CarpInternal
  728. This says which packages are internal to Perl's warning system. For
  729. generating a full stack backtrace this is the same as being internal
  730. to Perl, the stack backtrace will not start inside packages that are
  731. listed in C<%Carp::CarpInternal>. But it is slightly different for
  732. the summary message generated by C<carp> or C<croak>. There errors
  733. will not be reported on any lines that are calling packages in
  734. C<%Carp::CarpInternal>.
  735. For example C<Carp> itself is listed in C<%Carp::CarpInternal>.
  736. Therefore the full stack backtrace from C<confess> will not start
  737. inside of C<Carp>, and the short message from calling C<croak> is
  738. not placed on the line where C<croak> was called.
  739. =head2 $Carp::CarpLevel
  740. This variable determines how many additional call frames are to be
  741. skipped that would not otherwise be when reporting where an error
  742. occurred on a call to one of C<Carp>'s functions. It is fairly easy
  743. to count these call frames on calls that generate a full stack
  744. backtrace. However it is much harder to do this accounting for calls
  745. that generate a short message. Usually people skip too many call
  746. frames. If they are lucky they skip enough that C<Carp> goes all of
  747. the way through the call stack, realizes that something is wrong, and
  748. then generates a full stack backtrace. If they are unlucky then the
  749. error is reported from somewhere misleading very high in the call
  750. stack.
  751. Therefore it is best to avoid C<$Carp::CarpLevel>. Instead use
  752. C<@CARP_NOT>, C<%Carp::Internal> and C<%Carp::CarpInternal>.
  753. Defaults to C<0>.
  754. =head1 BUGS
  755. The Carp routines don't handle exception objects currently.
  756. If called with a first argument that is a reference, they simply
  757. call die() or warn(), as appropriate.
  758. =head1 SEE ALSO
  759. L<Carp::Always>,
  760. L<Carp::Clan>
  761. =head1 AUTHOR
  762. The Carp module first appeared in Larry Wall's perl 5.000 distribution.
  763. Since then it has been modified by several of the perl 5 porters.
  764. Andrew Main (Zefram) <zefram@fysh.org> divested Carp into an independent
  765. distribution.
  766. =head1 COPYRIGHT
  767. Copyright (C) 1994-2013 Larry Wall
  768. Copyright (C) 2011, 2012, 2013 Andrew Main (Zefram) <zefram@fysh.org>
  769. =head1 LICENSE
  770. This module is free software; you can redistribute it and/or modify it
  771. under the same terms as Perl itself.