- Moved unused argc, temp variable into small scope.
[dragonfly.git] / contrib / perl5 / lib / overload.pm
1 package overload;
2
3 sub nil {}
4
5 sub OVERLOAD {
6   $package = shift;
7   my %arg = @_;
8   my ($sub, $fb);
9   $ {$package . "::OVERLOAD"}{dummy}++; # Register with magic by touching.
10   *{$package . "::()"} = \&nil; # Make it findable via fetchmethod.
11   for (keys %arg) {
12     if ($_ eq 'fallback') {
13       $fb = $arg{$_};
14     } else {
15       $sub = $arg{$_};
16       if (not ref $sub and $sub !~ /::/) {
17         $ {$package . "::(" . $_} = $sub;
18         $sub = \&nil;
19       }
20       #print STDERR "Setting `$ {'package'}::\cO$_' to \\&`$sub'.\n";
21       *{$package . "::(" . $_} = \&{ $sub };
22     }
23   }
24   ${$package . "::()"} = $fb; # Make it findable too (fallback only).
25 }
26
27 sub import {
28   $package = (caller())[0];
29   # *{$package . "::OVERLOAD"} = \&OVERLOAD;
30   shift;
31   $package->overload::OVERLOAD(@_);
32 }
33
34 sub unimport {
35   $package = (caller())[0];
36   ${$package . "::OVERLOAD"}{dummy}++; # Upgrade the table
37   shift;
38   for (@_) {
39     if ($_ eq 'fallback') {
40       undef $ {$package . "::()"};
41     } else {
42       delete $ {$package . "::"}{"(" . $_};
43     }
44   }
45 }
46
47 sub Overloaded {
48   my $package = shift;
49   $package = ref $package if ref $package;
50   $package->can('()');
51 }
52
53 sub ov_method {
54   my $globref = shift;
55   return undef unless $globref;
56   my $sub = \&{*$globref};
57   return $sub if $sub ne \&nil;
58   return shift->can($ {*$globref});
59 }
60
61 sub OverloadedStringify {
62   my $package = shift;
63   $package = ref $package if ref $package;
64   #$package->can('(""')
65   ov_method mycan($package, '(""'), $package
66     or ov_method mycan($package, '(0+'), $package
67     or ov_method mycan($package, '(bool'), $package
68     or ov_method mycan($package, '(nomethod'), $package;
69 }
70
71 sub Method {
72   my $package = shift;
73   $package = ref $package if ref $package;
74   #my $meth = $package->can('(' . shift);
75   ov_method mycan($package, '(' . shift), $package;
76   #return $meth if $meth ne \&nil;
77   #return $ {*{$meth}};
78 }
79
80 sub AddrRef {
81   my $package = ref $_[0];
82   return "$_[0]" unless $package;
83   bless $_[0], overload::Fake;  # Non-overloaded package
84   my $str = "$_[0]";
85   bless $_[0], $package;        # Back
86   $package . substr $str, index $str, '=';
87 }
88
89 sub StrVal {
90   (OverloadedStringify($_[0])) ?
91     (AddrRef(shift)) :
92     "$_[0]";
93 }
94
95 sub mycan {                             # Real can would leave stubs.
96   my ($package, $meth) = @_;
97   return \*{$package . "::$meth"} if defined &{$package . "::$meth"};
98   my $p;
99   foreach $p (@{$package . "::ISA"}) {
100     my $out = mycan($p, $meth);
101     return $out if $out;
102   }
103   return undef;
104 }
105
106 %constants = (
107               'integer'   =>  0x1000, 
108               'float'     =>  0x2000,
109               'binary'    =>  0x4000,
110               'q'         =>  0x8000,
111               'qr'        => 0x10000,
112              );
113
114 %ops = ( with_assign      => "+ - * / % ** << >> x .",
115          assign           => "+= -= *= /= %= **= <<= >>= x= .=",
116          str_comparison   => "< <= >  >= == !=",
117          '3way_comparison'=> "<=> cmp",
118          num_comparison   => "lt le gt ge eq ne",
119          binary           => "& | ^",
120          unary            => "neg ! ~",
121          mutators         => '++ --',
122          func             => "atan2 cos sin exp abs log sqrt",
123          conversion       => 'bool "" 0+',
124          special          => 'nomethod fallback =');
125
126 sub constant {
127   # Arguments: what, sub
128   while (@_) {
129     $^H{$_[0]} = $_[1];
130     $^H |= $constants{$_[0]} | 0x20000;
131     shift, shift;
132   }
133 }
134
135 sub remove_constant {
136   # Arguments: what, sub
137   while (@_) {
138     delete $^H{$_[0]};
139     $^H &= ~ $constants{$_[0]};
140     shift, shift;
141   }
142 }
143
144 1;
145
146 __END__
147
148 =head1 NAME 
149
150 overload - Package for overloading perl operations
151
152 =head1 SYNOPSIS
153
154     package SomeThing;
155
156     use overload 
157         '+' => \&myadd,
158         '-' => \&mysub;
159         # etc
160     ...
161
162     package main;
163     $a = new SomeThing 57;
164     $b=5+$a;
165     ...
166     if (overload::Overloaded $b) {...}
167     ...
168     $strval = overload::StrVal $b;
169
170 =head1 DESCRIPTION
171
172 =head2 Declaration of overloaded functions
173
174 The compilation directive
175
176     package Number;
177     use overload
178         "+" => \&add, 
179         "*=" => "muas";
180
181 declares function Number::add() for addition, and method muas() in
182 the "class" C<Number> (or one of its base classes)
183 for the assignment form C<*=> of multiplication.  
184
185 Arguments of this directive come in (key, value) pairs.  Legal values
186 are values legal inside a C<&{ ... }> call, so the name of a
187 subroutine, a reference to a subroutine, or an anonymous subroutine
188 will all work.  Note that values specified as strings are
189 interpreted as methods, not subroutines.  Legal keys are listed below.
190
191 The subroutine C<add> will be called to execute C<$a+$b> if $a
192 is a reference to an object blessed into the package C<Number>, or if $a is
193 not an object from a package with defined mathemagic addition, but $b is a
194 reference to a C<Number>.  It can also be called in other situations, like
195 C<$a+=7>, or C<$a++>.  See L<MAGIC AUTOGENERATION>.  (Mathemagical
196 methods refer to methods triggered by an overloaded mathematical
197 operator.)
198
199 Since overloading respects inheritance via the @ISA hierarchy, the
200 above declaration would also trigger overloading of C<+> and C<*=> in
201 all the packages which inherit from C<Number>.
202
203 =head2 Calling Conventions for Binary Operations
204
205 The functions specified in the C<use overload ...> directive are called
206 with three (in one particular case with four, see L<Last Resort>)
207 arguments.  If the corresponding operation is binary, then the first
208 two arguments are the two arguments of the operation.  However, due to
209 general object calling conventions, the first argument should always be
210 an object in the package, so in the situation of C<7+$a>, the
211 order of the arguments is interchanged.  It probably does not matter
212 when implementing the addition method, but whether the arguments
213 are reversed is vital to the subtraction method.  The method can
214 query this information by examining the third argument, which can take
215 three different values:
216
217 =over 7
218
219 =item FALSE
220
221 the order of arguments is as in the current operation.
222
223 =item TRUE
224
225 the arguments are reversed.
226
227 =item C<undef>
228
229 the current operation is an assignment variant (as in
230 C<$a+=7>), but the usual function is called instead.  This additional
231 information can be used to generate some optimizations.  Compare
232 L<Calling Conventions for Mutators>.
233
234 =back
235
236 =head2 Calling Conventions for Unary Operations
237
238 Unary operation are considered binary operations with the second
239 argument being C<undef>.  Thus the functions that overloads C<{"++"}>
240 is called with arguments C<($a,undef,'')> when $a++ is executed.
241
242 =head2 Calling Conventions for Mutators
243
244 Two types of mutators have different calling conventions:
245
246 =over
247
248 =item C<++> and C<-->
249
250 The routines which implement these operators are expected to actually
251 I<mutate> their arguments.  So, assuming that $obj is a reference to a
252 number,
253
254   sub incr { my $n = $ {$_[0]}; ++$n; $_[0] = bless \$n}
255
256 is an appropriate implementation of overloaded C<++>.  Note that
257
258   sub incr { ++$ {$_[0]} ; shift }
259
260 is OK if used with preincrement and with postincrement. (In the case
261 of postincrement a copying will be performed, see L<Copy Constructor>.)
262
263 =item C<x=> and other assignment versions
264
265 There is nothing special about these methods.  They may change the
266 value of their arguments, and may leave it as is.  The result is going
267 to be assigned to the value in the left-hand-side if different from
268 this value.
269
270 This allows for the same method to be used as overloaded C<+=> and
271 C<+>.  Note that this is I<allowed>, but not recommended, since by the
272 semantic of L<"Fallback"> Perl will call the method for C<+> anyway,
273 if C<+=> is not overloaded.
274
275 =back
276
277 B<Warning.>  Due to the presense of assignment versions of operations,
278 routines which may be called in assignment context may create 
279 self-referential structures.  Currently Perl will not free self-referential 
280 structures until cycles are C<explicitly> broken.  You may get problems
281 when traversing your structures too.
282
283 Say, 
284
285   use overload '+' => sub { bless [ \$_[0], \$_[1] ] };
286
287 is asking for trouble, since for code C<$obj += $foo> the subroutine
288 is called as C<$obj = add($obj, $foo, undef)>, or C<$obj = [\$obj, 
289 \$foo]>.  If using such a subroutine is an important optimization, one
290 can overload C<+=> explicitly by a non-"optimized" version, or switch
291 to non-optimized version if C<not defined $_[2]> (see 
292 L<Calling Conventions for Binary Operations>).
293
294 Even if no I<explicit> assignment-variants of operators are present in
295 the script, they may be generated by the optimizer.  Say, C<",$obj,"> or
296 C<',' . $obj . ','> may be both optimized to
297
298   my $tmp = ',' . $obj;    $tmp .= ',';
299
300 =head2 Overloadable Operations
301
302 The following symbols can be specified in C<use overload> directive:
303
304 =over 5
305
306 =item * I<Arithmetic operations>
307
308     "+", "+=", "-", "-=", "*", "*=", "/", "/=", "%", "%=",
309     "**", "**=", "<<", "<<=", ">>", ">>=", "x", "x=", ".", ".=",
310
311 For these operations a substituted non-assignment variant can be called if
312 the assignment variant is not available.  Methods for operations "C<+>",
313 "C<->", "C<+=>", and "C<-=>" can be called to automatically generate
314 increment and decrement methods.  The operation "C<->" can be used to
315 autogenerate missing methods for unary minus or C<abs>.
316
317 See L<"MAGIC AUTOGENERATION">, L<"Calling Conventions for Mutators"> and
318 L<"Calling Conventions for Binary Operations">) for details of these
319 substitutions.
320
321 =item * I<Comparison operations>
322
323     "<",  "<=", ">",  ">=", "==", "!=", "<=>",
324     "lt", "le", "gt", "ge", "eq", "ne", "cmp",
325
326 If the corresponding "spaceship" variant is available, it can be
327 used to substitute for the missing operation.  During C<sort>ing
328 arrays, C<cmp> is used to compare values subject to C<use overload>.
329
330 =item * I<Bit operations>
331
332     "&", "^", "|", "neg", "!", "~",
333
334 "C<neg>" stands for unary minus.  If the method for C<neg> is not
335 specified, it can be autogenerated using the method for
336 subtraction. If the method for "C<!>" is not specified, it can be
337 autogenerated using the methods for "C<bool>", or "C<\"\">", or "C<0+>".
338
339 =item * I<Increment and decrement>
340
341     "++", "--",
342
343 If undefined, addition and subtraction methods can be
344 used instead.  These operations are called both in prefix and
345 postfix form.
346
347 =item * I<Transcendental functions>
348
349     "atan2", "cos", "sin", "exp", "abs", "log", "sqrt",
350
351 If C<abs> is unavailable, it can be autogenerated using methods
352 for "E<lt>" or "E<lt>=E<gt>" combined with either unary minus or subtraction.
353
354 =item * I<Boolean, string and numeric conversion>
355
356     "bool", "\"\"", "0+",
357
358 If one or two of these operations are unavailable, the remaining ones can
359 be used instead.  C<bool> is used in the flow control operators
360 (like C<while>) and for the ternary "C<?:>" operation.  These functions can
361 return any arbitrary Perl value.  If the corresponding operation for this value
362 is overloaded too, that operation will be called again with this value.
363
364 =item * I<Special>
365
366     "nomethod", "fallback", "=",
367
368 see L<SPECIAL SYMBOLS FOR C<use overload>>.
369
370 =back
371
372 See L<"Fallback"> for an explanation of when a missing method can be
373 autogenerated.
374
375 A computer-readable form of the above table is available in the hash
376 %overload::ops, with values being space-separated lists of names:
377
378  with_assign      => '+ - * / % ** << >> x .',
379  assign           => '+= -= *= /= %= **= <<= >>= x= .=',
380  str_comparison   => '< <= > >= == !=',
381  '3way_comparison'=> '<=> cmp',
382  num_comparison   => 'lt le gt ge eq ne',
383  binary           => '& | ^',
384  unary            => 'neg ! ~',
385  mutators         => '++ --',
386  func             => 'atan2 cos sin exp abs log sqrt',
387  conversion       => 'bool "" 0+',
388  special          => 'nomethod fallback ='
389
390 =head2 Inheritance and overloading
391
392 Inheritance interacts with overloading in two ways.
393
394 =over
395
396 =item Strings as values of C<use overload> directive
397
398 If C<value> in
399
400   use overload key => value;
401
402 is a string, it is interpreted as a method name.
403
404 =item Overloading of an operation is inherited by derived classes
405
406 Any class derived from an overloaded class is also overloaded.  The
407 set of overloaded methods is the union of overloaded methods of all
408 the ancestors. If some method is overloaded in several ancestor, then
409 which description will be used is decided by the usual inheritance
410 rules:
411
412 If C<A> inherits from C<B> and C<C> (in this order), C<B> overloads
413 C<+> with C<\&D::plus_sub>, and C<C> overloads C<+> by C<"plus_meth">,
414 then the subroutine C<D::plus_sub> will be called to implement
415 operation C<+> for an object in package C<A>.
416
417 =back
418
419 Note that since the value of the C<fallback> key is not a subroutine,
420 its inheritance is not governed by the above rules.  In the current
421 implementation, the value of C<fallback> in the first overloaded
422 ancestor is used, but this is accidental and subject to change.
423
424 =head1 SPECIAL SYMBOLS FOR C<use overload>
425
426 Three keys are recognized by Perl that are not covered by the above
427 description.
428
429 =head2 Last Resort
430
431 C<"nomethod"> should be followed by a reference to a function of four
432 parameters.  If defined, it is called when the overloading mechanism
433 cannot find a method for some operation.  The first three arguments of
434 this function coincide with the arguments for the corresponding method if
435 it were found, the fourth argument is the symbol
436 corresponding to the missing method.  If several methods are tried,
437 the last one is used.  Say, C<1-$a> can be equivalent to
438
439         &nomethodMethod($a,1,1,"-")
440
441 if the pair C<"nomethod" =E<gt> "nomethodMethod"> was specified in the
442 C<use overload> directive.
443
444 If some operation cannot be resolved, and there is no function
445 assigned to C<"nomethod">, then an exception will be raised via die()--
446 unless C<"fallback"> was specified as a key in C<use overload> directive.
447
448 =head2 Fallback 
449
450 The key C<"fallback"> governs what to do if a method for a particular
451 operation is not found.  Three different cases are possible depending on
452 the value of C<"fallback">:
453
454 =over 16
455
456 =item * C<undef>
457
458 Perl tries to use a
459 substituted method (see L<MAGIC AUTOGENERATION>).  If this fails, it
460 then tries to calls C<"nomethod"> value; if missing, an exception
461 will be raised.
462
463 =item * TRUE
464
465 The same as for the C<undef> value, but no exception is raised.  Instead,
466 it silently reverts to what it would have done were there no C<use overload>
467 present.
468
469 =item * defined, but FALSE
470
471 No autogeneration is tried.  Perl tries to call
472 C<"nomethod"> value, and if this is missing, raises an exception. 
473
474 =back
475
476 B<Note.> C<"fallback"> inheritance via @ISA is not carved in stone
477 yet, see L<"Inheritance and overloading">.
478
479 =head2 Copy Constructor
480
481 The value for C<"="> is a reference to a function with three
482 arguments, i.e., it looks like the other values in C<use
483 overload>. However, it does not overload the Perl assignment
484 operator. This would go against Camel hair.
485
486 This operation is called in the situations when a mutator is applied
487 to a reference that shares its object with some other reference, such
488 as
489
490         $a=$b; 
491         ++$a;
492
493 To make this change $a and not change $b, a copy of C<$$a> is made,
494 and $a is assigned a reference to this new object.  This operation is
495 done during execution of the C<++$a>, and not during the assignment,
496 (so before the increment C<$$a> coincides with C<$$b>).  This is only
497 done if C<++> is expressed via a method for C<'++'> or C<'+='> (or
498 C<nomethod>).  Note that if this operation is expressed via C<'+'>
499 a nonmutator, i.e., as in
500
501         $a=$b; 
502         $a=$a+1;
503
504 then C<$a> does not reference a new copy of C<$$a>, since $$a does not
505 appear as lvalue when the above code is executed.
506
507 If the copy constructor is required during the execution of some mutator,
508 but a method for C<'='> was not specified, it can be autogenerated as a
509 string copy if the object is a plain scalar.
510
511 =over 5
512
513 =item B<Example>
514
515 The actually executed code for 
516
517         $a=$b; 
518         Something else which does not modify $a or $b....
519         ++$a;
520
521 may be
522
523         $a=$b; 
524         Something else which does not modify $a or $b....
525         $a = $a->clone(undef,"");
526         $a->incr(undef,"");
527
528 if $b was mathemagical, and C<'++'> was overloaded with C<\&incr>,
529 C<'='> was overloaded with C<\&clone>.
530
531 =back
532
533 Same behaviour is triggered by C<$b = $a++>, which is consider a synonym for
534 C<$b = $a; ++$a>.
535
536 =head1 MAGIC AUTOGENERATION
537
538 If a method for an operation is not found, and the value for  C<"fallback"> is
539 TRUE or undefined, Perl tries to autogenerate a substitute method for
540 the missing operation based on the defined operations.  Autogenerated method
541 substitutions are possible for the following operations:
542
543 =over 16
544
545 =item I<Assignment forms of arithmetic operations>
546
547 C<$a+=$b> can use the method for C<"+"> if the method for C<"+=">
548 is not defined.
549
550 =item I<Conversion operations> 
551
552 String, numeric, and boolean conversion are calculated in terms of one
553 another if not all of them are defined.
554
555 =item I<Increment and decrement>
556
557 The C<++$a> operation can be expressed in terms of C<$a+=1> or C<$a+1>,
558 and C<$a--> in terms of C<$a-=1> and C<$a-1>.
559
560 =item C<abs($a)>
561
562 can be expressed in terms of C<$aE<lt>0> and C<-$a> (or C<0-$a>).
563
564 =item I<Unary minus>
565
566 can be expressed in terms of subtraction.
567
568 =item I<Negation>
569
570 C<!> and C<not> can be expressed in terms of boolean conversion, or
571 string or numerical conversion.
572
573 =item I<Concatenation>
574
575 can be expressed in terms of string conversion.
576
577 =item I<Comparison operations> 
578
579 can be expressed in terms of its "spaceship" counterpart: either
580 C<E<lt>=E<gt>> or C<cmp>:
581
582     <, >, <=, >=, ==, !=        in terms of <=>
583     lt, gt, le, ge, eq, ne      in terms of cmp
584
585 =item I<Copy operator>
586
587 can be expressed in terms of an assignment to the dereferenced value, if this
588 value is a scalar and not a reference.
589
590 =back
591
592 =head1 Losing overloading
593
594 The restriction for the comparison operation is that even if, for example,
595 `C<cmp>' should return a blessed reference, the autogenerated `C<lt>'
596 function will produce only a standard logical value based on the
597 numerical value of the result of `C<cmp>'.  In particular, a working
598 numeric conversion is needed in this case (possibly expressed in terms of
599 other conversions).
600
601 Similarly, C<.=>  and C<x=> operators lose their mathemagical properties
602 if the string conversion substitution is applied.
603
604 When you chop() a mathemagical object it is promoted to a string and its
605 mathemagical properties are lost.  The same can happen with other
606 operations as well.
607
608 =head1 Run-time Overloading
609
610 Since all C<use> directives are executed at compile-time, the only way to
611 change overloading during run-time is to
612
613     eval 'use overload "+" => \&addmethod';
614
615 You can also use
616
617     eval 'no overload "+", "--", "<="';
618
619 though the use of these constructs during run-time is questionable.
620
621 =head1 Public functions
622
623 Package C<overload.pm> provides the following public functions:
624
625 =over 5
626
627 =item overload::StrVal(arg)
628
629 Gives string value of C<arg> as in absence of stringify overloading.
630
631 =item overload::Overloaded(arg)
632
633 Returns true if C<arg> is subject to overloading of some operations.
634
635 =item overload::Method(obj,op)
636
637 Returns C<undef> or a reference to the method that implements C<op>.
638
639 =back
640
641 =head1 Overloading constants
642
643 For some application Perl parser mangles constants too much.  It is possible
644 to hook into this process via overload::constant() and overload::remove_constant()
645 functions.
646
647 These functions take a hash as an argument.  The recognized keys of this hash
648 are
649
650 =over 8
651
652 =item integer
653
654 to overload integer constants,
655
656 =item float
657
658 to overload floating point constants,
659
660 =item binary
661
662 to overload octal and hexadecimal constants,
663
664 =item q
665
666 to overload C<q>-quoted strings, constant pieces of C<qq>- and C<qx>-quoted
667 strings and here-documents,
668
669 =item qr
670
671 to overload constant pieces of regular expressions.
672
673 =back
674
675 The corresponding values are references to functions which take three arguments:
676 the first one is the I<initial> string form of the constant, the second one
677 is how Perl interprets this constant, the third one is how the constant is used.  
678 Note that the initial string form does not
679 contain string delimiters, and has backslashes in backslash-delimiter 
680 combinations stripped (thus the value of delimiter is not relevant for
681 processing of this string).  The return value of this function is how this 
682 constant is going to be interpreted by Perl.  The third argument is undefined
683 unless for overloaded C<q>- and C<qr>- constants, it is C<q> in single-quote
684 context (comes from strings, regular expressions, and single-quote HERE
685 documents), it is C<tr> for arguments of C<tr>/C<y> operators, 
686 it is C<s> for right-hand side of C<s>-operator, and it is C<qq> otherwise.
687
688 Since an expression C<"ab$cd,,"> is just a shortcut for C<'ab' . $cd . ',,'>,
689 it is expected that overloaded constant strings are equipped with reasonable
690 overloaded catenation operator, otherwise absurd results will result.  
691 Similarly, negative numbers are considered as negations of positive constants.
692
693 Note that it is probably meaningless to call the functions overload::constant()
694 and overload::remove_constant() from anywhere but import() and unimport() methods.
695 From these methods they may be called as
696
697         sub import {
698           shift;
699           return unless @_;
700           die "unknown import: @_" unless @_ == 1 and $_[0] eq ':constant';
701           overload::constant integer => sub {Math::BigInt->new(shift)};
702         }
703
704 B<BUGS> Currently overloaded-ness of constants does not propagate 
705 into C<eval '...'>.
706
707 =head1 IMPLEMENTATION
708
709 What follows is subject to change RSN.
710
711 The table of methods for all operations is cached in magic for the
712 symbol table hash for the package.  The cache is invalidated during
713 processing of C<use overload>, C<no overload>, new function
714 definitions, and changes in @ISA. However, this invalidation remains
715 unprocessed until the next C<bless>ing into the package. Hence if you
716 want to change overloading structure dynamically, you'll need an
717 additional (fake) C<bless>ing to update the table.
718
719 (Every SVish thing has a magic queue, and magic is an entry in that
720 queue.  This is how a single variable may participate in multiple
721 forms of magic simultaneously.  For instance, environment variables
722 regularly have two forms at once: their %ENV magic and their taint
723 magic. However, the magic which implements overloading is applied to
724 the stashes, which are rarely used directly, thus should not slow down
725 Perl.)
726
727 If an object belongs to a package using overload, it carries a special
728 flag.  Thus the only speed penalty during arithmetic operations without
729 overloading is the checking of this flag.
730
731 In fact, if C<use overload> is not present, there is almost no overhead
732 for overloadable operations, so most programs should not suffer
733 measurable performance penalties.  A considerable effort was made to
734 minimize the overhead when overload is used in some package, but the
735 arguments in question do not belong to packages using overload.  When
736 in doubt, test your speed with C<use overload> and without it.  So far
737 there have been no reports of substantial speed degradation if Perl is
738 compiled with optimization turned on.
739
740 There is no size penalty for data if overload is not used. The only
741 size penalty if overload is used in some package is that I<all> the
742 packages acquire a magic during the next C<bless>ing into the
743 package. This magic is three-words-long for packages without
744 overloading, and carries the cache table if the package is overloaded.
745
746 Copying (C<$a=$b>) is shallow; however, a one-level-deep copying is 
747 carried out before any operation that can imply an assignment to the
748 object $a (or $b) refers to, like C<$a++>.  You can override this
749 behavior by defining your own copy constructor (see L<"Copy Constructor">).
750
751 It is expected that arguments to methods that are not explicitly supposed
752 to be changed are constant (but this is not enforced).
753
754 =head1 Metaphor clash
755
756 One may wonder why the semantic of overloaded C<=> is so counter intuitive.
757 If it I<looks> counter intuitive to you, you are subject to a metaphor 
758 clash.  
759
760 Here is a Perl object metaphor:
761
762 I<  object is a reference to blessed data>
763
764 and an arithmetic metaphor:
765
766 I<  object is a thing by itself>.
767
768 The I<main> problem of overloading C<=> is the fact that these metaphors
769 imply different actions on the assignment C<$a = $b> if $a and $b are
770 objects.  Perl-think implies that $a becomes a reference to whatever
771 $b was referencing.  Arithmetic-think implies that the value of "object"
772 $a is changed to become the value of the object $b, preserving the fact
773 that $a and $b are separate entities.
774
775 The difference is not relevant in the absence of mutators.  After
776 a Perl-way assignment an operation which mutates the data referenced by $a
777 would change the data referenced by $b too.  Effectively, after 
778 C<$a = $b> values of $a and $b become I<indistinguishable>.
779
780 On the other hand, anyone who has used algebraic notation knows the 
781 expressive power of the arithmetic metaphor.  Overloading works hard
782 to enable this metaphor while preserving the Perlian way as far as
783 possible.  Since it is not not possible to freely mix two contradicting
784 metaphors, overloading allows the arithmetic way to write things I<as
785 far as all the mutators are called via overloaded access only>.  The
786 way it is done is described in L<Copy Constructor>.
787
788 If some mutator methods are directly applied to the overloaded values,
789 one may need to I<explicitly unlink> other values which references the 
790 same value:
791
792     $a = new Data 23;
793     ...
794     $b = $a;            # $b is "linked" to $a
795     ...
796     $a = $a->clone;     # Unlink $b from $a
797     $a->increment_by(4);
798
799 Note that overloaded access makes this transparent:
800
801     $a = new Data 23;
802     $b = $a;            # $b is "linked" to $a
803     $a += 4;            # would unlink $b automagically
804
805 However, it would not make
806
807     $a = new Data 23;
808     $a = 4;             # Now $a is a plain 4, not 'Data'
809
810 preserve "objectness" of $a.  But Perl I<has> a way to make assignments
811 to an object do whatever you want.  It is just not the overload, but
812 tie()ing interface (see L<perlfunc/tie>).  Adding a FETCH() method
813 which returns the object itself, and STORE() method which changes the 
814 value of the object, one can reproduce the arithmetic metaphor in its
815 completeness, at least for variables which were tie()d from the start.
816
817 (Note that a workaround for a bug may be needed, see L<"BUGS">.)
818
819 =head1 Cookbook
820
821 Please add examples to what follows!
822
823 =head2 Two-face scalars
824
825 Put this in F<two_face.pm> in your Perl library directory:
826
827   package two_face;             # Scalars with separate string and
828                                 # numeric values.
829   sub new { my $p = shift; bless [@_], $p }
830   use overload '""' => \&str, '0+' => \&num, fallback => 1;
831   sub num {shift->[1]}
832   sub str {shift->[0]}
833
834 Use it as follows:
835
836   require two_face;
837   my $seven = new two_face ("vii", 7);
838   printf "seven=$seven, seven=%d, eight=%d\n", $seven, $seven+1;
839   print "seven contains `i'\n" if $seven =~ /i/;
840
841 (The second line creates a scalar which has both a string value, and a
842 numeric value.)  This prints:
843
844   seven=vii, seven=7, eight=8
845   seven contains `i'
846
847 =head2 Symbolic calculator
848
849 Put this in F<symbolic.pm> in your Perl library directory:
850
851   package symbolic;             # Primitive symbolic calculator
852   use overload nomethod => \&wrap;
853
854   sub new { shift; bless ['n', @_] }
855   sub wrap {
856     my ($obj, $other, $inv, $meth) = @_;
857     ($obj, $other) = ($other, $obj) if $inv;
858     bless [$meth, $obj, $other];
859   }
860
861 This module is very unusual as overloaded modules go: it does not
862 provide any usual overloaded operators, instead it provides the L<Last
863 Resort> operator C<nomethod>.  In this example the corresponding
864 subroutine returns an object which encapsulates operations done over
865 the objects: C<new symbolic 3> contains C<['n', 3]>, C<2 + new
866 symbolic 3> contains C<['+', 2, ['n', 3]]>.
867
868 Here is an example of the script which "calculates" the side of
869 circumscribed octagon using the above package:
870
871   require symbolic;
872   my $iter = 1;                 # 2**($iter+2) = 8
873   my $side = new symbolic 1;
874   my $cnt = $iter;
875   
876   while ($cnt--) {
877     $side = (sqrt(1 + $side**2) - 1)/$side;
878   }
879   print "OK\n";
880
881 The value of $side is
882
883   ['/', ['-', ['sqrt', ['+', 1, ['**', ['n', 1], 2]],
884                        undef], 1], ['n', 1]]
885
886 Note that while we obtained this value using a nice little script,
887 there is no simple way to I<use> this value.  In fact this value may
888 be inspected in debugger (see L<perldebug>), but ony if
889 C<bareStringify> B<O>ption is set, and not via C<p> command.
890
891 If one attempts to print this value, then the overloaded operator
892 C<""> will be called, which will call C<nomethod> operator.  The
893 result of this operator will be stringified again, but this result is
894 again of type C<symbolic>, which will lead to an infinite loop.
895
896 Add a pretty-printer method to the module F<symbolic.pm>:
897
898   sub pretty {
899     my ($meth, $a, $b) = @{+shift};
900     $a = 'u' unless defined $a;
901     $b = 'u' unless defined $b;
902     $a = $a->pretty if ref $a;
903     $b = $b->pretty if ref $b;
904     "[$meth $a $b]";
905   } 
906
907 Now one can finish the script by
908
909   print "side = ", $side->pretty, "\n";
910
911 The method C<pretty> is doing object-to-string conversion, so it
912 is natural to overload the operator C<""> using this method.  However,
913 inside such a method it is not necessary to pretty-print the
914 I<components> $a and $b of an object.  In the above subroutine
915 C<"[$meth $a $b]"> is a catenation of some strings and components $a
916 and $b.  If these components use overloading, the catenation operator
917 will look for an overloaded operator C<.>, if not present, it will
918 look for an overloaded operator C<"">.  Thus it is enough to use
919
920   use overload nomethod => \&wrap, '""' => \&str;
921   sub str {
922     my ($meth, $a, $b) = @{+shift};
923     $a = 'u' unless defined $a;
924     $b = 'u' unless defined $b;
925     "[$meth $a $b]";
926   } 
927
928 Now one can change the last line of the script to
929
930   print "side = $side\n";
931
932 which outputs
933
934   side = [/ [- [sqrt [+ 1 [** [n 1 u] 2]] u] 1] [n 1 u]]
935
936 and one can inspect the value in debugger using all the possible
937 methods.  
938
939 Something is is still amiss: consider the loop variable $cnt of the
940 script.  It was a number, not an object.  We cannot make this value of
941 type C<symbolic>, since then the loop will not terminate.
942
943 Indeed, to terminate the cycle, the $cnt should become false.
944 However, the operator C<bool> for checking falsity is overloaded (this
945 time via overloaded C<"">), and returns a long string, thus any object
946 of type C<symbolic> is true.  To overcome this, we need a way to
947 compare an object to 0.  In fact, it is easier to write a numeric
948 conversion routine.
949
950 Here is the text of F<symbolic.pm> with such a routine added (and
951 slightly modified str()):
952
953   package symbolic;             # Primitive symbolic calculator
954   use overload
955     nomethod => \&wrap, '""' => \&str, '0+' => \&num;
956
957   sub new { shift; bless ['n', @_] }
958   sub wrap {
959     my ($obj, $other, $inv, $meth) = @_;
960     ($obj, $other) = ($other, $obj) if $inv;
961     bless [$meth, $obj, $other];
962   }
963   sub str {
964     my ($meth, $a, $b) = @{+shift};
965     $a = 'u' unless defined $a;
966     if (defined $b) {
967       "[$meth $a $b]";
968     } else {
969       "[$meth $a]";
970     }
971   } 
972   my %subr = ( n => sub {$_[0]}, 
973                sqrt => sub {sqrt $_[0]}, 
974                '-' => sub {shift() - shift()},
975                '+' => sub {shift() + shift()},
976                '/' => sub {shift() / shift()},
977                '*' => sub {shift() * shift()},
978                '**' => sub {shift() ** shift()},
979              );
980   sub num {
981     my ($meth, $a, $b) = @{+shift};
982     my $subr = $subr{$meth} 
983       or die "Do not know how to ($meth) in symbolic";
984     $a = $a->num if ref $a eq __PACKAGE__;
985     $b = $b->num if ref $b eq __PACKAGE__;
986     $subr->($a,$b);
987   }
988
989 All the work of numeric conversion is done in %subr and num().  Of
990 course, %subr is not complete, it contains only operators used in the
991 example below.  Here is the extra-credit question: why do we need an
992 explicit recursion in num()?  (Answer is at the end of this section.)
993
994 Use this module like this:
995
996   require symbolic;
997   my $iter = new symbolic 2;    # 16-gon
998   my $side = new symbolic 1;
999   my $cnt = $iter;
1000   
1001   while ($cnt) {
1002     $cnt = $cnt - 1;            # Mutator `--' not implemented
1003     $side = (sqrt(1 + $side**2) - 1)/$side;
1004   }
1005   printf "%s=%f\n", $side, $side;
1006   printf "pi=%f\n", $side*(2**($iter+2));
1007
1008 It prints (without so many line breaks)
1009
1010   [/ [- [sqrt [+ 1 [** [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1]
1011                           [n 1]] 2]]] 1]
1012      [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]]]=0.198912
1013   pi=3.182598
1014
1015 The above module is very primitive.  It does not implement
1016 mutator methods (C<++>, C<-=> and so on), does not do deep copying
1017 (not required without mutators!), and implements only those arithmetic
1018 operations which are used in the example.
1019
1020 To implement most arithmetic operations is easy, one should just use
1021 the tables of operations, and change the code which fills %subr to
1022
1023   my %subr = ( 'n' => sub {$_[0]} );
1024   foreach my $op (split " ", $overload::ops{with_assign}) {
1025     $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}";
1026   }
1027   my @bins = qw(binary 3way_comparison num_comparison str_comparison);
1028   foreach my $op (split " ", "@overload::ops{ @bins }") {
1029     $subr{$op} = eval "sub {shift() $op shift()}";
1030   }
1031   foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
1032     print "defining `$op'\n";
1033     $subr{$op} = eval "sub {$op shift()}";
1034   }
1035
1036 Due to L<Calling Conventions for Mutators>, we do not need anything
1037 special to make C<+=> and friends work, except filling C<+=> entry of
1038 %subr, and defining a copy constructor (needed since Perl has no
1039 way to know that the implementation of C<'+='> does not mutate
1040 the argument, compare L<Copy Constructor>).
1041
1042 To implement a copy constructor, add C<'=' => \&cpy> to C<use overload>
1043 line, and code (this code assumes that mutators change things one level
1044 deep only, so recursive copying is not needed):
1045
1046   sub cpy {
1047     my $self = shift;
1048     bless [@$self], ref $self;
1049   }
1050
1051 To make C<++> and C<--> work, we need to implement actual mutators, 
1052 either directly, or in C<nomethod>.  We continue to do things inside
1053 C<nomethod>, thus add
1054
1055     if ($meth eq '++' or $meth eq '--') {
1056       @$obj = ($meth, (bless [@$obj]), 1); # Avoid circular reference
1057       return $obj;
1058     }
1059
1060 after the first line of wrap().  This is not a most effective 
1061 implementation, one may consider
1062
1063   sub inc { $_[0] = bless ['++', shift, 1]; }
1064
1065 instead.
1066
1067 As a final remark, note that one can fill %subr by
1068
1069   my %subr = ( 'n' => sub {$_[0]} );
1070   foreach my $op (split " ", $overload::ops{with_assign}) {
1071     $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}";
1072   }
1073   my @bins = qw(binary 3way_comparison num_comparison str_comparison);
1074   foreach my $op (split " ", "@overload::ops{ @bins }") {
1075     $subr{$op} = eval "sub {shift() $op shift()}";
1076   }
1077   foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
1078     $subr{$op} = eval "sub {$op shift()}";
1079   }
1080   $subr{'++'} = $subr{'+'};
1081   $subr{'--'} = $subr{'-'};
1082
1083 This finishes implementation of a primitive symbolic calculator in 
1084 50 lines of Perl code.  Since the numeric values of subexpressions 
1085 are not cached, the calculator is very slow.
1086
1087 Here is the answer for the exercise: In the case of str(), we need no
1088 explicit recursion since the overloaded C<.>-operator will fall back
1089 to an existing overloaded operator C<"">.  Overloaded arithmetic
1090 operators I<do not> fall back to numeric conversion if C<fallback> is
1091 not explicitly requested.  Thus without an explicit recursion num()
1092 would convert C<['+', $a, $b]> to C<$a + $b>, which would just rebuild
1093 the argument of num().
1094
1095 If you wonder why defaults for conversion are different for str() and
1096 num(), note how easy it was to write the symbolic calculator.  This
1097 simplicity is due to an appropriate choice of defaults.  One extra
1098 note: due to the explicit recursion num() is more fragile than sym():
1099 we need to explicitly check for the type of $a and $b.  If components
1100 $a and $b happen to be of some related type, this may lead to problems.
1101
1102 =head2 I<Really> symbolic calculator
1103
1104 One may wonder why we call the above calculator symbolic.  The reason
1105 is that the actual calculation of the value of expression is postponed
1106 until the value is I<used>.
1107
1108 To see it in action, add a method
1109
1110   sub STORE { 
1111     my $obj = shift; 
1112     $#$obj = 1; 
1113     @$obj->[0,1] = ('=', shift);
1114   }
1115
1116 to the package C<symbolic>.  After this change one can do
1117
1118   my $a = new symbolic 3;
1119   my $b = new symbolic 4;
1120   my $c = sqrt($a**2 + $b**2);
1121
1122 and the numeric value of $c becomes 5.  However, after calling
1123
1124   $a->STORE(12);  $b->STORE(5);
1125
1126 the numeric value of $c becomes 13.  There is no doubt now that the module
1127 symbolic provides a I<symbolic> calculator indeed.
1128
1129 To hide the rough edges under the hood, provide a tie()d interface to the
1130 package C<symbolic> (compare with L<Metaphor clash>).  Add methods
1131
1132   sub TIESCALAR { my $pack = shift; $pack->new(@_) }
1133   sub FETCH { shift }
1134   sub nop {  }          # Around a bug
1135
1136 (the bug is described in L<"BUGS">).  One can use this new interface as
1137
1138   tie $a, 'symbolic', 3;
1139   tie $b, 'symbolic', 4;
1140   $a->nop;  $b->nop;    # Around a bug
1141
1142   my $c = sqrt($a**2 + $b**2);
1143
1144 Now numeric value of $c is 5.  After C<$a = 12; $b = 5> the numeric value
1145 of $c becomes 13.  To insulate the user of the module add a method
1146
1147   sub vars { my $p = shift; tie($_, $p), $_->nop foreach @_; }
1148
1149 Now
1150
1151   my ($a, $b);
1152   symbolic->vars($a, $b);
1153   my $c = sqrt($a**2 + $b**2);
1154
1155   $a = 3; $b = 4;
1156   printf "c5  %s=%f\n", $c, $c;
1157
1158   $a = 12; $b = 5;
1159   printf "c13  %s=%f\n", $c, $c;
1160
1161 shows that the numeric value of $c follows changes to the values of $a
1162 and $b.
1163
1164 =head1 AUTHOR
1165
1166 Ilya Zakharevich E<lt>F<ilya@math.mps.ohio-state.edu>E<gt>.
1167
1168 =head1 DIAGNOSTICS
1169
1170 When Perl is run with the B<-Do> switch or its equivalent, overloading
1171 induces diagnostic messages.
1172
1173 Using the C<m> command of Perl debugger (see L<perldebug>) one can
1174 deduce which operations are overloaded (and which ancestor triggers
1175 this overloading). Say, if C<eq> is overloaded, then the method C<(eq>
1176 is shown by debugger. The method C<()> corresponds to the C<fallback>
1177 key (in fact a presence of this method shows that this package has
1178 overloading enabled, and it is what is used by the C<Overloaded>
1179 function of module C<overload>).
1180
1181 =head1 BUGS
1182
1183 Because it is used for overloading, the per-package hash %OVERLOAD now
1184 has a special meaning in Perl. The symbol table is filled with names
1185 looking like line-noise.
1186
1187 For the purpose of inheritance every overloaded package behaves as if
1188 C<fallback> is present (possibly undefined). This may create
1189 interesting effects if some package is not overloaded, but inherits
1190 from two overloaded packages.
1191
1192 Relation between overloading and tie()ing is broken.  Overloading is 
1193 triggered or not basing on the I<previous> class of tie()d value.
1194
1195 This happens because the presence of overloading is checked too early, 
1196 before any tie()d access is attempted.  If the FETCH()ed class of the
1197 tie()d value does not change, a simple workaround is to access the value 
1198 immediately after tie()ing, so that after this call the I<previous> class
1199 coincides with the current one.
1200
1201 B<Needed:> a way to fix this without a speed penalty.
1202
1203 Barewords are not covered by overloaded string constants.
1204
1205 This document is confusing.  There are grammos and misleading language
1206 used in places.  It would seem a total rewrite is needed.
1207
1208 =cut
1209