Leaked source code of windows server 2003
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.

285 lines
8.1 KiB

  1. package fields;
  2. =head1 NAME
  3. fields - compile-time class fields
  4. =head1 SYNOPSIS
  5. {
  6. package Foo;
  7. use fields qw(foo bar _Foo_private);
  8. sub new {
  9. my Foo $self = shift;
  10. unless (ref $self) {
  11. $self = fields::new($self);
  12. $self->{_Foo_private} = "this is Foo's secret";
  13. }
  14. $self->{foo} = 10;
  15. $self->{bar} = 20;
  16. return $self;
  17. }
  18. }
  19. my Foo $var = Foo::->new;
  20. $var->{foo} = 42;
  21. # this will generate a compile-time error
  22. $var->{zap} = 42;
  23. # subclassing
  24. {
  25. package Bar;
  26. use base 'Foo';
  27. use fields qw(baz _Bar_private); # not shared with Foo
  28. sub new {
  29. my $class = shift;
  30. my $self = fields::new($class);
  31. $self->SUPER::new(); # init base fields
  32. $self->{baz} = 10; # init own fields
  33. $self->{_Bar_private} = "this is Bar's secret";
  34. return $self;
  35. }
  36. }
  37. =head1 DESCRIPTION
  38. The C<fields> pragma enables compile-time verified class fields.
  39. NOTE: The current implementation keeps the declared fields in the %FIELDS
  40. hash of the calling package, but this may change in future versions.
  41. Do B<not> update the %FIELDS hash directly, because it must be created
  42. at compile-time for it to be fully useful, as is done by this pragma.
  43. If a typed lexical variable holding a reference is used to access a
  44. hash element and a package with the same name as the type has declared
  45. class fields using this pragma, then the operation is turned into an
  46. array access at compile time.
  47. The related C<base> pragma will combine fields from base classes and any
  48. fields declared using the C<fields> pragma. This enables field
  49. inheritance to work properly.
  50. Field names that start with an underscore character are made private to
  51. the class and are not visible to subclasses. Inherited fields can be
  52. overridden but will generate a warning if used together with the C<-w>
  53. switch.
  54. The effect of all this is that you can have objects with named fields
  55. which are as compact and as fast arrays to access. This only works
  56. as long as the objects are accessed through properly typed variables.
  57. If the objects are not typed, access is only checked at run time.
  58. The following functions are supported:
  59. =over 8
  60. =item new
  61. fields::new() creates and blesses a pseudo-hash comprised of the fields
  62. declared using the C<fields> pragma into the specified class.
  63. This makes it possible to write a constructor like this:
  64. package Critter::Sounds;
  65. use fields qw(cat dog bird);
  66. sub new {
  67. my Critter::Sounds $self = shift;
  68. $self = fields::new($self) unless ref $self;
  69. $self->{cat} = 'meow'; # scalar element
  70. @$self{'dog','bird'} = ('bark','tweet'); # slice
  71. return $self;
  72. }
  73. =item phash
  74. fields::phash() can be used to create and initialize a plain (unblessed)
  75. pseudo-hash. This function should always be used instead of creating
  76. pseudo-hashes directly.
  77. If the first argument is a reference to an array, the pseudo-hash will
  78. be created with keys from that array. If a second argument is supplied,
  79. it must also be a reference to an array whose elements will be used as
  80. the values. If the second array contains less elements than the first,
  81. the trailing elements of the pseudo-hash will not be initialized.
  82. This makes it particularly useful for creating a pseudo-hash from
  83. subroutine arguments:
  84. sub dogtag {
  85. my $tag = fields::phash([qw(name rank ser_num)], [@_]);
  86. }
  87. fields::phash() also accepts a list of key-value pairs that will
  88. be used to construct the pseudo hash. Examples:
  89. my $tag = fields::phash(name => "Joe",
  90. rank => "captain",
  91. ser_num => 42);
  92. my $pseudohash = fields::phash(%args);
  93. =back
  94. =head1 SEE ALSO
  95. L<base>,
  96. L<perlref/Pseudo-hashes: Using an array as a hash>
  97. =cut
  98. use 5.005_64;
  99. use strict;
  100. no strict 'refs';
  101. use warnings::register;
  102. our(%attr, $VERSION);
  103. $VERSION = "1.01";
  104. # some constants
  105. sub _PUBLIC () { 1 }
  106. sub _PRIVATE () { 2 }
  107. # The %attr hash holds the attributes of the currently assigned fields
  108. # per class. The hash is indexed by class names and the hash value is
  109. # an array reference. The first element in the array is the lowest field
  110. # number not belonging to a base class. The remaining elements' indices
  111. # are the field numbers. The values are integer bit masks, or undef
  112. # in the case of base class private fields (which occupy a slot but are
  113. # otherwise irrelevant to the class).
  114. sub import {
  115. my $class = shift;
  116. return unless @_;
  117. my $package = caller(0);
  118. # avoid possible typo warnings
  119. %{"$package\::FIELDS"} = () unless %{"$package\::FIELDS"};
  120. my $fields = \%{"$package\::FIELDS"};
  121. my $fattr = ($attr{$package} ||= [1]);
  122. my $next = @$fattr;
  123. if ($next > $fattr->[0]
  124. and ($fields->{$_[0]} || 0) >= $fattr->[0])
  125. {
  126. # There are already fields not belonging to base classes.
  127. # Looks like a possible module reload...
  128. $next = $fattr->[0];
  129. }
  130. foreach my $f (@_) {
  131. my $fno = $fields->{$f};
  132. # Allow the module to be reloaded so long as field positions
  133. # have not changed.
  134. if ($fno and $fno != $next) {
  135. require Carp;
  136. if ($fno < $fattr->[0]) {
  137. warnings::warnif("Hides field '$f' in base class") ;
  138. } else {
  139. Carp::croak("Field name '$f' already in use");
  140. }
  141. }
  142. $fields->{$f} = $next;
  143. $fattr->[$next] = ($f =~ /^_/) ? _PRIVATE : _PUBLIC;
  144. $next += 1;
  145. }
  146. if (@$fattr > $next) {
  147. # Well, we gave them the benefit of the doubt by guessing the
  148. # module was reloaded, but they appear to be declaring fields
  149. # in more than one place. We can't be sure (without some extra
  150. # bookkeeping) that the rest of the fields will be declared or
  151. # have the same positions, so punt.
  152. require Carp;
  153. Carp::croak ("Reloaded module must declare all fields at once");
  154. }
  155. }
  156. sub inherit { # called by base.pm when $base_fields is nonempty
  157. my($derived, $base) = @_;
  158. my $base_attr = $attr{$base};
  159. my $derived_attr = $attr{$derived} ||= [];
  160. # avoid possible typo warnings
  161. %{"$base\::FIELDS"} = () unless %{"$base\::FIELDS"};
  162. %{"$derived\::FIELDS"} = () unless %{"$derived\::FIELDS"};
  163. my $base_fields = \%{"$base\::FIELDS"};
  164. my $derived_fields = \%{"$derived\::FIELDS"};
  165. $derived_attr->[0] = $base_attr ? scalar(@$base_attr) : 1;
  166. while (my($k,$v) = each %$base_fields) {
  167. my($fno);
  168. if ($fno = $derived_fields->{$k} and $fno != $v) {
  169. require Carp;
  170. Carp::croak ("Inherited %FIELDS can't override existing %FIELDS");
  171. }
  172. if ($base_attr->[$v] & _PRIVATE) {
  173. $derived_attr->[$v] = undef;
  174. } else {
  175. $derived_attr->[$v] = $base_attr->[$v];
  176. $derived_fields->{$k} = $v;
  177. }
  178. }
  179. }
  180. sub _dump # sometimes useful for debugging
  181. {
  182. for my $pkg (sort keys %attr) {
  183. print "\n$pkg";
  184. if (@{"$pkg\::ISA"}) {
  185. print " (", join(", ", @{"$pkg\::ISA"}), ")";
  186. }
  187. print "\n";
  188. my $fields = \%{"$pkg\::FIELDS"};
  189. for my $f (sort {$fields->{$a} <=> $fields->{$b}} keys %$fields) {
  190. my $no = $fields->{$f};
  191. print " $no: $f";
  192. my $fattr = $attr{$pkg}[$no];
  193. if (defined $fattr) {
  194. my @a;
  195. push(@a, "public") if $fattr & _PUBLIC;
  196. push(@a, "private") if $fattr & _PRIVATE;
  197. push(@a, "inherited") if $no < $attr{$pkg}[0];
  198. print "\t(", join(", ", @a), ")";
  199. }
  200. print "\n";
  201. }
  202. }
  203. }
  204. sub new {
  205. my $class = shift;
  206. $class = ref $class if ref $class;
  207. return bless [\%{$class . "::FIELDS"}], $class;
  208. }
  209. sub phash {
  210. my $h;
  211. my $v;
  212. if (@_) {
  213. if (ref $_[0] eq 'ARRAY') {
  214. my $a = shift;
  215. @$h{@$a} = 1 .. @$a;
  216. if (@_) {
  217. $v = shift;
  218. unless (! @_ and ref $v eq 'ARRAY') {
  219. require Carp;
  220. Carp::croak ("Expected at most two array refs\n");
  221. }
  222. }
  223. }
  224. else {
  225. if (@_ % 2) {
  226. require Carp;
  227. Carp::croak ("Odd number of elements initializing pseudo-hash\n");
  228. }
  229. my $i = 0;
  230. @$h{grep ++$i % 2, @_} = 1 .. @_ / 2;
  231. $i = 0;
  232. $v = [grep $i++ % 2, @_];
  233. }
  234. }
  235. else {
  236. $h = {};
  237. $v = [];
  238. }
  239. [ $h, @$v ];
  240. }
  241. 1;