This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
e13bbb87de5d0a8720ca0cca9f8d351d5b86a97d
[perl5.git] / ext / attributes / attributes.pm
1 package attributes;
2
3 our $VERSION = 0.18;
4
5 @EXPORT_OK = qw(get reftype);
6 @EXPORT = ();
7 %EXPORT_TAGS = (ALL => [@EXPORT, @EXPORT_OK]);
8
9 use strict;
10
11 sub croak {
12     require Carp;
13     goto &Carp::croak;
14 }
15
16 sub carp {
17     require Carp;
18     goto &Carp::carp;
19 }
20
21 my %deprecated;
22 $deprecated{CODE} = qr/\A-?(locked)\z/;
23 $deprecated{ARRAY} = $deprecated{HASH} = $deprecated{SCALAR}
24     = qr/\A-?(unique)\z/;
25
26 sub _modify_attrs_and_deprecate {
27     my $svtype = shift;
28     # Now that we've removed handling of locked from the XS code, we need to
29     # remove it here, else it ends up in @badattrs. (If we do the deprecation in
30     # XS, we can't control the warning based on *our* caller's lexical settings,
31     # and the warned line is in this package)
32     grep {
33         $deprecated{$svtype} && /$deprecated{$svtype}/ ? do {
34             require warnings;
35             warnings::warnif('deprecated', "Attribute \"$1\" is deprecated");
36             0;
37         } : $svtype eq 'CODE' && /^-?lvalue\z/ ? do {
38             require warnings;
39             warnings::warnif(
40                 'misc',
41                 "lvalue attribute "
42                    . (/^-/ ? "removed from" : "applied to")
43                    . " already-defined subroutine"
44             );
45             0;
46         } : 1
47     } _modify_attrs(@_);
48 }
49
50 sub import {
51     @_ > 2 && ref $_[2] or do {
52         require Exporter;
53         goto &Exporter::import;
54     };
55     my (undef,$home_stash,$svref,@attrs) = @_;
56
57     my $svtype = uc reftype($svref);
58     my $pkgmeth;
59     $pkgmeth = UNIVERSAL::can($home_stash, "MODIFY_${svtype}_ATTRIBUTES")
60         if defined $home_stash && $home_stash ne '';
61     my @badattrs;
62     if ($pkgmeth) {
63         my @pkgattrs = _modify_attrs_and_deprecate($svtype, $svref, @attrs);
64         @badattrs = $pkgmeth->($home_stash, $svref, @pkgattrs);
65         if (!@badattrs && @pkgattrs) {
66             require warnings;
67             return unless warnings::enabled('reserved');
68             @pkgattrs = grep { m/\A[[:lower:]]+(?:\z|\()/ } @pkgattrs;
69             if (@pkgattrs) {
70                 for my $attr (@pkgattrs) {
71                     $attr =~ s/\(.+\z//s;
72                 }
73                 my $s = ((@pkgattrs == 1) ? '' : 's');
74                 carp "$svtype package attribute$s " .
75                     "may clash with future reserved word$s: " .
76                     join(' : ' , @pkgattrs);
77             }
78         }
79     }
80     else {
81         @badattrs = _modify_attrs_and_deprecate($svtype, $svref, @attrs);
82     }
83     if (@badattrs) {
84         croak "Invalid $svtype attribute" .
85             (( @badattrs == 1 ) ? '' : 's') .
86             ": " .
87             join(' : ', @badattrs);
88     }
89 }
90
91 sub get ($) {
92     @_ == 1  && ref $_[0] or
93         croak 'Usage: '.__PACKAGE__.'::get $ref';
94     my $svref = shift;
95     my $svtype = uc reftype($svref);
96     my $stash = _guess_stash($svref);
97     $stash = caller unless defined $stash;
98     my $pkgmeth;
99     $pkgmeth = UNIVERSAL::can($stash, "FETCH_${svtype}_ATTRIBUTES")
100         if defined $stash && $stash ne '';
101     return $pkgmeth ?
102                 (_fetch_attrs($svref), $pkgmeth->($stash, $svref)) :
103                 (_fetch_attrs($svref))
104         ;
105 }
106
107 sub require_version { goto &UNIVERSAL::VERSION }
108
109 require XSLoader;
110 XSLoader::load();
111
112 1;
113 __END__
114 #The POD goes here
115
116 =head1 NAME
117
118 attributes - get/set subroutine or variable attributes
119
120 =head1 SYNOPSIS
121
122   sub foo : method ;
123   my ($x,@y,%z) : Bent = 1;
124   my $s = sub : method { ... };
125
126   use attributes ();    # optional, to get subroutine declarations
127   my @attrlist = attributes::get(\&foo);
128
129   use attributes 'get'; # import the attributes::get subroutine
130   my @attrlist = get \&foo;
131
132 =head1 DESCRIPTION
133
134 Subroutine declarations and definitions may optionally have attribute lists
135 associated with them.  (Variable C<my> declarations also may, but see the
136 warning below.)  Perl handles these declarations by passing some information
137 about the call site and the thing being declared along with the attribute
138 list to this module.  In particular, the first example above is equivalent to
139 the following:
140
141     use attributes __PACKAGE__, \&foo, 'method';
142
143 The second example in the synopsis does something equivalent to this:
144
145     use attributes ();
146     my ($x,@y,%z);
147     attributes::->import(__PACKAGE__, \$x, 'Bent');
148     attributes::->import(__PACKAGE__, \@y, 'Bent');
149     attributes::->import(__PACKAGE__, \%z, 'Bent');
150     ($x,@y,%z) = 1;
151
152 Yes, that's a lot of expansion.
153
154 B<WARNING>: attribute declarations for variables are still evolving.
155 The semantics and interfaces of such declarations could change in
156 future versions.  They are present for purposes of experimentation
157 with what the semantics ought to be.  Do not rely on the current
158 implementation of this feature.
159
160 There are only a few attributes currently handled by Perl itself (or
161 directly by this module, depending on how you look at it.)  However,
162 package-specific attributes are allowed by an extension mechanism.
163 (See L<"Package-specific Attribute Handling"> below.)
164
165 The setting of subroutine attributes happens at compile time.
166 Variable attributes in C<our> declarations are also applied at compile time.
167 However, C<my> variables get their attributes applied at run-time.
168 This means that you have to I<reach> the run-time component of the C<my>
169 before those attributes will get applied.  For example:
170
171     my $x : Bent = 42 if 0;
172
173 will neither assign 42 to $x I<nor> will it apply the C<Bent> attribute
174 to the variable.
175
176 An attempt to set an unrecognized attribute is a fatal error.  (The
177 error is trappable, but it still stops the compilation within that
178 C<eval>.)  Setting an attribute with a name that's all lowercase
179 letters that's not a built-in attribute (such as "foo") will result in
180 a warning with B<-w> or C<use warnings 'reserved'>.
181
182 =head2 What C<import> does
183
184 In the description it is mentioned that
185
186   sub foo : method;
187
188 is equivalent to
189
190   use attributes __PACKAGE__, \&foo, 'method';
191
192 As you might know this calls the C<import> function of C<attributes> at compile 
193 time with these parameters: 'attributes', the caller's package name, the reference 
194 to the code and 'method'.
195
196   attributes->import( __PACKAGE__, \&foo, 'method' );
197
198 So you want to know what C<import> actually does?
199
200 First of all C<import> gets the type of the third parameter ('CODE' in this case).
201 C<attributes.pm> checks if there is a subroutine called C<< MODIFY_<reftype>_ATTRIBUTES >>
202 in the caller's namespace (here: 'main'). In this case a subroutine C<MODIFY_CODE_ATTRIBUTES> is
203 required. Then this method is called to check if you have used a "bad attribute".
204 The subroutine call in this example would look like
205
206   MODIFY_CODE_ATTRIBUTES( 'main', \&foo, 'method' );
207
208 C<< MODIFY_<reftype>_ATTRIBUTES >> has to return a list of all "bad attributes".
209 If there are any bad attributes C<import> croaks.
210
211 (See L<"Package-specific Attribute Handling"> below.)
212
213 =head2 Built-in Attributes
214
215 The following are the built-in attributes for subroutines:
216
217 =over 4
218
219 =item lvalue
220
221 Indicates that the referenced subroutine is a valid lvalue and can
222 be assigned to. The subroutine must return a modifiable value such
223 as a scalar variable, as described in L<perlsub>.
224
225 This module allows one to set this attribute on a subroutine that is
226 already defined.  For Perl subroutines (XSUBs are fine), it may or may not
227 do what you want, depending on the code inside the subroutine, with details
228 subject to change in future Perl versions.  You may run into problems with
229 lvalue context not being propagated properly into the subroutine, or maybe
230 even assertion failures.  For this reason, a warning is emitted if warnings
231 are enabled.  In other words, you should only do this if you really know
232 what you are doing.  You have been warned.
233
234 =item method
235
236 Indicates that the referenced subroutine is a method. A subroutine so marked
237 will not trigger the "Ambiguous call resolved as CORE::%s" warning.
238
239 =item locked
240
241 The "locked" attribute has no effect in 5.10.0 and later. It was used as part
242 of the now-removed "Perl 5.005 threads".
243
244 =back
245
246 =head2 Available Subroutines
247
248 The following subroutines are available for general use once this module
249 has been loaded:
250
251 =over 4
252
253 =item get
254
255 This routine expects a single parameter--a reference to a
256 subroutine or variable.  It returns a list of attributes, which may be
257 empty.  If passed invalid arguments, it uses die() (via L<Carp::croak|Carp>)
258 to raise a fatal exception.  If it can find an appropriate package name
259 for a class method lookup, it will include the results from a
260 C<FETCH_I<type>_ATTRIBUTES> call in its return list, as described in
261 L<"Package-specific Attribute Handling"> below.
262 Otherwise, only L<built-in attributes|"Built-in Attributes"> will be returned.
263
264 =item reftype
265
266 This routine expects a single parameter--a reference to a subroutine or
267 variable.  It returns the built-in type of the referenced variable,
268 ignoring any package into which it might have been blessed.
269 This can be useful for determining the I<type> value which forms part of
270 the method names described in L<"Package-specific Attribute Handling"> below.
271
272 =back
273
274 Note that these routines are I<not> exported by default.
275
276 =head2 Package-specific Attribute Handling
277
278 B<WARNING>: the mechanisms described here are still experimental.  Do not
279 rely on the current implementation.  In particular, there is no provision
280 for applying package attributes to 'cloned' copies of subroutines used as
281 closures.  (See L<perlref/"Making References"> for information on closures.)
282 Package-specific attribute handling may change incompatibly in a future
283 release.
284
285 When an attribute list is present in a declaration, a check is made to see
286 whether an attribute 'modify' handler is present in the appropriate package
287 (or its @ISA inheritance tree).  Similarly, when C<attributes::get> is
288 called on a valid reference, a check is made for an appropriate attribute
289 'fetch' handler.  See L<"EXAMPLES"> to see how the "appropriate package"
290 determination works.
291
292 The handler names are based on the underlying type of the variable being
293 declared or of the reference passed.  Because these attributes are
294 associated with subroutine or variable declarations, this deliberately
295 ignores any possibility of being blessed into some package.  Thus, a
296 subroutine declaration uses "CODE" as its I<type>, and even a blessed
297 hash reference uses "HASH" as its I<type>.
298
299 The class methods invoked for modifying and fetching are these:
300
301 =over 4
302
303 =item FETCH_I<type>_ATTRIBUTES
304
305 This method is called with two arguments:  the relevant package name,
306 and a reference to a variable or subroutine for which package-defined
307 attributes are desired.  The expected return value is a list of
308 associated attributes.  This list may be empty.
309
310 =item MODIFY_I<type>_ATTRIBUTES
311
312 This method is called with two fixed arguments, followed by the list of
313 attributes from the relevant declaration.  The two fixed arguments are
314 the relevant package name and a reference to the declared subroutine or
315 variable.  The expected return value is a list of attributes which were
316 not recognized by this handler.  Note that this allows for a derived class
317 to delegate a call to its base class, and then only examine the attributes
318 which the base class didn't already handle for it.
319
320 The call to this method is currently made I<during> the processing of the
321 declaration.  In particular, this means that a subroutine reference will
322 probably be for an undefined subroutine, even if this declaration is
323 actually part of the definition.
324
325 It is up to this method to store the list of attributes if they will be
326 needed later, as well as checking for any errors.  In this example there
327 are no error conditions, so we just store:
328
329   my %attrs;
330   sub MODIFY_CODE_ATTRIBUTES {
331     my($package, $subref, @attrs) = @_;
332     $attrs{ refaddr $subref } = \@attrs;
333     return;
334   }
335   sub FETCH_CODE_ATTRIBUTES {
336     my($package, $subref) = @_;
337     my $attrs = $attrs{ refaddr $subref };
338     return $attrs ? @$attrs : ();
339   }
340
341 =back
342
343 Calling C<attributes::get()> from within the scope of a null package
344 declaration C<package ;> for an unblessed variable reference will
345 not provide any starting package name for the 'fetch' method lookup.
346 Thus, this circumstance will not result in a method call for package-defined
347 attributes.  A named subroutine knows to which symbol table entry it belongs
348 (or originally belonged), and it will use the corresponding package.
349 An anonymous subroutine knows the package name into which it was compiled
350 (unless it was also compiled with a null package declaration), and so it
351 will use that package name.
352
353 =head2 Syntax of Attribute Lists
354
355 An attribute list is a sequence of attribute specifications, separated by
356 whitespace or a colon (with optional whitespace).
357 Each attribute specification is a simple
358 name, optionally followed by a parenthesised parameter list.
359 If such a parameter list is present, it is scanned past as for the rules
360 for the C<q()> operator.  (See L<perlop/"Quote and Quote-like Operators">.)
361 The parameter list is passed as it was found, however, and not as per C<q()>.
362
363 Some examples of syntactically valid attribute lists:
364
365     switch(10,foo(7,3))  :  expensive
366     Ugly('\(") :Bad
367     _5x5
368     lvalue method
369
370 Some examples of syntactically invalid attribute lists (with annotation):
371
372     switch(10,foo()             # ()-string not balanced
373     Ugly('(')                   # ()-string not balanced
374     5x5                         # "5x5" not a valid identifier
375     Y2::north                   # "Y2::north" not a simple identifier
376     foo + bar                   # "+" neither a colon nor whitespace
377
378 =head1 EXPORTS
379
380 =head2 Default exports
381
382 None.
383
384 =head2 Available exports
385
386 The routines C<get> and C<reftype> are exportable.
387
388 =head2 Export tags defined
389
390 The C<:ALL> tag will get all of the above exports.
391
392 =head1 EXAMPLES
393
394 Here are some samples of syntactically valid declarations, with annotation
395 as to how they resolve internally into C<use attributes> invocations by
396 perl.  These examples are primarily useful to see how the "appropriate
397 package" is found for the possible method lookups for package-defined
398 attributes.
399
400 =over 4
401
402 =item 1.
403
404 Code:
405
406     package Canine;
407     package Dog;
408     my Canine $spot : Watchful ;
409
410 Effect:
411
412     use attributes ();
413     attributes::->import(Canine => \$spot, "Watchful");
414
415 =item 2.
416
417 Code:
418
419     package Felis;
420     my $cat : Nervous;
421
422 Effect:
423
424     use attributes ();
425     attributes::->import(Felis => \$cat, "Nervous");
426
427 =item 3.
428
429 Code:
430
431     package X;
432     sub foo : lvalue ;
433
434 Effect:
435
436     use attributes X => \&foo, "lvalue";
437
438 =item 4.
439
440 Code:
441
442     package X;
443     sub Y::x : lvalue { 1 }
444
445 Effect:
446
447     use attributes Y => \&Y::x, "lvalue";
448
449 =item 5.
450
451 Code:
452
453     package X;
454     sub foo { 1 }
455
456     package Y;
457     BEGIN { *bar = \&X::foo; }
458
459     package Z;
460     sub Y::bar : lvalue ;
461
462 Effect:
463
464     use attributes X => \&X::foo, "lvalue";
465
466 =back
467
468 This last example is purely for purposes of completeness.  You should not
469 be trying to mess with the attributes of something in a package that's
470 not your own.
471
472 =head1 MORE EXAMPLES
473
474 =over 4
475
476 =item 1.
477
478     sub MODIFY_CODE_ATTRIBUTES {
479        my ($class,$code,@attrs) = @_;
480
481        my $allowed = 'MyAttribute';
482        my @bad = grep { $_ ne $allowed } @attrs;
483
484        return @bad;
485     }
486
487     sub foo : MyAttribute {
488        print "foo\n";
489     }
490
491 This example runs. At compile time C<MODIFY_CODE_ATTRIBUTES> is called. In that
492 subroutine, we check if any attribute is disallowed and we return a list of
493 these "bad attributes".
494
495 As we return an empty list, everything is fine.
496
497 =item 2.
498
499   sub MODIFY_CODE_ATTRIBUTES {
500      my ($class,$code,@attrs) = @_;
501
502      my $allowed = 'MyAttribute';
503      my @bad = grep{ $_ ne $allowed }@attrs;
504
505      return @bad;
506   }
507
508   sub foo : MyAttribute Test {
509      print "foo\n";
510   }
511
512 This example is aborted at compile time as we use the attribute "Test" which
513 isn't allowed. C<MODIFY_CODE_ATTRIBUTES> returns a list that contains a single
514 element ('Test').
515
516 =back
517
518 =head1 SEE ALSO
519
520 L<perlsub/"Private Variables via my()"> and
521 L<perlsub/"Subroutine Attributes"> for details on the basic declarations;
522 L<perlfunc/use> for details on the normal invocation mechanism.
523
524 =cut