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