This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Change docs display for PERL_UNUSED_foo
[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 #    proto.h
8 #
9 # from information stored in
10 #
11 #    embed.fnc
12 #    intrpvar.h
13 #    perlvars.h
14 #    regen/opcodes
15 #
16 # Accepts the standard regen_lib -q and -v args.
17 #
18 # This script is normally invoked from regen.pl.
19
20 require 5.004;  # keep this compatible, an old perl is all we may have before
21                 # we build the new one
22
23 use strict;
24
25 BEGIN {
26     # Get function prototypes
27     require './regen/regen_lib.pl';
28     require './regen/embed_lib.pl';
29 }
30
31 my $unflagged_pointers;
32
33 #
34 # See database of global and static function prototypes in embed.fnc
35 # This is used to generate prototype headers under various configurations,
36 # export symbols lists for different platforms, and macros to provide an
37 # implicit interpreter context argument.
38 #
39
40 my $error_count = 0;
41 sub die_at_end ($) { # Keeps going for now, but makes sure the regen doesn't
42                      # succeed.
43     warn shift;
44     $error_count++;
45 }
46
47 sub full_name ($$) { # Returns the function name with potentially the
48                      # prefixes 'S_' or 'Perl_'
49     my ($func, $flags) = @_;
50
51     return "Perl_$func" if $flags =~ /p/;
52     return "S_$func" if $flags =~ /[SIi]/;
53     return $func;
54 }
55
56 sub open_print_header {
57     my ($file, $quote) = @_;
58
59     return open_new($file, '>',
60                     { file => $file, style => '*', by => 'regen/embed.pl',
61                       from => ['data in embed.fnc', 'regen/embed.pl',
62                                'regen/opcodes', 'intrpvar.h', 'perlvars.h'],
63                       final => "\nEdit those files and run 'make regen_headers' to effect changes.\n",
64                       copyright => [1993 .. 2009], quote => $quote });
65 }
66
67 my ($embed, $core, $ext, $api) = setup_embed();
68
69 # generate proto.h
70 {
71     my $pr = open_print_header("proto.h");
72     print $pr "START_EXTERN_C\n";
73     my $ret;
74
75     foreach (@$embed) {
76         if (@$_ == 1) {
77             print $pr "$_->[0]\n";
78             next;
79         }
80
81         my ($flags,$retval,$plain_func,@args) = @$_;
82         if ($flags =~ / ( [^AabCDdEefFGhIiMmNnOoPpRrSsTUuWXx] ) /x) {
83             die_at_end "flag $1 is not legal (for function $plain_func)";
84         }
85         my @nonnull;
86         my $args_assert_line = ( $flags !~ /G/ );
87         my $has_depth = ( $flags =~ /W/ );
88         my $has_context = ( $flags !~ /T/ );
89         my $never_returns = ( $flags =~ /r/ );
90         my $binarycompat = ( $flags =~ /b/ );
91         my $commented_out = ( $flags =~ /m/ );
92         my $is_malloc = ( $flags =~ /a/ );
93         my $can_ignore = ( $flags !~ /R/ ) && ( $flags !~ /P/ ) && !$is_malloc;
94         my @names_of_nn;
95         my $func;
96
97         if (! $can_ignore && $retval eq 'void') {
98             warn "It is nonsensical to require the return value of a void function ($plain_func) to be checked";
99         }
100
101         die_at_end "$plain_func: S and p flags are mutually exclusive"
102                                             if $flags =~ /S/ && $flags =~ /p/;
103         die_at_end "$plain_func: m and $1 flags are mutually exclusive"
104                                         if $flags =~ /m/ && $flags =~ /([pS])/;
105
106         die_at_end "$plain_func: u flag only usable with m" if $flags =~ /u/
107                                                             && $flags !~ /m/;
108
109         my $static_inline = 0;
110         if ($flags =~ /([SIi])/) {
111             my $type;
112             if ($never_returns) {
113                 $type = {
114                     'S' => 'PERL_STATIC_NO_RET',
115                     'i' => 'PERL_STATIC_INLINE_NO_RET',
116                     'I' => 'PERL_STATIC_FORCE_INLINE_NO_RET'
117                 }->{$1};
118             }
119             else {
120                 $type = {
121                     'S' => 'STATIC',
122                     'i' => 'PERL_STATIC_INLINE',
123                     'I' => 'PERL_STATIC_FORCE_INLINE'
124                 }->{$1};
125             }
126             $retval = "$type $retval";
127             die_at_end "Don't declare static function '$plain_func' pure" if $flags =~ /P/;
128             $static_inline = $type =~ /^PERL_STATIC(?:_FORCE)?_INLINE/;
129         }
130         else {
131             if ($never_returns) {
132                 $retval = "PERL_CALLCONV_NO_RET $retval";
133             }
134             else {
135                 $retval = "PERL_CALLCONV $retval";
136             }
137         }
138
139         die_at_end "For '$plain_func', M flag requires p flag"
140                                             if $flags =~ /M/ && $flags !~ /p/;
141         die_at_end "For '$plain_func', C flag requires one of [pIimb] flags"
142                                             if $flags =~ /C/ && $flags !~ /[Iibmp]/;
143         die_at_end "For '$plain_func', X flag requires one of [Iip] flags"
144                                             if $flags =~ /X/ && $flags !~ /[Iip]/;
145         die_at_end "For '$plain_func', X and m flags are mutually exclusive"
146                                             if $flags =~ /X/ && $flags =~ /m/;
147         die_at_end "For '$plain_func', [Ii] with [ACX] requires p flag"
148                         if $flags =~ /[Ii]/ && $flags =~ /[ACX]/ && $flags !~ /p/;
149         die_at_end "For '$plain_func', b and m flags are mutually exclusive"
150                  . " (try M flag)" if $flags =~ /b/ && $flags =~ /m/;
151         die_at_end "For '$plain_func', b flag without M flag requires D flag"
152                             if $flags =~ /b/ && $flags !~ /M/ && $flags !~ /D/;
153         die_at_end "For '$plain_func', I and i flags are mutually exclusive"
154                                             if $flags =~ /I/ && $flags =~ /i/;
155
156         $func = full_name($plain_func, $flags);
157         $ret = "";
158         $ret .= "$retval\t$func(";
159         if ( $has_context ) {
160             $ret .= @args ? "pTHX_ " : "pTHX";
161         }
162         if (@args) {
163             die_at_end "n flag is contradicted by having arguments"
164                                                                 if $flags =~ /n/;
165             my $n;
166             for my $arg ( @args ) {
167                 ++$n;
168                 if ( $arg =~ /\*/ && $arg !~ /\b(NN|NULLOK)\b/ ) {
169                     warn "$func: $arg needs NN or NULLOK\n";
170                     ++$unflagged_pointers;
171                 }
172                 my $nn = ( $arg =~ s/\s*\bNN\b\s+// );
173                 push( @nonnull, $n ) if $nn;
174
175                 my $nullok = ( $arg =~ s/\s*\bNULLOK\b\s+// ); # strip NULLOK with no effect
176
177                 # Make sure each arg has at least a type and a var name.
178                 # An arg of "int" is valid C, but want it to be "int foo".
179                 my $temp_arg = $arg;
180                 $temp_arg =~ s/\*//g;
181                 $temp_arg =~ s/\s*\bstruct\b\s*/ /g;
182                 if ( ($temp_arg ne "...")
183                      && ($temp_arg !~ /\w+\s+(\w+)(?:\[\d+\])?\s*$/) ) {
184                     die_at_end "$func: $arg ($n) doesn't have a name\n";
185                 }
186                 if (defined $1 && $nn && !($commented_out && !$binarycompat)) {
187                     push @names_of_nn, $1;
188                 }
189             }
190             $ret .= join ", ", @args;
191         }
192         else {
193             $ret .= "void" if !$has_context;
194         }
195         $ret .= " _pDEPTH" if $has_depth;
196         $ret .= ")";
197         my @attrs;
198         if ( $flags =~ /r/ ) {
199             push @attrs, "__attribute__noreturn__";
200         }
201         if ( $flags =~ /D/ ) {
202             push @attrs, "__attribute__deprecated__";
203         }
204         if ( $is_malloc ) {
205             push @attrs, "__attribute__malloc__";
206         }
207         if ( !$can_ignore ) {
208             push @attrs, "__attribute__warn_unused_result__";
209         }
210         if ( $flags =~ /P/ ) {
211             push @attrs, "__attribute__pure__";
212         }
213         if ( $flags =~ /I/ ) {
214             push @attrs, "__attribute__always_inline__";
215         }
216         if( $flags =~ /f/ ) {
217             my $prefix  = $has_context ? 'pTHX_' : '';
218             my ($args, $pat);
219             if ($args[-1] eq '...') {
220                 $args   = scalar @args;
221                 $pat    = $args - 1;
222                 $args   = $prefix . $args;
223             }
224             else {
225                 # don't check args, and guess which arg is the pattern
226                 # (one of 'fmt', 'pat', 'f'),
227                 $args = 0;
228                 my @fmts = grep $args[$_] =~ /\b(f|pat|fmt)$/, 0..$#args;
229                 if (@fmts != 1) {
230                     die "embed.pl: '$plain_func': can't determine pattern arg\n";
231                 }
232                 $pat = $fmts[0] + 1;
233             }
234             my $macro   = grep($_ == $pat, @nonnull)
235                                 ? '__attribute__format__'
236                                 : '__attribute__format__null_ok__';
237             if ($plain_func =~ /strftime/) {
238                 push @attrs, sprintf "%s(__strftime__,%s1,0)", $macro, $prefix;
239             }
240             else {
241                 push @attrs, sprintf "%s(__printf__,%s%d,%s)", $macro,
242                                     $prefix, $pat, $args;
243             }
244         }
245         elsif ((grep { $_ eq '...' } @args) && $flags !~ /F/) {
246             die_at_end "$plain_func: Function with '...' arguments must have"
247                      . " f or F flag";
248         }
249         if ( @attrs ) {
250             $ret .= "\n";
251             $ret .= join( "\n", map { "\t\t\t$_" } @attrs );
252         }
253         $ret .= ";";
254         $ret = "/* $ret */" if $commented_out;
255
256         $ret .= "\n#define PERL_ARGS_ASSERT_\U$plain_func\E"
257                                             if $args_assert_line || @names_of_nn;
258         $ret .= "\t\\\n\t" . join '; ', map "assert($_)", @names_of_nn
259                                                                 if @names_of_nn;
260
261         $ret = "#ifndef PERL_NO_INLINE_FUNCTIONS\n$ret\n#endif" if $static_inline;
262         $ret = "#ifndef NO_MATHOMS\n$ret\n#endif" if $binarycompat;
263         $ret .= @attrs ? "\n\n" : "\n";
264
265         print $pr $ret;
266     }
267
268     print $pr <<'EOF';
269 #ifdef PERL_CORE
270 #  include "pp_proto.h"
271 #endif
272 END_EXTERN_C
273 EOF
274
275     read_only_bottom_close_and_rename($pr) if ! $error_count;
276 }
277
278 die_at_end "$unflagged_pointers pointer arguments to clean up\n" if $unflagged_pointers;
279
280 sub readvars {
281     my ($file, $pre) = @_;
282     local (*FILE, $_);
283     my %seen;
284     open(FILE, '<', $file)
285         or die "embed.pl: Can't open $file: $!\n";
286     while (<FILE>) {
287         s/[ \t]*#.*//;          # Delete comments.
288         if (/PERLVARA?I?C?\($pre,\s*(\w+)/) {
289             die_at_end "duplicate symbol $1 while processing $file line $.\n"
290                 if $seen{$1}++;
291         }
292     }
293     close(FILE);
294     return sort keys %seen;
295 }
296
297 my @intrp = readvars 'intrpvar.h','I';
298 my @globvar = readvars 'perlvars.h','G';
299
300 sub hide {
301     my ($from, $to, $indent) = @_;
302     $indent = '' unless defined $indent;
303     my $t = int(length("$indent$from") / 8);
304     "#${indent}define $from" . "\t" x ($t < 3 ? 3 - $t : 1) . "$to\n";
305 }
306
307 sub multon ($$$) {
308     my ($sym,$pre,$ptr) = @_;
309     hide("PL_$sym", "($ptr$pre$sym)");
310 }
311
312 my $em = open_print_header('embed.h');
313
314 print $em <<'END';
315 /* (Doing namespace management portably in C is really gross.) */
316
317 /* By defining PERL_NO_SHORT_NAMES (not done by default) the short forms
318  * (like warn instead of Perl_warn) for the API are not defined.
319  * Not defining the short forms is a good thing for cleaner embedding. */
320
321 #ifndef PERL_NO_SHORT_NAMES
322
323 /* Hide global symbols */
324
325 END
326
327 my @az = ('a'..'z');
328
329 sub embed_h {
330     my ($guard, $funcs) = @_;
331     print $em "$guard\n" if $guard;
332
333     my $lines;
334     foreach (@$funcs) {
335         if (@$_ == 1) {
336             my $cond = $_->[0];
337             # Indent the conditionals if we are wrapped in an #if/#endif pair.
338             $cond =~ s/#(.*)/#  $1/ if $guard;
339             $lines .= "$cond\n";
340             next;
341         }
342         my $ret = "";
343         my ($flags,$retval,$func,@args) = @$_;
344         unless ($flags =~ /[omM]/) {
345             my $args = scalar @args;
346             if ($flags =~ /T/) {
347                 my $full_name = full_name($func, $flags);
348                 next if $full_name eq $func;    # Don't output a no-op.
349                 $ret = hide($func, $full_name);
350             }
351             elsif ($args and $args[$args-1] =~ /\.\.\./) {
352                 if ($flags =~ /p/) {
353                     # we're out of luck for varargs functions under CPP
354                     # So we can only do these macros for no implicit context:
355                     $ret = "#ifndef PERL_IMPLICIT_CONTEXT\n"
356                         . hide($func, full_name($func, $flags)) . "#endif\n";
357                 }
358             }
359             else {
360                 my $alist = join(",", @az[0..$args-1]);
361                 $ret = "#define $func($alist)";
362                 my $t = int(length($ret) / 8);
363                 $ret .=  "\t" x ($t < 4 ? 4 - $t : 1);
364                 $ret .= full_name($func, $flags) . "(aTHX";
365                 $ret .= "_ " if $alist;
366                 $ret .= $alist;
367                 if ($flags =~ /W/) {
368                     if ($alist) {
369                         $ret .= " _aDEPTH";
370                     } else {
371                         die "Can't use W without other args (currently)";
372                     }
373                 }
374                 $ret .= ")\n";
375             }
376             $ret = "#ifndef NO_MATHOMS\n$ret#endif\n" if $flags =~ /b/;
377         }
378         $lines .= $ret;
379     }
380     # Prune empty #if/#endif pairs.
381     while ($lines =~ s/#\s*if[^\n]+\n#\s*endif\n//) {
382     }
383     # Merge adjacent blocks.
384     while ($lines =~ s/(#ifndef PERL_IMPLICIT_CONTEXT
385 [^\n]+
386 )#endif
387 #ifndef PERL_IMPLICIT_CONTEXT
388 /$1/) {
389     }
390
391     print $em $lines;
392     print $em "#endif\n" if $guard;
393 }
394
395 embed_h('', $api);
396 embed_h('#if defined(PERL_CORE) || defined(PERL_EXT)', $ext);
397 embed_h('#ifdef PERL_CORE', $core);
398
399 print $em <<'END';
400
401 #endif  /* #ifndef PERL_NO_SHORT_NAMES */
402
403 /* Compatibility stubs.  Compile extensions with -DPERL_NOCOMPAT to
404    disable them.
405  */
406
407 #if !defined(PERL_CORE)
408 #  define sv_setptrobj(rv,ptr,name)     sv_setref_iv(rv,name,PTR2IV(ptr))
409 #  define sv_setptrref(rv,ptr)          sv_setref_iv(rv,NULL,PTR2IV(ptr))
410 #endif
411
412 #if !defined(PERL_CORE) && !defined(PERL_NOCOMPAT)
413
414 /* Compatibility for various misnamed functions.  All functions
415    in the API that begin with "perl_" (not "Perl_") take an explicit
416    interpreter context pointer.
417    The following are not like that, but since they had a "perl_"
418    prefix in previous versions, we provide compatibility macros.
419  */
420 #  define perl_atexit(a,b)              call_atexit(a,b)
421 END
422
423 foreach (@$embed) {
424     my ($flags, $retval, $func, @args) = @$_;
425     next unless $func;
426     next unless $flags =~ /O/;
427
428     my $alist = join ",", @az[0..$#args];
429     my $ret = "#  define perl_$func($alist)";
430     my $t = (length $ret) >> 3;
431     $ret .=  "\t" x ($t < 5 ? 5 - $t : 1);
432     print $em "$ret$func($alist)\n";
433 }
434
435 my @nocontext;
436 {
437     my (%has_va, %has_nocontext);
438     foreach (@$embed) {
439         next unless @$_ > 1;
440         ++$has_va{$_->[2]} if $_->[-1] =~ /\.\.\./;
441         ++$has_nocontext{$1} if $_->[2] =~ /(.*)_nocontext/;
442     }
443
444     @nocontext = sort grep {
445         $has_nocontext{$_}
446             && !/printf/ # Not clear to me why these are skipped but they are.
447     } keys %has_va;
448 }
449
450 print $em <<'END';
451
452 /* varargs functions can't be handled with CPP macros. :-(
453    This provides a set of compatibility functions that don't take
454    an extra argument but grab the context pointer using the macro
455    dTHX.
456  */
457 #if defined(PERL_IMPLICIT_CONTEXT) && !defined(PERL_NO_SHORT_NAMES)
458 END
459
460 foreach (@nocontext) {
461     print $em hide($_, "Perl_${_}_nocontext", "  ");
462 }
463
464 print $em <<'END';
465 #endif
466
467 #endif /* !defined(PERL_CORE) && !defined(PERL_NOCOMPAT) */
468
469 #if !defined(PERL_IMPLICIT_CONTEXT)
470 /* undefined symbols, point them back at the usual ones */
471 END
472
473 foreach (@nocontext) {
474     print $em hide("Perl_${_}_nocontext", "Perl_$_", "  ");
475 }
476
477 print $em <<'END';
478 #endif
479 END
480
481 read_only_bottom_close_and_rename($em) if ! $error_count;
482
483 $em = open_print_header('embedvar.h');
484
485 print $em <<'END';
486 /* (Doing namespace management portably in C is really gross.) */
487
488 /*
489    The following combinations of MULTIPLICITY and PERL_IMPLICIT_CONTEXT
490    are supported:
491      1) none
492      2) MULTIPLICITY    # supported for compatibility
493      3) MULTIPLICITY && PERL_IMPLICIT_CONTEXT
494
495    All other combinations of these flags are errors.
496
497    only #3 is supported directly, while #2 is a special
498    case of #3 (supported by redefining vTHX appropriately).
499 */
500
501 #if defined(MULTIPLICITY)
502 /* cases 2 and 3 above */
503
504 #  if defined(PERL_IMPLICIT_CONTEXT)
505 #    define vTHX        aTHX
506 #  else
507 #    define vTHX        PERL_GET_INTERP
508 #  endif
509
510 END
511
512 my $sym;
513
514 for $sym (@intrp) {
515     if ($sym eq 'sawampersand') {
516         print $em "#ifndef PL_sawampersand\n";
517     }
518     print $em multon($sym,'I','vTHX->');
519     if ($sym eq 'sawampersand') {
520         print $em "#endif\n";
521     }
522 }
523
524 print $em <<'END';
525
526 #endif  /* MULTIPLICITY */
527 END
528
529 read_only_bottom_close_and_rename($em) if ! $error_count;
530
531 die "$error_count errors found" if $error_count;
532
533 # ex: set ts=8 sts=4 sw=4 noet: