Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

484 lines
14 KiB

  1. package Class::Struct;
  2. ## See POD after __END__
  3. require 5.002;
  4. use strict;
  5. use vars qw(@ISA @EXPORT);
  6. use Carp;
  7. require Exporter;
  8. @ISA = qw(Exporter);
  9. @EXPORT = qw(struct);
  10. ## Tested on 5.002 and 5.003 without class membership tests:
  11. my $CHECK_CLASS_MEMBERSHIP = ($] >= 5.003_95);
  12. my $print = 0;
  13. sub printem {
  14. if (@_) { $print = shift }
  15. else { $print++ }
  16. }
  17. {
  18. package Class::Struct::Tie_ISA;
  19. sub TIEARRAY {
  20. my $class = shift;
  21. return bless [], $class;
  22. }
  23. sub STORE {
  24. my ($self, $index, $value) = @_;
  25. Class::Struct::_subclass_error();
  26. }
  27. sub FETCH {
  28. my ($self, $index) = @_;
  29. $self->[$index];
  30. }
  31. sub FETCHSIZE {
  32. my $self = shift;
  33. return scalar(@$self);
  34. }
  35. sub DESTROY { }
  36. }
  37. sub struct {
  38. # Determine parameter list structure, one of:
  39. # struct( class => [ element-list ])
  40. # struct( class => { element-list })
  41. # struct( element-list )
  42. # Latter form assumes current package name as struct name.
  43. my ($class, @decls);
  44. my $base_type = ref $_[1];
  45. if ( $base_type eq 'HASH' ) {
  46. $class = shift;
  47. @decls = %{shift()};
  48. _usage_error() if @_;
  49. }
  50. elsif ( $base_type eq 'ARRAY' ) {
  51. $class = shift;
  52. @decls = @{shift()};
  53. _usage_error() if @_;
  54. }
  55. else {
  56. $base_type = 'ARRAY';
  57. $class = (caller())[0];
  58. @decls = @_;
  59. }
  60. _usage_error() if @decls % 2 == 1;
  61. # Ensure we are not, and will not be, a subclass.
  62. my $isa = do {
  63. no strict 'refs';
  64. \@{$class . '::ISA'};
  65. };
  66. _subclass_error() if @$isa;
  67. tie @$isa, 'Class::Struct::Tie_ISA';
  68. # Create constructor.
  69. croak "function 'new' already defined in package $class"
  70. if do { no strict 'refs'; defined &{$class . "::new"} };
  71. my @methods = ();
  72. my %refs = ();
  73. my %arrays = ();
  74. my %hashes = ();
  75. my %classes = ();
  76. my $got_class = 0;
  77. my $out = '';
  78. $out = "{\n package $class;\n use Carp;\n sub new {\n";
  79. my $cnt = 0;
  80. my $idx = 0;
  81. my( $cmt, $name, $type, $elem );
  82. if( $base_type eq 'HASH' ){
  83. $out .= " my(\$r) = {};\n";
  84. $cmt = '';
  85. }
  86. elsif( $base_type eq 'ARRAY' ){
  87. $out .= " my(\$r) = [];\n";
  88. }
  89. while( $idx < @decls ){
  90. $name = $decls[$idx];
  91. $type = $decls[$idx+1];
  92. push( @methods, $name );
  93. if( $base_type eq 'HASH' ){
  94. $elem = "{'$name'}";
  95. }
  96. elsif( $base_type eq 'ARRAY' ){
  97. $elem = "[$cnt]";
  98. ++$cnt;
  99. $cmt = " # $name";
  100. }
  101. if( $type =~ /^\*(.)/ ){
  102. $refs{$name}++;
  103. $type = $1;
  104. }
  105. if( $type eq '@' ){
  106. $out .= " \$r->$elem = [];$cmt\n";
  107. $arrays{$name}++;
  108. }
  109. elsif( $type eq '%' ){
  110. $out .= " \$r->$elem = {};$cmt\n";
  111. $hashes{$name}++;
  112. }
  113. elsif ( $type eq '$') {
  114. $out .= " \$r->$elem = undef;$cmt\n";
  115. }
  116. elsif( $type =~ /^\w+(?:::\w+)*$/ ){
  117. $out .= " \$r->$elem = '${type}'->new();$cmt\n";
  118. $classes{$name} = $type;
  119. $got_class = 1;
  120. }
  121. else{
  122. croak "'$type' is not a valid struct element type";
  123. }
  124. $idx += 2;
  125. }
  126. $out .= " bless \$r;\n }\n";
  127. # Create accessor methods.
  128. my( $pre, $pst, $sel );
  129. $cnt = 0;
  130. foreach $name (@methods){
  131. if ( do { no strict 'refs'; defined &{$class . "::$name"} } ) {
  132. carp "function '$name' already defined, overrides struct accessor method"
  133. if $^W;
  134. }
  135. else {
  136. $pre = $pst = $cmt = $sel = '';
  137. if( defined $refs{$name} ){
  138. $pre = "\\(";
  139. $pst = ")";
  140. $cmt = " # returns ref";
  141. }
  142. $out .= " sub $name {$cmt\n my \$r = shift;\n";
  143. if( $base_type eq 'ARRAY' ){
  144. $elem = "[$cnt]";
  145. ++$cnt;
  146. }
  147. elsif( $base_type eq 'HASH' ){
  148. $elem = "{'$name'}";
  149. }
  150. if( defined $arrays{$name} ){
  151. $out .= " my \$i;\n";
  152. $out .= " \@_ ? (\$i = shift) : return $pre\$r->$elem$pst;\n";
  153. $sel = "->[\$i]";
  154. }
  155. elsif( defined $hashes{$name} ){
  156. $out .= " my \$i;\n";
  157. $out .= " \@_ ? (\$i = shift) : return $pre\$r->$elem$pst;\n";
  158. $sel = "->{\$i}";
  159. }
  160. elsif( defined $classes{$name} ){
  161. if ( $CHECK_CLASS_MEMBERSHIP ) {
  162. $out .= " croak '$name argument is wrong class' if \@_ && ! UNIVERSAL::isa(\$_[0], '$classes{$name}');\n";
  163. }
  164. }
  165. $out .= " croak 'Too many args to $name' if \@_ > 1;\n";
  166. $out .= " \@_ ? ($pre\$r->$elem$sel = shift$pst) : $pre\$r->$elem$sel$pst;\n";
  167. $out .= " }\n";
  168. }
  169. }
  170. $out .= "}\n1;\n";
  171. print $out if $print;
  172. my $result = eval $out;
  173. carp $@ if $@;
  174. }
  175. sub _usage_error {
  176. confess "struct usage error";
  177. }
  178. sub _subclass_error {
  179. croak 'struct class cannot be a subclass (@ISA not allowed)';
  180. }
  181. 1; # for require
  182. __END__
  183. =head1 NAME
  184. Class::Struct - declare struct-like datatypes as Perl classes
  185. =head1 SYNOPSIS
  186. use Class::Struct;
  187. # declare struct, based on array:
  188. struct( CLASS_NAME => [ ELEMENT_NAME => ELEMENT_TYPE, ... ]);
  189. # declare struct, based on hash:
  190. struct( CLASS_NAME => { ELEMENT_NAME => ELEMENT_TYPE, ... });
  191. package CLASS_NAME;
  192. use Class::Struct;
  193. # declare struct, based on array, implicit class name:
  194. struct( ELEMENT_NAME => ELEMENT_TYPE, ... );
  195. package Myobj;
  196. use Class::Struct;
  197. # declare struct with four types of elements:
  198. struct( s => '$', a => '@', h => '%', c => 'My_Other_Class' );
  199. $obj = new Myobj; # constructor
  200. # scalar type accessor:
  201. $element_value = $obj->s; # element value
  202. $obj->s('new value'); # assign to element
  203. # array type accessor:
  204. $ary_ref = $obj->a; # reference to whole array
  205. $ary_element_value = $obj->a(2); # array element value
  206. $obj->a(2, 'new value'); # assign to array element
  207. # hash type accessor:
  208. $hash_ref = $obj->h; # reference to whole hash
  209. $hash_element_value = $obj->h('x'); # hash element value
  210. $obj->h('x', 'new value'); # assign to hash element
  211. # class type accessor:
  212. $element_value = $obj->c; # object reference
  213. $obj->c->method(...); # call method of object
  214. $obj->c(new My_Other_Class); # assign a new object
  215. =head1 DESCRIPTION
  216. C<Class::Struct> exports a single function, C<struct>.
  217. Given a list of element names and types, and optionally
  218. a class name, C<struct> creates a Perl 5 class that implements
  219. a "struct-like" data structure.
  220. The new class is given a constructor method, C<new>, for creating
  221. struct objects.
  222. Each element in the struct data has an accessor method, which is
  223. used to assign to the element and to fetch its value. The
  224. default accessor can be overridden by declaring a C<sub> of the
  225. same name in the package. (See Example 2.)
  226. Each element's type can be scalar, array, hash, or class.
  227. =head2 The C<struct()> function
  228. The C<struct> function has three forms of parameter-list.
  229. struct( CLASS_NAME => [ ELEMENT_LIST ]);
  230. struct( CLASS_NAME => { ELEMENT_LIST });
  231. struct( ELEMENT_LIST );
  232. The first and second forms explicitly identify the name of the
  233. class being created. The third form assumes the current package
  234. name as the class name.
  235. An object of a class created by the first and third forms is
  236. based on an array, whereas an object of a class created by the
  237. second form is based on a hash. The array-based forms will be
  238. somewhat faster and smaller; the hash-based forms are more
  239. flexible.
  240. The class created by C<struct> must not be a subclass of another
  241. class other than C<UNIVERSAL>.
  242. A function named C<new> must not be explicitly defined in a class
  243. created by C<struct>.
  244. The I<ELEMENT_LIST> has the form
  245. NAME => TYPE, ...
  246. Each name-type pair declares one element of the struct. Each
  247. element name will be defined as an accessor method unless a
  248. method by that name is explicitly defined; in the latter case, a
  249. warning is issued if the warning flag (B<-w>) is set.
  250. =head2 Element Types and Accessor Methods
  251. The four element types -- scalar, array, hash, and class -- are
  252. represented by strings -- C<'$'>, C<'@'>, C<'%'>, and a class name --
  253. optionally preceded by a C<'*'>.
  254. The accessor method provided by C<struct> for an element depends
  255. on the declared type of the element.
  256. =over
  257. =item Scalar (C<'$'> or C<'*$'>)
  258. The element is a scalar, and is initialized to C<undef>.
  259. The accessor's argument, if any, is assigned to the element.
  260. If the element type is C<'$'>, the value of the element (after
  261. assignment) is returned. If the element type is C<'*$'>, a reference
  262. to the element is returned.
  263. =item Array (C<'@'> or C<'*@'>)
  264. The element is an array, initialized to C<()>.
  265. With no argument, the accessor returns a reference to the
  266. element's whole array.
  267. With one or two arguments, the first argument is an index
  268. specifying one element of the array; the second argument, if
  269. present, is assigned to the array element. If the element type
  270. is C<'@'>, the accessor returns the array element value. If the
  271. element type is C<'*@'>, a reference to the array element is
  272. returned.
  273. =item Hash (C<'%'> or C<'*%'>)
  274. The element is a hash, initialized to C<()>.
  275. With no argument, the accessor returns a reference to the
  276. element's whole hash.
  277. With one or two arguments, the first argument is a key specifying
  278. one element of the hash; the second argument, if present, is
  279. assigned to the hash element. If the element type is C<'%'>, the
  280. accessor returns the hash element value. If the element type is
  281. C<'*%'>, a reference to the hash element is returned.
  282. =item Class (C<'Class_Name'> or C<'*Class_Name'>)
  283. The element's value must be a reference blessed to the named
  284. class or to one of its subclasses. The element is initialized to
  285. the result of calling the C<new> constructor of the named class.
  286. The accessor's argument, if any, is assigned to the element. The
  287. accessor will C<croak> if this is not an appropriate object
  288. reference.
  289. If the element type does not start with a C<'*'>, the accessor
  290. returns the element value (after assignment). If the element type
  291. starts with a C<'*'>, a reference to the element itself is returned.
  292. =back
  293. =head1 EXAMPLES
  294. =over
  295. =item Example 1
  296. Giving a struct element a class type that is also a struct is how
  297. structs are nested. Here, C<timeval> represents a time (seconds and
  298. microseconds), and C<rusage> has two elements, each of which is of
  299. type C<timeval>.
  300. use Class::Struct;
  301. struct( rusage => {
  302. ru_utime => timeval, # seconds
  303. ru_stime => timeval, # microseconds
  304. });
  305. struct( timeval => [
  306. tv_secs => '$',
  307. tv_usecs => '$',
  308. ]);
  309. # create an object:
  310. my $t = new rusage;
  311. # $t->ru_utime and $t->ru_stime are objects of type timeval.
  312. # set $t->ru_utime to 100.0 sec and $t->ru_stime to 5.0 sec.
  313. $t->ru_utime->tv_secs(100);
  314. $t->ru_utime->tv_usecs(0);
  315. $t->ru_stime->tv_secs(5);
  316. $t->ru_stime->tv_usecs(0);
  317. =item Example 2
  318. An accessor function can be redefined in order to provide
  319. additional checking of values, etc. Here, we want the C<count>
  320. element always to be nonnegative, so we redefine the C<count>
  321. accessor accordingly.
  322. package MyObj;
  323. use Class::Struct;
  324. # declare the struct
  325. struct ( 'MyObj', { count => '$', stuff => '%' } );
  326. # override the default accessor method for 'count'
  327. sub count {
  328. my $self = shift;
  329. if ( @_ ) {
  330. die 'count must be nonnegative' if $_[0] < 0;
  331. $self->{'count'} = shift;
  332. warn "Too many args to count" if @_;
  333. }
  334. return $self->{'count'};
  335. }
  336. package main;
  337. $x = new MyObj;
  338. print "\$x->count(5) = ", $x->count(5), "\n";
  339. # prints '$x->count(5) = 5'
  340. print "\$x->count = ", $x->count, "\n";
  341. # prints '$x->count = 5'
  342. print "\$x->count(-5) = ", $x->count(-5), "\n";
  343. # dies due to negative argument!
  344. =head1 Author and Modification History
  345. Renamed to C<Class::Struct> and modified by Jim Miner, 1997-04-02.
  346. members() function removed.
  347. Documentation corrected and extended.
  348. Use of struct() in a subclass prohibited.
  349. User definition of accessor allowed.
  350. Treatment of '*' in element types corrected.
  351. Treatment of classes as element types corrected.
  352. Class name to struct() made optional.
  353. Diagnostic checks added.
  354. Originally C<Class::Template> by Dean Roehrich.
  355. # Template.pm --- struct/member template builder
  356. # 12mar95
  357. # Dean Roehrich
  358. #
  359. # changes/bugs fixed since 28nov94 version:
  360. # - podified
  361. # changes/bugs fixed since 21nov94 version:
  362. # - Fixed examples.
  363. # changes/bugs fixed since 02sep94 version:
  364. # - Moved to Class::Template.
  365. # changes/bugs fixed since 20feb94 version:
  366. # - Updated to be a more proper module.
  367. # - Added "use strict".
  368. # - Bug in build_methods, was using @var when @$var needed.
  369. # - Now using my() rather than local().
  370. #
  371. # Uses perl5 classes to create nested data types.
  372. # This is offered as one implementation of Tom Christiansen's "structs.pl"
  373. # idea.
  374. =cut