1 package Attribute::Handlers;
10 my ($pkg, $ref, $type) = @_;
11 return $symcache{$pkg,$ref} if $symcache{$pkg,$ref};
14 foreach my $sym ( values %{$pkg."::"} ) {
15 return $symcache{$pkg,$ref} = \$sym
16 if *{$sym}{$type} && *{$sym}{$type} == $ref;
21 VAR => [qw[SCALAR ARRAY HASH]],
22 ANY => [qw[SCALAR ARRAY HASH CODE]],
23 "" => [qw[SCALAR ARRAY HASH CODE]],
24 SCALAR => [qw[SCALAR]],
33 my %sigil = (SCALAR=>'$', ARRAY=>'@', HASH=>'%');
36 croak "Usage: use $_[0] autotie => {AttrName => TieClassName,...}";
39 my $qual_id = qr/^[_a-z]\w*(::[_a-z]\w*)*$/i;
43 return unless $class eq "Attribute::Handlers";
46 if ($cmd =~ /^autotie((?:ref)?)$/) {
47 my $tiedata = '($was_arrayref ? $data : @$data)';
48 $tiedata = ($1 ? '$ref, ' : '') . $tiedata;
50 _usage_AH_ $class unless ref($mapping) eq 'HASH';
51 while (my($attr, $tieclass) = each %$mapping) {
52 $tieclass =~ s/^([_a-z]\w*(::[_a-z]\w*)*)(.*)/$1/is;
54 _usage_AH_ $class unless $attr =~ $qual_id
55 && $tieclass =~ $qual_id
56 && eval "use base $tieclass; 1";
57 if ($tieclass->isa('Exporter')) {
58 local $Exporter::ExportLevel = 2;
59 $tieclass->import(eval $args);
61 $attr =~ s/__CALLER__/caller(1)/e;
62 $attr = caller()."::".$attr unless $attr =~ /::/;
64 sub $attr : ATTR(VAR) {
65 my (\$ref, \$data) = \@_[2,4];
66 my \$was_arrayref = ref \$data eq 'ARRAY';
67 \$data = [ \$data ] unless \$was_arrayref;
68 my \$type = ref(\$ref)||"value (".(\$ref||"<undef>").")";
69 (\$type eq 'SCALAR')? tie \$\$ref,'$tieclass',$tiedata
70 :(\$type eq 'ARRAY') ? tie \@\$ref,'$tieclass',$tiedata
71 :(\$type eq 'HASH') ? tie \%\$ref,'$tieclass',$tiedata
72 : die "Can't autotie a \$type\n"
74 } or die "Internal error: $@";
78 croak "Can't understand $_";
82 sub _resolve_lastattr {
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};
96 my ($class) = $AUTOLOAD =~ m/(.*)::/g;
97 $AUTOLOAD =~ m/_ATTR_(.*?)_(.*)/ or
98 croak "Can't locate class method '$AUTOLOAD' via package '$class'";
99 croak "Attribute handler '$3' doesn't handle $2 attributes";
104 my $builtin = qr/lvalue|method|locked/;
106 sub _gen_handler_AH_() {
109 my ($pkg, $ref, @attrs) = @_;
111 my ($attr, $data) = /^([a-z_]\w*)(?:[(](.*)[)])?$/is or next;
112 if ($attr eq 'ATTR') {
114 $raw{$ref} = $data =~ s/\s*,?\s*RAWDATA\s*,?\s*//;
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"
126 croak "Bad attribute type: ATTR($data)"
127 unless $validtype{$data};
128 %lastattr=(pkg=>$pkg,ref=>$ref,type=>$data);
131 my $handler = $pkg->can($attr);
132 next unless $handler;
133 my $decl = [$pkg, $ref, $attr, $data,
134 $raw{$handler}, $phase{$handler}];
135 _apply_handler_AH_($decl,'BEGIN');
136 push @declarations, $decl;
140 return grep {defined && !/$builtin/} @attrs;
144 *{"MODIFY_${_}_ATTRIBUTES"} = _gen_handler_AH_ foreach @{$validtype{ANY}};
145 push @UNIVERSAL::ISA, 'Attribute::Handlers'
146 unless grep /^Attribute::Handlers$/, @UNIVERSAL::ISA;
148 sub _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";
154 my $handler = "_ATTR_${type}_${attr}";
155 my $sym = findsym($pkg, $ref);
156 $sym ||= $type eq 'CODE' ? 'ANON' : 'LEXICAL';
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
164 (ref $sym eq 'GLOB' ? *{$sym}{ref $ref}||$ref : $ref),
166 (@$data>1? $data : $data->[0]),
174 _apply_handler_AH_($_,'CHECK') foreach @declarations;
177 INIT { _apply_handler_AH_($_,'INIT') foreach @declarations }
179 END { _apply_handler_AH_($_,'END') foreach @declarations }
186 Attribute::Handlers - Simpler definition of attribute handlers
190 This document describes version 0.75 of Attribute::Handlers,
191 released September 3, 2001.
197 use Attribute::Handlers;
198 no warnings 'redefine';
201 sub Good : ATTR(SCALAR) {
202 my ($package, $symbol, $referent, $attr, $data) = @_;
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.
208 # Do whatever to $referent here (executed in CHECK phase).
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.
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.
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.
233 sub Ugly : ATTR(CODE) {
234 # Invoked for any subroutine declared in MyClass (or a
235 # derived class) with an :Ugly attribute.
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.
249 use Attribute::Handlers autotie => { Cycle => Tie::Cycle };
251 my $next : Cycle(['A'..'Z']);
256 This module, when inherited by a package, allows that package's class to
257 define attribute handler subroutines for specific attributes. Variables
258 and subroutines subsequently defined in that package, or in packages
259 derived from that package may be given attributes with the same names as
260 the attribute handler subroutines, which will then be called in one of
261 the compilation phases (i.e. in a C<BEGIN>, C<CHECK>, C<INIT>, or C<END>
264 To create a handler, define it as a subroutine with the same name as
265 the desired attribute, and declare the subroutine itself with the
266 attribute C<:ATTR>. For example:
269 use Attribute::Handlers;
272 my ($package, $symbol, $referent, $attr, $data, $phase) = @_;
275 *{$symbol}{NAME}, " ",
276 "($referent) ", "was just declared ",
277 "and ascribed the ${attr} attribute ",
278 "with data ($data)\n",
282 This creates an handler for the attribute C<:Loud> in the class LoudDecl.
283 Thereafter, any subroutine declared with a C<:Loud> attribute in the class
290 causes the above handler to be invoked, and passed:
296 the name of the package into which it was declared;
300 a reference to the symbol table entry (typeglob) containing the subroutine;
304 a reference to the subroutine;
308 the name of the attribute;
312 any data associated with that attribute;
316 the name of the phase in which the handler is being invoked.
320 Likewise, declaring any variables with the C<:Loud> attribute within the
329 will cause the handler to be called with a similar argument list (except,
330 of course, that C<$_[2]> will be a reference to the variable).
332 The package name argument will typically be the name of the class into
333 which the subroutine was declared, but it may also be the name of a derived
334 class (since handlers are inherited).
336 If a lexical variable is given an attribute, there is no symbol table to
337 which it belongs, so the symbol table argument (C<$_[1]>) is set to the
338 string C<'LEXICAL'> in that case. Likewise, ascribing an attribute to
339 an anonymous subroutine results in a symbol table argument of C<'ANON'>.
341 The data argument passes in the value (if any) associated with the
342 attribute. For example, if C<&foo> had been declared:
344 sub foo :Loud("turn it up to 11, man!") {...}
346 then the string C<"turn it up to 11, man!"> would be passed as the
349 Attribute::Handlers makes strenuous efforts to convert
350 the data argument (C<$_[4]>) to a useable form before passing it to
351 the handler (but see L<"Non-interpretive attribute handlers">).
352 For example, all of these:
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) {...}
360 causes it to pass C<['till','ears','are','bleeding']> as the handler's
361 data argument. However, if the data can't be parsed as valid Perl, then
362 it is passed as an uninterpreted string. For example:
364 sub foo :Loud(my,ears,are,bleeding) {...}
365 sub foo :Loud(qw/my ears are bleeding) {...}
367 cause the strings C<'my,ears,are,bleeding'> and C<'qw/my ears are bleeding'>
368 respectively to be passed as the data argument.
370 If the attribute has only a single associated scalar data value, that value is
371 passed as a scalar. If multiple values are associated, they are passed as an
372 array reference. If no value is associated with the attribute, C<undef> is
376 =head2 Typed lexicals
378 Regardless of the package in which it is declared, if a lexical variable is
379 ascribed an attribute, the handler that is invoked is the one belonging to
380 the package to which it is typed. For example, the following declarations:
384 my LoudDecl $loudobj : Loud;
385 my LoudDecl @loudobjs : Loud;
386 my LoudDecl %loudobjex : Loud;
388 causes the LoudDecl::Loud handler to be invoked (even if OtherClass also
389 defines a handler for C<:Loud> attributes).
392 =head2 Type-specific attribute handlers
394 If an attribute handler is declared and the C<:ATTR> specifier is
395 given the name of a built-in type (C<SCALAR>, C<ARRAY>, C<HASH>, or C<CODE>),
396 the handler is only applied to declarations of that type. For example,
397 the following definition:
401 sub RealLoud :ATTR(SCALAR) { print "Yeeeeow!" }
403 creates an attribute handler that applies only to scalars:
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
414 You 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):
418 use Attribute::Handlers;
419 no warnings 'redefine';
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" }
426 You can also explicitly indicate that a single handler is meant to be
427 used for all types of referents like so:
430 use Attribute::Handlers;
432 sub SeriousLoud :ATTR(ANY) { warn "Hearing loss imminent" }
434 (I.e. C<ATTR(ANY)> is a synonym for C<:ATTR>).
437 =head2 Non-interpretive attribute handlers
439 Occasionally the strenuous efforts Attribute::Handlers makes to convert
440 the data argument (C<$_[4]>) to a useable form before passing it to
441 the handler get in the way.
443 You can turn off that eagerness-to-help by declaring
444 an attribute handler with the the keyword C<RAWDATA>. For example:
446 sub Raw : ATTR(RAWDATA) {...}
447 sub Nekkid : ATTR(SCALAR,RAWDATA) {...}
448 sub Au::Naturale : ATTR(RAWDATA,ANY) {...}
450 Then the handler makes absolutely no attempt to interpret the data it
451 receives and simply passes it as a string:
453 my $power : Raw(1..100); # handlers receives "1..100"
455 =head2 Phase-specific attribute handlers
457 By default, attribute handlers are called at the end of the compilation
458 phase (in a C<CHECK> block). This seems to be optimal in most cases because
459 most things that can be defined are defined by that point but nothing has
462 However, it is possible to set up attribute handlers that are called at
463 other points in the program's compilation or execution, by explicitly
464 stating the phase (or phases) in which you wish the attribute handler to
465 be called. For example:
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) {...}
473 As the last example indicates, a handler may be set up to be (re)called in
474 two or more phases. The phase name is passed as the handler's final argument.
476 Note that attribute handlers that are scheduled for the C<BEGIN> phase
477 are handled as soon as the attribute is detected (i.e. before any
478 subsequently defined C<BEGIN> blocks are executed).
481 =head2 Attributes as C<tie> interfaces
483 Attributes make an excellent and intuitive interface through which to tie
484 variables. For example:
486 use Attribute::Handlers;
489 sub UNIVERSAL::Cycle : ATTR(SCALAR) {
490 my ($package, $symbol, $referent, $attr, $data, $phase) = @_;
491 $data = [ $data ] unless ref $data eq 'ARRAY';
492 tie $$referent, 'Tie::Cycle', $data;
499 my $next : Cycle('A'..'Z'); # $next is now a tied variable
505 In fact, this pattern is so widely applicable that Attribute::Handlers
506 provides a way to automate it: specifying C<'autotie'> in the
507 C<use Attribute::Handlers> statement. So, the previous example,
508 could also be written:
510 use Attribute::Handlers autotie => { Cycle => 'Tie::Cycle' };
516 my $next : Cycle('A'..'Z'); # $next is now a tied variable
521 The argument after C<'autotie'> is a reference to a hash in which each key is
522 the name of an attribute to be created, and each value is the class to which
523 variables ascribed that attribute should be tied.
525 Note that there is no longer any need to import the Tie::Cycle module --
526 Attribute::Handlers takes care of that automagically. You can even pass
527 arguments to the module's C<import> subroutine, by appending them to the
528 class name. For example:
530 use Attribute::Handlers
531 autotie => { Dir => 'Tie::Dir qw(DIR_UNLINK)' };
533 If the attribute name is unqualified, the attribute is installed in the
534 current package. Otherwise it is installed in the qualifier's package:
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
544 Autoties are most commonly used in the module to which they actually tie,
545 and need to export their attributes to any module that calls them. To
546 facilitiate this, Attribute::Handlers recognizes a special "pseudo-class" --
547 C<__CALLER__>, which may be specified as the qualifier of an attribute:
549 package Tie::Me::Kangaroo:Down::Sport;
551 use Attribute::Handlers autotie => { __CALLER__::Roo => __PACKAGE__ };
553 This causes Attribute::Handlers to define the C<Roo> attribute in the package
554 that imports the Tie::Me::Kangaroo:Down::Sport module.
556 =head3 Passing the tied object to C<tie>
558 Occasionally it is important to pass a reference to the object being tied
559 to the TIESCALAR, TIEHASH, etc. that ties it.
561 The C<autotie> mechanism supports this too. The following code:
563 use Attribute::Handlers autotieref => { Selfish => Tie::Selfish };
564 my $var : Selfish(@args);
566 has the same effect as:
568 tie my $var, 'Tie::Selfish', @args;
570 But when C<"autotieref"> is used instead of C<"autotie">:
572 use Attribute::Handlers autotieref => { Selfish => Tie::Selfish };
573 my $var : Selfish(@args);
575 the effect is to pass the C<tie> call an extra reference to the variable
578 tie my $var, 'Tie::Selfish', \$var, @args;
584 If the class shown in L<SYNOPSIS> were placed in the MyClass.pm
585 module, then the following code:
590 my MyClass $slr :Good :Bad(1**1-1) :Omni(-vorous);
592 package SomeOtherClass;
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/);
602 would cause the following handlers to be invoked:
604 # my MyClass $slr :Good :Bad(1**1-1) :Omni(-vorous);
606 MyClass::Good:ATTR(SCALAR)( 'MyClass', # class
607 'LEXICAL', # no typeglob
611 'CHECK', # compiler phase
614 MyClass::Bad:ATTR(SCALAR)( 'MyClass', # class
615 'LEXICAL', # no typeglob
619 'CHECK', # compiler phase
622 MyClass::Omni:ATTR(SCALAR)( 'MyClass', # class
623 'LEXICAL', # no typeglob
626 '-vorous' # eval'd attr data
627 'CHECK', # compiler phase
631 # sub fn :Ugly(sister) :Omni('po',tent()) {...}
633 MyClass::UGLY:ATTR(CODE)( 'SomeOtherClass', # class
634 \*SomeOtherClass::fn, # typeglob
635 \&SomeOtherClass::fn, # referent
637 'sister' # eval'd attr data
638 'CHECK', # compiler phase
641 MyClass::Omni:ATTR(CODE)( 'SomeOtherClass', # class
642 \*SomeOtherClass::fn, # typeglob
643 \&SomeOtherClass::fn, # referent
645 ['po','acle'] # eval'd attr data
646 'CHECK', # compiler phase
650 # my @arr :Good :Omni(s/cie/nt/);
652 MyClass::Good:ATTR(ARRAY)( 'SomeOtherClass', # class
653 'LEXICAL', # no typeglob
657 'CHECK', # compiler phase
660 MyClass::Omni:ATTR(ARRAY)( 'SomeOtherClass', # class
661 'LEXICAL', # no typeglob
664 "" # eval'd attr data
665 'CHECK', # compiler phase
669 # my %hsh :Good(q/bye) :Omni(q/bus/);
671 MyClass::Good:ATTR(HASH)( 'SomeOtherClass', # class
672 'LEXICAL', # no typeglob
675 'q/bye' # raw attr data
676 'CHECK', # compiler phase
679 MyClass::Omni:ATTR(HASH)( 'SomeOtherClass', # class
680 'LEXICAL', # no typeglob
683 'bus' # eval'd attr data
684 'CHECK', # compiler phase
688 Installing handlers into UNIVERSAL, makes them...err..universal.
691 package Descriptions;
692 use Attribute::Handlers;
695 sub name { return $name{$_[2]}||*{$_[1]}{NAME} }
697 sub UNIVERSAL::Name :ATTR {
698 $name{$_[2]} = $_[4];
701 sub UNIVERSAL::Purpose :ATTR {
702 print STDERR "Purpose of ", &name, " is $_[4]\n";
705 sub UNIVERSAL::Unit :ATTR {
706 print STDERR &name, " measured in $_[4]\n";
713 my $capacity : Name(capacity)
714 : Purpose(to store max storage capacity for files)
720 sub foo : Purpose(to foo all data before barring it) { }
729 =item C<Bad attribute type: ATTR(%s)>
731 An attribute handler was specified with an C<:ATTR(I<ref_type>)>, but the
732 type of referent it was defined to handle wasn't one of the five permitted:
733 C<SCALAR>, C<ARRAY>, C<HASH>, C<CODE>, or C<ANY>.
735 =item C<Attribute handler %s doesn't handle %s attributes>
737 A handler for attributes of the specified name I<was> defined, but not
738 for the specified type of declaration. Typically encountered whe trying
739 to apply a C<VAR> attribute handler to a subroutine, or a C<SCALAR>
740 attribute handler to some other type of variable.
742 =item C<Declaration of %s attribute in package %s may clash with future reserved word>
744 A handler for an attributes with an all-lowercase name was declared. An
745 attribute with an all-lowercase name might have a meaning to Perl
746 itself some day, even though most don't yet. Use a mixed-case attribute
749 =item C<Can't have two ATTR specifiers on one subroutine>
751 You just can't, okay?
752 Instead, put all the specifications together with commas between them
753 in a single C<ATTR(I<specification>)>.
755 =item C<Can't autotie a %s>
757 You can only declare autoties for types C<"SCALAR">, C<"ARRAY">, and
758 C<"SCALAR">. They're the only things (apart from typeglobs -- which are
759 not declarable) that Perl can tie.
761 =item C<Internal error: %s symbol went missing>
763 Something is rotten in the state of the program. An attributed
764 subroutine ceased to exist between the point it was declared and the point
765 at which its attribute handler(s) would have been called.
771 Damian Conway (damian@conway.org)
775 There are undoubtedly serious bugs lurking somewhere in code this funky :-)
776 Bug reports and other feedback are most welcome.
780 Copyright (c) 2001, Damian Conway. All Rights Reserved.
781 This module is free software. It may be used, redistributed
782 and/or modified under the same terms as Perl itself.