This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Add PL_ to merged file
[perl5.git] / lib / overload.pm
CommitLineData
4633a7c4
LW
1package overload;
2
a6006777 3sub nil {}
4
4633a7c4
LW
5sub OVERLOAD {
6 $package = shift;
7 my %arg = @_;
a6006777 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 12 if ($_ eq 'fallback') {
13 $fb = $arg{$_};
14 } else {
15 $sub = $arg{$_};
16 if (not ref $sub and $sub !~ /::/) {
44a8e56a 17 $ {$package . "::(" . $_} = $sub;
18 $sub = \&nil;
a6006777 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 39 if ($_ eq 'fallback') {
40 undef $ {$package . "::()"};
41 } else {
42 delete $ {$package . "::"}{"(" . $_};
43 }
4633a7c4
LW
44 }
45}
46
47sub Overloaded {
a6006777 48 my $package = shift;
49 $package = ref $package if ref $package;
50 $package->can('()');
4633a7c4
LW
51}
52
44a8e56a 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 62 my $package = shift;
63 $package = ref $package if ref $package;
44a8e56a 64 #$package->can('(""')
65 ov_method mycan($package, '(""'), $package;
4633a7c4
LW
66}
67
68sub Method {
a6006777 69 my $package = shift;
70 $package = ref $package if ref $package;
44a8e56a 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 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 87 (OverloadedStringify($_[0])) ?
88 (AddrRef(shift)) :
4633a7c4
LW
89 "$_[0]";
90}
91
44a8e56a 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
b3ac6de7
IZ
103%constants = (
104 'integer' => 0x1000,
105 'float' => 0x2000,
106 'binary' => 0x4000,
107 'q' => 0x8000,
108 'qr' => 0x10000,
109 );
110
111sub constant {
112 # Arguments: what, sub
113 while (@_) {
114 $^H{$_[0]} = $_[1];
115 $^H |= $constants{$_[0]} | 0x20000;
116 shift, shift;
117 }
118}
119
120sub remove_constant {
121 # Arguments: what, sub
122 while (@_) {
123 delete $^H{$_[0]};
124 $^H &= ~ $constants{$_[0]};
125 shift, shift;
126 }
127}
128
4633a7c4
LW
1291;
130
131__END__
132
133=head1 NAME
134
cb1a09d0 135overload - Package for overloading perl operations
4633a7c4
LW
136
137=head1 SYNOPSIS
138
139 package SomeThing;
140
141 use overload
142 '+' => \&myadd,
143 '-' => \&mysub;
144 # etc
145 ...
146
147 package main;
148 $a = new SomeThing 57;
149 $b=5+$a;
150 ...
151 if (overload::Overloaded $b) {...}
152 ...
153 $strval = overload::StrVal $b;
154
155=head1 CAVEAT SCRIPTOR
156
157Overloading of operators is a subject not to be taken lightly.
158Neither its precise implementation, syntax, nor semantics are
159100% endorsed by Larry Wall. So any of these may be changed
160at some point in the future.
161
162=head1 DESCRIPTION
163
164=head2 Declaration of overloaded functions
165
166The compilation directive
167
168 package Number;
169 use overload
170 "+" => \&add,
171 "*=" => "muas";
172
173declares function Number::add() for addition, and method muas() in
174the "class" C<Number> (or one of its base classes)
175for the assignment form C<*=> of multiplication.
176
177Arguments of this directive come in (key, value) pairs. Legal values
e7ea3e70
IZ
178are values legal inside a C<&{ ... }> call, so the name of a
179subroutine, a reference to a subroutine, or an anonymous subroutine
180will all work. Note that values specified as strings are
181interpreted as methods, not subroutines. Legal keys are listed below.
4633a7c4
LW
182
183The subroutine C<add> will be called to execute C<$a+$b> if $a
184is a reference to an object blessed into the package C<Number>, or if $a is
185not an object from a package with defined mathemagic addition, but $b is a
186reference to a C<Number>. It can also be called in other situations, like
187C<$a+=7>, or C<$a++>. See L<MAGIC AUTOGENERATION>. (Mathemagical
188methods refer to methods triggered by an overloaded mathematical
189operator.)
190
774d564b 191Since overloading respects inheritance via the @ISA hierarchy, the
192above declaration would also trigger overloading of C<+> and C<*=> in
193all the packages which inherit from C<Number>.
e7ea3e70 194
4633a7c4
LW
195=head2 Calling Conventions for Binary Operations
196
197The functions specified in the C<use overload ...> directive are called
198with three (in one particular case with four, see L<Last Resort>)
199arguments. If the corresponding operation is binary, then the first
200two arguments are the two arguments of the operation. However, due to
201general object calling conventions, the first argument should always be
202an object in the package, so in the situation of C<7+$a>, the
203order of the arguments is interchanged. It probably does not matter
204when implementing the addition method, but whether the arguments
205are reversed is vital to the subtraction method. The method can
206query this information by examining the third argument, which can take
207three different values:
208
209=over 7
210
211=item FALSE
212
213the order of arguments is as in the current operation.
214
215=item TRUE
216
217the arguments are reversed.
218
219=item C<undef>
220
221the current operation is an assignment variant (as in
222C<$a+=7>), but the usual function is called instead. This additional
223information can be used to generate some optimizations.
224
225=back
226
227=head2 Calling Conventions for Unary Operations
228
229Unary operation are considered binary operations with the second
230argument being C<undef>. Thus the functions that overloads C<{"++"}>
231is called with arguments C<($a,undef,'')> when $a++ is executed.
232
233=head2 Overloadable Operations
234
235The following symbols can be specified in C<use overload>:
236
237=over 5
238
239=item * I<Arithmetic operations>
240
241 "+", "+=", "-", "-=", "*", "*=", "/", "/=", "%", "%=",
242 "**", "**=", "<<", "<<=", ">>", ">>=", "x", "x=", ".", ".=",
243
244For these operations a substituted non-assignment variant can be called if
245the assignment variant is not available. Methods for operations "C<+>",
246"C<->", "C<+=>", and "C<-=>" can be called to automatically generate
247increment and decrement methods. The operation "C<->" can be used to
248autogenerate missing methods for unary minus or C<abs>.
249
250=item * I<Comparison operations>
251
252 "<", "<=", ">", ">=", "==", "!=", "<=>",
253 "lt", "le", "gt", "ge", "eq", "ne", "cmp",
254
255If the corresponding "spaceship" variant is available, it can be
256used to substitute for the missing operation. During C<sort>ing
257arrays, C<cmp> is used to compare values subject to C<use overload>.
258
259=item * I<Bit operations>
260
261 "&", "^", "|", "neg", "!", "~",
262
263"C<neg>" stands for unary minus. If the method for C<neg> is not
3bc6ec80 264specified, it can be autogenerated using the method for
265subtraction. If the method for "C<!>" is not specified, it can be
266autogenerated using the methods for "C<bool>", or "C<\"\">", or "C<0+>".
4633a7c4
LW
267
268=item * I<Increment and decrement>
269
270 "++", "--",
271
272If undefined, addition and subtraction methods can be
273used instead. These operations are called both in prefix and
274postfix form.
275
276=item * I<Transcendental functions>
277
278 "atan2", "cos", "sin", "exp", "abs", "log", "sqrt",
279
280If C<abs> is unavailable, it can be autogenerated using methods
1fef88e7 281for "E<lt>" or "E<lt>=E<gt>" combined with either unary minus or subtraction.
4633a7c4
LW
282
283=item * I<Boolean, string and numeric conversion>
284
285 "bool", "\"\"", "0+",
286
287If one or two of these operations are unavailable, the remaining ones can
288be used instead. C<bool> is used in the flow control operators
289(like C<while>) and for the ternary "C<?:>" operation. These functions can
290return any arbitrary Perl value. If the corresponding operation for this value
291is overloaded too, that operation will be called again with this value.
292
293=item * I<Special>
294
295 "nomethod", "fallback", "=",
296
297see L<SPECIAL SYMBOLS FOR C<use overload>>.
298
299=back
300
301See L<"Fallback"> for an explanation of when a missing method can be autogenerated.
302
e7ea3e70
IZ
303=head2 Inheritance and overloading
304
774d564b 305Inheritance interacts with overloading in two ways.
e7ea3e70
IZ
306
307=over
308
309=item Strings as values of C<use overload> directive
310
774d564b 311If C<value> in
e7ea3e70
IZ
312
313 use overload key => value;
314
774d564b 315is a string, it is interpreted as a method name.
e7ea3e70
IZ
316
317=item Overloading of an operation is inherited by derived classes
318
774d564b 319Any class derived from an overloaded class is also overloaded. The
320set of overloaded methods is the union of overloaded methods of all
321the ancestors. If some method is overloaded in several ancestor, then
e7ea3e70 322which description will be used is decided by the usual inheritance
774d564b 323rules:
e7ea3e70 324
774d564b 325If C<A> inherits from C<B> and C<C> (in this order), C<B> overloads
326C<+> with C<\&D::plus_sub>, and C<C> overloads C<+> by C<"plus_meth">,
327then the subroutine C<D::plus_sub> will be called to implement
328operation C<+> for an object in package C<A>.
e7ea3e70
IZ
329
330=back
331
774d564b 332Note that since the value of the C<fallback> key is not a subroutine,
333its inheritance is not governed by the above rules. In the current
334implementation, the value of C<fallback> in the first overloaded
335ancestor is used, but this is accidental and subject to change.
e7ea3e70 336
4633a7c4
LW
337=head1 SPECIAL SYMBOLS FOR C<use overload>
338
339Three keys are recognized by Perl that are not covered by the above
340description.
341
774d564b 342=head2 Last Resort
4633a7c4
LW
343
344C<"nomethod"> should be followed by a reference to a function of four
345parameters. If defined, it is called when the overloading mechanism
346cannot find a method for some operation. The first three arguments of
347this function coincide with the arguments for the corresponding method if
348it were found, the fourth argument is the symbol
349corresponding to the missing method. If several methods are tried,
350the last one is used. Say, C<1-$a> can be equivalent to
351
352 &nomethodMethod($a,1,1,"-")
353
354if the pair C<"nomethod" =E<gt> "nomethodMethod"> was specified in the
355C<use overload> directive.
356
357If some operation cannot be resolved, and there is no function
358assigned to C<"nomethod">, then an exception will be raised via die()--
359unless C<"fallback"> was specified as a key in C<use overload> directive.
360
361=head2 Fallback
362
363The key C<"fallback"> governs what to do if a method for a particular
364operation is not found. Three different cases are possible depending on
365the value of C<"fallback">:
366
367=over 16
368
369=item * C<undef>
370
371Perl tries to use a
372substituted method (see L<MAGIC AUTOGENERATION>). If this fails, it
373then tries to calls C<"nomethod"> value; if missing, an exception
374will be raised.
375
376=item * TRUE
377
378The same as for the C<undef> value, but no exception is raised. Instead,
379it silently reverts to what it would have done were there no C<use overload>
380present.
381
382=item * defined, but FALSE
383
384No autogeneration is tried. Perl tries to call
385C<"nomethod"> value, and if this is missing, raises an exception.
386
387=back
388
e7ea3e70
IZ
389B<Note.> C<"fallback"> inheritance via @ISA is not carved in stone
390yet, see L<"Inheritance and overloading">.
391
4633a7c4
LW
392=head2 Copy Constructor
393
394The value for C<"="> is a reference to a function with three
395arguments, i.e., it looks like the other values in C<use
396overload>. However, it does not overload the Perl assignment
397operator. This would go against Camel hair.
398
399This operation is called in the situations when a mutator is applied
400to a reference that shares its object with some other reference, such
401as
402
403 $a=$b;
404 $a++;
405
406To make this change $a and not change $b, a copy of C<$$a> is made,
407and $a is assigned a reference to this new object. This operation is
408done during execution of the C<$a++>, and not during the assignment,
409(so before the increment C<$$a> coincides with C<$$b>). This is only
410done if C<++> is expressed via a method for C<'++'> or C<'+='>. Note
411that if this operation is expressed via C<'+'> a nonmutator, i.e., as
412in
413
414 $a=$b;
415 $a=$a+1;
416
417then C<$a> does not reference a new copy of C<$$a>, since $$a does not
418appear as lvalue when the above code is executed.
419
420If the copy constructor is required during the execution of some mutator,
421but a method for C<'='> was not specified, it can be autogenerated as a
422string copy if the object is a plain scalar.
423
424=over 5
425
426=item B<Example>
427
428The actually executed code for
429
430 $a=$b;
431 Something else which does not modify $a or $b....
432 ++$a;
433
434may be
435
436 $a=$b;
437 Something else which does not modify $a or $b....
438 $a = $a->clone(undef,"");
439 $a->incr(undef,"");
440
441if $b was mathemagical, and C<'++'> was overloaded with C<\&incr>,
442C<'='> was overloaded with C<\&clone>.
443
444=back
445
446=head1 MAGIC AUTOGENERATION
447
448If a method for an operation is not found, and the value for C<"fallback"> is
449TRUE or undefined, Perl tries to autogenerate a substitute method for
450the missing operation based on the defined operations. Autogenerated method
451substitutions are possible for the following operations:
452
453=over 16
454
455=item I<Assignment forms of arithmetic operations>
456
457C<$a+=$b> can use the method for C<"+"> if the method for C<"+=">
458is not defined.
459
460=item I<Conversion operations>
461
462String, numeric, and boolean conversion are calculated in terms of one
463another if not all of them are defined.
464
465=item I<Increment and decrement>
466
467The C<++$a> operation can be expressed in terms of C<$a+=1> or C<$a+1>,
468and C<$a--> in terms of C<$a-=1> and C<$a-1>.
469
470=item C<abs($a)>
471
472can be expressed in terms of C<$aE<lt>0> and C<-$a> (or C<0-$a>).
473
474=item I<Unary minus>
475
476can be expressed in terms of subtraction.
477
3bc6ec80 478=item I<Negation>
479
480C<!> and C<not> can be expressed in terms of boolean conversion, or
481string or numerical conversion.
482
4633a7c4
LW
483=item I<Concatenation>
484
485can be expressed in terms of string conversion.
486
487=item I<Comparison operations>
488
489can be expressed in terms of its "spaceship" counterpart: either
490C<E<lt>=E<gt>> or C<cmp>:
1fef88e7 491
4633a7c4
LW
492 <, >, <=, >=, ==, != in terms of <=>
493 lt, gt, le, ge, eq, ne in terms of cmp
494
495=item I<Copy operator>
496
497can be expressed in terms of an assignment to the dereferenced value, if this
498value is a scalar and not a reference.
499
500=back
501
502=head1 WARNING
503
504The restriction for the comparison operation is that even if, for example,
505`C<cmp>' should return a blessed reference, the autogenerated `C<lt>'
506function will produce only a standard logical value based on the
507numerical value of the result of `C<cmp>'. In particular, a working
508numeric conversion is needed in this case (possibly expressed in terms of
509other conversions).
510
511Similarly, C<.=> and C<x=> operators lose their mathemagical properties
512if the string conversion substitution is applied.
513
514When you chop() a mathemagical object it is promoted to a string and its
515mathemagical properties are lost. The same can happen with other
516operations as well.
517
518=head1 Run-time Overloading
519
520Since all C<use> directives are executed at compile-time, the only way to
521change overloading during run-time is to
522
523 eval 'use overload "+" => \&addmethod';
524
525You can also use
526
527 eval 'no overload "+", "--", "<="';
528
529though the use of these constructs during run-time is questionable.
530
531=head1 Public functions
532
533Package C<overload.pm> provides the following public functions:
534
535=over 5
536
537=item overload::StrVal(arg)
538
539Gives string value of C<arg> as in absence of stringify overloading.
540
541=item overload::Overloaded(arg)
542
543Returns true if C<arg> is subject to overloading of some operations.
544
545=item overload::Method(obj,op)
546
547Returns C<undef> or a reference to the method that implements C<op>.
548
549=back
550
b3ac6de7
IZ
551=head1 Overloading constants
552
553For some application Perl parser mangles constants too much. It is possible
554to hook into this process via overload::constant() and overload::remove_constant()
555functions.
556
557These functions take a hash as an argument. The recognized keys of this hash
558are
559
560=over 8
561
562=item integer
563
564to overload integer constants,
565
566=item float
567
568to overload floating point constants,
569
570=item binary
571
572to overload octal and hexadecimal constants,
573
574=item q
575
576to overload C<q>-quoted strings, constant pieces of C<qq>- and C<qx>-quoted
577strings and here-documents,
578
579=item qr
580
581to overload constant pieces of regular expressions.
582
583=back
584
585The corresponding values are references to functions which take three arguments:
586the first one is the I<initial> string form of the constant, the second one
587is how Perl interprets this constant, the third one is how the constant is used.
588Note that the initial string form does not
589contain string delimiters, and has backslashes in backslash-delimiter
590combinations stripped (thus the value of delimiter is not relevant for
591processing of this string). The return value of this function is how this
592constant is going to be interpreted by Perl. The third argument is undefined
593unless for overloaded C<q>- and C<qr>- constants, it is C<q> in single-quote
594context (comes from strings, regular expressions, and single-quote HERE
595documents), it is C<tr> for arguments of C<tr>/C<y> operators,
596it is C<s> for right-hand side of C<s>-operator, and it is C<qq> otherwise.
597
598Since an expression C<"ab$cd,,"> is just a shortcut for C<'ab' . $cd . ',,'>,
599it is expected that overloaded constant strings are equipped with reasonable
600overloaded catenation operator, otherwise absurd results will result.
601Similarly, negative numbers are considered as negations of positive constants.
602
603Note that it is probably meaningless to call the functions overload::constant()
604and overload::remove_constant() from anywhere but import() and unimport() methods.
605From these methods they may be called as
606
607 sub import {
608 shift;
609 return unless @_;
610 die "unknown import: @_" unless @_ == 1 and $_[0] eq ':constant';
611 overload::constant integer => sub {Math::BigInt->new(shift)};
612 }
613
614B<BUGS> Currently overloaded-ness of constants does not propagate
615into C<eval '...'>.
616
4633a7c4
LW
617=head1 IMPLEMENTATION
618
619What follows is subject to change RSN.
620
e7ea3e70
IZ
621The table of methods for all operations is cached in magic for the
622symbol table hash for the package. The cache is invalidated during
623processing of C<use overload>, C<no overload>, new function
624definitions, and changes in @ISA. However, this invalidation remains
625unprocessed until the next C<bless>ing into the package. Hence if you
626want to change overloading structure dynamically, you'll need an
627additional (fake) C<bless>ing to update the table.
628
629(Every SVish thing has a magic queue, and magic is an entry in that
630queue. This is how a single variable may participate in multiple
631forms of magic simultaneously. For instance, environment variables
632regularly have two forms at once: their %ENV magic and their taint
633magic. However, the magic which implements overloading is applied to
634the stashes, which are rarely used directly, thus should not slow down
635Perl.)
4633a7c4
LW
636
637If an object belongs to a package using overload, it carries a special
638flag. Thus the only speed penalty during arithmetic operations without
639overloading is the checking of this flag.
640
774d564b 641In fact, if C<use overload> is not present, there is almost no overhead
642for overloadable operations, so most programs should not suffer
643measurable performance penalties. A considerable effort was made to
644minimize the overhead when overload is used in some package, but the
645arguments in question do not belong to packages using overload. When
646in doubt, test your speed with C<use overload> and without it. So far
647there have been no reports of substantial speed degradation if Perl is
648compiled with optimization turned on.
4633a7c4 649
e7ea3e70
IZ
650There is no size penalty for data if overload is not used. The only
651size penalty if overload is used in some package is that I<all> the
652packages acquire a magic during the next C<bless>ing into the
653package. This magic is three-words-long for packages without
654overloading, and carries the cache tabel if the package is overloaded.
4633a7c4
LW
655
656Copying (C<$a=$b>) is shallow; however, a one-level-deep copying is
657carried out before any operation that can imply an assignment to the
658object $a (or $b) refers to, like C<$a++>. You can override this
659behavior by defining your own copy constructor (see L<"Copy Constructor">).
660
661It is expected that arguments to methods that are not explicitly supposed
662to be changed are constant (but this is not enforced).
663
664=head1 AUTHOR
665
1fef88e7 666Ilya Zakharevich E<lt>F<ilya@math.mps.ohio-state.edu>E<gt>.
4633a7c4
LW
667
668=head1 DIAGNOSTICS
669
670When Perl is run with the B<-Do> switch or its equivalent, overloading
671induces diagnostic messages.
672
e7ea3e70
IZ
673Using the C<m> command of Perl debugger (see L<perldebug>) one can
674deduce which operations are overloaded (and which ancestor triggers
675this overloading). Say, if C<eq> is overloaded, then the method C<(eq>
676is shown by debugger. The method C<()> corresponds to the C<fallback>
677key (in fact a presence of this method shows that this package has
678overloading enabled, and it is what is used by the C<Overloaded>
679function).
680
4633a7c4
LW
681=head1 BUGS
682
aa689395 683Because it is used for overloading, the per-package hash %OVERLOAD now
684has a special meaning in Perl. The symbol table is filled with names
685looking like line-noise.
4633a7c4 686
a6006777 687For the purpose of inheritance every overloaded package behaves as if
688C<fallback> is present (possibly undefined). This may create
689interesting effects if some package is not overloaded, but inherits
690from two overloaded packages.
4633a7c4 691
b3ac6de7
IZ
692Barewords are not covered by overloaded string constants.
693
4633a7c4
LW
694This document is confusing.
695
696=cut
697