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