Add C_FH and XS_FH arguments to ExtUtils::Constant::WriteConstants,
[p5sagit/p5-mst-13.2.git] / lib / ExtUtils / t / Constant.t
1 #!/usr/bin/perl -w
2
3 BEGIN {
4     if( $ENV{PERL_CORE} ) {
5         chdir 't' if -d 't';
6         @INC = '../lib';
7     }
8     use Config;
9     unless ($Config{usedl}) {
10         print "1..0 # no usedl, skipping\n";
11         exit 0;
12     }
13 }
14
15 # use warnings;
16 use strict;
17 use ExtUtils::MakeMaker;
18 use ExtUtils::Constant qw (constant_types C_constant XS_constant autoload);
19 use File::Spec;
20 use Cwd;
21
22 my $do_utf_tests = $] > 5.006;
23 my $better_than_56 = $] > 5.007;
24 # For debugging set this to 1.
25 my $keep_files = 0;
26 $| = 1;
27
28 # Because were are going to be changing directory before running Makefile.PL
29 my $perl = $^X;
30 # 5.005 doesn't have new enough File::Spec to have rel2abs. But actually we
31 # only need it when $^X isn't absolute, which is going to be 5.8.0 or later
32 # (where ExtUtils::Constant is in the core, and tests against the uninstalled
33 # perl)
34 $perl = File::Spec->rel2abs ($perl) unless $] < 5.006;
35 # ExtUtils::Constant::C_constant uses $^X inside a comment, and we want to
36 # compare output to ensure that it is the same. We were probably run as ./perl
37 # whereas we will run the child with the full path in $perl. So make $^X for
38 # us the same as our child will see.
39 $^X = $perl;
40 my $lib = $ENV{PERL_CORE} ? '../../../lib' : '../../blib/lib';
41 my $runperl = "$perl \"-I$lib\"";
42 print "# perl=$perl\n";
43
44 my $make = $Config{make};
45 $make = $ENV{MAKE} if exists $ENV{MAKE};
46 if ($^O eq 'MSWin32' && $make eq 'nmake') { $make .= " -nologo"; }
47
48 # VMS may be using something other than MMS/MMK
49 my $mms_or_mmk = 0;
50 if ($^O eq 'VMS') {
51    $mms_or_mmk = 1 if (($make eq 'MMK') || ($make eq 'MMS'));
52 }
53
54 # Renamed by make clean
55 my $makefile = ($mms_or_mmk ? 'descrip' : 'Makefile');
56 my $makefile_ext = ($mms_or_mmk ? '.mms' : '');
57 my $makefile_rename = $makefile . ($mms_or_mmk ? '.mms_old' : '.old');
58
59 my $output = "output";
60 my $package = "ExtTest";
61 my $dir = "ext-$$";
62 my $subdir = 0;
63 # The real test counter.
64 my $realtest = 1;
65
66 my $orig_cwd = cwd;
67 my $updir = File::Spec->updir;
68 die "Can't get current directory: $!" unless defined $orig_cwd;
69
70 print "# $dir being created...\n";
71 mkdir $dir, 0777 or die "mkdir: $!\n";
72
73 END {
74   if (defined $orig_cwd and length $orig_cwd) {
75     chdir $orig_cwd or die "Can't chdir back to '$orig_cwd': $!";
76     use File::Path;
77     print "# $dir being removed...\n";
78     rmtree($dir) unless $keep_files;
79   } else {
80     # Can't get here.
81     die "cwd at start was empty, but directory '$dir' was created" if $dir;
82   }
83 }
84
85 chdir $dir or die $!;
86 push @INC, '../../lib', '../../../lib';
87
88 package TieOut;
89
90 sub TIEHANDLE {
91     my $class = shift;
92     bless(\( my $ref = ''), $class);
93 }
94
95 sub PRINT {
96     my $self = shift;
97     $$self .= join('', @_);
98 }
99
100 sub PRINTF {
101     my $self = shift;
102     $$self .= sprintf shift, @_;
103 }
104
105 sub read {
106     my $self = shift;
107     return substr($$self, 0, length($$self), '');
108 }
109
110 package main;
111
112 sub check_for_bonus_files {
113   my $dir = shift;
114   my %expect = map {($^O eq 'VMS' ? lc($_) : $_), 1} @_;
115
116   my $fail;
117   opendir DIR, $dir or die "opendir '$dir': $!";
118   while (defined (my $entry = readdir DIR)) {
119     $entry =~ s/\.$// if $^O eq 'VMS';  # delete trailing dot that indicates no extension
120     next if $expect{$entry};
121     print "# Extra file '$entry'\n";
122     $fail = 1;
123   }
124
125   closedir DIR or warn "closedir '.': $!";
126   if ($fail) {
127     print "not ok $realtest\n";
128   } else {
129     print "ok $realtest\n";
130   }
131   $realtest++;
132 }
133
134 sub build_and_run {
135   my ($tests, $expect, $files) = @_;
136   my $core = $ENV{PERL_CORE} ? ' PERL_CORE=1' : '';
137   my @perlout = `$runperl Makefile.PL $core`;
138   if ($?) {
139     print "not ok $realtest # $runperl Makefile.PL failed: $?\n";
140     print "# $_" foreach @perlout;
141     exit($?);
142   } else {
143     print "ok $realtest\n";
144   }
145   $realtest++;
146
147   if (-f "$makefile$makefile_ext") {
148     print "ok $realtest\n";
149   } else {
150     print "not ok $realtest\n";
151   }
152   $realtest++;
153
154   my @makeout;
155
156   if ($^O eq 'VMS') { $make .= ' all'; }
157
158   # Sometimes it seems that timestamps can get confused
159
160   # make failed: 256
161   # Makefile out-of-date with respect to Makefile.PL
162   # Cleaning current config before rebuilding Makefile...
163   # make -f Makefile.old clean > /dev/null 2>&1 || /bin/sh -c true
164   # ../../perl "-I../../../lib" "-I../../../lib" Makefile.PL "PERL_CORE=1"
165   # Checking if your kit is complete...                         
166   # Looks good
167   # Writing Makefile for ExtTest
168   # ==> Your Makefile has been rebuilt. <==
169   # ==> Please rerun the make command.  <==
170   # false
171
172   my $timewarp = (-M "Makefile.PL") - (-M "$makefile$makefile_ext");
173   # Convert from days to seconds
174   $timewarp *= 86400;
175   print "# Makefile.PL is $timewarp second(s) older than $makefile$makefile_ext\n";
176   if ($timewarp < 0) {
177       # Sleep for a while to catch up.
178       $timewarp = -$timewarp;
179       $timewarp+=2;
180       $timewarp = 10 if $timewarp > 10;
181       print "# Sleeping for $timewarp second(s) to try to resolve this\n";
182       sleep $timewarp;
183   }
184
185   print "# make = '$make'\n";
186   @makeout = `$make`;
187   if ($?) {
188     print "not ok $realtest # $make failed: $?\n";
189     print "# $_" foreach @makeout;
190     exit($?);
191   } else {
192     print "ok $realtest\n";
193   }
194   $realtest++;
195
196   if ($^O eq 'VMS') { $make =~ s{ all}{}; }
197
198   if ($Config{usedl}) {
199     print "ok $realtest # This is dynamic linking, so no need to make perl\n";
200   } else {
201     my $makeperl = "$make perl";
202     print "# make = '$makeperl'\n";
203     @makeout = `$makeperl`;
204     if ($?) {
205       print "not ok $realtest # $makeperl failed: $?\n";
206       print "# $_" foreach @makeout;
207       exit($?);
208     } else {
209       print "ok $realtest\n";
210     }
211   }
212   $realtest++;
213
214   my $maketest = "$make test";
215   print "# make = '$maketest'\n";
216
217   @makeout = `$maketest`;
218
219   if (open OUTPUT, "<$output") {
220     local $/; # Slurp it - faster.
221     print <OUTPUT>;
222     close OUTPUT or print "# Close $output failed: $!\n";
223   } else {
224     # Harness will report missing test results at this point.
225     print "# Open <$output failed: $!\n";
226   }
227
228   $realtest += $tests;
229   if ($?) {
230     print "not ok $realtest # $maketest failed: $?\n";
231     print "# $_" foreach @makeout;
232   } else {
233     print "ok $realtest - maketest\n";
234   }
235   $realtest++;
236
237   # -x is busted on Win32 < 5.6.1, so we emulate it.
238   my $regen;
239   if( $^O eq 'MSWin32' && $] <= 5.006001 ) {
240     open(REGENTMP, ">regentmp") or die $!;
241     open(XS, "$package.xs")     or die $!;
242     my $saw_shebang;
243     while(<XS>) {
244       $saw_shebang++ if /^#!.*/i ;
245         print REGENTMP $_ if $saw_shebang;
246     }
247     close XS;  close REGENTMP;
248     $regen = `$runperl regentmp`;
249     unlink 'regentmp';
250   }
251   else {
252     $regen = `$runperl -x $package.xs`;
253   }
254   if ($?) {
255     print "not ok $realtest # $runperl -x $package.xs failed: $?\n";
256   } else {
257     print "ok $realtest - regen\n";
258   }
259   $realtest++;
260
261   if ($expect eq $regen) {
262     print "ok $realtest - regen worked\n";
263   } else {
264     print "not ok $realtest - regen worked\n";
265     # open FOO, ">expect"; print FOO $expect;
266     # open FOO, ">regen"; print FOO $regen; close FOO;
267   }
268   $realtest++;
269
270   my $makeclean = "$make clean";
271   print "# make = '$makeclean'\n";
272   @makeout = `$makeclean`;
273   if ($?) {
274     print "not ok $realtest # $make failed: $?\n";
275     print "# $_" foreach @makeout;
276   } else {
277     print "ok $realtest\n";
278   }
279   $realtest++;
280
281   check_for_bonus_files ('.', @$files, $output, $makefile_rename, '.', '..');
282
283   rename $makefile_rename, $makefile . $makefile_ext
284     or die "Can't rename '$makefile_rename' to '$makefile$makefile_ext': $!";
285
286   unlink $output or warn "Can't unlink '$output': $!";
287
288   # Need to make distclean to remove ../../lib/ExtTest.pm
289   my $makedistclean = "$make distclean";
290   print "# make = '$makedistclean'\n";
291   @makeout = `$makedistclean`;
292   if ($?) {
293     print "not ok $realtest # $make failed: $?\n";
294     print "# $_" foreach @makeout;
295   } else {
296     print "ok $realtest\n";
297   }
298   $realtest++;
299
300   check_for_bonus_files ('.', @$files, '.', '..');
301
302   unless ($keep_files) {
303     foreach (@$files) {
304       unlink $_ or warn "unlink $_: $!";
305     }
306   }
307
308   check_for_bonus_files ('.', '.', '..');
309 }
310
311 sub Makefile_PL {
312   my $package = shift;
313   ################ Makefile.PL
314   # We really need a Makefile.PL because make test for a no dynamic linking perl
315   # will run Makefile.PL again as part of the "make perl" target.
316   my $makefilePL = "Makefile.PL";
317   open FH, ">$makefilePL" or die "open >$makefilePL: $!\n";
318   print FH <<"EOT";
319 #!$perl -w
320 use ExtUtils::MakeMaker;
321 WriteMakefile(
322               'NAME'            => "$package",
323               'VERSION_FROM'    => "$package.pm", # finds \$VERSION
324               (\$] >= 5.005 ?
325                (#ABSTRACT_FROM => "$package.pm", # XXX add this
326                 AUTHOR     => "$0") : ())
327              );
328 EOT
329
330   close FH or die "close $makefilePL: $!\n";
331   return $makefilePL;
332 }
333
334 sub MANIFEST {
335   my (@files) = @_;
336   ################ MANIFEST
337   # We really need a MANIFEST because make distclean checks it.
338   my $manifest = "MANIFEST";
339   push @files, $manifest;
340   open FH, ">$manifest" or die "open >$manifest: $!\n";
341   print FH "$_\n" foreach @files;
342   close FH or die "close $manifest: $!\n";
343   return @files;
344 }
345
346 sub write_and_run_extension {
347   my ($name, $items, $export_names, $package, $header, $testfile, $num_tests)
348     = @_;
349
350   my $c = tie *C, 'TieOut';
351   my $xs = tie *XS, 'TieOut';
352
353   ExtUtils::Constant::WriteConstants(C_FH => \*C, 
354                                      XS_FH => \*XS,
355                                      NAME => $package,
356                                      NAMES => $items,
357                                      );
358
359   my $C_code = $c->read();
360   my $XS_code = $xs->read();
361
362   undef $c;
363   undef $xs;
364
365   untie *C;
366   untie *XS;
367
368   my $expect = $C_code . "\n#### XS Section:\n" . $XS_code;
369
370   print "# $name\n# $dir/$subdir being created...\n";
371   mkdir $subdir, 0777 or die "mkdir: $!\n";
372   chdir $subdir or die $!;
373
374   my @files;
375
376   ################ Header
377   my $header_name = "test.h";
378   push @files, $header_name;
379   open FH, ">$header_name" or die "open >$header_name: $!\n";
380   print FH $header or die $!;
381   close FH or die "close $header_name: $!\n";
382
383   ################ XS
384   my $xs_name = "$package.xs";
385   push @files, $xs_name;
386   open FH, ">$xs_name" or die "open >$xs_name: $!\n";
387
388   print FH <<"EOT";
389 #include "EXTERN.h"
390 #include "perl.h"
391 #include "XSUB.h"
392 #include "$header_name"
393
394
395 $C_code
396 MODULE = $package               PACKAGE = $package
397 PROTOTYPES: ENABLE
398 $XS_code;
399 EOT
400
401   close FH or die "close $xs: $!\n";
402
403   ################ PM
404   my $pm = "$package.pm";
405   push @files, $pm;
406   open FH, ">$pm" or die "open >$pm: $!\n";
407   print FH "package $package;\n";
408   print FH "use $];\n";
409
410   print FH <<'EOT';
411
412 use strict;
413 EOT
414   printf FH "use warnings;\n" unless $] < 5.006;
415   print FH <<'EOT';
416 use Carp;
417
418 require Exporter;
419 require DynaLoader;
420 use vars qw ($VERSION @ISA @EXPORT_OK $AUTOLOAD);
421
422 $VERSION = '0.01';
423 @ISA = qw(Exporter DynaLoader);
424 EOT
425   # Having this qw( in the here doc confuses cperl mode far too much to be
426   # helpful. And I'm using cperl mode to edit this, even if you're not :-)
427   print FH "\@EXPORT_OK = qw(\n";
428
429   # Print the names of all our autoloaded constants
430   print FH "\t$_\n" foreach (@$export_names);
431   print FH ");\n";
432   # Print the AUTOLOAD subroutine ExtUtils::Constant generated for us
433   print FH autoload ($package, $]);
434   print FH "bootstrap $package \$VERSION;\n1;\n__END__\n";
435   close FH or die "close $pm: $!\n";
436
437   ################ test.pl
438   my $testpl = "test.pl";
439   push @files, $testpl;
440   open FH, ">$testpl" or die "open >$testpl: $!\n";
441   # Standard test header (need an option to suppress this?)
442   print FH <<"EOT" or die $!;
443 use strict;
444 use $package qw(@$export_names);
445
446 print "1..2\n";
447 if (open OUTPUT, ">$output") {
448   print "ok 1\n";
449   select OUTPUT;
450 } else {
451   print "not ok 1 # Failed to open '$output': \$!\n";
452   exit 1;
453 }
454 EOT
455   print FH $testfile or die $!;
456   print FH <<"EOT" or die $!;
457 select STDOUT;
458 if (close OUTPUT) {
459   print "ok 2\n";
460 } else {
461   print "not ok 2 # Failed to close '$output': \$!\n";
462 }
463 EOT
464   close FH or die "close $testpl: $!\n";
465
466   push @files, Makefile_PL($package);
467   @files = MANIFEST (@files);
468
469   build_and_run ($num_tests, $expect, \@files);
470
471   chdir $updir or die "chdir '$updir': $!";
472   ++$subdir;
473 }
474
475 # Tests are arrayrefs of the form
476 # $name, [items], [export_names], $package, $header, $testfile, $num_tests
477 my @tests;
478 my $before_tests = 4; # Number of "ok"s emitted to build extension
479 my $after_tests = 8; # Number of "ok"s emitted after make test run
480 my $dummytest = 1;
481
482 my $here;
483 sub start_tests {
484   $dummytest += $before_tests;
485   $here = $dummytest;
486 }
487 sub end_tests {
488   my ($name, $items, $export_names, $header, $testfile) = @_;
489   push @tests, [$name, $items, $export_names, $package, $header, $testfile,
490                $dummytest - $here];
491   $dummytest += $after_tests;
492 }
493
494 my $pound;
495 if (ord('A') == 193) {  # EBCDIC platform
496   $pound = chr 177; # A pound sign. (Currency)
497 } else { # ASCII platform
498   $pound = chr 163; # A pound sign. (Currency)
499 }
500 my @common_items = (
501                     {name=>"perl", type=>"PV",},
502                     {name=>"*/", type=>"PV", value=>'"CLOSE"', macro=>1},
503                     {name=>"/*", type=>"PV", value=>'"OPEN"', macro=>1},
504                     {name=>$pound, type=>"PV", value=>'"Sterling"', macro=>1},
505                    );
506
507 {
508   # Simple tests
509   start_tests();
510   my $parent_rfc1149 =
511     'A Standard for the Transmission of IP Datagrams on Avian Carriers';
512   # Test the code that generates 1 and 2 letter name comparisons.
513   my %compass = (
514                  N => 0, 'NE' => 45, E => 90, SE => 135,
515                  S => 180, SW => 225, W => 270, NW => 315
516                 );
517
518   my $header = << "EOT";
519 #define FIVE 5
520 #define OK6 "ok 6\\n"
521 #define OK7 1
522 #define FARTHING 0.25
523 #define NOT_ZERO 1
524 #define Yes 0
525 #define No 1
526 #define Undef 1
527 #define RFC1149 "$parent_rfc1149"
528 #undef NOTDEF
529 #define perl "rules"
530 EOT
531
532   while (my ($point, $bearing) = each %compass) {
533     $header .= "#define $point $bearing\n"
534   }
535
536   my @items = ("FIVE", {name=>"OK6", type=>"PV",},
537                {name=>"OK7", type=>"PVN",
538                 value=>['"not ok 7\\n\\0ok 7\\n"', 15]},
539                {name => "FARTHING", type=>"NV"},
540                {name => "NOT_ZERO", type=>"UV", value=>"~(UV)0"},
541                {name => "OPEN", type=>"PV", value=>'"/*"', macro=>1},
542                {name => "CLOSE", type=>"PV", value=>'"*/"',
543                 macro=>["#if 1\n", "#endif\n"]},
544                {name => "ANSWER", default=>["UV", 42]}, "NOTDEF",
545                {name => "Yes", type=>"YES"},
546                {name => "No", type=>"NO"},
547                {name => "Undef", type=>"UNDEF"},
548   # OK. It wasn't really designed to allow the creation of dual valued
549   # constants.
550   # It was more for INADDR_ANY INADDR_BROADCAST INADDR_LOOPBACK INADDR_NONE
551                {name=>"RFC1149", type=>"SV", value=>"sv_2mortal(temp_sv)",
552                 pre=>"SV *temp_sv = newSVpv(RFC1149, 0); "
553                 . "(void) SvUPGRADE(temp_sv,SVt_PVIV); SvIOK_on(temp_sv); "
554                 . "SvIV_set(temp_sv, 1149);"},
555               );
556
557   push @items, $_ foreach keys %compass;
558
559   # Automatically compile the list of all the macro names, and make them
560   # exported constants.
561   my @export_names = map {(ref $_) ? $_->{name} : $_} @items;
562
563   # Exporter::Heavy (currently) isn't able to export the last 3 of these:
564   push @items, @common_items;
565
566   # XXX there are hardwired still.
567   my $test_body = <<'EOT';
568 # What follows goes to the temporary file.
569 # IV
570 my $five = FIVE;
571 if ($five == 5) {
572   print "ok 5\n";
573 } else {
574   print "not ok 5 # \$five\n";
575 }
576
577 # PV
578 print OK6;
579
580 # PVN containing embedded \0s
581 $_ = OK7;
582 s/.*\0//s;
583 print;
584
585 # NV
586 my $farthing = FARTHING;
587 if ($farthing == 0.25) {
588   print "ok 8\n";
589 } else {
590   print "not ok 8 # $farthing\n";
591 }
592
593 # UV
594 my $not_zero = NOT_ZERO;
595 if ($not_zero > 0 && $not_zero == ~0) {
596   print "ok 9\n";
597 } else {
598   print "not ok 9 # \$not_zero=$not_zero ~0=" . (~0) . "\n";
599 }
600
601 # Value includes a "*/" in an attempt to bust out of a C comment.
602 # Also tests custom cpp #if clauses
603 my $close = CLOSE;
604 if ($close eq '*/') {
605   print "ok 10\n";
606 } else {
607   print "not ok 10 # \$close='$close'\n";
608 }
609
610 # Default values if macro not defined.
611 my $answer = ANSWER;
612 if ($answer == 42) {
613   print "ok 11\n";
614 } else {
615   print "not ok 11 # What do you get if you multiply six by nine? '$answer'\n";
616 }
617
618 # not defined macro
619 my $notdef = eval { NOTDEF; };
620 if (defined $notdef) {
621   print "not ok 12 # \$notdef='$notdef'\n";
622 } elsif ($@ !~ /Your vendor has not defined ExtTest macro NOTDEF/) {
623   print "not ok 12 # \$@='$@'\n";
624 } else {
625   print "ok 12\n";
626 }
627
628 # not a macro
629 my $notthere = eval { &ExtTest::NOTTHERE; };
630 if (defined $notthere) {
631   print "not ok 13 # \$notthere='$notthere'\n";
632 } elsif ($@ !~ /NOTTHERE is not a valid ExtTest macro/) {
633   chomp $@;
634   print "not ok 13 # \$@='$@'\n";
635 } else {
636   print "ok 13\n";
637 }
638
639 # Truth
640 my $yes = Yes;
641 if ($yes) {
642   print "ok 14\n";
643 } else {
644   print "not ok 14 # $yes='\$yes'\n";
645 }
646
647 # Falsehood
648 my $no = No;
649 if (defined $no and !$no) {
650   print "ok 15\n";
651 } else {
652   print "not ok 15 # \$no=" . defined ($no) ? "'$no'\n" : "undef\n";
653 }
654
655 # Undef
656 my $undef = Undef;
657 unless (defined $undef) {
658   print "ok 16\n";
659 } else {
660   print "not ok 16 # \$undef='$undef'\n";
661 }
662
663 # invalid macro (chosen to look like a mix up between No and SW)
664 $notdef = eval { &ExtTest::So };
665 if (defined $notdef) {
666   print "not ok 17 # \$notdef='$notdef'\n";
667 } elsif ($@ !~ /^So is not a valid ExtTest macro/) {
668   print "not ok 17 # \$@='$@'\n";
669 } else {
670   print "ok 17\n";
671 }
672
673 # invalid defined macro
674 $notdef = eval { &ExtTest::EW };
675 if (defined $notdef) {
676   print "not ok 18 # \$notdef='$notdef'\n";
677 } elsif ($@ !~ /^EW is not a valid ExtTest macro/) {
678   print "not ok 18 # \$@='$@'\n";
679 } else {
680   print "ok 18\n";
681 }
682
683 my %compass = (
684 EOT
685
686 while (my ($point, $bearing) = each %compass) {
687   $test_body .= "'$point' => $bearing, "
688 }
689
690 $test_body .= <<'EOT';
691
692 );
693
694 my $fail;
695 while (my ($point, $bearing) = each %compass) {
696   my $val = eval $point;
697   if ($@) {
698     print "# $point: \$@='$@'\n";
699     $fail = 1;
700   } elsif (!defined $bearing) {
701     print "# $point: \$val=undef\n";
702     $fail = 1;
703   } elsif ($val != $bearing) {
704     print "# $point: \$val=$val, not $bearing\n";
705     $fail = 1;
706   }
707 }
708 if ($fail) {
709   print "not ok 19\n";
710 } else {
711   print "ok 19\n";
712 }
713
714 EOT
715
716 $test_body .= <<"EOT";
717 my \$rfc1149 = RFC1149;
718 if (\$rfc1149 ne "$parent_rfc1149") {
719   print "not ok 20 # '\$rfc1149' ne '$parent_rfc1149'\n";
720 } else {
721   print "ok 20\n";
722 }
723
724 if (\$rfc1149 != 1149) {
725   printf "not ok 21 # %d != 1149\n", \$rfc1149;
726 } else {
727   print "ok 21\n";
728 }
729
730 EOT
731
732 $test_body .= <<'EOT';
733 # test macro=>1
734 my $open = OPEN;
735 if ($open eq '/*') {
736   print "ok 22\n";
737 } else {
738   print "not ok 22 # \$open='$open'\n";
739 }
740 EOT
741 $dummytest+=18;
742
743   end_tests("Simple tests", \@items, \@export_names, $header, $test_body);
744 }
745
746 if ($do_utf_tests) {
747   # utf8 tests
748   start_tests();
749   my ($inf, $pound_bytes, $pound_utf8);
750
751   $inf = chr 0x221E;
752   # Check that we can distiguish the pathological case of a string, and the
753   # utf8 representation of that string.
754   $pound_utf8 = $pound . '1';
755   if ($better_than_56) {
756     $pound_bytes = $pound_utf8;
757     utf8::encode ($pound_bytes);
758   } else {
759     # Must have that "U*" to generate a zero length UTF string that forces
760     # top bit set chars (such as the pound sign) into UTF8, so that the
761     # unpack 'C*' then gets the byte form of the UTF8.
762     $pound_bytes =  pack 'C*', unpack 'C*', $pound_utf8 . pack "U*";
763   }
764
765   my @items = (@common_items,
766                {name=>$inf, type=>"PV", value=>'"Infinity"', macro=>1},
767                {name=>$pound_utf8, type=>"PV", value=>'"1 Pound"', macro=>1},
768                {name=>$pound_bytes, type=>"PV", value=>'"1 Pound (as bytes)"',
769                 macro=>1},
770               );
771
772 =pod
773
774 The above set of names seems to produce a suitably bad set of compile
775 problems on a Unicode naive version of ExtUtils::Constant (ie 0.11):
776
777 nick@thinking-cap 15439-32-utf$ PERL_CORE=1 ./perl lib/ExtUtils/t/Constant.t
778 1..33
779 # perl=/stuff/perl5/15439-32-utf/perl
780 # ext-30370 being created...
781 Wide character in print at lib/ExtUtils/t/Constant.t line 140.
782 ok 1
783 ok 2
784 # make = 'make'
785 ExtTest.xs: In function `constant_1':
786 ExtTest.xs:80: warning: multi-character character constant
787 ExtTest.xs:80: warning: case value out of range
788 ok 3
789
790 =cut
791
792 # Grr `
793
794   # Do this in 7 bit in case someone is testing with some settings that cause
795   # 8 bit files incapable of storing this character.
796   my @values
797     = map {"'" . join (",", unpack "U*", $_ . pack "U*") . "'"}
798       ($pound, $inf, $pound_bytes, $pound_utf8);
799   # Values is a list of strings, such as ('194,163,49', '163,49')
800
801   my $test_body .= "my \$test = $dummytest;\n";
802   $dummytest += 7 * 3; # 3 tests for each of the 7 things:
803
804   $test_body .= << 'EOT';
805
806 use utf8;
807 my $better_than_56 = $] > 5.007;
808
809 my ($pound, $inf, $pound_bytes, $pound_utf8) = map {eval "pack 'U*', $_"}
810 EOT
811
812   $test_body .= join ",", @values;
813
814   $test_body .= << 'EOT';
815 ;
816
817 foreach (["perl", "rules", "rules"],
818          ["/*", "OPEN", "OPEN"],
819          ["*/", "CLOSE", "CLOSE"],
820          [$pound, 'Sterling', []],
821          [$inf, 'Infinity', []],
822          [$pound_utf8, '1 Pound', '1 Pound (as bytes)'],
823          [$pound_bytes, '1 Pound (as bytes)', []],
824         ) {
825   # Flag an expected error with a reference for the expect string.
826   my ($string, $expect, $expect_bytes) = @$_;
827   (my $name = $string) =~ s/([^ -~])/sprintf '\x{%X}', ord $1/ges;
828   print "# \"$name\" => \'$expect\'\n";
829   # Try to force this to be bytes if possible.
830   if ($better_than_56) {
831     utf8::downgrade ($string, 1);
832   } else {
833     if ($string =~ tr/0-\377// == length $string) {
834       # No chars outside range 0-255
835       $string = pack 'C*', unpack 'U*', ($string . pack 'U*');
836     }
837   }
838 EOT
839
840   $test_body .=  "my (\$error, \$got) = ${package}::constant (\$string);\n";
841
842   $test_body .= <<'EOT';
843   if ($error or $got ne $expect) {
844     print "not ok $test # error '$error', got '$got'\n";
845   } else {
846     print "ok $test\n";
847   }
848   $test++;
849   print "# Now upgrade '$name' to utf8\n";
850   if ($better_than_56) {
851     utf8::upgrade ($string);
852   } else {
853     $string = pack ('U*') . $string;
854   }
855 EOT
856
857   $test_body .=  "my (\$error, \$got) = ${package}::constant (\$string);\n";
858
859   $test_body .= <<'EOT';
860   if ($error or $got ne $expect) {
861     print "not ok $test # error '$error', got '$got'\n";
862   } else {
863     print "ok $test\n";
864   }
865   $test++;
866   if (defined $expect_bytes) {
867     print "# And now with the utf8 byte sequence for name\n";
868     # Try the encoded bytes.
869     if ($better_than_56) {
870       utf8::encode ($string);
871     } else {
872       $string = pack 'C*', unpack 'C*', $string . pack "U*";
873     }
874 EOT
875
876     $test_body .= "my (\$error, \$got) = ${package}::constant (\$string);\n";
877
878     $test_body .= <<'EOT';
879     if (ref $expect_bytes) {
880       # Error expected.
881       if ($error) {
882         print "ok $test # error='$error' (as expected)\n";
883       } else {
884         print "not ok $test # expected error, got no error and '$got'\n";
885       }
886     } elsif ($got ne $expect_bytes) {
887       print "not ok $test # error '$error', expect '$expect_bytes', got '$got'\n";
888     } else {
889       print "ok $test\n";
890     }
891     $test++;
892   }
893 }
894 EOT
895
896   end_tests("utf8 tests", \@items, [], "#define perl \"rules\"\n", $test_body);
897 }
898
899 # XXX I think that I should merge this into the utf8 test above.
900 sub explict_call_constant {
901   my ($string, $expect) = @_;
902   # This does assume simple strings suitable for ''
903   my $test_body = <<"EOT";
904 {
905   my (\$error, \$got) = ${package}::constant ('$string');\n;
906 EOT
907
908   if (defined $expect) {
909     # No error expected
910     $test_body .= <<"EOT";
911   if (\$error or \$got ne "$expect") {
912     print "not ok $dummytest # error '\$error', expect '$expect', got '\$got'\n";
913   } else {
914     print "ok $dummytest\n";
915     }
916   }
917 EOT
918   } else {
919     # Error expected.
920     $test_body .= <<"EOT";
921   if (\$error) {
922     print "ok $dummytest # error='\$error' (as expected)\n";
923   } else {
924     print "not ok $dummytest # expected error, got no error and '\$got'\n";
925   }
926 EOT
927   }
928   $dummytest++;
929   return $test_body . <<'EOT';
930 }
931 EOT
932 }
933
934 # Simple tests to verify bits of the switch generation system work.
935 sub simple {
936   start_tests();
937   # Deliberately leave $name in @_, so that it is indexed from 1.
938   my ($name, @items) = @_;
939   my $test_header;
940   my $test_body = "my \$value;\n";
941   foreach my $counter (1 .. $#_) {
942     my $thisname = $_[$counter];
943     $test_header .= "#define $thisname $counter\n";
944     $test_body .= <<"EOT";
945 \$value = $thisname;
946 if (\$value == $counter) {
947   print "ok $dummytest\n";
948 } else {
949   print "not ok $dummytest # $thisname gave \$value\n";
950 }
951 EOT
952     ++$dummytest;
953     # Yes, the last time round the loop appends a z to the string.
954     for my $i (0 .. length $thisname) {
955       my $copyname = $thisname;
956       substr ($copyname, $i, 1) = 'z';
957       $test_body .= explict_call_constant ($copyname,
958                                            $copyname eq $thisname
959                                              ? $thisname : undef);
960     }
961   }
962   # Ho. This seems to be buggy in 5.005_03:
963   # # Now remove $name from @_:
964   # shift @_;
965   end_tests($name, \@items, \@items, $test_header, $test_body);
966 }
967
968 # Check that the memeq clauses work correctly when there isn't a switch
969 # statement to bump off a character
970 simple ("Singletons", "A", "AB", "ABC", "ABCD", "ABCDE");
971 # Check the three code.
972 simple ("Three start", qw(Bea kea Lea lea nea pea rea sea tea Wea yea Zea));
973 # There were 162 2 letter words in /usr/share/dict/words on FreeBSD 4.6, which
974 # I felt was rather too many. So I used words with 2 vowels.
975 simple ("Twos and three middle", qw(aa ae ai ea eu ie io oe era eta));
976 # Given the choice go for the end, else the earliest point
977 simple ("Three end and four symetry", qw(ean ear eat barb marm tart));
978
979
980 # Need this if the single test below is rolled into @tests :
981 # --$dummytest;
982 print "1..$dummytest\n";
983
984 write_and_run_extension @$_ foreach @tests;
985
986 # This was causing an assertion failure (a C<confess>ion)
987 # Any single byte > 128 should do it.
988 C_constant ($package, undef, undef, undef, undef, undef, chr 255);
989 print "ok $realtest\n"; $realtest++;
990
991 print STDERR "# You were running with \$keep_files set to $keep_files\n"
992   if $keep_files;