This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Fix example #4 in perlXStut
[perl5.git] / lib / overload.pm
CommitLineData
4633a7c4
LW
1package overload;
2
a6006777
PP
3sub nil {}
4
4633a7c4
LW
5sub OVERLOAD {
6 $package = shift;
7 my %arg = @_;
a6006777
PP
8 my ($sub, $fb);
9 $ {$package . "::OVERLOAD"}{dummy}++; # Register with magic by touching.
10 *{$package . "::()"} = \&nil; # Make it findable via fetchmethod.
4633a7c4 11 for (keys %arg) {
a6006777
PP
12 if ($_ eq 'fallback') {
13 $fb = $arg{$_};
14 } else {
15 $sub = $arg{$_};
16 if (not ref $sub and $sub !~ /::/) {
17 $sub = "${'package'}::$sub";
18 }
19 #print STDERR "Setting `$ {'package'}::\cO$_' to \\&`$sub'.\n";
20 *{$package . "::(" . $_} = \&{ $sub };
21 }
4633a7c4 22 }
a6006777 23 ${$package . "::()"} = $fb; # Make it findable too (fallback only).
4633a7c4
LW
24}
25
26sub import {
27 $package = (caller())[0];
28 # *{$package . "::OVERLOAD"} = \&OVERLOAD;
29 shift;
30 $package->overload::OVERLOAD(@_);
31}
32
33sub unimport {
34 $package = (caller())[0];
a6006777 35 ${$package . "::OVERLOAD"}{dummy}++; # Upgrade the table
4633a7c4
LW
36 shift;
37 for (@_) {
a6006777
PP
38 if ($_ eq 'fallback') {
39 undef $ {$package . "::()"};
40 } else {
41 delete $ {$package . "::"}{"(" . $_};
42 }
4633a7c4
LW
43 }
44}
45
46sub Overloaded {
a6006777
PP
47 my $package = shift;
48 $package = ref $package if ref $package;
49 $package->can('()');
4633a7c4
LW
50}
51
52sub OverloadedStringify {
a6006777
PP
53 my $package = shift;
54 $package = ref $package if ref $package;
55 $package->can('(""')
4633a7c4
LW
56}
57
58sub Method {
a6006777
PP
59 my $package = shift;
60 $package = ref $package if ref $package;
61 $package->can('(' . shift)
4633a7c4
LW
62}
63
64sub AddrRef {
a6006777
PP
65 my $package = ref $_[0];
66 return "$_[0]" unless $package;
67 bless $_[0], overload::Fake; # Non-overloaded package
4633a7c4
LW
68 my $str = "$_[0]";
69 bless $_[0], $package; # Back
a6006777 70 $package . substr $str, index $str, '=';
4633a7c4
LW
71}
72
73sub StrVal {
a6006777
PP
74 (OverloadedStringify($_[0])) ?
75 (AddrRef(shift)) :
4633a7c4
LW
76 "$_[0]";
77}
78
791;
80
81__END__
82
83=head1 NAME
84
cb1a09d0 85overload - Package for overloading perl operations
4633a7c4
LW
86
87=head1 SYNOPSIS
88
89 package SomeThing;
90
91 use overload
92 '+' => \&myadd,
93 '-' => \&mysub;
94 # etc
95 ...
96
97 package main;
98 $a = new SomeThing 57;
99 $b=5+$a;
100 ...
101 if (overload::Overloaded $b) {...}
102 ...
103 $strval = overload::StrVal $b;
104
105=head1 CAVEAT SCRIPTOR
106
107Overloading of operators is a subject not to be taken lightly.
108Neither its precise implementation, syntax, nor semantics are
109100% endorsed by Larry Wall. So any of these may be changed
110at some point in the future.
111
112=head1 DESCRIPTION
113
114=head2 Declaration of overloaded functions
115
116The compilation directive
117
118 package Number;
119 use overload
120 "+" => \&add,
121 "*=" => "muas";
122
123declares function Number::add() for addition, and method muas() in
124the "class" C<Number> (or one of its base classes)
125for the assignment form C<*=> of multiplication.
126
127Arguments of this directive come in (key, value) pairs. Legal values
128are values legal inside a C<&{ ... }> call, so the name of a subroutine,
129a reference to a subroutine, or an anonymous subroutine will all work.
130Legal keys are listed below.
131
132The subroutine C<add> will be called to execute C<$a+$b> if $a
133is a reference to an object blessed into the package C<Number>, or if $a is
134not an object from a package with defined mathemagic addition, but $b is a
135reference to a C<Number>. It can also be called in other situations, like
136C<$a+=7>, or C<$a++>. See L<MAGIC AUTOGENERATION>. (Mathemagical
137methods refer to methods triggered by an overloaded mathematical
138operator.)
139
140=head2 Calling Conventions for Binary Operations
141
142The functions specified in the C<use overload ...> directive are called
143with three (in one particular case with four, see L<Last Resort>)
144arguments. If the corresponding operation is binary, then the first
145two arguments are the two arguments of the operation. However, due to
146general object calling conventions, the first argument should always be
147an object in the package, so in the situation of C<7+$a>, the
148order of the arguments is interchanged. It probably does not matter
149when implementing the addition method, but whether the arguments
150are reversed is vital to the subtraction method. The method can
151query this information by examining the third argument, which can take
152three different values:
153
154=over 7
155
156=item FALSE
157
158the order of arguments is as in the current operation.
159
160=item TRUE
161
162the arguments are reversed.
163
164=item C<undef>
165
166the current operation is an assignment variant (as in
167C<$a+=7>), but the usual function is called instead. This additional
168information can be used to generate some optimizations.
169
170=back
171
172=head2 Calling Conventions for Unary Operations
173
174Unary operation are considered binary operations with the second
175argument being C<undef>. Thus the functions that overloads C<{"++"}>
176is called with arguments C<($a,undef,'')> when $a++ is executed.
177
178=head2 Overloadable Operations
179
180The following symbols can be specified in C<use overload>:
181
182=over 5
183
184=item * I<Arithmetic operations>
185
186 "+", "+=", "-", "-=", "*", "*=", "/", "/=", "%", "%=",
187 "**", "**=", "<<", "<<=", ">>", ">>=", "x", "x=", ".", ".=",
188
189For these operations a substituted non-assignment variant can be called if
190the assignment variant is not available. Methods for operations "C<+>",
191"C<->", "C<+=>", and "C<-=>" can be called to automatically generate
192increment and decrement methods. The operation "C<->" can be used to
193autogenerate missing methods for unary minus or C<abs>.
194
195=item * I<Comparison operations>
196
197 "<", "<=", ">", ">=", "==", "!=", "<=>",
198 "lt", "le", "gt", "ge", "eq", "ne", "cmp",
199
200If the corresponding "spaceship" variant is available, it can be
201used to substitute for the missing operation. During C<sort>ing
202arrays, C<cmp> is used to compare values subject to C<use overload>.
203
204=item * I<Bit operations>
205
206 "&", "^", "|", "neg", "!", "~",
207
208"C<neg>" stands for unary minus. If the method for C<neg> is not
3bc6ec80
PP
209specified, it can be autogenerated using the method for
210subtraction. If the method for "C<!>" is not specified, it can be
211autogenerated using the methods for "C<bool>", or "C<\"\">", or "C<0+>".
4633a7c4
LW
212
213=item * I<Increment and decrement>
214
215 "++", "--",
216
217If undefined, addition and subtraction methods can be
218used instead. These operations are called both in prefix and
219postfix form.
220
221=item * I<Transcendental functions>
222
223 "atan2", "cos", "sin", "exp", "abs", "log", "sqrt",
224
225If C<abs> is unavailable, it can be autogenerated using methods
1fef88e7 226for "E<lt>" or "E<lt>=E<gt>" combined with either unary minus or subtraction.
4633a7c4
LW
227
228=item * I<Boolean, string and numeric conversion>
229
230 "bool", "\"\"", "0+",
231
232If one or two of these operations are unavailable, the remaining ones can
233be used instead. C<bool> is used in the flow control operators
234(like C<while>) and for the ternary "C<?:>" operation. These functions can
235return any arbitrary Perl value. If the corresponding operation for this value
236is overloaded too, that operation will be called again with this value.
237
238=item * I<Special>
239
240 "nomethod", "fallback", "=",
241
242see L<SPECIAL SYMBOLS FOR C<use overload>>.
243
244=back
245
246See L<"Fallback"> for an explanation of when a missing method can be autogenerated.
247
248=head1 SPECIAL SYMBOLS FOR C<use overload>
249
250Three keys are recognized by Perl that are not covered by the above
251description.
252
253=head2 Last Resort
254
255C<"nomethod"> should be followed by a reference to a function of four
256parameters. If defined, it is called when the overloading mechanism
257cannot find a method for some operation. The first three arguments of
258this function coincide with the arguments for the corresponding method if
259it were found, the fourth argument is the symbol
260corresponding to the missing method. If several methods are tried,
261the last one is used. Say, C<1-$a> can be equivalent to
262
263 &nomethodMethod($a,1,1,"-")
264
265if the pair C<"nomethod" =E<gt> "nomethodMethod"> was specified in the
266C<use overload> directive.
267
268If some operation cannot be resolved, and there is no function
269assigned to C<"nomethod">, then an exception will be raised via die()--
270unless C<"fallback"> was specified as a key in C<use overload> directive.
271
272=head2 Fallback
273
274The key C<"fallback"> governs what to do if a method for a particular
275operation is not found. Three different cases are possible depending on
276the value of C<"fallback">:
277
278=over 16
279
280=item * C<undef>
281
282Perl tries to use a
283substituted method (see L<MAGIC AUTOGENERATION>). If this fails, it
284then tries to calls C<"nomethod"> value; if missing, an exception
285will be raised.
286
287=item * TRUE
288
289The same as for the C<undef> value, but no exception is raised. Instead,
290it silently reverts to what it would have done were there no C<use overload>
291present.
292
293=item * defined, but FALSE
294
295No autogeneration is tried. Perl tries to call
296C<"nomethod"> value, and if this is missing, raises an exception.
297
298=back
299
300=head2 Copy Constructor
301
302The value for C<"="> is a reference to a function with three
303arguments, i.e., it looks like the other values in C<use
304overload>. However, it does not overload the Perl assignment
305operator. This would go against Camel hair.
306
307This operation is called in the situations when a mutator is applied
308to a reference that shares its object with some other reference, such
309as
310
311 $a=$b;
312 $a++;
313
314To make this change $a and not change $b, a copy of C<$$a> is made,
315and $a is assigned a reference to this new object. This operation is
316done during execution of the C<$a++>, and not during the assignment,
317(so before the increment C<$$a> coincides with C<$$b>). This is only
318done if C<++> is expressed via a method for C<'++'> or C<'+='>. Note
319that if this operation is expressed via C<'+'> a nonmutator, i.e., as
320in
321
322 $a=$b;
323 $a=$a+1;
324
325then C<$a> does not reference a new copy of C<$$a>, since $$a does not
326appear as lvalue when the above code is executed.
327
328If the copy constructor is required during the execution of some mutator,
329but a method for C<'='> was not specified, it can be autogenerated as a
330string copy if the object is a plain scalar.
331
332=over 5
333
334=item B<Example>
335
336The actually executed code for
337
338 $a=$b;
339 Something else which does not modify $a or $b....
340 ++$a;
341
342may be
343
344 $a=$b;
345 Something else which does not modify $a or $b....
346 $a = $a->clone(undef,"");
347 $a->incr(undef,"");
348
349if $b was mathemagical, and C<'++'> was overloaded with C<\&incr>,
350C<'='> was overloaded with C<\&clone>.
351
352=back
353
354=head1 MAGIC AUTOGENERATION
355
356If a method for an operation is not found, and the value for C<"fallback"> is
357TRUE or undefined, Perl tries to autogenerate a substitute method for
358the missing operation based on the defined operations. Autogenerated method
359substitutions are possible for the following operations:
360
361=over 16
362
363=item I<Assignment forms of arithmetic operations>
364
365C<$a+=$b> can use the method for C<"+"> if the method for C<"+=">
366is not defined.
367
368=item I<Conversion operations>
369
370String, numeric, and boolean conversion are calculated in terms of one
371another if not all of them are defined.
372
373=item I<Increment and decrement>
374
375The C<++$a> operation can be expressed in terms of C<$a+=1> or C<$a+1>,
376and C<$a--> in terms of C<$a-=1> and C<$a-1>.
377
378=item C<abs($a)>
379
380can be expressed in terms of C<$aE<lt>0> and C<-$a> (or C<0-$a>).
381
382=item I<Unary minus>
383
384can be expressed in terms of subtraction.
385
3bc6ec80
PP
386=item I<Negation>
387
388C<!> and C<not> can be expressed in terms of boolean conversion, or
389string or numerical conversion.
390
4633a7c4
LW
391=item I<Concatenation>
392
393can be expressed in terms of string conversion.
394
395=item I<Comparison operations>
396
397can be expressed in terms of its "spaceship" counterpart: either
398C<E<lt>=E<gt>> or C<cmp>:
1fef88e7 399
4633a7c4
LW
400 <, >, <=, >=, ==, != in terms of <=>
401 lt, gt, le, ge, eq, ne in terms of cmp
402
403=item I<Copy operator>
404
405can be expressed in terms of an assignment to the dereferenced value, if this
406value is a scalar and not a reference.
407
408=back
409
410=head1 WARNING
411
412The restriction for the comparison operation is that even if, for example,
413`C<cmp>' should return a blessed reference, the autogenerated `C<lt>'
414function will produce only a standard logical value based on the
415numerical value of the result of `C<cmp>'. In particular, a working
416numeric conversion is needed in this case (possibly expressed in terms of
417other conversions).
418
419Similarly, C<.=> and C<x=> operators lose their mathemagical properties
420if the string conversion substitution is applied.
421
422When you chop() a mathemagical object it is promoted to a string and its
423mathemagical properties are lost. The same can happen with other
424operations as well.
425
426=head1 Run-time Overloading
427
428Since all C<use> directives are executed at compile-time, the only way to
429change overloading during run-time is to
430
431 eval 'use overload "+" => \&addmethod';
432
433You can also use
434
435 eval 'no overload "+", "--", "<="';
436
437though the use of these constructs during run-time is questionable.
438
439=head1 Public functions
440
441Package C<overload.pm> provides the following public functions:
442
443=over 5
444
445=item overload::StrVal(arg)
446
447Gives string value of C<arg> as in absence of stringify overloading.
448
449=item overload::Overloaded(arg)
450
451Returns true if C<arg> is subject to overloading of some operations.
452
453=item overload::Method(obj,op)
454
455Returns C<undef> or a reference to the method that implements C<op>.
456
457=back
458
459=head1 IMPLEMENTATION
460
461What follows is subject to change RSN.
462
463The table of methods for all operations is cached as magic in the
464symbol table hash for the package. The table is rechecked for changes due to
465C<use overload>, C<no overload>, and @ISA only during
466C<bless>ing; so if they are changed dynamically, you'll need an
467additional fake C<bless>ing to update the table.
468
469(Every SVish thing has a magic queue, and magic is an entry in that queue.
470This is how a single variable may participate in multiple forms of magic
471simultaneously. For instance, environment variables regularly have two
472forms at once: their %ENV magic and their taint magic.)
473
474If an object belongs to a package using overload, it carries a special
475flag. Thus the only speed penalty during arithmetic operations without
476overloading is the checking of this flag.
477
478In fact, if C<use overload> is not present, there is almost no overhead for
479overloadable operations, so most programs should not suffer measurable
480performance penalties. A considerable effort was made to minimize the overhead
481when overload is used and the current operation is overloadable but
482the arguments in question do not belong to packages using overload. When
483in doubt, test your speed with C<use overload> and without it. So far there
484have been no reports of substantial speed degradation if Perl is compiled
485with optimization turned on.
486
487There is no size penalty for data if overload is not used.
488
489Copying (C<$a=$b>) is shallow; however, a one-level-deep copying is
490carried out before any operation that can imply an assignment to the
491object $a (or $b) refers to, like C<$a++>. You can override this
492behavior by defining your own copy constructor (see L<"Copy Constructor">).
493
494It is expected that arguments to methods that are not explicitly supposed
495to be changed are constant (but this is not enforced).
496
497=head1 AUTHOR
498
1fef88e7 499Ilya Zakharevich E<lt>F<ilya@math.mps.ohio-state.edu>E<gt>.
4633a7c4
LW
500
501=head1 DIAGNOSTICS
502
503When Perl is run with the B<-Do> switch or its equivalent, overloading
504induces diagnostic messages.
505
506=head1 BUGS
507
508Because it is used for overloading, the per-package associative array
a6006777
PP
509%OVERLOAD now has a special meaning in Perl. The symbol table is
510filled with names looking like line-noise.
4633a7c4 511
a6006777
PP
512For the purpose of inheritance every overloaded package behaves as if
513C<fallback> is present (possibly undefined). This may create
514interesting effects if some package is not overloaded, but inherits
515from two overloaded packages.
4633a7c4
LW
516
517This document is confusing.
518
519=cut
520