File Coverage

blib/lib/Struct/Dumb.pm
Criterion Covered Total %
statement 115 154 74.6
branch 24 44 54.5
condition 6 14 42.8
subroutine 27 34 79.4
pod 0 1 0.0
total 172 247 69.6


line stmt bran cond sub pod time code
1             # You may distribute under the terms of either the GNU General Public License
2             # or the Artistic License (the same terms as Perl itself)
3             #
4             # (C) Paul Evans, 2012-2022 -- leonerd@leonerd.org.uk
5              
6             package Struct::Dumb;
7              
8 7     7   1343818 use strict;
  7         46  
  7         198  
9 7     7   33 use warnings;
  7         16  
  7         253  
10              
11             our $VERSION = '0.14';
12              
13 7     7   40 use Carp;
  7         11  
  7         379  
14              
15 7     7   38 use Scalar::Util qw( refaddr );
  7         13  
  7         409  
16              
17             # 'overloading.pm' was only added in 5.10
18             # Before that we can't easily implement forbidding of @{} overload, so lets not
19 7     7   43 use constant HAVE_OVERLOADING => eval { require overloading };
  7         22  
  7         17  
  7         856  
20              
21 7     7   39 use constant HAVE_FEATURE_CLASS => defined eval { require feature; $feature::feature{class} };
  7         13  
  7         10  
  7         34  
  7         2210  
