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