attributes.pm 16 KB

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