home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2004 December / PCpro_2004_12.ISO / files / webserver / tsw / TSW_3.4.0.exe / Apache2 / perl / Assert.pm < prev    next >
Encoding:
Perl POD Document  |  2001-10-01  |  14.1 KB  |  498 lines

  1. package Carp::Assert;
  2.  
  3. require 5.004;
  4.  
  5. use strict qw(subs vars);
  6. use Exporter;
  7.  
  8. use vars qw(@ISA $VERSION %EXPORT_TAGS);
  9.  
  10. BEGIN {
  11.     $VERSION = '0.17';
  12.  
  13.     @ISA = qw(Exporter);
  14.  
  15.     %EXPORT_TAGS = (
  16.                     NDEBUG => [qw(assert affirm should shouldnt DEBUG)],
  17.                    );
  18.     $EXPORT_TAGS{DEBUG} = $EXPORT_TAGS{NDEBUG};
  19.     Exporter::export_tags(qw(NDEBUG DEBUG));
  20. }
  21.  
  22. # constant.pm, alas, adds too much load time (yes, I benchmarked it)
  23. sub REAL_DEBUG  ()  { 1 }       # CONSTANT
  24. sub NDEBUG      ()  { 0 }       # CONSTANT
  25.  
  26. # Export the proper DEBUG flag according to if :NDEBUG is set.
  27. # Also export noop versions of our routines if NDEBUG
  28. sub noop { undef }
  29. sub noop_affirm (&;$) { undef };
  30.  
  31. sub import {
  32.     my $env_ndebug = exists $ENV{PERL_NDEBUG} ? $ENV{PERL_NDEBUG}
  33.                                               : $ENV{'NDEBUG'};
  34.     if( grep(/^:NDEBUG$/, @_) or $env_ndebug ) {
  35.         my $caller = caller;
  36.         foreach my $func (grep !/^DEBUG$/, @{$EXPORT_TAGS{'NDEBUG'}}) {
  37.             if( $func eq 'affirm' ) {
  38.                 *{$caller.'::'.$func} = \&noop_affirm;
  39.             } else {
  40.                 *{$caller.'::'.$func} = \&noop;
  41.             }
  42.         }
  43.         *{$caller.'::DEBUG'} = \&NDEBUG;
  44.     }
  45.     else {
  46.         *DEBUG = *REAL_DEBUG;
  47.         Carp::Assert->_export_to_level(1, @_);
  48.     }
  49. }
  50.  
  51.  
  52. # 5.004's Exporter doesn't have export_to_level.
  53. sub _export_to_level
  54. {
  55.       my $pkg = shift;
  56.       my $level = shift;
  57.       (undef) = shift;                  # XXX redundant arg
  58.       my $callpkg = caller($level);
  59.       $pkg->export($callpkg, @_);
  60. }
  61.  
  62.  
  63. sub unimport {
  64.     *DEBUG = *NDEBUG;
  65.     push @_, ':NDEBUG';
  66.     goto &import;
  67. }
  68.  
  69.  
  70. # Can't call confess() here or the stack trace will be wrong.
  71. sub _fail_msg {
  72.     my($name) = shift;
  73.     my $msg = 'Assertion';
  74.     $msg   .= " ($name)" if defined $name;
  75.     $msg   .= " failed!\n";
  76.     return $msg;
  77. }
  78.  
  79.  
  80. =head1 NAME
  81.  
  82. Carp::Assert - executable comments
  83.  
  84. =head1 SYNOPSIS
  85.  
  86.     # Assertions are on.
  87.     use Carp::Assert;
  88.  
  89.     $next_sunrise_time = sunrise();
  90.  
  91.     # Assert that the sun must rise in the next 24 hours.
  92.     assert(($next_sunrise_time - time) < 24*60*60) if DEBUG;
  93.  
  94.     # Assert that your customer's primary credit card is active
  95.     affirm {
  96.         my @cards = @{$customer->credit_cards};
  97.         $cards[0]->is_active;
  98.     };
  99.  
  100.  
  101.     # Assertions are off.
  102.     no Carp::Assert;
  103.  
  104.     $next_pres = divine_next_president();
  105.  
  106.     # Assert that if you predict Dan Quayle will be the next president
  107.     # your crystal ball might need some polishing.  However, since
  108.     # assertions are off, IT COULD HAPPEN!
  109.     shouldnt($next_pres, 'Dan Quayle') if DEBUG;
  110.  
  111.  
  112. =head1 DESCRIPTION
  113.  
  114. =for testing
  115. use Carp::Assert;
  116.  
  117.  
  118.     "We are ready for any unforseen event that may or may not 
  119.     occur."
  120.         - Dan Quayle
  121.  
  122. Carp::Assert is intended for a purpose like the ANSI C library
  123. assert.h.  If you're already familiar with assert.h, then you can
  124. probably skip this and go straight to the FUNCTIONS section.
  125.  
  126. Assertions are the explict expressions of your assumptions about the
  127. reality your program is expected to deal with, and a declaration of
  128. those which it is not.  They are used to prevent your program from
  129. blissfully processing garbage inputs (garbage in, garbage out becomes
  130. garbage in, error out) and to tell you when you've produced garbage
  131. output.  (If I was going to be a cynic about Perl and the user nature,
  132. I'd say there are no user inputs but garbage, and Perl produces
  133. nothing but...)
  134.  
  135. An assertion is used to prevent the impossible from being asked of
  136. your code, or at least tell you when it does.  For example:
  137.  
  138. =for example begin
  139.  
  140.     # Take the square root of a number.
  141.     sub my_sqrt {
  142.         my($num) = shift;
  143.  
  144.         # the square root of a negative number is imaginary.
  145.         assert($num >= 0);
  146.  
  147.         return sqrt $num;
  148.     }
  149.  
  150. =for example end
  151.  
  152. =for example_testing
  153. is( my_sqrt(4),  2,            'my_sqrt example with good input' );
  154. ok( !eval{ my_sqrt(-1); 1 },   '  and pukes on bad' );
  155.  
  156. The assertion will warn you if a negative number was handed to your
  157. subroutine, a reality the routine has no intention of dealing with.
  158.  
  159. An assertion should also be used a something of a reality check, to
  160. make sure what your code just did really did happen:
  161.  
  162.     open(FILE, $filename) || die $!;
  163.     @stuff = <FILE>;
  164.     @stuff = do_something(@stuff);
  165.  
  166.     # I should have some stuff.
  167.     assert(@stuff > 0);
  168.  
  169. The assertion makes sure you have some @stuff at the end.  Maybe the
  170. file was empty, maybe do_something() returned an empty list... either
  171. way, the assert() will give you a clue as to where the problem lies,
  172. rather than 50 lines down at when you wonder why your program isn't
  173. printing anything.
  174.  
  175. Since assertions are designed for debugging and will remove themelves
  176. from production code, your assertions should be carefully crafted so
  177. as to not have any side-effects, change any variables or otherwise
  178. have any effect on your program.  Here is an example of a bad
  179. assertation:
  180.  
  181.     assert($error = 1 if $king ne 'Henry');  # Bad!
  182.  
  183. It sets an error flag which may then be used somewhere else in your
  184. program. When you shut off your assertions with the $DEBUG flag,
  185. $error will no longer be set.
  186.  
  187. Here's another example of B<bad> use:
  188.  
  189.     assert($next_pres ne 'Dan Quayle' or goto Canada);  # Bad!
  190.  
  191. This assertion has the side effect of moving to Canada should it fail.
  192. This is a very bad assertion since error handling should not be
  193. placed in an assertion, nor should it have side-effects.
  194.  
  195. In short, an assertion is an executable comment.  For instance, instead
  196. of writing this
  197.  
  198.     # $life ends with a '!'
  199.     $life = begin_life();
  200.  
  201. you'd replace the comment with an assertion which B<enforces> the comment.
  202.  
  203.     $life = begin_life();
  204.     assert( $life =~ /!$/ );
  205.  
  206. =for testing
  207. my $life = 'Whimper!';
  208. ok( eval { assert( $life =~ /!$/ ); 1 },   'life ends with a bang' );
  209.  
  210.  
  211. =head1 FUNCTIONS
  212.  
  213. =over 4
  214.  
  215. =item B<assert>
  216.  
  217.     assert(EXPR) if DEBUG;
  218.     assert(EXPR, $name) if DEBUG;
  219.  
  220. assert's functionality is effected by compile time value of the DEBUG
  221. constant, controlled by saying C<use Carp::Assert> or C<no
  222. Carp::Assert>.  In the former case, assert will function as below.
  223. Otherwise, the assert function will compile itself out of the program.
  224. See L<Debugging vs Production> for details.
  225.  
  226. =for testing
  227. {
  228.   package Some::Other;
  229.   no Carp::Assert;
  230.   ::ok( eval { assert(0) if DEBUG; 1 } );
  231. }
  232.  
  233. Give assert an expression, assert will Carp::confess() if that
  234. expression is false, otherwise it does nothing.  (DO NOT use the
  235. return value of assert for anything, I mean it... really!).
  236.  
  237. =for testing
  238. ok( eval { assert(1); 1 } );
  239. ok( !eval { assert(0); 1 } );
  240.  
  241. The error from assert will look something like this:
  242.  
  243.     Assertion failed!
  244.             Carp::Assert::assert(0) called at prog line 23
  245.             main::foo called at prog line 50
  246.  
  247. =for testing
  248. eval { assert(0) };
  249. like( $@, '/^Assertion failed!/',       'error format' );
  250. like( $@, '/Carp::Assert::assert\(0\) called at/',      '  with stack trace' );
  251.  
  252. Indicating that in the file "prog" an assert failed inside the
  253. function main::foo() on line 23 and that foo() was in turn called from
  254. line 50 in the same file.
  255.  
  256. If given a $name, assert() will incorporate this into your error message,
  257. giving users something of a better idea what's going on.
  258.  
  259.     assert( Dogs->isa('People'), 'Dogs are people, too!' ) if DEBUG;
  260.     # Result - "Assertion (Dogs are people, too!) failed!"
  261.  
  262. =for testing
  263. eval { assert( Dogs->isa('People'), 'Dogs are people, too!' ); };
  264. like( $@, '/^Assertion \(Dogs are people, too!\) failed!/', 'names' );
  265.  
  266. =cut
  267.  
  268. sub assert ($;$) {
  269.     unless($_[0]) {
  270.         require Carp;
  271.         Carp::confess( _fail_msg($_[1]) );
  272.     }
  273.     return undef;
  274. }
  275.  
  276.  
  277. =item B<affirm>
  278.  
  279.     affirm BLOCK if DEBUG;
  280.     affirm BLOCK $name if DEBUG;
  281.  
  282. Very similar to assert(), but instead of taking just a simple
  283. expression it takes an entire block of code and evaluates it to make
  284. sure its true.  This can allow more complicated assertions than
  285. assert() can without letting the debugging code leak out into
  286. production and without having to smash together several
  287. statements into one.
  288.  
  289. =for example begin
  290.  
  291.     affirm {
  292.         my $customer = Customer->new($customerid);
  293.         my @cards = $customer->credit_cards;
  294.         grep { $_->is_active } @cards;
  295.     } "Our customer has an active credit card";
  296.  
  297. =for example end
  298.  
  299. affirm() also has the nice side effect that if you forgot the C<if DEBUG>
  300. suffix its arguments will not be evaluated at all.  This can be nice
  301. if you stick affirm()s with expensive checks into hot loops and other
  302. time-sensitive parts of your program.
  303.  
  304. =cut
  305.  
  306. sub affirm (&;$) {
  307.     unless( eval { &{$_[0]}; } ) {
  308.         my $name = $_[1];
  309.         if( !defined $name and eval { require B::Deparse } ) {
  310.             $name = B::Deparse->new->coderef2text($_[0]);
  311.         }
  312.         require Carp;
  313.         Carp::confess( _fail_msg($name) );
  314.     }
  315.     return undef;
  316. }
  317.  
  318. =item B<should>
  319.  
  320. =item B<shouldnt>
  321.  
  322.     should  ($this, $shouldbe)   if DEBUG;
  323.     shouldnt($this, $shouldntbe) if DEBUG;
  324.  
  325. Similar to assert(), it is specially for simple "this should be that"
  326. or "this should be anything but that" style of assertions.
  327.  
  328. Due to Perl's lack of a good macro system, assert() can only report
  329. where something failed, but it can't report I<what> failed or I<how>.
  330. should() and shouldnt() can produce more informative error messages:
  331.  
  332.     Assertion ('this' should be 'that'!) failed!
  333.             Carp::Assert::should('this', 'that') called at moof line 29
  334.             main::foo() called at moof line 58
  335.  
  336. So this:
  337.  
  338.     should($this, $that) if DEBUG;
  339.  
  340. is similar to this:
  341.  
  342.     assert($this eq $that) if DEBUG;
  343.  
  344. except for the better error message.
  345.  
  346. Currently, should() and shouldnt() can only do simple eq and ne tests
  347. (respectively).  Future versions may allow regexes.
  348.  
  349. =cut
  350.  
  351. sub should ($$) {
  352.     unless($_[0] eq $_[1]) {
  353.         require Carp;
  354.         &Carp::confess( _fail_msg("'$_[0]' should be '$_[1]'!") );
  355.     }
  356.     return undef;
  357. }
  358.  
  359. sub shouldnt ($$) {
  360.     unless($_[0] ne $_[1]) {
  361.         require Carp;
  362.         &Carp::confess( _fail_msg("'$_[0]' shouldn't be that!") );
  363.     }
  364.     return undef;
  365. }
  366.  
  367. # Sorry, I couldn't resist.
  368. sub shouldn't ($$) {     # emacs cperl-mode madness #' sub {
  369.     my $env_ndebug = exists $ENV{PERL_NDEBUG} ? $ENV{PERL_NDEBUG}
  370.                                               : $ENV{'NDEBUG'};
  371.     if( $env_ndebug ) {
  372.         return undef;
  373.     }
  374.     else {
  375.         shouldnt($_[0], $_[1]);
  376.     }
  377. }
  378.  
  379.  
  380. =head1 Debugging vs Production
  381.  
  382. Because assertions are extra code and because it is sometimes necessary to
  383. place them in 'hot' portions of your code where speed is paramount,
  384. Carp::Assert provides the option to remove its assert() calls from your
  385. program.
  386.  
  387. So, we provide a way to force Perl to inline the switched off assert()
  388. routine, thereby removing almost all performance impact on your production
  389. code.
  390.  
  391.     no Carp::Assert;  # assertions are off.
  392.     assert(1==1) if DEBUG;
  393.  
  394. DEBUG is a constant set to 0.  Adding the 'if DEBUG' condition on your
  395. assert() call gives perl the cue to go ahead and remove assert() call from
  396. your program entirely, since the if conditional will always be false.
  397.  
  398.     # With C<no Carp::Assert> the assert() has no impact.
  399.     for (1..100) {
  400.         assert( do_some_really_time_consuming_check ) if DEBUG;
  401.     }
  402.  
  403. If C<if DEBUG> gets too annoying, you can always use affirm().
  404.  
  405.     # Once again, affirm() has (almost) no impact with C<no Carp::Assert>
  406.     for (1..100) {
  407.         affirm { do_some_really_time_consuming_check };
  408.     }
  409.  
  410. Another way to switch off all asserts, system wide, is to define the
  411. NDEBUG or the PERL_NDEBUG environment variable.
  412.  
  413. You can safely leave out the "if DEBUG" part, but then your assert()
  414. function will always execute (and its arguments evaluated and time
  415. spent).  To get around this, use affirm().  You still have the
  416. overhead of calling a function but at least its arguments will not be
  417. evaluated.
  418.  
  419.  
  420. =head1 Differences from ANSI C
  421.  
  422. assert() is intended to act like the function from ANSI C fame. 
  423. Unfortunately, due to perl's lack of macros or strong inlining, it's not
  424. nearly as unobtrusive.
  425.  
  426. Well, the obvious one is the "if DEBUG" part.  This is cleanest way I could
  427. think of to cause each assert() call and its arguments to be removed from
  428. the program at compile-time, like the ANSI C macro does.
  429.  
  430. Also, this version of assert does not report the statement which
  431. failed, just the line number and call frame via Carp::confess.  You
  432. can't do C<assert('$a == $b')> because $a and $b will probably be
  433. lexical, and thus unavailable to assert().  But with Perl, unlike C,
  434. you always have the source to look through, so the need isn't as
  435. great.
  436.  
  437.  
  438. =head1 EFFICIENCY
  439.  
  440. With C<no Carp::Assert> (or NDEBUG) and using the C<if DEBUG> suffixes
  441. on all your assertions, Carp::Assert has almost no impact on your
  442. production code.  I say almost because it does still add some load-time
  443. to your code (I've tried to reduce this as much as possible).
  444.  
  445. If you forget the C<if DEBUG> on an C<assert()>, C<should()> or
  446. C<shouldnt()>, its arguments are still evaluated and thus will impact
  447. your code.  You'll also have the extra overhead of calling a
  448. subroutine (even if that subroutine does nothing).
  449.  
  450. Forgetting the C<if DEBUG> on an C<affirm()> is not so bad.  While you
  451. still have the overhead of calling a subroutine (one that does
  452. nothing) it will B<not> evaluate its code block and that can save
  453. alot.
  454.  
  455. Try to remember the B<if DEBUG>.
  456.  
  457.  
  458. =head1 ENVIRONMENT
  459.  
  460. =over 4
  461.  
  462. =item NDEBUG
  463.  
  464. Defining NDEBUG switches off all assertions.  It has the same effect
  465. as changing "use Carp::Assert" to "no Carp::Assert" but it effects all
  466. code.
  467.  
  468. =item PERL_NDEBUG
  469.  
  470. Same as NDEBUG and will override it.  Its provided to give you
  471. something which won't conflict with any C programs you might be
  472. working on at the same time.
  473.  
  474. =back
  475.  
  476.  
  477. =head1 BUGS, CAVETS and other MUSINGS
  478.  
  479. Someday, Perl will have an inline pragma, and the C<if DEBUG>
  480. bletcherousness will go away.
  481.  
  482. affirm() mucks with the expression's caller and it is run in an eval
  483. so anything that checks $^S will be wrong.
  484.  
  485. Yes, there is a C<shouldn't> routine.  It mostly works, but you B<must>
  486. put the C<if DEBUG> after it.
  487.  
  488. It would be nice if we could warn about missing C<if DEBUG>.
  489.  
  490.  
  491. =head1 AUTHOR
  492.  
  493. Michael G Schwern <schwern@pobox.com>
  494.  
  495. =cut
  496.  
  497. return q|You don't just EAT the largest turnip in the world!|;
  498.