fortran: clean up core files after AC_FC_CHECK_BOUNDS
[autoconf.git] / lib / Autom4te / Struct.pm
blobd58b6754840f26bc80b056e6b470fc8e42e4836e
1 # Copyright (C) 2001-2012 Free Software Foundation, Inc.
3 # This program is free software; you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation; either version 2, or (at your option)
6 # any later version.
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
13 # You should have received a copy of the GNU General Public License
14 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 # This file is basically Perl 5.6's Class::Struct, but made compatible
17 # with Perl 5.5. If someday this has to be updated, be sure to rename
18 # all the occurrences of Class::Struct into Autom4te::Struct, otherwise
19 # if we 'use' a Perl module (e.g., File::stat) that uses Class::Struct,
20 # we would have two packages defining the same symbols. Boom.
22 ###############################################################
23 # The main copy of this file is in Automake's git repository. #
24 # Updates should be sent to automake-patches@gnu.org. #
25 ###############################################################
27 package Autom4te::Struct;
29 ## See POD after __END__
31 use 5.005_03;
33 use strict;
34 use vars qw(@ISA @EXPORT $VERSION);
36 use Carp;
38 require Exporter;
39 @ISA = qw(Exporter);
40 @EXPORT = qw(struct);
42 $VERSION = '0.58';
44 ## Tested on 5.002 and 5.003 without class membership tests:
45 my $CHECK_CLASS_MEMBERSHIP = ($] >= 5.003_95);
47 my $print = 0;
48 sub printem {
49 if (@_) { $print = shift }
50 else { $print++ }
54 package Autom4te::Struct::Tie_ISA;
56 sub TIEARRAY {
57 my $class = shift;
58 return bless [], $class;
61 sub STORE {
62 my ($self, $index, $value) = @_;
63 Autom4te::Struct::_subclass_error();
66 sub FETCH {
67 my ($self, $index) = @_;
68 $self->[$index];
71 sub FETCHSIZE {
72 my $self = shift;
73 return scalar(@$self);
76 sub DESTROY { }
79 sub struct {
81 # Determine parameter list structure, one of:
82 # struct( class => [ element-list ])
83 # struct( class => { element-list })
84 # struct( element-list )
85 # Latter form assumes current package name as struct name.
87 my ($class, @decls);
88 my $base_type = ref $_[1];
89 if ( $base_type eq 'HASH' ) {
90 $class = shift;
91 @decls = %{shift()};
92 _usage_error() if @_;
94 elsif ( $base_type eq 'ARRAY' ) {
95 $class = shift;
96 @decls = @{shift()};
97 _usage_error() if @_;
99 else {
100 $base_type = 'ARRAY';
101 $class = (caller())[0];
102 @decls = @_;
104 _usage_error() if @decls % 2 == 1;
106 # Ensure we are not, and will not be, a subclass.
108 my $isa = do {
109 no strict 'refs';
110 \@{$class . '::ISA'};
112 _subclass_error() if @$isa;
113 tie @$isa, 'Autom4te::Struct::Tie_ISA';
115 # Create constructor.
117 croak "function 'new' already defined in package $class"
118 if do { no strict 'refs'; defined &{$class . "::new"} };
120 my @methods = ();
121 my %refs = ();
122 my %arrays = ();
123 my %hashes = ();
124 my %classes = ();
125 my $got_class = 0;
126 my $out = '';
128 $out = "{\n package $class;\n use Carp;\n sub new {\n";
129 $out .= " my (\$class, \%init) = \@_;\n";
130 $out .= " \$class = __PACKAGE__ unless \@_;\n";
132 my $cnt = 0;
133 my $idx = 0;
134 my( $cmt, $name, $type, $elem );
136 if( $base_type eq 'HASH' ){
137 $out .= " my(\$r) = {};\n";
138 $cmt = '';
140 elsif( $base_type eq 'ARRAY' ){
141 $out .= " my(\$r) = [];\n";
143 while( $idx < @decls ){
144 $name = $decls[$idx];
145 $type = $decls[$idx+1];
146 push( @methods, $name );
147 if( $base_type eq 'HASH' ){
148 $elem = "{'${class}::$name'}";
150 elsif( $base_type eq 'ARRAY' ){
151 $elem = "[$cnt]";
152 ++$cnt;
153 $cmt = " # $name";
155 if( $type =~ /^\*(.)/ ){
156 $refs{$name}++;
157 $type = $1;
159 my $init = "defined(\$init{'$name'}) ? \$init{'$name'} :";
160 if( $type eq '@' ){
161 $out .= " croak 'Initializer for $name must be array reference'\n";
162 $out .= " if defined(\$init{'$name'}) && ref(\$init{'$name'}) ne 'ARRAY';\n";
163 $out .= " \$r->$elem = $init [];$cmt\n";
164 $arrays{$name}++;
166 elsif( $type eq '%' ){
167 $out .= " croak 'Initializer for $name must be hash reference'\n";
168 $out .= " if defined(\$init{'$name'}) && ref(\$init{'$name'}) ne 'HASH';\n";
169 $out .= " \$r->$elem = $init {};$cmt\n";
170 $hashes{$name}++;
172 elsif ( $type eq '$') {
173 $out .= " \$r->$elem = $init undef;$cmt\n";
175 elsif( $type =~ /^\w+(?:::\w+)*$/ ){
176 $init = "defined(\$init{'$name'}) ? \%{\$init{'$name'}} : ()";
177 $out .= " croak 'Initializer for $name must be hash reference'\n";
178 $out .= " if defined(\$init{'$name'}) && ref(\$init{'$name'}) ne 'HASH';\n";
179 $out .= " \$r->$elem = '${type}'->new($init);$cmt\n";
180 $classes{$name} = $type;
181 $got_class = 1;
183 else{
184 croak "'$type' is not a valid struct element type";
186 $idx += 2;
188 $out .= " bless \$r, \$class;\n }\n";
190 # Create accessor methods.
192 my( $pre, $pst, $sel );
193 $cnt = 0;
194 foreach $name (@methods){
195 if ( do { no strict 'refs'; defined &{$class . "::$name"} } ) {
196 carp "function '$name' already defined, overrides struct accessor method";
198 else {
199 $pre = $pst = $cmt = $sel = '';
200 if( defined $refs{$name} ){
201 $pre = "\\(";
202 $pst = ")";
203 $cmt = " # returns ref";
205 $out .= " sub $name {$cmt\n my \$r = shift;\n";
206 if( $base_type eq 'ARRAY' ){
207 $elem = "[$cnt]";
208 ++$cnt;
210 elsif( $base_type eq 'HASH' ){
211 $elem = "{'${class}::$name'}";
213 if( defined $arrays{$name} ){
214 $out .= " my \$i;\n";
215 $out .= " \@_ ? (\$i = shift) : return \$r->$elem;\n";
216 $sel = "->[\$i]";
218 elsif( defined $hashes{$name} ){
219 $out .= " my \$i;\n";
220 $out .= " \@_ ? (\$i = shift) : return \$r->$elem;\n";
221 $sel = "->{\$i}";
223 elsif( defined $classes{$name} ){
224 if ( $CHECK_CLASS_MEMBERSHIP ) {
225 $out .= " croak '$name argument is wrong class' if \@_ && ! UNIVERSAL::isa(\$_[0], '$classes{$name}');\n";
228 $out .= " croak 'Too many args to $name' if \@_ > 1;\n";
229 $out .= " \@_ ? ($pre\$r->$elem$sel = shift$pst) : $pre\$r->$elem$sel$pst;\n";
230 $out .= " }\n";
233 $out .= "}\n1;\n";
235 print $out if $print;
236 my $result = eval $out;
237 carp $@ if $@;
240 sub _usage_error {
241 confess "struct usage error";
244 sub _subclass_error {
245 croak 'struct class cannot be a subclass (@ISA not allowed)';
248 1; # for require
251 __END__
253 =head1 NAME
255 Autom4te::Struct - declare struct-like datatypes as Perl classes
257 =head1 SYNOPSIS
259 use Autom4te::Struct;
260 # declare struct, based on array:
261 struct( CLASS_NAME => [ ELEMENT_NAME => ELEMENT_TYPE, ... ]);
262 # declare struct, based on hash:
263 struct( CLASS_NAME => { ELEMENT_NAME => ELEMENT_TYPE, ... });
265 package CLASS_NAME;
266 use Autom4te::Struct;
267 # declare struct, based on array, implicit class name:
268 struct( ELEMENT_NAME => ELEMENT_TYPE, ... );
271 package Myobj;
272 use Autom4te::Struct;
273 # declare struct with four types of elements:
274 struct( s => '$', a => '@', h => '%', c => 'My_Other_Class' );
276 $obj = new Myobj; # constructor
278 # scalar type accessor:
279 $element_value = $obj->s; # element value
280 $obj->s('new value'); # assign to element
282 # array type accessor:
283 $ary_ref = $obj->a; # reference to whole array
284 $ary_element_value = $obj->a(2); # array element value
285 $obj->a(2, 'new value'); # assign to array element
287 # hash type accessor:
288 $hash_ref = $obj->h; # reference to whole hash
289 $hash_element_value = $obj->h('x'); # hash element value
290 $obj->h('x', 'new value'); # assign to hash element
292 # class type accessor:
293 $element_value = $obj->c; # object reference
294 $obj->c->method(...); # call method of object
295 $obj->c(new My_Other_Class); # assign a new object
298 =head1 DESCRIPTION
300 C<Autom4te::Struct> exports a single function, C<struct>.
301 Given a list of element names and types, and optionally
302 a class name, C<struct> creates a Perl 5 class that implements
303 a "struct-like" data structure.
305 The new class is given a constructor method, C<new>, for creating
306 struct objects.
308 Each element in the struct data has an accessor method, which is
309 used to assign to the element and to fetch its value. The
310 default accessor can be overridden by declaring a C<sub> of the
311 same name in the package. (See Example 2.)
313 Each element's type can be scalar, array, hash, or class.
316 =head2 The C<struct()> function
318 The C<struct> function has three forms of parameter-list.
320 struct( CLASS_NAME => [ ELEMENT_LIST ]);
321 struct( CLASS_NAME => { ELEMENT_LIST });
322 struct( ELEMENT_LIST );
324 The first and second forms explicitly identify the name of the
325 class being created. The third form assumes the current package
326 name as the class name.
328 An object of a class created by the first and third forms is
329 based on an array, whereas an object of a class created by the
330 second form is based on a hash. The array-based forms will be
331 somewhat faster and smaller; the hash-based forms are more
332 flexible.
334 The class created by C<struct> must not be a subclass of another
335 class other than C<UNIVERSAL>.
337 It can, however, be used as a superclass for other classes. To facilitate
338 this, the generated constructor method uses a two-argument blessing.
339 Furthermore, if the class is hash-based, the key of each element is
340 prefixed with the class name (see I<Perl Cookbook>, Recipe 13.12).
342 A function named C<new> must not be explicitly defined in a class
343 created by C<struct>.
345 The I<ELEMENT_LIST> has the form
347 NAME => TYPE, ...
349 Each name-type pair declares one element of the struct. Each
350 element name will be defined as an accessor method unless a
351 method by that name is explicitly defined; in the latter case, a
352 warning is issued if the warning flag (B<-w>) is set.
355 =head2 Element Types and Accessor Methods
357 The four element types -- scalar, array, hash, and class -- are
358 represented by strings -- C<'$'>, C<'@'>, C<'%'>, and a class name --
359 optionally preceded by a C<'*'>.
361 The accessor method provided by C<struct> for an element depends
362 on the declared type of the element.
364 =over
366 =item Scalar (C<'$'> or C<'*$'>)
368 The element is a scalar, and by default is initialized to C<undef>
369 (but see L<Initializing with new>).
371 The accessor's argument, if any, is assigned to the element.
373 If the element type is C<'$'>, the value of the element (after
374 assignment) is returned. If the element type is C<'*$'>, a reference
375 to the element is returned.
377 =item Array (C<'@'> or C<'*@'>)
379 The element is an array, initialized by default to C<()>.
381 With no argument, the accessor returns a reference to the
382 element's whole array (whether or not the element was
383 specified as C<'@'> or C<'*@'>).
385 With one or two arguments, the first argument is an index
386 specifying one element of the array; the second argument, if
387 present, is assigned to the array element. If the element type
388 is C<'@'>, the accessor returns the array element value. If the
389 element type is C<'*@'>, a reference to the array element is
390 returned.
392 =item Hash (C<'%'> or C<'*%'>)
394 The element is a hash, initialized by default to C<()>.
396 With no argument, the accessor returns a reference to the
397 element's whole hash (whether or not the element was
398 specified as C<'%'> or C<'*%'>).
400 With one or two arguments, the first argument is a key specifying
401 one element of the hash; the second argument, if present, is
402 assigned to the hash element. If the element type is C<'%'>, the
403 accessor returns the hash element value. If the element type is
404 C<'*%'>, a reference to the hash element is returned.
406 =item Class (C<'Class_Name'> or C<'*Class_Name'>)
408 The element's value must be a reference blessed to the named
409 class or to one of its subclasses. The element is initialized to
410 the result of calling the C<new> constructor of the named class.
412 The accessor's argument, if any, is assigned to the element. The
413 accessor will C<croak> if this is not an appropriate object
414 reference.
416 If the element type does not start with a C<'*'>, the accessor
417 returns the element value (after assignment). If the element type
418 starts with a C<'*'>, a reference to the element itself is returned.
420 =back
422 =head2 Initializing with C<new>
424 C<struct> always creates a constructor called C<new>. That constructor
425 may take a list of initializers for the various elements of the new
426 struct.
428 Each initializer is a pair of values: I<element name>C< =E<gt> >I<value>.
429 The initializer value for a scalar element is just a scalar value. The
430 initializer for an array element is an array reference. The initializer
431 for a hash is a hash reference.
433 The initializer for a class element is also a hash reference, and the
434 contents of that hash are passed to the element's own constructor.
436 See Example 3 below for an example of initialization.
439 =head1 EXAMPLES
441 =over
443 =item Example 1
445 Giving a struct element a class type that is also a struct is how
446 structs are nested. Here, C<timeval> represents a time (seconds and
447 microseconds), and C<rusage> has two elements, each of which is of
448 type C<timeval>.
450 use Autom4te::Struct;
452 struct( rusage => {
453 ru_utime => timeval, # seconds
454 ru_stime => timeval, # microseconds
457 struct( timeval => [
458 tv_secs => '$',
459 tv_usecs => '$',
462 # create an object:
463 my $t = new rusage;
465 # $t->ru_utime and $t->ru_stime are objects of type timeval.
466 # set $t->ru_utime to 100.0 sec and $t->ru_stime to 5.0 sec.
467 $t->ru_utime->tv_secs(100);
468 $t->ru_utime->tv_usecs(0);
469 $t->ru_stime->tv_secs(5);
470 $t->ru_stime->tv_usecs(0);
473 =item Example 2
475 An accessor function can be redefined in order to provide
476 additional checking of values, etc. Here, we want the C<count>
477 element always to be nonnegative, so we redefine the C<count>
478 accessor accordingly.
480 package MyObj;
481 use Autom4te::Struct;
483 # declare the struct
484 struct ( 'MyObj', { count => '$', stuff => '%' } );
486 # override the default accessor method for 'count'
487 sub count {
488 my $self = shift;
489 if ( @_ ) {
490 die 'count must be nonnegative' if $_[0] < 0;
491 $self->{'count'} = shift;
492 warn "Too many args to count" if @_;
494 return $self->{'count'};
497 package main;
498 $x = new MyObj;
499 print "\$x->count(5) = ", $x->count(5), "\n";
500 # prints '$x->count(5) = 5'
502 print "\$x->count = ", $x->count, "\n";
503 # prints '$x->count = 5'
505 print "\$x->count(-5) = ", $x->count(-5), "\n";
506 # dies due to negative argument!
508 =item Example 3
510 The constructor of a generated class can be passed a list
511 of I<element>=>I<value> pairs, with which to initialize the struct.
512 If no initializer is specified for a particular element, its default
513 initialization is performed instead. Initializers for non-existent
514 elements are silently ignored.
516 Note that the initializer for a nested struct is specified
517 as an anonymous hash of initializers, which is passed on to the nested
518 struct's constructor.
521 use Autom4te::Struct;
523 struct Breed =>
525 name => '$',
526 cross => '$',
529 struct Cat =>
531 name => '$',
532 kittens => '@',
533 markings => '%',
534 breed => 'Breed',
538 my $cat = Cat->new( name => 'Socks',
539 kittens => ['Monica', 'Kenneth'],
540 markings => { socks=>1, blaze=>"white" },
541 breed => { name=>'short-hair', cross=>1 },
544 print "Once a cat called ", $cat->name, "\n";
545 print "(which was a ", $cat->breed->name, ")\n";
546 print "had two kittens: ", join(' and ', @{$cat->kittens}), "\n";
548 =back
550 =head1 Author and Modification History
552 Modified by Akim Demaille, 2001-08-03
554 Rename as Autom4te::Struct to avoid name clashes with
555 Class::Struct.
557 Make it compatible with Perl 5.5.
559 Modified by Damian Conway, 1999-03-05, v0.58.
561 Added handling of hash-like arg list to class ctor.
563 Changed to two-argument blessing in ctor to support
564 derivation from created classes.
566 Added classname prefixes to keys in hash-based classes
567 (refer to "Perl Cookbook", Recipe 13.12 for rationale).
569 Corrected behavior of accessors for '*@' and '*%' struct
570 elements. Package now implements documented behavior when
571 returning a reference to an entire hash or array element.
572 Previously these were returned as a reference to a reference
573 to the element.
576 Renamed to C<Class::Struct> and modified by Jim Miner, 1997-04-02.
578 members() function removed.
579 Documentation corrected and extended.
580 Use of struct() in a subclass prohibited.
581 User definition of accessor allowed.
582 Treatment of '*' in element types corrected.
583 Treatment of classes as element types corrected.
584 Class name to struct() made optional.
585 Diagnostic checks added.
588 Originally C<Class::Template> by Dean Roehrich.
590 # Template.pm --- struct/member template builder
591 # 12mar95
592 # Dean Roehrich
594 # changes/bugs fixed since 28nov94 version:
595 # - podified
596 # changes/bugs fixed since 21nov94 version:
597 # - Fixed examples.
598 # changes/bugs fixed since 02sep94 version:
599 # - Moved to Class::Template.
600 # changes/bugs fixed since 20feb94 version:
601 # - Updated to be a more proper module.
602 # - Added "use strict".
603 # - Bug in build_methods, was using @var when @$var needed.
604 # - Now using my() rather than local().
606 # Uses perl5 classes to create nested data types.
607 # This is offered as one implementation of Tom Christiansen's "structs.pl"
608 # idea.
610 =cut
612 ### Setup "GNU" style for perl-mode and cperl-mode.
613 ## Local Variables:
614 ## perl-indent-level: 2
615 ## perl-continued-statement-offset: 2
616 ## perl-continued-brace-offset: 0
617 ## perl-brace-offset: 0
618 ## perl-brace-imaginary-offset: 0
619 ## perl-label-offset: -2
620 ## cperl-indent-level: 2
621 ## cperl-brace-offset: 0
622 ## cperl-continued-brace-offset: 0
623 ## cperl-label-offset: -2
624 ## cperl-extra-newline-before-brace: t
625 ## cperl-merge-trailing-else: nil
626 ## cperl-continued-statement-offset: 2
627 ## End: