MPE/iX fixes from Mark Bixby (a Configure fix is also needed.)
[p5sagit/p5-mst-13.2.git] / lib / ExtUtils / Constant.pm
CommitLineData
af6c647e 1package ExtUtils::Constant;
8ac27563 2use vars qw (@ISA $VERSION %XS_Constant %XS_TypeSet @EXPORT_OK %EXPORT_TAGS);
72f7b9a1 3$VERSION = '0.08';
af6c647e 4
5=head1 NAME
6
7ExtUtils::Constant - generate XS code to import C header constants
8
9=head1 SYNOPSIS
10
0552bf3a 11 use ExtUtils::Constant qw (WriteConstants);
12 WriteConstants(
13 NAME => 'Foo',
14 NAMES => [qw(FOO BAR BAZ)],
15 C_FILE => 'constants.c',
16 XS_FILE => 'constants.xs',
17 );
18 # Generates wrapper code to make the values of the constants FOO BAR BAZ
19 # available to perl
af6c647e 20
21=head1 DESCRIPTION
22
23ExtUtils::Constant facilitates generating C and XS wrapper code to allow
24perl modules to AUTOLOAD constants defined in C library header files.
25It is principally used by the C<h2xs> utility, on which this code is based.
26It doesn't contain the routines to scan header files to extract these
27constants.
28
29=head1 USAGE
30
0552bf3a 31Generally one only needs to call the C<WriteConstants> function, and then
32
33 #include "constants.c"
34
35in the C section of C<Foo.xs>
36
37 INCLUDE constants.xs
38
39in the XS section of C<Foo.xs>.
40
41For greater flexibility use C<constant_types()>, C<C_constant> and
42C<XS_constant>, with which C<WriteConstants> is implemented.
af6c647e 43
44Currently this module understands the following types. h2xs may only know
45a subset. The sizes of the numeric types are chosen by the C<Configure>
46script at compile time.
47
48=over 4
49
50=item IV
51
52signed integer, at least 32 bits.
53
54=item UV
55
56unsigned integer, the same size as I<IV>
57
58=item NV
59
60floating point type, probably C<double>, possibly C<long double>
61
62=item PV
63
64NUL terminated string, length will be determined with C<strlen>
65
66=item PVN
67
68A fixed length thing, given as a [pointer, length] pair. If you know the
69length of a string at compile time you may use this instead of I<PV>
70
cea00dc5 71=item PVN
72
73A B<mortal> SV.
74
3414cef0 75=item YES
76
77Truth. (C<PL_sv_yes>) The value is not needed (and ignored).
78
79=item NO
80
81Defined Falsehood. (C<PL_sv_no>) The value is not needed (and ignored).
82
83=item UNDEF
84
85C<undef>. The value of the macro is not needed.
86
af6c647e 87=back
88
89=head1 FUNCTIONS
90
91=over 4
92
93=cut
94
95require 5.006; # I think, for [:cntrl:] in REGEXP
96use warnings;
97use strict;
98use Carp;
99
100use Exporter;
af6c647e 101use Text::Wrap;
102$Text::Wrap::huge = 'overflow';
103$Text::Wrap::columns = 80;
104
105@ISA = 'Exporter';
af6c647e 106
107%EXPORT_TAGS = ( 'all' => [ qw(
108 XS_constant constant_types return_clause memEQ_clause C_stringify
0552bf3a 109 C_constant autoload WriteConstants
af6c647e 110) ] );
111
112@EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
113
114%XS_Constant = (
cea00dc5 115 IV => 'PUSHi(iv)',
116 UV => 'PUSHu((UV)iv)',
117 NV => 'PUSHn(nv)',
118 PV => 'PUSHp(pv, strlen(pv))',
119 PVN => 'PUSHp(pv, iv)',
120 SV => 'PUSHs(sv)',
121 YES => 'PUSHs(&PL_sv_yes)',
122 NO => 'PUSHs(&PL_sv_no)',
19d75eda 123 UNDEF => '', # implicit undef
af6c647e 124);
125
126%XS_TypeSet = (
cea00dc5 127 IV => '*iv_return =',
128 UV => '*iv_return = (IV)',
129 NV => '*nv_return =',
130 PV => '*pv_return =',
131 PVN => ['*pv_return =', '*iv_return = (IV)'],
132 SV => '*sv_return = ',
19d75eda 133 YES => undef,
134 NO => undef,
135 UNDEF => undef,
af6c647e 136);
137
138
139=item C_stringify NAME
140
141A function which returns a correctly \ escaped version of the string passed
6d79cad2 142suitable for C's "" or ''. It will also be valid as a perl "" string.
af6c647e 143
144=cut
145
146# Hopefully make a happy C identifier.
147sub C_stringify {
148 local $_ = shift;
6d79cad2 149 return unless defined $_;
af6c647e 150 s/\\/\\\\/g;
151 s/([\"\'])/\\$1/g; # Grr. fix perl mode.
6d79cad2 152 s/\n/\\n/g; # Ensure newlines don't end up in octal
153 s/\r/\\r/g;
3414cef0 154 s/\t/\\t/g;
155 s/\f/\\f/g;
156 s/\a/\\a/g;
af6c647e 157 s/([[:cntrl:]])/sprintf "\\%03o", ord $1/ge;
158 s/\177/\\177/g; # DEL doesn't seem to be a [:cntrl:]
159 $_;
160}
161
162=item constant_types
163
164A function returning a single scalar with C<#define> definitions for the
165constants used internally between the generated C and XS functions.
166
167=cut
168
169sub constant_types () {
170 my $start = 1;
171 my @lines;
172 push @lines, "#define PERL_constant_NOTFOUND\t$start\n"; $start++;
173 push @lines, "#define PERL_constant_NOTDEF\t$start\n"; $start++;
174 foreach (sort keys %XS_Constant) {
175 push @lines, "#define PERL_constant_IS$_\t$start\n"; $start++;
176 }
177 push @lines, << 'EOT';
178
179#ifndef NVTYPE
180typedef double NV; /* 5.6 and later define NVTYPE, and typedef NV to it. */
181#endif
182EOT
183
184 return join '', @lines;
185}
186
187=item memEQ_clause NAME, CHECKED_AT, INDENT
188
189A function to return a suitable C C<if> statement to check whether I<NAME>
190is equal to the C variable C<name>. If I<CHECKED_AT> is defined, then it
191is used to avoid C<memEQ> for short names, or to generate a comment to
192highlight the position of the character in the C<switch> statement.
193
194=cut
195
196sub memEQ_clause {
197# if (memEQ(name, "thingy", 6)) {
198 # Which could actually be a character comparison or even ""
199 my ($name, $checked_at, $indent) = @_;
200 $indent = ' ' x ($indent || 4);
201 my $len = length $name;
202
203 if ($len < 2) {
204 return $indent . "{\n" if (defined $checked_at and $checked_at == 0);
205 # We didn't switch, drop through to the code for the 2 character string
206 $checked_at = 1;
207 }
208 if ($len < 3 and defined $checked_at) {
209 my $check;
210 if ($checked_at == 1) {
211 $check = 0;
212 } elsif ($checked_at == 0) {
213 $check = 1;
214 }
215 if (defined $check) {
216 my $char = C_stringify (substr $name, $check, 1);
217 return $indent . "if (name[$check] == '$char') {\n";
218 }
219 }
220 # Could optimise a memEQ on 3 to 2 single character checks here
221 $name = C_stringify ($name);
222 my $body = $indent . "if (memEQ(name, \"$name\", $len)) {\n";
223 $body .= $indent . "/* ". (' ' x $checked_at) . '^'
224 . (' ' x ($len - $checked_at + length $len)) . " */\n"
225 if defined $checked_at;
226 return $body;
227}
228
cea00dc5 229=item assign INDENT, TYPE, PRE, POST, VALUE...
6d79cad2 230
231A function to return a suitable assignment clause. If I<TYPE> is aggregate
232(eg I<PVN> expects both pointer and length) then there should be multiple
cea00dc5 233I<VALUE>s for the components. I<PRE> and I<POST> if defined give snippets
234of C code to preceed and follow the assignment. I<PRE> will be at the start
235of a block, so variables may be defined in it.
6d79cad2 236
237=cut
238
239# Hmm. value undef to to NOTDEF? value () to do NOTFOUND?
240
241sub assign {
242 my $indent = shift;
243 my $type = shift;
cea00dc5 244 my $pre = shift;
245 my $post = shift || '';
6d79cad2 246 my $clause;
cea00dc5 247 my $close;
248 if ($pre) {
249 chomp $pre;
250 $clause = $indent . "{\n$pre";
251 $clause .= ";" unless $pre =~ /;$/;
252 $clause .= "\n";
253 $close = "$indent}\n";
254 $indent .= " ";
255 }
3414cef0 256 die "Can't generate code for type $type" unless exists $XS_TypeSet{$type};
257 my $typeset = $XS_TypeSet{$type};
6d79cad2 258 if (ref $typeset) {
259 die "Type $type is aggregate, but only single value given"
260 if @_ == 1;
261 foreach (0 .. $#$typeset) {
262 $clause .= $indent . "$typeset->[$_] $_[$_];\n";
263 }
3414cef0 264 } elsif (defined $typeset) {
6d79cad2 265 die "Aggregate value given for type $type"
266 if @_ > 1;
267 $clause .= $indent . "$typeset $_[0];\n";
268 }
cea00dc5 269 chomp $post;
270 if (length $post) {
271 $clause .= "$post";
272 $clause .= ";" unless $post =~ /;$/;
273 $clause .= "\n";
a2c454fa 274 }
6d79cad2 275 $clause .= "${indent}return PERL_constant_IS$type;\n";
cea00dc5 276 $clause .= $close if $close;
6d79cad2 277 return $clause;
278}
279
cea00dc5 280=item return_clause VALUE, TYPE, INDENT, MACRO, DEFAULT, PRE, POST, PRE, POST
af6c647e 281
282A function to return a suitable C<#ifdef> clause. I<MACRO> defaults to
6d79cad2 283I<VALUE> when not defined. If I<TYPE> is aggregate (eg I<PVN> expects both
af6c647e 284pointer and length) then I<VALUE> should be a reference to an array of
6d79cad2 285values in the order expected by the type. C<C_constant> will always call
286this function with I<MACRO> defined, defaulting to the constant's name.
287I<DEFAULT> if defined is an array reference giving default type and and
288value(s) if the clause generated by I<MACRO> doesn't evaluate to true.
cea00dc5 289The two pairs I<PRE> and I<POST> if defined give C code snippets to proceed
290and follow the value, and the default value.
af6c647e 291
292=cut
293
cea00dc5 294sub return_clause ($$$$$$$$$) {
af6c647e 295##ifdef thingy
296# *iv_return = thingy;
297# return PERL_constant_ISIV;
298##else
299# return PERL_constant_NOTDEF;
300##endif
cea00dc5 301 my ($value, $type, $indent, $macro, $default, $pre, $post,
302 $def_pre, $def_post) = @_;
af6c647e 303 $macro = $value unless defined $macro;
304 $indent = ' ' x ($indent || 6);
305
6d79cad2 306 my $clause;
af6c647e 307
6d79cad2 308 ##ifdef thingy
309 if (ref $macro) {
310 $clause = $macro->[0];
72f7b9a1 311 } elsif ($macro ne "1") {
6d79cad2 312 $clause = "#ifdef $macro\n";
af6c647e 313 }
6d79cad2 314
315 # *iv_return = thingy;
316 # return PERL_constant_ISIV;
cea00dc5 317 $clause .= assign ($indent, $type, $pre, $post,
318 ref $value ? @$value : $value);
6d79cad2 319
72f7b9a1 320 if (ref $macro or $macro ne "1") {
321 ##else
322 $clause .= "#else\n";
a2c454fa 323
72f7b9a1 324 # return PERL_constant_NOTDEF;
325 if (!defined $default) {
326 $clause .= "${indent}return PERL_constant_NOTDEF;\n";
327 } else {
328 my @default = ref $default ? @$default : $default;
329 $type = shift @default;
330 $clause .= assign ($indent, $type, $def_pre, $def_post, @default);
331 }
6d79cad2 332
72f7b9a1 333 ##endif
334 if (ref $macro) {
335 $clause .= $macro->[1];
336 } else {
337 $clause .= "#endif\n";
338 }
6d79cad2 339 }
340 return $clause
af6c647e 341}
342
8ac27563 343=item switch_clause INDENT, NAMELEN, ITEMHASH, ITEM...
344
345An internal function to generate a suitable C<switch> clause, called by
346C<C_constant> I<ITEM>s are in the hash ref format as given in the description
347of C<C_constant>, and must all have the names of the same length, given by
348I<NAMELEN> (This is not checked). I<ITEMHASH> is a reference to a hash,
349keyed by name, values being the hashrefs in the I<ITEM> list.
350(No parameters are modified, and there can be keys in the I<ITEMHASH> that
351are not in the list of I<ITEM>s without causing problems).
352
353=cut
354
355sub switch_clause {
356 my ($indent, $comment, $namelen, $items, @items) = @_;
357 $indent = ' ' x ($indent || 2);
a2c454fa 358
8ac27563 359 my @names = sort map {$_->{name}} @items;
360 my $leader = $indent . '/* ';
361 my $follower = ' ' x length $leader;
362 my $body = $indent . "/* Names all of length $namelen. */\n";
363 if ($comment) {
364 $body = wrap ($leader, $follower, $comment) . "\n";
365 $leader = $follower;
366 }
367 $body .= wrap ($leader, $follower, join (" ", @names) . " */") . "\n";
368 # Figure out what to switch on.
369 # (RMS, Spread of jump table, Position, Hashref)
370 my @best = (1e38, ~0);
371 foreach my $i (0 .. ($namelen - 1)) {
372 my ($min, $max) = (~0, 0);
373 my %spread;
374 foreach (@names) {
375 my $char = substr $_, $i, 1;
376 my $ord = ord $char;
a2c454fa 377 $max = $ord if $ord > $max;
8ac27563 378 $min = $ord if $ord < $min;
379 push @{$spread{$char}}, $_;
380 # warn "$_ $char";
381 }
382 # I'm going to pick the character to split on that minimises the root
383 # mean square of the number of names in each case. Normally this should
384 # be the one with the most keys, but it may pick a 7 where the 8 has
385 # one long linear search. I'm not sure if RMS or just sum of squares is
386 # actually better.
387 # $max and $min are for the tie-breaker if the root mean squares match.
388 # Assuming that the compiler may be building a jump table for the
389 # switch() then try to minimise the size of that jump table.
390 # Finally use < not <= so that if it still ties the earliest part of
391 # the string wins. Because if that passes but the memEQ fails, it may
392 # only need the start of the string to bin the choice.
393 # I think. But I'm micro-optimising. :-)
394 my $ss;
395 $ss += @$_ * @$_ foreach values %spread;
396 my $rms = sqrt ($ss / keys %spread);
397 if ($rms < $best[0] || ($rms == $best[0] && ($max - $min) < $best[1])) {
398 @best = ($rms, $max - $min, $i, \%spread);
399 }
400 }
401 die "Internal error. Failed to pick a switch point for @names"
402 unless defined $best[2];
403 # use Data::Dumper; print Dumper (@best);
404 my ($offset, $best) = @best[2,3];
405 $body .= $indent . "/* Offset $offset gives the best switch position. */\n";
406 $body .= $indent . "switch (name[$offset]) {\n";
407 foreach my $char (sort keys %$best) {
408 $body .= $indent . "case '" . C_stringify ($char) . "':\n";
409 foreach my $name (sort @{$best->{$char}}) {
410 my $thisone = $items->{$name};
cea00dc5 411 my ($value, $macro, $default, $pre, $post, $def_pre, $def_post)
412 = @$thisone{qw (value macro default pre post def_pre def_post)};
8ac27563 413 $value = $name unless defined $value;
414 $macro = $name unless defined $macro;
415
416 # We have checked this offset.
417 $body .= memEQ_clause ($name, $offset, 2 + length $indent);
418 $body .= return_clause ($value, $thisone->{type}, 4 + length $indent,
cea00dc5 419 $macro, $default, $pre, $post,
420 $def_pre, $def_post);
8ac27563 421 $body .= $indent . " }\n";
422 }
423 $body .= $indent . " break;\n";
424 }
425 $body .= $indent . "}\n";
426 return $body;
427}
428
af6c647e 429=item params WHAT
430
431An internal function. I<WHAT> should be a hashref of types the constant
72f7b9a1 432function will return. I<params> returns a hashref keyed IV NV PV SV to show
433which combination of pointers will be needed in the C argument list.
af6c647e 434
435=cut
436
437sub params {
438 my $what = shift;
439 foreach (sort keys %$what) {
440 warn "ExtUtils::Constant doesn't know how to handle values of type $_" unless defined $XS_Constant{$_};
441 }
72f7b9a1 442 my $params = {};
443 $params->{IV} = 1 if $what->{IV} || $what->{UV} || $what->{PVN};
444 $params->{NV} = 1 if $what->{NV};
445 $params->{PV} = 1 if $what->{PV} || $what->{PVN};
446 $params->{SV} = 1 if $what->{SV};
447 return $params;
af6c647e 448}
449
a2c454fa 450=item dump_names
0addb26a 451
8ac27563 452dump_names PACKAGE, SUBNAME, DEFAULT_TYPE, TYPES, INDENT, BREAKOUT, ITEM...
6d79cad2 453
454An internal function to generate the embedded perl code that will regenerate
8ac27563 455the constant subroutines. Parameters are the same as for C_constant.
6d79cad2 456
457=cut
458
459sub dump_names {
8ac27563 460 my ($package, $subname, $default_type, $what, $indent, $breakout, @items)
461 = @_;
6d79cad2 462 my (@simple, @complex);
463 foreach (@items) {
464 my $type = $_->{type} || $default_type;
465 if ($type eq $default_type and 0 == ($_->{name} =~ tr/A-Za-z0-9_//c)
466 and !defined ($_->{macro}) and !defined ($_->{value})
cea00dc5 467 and !defined ($_->{default}) and !defined ($_->{pre})
468 and !defined ($_->{post}) and !defined ($_->{def_pre})
469 and !defined ($_->{def_post})) {
6d79cad2 470 # It's the default type, and the name consists only of A-Za-z0-9_
471 push @simple, $_->{name};
472 } else {
473 push @complex, $_;
474 }
475 }
476 my $result = <<"EOT";
477 /* When generated this function returned values for the list of names given
478 in this section of perl code. Rather than manually editing these functions
479 to add or remove constants, which would result in this comment and section
480 of code becoming inaccurate, we recommend that you edit this section of
481 code, and use it to regenerate a new set of constant functions which you
482 then use to replace the originals.
483
484 Regenerate these constant functions by feeding this entire source file to
485 perl -x
486
487#!$^X -w
488use ExtUtils::Constant qw (constant_types C_constant XS_constant);
489
490EOT
8ac27563 491 $result .= 'my $types = {map {($_, 1)} qw(' . join (" ", sort keys %$what)
492 . ")};\n";
6d79cad2 493 $result .= wrap ("my \@names = (qw(",
494 " ", join (" ", sort @simple) . ")");
495 if (@complex) {
496 foreach my $item (sort {$a->{name} cmp $b->{name}} @complex) {
497 my $name = C_stringify $item->{name};
6d79cad2 498 my $line = ",\n {name=>\"$name\"";
499 $line .= ", type=>\"$item->{type}\"" if defined $item->{type};
cea00dc5 500 foreach my $thing (qw (macro value default pre post def_pre def_post)) {
501 my $value = $item->{$thing};
502 if (defined $value) {
503 if (ref $value) {
504 $line .= ", $thing=>[\""
505 . join ('", "', map {C_stringify $_} @$value) . '"]';
506 } else {
507 $line .= ", $thing=>\"" . C_stringify($value) . "\"";
508 }
6d79cad2 509 }
510 }
511 $line .= "}";
512 # Ensure that the enclosing C comment doesn't end
513 # by turning */ into *" . "/
514 $line =~ s!\*\/!\*" . "/!gs;
3414cef0 515 # gcc -Wall doesn't like finding /* inside a comment
516 $line =~ s!\/\*!/" . "\*!gs;
6d79cad2 517 $result .= $line;
518 }
519 }
520 $result .= ");\n";
521
522 $result .= <<'EOT';
523
524print constant_types(); # macro defs
525EOT
526 $package = C_stringify($package);
527 $result .=
528 "foreach (C_constant (\"$package\", '$subname', '$default_type', \$types, ";
529 # The form of the indent parameter isn't defined. (Yet)
530 if (defined $indent) {
531 require Data::Dumper;
532 $Data::Dumper::Terse=1;
8ac27563 533 $Data::Dumper::Terse=1; # Not used once. :-)
6d79cad2 534 chomp ($indent = Data::Dumper::Dumper ($indent));
535 $result .= $indent;
536 } else {
537 $result .= 'undef';
538 }
8ac27563 539 $result .= ", $breakout" . ', @names) ) {
6d79cad2 540 print $_, "\n"; # C constant subs
541}
542print "#### XS Section:\n";
543print XS_constant ("' . $package . '", $types);
544__END__
545 */
546
547';
a2c454fa 548
6d79cad2 549 $result;
550}
551
a2c454fa 552=item C_constant
0addb26a 553
8ac27563 554C_constant PACKAGE, SUBNAME, DEFAULT_TYPE, TYPES, INDENT, BREAKOUT, ITEM...
af6c647e 555
556A function that returns a B<list> of C subroutine definitions that return
557the value and type of constants when passed the name by the XS wrapper.
558I<ITEM...> gives a list of constant names. Each can either be a string,
559which is taken as a C macro name, or a reference to a hash with the following
560keys
561
562=over 8
563
564=item name
565
566The name of the constant, as seen by the perl code.
567
568=item type
569
570The type of the constant (I<IV>, I<NV> etc)
571
572=item value
573
574A C expression for the value of the constant, or a list of C expressions if
575the type is aggregate. This defaults to the I<name> if not given.
576
577=item macro
578
579The C pre-processor macro to use in the C<#ifdef>. This defaults to the
6d79cad2 580I<name>, and is mainly used if I<value> is an C<enum>. If a reference an
581array is passed then the first element is used in place of the C<#ifdef>
582line, and the second element in place of the C<#endif>. This allows
583pre-processor constructions such as
584
585 #if defined (foo)
586 #if !defined (bar)
587 ...
588 #endif
589 #endif
590
591to be used to determine if a constant is to be defined.
592
72f7b9a1 593A "macro" 1 signals that the constant is always defined, so the C<#if>/C<#endif>
594test is omitted.
595
6d79cad2 596=item default
597
598Default value to use (instead of C<croak>ing with "your vendor has not
599defined...") to return if the macro isn't defined. Specify a reference to
600an array with type followed by value(s).
af6c647e 601
cea00dc5 602=item pre
603
604C code to use before the assignment of the value of the constant. This allows
605you to use temporary variables to extract a value from part of a C<struct>
606and return this as I<value>. This C code is places at the start of a block,
607so you can declare variables in it.
608
609=item post
610
611C code to place between the assignment of value (to a temporary) and the
612return from the function. This allows you to clear up anything in I<pre>.
613Rarely needed.
614
615=item def_pre
616=item def_post
617
618Equivalents of I<pre> and I<post> for the default value.
619
af6c647e 620=back
621
6d79cad2 622I<PACKAGE> is the name of the package, and is only used in comments inside the
623generated C code.
624
625The next 5 arguments can safely be given as C<undef>, and are mainly used
af6c647e 626for recursion. I<SUBNAME> defaults to C<constant> if undefined.
627
628I<DEFAULT_TYPE> is the type returned by C<ITEM>s that don't specify their
629type. In turn it defaults to I<IV>. I<TYPES> should be given either as a comma
630separated list of types that the C subroutine C<constant> will generate or as
631a reference to a hash. I<DEFAULT_TYPE> will be added to the list if not
632present, as will any types given in the list of I<ITEM>s. The resultant list
633should be the same list of types that C<XS_constant> is given. [Otherwise
634C<XS_constant> and C<C_constant> may differ in the number of parameters to the
635constant function. I<INDENT> is currently unused and ignored. In future it may
636be used to pass in information used to change the C indentation style used.]
637The best way to maintain consistency is to pass in a hash reference and let
638this function update it.
639
8ac27563 640I<BREAKOUT> governs when child functions of I<SUBNAME> are generated. If there
641are I<BREAKOUT> or more I<ITEM>s with the same length of name, then the code
642to switch between them is placed into a function named I<SUBNAME>_I<LEN>, for
643example C<constant_5> for names 5 characters long. The default I<BREAKOUT> is
6443. A single C<ITEM> is always inlined.
af6c647e 645
646=cut
647
8ac27563 648# The parameter now BREAKOUT was previously documented as:
649#
650# I<NAMELEN> if defined signals that all the I<name>s of the I<ITEM>s are of
651# this length, and that the constant name passed in by perl is checked and
652# also of this length. It is used during recursion, and should be C<undef>
653# unless the caller has checked all the lengths during code generation, and
654# the generated subroutine is only to be called with a name of this length.
655#
656# As you can see it now performs this function during recursion by being a
657# scalar reference.
658
af6c647e 659sub C_constant {
8ac27563 660 my ($package, $subname, $default_type, $what, $indent, $breakout, @items)
661 = @_;
6d79cad2 662 $package ||= 'Foo';
af6c647e 663 $subname ||= 'constant';
664 # I'm not using this. But a hashref could be used for full formatting without
665 # breaking this API
6d79cad2 666 # $indent ||= 0;
72f7b9a1 667
668 my ($namelen, $items);
669 if (ref $breakout) {
670 # We are called recursively. We trust @items to be normalised, $what to
671 # be a hashref, and pinch %$items from our parent to save recalculation.
672 ($namelen, $items) = @$breakout;
673 } else {
674 $breakout ||= 3;
675 $default_type ||= 'IV';
676 if (!ref $what) {
677 # Convert line of the form IV,UV,NV to hash
678 $what = {map {$_ => 1} split /,\s*/, ($what || '')};
679 # Figure out what types we're dealing with, and assign all unknowns to the
680 # default type
af6c647e 681 }
72f7b9a1 682 foreach (@items) {
683 my $name;
684 if (ref $_) {
685 my $orig = $_;
686 # Make a copy which is a normalised version of the ref passed in.
687 $name = $_->{name};
688 my ($type, $macro, $value) = @$_{qw (type macro value)};
689 $type ||= $default_type;
690 $what->{$type} = 1;
691 $_ = {name=>$name, type=>$type};
692
693 undef $macro if defined $macro and $macro eq $name;
694 $_->{macro} = $macro if defined $macro;
695 undef $value if defined $value and $value eq $name;
696 $_->{value} = $value if defined $value;
697 foreach my $key (qw(default pre post def_pre def_post)) {
698 my $value = $orig->{$key};
699 $_->{$key} = $value if defined $value;
700 # warn "$key $value";
701 }
702 } else {
703 $name = $_;
704 $_ = {name=>$_, type=>$default_type};
705 $what->{$default_type} = 1;
706 }
707 warn "ExtUtils::Constant doesn't know how to handle values of type $_ used in macro $name" unless defined $XS_Constant{$_->{type}};
708 if (exists $items->{$name}) {
709 die "Multiple definitions for macro $name";
710 }
711 $items->{$name} = $_;
af6c647e 712 }
af6c647e 713 }
72f7b9a1 714 my $params = params ($what);
af6c647e 715
a2c454fa 716 my ($body, @subs) = "static int\n$subname (pTHX_ const char *name";
af6c647e 717 $body .= ", STRLEN len" unless defined $namelen;
72f7b9a1 718 $body .= ", IV *iv_return" if $params->{IV};
719 $body .= ", NV *nv_return" if $params->{NV};
720 $body .= ", const char **pv_return" if $params->{PV};
721 $body .= ", SV **sv_return" if $params->{SV};
af6c647e 722 $body .= ") {\n";
723
6d79cad2 724 if (defined $namelen) {
725 # We are a child subroutine. Print the simple description
8ac27563 726 my $comment = 'When generated this function returned values for the list'
727 . ' of names given here. However, subsequent manual editing may have'
728 . ' added or removed some.';
72f7b9a1 729 $body .= switch_clause (2, $comment, $namelen, $items, @items);
af6c647e 730 } else {
731 # We are the top level.
732 $body .= " /* Initially switch on the length of the name. */\n";
6d79cad2 733 $body .= dump_names ($package, $subname, $default_type, $what, $indent,
8ac27563 734 $breakout, @items);
af6c647e 735 $body .= " switch (len) {\n";
736 # Need to group names of the same length
737 my @by_length;
738 foreach (@items) {
739 push @{$by_length[length $_->{name}]}, $_;
740 }
741 foreach my $i (0 .. $#by_length) {
742 next unless $by_length[$i]; # None of this length
743 $body .= " case $i:\n";
744 if (@{$by_length[$i]} == 1) {
745 my $thisone = $by_length[$i]->[0];
cea00dc5 746 my ($name, $value, $macro, $default, $pre, $post, $def_pre, $def_post)
747 = @$thisone{qw (name value macro default pre post def_pre def_post)};
af6c647e 748 $value = $name unless defined $value;
749 $macro = $name unless defined $macro;
750
751 $body .= memEQ_clause ($name);
6d79cad2 752 $body .= return_clause ($value, $thisone->{type}, undef, $macro,
cea00dc5 753 $default, $pre, $post, $def_pre, $def_post);
af6c647e 754 $body .= " }\n";
8ac27563 755 } elsif (@{$by_length[$i]} < $breakout) {
72f7b9a1 756 $body .= switch_clause (4, '', $i, $items, @{$by_length[$i]});
af6c647e 757 } else {
72f7b9a1 758 # Only use the minimal set of parameters actually needed by the types
759 # of the names of this length.
760 my $what = {};
761 foreach (@{$by_length[$i]}) {
762 $what->{$_->{type}} = 1;
763 }
764 $params = params ($what);
765 push @subs, C_constant ($package, "${subname}_$i", $default_type, $what,
766 $indent, [$i, $items], @{$by_length[$i]});
a2c454fa 767 $body .= " return ${subname}_$i (aTHX_ name";
72f7b9a1 768 $body .= ", iv_return" if $params->{IV};
769 $body .= ", nv_return" if $params->{NV};
770 $body .= ", pv_return" if $params->{PV};
771 $body .= ", sv_return" if $params->{SV};
af6c647e 772 $body .= ");\n";
773 }
774 $body .= " break;\n";
775 }
776 $body .= " }\n";
777 }
778 $body .= " return PERL_constant_NOTFOUND;\n}\n";
779 return (@subs, $body);
780}
781
782=item XS_constant PACKAGE, TYPES, SUBNAME, C_SUBNAME
783
784A function to generate the XS code to implement the perl subroutine
785I<PACKAGE>::constant used by I<PACKAGE>::AUTOLOAD to load constants.
786This XS code is a wrapper around a C subroutine usually generated by
787C<C_constant>, and usually named C<constant>.
788
789I<TYPES> should be given either as a comma separated list of types that the
790C subroutine C<constant> will generate or as a reference to a hash. It should
791be the same list of types as C<C_constant> was given.
792[Otherwise C<XS_constant> and C<C_constant> may have different ideas about
793the number of parameters passed to the C function C<constant>]
794
795You can call the perl visible subroutine something other than C<constant> if
796you give the parameter I<SUBNAME>. The C subroutine it calls defaults to the
797the name of the perl visible subroutine, unless you give the parameter
798I<C_SUBNAME>.
799
800=cut
801
802sub XS_constant {
803 my $package = shift;
804 my $what = shift;
805 my $subname = shift;
806 my $C_subname = shift;
807 $subname ||= 'constant';
808 $C_subname ||= $subname;
809
810 if (!ref $what) {
811 # Convert line of the form IV,UV,NV to hash
812 $what = {map {$_ => 1} split /,\s*/, ($what)};
813 }
72f7b9a1 814 my $params = params ($what);
af6c647e 815 my $type;
816
817 my $xs = <<"EOT";
818void
819$subname(sv)
820 PREINIT:
821#ifdef dXSTARG
822 dXSTARG; /* Faster if we have it. */
823#else
824 dTARGET;
825#endif
826 STRLEN len;
827 int type;
828EOT
829
72f7b9a1 830 if ($params->{IV}) {
af6c647e 831 $xs .= " IV iv;\n";
832 } else {
833 $xs .= " /* IV\t\tiv;\tUncomment this if you need to return IVs */\n";
834 }
72f7b9a1 835 if ($params->{NV}) {
af6c647e 836 $xs .= " NV nv;\n";
837 } else {
838 $xs .= " /* NV\t\tnv;\tUncomment this if you need to return NVs */\n";
839 }
72f7b9a1 840 if ($params->{PV}) {
af6c647e 841 $xs .= " const char *pv;\n";
842 } else {
843 $xs .=
844 " /* const char\t*pv;\tUncomment this if you need to return PVs */\n";
845 }
846
847 $xs .= << 'EOT';
848 INPUT:
849 SV * sv;
850 const char * s = SvPV(sv, len);
851 PPCODE:
852EOT
853
72f7b9a1 854 if ($params->{IV} xor $params->{NV}) {
af6c647e 855 $xs .= << "EOT";
a2c454fa 856 /* Change this to $C_subname(aTHX_ s, len, &iv, &nv);
af6c647e 857 if you need to return both NVs and IVs */
858EOT
859 }
a2c454fa 860 $xs .= " type = $C_subname(aTHX_ s, len";
72f7b9a1 861 $xs .= ', &iv' if $params->{IV};
862 $xs .= ', &nv' if $params->{NV};
863 $xs .= ', &pv' if $params->{PV};
864 $xs .= ', &sv' if $params->{SV};
af6c647e 865 $xs .= ");\n";
866
867 $xs .= << "EOT";
868 /* Return 1 or 2 items. First is error message, or undef if no error.
869 Second, if present, is found value */
870 switch (type) {
871 case PERL_constant_NOTFOUND:
872 sv = sv_2mortal(newSVpvf("%s is not a valid $package macro", s));
6d79cad2 873 PUSHs(sv);
af6c647e 874 break;
875 case PERL_constant_NOTDEF:
876 sv = sv_2mortal(newSVpvf(
8ac27563 877 "Your vendor has not defined $package macro %s, used", s));
6d79cad2 878 PUSHs(sv);
af6c647e 879 break;
880EOT
881
882 foreach $type (sort keys %XS_Constant) {
883 $xs .= "\t/* Uncomment this if you need to return ${type}s\n"
884 unless $what->{$type};
8ac27563 885 $xs .= " case PERL_constant_IS$type:\n";
886 if (length $XS_Constant{$type}) {
887 $xs .= << "EOT";
af6c647e 888 EXTEND(SP, 1);
889 PUSHs(&PL_sv_undef);
890 $XS_Constant{$type};
af6c647e 891EOT
8ac27563 892 } else {
893 # Do nothing. return (), which will be correctly interpreted as
894 # (undef, undef)
895 }
896 $xs .= " break;\n";
af6c647e 897 unless ($what->{$type}) {
898 chop $xs; # Yes, another need for chop not chomp.
899 $xs .= " */\n";
900 }
901 }
902 $xs .= << "EOT";
903 default:
904 sv = sv_2mortal(newSVpvf(
8ac27563 905 "Unexpected return type %d while processing $package macro %s, used",
af6c647e 906 type, s));
6d79cad2 907 PUSHs(sv);
af6c647e 908 }
909EOT
910
911 return $xs;
912}
913
914
6d79cad2 915=item autoload PACKAGE, VERSION, AUTOLOADER
af6c647e 916
917A function to generate the AUTOLOAD subroutine for the module I<PACKAGE>
918I<VERSION> is the perl version the code should be backwards compatible with.
6d79cad2 919It defaults to the version of perl running the subroutine. If I<AUTOLOADER>
920is true, the AUTOLOAD subroutine falls back on AutoLoader::AUTOLOAD for all
921names that the constant() routine doesn't recognise.
af6c647e 922
923=cut
924
6d79cad2 925# ' # Grr. syntax highlighters that don't grok pod.
926
af6c647e 927sub autoload {
6d79cad2 928 my ($module, $compat_version, $autoloader) = @_;
af6c647e 929 $compat_version ||= $];
930 croak "Can't maintain compatibility back as far as version $compat_version"
931 if $compat_version < 5;
6d79cad2 932 my $func = "sub AUTOLOAD {\n"
933 . " # This AUTOLOAD is used to 'autoload' constants from the constant()\n"
934 . " # XS function.";
935 $func .= " If a constant is not found then control is passed\n"
936 . " # to the AUTOLOAD in AutoLoader." if $autoloader;
937
938
939 $func .= "\n\n"
940 . " my \$constname;\n";
a2c454fa 941 $func .=
6d79cad2 942 " our \$AUTOLOAD;\n" if ($compat_version >= 5.006);
943
944 $func .= <<"EOT";
af6c647e 945 (\$constname = \$AUTOLOAD) =~ s/.*:://;
946 croak "&${module}::constant not defined" if \$constname eq 'constant';
947 my (\$error, \$val) = constant(\$constname);
6d79cad2 948EOT
949
950 if ($autoloader) {
951 $func .= <<'EOT';
952 if ($error) {
953 if ($error =~ /is not a valid/) {
954 $AutoLoader::AUTOLOAD = $AUTOLOAD;
af6c647e 955 goto &AutoLoader::AUTOLOAD;
956 } else {
6d79cad2 957 croak $error;
af6c647e 958 }
959 }
6d79cad2 960EOT
961 } else {
962 $func .=
963 " if (\$error) { croak \$error; }\n";
964 }
965
966 $func .= <<'END';
af6c647e 967 {
968 no strict 'refs';
969 # Fixed between 5.005_53 and 5.005_61
6d79cad2 970#XXX if ($] >= 5.00561) {
971#XXX *$AUTOLOAD = sub () { $val };
af6c647e 972#XXX }
973#XXX else {
6d79cad2 974 *$AUTOLOAD = sub { $val };
af6c647e 975#XXX }
976 }
6d79cad2 977 goto &$AUTOLOAD;
af6c647e 978}
979
980END
981
6d79cad2 982 return $func;
af6c647e 983}
0552bf3a 984
985
986=item WriteConstants ATTRIBUTE =E<gt> VALUE [, ...]
987
988Writes a file of C code and a file of XS code which you should C<#include>
989and C<INCLUDE> in the C and XS sections respectively of your module's XS
990code. You probaby want to do this in your C<Makefile.PL>, so that you can
991easily edit the list of constants without touching the rest of your module.
992The attributes supported are
993
994=over 4
995
996=item NAME
997
998Name of the module. This must be specified
999
1000=item DEFAULT_TYPE
1001
1002The default type for the constants. If not specified C<IV> is assumed.
1003
1004=item BREAKOUT_AT
1005
1006The names of the constants are grouped by length. Generate child subroutines
1007for each group with this number or more names in.
1008
1009=item NAMES
1010
1011An array of constants' names, either scalars containing names, or hashrefs
1012as detailed in L<"C_constant">.
1013
1014=item C_FILE
1015
1016The name of the file to write containing the C code. The default is
1017C<constants.c>.
1018
1019=item XS_FILE
1020
1021The name of the file to write containing the XS code. The default is
1022C<constants.xs>.
1023
1024=item SUBNAME
1025
1026The perl visible name of the XS subroutine generated which will return the
1027constants. The default is C<constant>.
1028
1029=item C_SUBNAME
1030
1031The name of the C subroutine generated which will return the constants.
1032The default is I<SUBNAME>. Child subroutines have C<_> and the name
1033length appended, so constants with 10 character names would be in
1034C<constant_10> with the default I<XS_SUBNAME>.
1035
1036=back
1037
1038=cut
1039
1040sub WriteConstants {
1041 my %ARGS =
1042 ( # defaults
1043 C_FILE => 'constants.c',
1044 XS_FILE => 'constants.xs',
1045 SUBNAME => 'constant',
1046 DEFAULT_TYPE => 'IV',
1047 @_);
1048
1049 $ARGS{C_SUBNAME} ||= $ARGS{SUBNAME}; # No-one sane will have C_SUBNAME eq '0'
1050
1051 croak "Module name not specified" unless length $ARGS{NAME};
1052
1053 open my $c_fh, ">$ARGS{C_FILE}" or die "Can't open $ARGS{C_FILE}: $!";
1054 open my $xs_fh, ">$ARGS{XS_FILE}" or die "Can't open $ARGS{XS_FILE}: $!";
1055
1056 # As this subroutine is intended to make code that isn't edited, there's no
1057 # need for the user to specify any types that aren't found in the list of
1058 # names.
1059 my $types = {};
1060
1061 print $c_fh constant_types(); # macro defs
1062 print $c_fh "\n";
1063
1064 # indent is still undef. Until anyone implents indent style rules with it.
1065 foreach (C_constant ($ARGS{NAME}, $ARGS{C_SUBNAME}, $ARGS{DEFAULT_TYPE},
1066 $types, undef, $ARGS{BREAKOUT_AT}, @{$ARGS{NAMES}})) {
1067 print $c_fh $_, "\n"; # C constant subs
1068 }
1069 print $xs_fh XS_constant ($ARGS{NAME}, $types, $ARGS{XS_SUBNAME},
1070 $ARGS{C_SUBNAME});
1071
1072 close $c_fh or warn "Error closing $ARGS{C_FILE}: $!";
1073 close $xs_fh or warn "Error closing $ARGS{XS_FILE}: $!";
1074}
1075
af6c647e 10761;
1077__END__
1078
1079=back
1080
1081=head1 AUTHOR
1082
1083Nicholas Clark <nick@ccl4.org> based on the code in C<h2xs> by Larry Wall and
1084others
1085
1086=cut