22              
23             =head1 NAME
24              
25             C - make simple lightweight record-like structures
26              
27             =head1 SYNOPSIS
28              
29             use Struct::Dumb;
30              
31             struct Point => [qw( x y )];
32              
33             my $point = Point(10, 20);
34              
35             printf "Point is at (%d, %d)\n", $point->x, $point->y;
36              
37             $point->y = 30;
38             printf "Point is now at (%d, %d)\n", $point->x, $point->y;
39              
40             Z<>
41              
42             struct Point3D => [qw( x y z )], named_constructor => 1;
43              
44             my $point3d = Point3D( z => 12, x => 100, y => 50 );
45              
46             printf "Point3d's height is %d\n", $point3d->z;
47              
48             Z<>
49              
50             struct Point3D => [qw( x y z )], predicate => "is_Point3D";
51              
52             my $point3d = Point3D( 1, 2, 3 );
53              
54             printf "This is a Point3D\n" if is_Point3D( $point3d );
55              
56             Z<>
57              
58             use Struct::Dumb qw( -named_constructors )
59              
60             struct Point3D => [qw( x y z )];
61              
62             my $point3d = Point3D( x => 100, z => 12, y => 50 );
63              
64             =head1 DESCRIPTION
65              
66             C creates record-like structure types, similar to the C
67             keyword in C, C++ or C#, or C in Pascal. An invocation of this module
68             will create a construction function which returns new object references with
69             the given field values. These references all respond to lvalue methods that
70             access or modify the values stored.
71              
72             It's specifically and intentionally not meant to be an object class. You
73             cannot subclass it. You cannot provide additional methods. You cannot apply
74             roles or mixins or metaclasses or traits or antlers or whatever else is in
75             fashion this week.
76              
77             On the other hand, it is tiny, creates cheap lightweight array-backed
78             structures, uses nothing outside of core. It's intended simply to be a
79             slightly nicer way to store data structures, where otherwise you might be
80             tempted to abuse a hash, complete with the risk of typoing key names. The
81             constructor will C if passed the wrong number of arguments, as will
82             attempts to refer to fields that don't exist. Accessor-mutators will C
83             if invoked with arguments. (This helps detect likely bugs such as accidentally
84             passing in the new value as an argument, or attempting to invoke a stored
85             C reference by passing argument values directly to the accessor.)
86              
87             $ perl -E 'use Struct::Dumb; struct Point => [qw( x y )]; Point(30)'
88             usage: main::Point($x, $y) at -e line 1
89              
90             $ perl -E 'use Struct::Dumb; struct Point => [qw( x y )]; Point(10,20)->z'
91             main::Point does not have a 'z' field at -e line 1
92              
93             $ perl -E 'use Struct::Dumb; struct Point => [qw( x y )]; Point(1,2)->x(3)'
94             main::Point->x invoked with arguments at -e line 1.
95              
96             Objects in this class are (currently) backed by an ARRAY reference store,
97             though this is an internal implementation detail and should not be relied on
98             by using code. Attempting to dereference the object as an ARRAY will throw an
99             exception.
100              
101             I: That on development perls that support C, this
102             is used instead of a blessed ARRAY reference. This implementation choice
103             should be transparent to the end-user, as all the same features are supported.
104              
105             =head2 CONSTRUCTOR FORMS
106              
107             The C and C declarations create two different kinds
108             of constructor function, depending on the setting of the C
109             option. When false, the constructor takes positional values in the same order
110             as the fields were declared. When true, the constructor takes a key/value pair
111             list in no particular order, giving the value of each named field.
112              
113             This option can be specified to the C and C
114             functions. It defaults to false, but it can be set on a per-package basis to
115             default true by supplying the C<-named_constructors> option on the C
116             statement.
117              
118             When using named constructors, individual fields may be declared as being
119             optional. By preceeding the field name with a C character, the constructor
120             is instructed not to complain if a named parameter is not given for that
121             field; instead it will be set to C.
122              
123             struct Person => [qw( name age ?address )],
124             named_constructor => 1;
125              
126             my $bob = Person( name => "Bob", age => 20 );
127             # This is valid because 'address' is marked as optional
128              
129             =cut
130              
131             sub import
132             {
133 9     9   63 my $pkg = shift;
134 9         20 my $caller = caller;
135              
136 9         18 my %default_opts;
137             my %syms;
138              
139 9         23 foreach ( @_ ) {
140 2 100       22 if( $_ eq "-named_constructors" ) {
141 1         4 $default_opts{named_constructor} = 1;
142             }
143             else {
144 1         3 $syms{$_}++;
145             }
146             }
147              
148 9 100       42 keys %syms or $syms{struct}++;
149              
150 9         17 my %export;
151              
152 9 100       43 if( delete $syms{struct} ) {
153             $export{struct} = sub {
154 7     7   1219 my ( $name, $fields, @opts ) = @_;
155 7         46 _struct( $name, $fields, scalar caller, lvalue => 1, %default_opts, @opts );
156 8         38 };
157             }
158 9 100       31 if( delete $syms{readonly_struct} ) {
159             $export{readonly_struct} = sub {
160 1     1   99 my ( $name, $fields, @opts ) = @_;
161 1         6 _struct( $name, $fields, scalar caller, lvalue => 0, %default_opts, @opts );
162 1         4 };
163             }
164              
165 9 50       26 if( keys %syms ) {
166 0         0 croak "Unrecognised export symbols " . join( ", ", keys %syms );
167             }
168              
169 7     7   53 no strict 'refs';
  7         14  
  7         2558  
170 9         29 *{"${caller}::$_"} = $export{$_} for keys %export;
  9         8361  
171             }
172              
173             =head1 FUNCTIONS
174              
175             =cut
176              
177             my %_STRUCT_PACKAGES;
178              
179             sub _struct
180             {
181 8     8   42 my ( $name, $_fields, $caller, %opts ) = @_;
182              
183 8         25 my $lvalue = !!$opts{lvalue};
184 8         20 my $named = !!$opts{named_constructor};
185              
186 8         26 my $pkg = "${caller}::$name";
187              
188 8         21 my @fields = @$_fields;
189              
190 8         16 my %optional;
191 8   66     53 s/^\?// and $optional{$_}++ for @fields;
192              
193 8         15 my %subs;
194 8     0   45 $subs{DESTROY} = sub {};
195             $subs{AUTOLOAD} = sub :lvalue {
196 2     2   597 my ( $field ) = our $AUTOLOAD =~ m/::([^:]+)$/;
197 2         249 croak "$pkg does not have a '$field' field";
198 0         0 my $dummy; ## croak can't be last because it isn't lvalue, so this line is required
199 8         36 };
200              
201 8         16 my $constructor;
202              
203 8         15 if( HAVE_FEATURE_CLASS ) {
204             _build_class_for_feature_class( $pkg, \@fields, \%optional, $named, $lvalue, \$constructor );
205             }
206             else {
207 8         31 _build_class_for_classical( $pkg, \@fields, \%optional, $named, $lvalue, \$constructor );
208             }
209              
210 7     7   52 no strict 'refs';
  7         22  
  7         4539  
211 8         36 *{"${pkg}::$_"} = $subs{$_} for keys %subs;
  16         63  
212 8         19 *{"${caller}::$name"} = $constructor;
  8         35  
213              
214 8 100       30 if( my $predicate = $opts{predicate} ) {
215 1   50 2   5 *{"${caller}::$predicate"} = sub { ( ref($_[0]) || "" ) eq $pkg };
  1         4  
  2         18  
216             }
217              
218 8         39 *{"${pkg}::_forbid_arrayification"} = sub {
219 1     1   2 return if !HAVE_OVERLOADING and caller eq __PACKAGE__;
220 1         77 croak "Cannot use $pkg as an ARRAY reference"
221 8         46 };
222              
223 8         73 require overload;
224             $pkg->overload::OVERLOAD(
225 2     2   9 '@{}' => sub { $_[0]->_forbid_arrayification; return $_[0] },
  1         5  
226 1     1   268 '0+' => sub { refaddr $_[0] },
227 1     1   14 '""' => sub { sprintf "%s=Struct::Dumb(%#x)", $pkg, refaddr $_[0] },
228 1     1   3 'bool' => sub { 1 },
229 8         116 fallback => 1,
230             );
231              
232 8         583 $_STRUCT_PACKAGES{$pkg} = {
233             named => $named,
234             fields => \@fields,
235             }
236             }
237              
238             sub _build_class_for_classical
239             {
240 8     8   37 my ( $pkg, $fields, $optional, $named, $lvalue, $constructorvar ) = @_;
241 8         25 my @fields = @$fields;
242              
243 8 100       23 if( $named ) {
244             $$constructorvar = sub {
245 6     6   1516 my %values = @_;
246 6         10 my @values;
247 6         12 foreach ( @fields ) {
248 18 100 100     239 exists $values{$_} or $optional->{$_} or
249             croak "usage: $pkg requires '$_'";
250 17         30 push @values, delete $values{$_};
251             }
252 5 100       18 if( my ( $extrakey ) = keys %values ) {
253 1         114 croak "usage: $pkg does not recognise '$extrakey'";
254             }
255 4         14 bless \@values, $pkg;
256 3         12 };
257             }
258             else {
259 5         12 my $fieldcount = @fields;
260 5         31 my $argnames = join ", ", map "\$$_", @fields;
261             $$constructorvar = sub {
262 10 100   10   1998 @_ == $fieldcount or croak "usage: $pkg($argnames)";
263 9         103 bless [ @_ ], $pkg;
264 5         30 };
265             }
266              
267 8         16 my %subs;
268 8         38 foreach ( 0 .. $#fields ) {
269 20         48 my $idx = $_;
270 20         42 my $field = $fields[$idx];
271              
272             BEGIN {
273 7     7   1299 overloading->unimport if HAVE_OVERLOADING;
274             }
275              
276             $subs{$field} = $lvalue
277 8 100   8   13159 ? sub :lvalue { @_ > 1 and croak "$pkg->$field invoked with arguments";
278 7         37 shift->[$idx] }
279 1 50   1   7 : sub { @_ > 1 and croak "$pkg->$field invoked with arguments";
280 20 100       119 shift->[$idx] };
  1         10  
281             }
282              
283 7     7   55 no strict 'refs';
  7         14  
  7         5940  
284 8         34 *{"${pkg}::$_"} = $subs{$_} for keys %subs;
  20         132  
285             }
286              
287             sub _build_class_for_feature_class
288             {
289 0     0   0 my ( $pkg, $fields, $optional, $named, $lvalue, $constructorvar ) = @_;
290 0         0 my @fields = @$fields;
291 0         0 my %optional = %$optional;
292              
293 0 0       0 if( $named ) {
294 0         0 my %fieldnames = map { $_ => 1 } @fields;
  0         0  
295              
296             $$constructorvar = sub {
297 0     0   0 my %values = @_;
298 0         0 foreach ( @fields ) {
299 0 0 0     0 exists $values{$_} or $optional{$_} or
300             croak "usage: $pkg requires '$_'";
301             }
302 0   0     0 $fieldnames{$_} or croak "usage: $pkg does not recognise '$_'" for keys %values;
303 0         0 return $pkg->new( %values );
304 0         0 };
305             }
306             else {
307 0         0 my $fieldcount = @fields;
308 0         0 my $argnames = join ", ", map "\$$_", @fields;
309             $$constructorvar = sub {
310 0 0   0   0 @_ == $fieldcount or croak "usage: $pkg($argnames)";
311 0         0 my %values; @values{@fields} = @_;
  0         0  
312 0         0 return $pkg->new( %values );
313 0         0 };
314             }
315              
316 0 0       0 $lvalue = $lvalue ? " :lvalue" : "";
317              
318             my @fieldcode = map {
319 0         0 my $name = $_;
  0         0  
320 0         0 my $var = "\$$name";
321              
322 0         0 " field $var :param = undef;",
323             " method $name$lvalue { \@_ and croak \"$pkg->$name invoked with arguments\"; $var }",
324             } @$fields;
325              
326 0         0 my $code = join( "\n",
327             "use experimental 'class';",
328             "class $pkg {",
329             " use Carp;",
330             @fieldcode,
331             "}", "" );
332              
333 0 0       0 eval "$code; 1" or die $@;
334             }
335              
336             =head2 struct
337              
338             struct $name => [ @fieldnames ],
339             named_constructor => (1|0),
340             predicate => "is_$name";
341              
342             Creates a new structure type. This exports a new function of the type's name
343             into the caller's namespace. Invoking this function returns a new instance of
344             a type that implements those field names, as accessors and mutators for the
345             fields.
346              
347             Takes the following options:
348              
349             =over 4
350              
351             =item named_constructor => BOOL
352              
353             Determines whether the structure will take positional or named arguments.
354              
355             =item predicate => STR
356              
357             If defined, gives the name of a second function to export to the caller's
358             namespace. This function will be a type test predicate; that is, a function
359             that takes a single argmuent, and returns true if-and-only-if that argument is
360             an instance of this structure type.
361              
362             =back
363              
364             =cut
365              
366             =head2 readonly_struct
367              
368             readonly_struct $name => [ @fieldnames ],
369             ...
370              
371             Similar to L, but instances of this type are immutable once
372             constructed. The field accessor methods will not be marked with the
373             C<:lvalue> attribute.
374              
375             Takes the same options as L.
376              
377             =cut
378              
379             =head1 DATA::DUMP FILTER
380              
381             I
382              
383             If L is loaded, an extra filter is applied so that struct
384             instances are printed in a format matching that which would construct them.
385              
386             struct Colour => [qw( red green blue )];
387              
388             use Data::Dump;
389              
390             my %hash = ( col => Colour( 0.8, 0.5, 0.2 ) );
391             Data::Dump::dd \%hash;
392              
393             # prints {col => main::Colour(0.8, 0.5, 0.2)}
394              
395             =head1 NOTES
396              
397             =head2 Allowing ARRAY dereference
398              
399             The way that forbidding access to instances as if they were ARRAY references
400             is currently implemented uses an internal method on the generated structure
401             class called C<_forbid_arrayification>. If special circumstances require that
402             this exception mechanism be bypassed, the method can be overloaded with an
403             empty C body, allowing the struct instances in that class to be
404             accessed like normal ARRAY references. For good practice this should be
405             limited by a C override.
406              
407             For example, L needs to access the instances as plain ARRAY
408             references so it can walk the data structure looking for reference cycles.
409              
410             use Devel::Cycle;
411              
412             {
413             no warnings 'redefine';
414             local *Point::_forbid_arrayification = sub {};
415              
416             memory_cycle_ok( $point );
417             }
418              
419             =head1 TODO
420              
421             =over 4
422              
423             =item *
424              
425             Consider adding an C option, giving name of another function to
426             convert structs to key/value pairs, or a HASH ref.
427              
428             =back
429              
430             =head1 AUTHOR
431              
432             Paul Evans
433              
434             =cut
435              
436             sub maybe_apply_datadump_filter
437             {
438 0 0   0 0 0 return unless $INC{"Data/Dump.pm"};
439              
440 0         0 require Data::Dump::Filtered;
441              
442             Data::Dump::Filtered::add_dump_filter( sub {
443 0     0   0 my ( $ctx, $obj ) = @_;
444 0 0       0 return undef unless my $meta = $_STRUCT_PACKAGES{ $ctx->class };
445              
446 0         0 my $fields = $meta->{fields};
447             return {
448             dump => sprintf "%s(%s)", $ctx->class,
449             join ", ", map {
450 0         0 my $field = $fields->[$_];
  0         0  
451              
452 0 0       0 ( $meta->{named} ? "$field => " : "" ) .
453             Data::Dump::dump($obj->$field)
454             } 0 .. $#$fields
455             };
456 0         0 });
457             }
458              
459             if( defined &Data::Dump::dump ) {
460             maybe_apply_datadump_filter;
461             }
462             else {
463             # A package var we observe that Data/Dump.pm seems to set when loaded
464             # We can't attach to VERSION because too many other things get upset by
465             # that.
466             $Data::Dump::DEBUG = bless \( my $x = \&maybe_apply_datadump_filter ),
467             "Struct::Dumb::_DestroyWatch";
468             }
469              
470             {
471             package Struct::Dumb::_DestroyWatch;
472             my $GD = 0;
473 6     6   13427 END { $GD = 1 }
474 0 0   0   0 sub DESTROY { ${$_[0]}->() unless $GD; }
  0         0  
475             }
476              
477             0x55AA;