Install msysDTK-1.0.1
[msysgit.git] / share / automake-1.7 / Automake / Struct.pm
blob85b07e5a41301c639f811861447e2ddc21cfbe77
1 # autoconf -- create `configure' using m4 macros
2 # Copyright (C) 2001, 2002 Free Software Foundation, Inc.
4 # This program is free software; you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation; either version 2, or (at your option)
7 # any later version.
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
17 # 02111-1307, USA.
19 # This file is basically Perl 5.6's Class::Struct, but made compatible
20 # with Perl 5.5. If someday this has to be updated, be sure to rename
21 # all the occurrences of Class::Struct into Automake::Struct, otherwise
22 # if we `use' a Perl module (e.g., File::stat) that uses Class::Struct,
23 # we would have two packages defining the same symbols. Boom.
25 package Automake::Struct;
27 ## See POD after __END__
29 use 5.005_03;
31 use strict;
32 use vars qw(@ISA @EXPORT $VERSION);
34 use Carp;
36 require Exporter;
37 @ISA = qw(Exporter);
38 @EXPORT = qw(struct);
40 $VERSION = '0.58';
42 ## Tested on 5.002 and 5.003 without class membership tests:
43 my $CHECK_CLASS_MEMBERSHIP = ($] >= 5.003_95);
45 my $print = 0;
46 sub printem {
47 if (@_) { $print = shift }
48 else { $print++ }
52 package Automake::Struct::Tie_ISA;
54 sub TIEARRAY {
55 my $class = shift;
56 return bless [], $class;
59 sub STORE {
60 my ($self, $index, $value) = @_;
61 Automake::Struct::_subclass_error();
64 sub FETCH {
65 my ($self, $index) = @_;
66 $self->[$index];
69 sub FETCHSIZE {
70 my $self = shift;
71 return scalar(@$self);
74 sub DESTROY { }
77 sub struct {
79 # Determine parameter list structure, one of:
80 # struct( class => [ element-list ])
81 # struct( class => { element-list })
82 # struct( element-list )
83 # Latter form assumes current package name as struct name.
85 my ($class, @decls);
86 my $base_type = ref $_[1];
87 if ( $base_type eq 'HASH' ) {
88 $class = shift;
89 @decls = %{shift()};
90 _usage_error() if @_;
92 elsif ( $base_type eq 'ARRAY' ) {
93 $class = shift;
94 @decls = @{shift()};
95 _usage_error() if @_;
97 else {
98 $base_type = 'ARRAY';
99 $class = (caller())[0];
100 @decls = @_;
102 _usage_error() if @decls % 2 == 1;
104 # Ensure we are not, and will not be, a subclass.
106 my $isa = do {
107 no strict 'refs';
108 \@{$class . '::ISA'};
110 _subclass_error() if @$isa;
111 tie @$isa, 'Automake::Struct::Tie_ISA';
113 # Create constructor.
115 croak "function 'new' already defined in package $class"
116 if do { no strict 'refs'; defined &{$class . "::new"} };
118 my @methods = ();
119 my %refs = ();
120 my %arrays = ();
121 my %hashes = ();
122 my %classes = ();
123 my $got_class = 0;
124 my $out = '';
126 $out = "{\n package $class;\n use Carp;\n sub new {\n";
127 $out .= " my (\$class, \%init) = \@_;\n";
128 $out .= " \$class = __PACKAGE__ unless \@_;\n";
130 my $cnt = 0;
131 my $idx = 0;
132 my( $cmt, $name, $type, $elem );
134 if( $base_type eq 'HASH' ){
135 $out .= " my(\$r) = {};\n";
136 $cmt = '';
138 elsif( $base_type eq 'ARRAY' ){
139 $out .= " my(\$r) = [];\n";
141 while( $idx < @decls ){
142 $name = $decls[$idx];
143 $type = $decls[$idx+1];
144 push( @methods, $name );
145 if( $base_type eq 'HASH' ){
146 $elem = "{'${class}::$name'}";
148 elsif( $base_type eq 'ARRAY' ){
149 $elem = "[$cnt]";
150 ++$cnt;
151 $cmt = " # $name";
153 if( $type =~ /^\*(.)/ ){
154 $refs{$name}++;
155 $type = $1;
157 my $init = "defined(\$init{'$name'}) ? \$init{'$name'} :";
158 if( $type eq '@' ){
159 $out .= " croak 'Initializer for $name must be array reference'\n";
160 $out .= " if defined(\$init{'$name'}) && ref(\$init{'$name'}) ne 'ARRAY';\n";
161 $out .= " \$r->$elem = $init [];$cmt\n";
162 $arrays{$name}++;
164 elsif( $type eq '%' ){
165 $out .= " croak 'Initializer for $name must be hash reference'\n";
166 $out .= " if defined(\$init{'$name'}) && ref(\$init{'$name'}) ne 'HASH';\n";
167 $out .= " \$r->$elem = $init {};$cmt\n";
168 $hashes{$name}++;
170 elsif ( $type eq '$') {
171 $out .= " \$r->$elem = $init undef;$cmt\n";
173 elsif( $type =~ /^\w+(?:::\w+)*$/ ){
174 $init = "defined(\$init{'$name'}) ? \%{\$init{'$name'}} : ()";
175 $out .= " croak 'Initializer for $name must be hash reference'\n";
176 $out .= " if defined(\$init{'$name'}) && ref(\$init{'$name'}) ne 'HASH';\n";
177 $out .= " \$r->$elem = '${type}'->new($init);$cmt\n";
178 $classes{$name} = $type;
179 $got_class = 1;
181 else{
182 croak "'$type' is not a valid struct element type";
184 $idx += 2;
186 $out .= " bless \$r, \$class;\n }\n";
188 # Create accessor methods.
190 my( $pre, $pst, $sel );
191 $cnt = 0;
192 foreach $name (@methods){
193 if ( do { no strict 'refs'; defined &{$class . "::$name"} } ) {
194 carp "function '$name' already defined, overrides struct accessor method";
196 else {
197 $pre = $pst = $cmt = $sel = '';
198 if( defined $refs{$name} ){
199 $pre = "\\(";
200 $pst = ")";
201 $cmt = " # returns ref";
203 $out .= " sub $name {$cmt\n my \$r = shift;\n";
204 if( $base_type eq 'ARRAY' ){
205 $elem = "[$cnt]";
206 ++$cnt;
208 elsif( $base_type eq 'HASH' ){
209 $elem = "{'${class}::$name'}";
211 if( defined $arrays{$name} ){
212 $out .= " my \$i;\n";
213 $out .= " \@_ ? (\$i = shift) : return \$r->$elem;\n";
214 $sel = "->[\$i]";
216 elsif( defined $hashes{$name} ){
217 $out .= " my \$i;\n";
218 $out .= " \@_ ? (\$i = shift) : return \$r->$elem;\n";
219 $sel = "->{\$i}";
221 elsif( defined $classes{$name} ){
222 if ( $CHECK_CLASS_MEMBERSHIP ) {
223 $out .= " croak '$name argument is wrong class' if \@_ && ! UNIVERSAL::isa(\$_[0], '$classes{$name}');\n";
226 $out .= " croak 'Too many args to $name' if \@_ > 1;\n";
227 $out .= " \@_ ? ($pre\$r->$elem$sel = shift$pst) : $pre\$r->$elem$sel$pst;\n";
228 $out .= " }\n";
231 $out .= "}\n1;\n";
233 print $out if $print;
234 my $result = eval $out;
235 carp $@ if $@;
238 sub _usage_error {
239 confess "struct usage error";
242 sub _subclass_error {
243 croak 'struct class cannot be a subclass (@ISA not allowed)';
246 1; # for require
249 __END__
251 =head1 NAME
253 Automake::Struct - declare struct-like datatypes as Perl classes
255 =head1 SYNOPSIS
257 use Automake::Struct;
258 # declare struct, based on array:
259 struct( CLASS_NAME => [ ELEMENT_NAME => ELEMENT_TYPE, ... ]);
260 # declare struct, based on hash:
261 struct( CLASS_NAME => { ELEMENT_NAME => ELEMENT_TYPE, ... });
263 package CLASS_NAME;
264 use Automake::Struct;
265 # declare struct, based on array, implicit class name:
266 struct( ELEMENT_NAME => ELEMENT_TYPE, ... );
269 package Myobj;
270 use Automake::Struct;
271 # declare struct with four types of elements:
272 struct( s => '$', a => '@', h => '%', c => 'My_Other_Class' );
274 $obj = new Myobj; # constructor
276 # scalar type accessor:
277 $element_value = $obj->s; # element value
278 $obj->s('new value'); # assign to element
280 # array type accessor:
281 $ary_ref = $obj->a; # reference to whole array
282 $ary_element_value = $obj->a(2); # array element value
283 $obj->a(2, 'new value'); # assign to array element
285 # hash type accessor:
286 $hash_ref = $obj->h; # reference to whole hash
287 $hash_element_value = $obj->h('x'); # hash element value
288 $obj->h('x', 'new value'); # assign to hash element
290 # class type accessor:
291 $element_value = $obj->c; # object reference
292 $obj->c->method(...); # call method of object
293 $obj->c(new My_Other_Class); # assign a new object
296 =head1 DESCRIPTION
298 C<Automake::Struct> exports a single function, C<struct>.
299 Given a list of element names and types, and optionally
300 a class name, C<struct> creates a Perl 5 class that implements
301 a "struct-like" data structure.
303 The new class is given a constructor method, C<new>, for creating
304 struct objects.
306 Each element in the struct data has an accessor method, which is
307 used to assign to the element and to fetch its value. The
308 default accessor can be overridden by declaring a C<sub> of the
309 same name in the package. (See Example 2.)
311 Each element's type can be scalar, array, hash, or class.
314 =head2 The C<struct()> function
316 The C<struct> function has three forms of parameter-list.
318 struct( CLASS_NAME => [ ELEMENT_LIST ]);
319 struct( CLASS_NAME => { ELEMENT_LIST });
320 struct( ELEMENT_LIST );
322 The first and second forms explicitly identify the name of the
323 class being created. The third form assumes the current package
324 name as the class name.
326 An object of a class created by the first and third forms is
327 based on an array, whereas an object of a class created by the
328 second form is based on a hash. The array-based forms will be
329 somewhat faster and smaller; the hash-based forms are more
330 flexible.
332 The class created by C<struct> must not be a subclass of another
333 class other than C<UNIVERSAL>.
335 It can, however, be used as a superclass for other classes. To facilitate
336 this, the generated constructor method uses a two-argument blessing.
337 Furthermore, if the class is hash-based, the key of each element is
338 prefixed with the class name (see I<Perl Cookbook>, Recipe 13.12).
340 A function named C<new> must not be explicitly defined in a class
341 created by C<struct>.
343 The I<ELEMENT_LIST> has the form
345 NAME => TYPE, ...
347 Each name-type pair declares one element of the struct. Each
348 element name will be defined as an accessor method unless a
349 method by that name is explicitly defined; in the latter case, a
350 warning is issued if the warning flag (B<-w>) is set.
353 =head2 Element Types and Accessor Methods
355 The four element types -- scalar, array, hash, and class -- are
356 represented by strings -- C<'$'>, C<'@'>, C<'%'>, and a class name --
357 optionally preceded by a C<'*'>.
359 The accessor method provided by C<struct> for an element depends
360 on the declared type of the element.
362 =over
364 =item Scalar (C<'$'> or C<'*$'>)
366 The element is a scalar, and by default is initialized to C<undef>
367 (but see L<Initializing with new>).
369 The accessor's argument, if any, is assigned to the element.
371 If the element type is C<'$'>, the value of the element (after
372 assignment) is returned. If the element type is C<'*$'>, a reference
373 to the element is returned.
375 =item Array (C<'@'> or C<'*@'>)
377 The element is an array, initialized by default to C<()>.
379 With no argument, the accessor returns a reference to the
380 element's whole array (whether or not the element was
381 specified as C<'@'> or C<'*@'>).
383 With one or two arguments, the first argument is an index
384 specifying one element of the array; the second argument, if
385 present, is assigned to the array element. If the element type
386 is C<'@'>, the accessor returns the array element value. If the
387 element type is C<'*@'>, a reference to the array element is
388 returned.
390 =item Hash (C<'%'> or C<'*%'>)
392 The element is a hash, initialized by default to C<()>.
394 With no argument, the accessor returns a reference to the
395 element's whole hash (whether or not the element was
396 specified as C<'%'> or C<'*%'>).
398 With one or two arguments, the first argument is a key specifying
399 one element of the hash; the second argument, if present, is
400 assigned to the hash element. If the element type is C<'%'>, the
401 accessor returns the hash element value. If the element type is
402 C<'*%'>, a reference to the hash element is returned.
404 =item Class (C<'Class_Name'> or C<'*Class_Name'>)
406 The element's value must be a reference blessed to the named
407 class or to one of its subclasses. The element is initialized to
408 the result of calling the C<new> constructor of the named class.
410 The accessor's argument, if any, is assigned to the element. The
411 accessor will C<croak> if this is not an appropriate object
412 reference.
414 If the element type does not start with a C<'*'>, the accessor
415 returns the element value (after assignment). If the element type
416 starts with a C<'*'>, a reference to the element itself is returned.
418 =back
420 =head2 Initializing with C<new>
422 C<struct> always creates a constructor called C<new>. That constructor
423 may take a list of initializers for the various elements of the new
424 struct.
426 Each initializer is a pair of values: I<element name>C< =E<gt> >I<value>.
427 The initializer value for a scalar element is just a scalar value. The
428 initializer for an array element is an array reference. The initializer
429 for a hash is a hash reference.
431 The initializer for a class element is also a hash reference, and the
432 contents of that hash are passed to the element's own constructor.
434 See Example 3 below for an example of initialization.
437 =head1 EXAMPLES
439 =over
441 =item Example 1
443 Giving a struct element a class type that is also a struct is how
444 structs are nested. Here, C<timeval> represents a time (seconds and
445 microseconds), and C<rusage> has two elements, each of which is of
446 type C<timeval>.
448 use Automake::Struct;
450 struct( rusage => {
451 ru_utime => timeval, # seconds
452 ru_stime => timeval, # microseconds
455 struct( timeval => [
456 tv_secs => '$',
457 tv_usecs => '$',
460 # create an object:
461 my $t = new rusage;
463 # $t->ru_utime and $t->ru_stime are objects of type timeval.
464 # set $t->ru_utime to 100.0 sec and $t->ru_stime to 5.0 sec.
465 $t->ru_utime->tv_secs(100);
466 $t->ru_utime->tv_usecs(0);
467 $t->ru_stime->tv_secs(5);
468 $t->ru_stime->tv_usecs(0);
471 =item Example 2
473 An accessor function can be redefined in order to provide
474 additional checking of values, etc. Here, we want the C<count>
475 element always to be nonnegative, so we redefine the C<count>
476 accessor accordingly.
478 package MyObj;
479 use Automake::Struct;
481 # declare the struct
482 struct ( 'MyObj', { count => '$', stuff => '%' } );
484 # override the default accessor method for 'count'
485 sub count {
486 my $self = shift;
487 if ( @_ ) {
488 die 'count must be nonnegative' if $_[0] < 0;
489 $self->{'count'} = shift;
490 warn "Too many args to count" if @_;
492 return $self->{'count'};
495 package main;
496 $x = new MyObj;
497 print "\$x->count(5) = ", $x->count(5), "\n";
498 # prints '$x->count(5) = 5'
500 print "\$x->count = ", $x->count, "\n";
501 # prints '$x->count = 5'
503 print "\$x->count(-5) = ", $x->count(-5), "\n";
504 # dies due to negative argument!
506 =item Example 3
508 The constructor of a generated class can be passed a list
509 of I<element>=>I<value> pairs, with which to initialize the struct.
510 If no initializer is specified for a particular element, its default
511 initialization is performed instead. Initializers for non-existent
512 elements are silently ignored.
514 Note that the initializer for a nested struct is specified
515 as an anonymous hash of initializers, which is passed on to the nested
516 struct's constructor.
519 use Automake::Struct;
521 struct Breed =>
523 name => '$',
524 cross => '$',
527 struct Cat =>
529 name => '$',
530 kittens => '@',
531 markings => '%',
532 breed => 'Breed',
536 my $cat = Cat->new( name => 'Socks',
537 kittens => ['Monica', 'Kenneth'],
538 markings => { socks=>1, blaze=>"white" },
539 breed => { name=>'short-hair', cross=>1 },
542 print "Once a cat called ", $cat->name, "\n";
543 print "(which was a ", $cat->breed->name, ")\n";
544 print "had two kittens: ", join(' and ', @{$cat->kittens}), "\n";
546 =back
548 =head1 Author and Modification History
550 Modified by Akim Demaille, 2001-08-03
552 Rename as Automake::Struct to avoid name clashes with
553 Class::Struct.
555 Make it compatible with Perl 5.5.
557 Modified by Damian Conway, 1999-03-05, v0.58.
559 Added handling of hash-like arg list to class ctor.
561 Changed to two-argument blessing in ctor to support
562 derivation from created classes.
564 Added classname prefixes to keys in hash-based classes
565 (refer to "Perl Cookbook", Recipe 13.12 for rationale).
567 Corrected behavior of accessors for '*@' and '*%' struct
568 elements. Package now implements documented behavior when
569 returning a reference to an entire hash or array element.
570 Previously these were returned as a reference to a reference
571 to the element.
574 Renamed to C<Class::Struct> and modified by Jim Miner, 1997-04-02.
576 members() function removed.
577 Documentation corrected and extended.
578 Use of struct() in a subclass prohibited.
579 User definition of accessor allowed.
580 Treatment of '*' in element types corrected.
581 Treatment of classes as element types corrected.
582 Class name to struct() made optional.
583 Diagnostic checks added.
586 Originally C<Class::Template> by Dean Roehrich.
588 # Template.pm --- struct/member template builder
589 # 12mar95
590 # Dean Roehrich
592 # changes/bugs fixed since 28nov94 version:
593 # - podified
594 # changes/bugs fixed since 21nov94 version:
595 # - Fixed examples.
596 # changes/bugs fixed since 02sep94 version:
597 # - Moved to Class::Template.
598 # changes/bugs fixed since 20feb94 version:
599 # - Updated to be a more proper module.
600 # - Added "use strict".
601 # - Bug in build_methods, was using @var when @$var needed.
602 # - Now using my() rather than local().
604 # Uses perl5 classes to create nested data types.
605 # This is offered as one implementation of Tom Christiansen's "structs.pl"
606 # idea.
608 =cut
610 ### Setup "GNU" style for perl-mode and cperl-mode.
611 ## Local Variables:
612 ## perl-indent-level: 2
613 ## perl-continued-statement-offset: 2
614 ## perl-continued-brace-offset: 0
615 ## perl-brace-offset: 0
616 ## perl-brace-imaginary-offset: 0
617 ## perl-label-offset: -2
618 ## cperl-indent-level: 2
619 ## cperl-brace-offset: 0
620 ## cperl-continued-brace-offset: 0
621 ## cperl-label-offset: -2
622 ## cperl-extra-newline-before-brace: t
623 ## cperl-merge-trailing-else: nil
624 ## cperl-continued-statement-offset: 2
625 ## End: