Leaked source code of windows server 2003
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.

602 lines
19 KiB

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