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