Doc tweaks.
[p5sagit/p5-mst-13.2.git] / lib / Attribute / Handlers.pm
CommitLineData
dc6b6eef 1package Attribute::Handlers;
2use 5.006;
3use Carp;
4use warnings;
55a1c97c 5$VERSION = '0.75';
6# $DB::single=1;
dc6b6eef 7
9df0c874 8my %symcache;
dc6b6eef 9sub findsym {
10 my ($pkg, $ref, $type) = @_;
9df0c874 11 return $symcache{$pkg,$ref} if $symcache{$pkg,$ref};
dc6b6eef 12 $type ||= ref($ref);
9df0c874 13 my $found;
dc6b6eef 14 foreach my $sym ( values %{$pkg."::"} ) {
9df0c874 15 return $symcache{$pkg,$ref} = \$sym
16 if *{$sym}{$type} && *{$sym}{$type} == $ref;
dc6b6eef 17 }
18}
19
20my %validtype = (
21 VAR => [qw[SCALAR ARRAY HASH]],
22 ANY => [qw[SCALAR ARRAY HASH CODE]],
23 "" => [qw[SCALAR ARRAY HASH CODE]],
24 SCALAR => [qw[SCALAR]],
25 ARRAY => [qw[ARRAY]],
26 HASH => [qw[HASH]],
27 CODE => [qw[CODE]],
28);
29my %lastattr;
30my @declarations;
31my %raw;
9df0c874 32my %phase;
dc6b6eef 33my %sigil = (SCALAR=>'$', ARRAY=>'@', HASH=>'%');
34
9df0c874 35sub _usage_AH_ {
36 croak "Usage: use $_[0] autotie => {AttrName => TieClassName,...}";
37}
dc6b6eef 38
55a1c97c 39my $qual_id = qr/^[_a-z]\w*(::[_a-z]\w*)*$/i;
40
dc6b6eef 41sub import {
42 my $class = shift @_;
9df0c874 43 return unless $class eq "Attribute::Handlers";
dc6b6eef 44 while (@_) {
45 my $cmd = shift;
55a1c97c 46 if ($cmd =~ /^autotie((?:ref)?)$/) {
47 my $tiedata = '($was_arrayref ? $data : @$data)';
48 $tiedata = ($1 ? '$ref, ' : '') . $tiedata;
dc6b6eef 49 my $mapping = shift;
9df0c874 50 _usage_AH_ $class unless ref($mapping) eq 'HASH';
dc6b6eef 51 while (my($attr, $tieclass) = each %$mapping) {
55a1c97c 52 $tieclass =~ s/^([_a-z]\w*(::[_a-z]\w*)*)(.*)/$1/is;
9df0c874 53 my $args = $3||'()';
55a1c97c 54 _usage_AH_ $class unless $attr =~ $qual_id
55 && $tieclass =~ $qual_id
dc6b6eef 56 && eval "use base $tieclass; 1";
9df0c874 57 if ($tieclass->isa('Exporter')) {
58 local $Exporter::ExportLevel = 2;
59 $tieclass->import(eval $args);
60 }
61 $attr =~ s/__CALLER__/caller(1)/e;
62 $attr = caller()."::".$attr unless $attr =~ /::/;
dc6b6eef 63 eval qq{
64 sub $attr : ATTR(VAR) {
65 my (\$ref, \$data) = \@_[2,4];
55a1c97c 66 my \$was_arrayref = ref \$data eq 'ARRAY';
67 \$data = [ \$data ] unless \$was_arrayref;
9df0c874 68 my \$type = ref(\$ref)||"value (".(\$ref||"<undef>").")";
55a1c97c 69 (\$type eq 'SCALAR')? tie \$\$ref,'$tieclass',$tiedata
70 :(\$type eq 'ARRAY') ? tie \@\$ref,'$tieclass',$tiedata
71 :(\$type eq 'HASH') ? tie \%\$ref,'$tieclass',$tiedata
9df0c874 72 : die "Can't autotie a \$type\n"
dc6b6eef 73 } 1
74 } or die "Internal error: $@";
75 }
76 }
77 else {
78 croak "Can't understand $_";
79 }
80 }
81}
9df0c874 82sub _resolve_lastattr {
dc6b6eef 83 return unless $lastattr{ref};
84 my $sym = findsym @lastattr{'pkg','ref'}
85 or die "Internal error: $lastattr{pkg} symbol went missing";
86 my $name = *{$sym}{NAME};
87 warn "Declaration of $name attribute in package $lastattr{pkg} may clash with future reserved word\n"
88 if $^W and $name !~ /[A-Z]/;
89 foreach ( @{$validtype{$lastattr{type}}} ) {
90 *{"$lastattr{pkg}::_ATTR_${_}_${name}"} = $lastattr{ref};
91 }
92 %lastattr = ();
93}
94
95sub AUTOLOAD {
55a1c97c 96 my ($class) = $AUTOLOAD =~ m/(.*)::/g;
97 $AUTOLOAD =~ m/_ATTR_(.*?)_(.*)/ or
dc6b6eef 98 croak "Can't locate class method '$AUTOLOAD' via package '$class'";
55a1c97c 99 croak "Attribute handler '$3' doesn't handle $2 attributes";
dc6b6eef 100}
101
102sub DESTROY {}
103
104my $builtin = qr/lvalue|method|locked/;
105
9df0c874 106sub _gen_handler_AH_() {
dc6b6eef 107 return sub {
9df0c874 108 _resolve_lastattr;
dc6b6eef 109 my ($pkg, $ref, @attrs) = @_;
110 foreach (@attrs) {
55a1c97c 111 my ($attr, $data) = /^([a-z_]\w*)(?:[(](.*)[)])?$/is or next;
dc6b6eef 112 if ($attr eq 'ATTR') {
113 $data ||= "ANY";
114 $raw{$ref} = $data =~ s/\s*,?\s*RAWDATA\s*,?\s*//;
9df0c874 115 $phase{$ref}{BEGIN} = 1
116 if $data =~ s/\s*,?\s*(BEGIN)\s*,?\s*//;
117 $phase{$ref}{INIT} = 1
118 if $data =~ s/\s*,?\s*(INIT)\s*,?\s*//;
119 $phase{$ref}{END} = 1
120 if $data =~ s/\s*,?\s*(END)\s*,?\s*//;
121 $phase{$ref}{CHECK} = 1
122 if $data =~ s/\s*,?\s*(CHECK)\s*,?\s*//
123 || ! keys %{$phase{$ref}};
124 croak "Can't have two ATTR specifiers on one subroutine"
125 if keys %lastattr;
dc6b6eef 126 croak "Bad attribute type: ATTR($data)"
127 unless $validtype{$data};
128 %lastattr=(pkg=>$pkg,ref=>$ref,type=>$data);
129 }
130 else {
131 my $handler = $pkg->can($attr);
132 next unless $handler;
9df0c874 133 my $decl = [$pkg, $ref, $attr, $data,
134 $raw{$handler}, $phase{$handler}];
135 _apply_handler_AH_($decl,'BEGIN');
136 push @declarations, $decl;
dc6b6eef 137 }
138 $_ = undef;
139 }
140 return grep {defined && !/$builtin/} @attrs;
141 }
142}
143
9df0c874 144*{"MODIFY_${_}_ATTRIBUTES"} = _gen_handler_AH_ foreach @{$validtype{ANY}};
dc6b6eef 145push @UNIVERSAL::ISA, 'Attribute::Handlers'
146 unless grep /^Attribute::Handlers$/, @UNIVERSAL::ISA;
147
9df0c874 148sub _apply_handler_AH_ {
149 my ($declaration, $phase) = @_;
150 my ($pkg, $ref, $attr, $data, $raw, $handlerphase) = @$declaration;
151 return unless $handlerphase->{$phase};
152 # print STDERR "Handling $attr on $ref in $phase with [$data]\n";
153 my $type = ref $ref;
154 my $handler = "_ATTR_${type}_${attr}";
155 my $sym = findsym($pkg, $ref);
156 $sym ||= $type eq 'CODE' ? 'ANON' : 'LEXICAL';
157 no warnings;
158 my $evaled = !$raw && eval("package $pkg; no warnings;
159 local \$SIG{__WARN__}=sub{die}; [$data]");
160 $data = ($evaled && $data =~ /^\s*\[/) ? [$evaled]
161 : ($evaled) ? $evaled
162 : [$data];
163 $pkg->$handler($sym,
164 (ref $sym eq 'GLOB' ? *{$sym}{ref $ref}||$ref : $ref),
165 $attr,
166 (@$data>1? $data : $data->[0]),
167 $phase,
168 );
169 return 1;
170}
171
dc6b6eef 172CHECK {
9df0c874 173 _resolve_lastattr;
174 _apply_handler_AH_($_,'CHECK') foreach @declarations;
dc6b6eef 175}
176
9df0c874 177INIT { _apply_handler_AH_($_,'INIT') foreach @declarations }
178
179END { _apply_handler_AH_($_,'END') foreach @declarations }
180
dc6b6eef 1811;
182__END__
183
184=head1 NAME
185
186Attribute::Handlers - Simpler definition of attribute handlers
187
188=head1 VERSION
189
55a1c97c 190This document describes version 0.75 of Attribute::Handlers,
191released September 3, 2001.
dc6b6eef 192
193=head1 SYNOPSIS
194
195 package MyClass;
196 require v5.6.0;
197 use Attribute::Handlers;
198 no warnings 'redefine';
199
200
201 sub Good : ATTR(SCALAR) {
202 my ($package, $symbol, $referent, $attr, $data) = @_;
203
204 # Invoked for any scalar variable with a :Good attribute,
205 # provided the variable was declared in MyClass (or
206 # a derived class) or typed to MyClass.
207
208 # Do whatever to $referent here (executed in CHECK phase).
209 ...
210 }
211
212 sub Bad : ATTR(SCALAR) {
213 # Invoked for any scalar variable with a :Bad attribute,
214 # provided the variable was declared in MyClass (or
215 # a derived class) or typed to MyClass.
216 ...
217 }
218
219 sub Good : ATTR(ARRAY) {
220 # Invoked for any array variable with a :Good attribute,
221 # provided the variable was declared in MyClass (or
222 # a derived class) or typed to MyClass.
223 ...
224 }
225
226 sub Good : ATTR(HASH) {
227 # Invoked for any hash variable with a :Good attribute,
228 # provided the variable was declared in MyClass (or
229 # a derived class) or typed to MyClass.
230 ...
231 }
232
233 sub Ugly : ATTR(CODE) {
234 # Invoked for any subroutine declared in MyClass (or a
235 # derived class) with an :Ugly attribute.
236 ...
237 }
238
239 sub Omni : ATTR {
240 # Invoked for any scalar, array, hash, or subroutine
241 # with an :Omni attribute, provided the variable or
242 # subroutine was declared in MyClass (or a derived class)
243 # or the variable was typed to MyClass.
244 # Use ref($_[2]) to determine what kind of referent it was.
245 ...
246 }
247
248
249 use Attribute::Handlers autotie => { Cycle => Tie::Cycle };
250
251 my $next : Cycle(['A'..'Z']);
252
253
254=head1 DESCRIPTION
255
256This module, when inherited by a package, allows that package's class to
257define attribute handler subroutines for specific attributes. Variables
258and subroutines subsequently defined in that package, or in packages
259derived from that package may be given attributes with the same names as
9df0c874 260the attribute handler subroutines, which will then be called in one of
261the compilation phases (i.e. in a C<BEGIN>, C<CHECK>, C<INIT>, or C<END>
262block).
dc6b6eef 263
264To create a handler, define it as a subroutine with the same name as
265the desired attribute, and declare the subroutine itself with the
266attribute C<:ATTR>. For example:
267
268 package LoudDecl;
269 use Attribute::Handlers;
270
271 sub Loud :ATTR {
9df0c874 272 my ($package, $symbol, $referent, $attr, $data, $phase) = @_;
dc6b6eef 273 print STDERR
274 ref($referent), " ",
275 *{$symbol}{NAME}, " ",
276 "($referent) ", "was just declared ",
277 "and ascribed the ${attr} attribute ",
9df0c874 278 "with data ($data)\n",
279 "in phase $phase\n";
dc6b6eef 280 }
281
282This creates an handler for the attribute C<:Loud> in the class LoudDecl.
283Thereafter, any subroutine declared with a C<:Loud> attribute in the class
284LoudDecl:
285
286 package LoudDecl;
287
288 sub foo: Loud {...}
289
290causes the above handler to be invoked, and passed:
291
292=over
293
294=item [0]
295
296the name of the package into which it was declared;
297
298=item [1]
299
300a reference to the symbol table entry (typeglob) containing the subroutine;
301
302=item [2]
303
304a reference to the subroutine;
305
306=item [3]
307
308the name of the attribute;
309
310=item [4]
311
9df0c874 312any data associated with that attribute;
313
314=item [5]
315
316the name of the phase in which the handler is being invoked.
dc6b6eef 317
318=back
319
320Likewise, declaring any variables with the C<:Loud> attribute within the
321package:
322
9df0c874 323 package LoudDecl;
dc6b6eef 324
9df0c874 325 my $foo :Loud;
326 my @foo :Loud;
327 my %foo :Loud;
dc6b6eef 328
329will cause the handler to be called with a similar argument list (except,
330of course, that C<$_[2]> will be a reference to the variable).
331
332The package name argument will typically be the name of the class into
333which the subroutine was declared, but it may also be the name of a derived
334class (since handlers are inherited).
335
336If a lexical variable is given an attribute, there is no symbol table to
337which it belongs, so the symbol table argument (C<$_[1]>) is set to the
338string C<'LEXICAL'> in that case. Likewise, ascribing an attribute to
339an anonymous subroutine results in a symbol table argument of C<'ANON'>.
340
341The data argument passes in the value (if any) associated with the
342attribute. For example, if C<&foo> had been declared:
343
9df0c874 344 sub foo :Loud("turn it up to 11, man!") {...}
dc6b6eef 345
346then the string C<"turn it up to 11, man!"> would be passed as the
347last argument.
348
349Attribute::Handlers makes strenuous efforts to convert
350the data argument (C<$_[4]>) to a useable form before passing it to
351the handler (but see L<"Non-interpretive attribute handlers">).
352For example, all of these:
353
9df0c874 354 sub foo :Loud(till=>ears=>are=>bleeding) {...}
355 sub foo :Loud(['till','ears','are','bleeding']) {...}
356 sub foo :Loud(qw/till ears are bleeding/) {...}
357 sub foo :Loud(qw/my, ears, are, bleeding/) {...}
358 sub foo :Loud(till,ears,are,bleeding) {...}
dc6b6eef 359
360causes it to pass C<['till','ears','are','bleeding']> as the handler's
361data argument. However, if the data can't be parsed as valid Perl, then
362it is passed as an uninterpreted string. For example:
363
9df0c874 364 sub foo :Loud(my,ears,are,bleeding) {...}
365 sub foo :Loud(qw/my ears are bleeding) {...}
dc6b6eef 366
367cause the strings C<'my,ears,are,bleeding'> and C<'qw/my ears are bleeding'>
368respectively to be passed as the data argument.
369
370If the attribute has only a single associated scalar data value, that value is
371passed as a scalar. If multiple values are associated, they are passed as an
372array reference. If no value is associated with the attribute, C<undef> is
373passed.
374
375
376=head2 Typed lexicals
377
378Regardless of the package in which it is declared, if a lexical variable is
379ascribed an attribute, the handler that is invoked is the one belonging to
380the package to which it is typed. For example, the following declarations:
381
9df0c874 382 package OtherClass;
dc6b6eef 383
9df0c874 384 my LoudDecl $loudobj : Loud;
385 my LoudDecl @loudobjs : Loud;
386 my LoudDecl %loudobjex : Loud;
dc6b6eef 387
388causes the LoudDecl::Loud handler to be invoked (even if OtherClass also
389defines a handler for C<:Loud> attributes).
390
391
392=head2 Type-specific attribute handlers
393
394If an attribute handler is declared and the C<:ATTR> specifier is
395given the name of a built-in type (C<SCALAR>, C<ARRAY>, C<HASH>, or C<CODE>),
396the handler is only applied to declarations of that type. For example,
397the following definition:
398
9df0c874 399 package LoudDecl;
dc6b6eef 400
9df0c874 401 sub RealLoud :ATTR(SCALAR) { print "Yeeeeow!" }
dc6b6eef 402
403creates an attribute handler that applies only to scalars:
404
405
9df0c874 406 package Painful;
407 use base LoudDecl;
dc6b6eef 408
9df0c874 409 my $metal : RealLoud; # invokes &LoudDecl::RealLoud
410 my @metal : RealLoud; # error: unknown attribute
411 my %metal : RealLoud; # error: unknown attribute
412 sub metal : RealLoud {...} # error: unknown attribute
dc6b6eef 413
414You can, of course, declare separate handlers for these types as well
415(but you'll need to specify C<no warnings 'redefine'> to do it quietly):
416
9df0c874 417 package LoudDecl;
418 use Attribute::Handlers;
419 no warnings 'redefine';
dc6b6eef 420
9df0c874 421 sub RealLoud :ATTR(SCALAR) { print "Yeeeeow!" }
422 sub RealLoud :ATTR(ARRAY) { print "Urrrrrrrrrr!" }
423 sub RealLoud :ATTR(HASH) { print "Arrrrrgggghhhhhh!" }
424 sub RealLoud :ATTR(CODE) { croak "Real loud sub torpedoed" }
dc6b6eef 425
426You can also explicitly indicate that a single handler is meant to be
427used for all types of referents like so:
428
9df0c874 429 package LoudDecl;
430 use Attribute::Handlers;
dc6b6eef 431
9df0c874 432 sub SeriousLoud :ATTR(ANY) { warn "Hearing loss imminent" }
dc6b6eef 433
434(I.e. C<ATTR(ANY)> is a synonym for C<:ATTR>).
435
436
437=head2 Non-interpretive attribute handlers
438
439Occasionally the strenuous efforts Attribute::Handlers makes to convert
440the data argument (C<$_[4]>) to a useable form before passing it to
441the handler get in the way.
442
443You can turn off that eagerness-to-help by declaring
444an attribute handler with the the keyword C<RAWDATA>. For example:
445
9df0c874 446 sub Raw : ATTR(RAWDATA) {...}
447 sub Nekkid : ATTR(SCALAR,RAWDATA) {...}
448 sub Au::Naturale : ATTR(RAWDATA,ANY) {...}
dc6b6eef 449
450Then the handler makes absolutely no attempt to interpret the data it
451receives and simply passes it as a string:
452
9df0c874 453 my $power : Raw(1..100); # handlers receives "1..100"
454
455=head2 Phase-specific attribute handlers
456
457By default, attribute handlers are called at the end of the compilation
458phase (in a C<CHECK> block). This seems to be optimal in most cases because
459most things that can be defined are defined by that point but nothing has
460been executed.
461
462However, it is possible to set up attribute handlers that are called at
463other points in the program's compilation or execution, by explicitly
464stating the phase (or phases) in which you wish the attribute handler to
465be called. For example:
466
467 sub Early :ATTR(SCALAR,BEGIN) {...}
468 sub Normal :ATTR(SCALAR,CHECK) {...}
469 sub Late :ATTR(SCALAR,INIT) {...}
470 sub Final :ATTR(SCALAR,END) {...}
471 sub Bookends :ATTR(SCALAR,BEGIN,END) {...}
472
473As the last example indicates, a handler may be set up to be (re)called in
474two or more phases. The phase name is passed as the handler's final argument.
475
476Note that attribute handlers that are scheduled for the C<BEGIN> phase
477are handled as soon as the attribute is detected (i.e. before any
478subsequently defined C<BEGIN> blocks are executed).
dc6b6eef 479
480
481=head2 Attributes as C<tie> interfaces
482
483Attributes make an excellent and intuitive interface through which to tie
484variables. For example:
485
486 use Attribute::Handlers;
487 use Tie::Cycle;
488
489 sub UNIVERSAL::Cycle : ATTR(SCALAR) {
9df0c874 490 my ($package, $symbol, $referent, $attr, $data, $phase) = @_;
dc6b6eef 491 $data = [ $data ] unless ref $data eq 'ARRAY';
492 tie $$referent, 'Tie::Cycle', $data;
493 }
494
495 # and thereafter...
496
497 package main;
498
9df0c874 499 my $next : Cycle('A'..'Z'); # $next is now a tied variable
dc6b6eef 500
501 while (<>) {
502 print $next;
503 }
504
505In fact, this pattern is so widely applicable that Attribute::Handlers
506provides a way to automate it: specifying C<'autotie'> in the
507C<use Attribute::Handlers> statement. So, the previous example,
508could also be written:
509
510 use Attribute::Handlers autotie => { Cycle => 'Tie::Cycle' };
511
512 # and thereafter...
513
514 package main;
515
9df0c874 516 my $next : Cycle('A'..'Z'); # $next is now a tied variable
dc6b6eef 517
518 while (<>) {
519 print $next;
520
521The argument after C<'autotie'> is a reference to a hash in which each key is
522the name of an attribute to be created, and each value is the class to which
523variables ascribed that attribute should be tied.
524
525Note that there is no longer any need to import the Tie::Cycle module --
9df0c874 526Attribute::Handlers takes care of that automagically. You can even pass
527arguments to the module's C<import> subroutine, by appending them to the
528class name. For example:
529
530 use Attribute::Handlers
531 autotie => { Dir => 'Tie::Dir qw(DIR_UNLINK)' };
dc6b6eef 532
533If the attribute name is unqualified, the attribute is installed in the
534current package. Otherwise it is installed in the qualifier's package:
535
dc6b6eef 536 package Here;
537
538 use Attribute::Handlers autotie => {
539 Other::Good => Tie::SecureHash, # tie attr installed in Other::
540 Bad => Tie::Taxes, # tie attr installed in Here::
541 UNIVERSAL::Ugly => Software::Patent # tie attr installed everywhere
542 };
543
9df0c874 544Autoties are most commonly used in the module to which they actually tie,
545and need to export their attributes to any module that calls them. To
546facilitiate this, Attribute::Handlers recognizes a special "pseudo-class" --
547C<__CALLER__>, which may be specified as the qualifier of an attribute:
548
549 package Tie::Me::Kangaroo:Down::Sport;
550
55a1c97c 551 use Attribute::Handlers autotie => { __CALLER__::Roo => __PACKAGE__ };
9df0c874 552
553This causes Attribute::Handlers to define the C<Roo> attribute in the package
554that imports the Tie::Me::Kangaroo:Down::Sport module.
555
55a1c97c 556=head3 Passing the tied object to C<tie>
557
558Occasionally it is important to pass a reference to the object being tied
559to the TIESCALAR, TIEHASH, etc. that ties it.
560
561The C<autotie> mechanism supports this too. The following code:
562
563 use Attribute::Handlers autotieref => { Selfish => Tie::Selfish };
564 my $var : Selfish(@args);
565
566has the same effect as:
567
568 tie my $var, 'Tie::Selfish', @args;
569
570But when C<"autotieref"> is used instead of C<"autotie">:
571
572 use Attribute::Handlers autotieref => { Selfish => Tie::Selfish };
573 my $var : Selfish(@args);
574
575the effect is to pass the C<tie> call an extra reference to the variable
576being tied:
577
578 tie my $var, 'Tie::Selfish', \$var, @args;
579
580
dc6b6eef 581
582=head1 EXAMPLES
583
584If the class shown in L<SYNOPSIS> were placed in the MyClass.pm
585module, then the following code:
586
587 package main;
588 use MyClass;
589
590 my MyClass $slr :Good :Bad(1**1-1) :Omni(-vorous);
591
592 package SomeOtherClass;
593 use base MyClass;
594
595 sub tent { 'acle' }
596
597 sub fn :Ugly(sister) :Omni('po',tent()) {...}
598 my @arr :Good :Omni(s/cie/nt/);
599 my %hsh :Good(q/bye) :Omni(q/bus/);
600
601
602would cause the following handlers to be invoked:
603
604 # my MyClass $slr :Good :Bad(1**1-1) :Omni(-vorous);
605
606 MyClass::Good:ATTR(SCALAR)( 'MyClass', # class
607 'LEXICAL', # no typeglob
608 \$slr, # referent
609 'Good', # attr name
610 undef # no attr data
9df0c874 611 'CHECK', # compiler phase
dc6b6eef 612 );
613
614 MyClass::Bad:ATTR(SCALAR)( 'MyClass', # class
615 'LEXICAL', # no typeglob
616 \$slr, # referent
617 'Bad', # attr name
618 0 # eval'd attr data
9df0c874 619 'CHECK', # compiler phase
dc6b6eef 620 );
621
622 MyClass::Omni:ATTR(SCALAR)( 'MyClass', # class
623 'LEXICAL', # no typeglob
624 \$slr, # referent
625 'Omni', # attr name
626 '-vorous' # eval'd attr data
9df0c874 627 'CHECK', # compiler phase
dc6b6eef 628 );
629
630
631 # sub fn :Ugly(sister) :Omni('po',tent()) {...}
632
633 MyClass::UGLY:ATTR(CODE)( 'SomeOtherClass', # class
634 \*SomeOtherClass::fn, # typeglob
635 \&SomeOtherClass::fn, # referent
636 'Ugly', # attr name
637 'sister' # eval'd attr data
9df0c874 638 'CHECK', # compiler phase
dc6b6eef 639 );
640
641 MyClass::Omni:ATTR(CODE)( 'SomeOtherClass', # class
642 \*SomeOtherClass::fn, # typeglob
643 \&SomeOtherClass::fn, # referent
644 'Omni', # attr name
645 ['po','acle'] # eval'd attr data
9df0c874 646 'CHECK', # compiler phase
dc6b6eef 647 );
648
649
650 # my @arr :Good :Omni(s/cie/nt/);
651
652 MyClass::Good:ATTR(ARRAY)( 'SomeOtherClass', # class
653 'LEXICAL', # no typeglob
654 \@arr, # referent
655 'Good', # attr name
656 undef # no attr data
9df0c874 657 'CHECK', # compiler phase
dc6b6eef 658 );
659
660 MyClass::Omni:ATTR(ARRAY)( 'SomeOtherClass', # class
661 'LEXICAL', # no typeglob
662 \@arr, # referent
663 'Omni', # attr name
664 "" # eval'd attr data
9df0c874 665 'CHECK', # compiler phase
dc6b6eef 666 );
667
668
669 # my %hsh :Good(q/bye) :Omni(q/bus/);
670
671 MyClass::Good:ATTR(HASH)( 'SomeOtherClass', # class
672 'LEXICAL', # no typeglob
673 \%hsh, # referent
674 'Good', # attr name
675 'q/bye' # raw attr data
9df0c874 676 'CHECK', # compiler phase
dc6b6eef 677 );
678
679 MyClass::Omni:ATTR(HASH)( 'SomeOtherClass', # class
680 'LEXICAL', # no typeglob
681 \%hsh, # referent
682 'Omni', # attr name
683 'bus' # eval'd attr data
9df0c874 684 'CHECK', # compiler phase
dc6b6eef 685 );
686
687
688Installing handlers into UNIVERSAL, makes them...err..universal.
689For example:
690
9df0c874 691 package Descriptions;
692 use Attribute::Handlers;
dc6b6eef 693
9df0c874 694 my %name;
695 sub name { return $name{$_[2]}||*{$_[1]}{NAME} }
dc6b6eef 696
9df0c874 697 sub UNIVERSAL::Name :ATTR {
698 $name{$_[2]} = $_[4];
699 }
dc6b6eef 700
9df0c874 701 sub UNIVERSAL::Purpose :ATTR {
702 print STDERR "Purpose of ", &name, " is $_[4]\n";
703 }
dc6b6eef 704
9df0c874 705 sub UNIVERSAL::Unit :ATTR {
706 print STDERR &name, " measured in $_[4]\n";
707 }
dc6b6eef 708
709Let's you write:
710
9df0c874 711 use Descriptions;
dc6b6eef 712
9df0c874 713 my $capacity : Name(capacity)
714 : Purpose(to store max storage capacity for files)
715 : Unit(Gb);
dc6b6eef 716
717
9df0c874 718 package Other;
dc6b6eef 719
9df0c874 720 sub foo : Purpose(to foo all data before barring it) { }
dc6b6eef 721
9df0c874 722 # etc.
dc6b6eef 723
724
725=head1 DIAGNOSTICS
726
727=over
728
9df0c874 729=item C<Bad attribute type: ATTR(%s)>
dc6b6eef 730
731An attribute handler was specified with an C<:ATTR(I<ref_type>)>, but the
732type of referent it was defined to handle wasn't one of the five permitted:
733C<SCALAR>, C<ARRAY>, C<HASH>, C<CODE>, or C<ANY>.
734
9df0c874 735=item C<Attribute handler %s doesn't handle %s attributes>
dc6b6eef 736
737A handler for attributes of the specified name I<was> defined, but not
738for the specified type of declaration. Typically encountered whe trying
739to apply a C<VAR> attribute handler to a subroutine, or a C<SCALAR>
740attribute handler to some other type of variable.
741
9df0c874 742=item C<Declaration of %s attribute in package %s may clash with future reserved word>
dc6b6eef 743
744A handler for an attributes with an all-lowercase name was declared. An
745attribute with an all-lowercase name might have a meaning to Perl
746itself some day, even though most don't yet. Use a mixed-case attribute
747name, instead.
748
9df0c874 749=item C<Can't have two ATTR specifiers on one subroutine>
750
751You just can't, okay?
752Instead, put all the specifications together with commas between them
753in a single C<ATTR(I<specification>)>.
754
755=item C<Can't autotie a %s>
756
757You can only declare autoties for types C<"SCALAR">, C<"ARRAY">, and
41f31d6e 758C<"HASH">. They're the only things (apart from typeglobs -- which are
9df0c874 759not declarable) that Perl can tie.
0addb26a 760
9df0c874 761=item C<Internal error: %s symbol went missing>
dc6b6eef 762
763Something is rotten in the state of the program. An attributed
9df0c874 764subroutine ceased to exist between the point it was declared and the point
765at which its attribute handler(s) would have been called.
dc6b6eef 766
767=back
768
769=head1 AUTHOR
770
771Damian Conway (damian@conway.org)
772
773=head1 BUGS
774
775There are undoubtedly serious bugs lurking somewhere in code this funky :-)
776Bug reports and other feedback are most welcome.
777
778=head1 COPYRIGHT
779
780 Copyright (c) 2001, Damian Conway. All Rights Reserved.
781 This module is free software. It may be used, redistributed
55a1c97c 782 and/or modified under the same terms as Perl itself.