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