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