xref: /openbsd-src/gnu/usr.bin/perl/lib/Class/Struct.pm (revision 5ad04d351680822078003e2b066cfc9680d6157d)
1package Class::Struct;
2
3## See POD after __END__
4
5use 5.006_001;
6
7use strict;
8use warnings::register;
9our(@ISA, @EXPORT, $VERSION);
10
11use Carp;
12
13require Exporter;
14@ISA = qw(Exporter);
15@EXPORT = qw(struct);
16
17$VERSION = '0.64';
18
19my $print = 0;
20sub printem {
21    if (@_) { $print = shift }
22    else    { $print++ }
23}
24
25{
26    package Class::Struct::Tie_ISA;
27
28    sub TIEARRAY {
29        my $class = shift;
30        return bless [], $class;
31    }
32
33    sub STORE {
34        my ($self, $index, $value) = @_;
35        Class::Struct::_subclass_error();
36    }
37
38    sub FETCH {
39        my ($self, $index) = @_;
40        $self->[$index];
41    }
42
43    sub FETCHSIZE {
44        my $self = shift;
45        return scalar(@$self);
46    }
47
48    sub DESTROY { }
49}
50
51sub import {
52    my $self = shift;
53
54    if ( @_ == 0 ) {
55      $self->export_to_level( 1, $self, @EXPORT );
56    } elsif ( @_ == 1 ) {
57	# This is admittedly a little bit silly:
58	# do we ever export anything else than 'struct'...?
59      $self->export_to_level( 1, $self, @_ );
60    } else {
61      goto &struct;
62    }
63}
64
65sub struct {
66
67    # Determine parameter list structure, one of:
68    #   struct( class => [ element-list ])
69    #   struct( class => { element-list })
70    #   struct( element-list )
71    # Latter form assumes current package name as struct name.
72
73    my ($class, @decls);
74    my $base_type = ref $_[1];
75    if ( $base_type eq 'HASH' ) {
76        $class = shift;
77        @decls = %{shift()};
78        _usage_error() if @_;
79    }
80    elsif ( $base_type eq 'ARRAY' ) {
81        $class = shift;
82        @decls = @{shift()};
83        _usage_error() if @_;
84    }
85    else {
86        $base_type = 'ARRAY';
87        $class = (caller())[0];
88        @decls = @_;
89    }
90
91    _usage_error() if @decls % 2 == 1;
92
93    # Ensure we are not, and will not be, a subclass.
94
95    my $isa = do {
96        no strict 'refs';
97        \@{$class . '::ISA'};
98    };
99    _subclass_error() if @$isa;
100    tie @$isa, 'Class::Struct::Tie_ISA';
101
102    # Create constructor.
103
104    croak "function 'new' already defined in package $class"
105        if do { no strict 'refs'; defined &{$class . "::new"} };
106
107    my @methods = ();
108    my %refs = ();
109    my %arrays = ();
110    my %hashes = ();
111    my %classes = ();
112    my $got_class = 0;
113    my $out = '';
114
115    $out = "{\n  package $class;\n  use Carp;\n  sub new {\n";
116    $out .= "    my (\$class, \%init) = \@_;\n";
117    $out .= "    \$class = __PACKAGE__ unless \@_;\n";
118
119    my $cnt = 0;
120    my $idx = 0;
121    my( $cmt, $name, $type, $elem );
122
123    if( $base_type eq 'HASH' ){
124        $out .= "    my(\$r) = {};\n";
125        $cmt = '';
126    }
127    elsif( $base_type eq 'ARRAY' ){
128        $out .= "    my(\$r) = [];\n";
129    }
130
131    $out .= " bless \$r, \$class;\n\n";
132
133    while( $idx < @decls ){
134        $name = $decls[$idx];
135        $type = $decls[$idx+1];
136        push( @methods, $name );
137        if( $base_type eq 'HASH' ){
138            $elem = "{'${class}::$name'}";
139        }
140        elsif( $base_type eq 'ARRAY' ){
141            $elem = "[$cnt]";
142            ++$cnt;
143            $cmt = " # $name";
144        }
145        if( $type =~ /^\*(.)/ ){
146            $refs{$name}++;
147            $type = $1;
148        }
149        my $init = "defined(\$init{'$name'}) ? \$init{'$name'} :";
150        if( $type eq '@' ){
151            $out .= "    croak 'Initializer for $name must be array reference'\n";
152            $out .= "        if defined(\$init{'$name'}) && ref(\$init{'$name'}) ne 'ARRAY';\n";
153            $out .= "    \$r->$name( $init [] );$cmt\n";
154            $arrays{$name}++;
155        }
156        elsif( $type eq '%' ){
157            $out .= "    croak 'Initializer for $name must be hash reference'\n";
158            $out .= "        if defined(\$init{'$name'}) && ref(\$init{'$name'}) ne 'HASH';\n";
159            $out .= "    \$r->$name( $init {} );$cmt\n";
160            $hashes{$name}++;
161        }
162        elsif ( $type eq '$') {
163            $out .= "    \$r->$name( $init undef );$cmt\n";
164        }
165        elsif( $type =~ /^\w+(?:::\w+)*$/ ){
166            $out .= "    if (defined(\$init{'$name'})) {\n";
167           $out .= "       if (ref \$init{'$name'} eq 'HASH')\n";
168            $out .= "            { \$r->$name( $type->new(\%{\$init{'$name'}}) ) } $cmt\n";
169           $out .= "       elsif (UNIVERSAL::isa(\$init{'$name'}, '$type'))\n";
170            $out .= "            { \$r->$name( \$init{'$name'} ) } $cmt\n";
171            $out .= "       else { croak 'Initializer for $name must be hash or $type reference' }\n";
172            $out .= "    }\n";
173            $classes{$name} = $type;
174            $got_class = 1;
175        }
176        else{
177            croak "'$type' is not a valid struct element type";
178        }
179        $idx += 2;
180    }
181
182    $out .= "\n \$r;\n}\n";
183
184    # Create accessor methods.
185
186    my( $pre, $pst, $sel );
187    $cnt = 0;
188    foreach $name (@methods){
189        if ( do { no strict 'refs'; defined &{$class . "::$name"} } ) {
190            warnings::warnif("function '$name' already defined, overrides struct accessor method");
191        }
192        else {
193            $pre = $pst = $cmt = $sel = '';
194            if( defined $refs{$name} ){
195                $pre = "\\(";
196                $pst = ")";
197                $cmt = " # returns ref";
198            }
199            $out .= "  sub $name {$cmt\n    my \$r = shift;\n";
200            if( $base_type eq 'ARRAY' ){
201                $elem = "[$cnt]";
202                ++$cnt;
203            }
204            elsif( $base_type eq 'HASH' ){
205                $elem = "{'${class}::$name'}";
206            }
207            if( defined $arrays{$name} ){
208                $out .= "    my \$i;\n";
209                $out .= "    \@_ ? (\$i = shift) : return \$r->$elem;\n";
210                $out .= "    if (ref(\$i) eq 'ARRAY' && !\@_) { \$r->$elem = \$i; return \$r }\n";
211                $sel = "->[\$i]";
212            }
213            elsif( defined $hashes{$name} ){
214                $out .= "    my \$i;\n";
215                $out .= "    \@_ ? (\$i = shift) : return \$r->$elem;\n";
216                $out .= "    if (ref(\$i) eq 'HASH' && !\@_) { \$r->$elem = \$i; return \$r }\n";
217                $sel = "->{\$i}";
218            }
219            elsif( defined $classes{$name} ){
220                $out .= "    croak '$name argument is wrong class' if \@_ && ! UNIVERSAL::isa(\$_[0], '$classes{$name}');\n";
221            }
222            $out .= "    croak 'Too many args to $name' if \@_ > 1;\n";
223            $out .= "    \@_ ? ($pre\$r->$elem$sel = shift$pst) : $pre\$r->$elem$sel$pst;\n";
224            $out .= "  }\n";
225        }
226    }
227    $out .= "}\n1;\n";
228
229    print $out if $print;
230    my $result = eval $out;
231    carp $@ if $@;
232}
233
234sub _usage_error {
235    confess "struct usage error";
236}
237
238sub _subclass_error {
239    croak 'struct class cannot be a subclass (@ISA not allowed)';
240}
241
2421; # for require
243
244
245__END__
246
247=head1 NAME
248
249Class::Struct - declare struct-like datatypes as Perl classes
250
251=head1 SYNOPSIS
252
253    use Class::Struct;
254            # declare struct, based on array:
255    struct( CLASS_NAME => [ ELEMENT_NAME => ELEMENT_TYPE, ... ]);
256            # declare struct, based on hash:
257    struct( CLASS_NAME => { ELEMENT_NAME => ELEMENT_TYPE, ... });
258
259    package CLASS_NAME;
260    use Class::Struct;
261            # declare struct, based on array, implicit class name:
262    struct( ELEMENT_NAME => ELEMENT_TYPE, ... );
263
264    # Declare struct at compile time
265    use Class::Struct CLASS_NAME => [ ELEMENT_NAME => ELEMENT_TYPE, ... ];
266    use Class::Struct CLASS_NAME => { ELEMENT_NAME => ELEMENT_TYPE, ... };
267
268    # declare struct at compile time, based on array, implicit class name:
269    package CLASS_NAME;
270    use Class::Struct ELEMENT_NAME => ELEMENT_TYPE, ... ;
271
272    package Myobj;
273    use Class::Struct;
274            # declare struct with four types of elements:
275    struct( s => '$', a => '@', h => '%', c => 'My_Other_Class' );
276
277    $obj = new Myobj;               # constructor
278
279                                    # scalar type accessor:
280    $element_value = $obj->s;           # element value
281    $obj->s('new value');               # assign to element
282
283                                    # array type accessor:
284    $ary_ref = $obj->a;                 # reference to whole array
285    $ary_element_value = $obj->a(2);    # array element value
286    $obj->a(2, 'new value');            # assign to array element
287
288                                    # hash type accessor:
289    $hash_ref = $obj->h;                # reference to whole hash
290    $hash_element_value = $obj->h('x'); # hash element value
291    $obj->h('x', 'new value');          # assign to hash element
292
293                                    # class type accessor:
294    $element_value = $obj->c;           # object reference
295    $obj->c->method(...);               # call method of object
296    $obj->c(new My_Other_Class);        # assign a new object
297
298=head1 DESCRIPTION
299
300C<Class::Struct> exports a single function, C<struct>.
301Given a list of element names and types, and optionally
302a class name, C<struct> creates a Perl 5 class that implements
303a "struct-like" data structure.
304
305The new class is given a constructor method, C<new>, for creating
306struct objects.
307
308Each element in the struct data has an accessor method, which is
309used to assign to the element and to fetch its value.  The
310default accessor can be overridden by declaring a C<sub> of the
311same name in the package.  (See Example 2.)
312
313Each element's type can be scalar, array, hash, or class.
314
315=head2 The C<struct()> function
316
317The C<struct> function has three forms of parameter-list.
318
319    struct( CLASS_NAME => [ ELEMENT_LIST ]);
320    struct( CLASS_NAME => { ELEMENT_LIST });
321    struct( ELEMENT_LIST );
322
323The first and second forms explicitly identify the name of the
324class being created.  The third form assumes the current package
325name as the class name.
326
327An object of a class created by the first and third forms is
328based on an array, whereas an object of a class created by the
329second form is based on a hash. The array-based forms will be
330somewhat faster and smaller; the hash-based forms are more
331flexible.
332
333The class created by C<struct> must not be a subclass of another
334class other than C<UNIVERSAL>.
335
336It can, however, be used as a superclass for other classes. To facilitate
337this, the generated constructor method uses a two-argument blessing.
338Furthermore, if the class is hash-based, the key of each element is
339prefixed with the class name (see I<Perl Cookbook>, Recipe 13.12).
340
341A function named C<new> must not be explicitly defined in a class
342created by C<struct>.
343
344The I<ELEMENT_LIST> has the form
345
346    NAME => TYPE, ...
347
348Each name-type pair declares one element of the struct. Each
349element name will be defined as an accessor method unless a
350method by that name is explicitly defined; in the latter case, a
351warning is issued if the warning flag (B<-w>) is set.
352
353=head2 Class Creation at Compile Time
354
355C<Class::Struct> can create your class at compile time.  The main reason
356for doing this is obvious, so your class acts like every other class in
357Perl.  Creating your class at compile time will make the order of events
358similar to using any other class ( or Perl module ).
359
360There is no significant speed gain between compile time and run time
361class creation, there is just a new, more standard order of events.
362
363=head2 Element Types and Accessor Methods
364
365The four element types -- scalar, array, hash, and class -- are
366represented by strings -- C<'$'>, C<'@'>, C<'%'>, and a class name --
367optionally preceded by a C<'*'>.
368
369The accessor method provided by C<struct> for an element depends
370on the declared type of the element.
371
372=over 4
373
374=item Scalar (C<'$'> or C<'*$'>)
375
376The element is a scalar, and by default is initialized to C<undef>
377(but see L<Initializing with new>).
378
379The accessor's argument, if any, is assigned to the element.
380
381If the element type is C<'$'>, the value of the element (after
382assignment) is returned. If the element type is C<'*$'>, a reference
383to the element is returned.
384
385=item Array (C<'@'> or C<'*@'>)
386
387The element is an array, initialized by default to C<()>.
388
389With no argument, the accessor returns a reference to the
390element's whole array (whether or not the element was
391specified as C<'@'> or C<'*@'>).
392
393With one or two arguments, the first argument is an index
394specifying one element of the array; the second argument, if
395present, is assigned to the array element.  If the element type
396is C<'@'>, the accessor returns the array element value.  If the
397element type is C<'*@'>, a reference to the array element is
398returned.
399
400As a special case, when the accessor is called with an array reference
401as the sole argument, this causes an assignment of the whole array element.
402The object reference is returned.
403
404=item Hash (C<'%'> or C<'*%'>)
405
406The element is a hash, initialized by default to C<()>.
407
408With no argument, the accessor returns a reference to the
409element's whole hash (whether or not the element was
410specified as C<'%'> or C<'*%'>).
411
412With one or two arguments, the first argument is a key specifying
413one element of the hash; the second argument, if present, is
414assigned to the hash element.  If the element type is C<'%'>, the
415accessor returns the hash element value.  If the element type is
416C<'*%'>, a reference to the hash element is returned.
417
418As a special case, when the accessor is called with a hash reference
419as the sole argument, this causes an assignment of the whole hash element.
420The object reference is returned.
421
422=item Class (C<'Class_Name'> or C<'*Class_Name'>)
423
424The element's value must be a reference blessed to the named
425class or to one of its subclasses. The element is not initialized
426by default.
427
428The accessor's argument, if any, is assigned to the element. The
429accessor will C<croak> if this is not an appropriate object
430reference.
431
432If the element type does not start with a C<'*'>, the accessor
433returns the element value (after assignment). If the element type
434starts with a C<'*'>, a reference to the element itself is returned.
435
436=back
437
438=head2 Initializing with C<new>
439
440C<struct> always creates a constructor called C<new>. That constructor
441may take a list of initializers for the various elements of the new
442struct.
443
444Each initializer is a pair of values: I<element name>C< =E<gt> >I<value>.
445The initializer value for a scalar element is just a scalar value. The
446initializer for an array element is an array reference. The initializer
447for a hash is a hash reference.
448
449The initializer for a class element is an object of the corresponding class,
450or of one of it's subclasses, or a reference to a hash containing named
451arguments to be passed to the element's constructor.
452
453See Example 3 below for an example of initialization.
454
455=head1 EXAMPLES
456
457=over 4
458
459=item Example 1
460
461Giving a struct element a class type that is also a struct is how
462structs are nested.  Here, C<Timeval> represents a time (seconds and
463microseconds), and C<Rusage> has two elements, each of which is of
464type C<Timeval>.
465
466    use Class::Struct;
467
468    struct( Rusage => {
469        ru_utime => 'Timeval',  # user time used
470        ru_stime => 'Timeval',  # system time used
471    });
472
473    struct( Timeval => [
474        tv_secs  => '$',        # seconds
475        tv_usecs => '$',        # microseconds
476    ]);
477
478        # create an object:
479    my $t = Rusage->new(ru_utime=>Timeval->new(), ru_stime=>Timeval->new());
480
481        # $t->ru_utime and $t->ru_stime are objects of type Timeval.
482        # set $t->ru_utime to 100.0 sec and $t->ru_stime to 5.0 sec.
483    $t->ru_utime->tv_secs(100);
484    $t->ru_utime->tv_usecs(0);
485    $t->ru_stime->tv_secs(5);
486    $t->ru_stime->tv_usecs(0);
487
488=item Example 2
489
490An accessor function can be redefined in order to provide
491additional checking of values, etc.  Here, we want the C<count>
492element always to be nonnegative, so we redefine the C<count>
493accessor accordingly.
494
495    package MyObj;
496    use Class::Struct;
497
498    # declare the struct
499    struct ( 'MyObj', { count => '$', stuff => '%' } );
500
501    # override the default accessor method for 'count'
502    sub count {
503        my $self = shift;
504        if ( @_ ) {
505            die 'count must be nonnegative' if $_[0] < 0;
506            $self->{'MyObj::count'} = shift;
507            warn "Too many args to count" if @_;
508        }
509        return $self->{'MyObj::count'};
510    }
511
512    package main;
513    $x = new MyObj;
514    print "\$x->count(5) = ", $x->count(5), "\n";
515                            # prints '$x->count(5) = 5'
516
517    print "\$x->count = ", $x->count, "\n";
518                            # prints '$x->count = 5'
519
520    print "\$x->count(-5) = ", $x->count(-5), "\n";
521                            # dies due to negative argument!
522
523=item Example 3
524
525The constructor of a generated class can be passed a list
526of I<element>=>I<value> pairs, with which to initialize the struct.
527If no initializer is specified for a particular element, its default
528initialization is performed instead. Initializers for non-existent
529elements are silently ignored.
530
531Note that the initializer for a nested class may be specified as
532an object of that class, or as a reference to a hash of initializers
533that are passed on to the nested struct's constructor.
534
535    use Class::Struct;
536
537    struct Breed =>
538    {
539        name  => '$',
540        cross => '$',
541    };
542
543    struct Cat =>
544    [
545        name     => '$',
546        kittens  => '@',
547        markings => '%',
548        breed    => 'Breed',
549    ];
550
551
552    my $cat = Cat->new( name     => 'Socks',
553                        kittens  => ['Monica', 'Kenneth'],
554                        markings => { socks=>1, blaze=>"white" },
555                        breed    => Breed->new(name=>'short-hair', cross=>1),
556                   or:  breed    => {name=>'short-hair', cross=>1},
557                      );
558
559    print "Once a cat called ", $cat->name, "\n";
560    print "(which was a ", $cat->breed->name, ")\n";
561    print "had two kittens: ", join(' and ', @{$cat->kittens}), "\n";
562
563=back
564
565=head1 Author and Modification History
566
567Modified by Damian Conway, 2001-09-10, v0.62.
568
569   Modified implicit construction of nested objects.
570   Now will also take an object ref instead of requiring a hash ref.
571   Also default initializes nested object attributes to undef, rather
572   than calling object constructor without args
573   Original over-helpfulness was fraught with problems:
574       * the class's constructor might not be called 'new'
575       * the class might not have a hash-like-arguments constructor
576       * the class might not have a no-argument constructor
577       * "recursive" data structures didn't work well:
578                 package Person;
579                 struct { mother => 'Person', father => 'Person'};
580
581
582Modified by Casey West, 2000-11-08, v0.59.
583
584    Added the ability for compile time class creation.
585
586Modified by Damian Conway, 1999-03-05, v0.58.
587
588    Added handling of hash-like arg list to class ctor.
589
590    Changed to two-argument blessing in ctor to support
591    derivation from created classes.
592
593    Added classname prefixes to keys in hash-based classes
594    (refer to "Perl Cookbook", Recipe 13.12 for rationale).
595
596    Corrected behaviour of accessors for '*@' and '*%' struct
597    elements.  Package now implements documented behaviour when
598    returning a reference to an entire hash or array element.
599    Previously these were returned as a reference to a reference
600    to the element.
601
602Renamed to C<Class::Struct> and modified by Jim Miner, 1997-04-02.
603
604    members() function removed.
605    Documentation corrected and extended.
606    Use of struct() in a subclass prohibited.
607    User definition of accessor allowed.
608    Treatment of '*' in element types corrected.
609    Treatment of classes as element types corrected.
610    Class name to struct() made optional.
611    Diagnostic checks added.
612
613Originally C<Class::Template> by Dean Roehrich.
614
615    # Template.pm   --- struct/member template builder
616    #   12mar95
617    #   Dean Roehrich
618    #
619    # changes/bugs fixed since 28nov94 version:
620    #  - podified
621    # changes/bugs fixed since 21nov94 version:
622    #  - Fixed examples.
623    # changes/bugs fixed since 02sep94 version:
624    #  - Moved to Class::Template.
625    # changes/bugs fixed since 20feb94 version:
626    #  - Updated to be a more proper module.
627    #  - Added "use strict".
628    #  - Bug in build_methods, was using @var when @$var needed.
629    #  - Now using my() rather than local().
630    #
631    # Uses perl5 classes to create nested data types.
632    # This is offered as one implementation of Tom Christiansen's "structs.pl"
633    # idea.
634
635=cut
636