Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1209 lines
38 KiB

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