At least, fix the MakeMaker build_man tests.
[p5sagit/p5-mst-13.2.git] / lib / ExtUtils / Constant / ProxySubs.pm
1 package ExtUtils::Constant::ProxySubs;
2
3 use strict;
4 use vars qw($VERSION @ISA %type_to_struct %type_from_struct %type_to_sv
5             %type_to_C_value %type_is_a_problem %type_num_args
6             %type_temporary);
7 use Carp;
8 require ExtUtils::Constant::XS;
9 use ExtUtils::Constant::Utils qw(C_stringify);
10 use ExtUtils::Constant::XS qw(%XS_TypeSet);
11
12 $VERSION = '0.03';
13 @ISA = 'ExtUtils::Constant::XS';
14
15 %type_to_struct =
16     (
17      IV => '{const char *name; I32 namelen; IV value;}',
18      NV => '{const char *name; I32 namelen; NV value;}',
19      UV => '{const char *name; I32 namelen; UV value;}',
20      PV => '{const char *name; I32 namelen; const char *value;}',
21      PVN => '{const char *name; I32 namelen; const char *value; STRLEN len;}',
22      YES => '{const char *name; I32 namelen;}',
23      NO => '{const char *name; I32 namelen;}',
24      UNDEF => '{const char *name; I32 namelen;}',
25      '' => '{const char *name; I32 namelen;} ',
26      );
27
28 %type_from_struct =
29     (
30      IV => sub { $_[0] . '->value' },
31      NV => sub { $_[0] . '->value' },
32      UV => sub { $_[0] . '->value' },
33      PV => sub { $_[0] . '->value' },
34      PVN => sub { $_[0] . '->value', $_[0] . '->len' },
35      YES => sub {},
36      NO => sub {},
37      UNDEF => sub {},
38      '' => sub {},
39     );
40
41 %type_to_sv = 
42     (
43      IV => sub { "newSViv($_[0])" },
44      NV => sub { "newSVnv($_[0])" },
45      UV => sub { "newSVuv($_[0])" },
46      PV => sub { "newSVpv($_[0], 0)" },
47      PVN => sub { "newSVpvn($_[0], $_[1])" },
48      YES => sub { '&PL_sv_yes' },
49      NO => sub { '&PL_sv_no' },
50      UNDEF => sub { '&PL_sv_undef' },
51      '' => sub { '&PL_sv_yes' },
52      SV => sub {"SvREFCNT_inc($_[0])"},
53      );
54
55 %type_to_C_value = 
56     (
57      YES => sub {},
58      NO => sub {},
59      UNDEF => sub {},
60      '' => sub {},
61      );
62
63 sub type_to_C_value {
64     my ($self, $type) = @_;
65     return $type_to_C_value{$type} || sub {return map {ref $_ ? @$_ : $_} @_};
66 }
67
68 # TODO - figure out if there is a clean way for the type_to_sv code to
69 # attempt s/sv_2mortal// and if it succeeds tell type_to_sv not to add
70 # SvREFCNT_inc
71 %type_is_a_problem =
72     (
73      # The documentation says *mortal SV*, but we now need a non-mortal copy.
74      SV => 1,
75      );
76
77 %type_temporary =
78     (
79      SV => ['SV *'],
80      PV => ['const char *'],
81      PVN => ['const char *', 'STRLEN'],
82      );
83 $type_temporary{$_} = [$_] foreach qw(IV UV NV);
84      
85 while (my ($type, $value) = each %XS_TypeSet) {
86     $type_num_args{$type}
87         = defined $value ? ref $value ? scalar @$value : 1 : 0;
88 }
89 $type_num_args{''} = 0;
90
91 sub partition_names {
92     my ($self, $default_type, @items) = @_;
93     my (%found, @notfound, @trouble);
94
95     while (my $item = shift @items) {
96         my $default = delete $item->{default};
97         if ($default) {
98             # If we find a default value, convert it into a regular item and
99             # append it to the queue of items to process
100             my $default_item = {%$item};
101             $default_item->{invert_macro} = 1;
102             $default_item->{pre} = delete $item->{def_pre};
103             $default_item->{post} = delete $item->{def_post};
104             $default_item->{type} = shift @$default;
105             $default_item->{value} = $default;
106             push @items, $default_item;
107         } else {
108             # It can be "not found" unless it's the default (invert the macro)
109             # or the "macro" is an empty string (ie no macro)
110             push @notfound, $item unless $item->{invert_macro}
111                 or !$self->macro_to_ifdef($self->macro_from_item($item));
112         }
113
114         if ($item->{pre} or $item->{post} or $item->{not_constant}
115             or $type_is_a_problem{$item->{type}}) {
116             push @trouble, $item;
117         } else {
118             push @{$found{$item->{type}}}, $item;
119         }
120     }
121     # use Data::Dumper; print Dumper \%found;
122     (\%found, \@notfound, \@trouble);
123 }
124
125 sub boottime_iterator {
126     my ($self, $type, $iterator, $hash, $subname) = @_;
127     my $extractor = $type_from_struct{$type};
128     die "Can't find extractor code for type $type"
129         unless defined $extractor;
130     my $generator = $type_to_sv{$type};
131     die "Can't find generator code for type $type"
132         unless defined $generator;
133
134     my $athx = $self->C_constant_prefix_param();
135
136     return sprintf <<"EOBOOT", &$generator(&$extractor($iterator));
137         while ($iterator->name) {
138             $subname($athx $hash, $iterator->name,
139                                 $iterator->namelen, %s);
140             ++$iterator;
141         }
142 EOBOOT
143 }
144
145 sub name_len_value_macro {
146     my ($self, $item) = @_;
147     my $name = $item->{name};
148     my $value = $item->{value};
149     $value = $item->{name} unless defined $value;
150
151     my $namelen = length $name;
152     if ($name =~ tr/\0-\377// != $namelen) {
153         # the hash API signals UTF-8 by passing the length negated.
154         utf8::encode($name);
155         $namelen = -length $name;
156     }
157     $name = C_stringify($name);
158
159     my $macro = $self->macro_from_item($item);
160     ($name, $namelen, $value, $macro);
161 }
162
163 sub WriteConstants {
164     my $self = shift;
165     my $ARGS = {@_};
166
167     my ($c_fh, $xs_fh, $c_subname, $xs_subname, $default_type, $package)
168         = @{$ARGS}{qw(C_FH XS_FH C_SUBNAME XS_SUBNAME DEFAULT_TYPE NAME)};
169
170     my $options = $ARGS->{PROXYSUBS};
171     $options = {} unless ref $options;
172     my $explosives = $options->{croak_on_read};
173
174     $xs_subname ||= 'constant';
175
176     # If anyone is insane enough to suggest a package name containing %
177     my $package_sprintf_safe = $package;
178     $package_sprintf_safe =~ s/%/%%/g;
179
180     # All the types we see
181     my $what = {};
182     # A hash to lookup items with.
183     my $items = {};
184
185     my @items = $self->normalise_items ({disable_utf8_duplication => 1},
186                                         $default_type, $what, $items,
187                                         @{$ARGS->{NAMES}});
188
189     # Partition the values by type. Also include any defaults in here
190     # Everything that doesn't have a default needs alternative code for
191     # "I'm missing"
192     # And everything that has pre or post code ends up in a private block
193     my ($found, $notfound, $trouble)
194         = $self->partition_names($default_type, @items);
195
196     my $pthx = $self->C_constant_prefix_param_defintion();
197     my $athx = $self->C_constant_prefix_param();
198     my $symbol_table = C_stringify($package) . '::';
199
200     print $c_fh $self->header(), <<"EOADD";
201 static void
202 ${c_subname}_add_symbol($pthx HV *hash, const char *name, I32 namelen, SV *value) {
203     SV **sv = hv_fetch(hash, name, namelen, TRUE);
204     if (!sv) {
205         Perl_croak($athx "Couldn't add key '%s' to %%$package_sprintf_safe\::",
206                    name);
207     }
208     if (SvOK(*sv) || SvTYPE(*sv) == SVt_PVGV) {
209         /* Someone has been here before us - have to make a real sub.  */
210         newCONSTSUB(hash, name, value);
211     } else {
212         SvUPGRADE(*sv, SVt_RV);
213         SvRV_set(*sv, value);
214         SvROK_on(*sv);
215         SvREADONLY_on(value);
216     }
217 }
218
219 EOADD
220
221     print $c_fh $explosives ? <<"EXPLODE" : <<"DONT";
222
223 static int
224 Im_sorry_Dave(pTHX_ SV *sv, MAGIC *mg)
225 {
226     PERL_UNUSED_ARG(mg);
227     Perl_croak(aTHX_
228                "Your vendor has not defined $package_sprintf_safe macro %"SVf
229                " used", sv);
230     NORETURN_FUNCTION_END;
231 }
232
233 static MGVTBL not_defined_vtbl = {
234  Im_sorry_Dave, /* get - I'm afraid I can't do that */
235  Im_sorry_Dave, /* set */
236  0, /* len */
237  0, /* clear */
238  0, /* free */
239  0, /* copy */
240  0, /* dup */
241 };
242
243 EXPLODE
244
245 #ifndef SYMBIAN
246 static HV *${c_subname}_missing = NULL;
247 #endif
248
249 DONT
250
251     print $xs_fh <<"EOBOOT";
252 BOOT:
253   {
254 #ifdef dTHX
255     dTHX;
256 #endif
257     HV *symbol_table = get_hv("$symbol_table", TRUE);
258 EOBOOT
259
260     my %iterator;
261
262     $found->{''}
263         = [map {{%$_, type=>'', invert_macro => 1}} @$notfound];
264
265     foreach my $type (sort keys %$found) {
266         my $struct = $type_to_struct{$type};
267         my $type_to_value = $self->type_to_C_value($type);
268         my $number_of_args = $type_num_args{$type};
269         die "Can't find structure definition for type $type"
270             unless defined $struct;
271
272         my $struct_type = $type ? lc($type) . '_s' : 'notfound_s';
273         print $c_fh "struct $struct_type $struct;\n";
274
275         my $array_name = 'values_for_' . ($type ? lc $type : 'notfound');
276         print $xs_fh <<"EOBOOT";
277
278     static const struct $struct_type $array_name\[] =
279       {
280 EOBOOT
281
282
283         foreach my $item (@{$found->{$type}}) {
284             my ($name, $namelen, $value, $macro)
285                  = $self->name_len_value_macro($item);
286
287             my $ifdef = $self->macro_to_ifdef($macro);
288             if (!$ifdef && $item->{invert_macro}) {
289                 carp("Attempting to supply a default for '$name' which has no conditional macro");
290                 next;
291             }
292             print $xs_fh $ifdef;
293             if ($item->{invert_macro}) {
294                 print $xs_fh
295                     "        /* This is the default value: */\n" if $type;
296                 print $xs_fh "#else\n";
297             }
298             print $xs_fh "        { ", join (', ', "\"$name\"", $namelen,
299                                              &$type_to_value($value)), " },\n",
300                                                  $self->macro_to_endif($macro);
301         }
302
303
304     # Terminate the list with a NULL
305         print $xs_fh "        { NULL, 0", (", 0" x $number_of_args), " } };\n";
306
307         $iterator{$type} = "value_for_" . ($type ? lc $type : 'notfound');
308
309         print $xs_fh <<"EOBOOT";
310         const struct $struct_type *$iterator{$type} = $array_name;
311
312 EOBOOT
313     }
314
315     delete $found->{''};
316
317     my $add_symbol_subname = $c_subname . '_add_symbol';
318     foreach my $type (sort keys %$found) {
319         print $xs_fh $self->boottime_iterator($type, $iterator{$type}, 
320                                               'symbol_table',
321                                               $add_symbol_subname);
322     }
323     print $xs_fh $explosives ? "\n" : <<"EOBOOT";
324 #ifndef SYMBIAN
325         ${c_subname}_missing = newHV();
326 #endif
327 EOBOOT
328
329     print $xs_fh <<"EOBOOT";
330         while (value_for_notfound->name) {
331 EOBOOT
332
333     print $xs_fh $explosives ? <<"EXPLODE" : << "DONT";
334             SV *tripwire = newSV(0);
335             
336             sv_magicext(tripwire, 0, PERL_MAGIC_ext, &not_defined_vtbl, 0, 0);
337             SvPV_set(tripwire, (char *)value_for_notfound->name);
338             if(value_for_notfound->namelen >= 0) {
339                 SvCUR_set(tripwire, value_for_notfound->namelen);
340             } else {
341                 SvCUR_set(tripwire, -value_for_notfound->namelen);
342                 SvUTF8_on(tripwire);
343             }
344             SvPOKp_on(tripwire);
345             SvREADONLY_on(tripwire);
346             assert(SvLEN(tripwire) == 0);
347
348             $add_symbol_subname($athx symbol_table, value_for_notfound->name,
349                                 value_for_notfound->namelen, tripwire);
350 EXPLODE
351
352             /* Need to add prototypes, else parsing will vary by platform.  */
353             SV **sv = hv_fetch(symbol_table, value_for_notfound->name,
354                                value_for_notfound->namelen, TRUE);
355             if (!sv) {
356                 Perl_croak($athx
357                            "Couldn't add key '%s' to %%$package_sprintf_safe\::",
358                            value_for_notfound->name);
359             }
360             if (!SvOK(*sv) && SvTYPE(*sv) != SVt_PVGV) {
361                 /* Nothing was here before, so mark a prototype of ""  */
362                 sv_setpvn(*sv, "", 0);
363             } else if (SvPOK(*sv) && SvCUR(*sv) == 0) {
364                 /* There is already a prototype of "" - do nothing  */
365             } else {
366                 /* Someone has been here before us - have to make a real
367                    typeglob.  */
368                 /* It turns out to be incredibly hard to deal with all the
369                    corner cases of sub foo (); and reporting errors correctly,
370                    so lets cheat a bit.  Start with a constant subroutine  */
371                 CV *cv = newCONSTSUB(symbol_table, value_for_notfound->name,
372                                      &PL_sv_yes);
373                 /* and then turn it into a non constant declaration only.  */
374                 SvREFCNT_dec(CvXSUBANY(cv).any_ptr);
375                 CvCONST_off(cv);
376                 CvXSUB(cv) = NULL;
377                 CvXSUBANY(cv).any_ptr = NULL;
378             }
379 #ifndef SYMBIAN
380             if (!hv_store(${c_subname}_missing, value_for_notfound->name,
381                           value_for_notfound->namelen, &PL_sv_yes, 0))
382                 Perl_croak($athx "Couldn't add key '%s' to missing_hash",
383                            value_for_notfound->name);
384 #endif
385 DONT
386
387     print $xs_fh <<"EOBOOT";
388
389             ++value_for_notfound;
390         }
391 EOBOOT
392
393     foreach my $item (@$trouble) {
394         my ($name, $namelen, $value, $macro)
395             = $self->name_len_value_macro($item);
396         my $ifdef = $self->macro_to_ifdef($macro);
397         my $type = $item->{type};
398         my $type_to_value = $self->type_to_C_value($type);
399
400         print $xs_fh $ifdef;
401         if ($item->{invert_macro}) {
402             print $xs_fh
403                  "        /* This is the default value: */\n" if $type;
404             print $xs_fh "#else\n";
405         }
406         my $generator = $type_to_sv{$type};
407         die "Can't find generator code for type $type"
408             unless defined $generator;
409
410         print $xs_fh "        {\n";
411         # We need to use a temporary value because some really troublesome
412         # items use C pre processor directives in their values, and in turn
413         # these don't fit nicely in the macro-ised generator functions
414         my $counter = 0;
415         printf $xs_fh "            %s temp%d;\n", $_, $counter++
416             foreach @{$type_temporary{$type}};
417
418         print $xs_fh "            $item->{pre}\n" if $item->{pre};
419
420         # And because the code in pre might be both declarations and
421         # statements, we can't declare and assign to the temporaries in one.
422         $counter = 0;
423         printf $xs_fh "            temp%d = %s;\n", $counter++, $_
424             foreach &$type_to_value($value);
425
426         my @tempvarnames = map {sprintf 'temp%d', $_} 0 .. $counter - 1;
427         printf $xs_fh <<"EOBOOT", $name, &$generator(@tempvarnames);
428             ${c_subname}_add_symbol($athx symbol_table, "%s",
429                                     $namelen, %s);
430 EOBOOT
431         print $xs_fh "        $item->{post}\n" if $item->{post};
432         print $xs_fh "        }\n";
433
434         print $xs_fh $self->macro_to_endif($macro);
435     }
436
437     print $xs_fh <<EOBOOT;
438     /* As we've been creating subroutines, we better invalidate any cached
439        methods  */
440     ++PL_sub_generation;
441   }
442 EOBOOT
443
444     print $xs_fh $explosives ? <<"EXPLODE" : <<"DONT";
445
446 void
447 $xs_subname(sv)
448     INPUT:
449         SV *            sv;
450     PPCODE:
451         sv = newSVpvf("Your vendor has not defined $package_sprintf_safe macro %" SVf
452                           ", used", sv);
453         PUSHs(sv_2mortal(sv));
454 EXPLODE
455
456 void
457 $xs_subname(sv)
458     PREINIT:
459         STRLEN          len;
460     INPUT:
461         SV *            sv;
462         const char *    s = SvPV(sv, len);
463     PPCODE:
464 #ifdef SYMBIAN
465         sv = newSVpvf("%"SVf" is not a valid $package_sprintf_safe macro", sv);
466 #else
467         if (hv_exists(${c_subname}_missing, s, SvUTF8(sv) ? -(I32)len : (I32)len)) {
468             sv = newSVpvf("Your vendor has not defined $package_sprintf_safe macro %" SVf
469                           ", used", sv);
470         } else {
471             sv = newSVpvf("%"SVf" is not a valid $package_sprintf_safe macro",
472                           sv);
473         }
474 #endif
475         PUSHs(sv_2mortal(sv));
476 DONT
477
478 }
479
480 1;