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