source: trunk/third/perl/lib/fields.pm @ 14545

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