This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
e06d764fe488ac940269a0837ec00e24fd9de144
[perl5.git] / regen / embed.pl
1 #!/usr/bin/perl -w
2
3 # Regenerate (overwriting only if changed):
4 #
5 #    embed.h
6 #    embedvar.h
7 #    perlapi.c
8 #    perlapi.h
9 #    proto.h
10 #
11 # from information stored in
12 #
13 #    embed.fnc
14 #    intrpvar.h
15 #    perlvars.h
16 #    regen/opcodes
17 #
18 # Accepts the standard regen_lib -q and -v args.
19 #
20 # This script is normally invoked from regen.pl.
21
22 require 5.004;  # keep this compatible, an old perl is all we may have before
23                 # we build the new one
24
25 use strict;
26
27 BEGIN {
28     # Get function prototypes
29     require 'regen/regen_lib.pl';
30     require 'regen/embed_lib.pl';
31 }
32
33 my $SPLINT = 0; # Turn true for experimental splint support http://www.splint.org
34 my $unflagged_pointers;
35
36 #
37 # See database of global and static function prototypes in embed.fnc
38 # This is used to generate prototype headers under various configurations,
39 # export symbols lists for different platforms, and macros to provide an
40 # implicit interpreter context argument.
41 #
42
43 sub full_name ($$) { # Returns the function name with potentially the
44                      # prefixes 'S_' or 'Perl_'
45     my ($func, $flags) = @_;
46
47     return "S_$func" if $flags =~ /[si]/;
48     return "Perl_$func" if $flags =~ /p/;
49     return $func;
50 }
51
52 sub open_print_header {
53     my ($file, $quote) = @_;
54
55     return open_new($file, '>',
56                     { file => $file, style => '*', by => 'regen/embed.pl',
57                       from => ['data in embed.fnc', 'regen/embed.pl',
58                                'regen/opcodes', 'intrpvar.h', 'perlvars.h'],
59                       final => "\nEdit those files and run 'make regen_headers' to effect changes.\n",
60                       copyright => [1993 .. 2009], quote => $quote });
61 }
62
63 my ($embed, $core, $ext, $api) = setup_embed();
64
65 # generate proto.h
66 {
67     my $pr = open_print_header("proto.h");
68     print $pr "START_EXTERN_C\n";
69     my $ret;
70
71     foreach (@$embed) {
72         if (@$_ == 1) {
73             print $pr "$_->[0]\n";
74             next;
75         }
76
77         my ($flags,$retval,$plain_func,@args) = @$_;
78         if ($flags =~ / ( [^AabDdEfiMmnOoPpRrsUXx] ) /x) {
79             warn "flag $1 is not legal (for function $plain_func)";
80         }
81         my @nonnull;
82         my $has_context = ( $flags !~ /n/ );
83         my $never_returns = ( $flags =~ /r/ );
84         my $commented_out = ( $flags =~ /m/ );
85         my $binarycompat = ( $flags =~ /b/ );
86         my $is_malloc = ( $flags =~ /a/ );
87         my $can_ignore = ( $flags !~ /R/ ) && !$is_malloc;
88         my @names_of_nn;
89         my $func;
90
91         if (! $can_ignore && $retval eq 'void') {
92             warn "It is nonsensical to require the return value of a void function ($plain_func) to be checked";
93         }
94
95         my $scope_type_flag_count = 0;
96         $scope_type_flag_count++ if $flags =~ /s/;
97         $scope_type_flag_count++ if $flags =~ /i/;
98         $scope_type_flag_count++ if $flags =~ /p/;
99         warn "$plain_func: i, p, and s flags are all mutually exclusive"
100                                                    if $scope_type_flag_count > 1;
101         my $splint_flags = "";
102         if ( $SPLINT && !$commented_out ) {
103             $splint_flags .= '/*@noreturn@*/ ' if $never_returns;
104             if ($can_ignore && ($retval ne 'void') && ($retval !~ /\*/)) {
105                 $retval .= " /*\@alt void\@*/";
106             }
107         }
108
109         if ($flags =~ /([si])/) {
110             my $type;
111             if ($never_returns) {
112                 $type = $1 eq 's' ? "PERL_STATIC_NO_RET" : "PERL_STATIC_INLINE_NO_RET";
113             }
114             else {
115                 $type = $1 eq 's' ? "STATIC" : "PERL_STATIC_INLINE";
116             }
117             $retval = "$type $splint_flags$retval";
118         }
119         else {
120             if ($never_returns) {
121                 $retval = "PERL_CALLCONV_NO_RET $splint_flags$retval";
122             }
123             else {
124                 $retval = "PERL_CALLCONV $splint_flags$retval";
125             }
126         }
127         $func = full_name($plain_func, $flags);
128         $ret = "$retval\t$func(";
129         if ( $has_context ) {
130             $ret .= @args ? "pTHX_ " : "pTHX";
131         }
132         if (@args) {
133             my $n;
134             for my $arg ( @args ) {
135                 ++$n;
136                 if ( $arg =~ /\*/ && $arg !~ /\b(NN|NULLOK)\b/ ) {
137                     warn "$func: $arg needs NN or NULLOK\n";
138                     ++$unflagged_pointers;
139                 }
140                 my $nn = ( $arg =~ s/\s*\bNN\b\s+// );
141                 push( @nonnull, $n ) if $nn;
142
143                 my $nullok = ( $arg =~ s/\s*\bNULLOK\b\s+// ); # strip NULLOK with no effect
144
145                 # Make sure each arg has at least a type and a var name.
146                 # An arg of "int" is valid C, but want it to be "int foo".
147                 my $temp_arg = $arg;
148                 $temp_arg =~ s/\*//g;
149                 $temp_arg =~ s/\s*\bstruct\b\s*/ /g;
150                 if ( ($temp_arg ne "...")
151                      && ($temp_arg !~ /\w+\s+(\w+)(?:\[\d+\])?\s*$/) ) {
152                     warn "$func: $arg ($n) doesn't have a name\n";
153                 }
154                 if ( $SPLINT && $nullok && !$commented_out ) {
155                     $arg = '/*@null@*/ ' . $arg;
156                 }
157                 if (defined $1 && $nn && !($commented_out && !$binarycompat)) {
158                     push @names_of_nn, $1;
159                 }
160             }
161             $ret .= join ", ", @args;
162         }
163         else {
164             $ret .= "void" if !$has_context;
165         }
166         $ret .= ")";
167         my @attrs;
168         if ( $flags =~ /r/ ) {
169             push @attrs, "__attribute__noreturn__";
170         }
171         if ( $flags =~ /D/ ) {
172             push @attrs, "__attribute__deprecated__";
173         }
174         if ( $is_malloc ) {
175             push @attrs, "__attribute__malloc__";
176         }
177         if ( !$can_ignore ) {
178             push @attrs, "__attribute__warn_unused_result__";
179         }
180         if ( $flags =~ /P/ ) {
181             push @attrs, "__attribute__pure__";
182         }
183         if( $flags =~ /f/ ) {
184             my $prefix  = $has_context ? 'pTHX_' : '';
185             my ($args, $pat);
186             if ($args[-1] eq '...') {
187                 $args   = scalar @args;
188                 $pat    = $args - 1;
189                 $args   = $prefix . $args;
190             }
191             else {
192                 # don't check args, and guess which arg is the pattern
193                 # (one of 'fmt', 'pat', 'f'),
194                 $args = 0;
195                 my @fmts = grep $args[$_] =~ /\b(f|pat|fmt)$/, 0..$#args;
196                 if (@fmts != 1) {
197                     die "embed.pl: '$plain_func': can't determine pattern arg\n";
198                 }
199                 $pat = $fmts[0] + 1;
200             }
201             my $macro   = grep($_ == $pat, @nonnull)
202                                 ? '__attribute__format__'
203                                 : '__attribute__format__null_ok__';
204             if ($plain_func =~ /strftime/) {
205                 push @attrs, sprintf "%s(__strftime__,%s1,0)", $macro, $prefix;
206             }
207             else {
208                 push @attrs, sprintf "%s(__printf__,%s%d,%s)", $macro,
209                                     $prefix, $pat, $args;
210             }
211         }
212         if ( @attrs ) {
213             $ret .= "\n";
214             $ret .= join( "\n", map { "\t\t\t$_" } @attrs );
215         }
216         $ret .= ";";
217         $ret = "/* $ret */" if $commented_out;
218         if (@names_of_nn) {
219             $ret .= "\n#define PERL_ARGS_ASSERT_\U$plain_func\E\t\\\n\t"
220                 . join '; ', map "assert($_)", @names_of_nn;
221         }
222         $ret .= @attrs ? "\n\n" : "\n";
223
224         print $pr $ret;
225     }
226
227     print $pr <<'EOF';
228 #ifdef PERL_CORE
229 #  include "pp_proto.h"
230 #endif
231 END_EXTERN_C
232 EOF
233
234     read_only_bottom_close_and_rename($pr);
235 }
236
237 warn "$unflagged_pointers pointer arguments to clean up\n" if $unflagged_pointers;
238
239 sub readvars {
240     my ($file, $pre) = @_;
241     local (*FILE, $_);
242     my %seen;
243     open(FILE, "< $file")
244         or die "embed.pl: Can't open $file: $!\n";
245     while (<FILE>) {
246         s/[ \t]*#.*//;          # Delete comments.
247         if (/PERLVARA?I?C?\($pre,\s*(\w+)/) {
248             warn "duplicate symbol $1 while processing $file line $.\n"
249                 if $seen{$1}++;
250         }
251     }
252     close(FILE);
253     return sort keys %seen;
254 }
255
256 my @intrp = readvars 'intrpvar.h','I';
257 my @globvar = readvars 'perlvars.h','G';
258
259 sub hide {
260     my ($from, $to, $indent) = @_;
261     $indent = '' unless defined $indent;
262     my $t = int(length("$indent$from") / 8);
263     "#${indent}define $from" . "\t" x ($t < 3 ? 3 - $t : 1) . "$to\n";
264 }
265
266 sub multon ($$$) {
267     my ($sym,$pre,$ptr) = @_;
268     hide("PL_$sym", "($ptr$pre$sym)");
269 }
270
271 my $em = open_print_header('embed.h');
272
273 print $em <<'END';
274 /* (Doing namespace management portably in C is really gross.) */
275
276 /* By defining PERL_NO_SHORT_NAMES (not done by default) the short forms
277  * (like warn instead of Perl_warn) for the API are not defined.
278  * Not defining the short forms is a good thing for cleaner embedding. */
279
280 #ifndef PERL_NO_SHORT_NAMES
281
282 /* Hide global symbols */
283
284 END
285
286 my @az = ('a'..'z');
287
288 sub embed_h {
289     my ($guard, $funcs) = @_;
290     print $em "$guard\n" if $guard;
291
292     my $lines;
293     foreach (@$funcs) {
294         if (@$_ == 1) {
295             my $cond = $_->[0];
296             # Indent the conditionals if we are wrapped in an #if/#endif pair.
297             $cond =~ s/#(.*)/#  $1/ if $guard;
298             $lines .= "$cond\n";
299             next;
300         }
301         my $ret = "";
302         my ($flags,$retval,$func,@args) = @$_;
303         unless ($flags =~ /[om]/) {
304             my $args = scalar @args;
305             if ($flags =~ /n/) {
306                 $ret = hide($func, full_name($func, $flags));
307             }
308             elsif ($args and $args[$args-1] =~ /\.\.\./) {
309                 if ($flags =~ /p/) {
310                     # we're out of luck for varargs functions under CPP
311                     # So we can only do these macros for no implicit context:
312                     $ret = "#ifndef PERL_IMPLICIT_CONTEXT\n"
313                         . hide($func, full_name($func, $flags)) . "#endif\n";
314                 }
315             }
316             else {
317                 my $alist = join(",", @az[0..$args-1]);
318                 $ret = "#define $func($alist)";
319                 my $t = int(length($ret) / 8);
320                 $ret .=  "\t" x ($t < 4 ? 4 - $t : 1);
321                 $ret .= full_name($func, $flags) . "(aTHX";
322                 $ret .= "_ " if $alist;
323                 $ret .= $alist . ")\n";
324             }
325         }
326         $lines .= $ret;
327     }
328     # Prune empty #if/#endif pairs.
329     while ($lines =~ s/#\s*if[^\n]+\n#\s*endif\n//) {
330     }
331     # Merge adjacent blocks.
332     while ($lines =~ s/(#ifndef PERL_IMPLICIT_CONTEXT
333 [^\n]+
334 )#endif
335 #ifndef PERL_IMPLICIT_CONTEXT
336 /$1/) {
337     }
338
339     print $em $lines;
340     print $em "#endif\n" if $guard;
341 }
342
343 embed_h('', $api);
344 embed_h('#if defined(PERL_CORE) || defined(PERL_EXT)', $ext);
345 embed_h('#ifdef PERL_CORE', $core);
346
347 print $em <<'END';
348
349 #endif  /* #ifndef PERL_NO_SHORT_NAMES */
350
351 /* Compatibility stubs.  Compile extensions with -DPERL_NOCOMPAT to
352    disable them.
353  */
354
355 #if !defined(PERL_CORE)
356 #  define sv_setptrobj(rv,ptr,name)     sv_setref_iv(rv,name,PTR2IV(ptr))
357 #  define sv_setptrref(rv,ptr)          sv_setref_iv(rv,NULL,PTR2IV(ptr))
358 #endif
359
360 #if !defined(PERL_CORE) && !defined(PERL_NOCOMPAT)
361
362 /* Compatibility for various misnamed functions.  All functions
363    in the API that begin with "perl_" (not "Perl_") take an explicit
364    interpreter context pointer.
365    The following are not like that, but since they had a "perl_"
366    prefix in previous versions, we provide compatibility macros.
367  */
368 #  define perl_atexit(a,b)              call_atexit(a,b)
369 END
370
371 foreach (@$embed) {
372     my ($flags, $retval, $func, @args) = @$_;
373     next unless $func;
374     next unless $flags =~ /O/;
375
376     my $alist = join ",", @az[0..$#args];
377     my $ret = "#  define perl_$func($alist)";
378     my $t = (length $ret) >> 3;
379     $ret .=  "\t" x ($t < 5 ? 5 - $t : 1);
380     print $em "$ret$func($alist)\n";
381 }
382
383 my @nocontext;
384 {
385     my (%has_va, %has_nocontext);
386     foreach (@$embed) {
387         next unless @$_ > 1;
388         ++$has_va{$_->[2]} if $_->[-1] =~ /\.\.\./;
389         ++$has_nocontext{$1} if $_->[2] =~ /(.*)_nocontext/;
390     }
391
392     @nocontext = sort grep {
393         $has_nocontext{$_}
394             && !/printf/ # Not clear to me why these are skipped but they are.
395     } keys %has_va;
396 }
397
398 print $em <<'END';
399
400 /* varargs functions can't be handled with CPP macros. :-(
401    This provides a set of compatibility functions that don't take
402    an extra argument but grab the context pointer using the macro
403    dTHX.
404  */
405 #if defined(PERL_IMPLICIT_CONTEXT) && !defined(PERL_NO_SHORT_NAMES)
406 END
407
408 foreach (@nocontext) {
409     print $em hide($_, "Perl_${_}_nocontext", "  ");
410 }
411
412 print $em <<'END';
413 #endif
414
415 #endif /* !defined(PERL_CORE) && !defined(PERL_NOCOMPAT) */
416
417 #if !defined(PERL_IMPLICIT_CONTEXT)
418 /* undefined symbols, point them back at the usual ones */
419 END
420
421 foreach (@nocontext) {
422     print $em hide("Perl_${_}_nocontext", "Perl_$_", "  ");
423 }
424
425 print $em <<'END';
426 #endif
427 END
428
429 read_only_bottom_close_and_rename($em);
430
431 $em = open_print_header('embedvar.h');
432
433 print $em <<'END';
434 /* (Doing namespace management portably in C is really gross.) */
435
436 /*
437    The following combinations of MULTIPLICITY and PERL_IMPLICIT_CONTEXT
438    are supported:
439      1) none
440      2) MULTIPLICITY    # supported for compatibility
441      3) MULTIPLICITY && PERL_IMPLICIT_CONTEXT
442
443    All other combinations of these flags are errors.
444
445    only #3 is supported directly, while #2 is a special
446    case of #3 (supported by redefining vTHX appropriately).
447 */
448
449 #if defined(MULTIPLICITY)
450 /* cases 2 and 3 above */
451
452 #  if defined(PERL_IMPLICIT_CONTEXT)
453 #    define vTHX        aTHX
454 #  else
455 #    define vTHX        PERL_GET_INTERP
456 #  endif
457
458 END
459
460 my $sym;
461
462 for $sym (@intrp) {
463     if ($sym eq 'sawampersand') {
464         print $em "#ifndef PL_sawampersand\n";
465     }
466     print $em multon($sym,'I','vTHX->');
467     if ($sym eq 'sawampersand') {
468         print $em "#endif\n";
469     }
470 }
471
472 print $em <<'END';
473
474 #endif  /* MULTIPLICITY */
475
476 #if defined(PERL_GLOBAL_STRUCT)
477
478 END
479
480 for $sym (@globvar) {
481     print $em "#ifdef OS2\n" if $sym eq 'sh_path';
482     print $em multon($sym,   'G','my_vars->');
483     print $em multon("G$sym",'', 'my_vars->');
484     print $em "#endif\n" if $sym eq 'sh_path';
485 }
486
487 print $em <<'END';
488
489 #endif /* PERL_GLOBAL_STRUCT */
490 END
491
492 read_only_bottom_close_and_rename($em);
493
494 my $capih = open_print_header('perlapi.h');
495
496 print $capih <<'EOT';
497 /* declare accessor functions for Perl variables */
498 #ifndef __perlapi_h__
499 #define __perlapi_h__
500
501 #if defined (MULTIPLICITY) && defined (PERL_GLOBAL_STRUCT)
502
503 START_EXTERN_C
504
505 #undef PERLVAR
506 #undef PERLVARA
507 #undef PERLVARI
508 #undef PERLVARIC
509 #define PERLVAR(p,v,t)  EXTERN_C t* Perl_##p##v##_ptr(pTHX);
510 #define PERLVARA(p,v,n,t)       typedef t PL_##v##_t[n];                \
511                         EXTERN_C PL_##v##_t* Perl_##p##v##_ptr(pTHX);
512 #define PERLVARI(p,v,t,i)       PERLVAR(p,v,t)
513 #define PERLVARIC(p,v,t,i) PERLVAR(p,v, const t)
514
515 #include "perlvars.h"
516
517 #undef PERLVAR
518 #undef PERLVARA
519 #undef PERLVARI
520 #undef PERLVARIC
521
522 END_EXTERN_C
523
524 #if defined(PERL_CORE)
525
526 /* accessor functions for Perl "global" variables */
527
528 /* these need to be mentioned here, or most linkers won't put them in
529    the perl executable */
530
531 #ifndef PERL_NO_FORCE_LINK
532
533 START_EXTERN_C
534
535 #ifndef DOINIT
536 EXTCONST void * const PL_force_link_funcs[];
537 #else
538 EXTCONST void * const PL_force_link_funcs[] = {
539 #undef PERLVAR
540 #undef PERLVARA
541 #undef PERLVARI
542 #undef PERLVARIC
543 #define PERLVAR(p,v,t)          (void*)Perl_##p##v##_ptr,
544 #define PERLVARA(p,v,n,t)       PERLVAR(p,v,t)
545 #define PERLVARI(p,v,t,i)       PERLVAR(p,v,t)
546 #define PERLVARIC(p,v,t,i)      PERLVAR(p,v,t)
547
548 /* In Tru64 (__DEC && __osf__) the cc option -std1 causes that one
549  * cannot cast between void pointers and function pointers without
550  * info level warnings.  The PL_force_link_funcs[] would cause a few
551  * hundred of those warnings.  In code one can circumnavigate this by using
552  * unions that overlay the different pointers, but in declarations one
553  * cannot use this trick.  Therefore we just disable the warning here
554  * for the duration of the PL_force_link_funcs[] declaration. */
555
556 #if defined(__DECC) && defined(__osf__)
557 #pragma message save
558 #pragma message disable (nonstandcast)
559 #endif
560
561 #include "perlvars.h"
562
563 #if defined(__DECC) && defined(__osf__)
564 #pragma message restore
565 #endif
566
567 #undef PERLVAR
568 #undef PERLVARA
569 #undef PERLVARI
570 #undef PERLVARIC
571 };
572 #endif  /* DOINIT */
573
574 END_EXTERN_C
575
576 #endif  /* PERL_NO_FORCE_LINK */
577
578 #else   /* !PERL_CORE */
579
580 EOT
581
582 foreach $sym (@globvar) {
583     print $capih
584         "#undef  PL_$sym\n" . hide("PL_$sym", "(*Perl_G${sym}_ptr(NULL))");
585 }
586
587 print $capih <<'EOT';
588
589 #endif /* !PERL_CORE */
590 #endif /* MULTIPLICITY && PERL_GLOBAL_STRUCT */
591
592 #endif /* __perlapi_h__ */
593 EOT
594
595 read_only_bottom_close_and_rename($capih);
596
597 my $capi = open_print_header('perlapi.c', <<'EOQ');
598  *
599  *
600  * Up to the threshold of the door there mounted a flight of twenty-seven
601  * broad stairs, hewn by some unknown art of the same black stone.  This
602  * was the only entrance to the tower; ...
603  *
604  *     [p.577 of _The Lord of the Rings_, III/x: "The Voice of Saruman"]
605  *
606  */
607 EOQ
608
609 print $capi <<'EOT';
610 #include "EXTERN.h"
611 #include "perl.h"
612 #include "perlapi.h"
613
614 #if defined (MULTIPLICITY) && defined (PERL_GLOBAL_STRUCT)
615
616 /* accessor functions for Perl "global" variables */
617 START_EXTERN_C
618
619 #undef PERLVARI
620 #define PERLVARI(p,v,t,i) PERLVAR(p,v,t)
621
622 #undef PERLVAR
623 #undef PERLVARA
624 #define PERLVAR(p,v,t)          t* Perl_##p##v##_ptr(pTHX)              \
625                         { dVAR; PERL_UNUSED_CONTEXT; return &(PL_##v); }
626 #define PERLVARA(p,v,n,t)       PL_##v##_t* Perl_##p##v##_ptr(pTHX)     \
627                         { dVAR; PERL_UNUSED_CONTEXT; return &(PL_##v); }
628 #undef PERLVARIC
629 #define PERLVARIC(p,v,t,i)      \
630                         const t* Perl_##p##v##_ptr(pTHX)                \
631                         { PERL_UNUSED_CONTEXT; return (const t *)&(PL_##v); }
632 #include "perlvars.h"
633
634 #undef PERLVAR
635 #undef PERLVARA
636 #undef PERLVARI
637 #undef PERLVARIC
638
639 END_EXTERN_C
640
641 #endif /* MULTIPLICITY && PERL_GLOBAL_STRUCT */
642 EOT
643
644 read_only_bottom_close_and_rename($capi);
645
646 # ex: set ts=8 sts=4 sw=4 noet: