This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Make PushXSStack a method
[perl5.git] / dist / ExtUtils-ParseXS / lib / ExtUtils / ParseXS.pm
CommitLineData
6b09c160 1package ExtUtils::ParseXS;
f0744969 2use strict;
6b09c160
YST
3
4use 5.006; # We use /??{}/ in regexes
5use Cwd;
6use Config;
505ef4a5 7use Exporter;
6b09c160
YST
8use File::Basename;
9use File::Spec;
907ce46c 10use Symbol;
547742ac 11use ExtUtils::ParseXS::Constants ();
9e831c8e 12use ExtUtils::ParseXS::CountLines;
a65c06db
S
13use ExtUtils::ParseXS::Utilities qw(
14 standard_typemap_locations
1d40e528 15 trim_whitespace
73e91d5a 16 tidy_type
c1e43162 17 C_string
547742ac 18 valid_proto_string
50b96cc2 19 process_typemaps
af4112ab 20 make_targetable
0ec7450c 21 map_type
6c2c48aa 22 standard_XS_defs
362926c8 23 assign_func_args
361d4be6 24 analyze_preprocessor_statements
40a3ae2f 25 set_cond
2a09a23f
JK
26 Warn
27 blurt
28 death
29 check_conditional_preprocessor_statements
a65c06db 30);
6b09c160 31
c74be726
JK
32our @ISA = qw(Exporter);
33our @EXPORT_OK = qw(
34 process_file
35 report_error_count
36);
37our $VERSION = '3';
a1c5c71f 38$VERSION = eval $VERSION if $VERSION =~ /_/;
6b09c160 39
3e5e7357
JK
40# The scalars in the line below remain as 'our' variables because pulling
41# them into $self led to build problems. In most cases, strings being
42# 'eval'-ed contain the variables' names hard-coded.
37ddf986 43our (
3da1efaa 44 $FH, $Package, $func_name, $Full_func_name, $pname, $ALIAS,
14e0d708 45);
6b09c160 46
3a52cf21 47our $self = bless {} => __PACKAGE__;
551f599a 48
6b09c160 49sub process_file {
1efd22b7 50
6b09c160 51 # Allow for $package->process_file(%hash) in the future
c1e43162 52 my ($pkg, %options) = @_ % 2 ? @_ : (__PACKAGE__, @_);
1efd22b7 53
551f599a 54 $self->{ProtoUsed} = exists $options{prototypes};
1efd22b7 55
6b09c160 56 # Set defaults.
c1e43162 57 my %args = (
37ddf986
JK
58 argtypes => 1,
59 csuffix => '.c',
60 except => 0,
61 hiertype => 0,
62 inout => 1,
63 linenumbers => 1,
64 optimize => 1,
65 output => \*STDOUT,
66 prototypes => 0,
67 typemap => [],
68 versioncheck => 1,
c1e43162 69 %options,
34fa6cb6 70 );
c1e43162 71 $args{except} = $args{except} ? ' TRY' : '';
6b09c160
YST
72
73 # Global Constants
1efd22b7 74
6b09c160
YST
75 my ($Is_VMS, $SymSet);
76 if ($^O eq 'VMS') {
77 $Is_VMS = 1;
78 # Establish set of global symbols with max length 28, since xsubpp
79 # will later add the 'XS_' prefix.
80 require ExtUtils::XSSymSet;
18aa1386 81 $SymSet = ExtUtils::XSSymSet->new(28);
6b09c160 82 }
b8862861 83 @{ $self->{XSStack} } = ({type => 'none'});
e1b52aff 84 $self->{InitFileCode} = [ @ExtUtils::ParseXS::Constants::InitFileCode ];
b8862861 85 $FH = $ExtUtils::ParseXS::Constants::FH;
c2d2fdd0
JK
86 $self->{Overload} = $ExtUtils::ParseXS::Constants::Overload;
87 $self->{errors} = $ExtUtils::ParseXS::Constants::errors;
88 $self->{Fallback} = $ExtUtils::ParseXS::Constants::Fallback;
6b09c160
YST
89
90 # Most of the 1500 lines below uses these globals. We'll have to
91 # clean this up sometime, probably. For now, we just pull them out
92 # of %args. -Ken
1efd22b7 93
c2d2fdd0
JK
94 $self->{hiertype} = $args{hiertype};
95 $self->{WantPrototypes} = $args{prototypes};
96 $self->{WantVersionChk} = $args{versioncheck};
97 $self->{WantLineNumbers} = $args{linenumbers};
e1b52aff 98 $self->{IncludedFiles} = {};
1efd22b7 99
4c9f88ef
JK
100 die "Missing required parameter 'filename'" unless $args{filename};
101 $self->{filepathname} = $args{filename};
102 ($self->{dir}, $self->{filename}) =
103 (dirname($args{filename}), basename($args{filename}));
104 $self->{filepathname} =~ s/\\/\\\\/g;
105 $self->{IncludedFiles}->{$args{filename}}++;
1efd22b7 106
6b09c160
YST
107 # Open the output file if given as a string. If they provide some
108 # other kind of reference, trust them that we can print to it.
109 if (not ref $args{output}) {
110 open my($fh), "> $args{output}" or die "Can't create $args{output}: $!";
111 $args{outfile} = $args{output};
112 $args{output} = $fh;
113 }
114
115 # Really, we shouldn't have to chdir() or select() in the first
40a3ae2f 116 # place. For now, just save and restore.
6b09c160
YST
117 my $orig_cwd = cwd();
118 my $orig_fh = select();
1efd22b7 119
c2d2fdd0 120 chdir($self->{dir});
6b09c160 121 my $pwd = cwd();
008fb49c 122 my $csuffix = $args{csuffix};
1efd22b7 123
c2d2fdd0 124 if ($self->{WantLineNumbers}) {
6b09c160
YST
125 my $cfile;
126 if ( $args{outfile} ) {
127 $cfile = $args{outfile};
34fa6cb6
JK
128 }
129 else {
6b09c160 130 $cfile = $args{filename};
008fb49c 131 $cfile =~ s/\.xs$/$csuffix/i or $cfile .= $csuffix;
6b09c160
YST
132 }
133 tie(*PSEUDO_STDOUT, 'ExtUtils::ParseXS::CountLines', $cfile, $args{output});
134 select PSEUDO_STDOUT;
34fa6cb6
JK
135 }
136 else {
6b09c160
YST
137 select $args{output};
138 }
139
69b19f32 140 $self->{typemap} = process_typemaps( $args{typemap}, $pwd );
6b09c160 141
1efd22b7 142 my $END = "!End!\n\n"; # "impossible" keyword (multiple newline)
6b09c160
YST
143
144 # Match an XS keyword
c2d2fdd0 145 $self->{BLOCK_re} = '\s*(' .
0a4f6920 146 join('|' => @ExtUtils::ParseXS::Constants::XSKeywords) .
ef83c2cf 147 "|$END)\\s*:";
6b09c160 148
a8adbc99 149 our ($C_group_rex, $C_arg);
6b09c160
YST
150 # Group in C (no support for comments or literals)
151 $C_group_rex = qr/ [({\[]
1efd22b7 152 (?: (?> [^()\[\]{}]+ ) | (??{ $C_group_rex }) )*
7c3505a2 153 [)}\]] /x;
6b09c160
YST
154 # Chunk in C without comma at toplevel (no comments):
155 $C_arg = qr/ (?: (?> [^()\[\]{},"']+ )
1efd22b7
JK
156 | (??{ $C_group_rex })
157 | " (?: (?> [^\\"]+ )
158 | \\.
159 )* " # String literal
160 | ' (?: (?> [^\\']+ ) | \\. )* ' # Char literal
161 )* /xs;
162
9710e530
JK
163 # Since at this point we're ready to begin printing to the output file and
164 # reading from the input file, I want to get as much data as possible into
165 # the proto-object $self. That means assigning to $self and elements of
166 # %args referenced below this point.
167 # HOWEVER: This resulted in an error when I tried:
168 # $args{'s'} ---> $self->{s}.
169 # Use of uninitialized value in quotemeta at
170 # .../blib/lib/ExtUtils/ParseXS.pm line 733
171
172 foreach my $datum ( qw| argtypes except inout optimize | ) {
173 $self->{$datum} = $args{$datum};
174 }
175
6b09c160 176 # Identify the version of xsubpp used
7c3505a2 177 print <<EOM;
6b09c160 178/*
566395ef 179 * This file was generated automatically by ExtUtils::ParseXS version $VERSION from the
c2d2fdd0 180 * contents of $self->{filename}. Do not edit this file, edit $self->{filename} instead.
6b09c160 181 *
1efd22b7 182 * ANY CHANGES MADE HERE WILL BE LOST!
6b09c160
YST
183 *
184 */
185
186EOM
187
188
c2d2fdd0
JK
189 print("#line 1 \"$self->{filepathname}\"\n")
190 if $self->{WantLineNumbers};
6b09c160 191
c2d2fdd0
JK
192 # Open the input file (using $self->{filename} which
193 # is a basename'd $args{filename} due to chdir above)
194 open($FH, $self->{filename}) or die "cannot open $self->{filename}: $!\n";
af4112ab 195
6b09c160
YST
196 firstmodule:
197 while (<$FH>) {
198 if (/^=/) {
199 my $podstartline = $.;
200 do {
34fa6cb6
JK
201 if (/^=cut\s*$/) {
202 # We can't just write out a /* */ comment, as our embedded
203 # POD might itself be in a comment. We can't put a /**/
204 # comment inside #if 0, as the C standard says that the source
205 # file is decomposed into preprocessing characters in the stage
206 # before preprocessing commands are executed.
207 # I don't want to leave the text as barewords, because the spec
208 # isn't clear whether macros are expanded before or after
209 # preprocessing commands are executed, and someone pathological
210 # may just have defined one of the 3 words as a macro that does
211 # something strange. Multiline strings are illegal in C, so
212 # the "" we write must be a string literal. And they aren't
213 # concatenated until 2 steps later, so we are safe.
214 # - Nicholas Clark
215 print("#if 0\n \"Skipped embedded POD.\"\n#endif\n");
c2d2fdd0
JK
216 printf("#line %d \"$self->{filepathname}\"\n", $. + 1)
217 if $self->{WantLineNumbers};
34fa6cb6
JK
218 next firstmodule
219 }
1efd22b7 220
6b09c160
YST
221 } while (<$FH>);
222 # At this point $. is at end of file so die won't state the start
223 # of the problem, and as we haven't yet read any lines &death won't
224 # show the correct line in the message either.
c2d2fdd0
JK
225 die ("Error: Unterminated pod in $self->{filename}, line $podstartline\n")
226 unless $self->{lastline};
6b09c160 227 }
cdfe2888 228 last if ($Package, $self->{Prefix}) =
6b09c160 229 /^MODULE\s*=\s*[\w:]+(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/;
1efd22b7 230
6b09c160
YST
231 print $_;
232 }
233 unless (defined $_) {
234 warn "Didn't find a 'MODULE ... PACKAGE ... PREFIX' line\n";
235 exit 0; # Not a fatal error for the caller process
236 }
237
c2d2fdd0 238 print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $self->{WantLineNumbers};
708f9ca6 239
6c2c48aa 240 standard_XS_defs();
708f9ca6 241
c2d2fdd0 242 print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $self->{WantLineNumbers};
6b09c160 243
c2d2fdd0
JK
244 $self->{lastline} = $_;
245 $self->{lastline_no} = $.;
6b09c160 246
e8697f90 247 my $BootCode_ref = [];
30e7c36c
JK
248 my $XSS_work_idx = 0;
249 my $cpp_next_tmp = 'XSubPPtmpAAAA';
6b09c160
YST
250 PARAGRAPH:
251 while (fetch_para()) {
f5a6ef4f 252 my $outlist_ref = [];
6b09c160 253 # Print initial preprocessor statements and blank lines
87931035
JK
254 while (@{ $self->{line} } && $self->{line}->[0] !~ /^[^\#]/) {
255 my $ln = shift(@{ $self->{line} });
9e831c8e
JK
256 print $ln, "\n";
257 next unless $ln =~ /^\#\s*((if)(?:n?def)?|elsif|else|endif)\b/;
361d4be6 258 my $statement = $+;
fc7d0601 259 ( $self, $XSS_work_idx, $BootCode_ref ) =
361d4be6
JK
260 analyze_preprocessor_statements(
261 $self, $statement, $XSS_work_idx, $BootCode_ref
262 );
6b09c160 263 }
1efd22b7 264
87931035 265 next PARAGRAPH unless @{ $self->{line} };
1efd22b7 266
b8862861 267 if ($XSS_work_idx && !$self->{XSStack}->[$XSS_work_idx]{varname}) {
6b09c160
YST
268 # We are inside an #if, but have not yet #defined its xsubpp variable.
269 print "#define $cpp_next_tmp 1\n\n";
e1b52aff 270 push(@{ $self->{InitFileCode} }, "#if $cpp_next_tmp\n");
e8697f90 271 push(@{ $BootCode_ref }, "#if $cpp_next_tmp");
b8862861 272 $self->{XSStack}->[$XSS_work_idx]{varname} = $cpp_next_tmp++;
6b09c160
YST
273 }
274
e6de4093
JK
275 death( $self,
276 "Code is not inside a function"
277 ." (maybe last function was ended by a blank line "
278 ." followed by a statement on column one?)")
87931035 279 if $self->{line}->[0] =~ /^\s/;
1efd22b7 280
6b09c160 281 # initialize info arrays
e1b52aff
JK
282 undef(%{ $self->{args_match} });
283 undef(%{ $self->{var_types} });
fe36d206 284 undef(%{ $self->{defaults} });
e1b52aff
JK
285 undef(%{ $self->{arg_list} });
286 undef(@{ $self->{proto_arg} });
cdfe2888 287 undef($self->{processing_arg_with_types});
740dff65 288 undef(%{ $self->{argtype_seen} });
740dff65 289 undef(%{ $self->{in_out} });
fb9574f4 290 undef(%{ $self->{lengthof} });
cdfe2888
JK
291 undef($self->{proto_in_this_xsub});
292 undef($self->{scope_in_this_xsub});
293 undef($self->{interface});
cdfe2888
JK
294 $self->{interface_macro} = 'XSINTERFACE_FUNC';
295 $self->{interface_macro_set} = 'XSINTERFACE_FUNC_SET';
296 $self->{ProtoThisXSUB} = $self->{WantPrototypes};
297 $self->{ScopeThisXSUB} = 0;
2b0a6a8a 298 my $xsreturn = 0;
6b09c160 299
87931035 300 $_ = shift(@{ $self->{line} });
18aa1386 301 while (my $kwd = $self->check_keyword("REQUIRE|PROTOTYPES|FALLBACK|VERSIONCHECK|INCLUDE(?:_COMMAND)?|SCOPE")) {
d710f389 302 no strict 'refs';
7c3505a2 303 &{"${kwd}_handler"}();
d710f389 304 use strict 'refs';
87931035
JK
305 next PARAGRAPH unless @{ $self->{line} };
306 $_ = shift(@{ $self->{line} });
6b09c160
YST
307 }
308
18aa1386 309 if ($self->check_keyword("BOOT")) {
e6de4093 310 check_conditional_preprocessor_statements($self);
e8697f90 311 push (@{ $BootCode_ref }, "#line $self->{line_no}->[@{ $self->{line_no} } - @{ $self->{line} }] \"$self->{filepathname}\"")
87931035 312 if $self->{WantLineNumbers} && $self->{line}->[0] !~ /^\s*#\s*line\b/;
e8697f90 313 push (@{ $BootCode_ref }, @{ $self->{line} }, "");
7c3505a2 314 next PARAGRAPH;
6b09c160
YST
315 }
316
6b09c160 317 # extract return type, function name and arguments
9316f72a 318 ($self->{ret_type}) = tidy_type($_);
2b0a6a8a 319 my $RETVAL_no_return = 1 if $self->{ret_type} =~ s/^NO_OUTPUT\s+//;
6b09c160
YST
320
321 # Allow one-line ANSI-like declaration
87931035 322 unshift @{ $self->{line} }, $2
9710e530 323 if $self->{argtypes}
9316f72a 324 and $self->{ret_type} =~ s/^(.*?\w.*?)\s*\b(\w+\s*\(.*)/$1/s;
6b09c160
YST
325
326 # a function definition needs at least 2 lines
e6de4093 327 blurt( $self, "Error: Function definition too short '$self->{ret_type}'"), next PARAGRAPH
87931035 328 unless @{ $self->{line} };
6b09c160 329
2b0a6a8a
JK
330 my $externC = 1 if $self->{ret_type} =~ s/^extern "C"\s+//;
331 my $static = 1 if $self->{ret_type} =~ s/^static\s+//;
6b09c160 332
c06e4b91 333 my $func_header = shift(@{ $self->{line} });
e6de4093 334 blurt( $self, "Error: Cannot parse function definition from '$func_header'"), next PARAGRAPH
6b09c160
YST
335 unless $func_header =~ /^(?:([\w:]*)::)?(\w+)\s*\(\s*(.*?)\s*\)\s*(const)?\s*(;\s*)?$/s;
336
2b0a6a8a 337 my ($class, $orig_args);
7c3505a2 338 ($class, $func_name, $orig_args) = ($1, $2, $3);
6b09c160 339 $class = "$4 $class" if $4;
7a522819 340 ($pname = $func_name) =~ s/^($self->{Prefix})?/$self->{Packprefix}/;
081eda6f 341 my $clean_func_name;
cdfe2888 342 ($clean_func_name = $func_name) =~ s/^$self->{Prefix}//;
3da1efaa 343 $Full_func_name = "$self->{Packid}_$clean_func_name";
6b09c160
YST
344 if ($Is_VMS) {
345 $Full_func_name = $SymSet->addsym($Full_func_name);
346 }
347
348 # Check for duplicate function definition
b8862861 349 for my $tmp (@{ $self->{XSStack} }) {
6b09c160 350 next unless defined $tmp->{functions}{$Full_func_name};
e6de4093 351 Warn( $self, "Warning: duplicate function definition '$clean_func_name' detected");
6b09c160
YST
352 last;
353 }
b8862861 354 $self->{XSStack}->[$XSS_work_idx]{functions}{$Full_func_name}++;
fc7d0601
JK
355 %{ $self->{XsubAliases} } = ();
356 %{ $self->{XsubAliasValues} } = ();
357 %{ $self->{Interfaces} } = ();
358 @{ $self->{Attributes} } = ();
44066983 359 $self->{DoSetMagic} = 1;
6b09c160 360
1efd22b7 361 $orig_args =~ s/\\\s*/ /g; # process line continuations
6b09c160
YST
362 my @args;
363
f5a6ef4f
JK
364 my (@fake_INPUT_pre); # For length(s) generated variables
365 my (@fake_INPUT);
9d179ed2 366 my $only_C_inlist_ref = {}; # Not in the signature of Perl function
9710e530 367 if ($self->{argtypes} and $orig_args =~ /\S/) {
6b09c160
YST
368 my $args = "$orig_args ,";
369 if ($args =~ /^( (??{ $C_arg }) , )* $ /x) {
34fa6cb6
JK
370 @args = ($args =~ /\G ( (??{ $C_arg }) ) , /xg);
371 for ( @args ) {
372 s/^\s+//;
373 s/\s+$//;
e8cc43a7 374 my ($arg, $default) = ($_ =~ m/ ( [^=]* ) ( (?: = .* )? ) /x);
af4112ab 375 my ($pre, $len_name) = ($arg =~ /(.*?) \s*
34fa6cb6
JK
376 \b ( \w+ | length\( \s*\w+\s* \) )
377 \s* $ /x);
378 next unless defined($pre) && length($pre);
379 my $out_type = '';
380 my $inout_var;
9710e530 381 if ($self->{inout} and s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\b\s*//) {
34fa6cb6
JK
382 my $type = $1;
383 $out_type = $type if $type ne 'IN';
384 $arg =~ s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\b\s*//;
385 $pre =~ s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\b\s*//;
386 }
387 my $islength;
af4112ab
JK
388 if ($len_name =~ /^length\( \s* (\w+) \s* \)\z/x) {
389 $len_name = "XSauto_length_of_$1";
34fa6cb6
JK
390 $islength = 1;
391 die "Default value on length() argument: `$_'"
392 if length $default;
393 }
394 if (length $pre or $islength) { # Has a type
395 if ($islength) {
396 push @fake_INPUT_pre, $arg;
505ef4a5
JK
397 }
398 else {
34fa6cb6
JK
399 push @fake_INPUT, $arg;
400 }
401 # warn "pushing '$arg'\n";
740dff65 402 $self->{argtype_seen}->{$len_name}++;
af4112ab 403 $_ = "$len_name$default"; # Assigns to @args
34fa6cb6 404 }
9d179ed2
JK
405 $only_C_inlist_ref->{$_} = 1 if $out_type eq "OUTLIST" or $islength;
406 push @{ $outlist_ref }, $len_name if $out_type =~ /OUTLIST$/;
740dff65 407 $self->{in_out}->{$len_name} = $out_type if $out_type;
1efd22b7 408 }
1efd22b7 409 }
34fa6cb6
JK
410 else {
411 @args = split(/\s*,\s*/, $orig_args);
e6de4093 412 Warn( $self, "Warning: cannot parse argument list '$orig_args', fallback to split");
6b09c160 413 }
34fa6cb6
JK
414 }
415 else {
6b09c160
YST
416 @args = split(/\s*,\s*/, $orig_args);
417 for (@args) {
9710e530 418 if ($self->{inout} and s/^(IN|IN_OUTLIST|OUTLIST|IN_OUT|OUT)\b\s*//) {
34fa6cb6
JK
419 my $out_type = $1;
420 next if $out_type eq 'IN';
9d179ed2 421 $only_C_inlist_ref->{$_} = 1 if $out_type eq "OUTLIST";
e9bd0a47 422 if ($out_type =~ /OUTLIST$/) {
9d179ed2 423 push @{ $outlist_ref }, undef;
e9bd0a47 424 }
740dff65 425 $self->{in_out}->{$_} = $out_type;
34fa6cb6 426 }
6b09c160
YST
427 }
428 }
429 if (defined($class)) {
430 my $arg0 = ((defined($static) or $func_name eq 'new')
1efd22b7 431 ? "CLASS" : "THIS");
6b09c160 432 unshift(@args, $arg0);
6b09c160
YST
433 }
434 my $extra_args = 0;
a40ca62b
JK
435 my @args_num = ();
436 my $num_args = 0;
6b09c160 437 my $report_args = '';
2b0a6a8a 438 my $ellipsis;
6b09c160
YST
439 foreach my $i (0 .. $#args) {
440 if ($args[$i] =~ s/\.\.\.//) {
34fa6cb6
JK
441 $ellipsis = 1;
442 if ($args[$i] eq '' && $i == $#args) {
443 $report_args .= ", ...";
444 pop(@args);
445 last;
446 }
6b09c160 447 }
9d179ed2 448 if ($only_C_inlist_ref->{$args[$i]}) {
34fa6cb6
JK
449 push @args_num, undef;
450 }
451 else {
452 push @args_num, ++$num_args;
453 $report_args .= ", $args[$i]";
6b09c160
YST
454 }
455 if ($args[$i] =~ /^([^=]*[^\s=])\s*=\s*(.*)/s) {
34fa6cb6
JK
456 $extra_args++;
457 $args[$i] = $1;
fe36d206
JK
458 $self->{defaults}->{$args[$i]} = $2;
459 $self->{defaults}->{$args[$i]} =~ s/"/\\"/g;
6b09c160 460 }
e1b52aff 461 $self->{proto_arg}->[$i+1] = '$';
6b09c160 462 }
a40ca62b 463 my $min_args = $num_args - $extra_args;
6b09c160
YST
464 $report_args =~ s/"/\\"/g;
465 $report_args =~ s/^,\s+//;
362926c8 466 $self->{func_args} = assign_func_args($self, \@args, $class);
e1b52aff 467 @{ $self->{args_match} }{@args} = @args_num;
6b09c160 468
87931035
JK
469 my $PPCODE = grep(/^\s*PPCODE\s*:/, @{ $self->{line} });
470 my $CODE = grep(/^\s*CODE\s*:/, @{ $self->{line} });
6b09c160 471 # Detect CODE: blocks which use ST(n)= or XST_m*(n,v)
27b7514f 472 # to set explicit return values.
9e831c8e 473 my $EXPLICIT_RETURN = ($CODE &&
87931035 474 ("@{ $self->{line} }" =~ /(\bST\s*\([^;]*=) | (\bXST_m\w+\s*\()/x ));
b9709a1c 475
50b96cc2
JK
476 # The $ALIAS which follows is only explicitly called within the scope of
477 # process_file(). In principle, it ought to be a lexical, i.e., 'my
b9709a1c
JK
478 # $ALIAS' like the other nearby variables. However, implementing that
479 # change produced a slight difference in the resulting .c output in at
480 # least two distributions: B/BD/BDFOY/Crypt-Rijndael and
481 # G/GF/GFUJI/Hash-FieldHash. The difference is, arguably, an improvement
482 # in the resulting C code. Example:
483 # 388c388
484 # < GvNAME(CvGV(cv)),
485 # ---
486 # > "Crypt::Rijndael::encrypt",
487 # But at this point we're committed to generating the *same* C code that
488 # the current version of ParseXS.pm does. So we're declaring it as 'our'.
87931035 489 $ALIAS = grep(/^\s*ALIAS\s*:/, @{ $self->{line} });
b9709a1c 490
87931035 491 my $INTERFACE = grep(/^\s*INTERFACE\s*:/, @{ $self->{line} });
6b09c160
YST
492
493 $xsreturn = 1 if $EXPLICIT_RETURN;
494
008fb49c
JH
495 $externC = $externC ? qq[extern "C"] : "";
496
6b09c160
YST
497 # print function header
498 print Q(<<"EOF");
008fb49c 499#$externC
6b09c160
YST
500#XS(XS_${Full_func_name}); /* prototype to pass -Wmissing-prototypes */
501#XS(XS_${Full_func_name})
502#[[
97aff369
JH
503##ifdef dVAR
504# dVAR; dXSARGS;
505##else
6b09c160 506# dXSARGS;
97aff369 507##endif
6b09c160 508EOF
7c3505a2 509 print Q(<<"EOF") if $ALIAS;
6b09c160
YST
510# dXSI32;
511EOF
7c3505a2 512 print Q(<<"EOF") if $INTERFACE;
9316f72a 513# dXSFUNCTION($self->{ret_type});
6b09c160 514EOF
40a3ae2f
JK
515
516 $self->{cond} = set_cond($ellipsis, $min_args, $num_args);
6b09c160 517
9710e530 518 print Q(<<"EOF") if $self->{except};
6b09c160
YST
519# char errbuf[1024];
520# *errbuf = '\0';
521EOF
522
b827acfb 523 if($self->{cond}) {
34fa6cb6 524 print Q(<<"EOF");
b827acfb 525# if ($self->{cond})
708f9ca6 526# croak_xs_usage(cv, "$report_args");
6b09c160 527EOF
34fa6cb6
JK
528 }
529 else {
708f9ca6
DG
530 # cv likely to be unused
531 print Q(<<"EOF");
6b09c160
YST
532# PERL_UNUSED_VAR(cv); /* -W */
533EOF
708f9ca6 534 }
6b09c160
YST
535
536 #gcc -Wall: if an xsub has PPCODE is used
537 #it is possible none of ST, XSRETURN or XSprePUSH macros are used
538 #hence `ax' (setup by dXSARGS) is unused
539 #XXX: could breakup the dXSARGS; into dSP;dMARK;dITEMS
540 #but such a move could break third-party extensions
541 print Q(<<"EOF") if $PPCODE;
542# PERL_UNUSED_VAR(ax); /* -Wall */
543EOF
544
545 print Q(<<"EOF") if $PPCODE;
546# SP -= items;
547EOF
548
549 # Now do a block of some sort.
550
b827acfb 551 $self->{condnum} = 0;
40a3ae2f 552 $self->{cond} = ''; # last CASE: conditional
87931035 553 push(@{ $self->{line} }, "$END:");
b8862861 554 push(@{ $self->{line_no} }, $self->{line_no}->[-1]);
6b09c160 555 $_ = '';
18aa1386 556 $self->check_conditional_preprocessor_statements();
87931035 557 while (@{ $self->{line} }) {
18aa1386 558 CASE_handler() if $self->check_keyword("CASE");
6b09c160 559 print Q(<<"EOF");
9710e530 560# $self->{except} [[
6b09c160
YST
561EOF
562
563 # do initialization of input variables
ecafe0ca
JK
564 $self->{thisdone} = 0;
565 $self->{retvaldone} = 0;
706e7216 566 $self->{deferred} = "";
e1b52aff 567 %{ $self->{arg_list} } = ();
cf684ec1 568 $self->{gotRETVAL} = 0;
1efd22b7 569
7c3505a2 570 INPUT_handler();
18aa1386 571 $self->process_keyword("INPUT|PREINIT|INTERFACE_MACRO|C_ARGS|ALIAS|ATTRS|PROTOTYPE|SCOPE|OVERLOAD");
6b09c160 572
cdfe2888 573 print Q(<<"EOF") if $self->{ScopeThisXSUB};
6b09c160
YST
574# ENTER;
575# [[
576EOF
1efd22b7 577
ecafe0ca 578 if (!$self->{thisdone} && defined($class)) {
34fa6cb6
JK
579 if (defined($static) or $func_name eq 'new') {
580 print "\tchar *";
e1b52aff 581 $self->{var_types}->{"CLASS"} = "char *";
879afb6d
JK
582 generate_init( {
583 type => "char *",
584 num => 1,
585 var => "CLASS",
586 printed_name => undef,
587 } );
34fa6cb6
JK
588 }
589 else {
590 print "\t$class *";
e1b52aff 591 $self->{var_types}->{"THIS"} = "$class *";
879afb6d
JK
592 generate_init( {
593 type => "$class *",
594 num => 1,
595 var => "THIS",
596 printed_name => undef,
597 } );
34fa6cb6 598 }
6b09c160 599 }
1efd22b7 600
2b0a6a8a 601 my ($wantRETVAL);
6b09c160
YST
602 # do code
603 if (/^\s*NOT_IMPLEMENTED_YET/) {
34fa6cb6
JK
604 print "\n\tPerl_croak(aTHX_ \"$pname: not implemented yet\");\n";
605 $_ = '';
606 }
607 else {
9316f72a 608 if ($self->{ret_type} ne "void") {
361d4be6 609 print "\t" . map_type($self, $self->{ret_type}, 'RETVAL') . ";\n"
ecafe0ca 610 if !$self->{retvaldone};
e1b52aff
JK
611 $self->{args_match}->{"RETVAL"} = 0;
612 $self->{var_types}->{"RETVAL"} = $self->{ret_type};
69b19f32 613 my $outputmap = $self->{typemap}->get_outputmap( ctype => $self->{ret_type} );
34fa6cb6 614 print "\tdXSTARG;\n"
69b19f32 615 if $self->{optimize} and $outputmap and $outputmap->targetable;
34fa6cb6 616 }
1efd22b7 617
34fa6cb6 618 if (@fake_INPUT or @fake_INPUT_pre) {
87931035 619 unshift @{ $self->{line} }, @fake_INPUT_pre, @fake_INPUT, $_;
34fa6cb6 620 $_ = "";
cdfe2888 621 $self->{processing_arg_with_types} = 1;
34fa6cb6
JK
622 INPUT_handler();
623 }
706e7216 624 print $self->{deferred};
1efd22b7 625
18aa1386 626 $self->process_keyword("INIT|ALIAS|ATTRS|PROTOTYPE|INTERFACE_MACRO|INTERFACE|C_ARGS|OVERLOAD");
1efd22b7 627
18aa1386 628 if ($self->check_keyword("PPCODE")) {
34fa6cb6 629 print_section();
e6de4093 630 death( $self, "PPCODE must be last thing") if @{ $self->{line} };
cdfe2888 631 print "\tLEAVE;\n" if $self->{ScopeThisXSUB};
34fa6cb6 632 print "\tPUTBACK;\n\treturn;\n";
1efd22b7 633 }
18aa1386 634 elsif ($self->check_keyword("CODE")) {
34fa6cb6
JK
635 print_section();
636 }
637 elsif (defined($class) and $func_name eq "DESTROY") {
638 print "\n\t";
639 print "delete THIS;\n";
640 }
641 else {
642 print "\n\t";
9316f72a 643 if ($self->{ret_type} ne "void") {
34fa6cb6
JK
644 print "RETVAL = ";
645 $wantRETVAL = 1;
646 }
647 if (defined($static)) {
648 if ($func_name eq 'new') {
649 $func_name = "$class";
650 }
651 else {
652 print "${class}::";
653 }
654 }
655 elsif (defined($class)) {
656 if ($func_name eq 'new') {
657 $func_name .= " $class";
658 }
659 else {
660 print "THIS->";
661 }
662 }
663 $func_name =~ s/^\Q$args{'s'}//
664 if exists $args{'s'};
cdfe2888 665 $func_name = 'XSFUNCTION' if $self->{interface};
3c98792c 666 print "$func_name($self->{func_args});\n";
1efd22b7 667 }
1efd22b7
JK
668 }
669
6b09c160 670 # do output variables
cf684ec1 671 $self->{gotRETVAL} = 0; # 1 if RETVAL seen in OUTPUT section;
b23f32cf 672 undef $self->{RETVAL_code} ; # code to set RETVAL (from OUTPUT section);
6b09c160 673 # $wantRETVAL set if 'RETVAL =' autogenerated
9316f72a 674 ($wantRETVAL, $self->{ret_type}) = (0, 'void') if $RETVAL_no_return;
b8862861 675 undef %{ $self->{outargs} };
18aa1386 676 $self->process_keyword("POSTCALL|OUTPUT|ALIAS|ATTRS|PROTOTYPE|OVERLOAD");
1efd22b7 677
879afb6d 678 generate_output( {
e1b52aff
JK
679 type => $self->{var_types}->{$_},
680 num => $self->{args_match}->{$_},
879afb6d 681 var => $_,
44066983 682 do_setmagic => $self->{DoSetMagic},
879afb6d 683 do_push => undef,
740dff65 684 } ) for grep $self->{in_out}->{$_} =~ /OUT$/, keys %{ $self->{in_out} };
1efd22b7 685
fda75597 686 my $prepush_done;
6b09c160 687 # all OUTPUT done, so now push the return value on the stack
b23f32cf
JK
688 if ($self->{gotRETVAL} && $self->{RETVAL_code}) {
689 print "\t$self->{RETVAL_code}\n";
34fa6cb6 690 }
cf684ec1 691 elsif ($self->{gotRETVAL} || $wantRETVAL) {
69b19f32
S
692 my $outputmap = $self->{typemap}->get_outputmap( ctype => $self->{ret_type} );
693 my $t = $self->{optimize} && $outputmap && $outputmap->targetable;
fae3e113
JK
694 # Although the '$var' declared in the next line is never explicitly
695 # used within this 'elsif' block, commenting it out leads to
696 # disaster, starting with the first 'eval qq' inside the 'elsif' block
697 # below.
698 # It appears that this is related to the fact that at this point the
699 # value of $t is a reference to an array whose [2] element includes
700 # '$var' as a substring:
701 # <i> <> <(IV)$var>
34fa6cb6 702 my $var = 'RETVAL';
9316f72a 703 my $type = $self->{ret_type};
197a5a33 704
69b19f32 705 if ($t and not $t->{with_size} and $t->{type} eq 'p') {
629b8367 706 # PUSHp corresponds to setpvn. Treat setpv directly
69b19f32 707 my $what = eval qq("$t->{what}");
34fa6cb6 708 warn $@ if $@;
197a5a33 709
34fa6cb6
JK
710 print "\tsv_setpv(TARG, $what); XSprePUSH; PUSHTARG;\n";
711 $prepush_done = 1;
712 }
713 elsif ($t) {
69b19f32 714 my $what = eval qq("$t->{what}");
34fa6cb6 715 warn $@ if $@;
197a5a33 716
69b19f32 717 my $tsize = $t->{what_size};
af4112ab
JK
718 $tsize = '' unless defined $tsize;
719 $tsize = eval qq("$tsize");
34fa6cb6 720 warn $@ if $@;
69b19f32 721 print "\tXSprePUSH; PUSH$t->{type}($what$tsize);\n";
34fa6cb6
JK
722 $prepush_done = 1;
723 }
724 else {
725 # RETVAL almost never needs SvSETMAGIC()
879afb6d 726 generate_output( {
9316f72a 727 type => $self->{ret_type},
879afb6d
JK
728 num => 0,
729 var => 'RETVAL',
730 do_setmagic => 0,
731 do_push => undef,
732 } );
34fa6cb6 733 }
6b09c160 734 }
1efd22b7 735
9316f72a 736 $xsreturn = 1 if $self->{ret_type} ne "void";
6b09c160 737 my $num = $xsreturn;
9d179ed2 738 my $c = @{ $outlist_ref };
6b09c160
YST
739 print "\tXSprePUSH;" if $c and not $prepush_done;
740 print "\tEXTEND(SP,$c);\n" if $c;
741 $xsreturn += $c;
879afb6d 742 generate_output( {
e1b52aff 743 type => $self->{var_types}->{$_},
879afb6d
JK
744 num => $num++,
745 var => $_,
746 do_setmagic => 0,
747 do_push => 1,
9d179ed2 748 } ) for @{ $outlist_ref };
1efd22b7 749
6b09c160 750 # do cleanup
18aa1386 751 $self->process_keyword("CLEANUP|ALIAS|ATTRS|PROTOTYPE|OVERLOAD");
1efd22b7 752
cdfe2888 753 print Q(<<"EOF") if $self->{ScopeThisXSUB};
6b09c160
YST
754# ]]
755EOF
cdfe2888 756 print Q(<<"EOF") if $self->{ScopeThisXSUB} and not $PPCODE;
6b09c160
YST
757# LEAVE;
758EOF
1efd22b7 759
6b09c160
YST
760 # print function trailer
761 print Q(<<"EOF");
762# ]]
763EOF
9710e530 764 print Q(<<"EOF") if $self->{except};
6b09c160
YST
765# BEGHANDLERS
766# CATCHALL
1efd22b7 767# sprintf(errbuf, "%s: %s\\tpropagated", Xname, Xreason);
6b09c160
YST
768# ENDHANDLERS
769EOF
18aa1386 770 if ($self->check_keyword("CASE")) {
e6de4093 771 blurt( $self, "Error: No `CASE:' at top of function")
b827acfb 772 unless $self->{condnum};
34fa6cb6
JK
773 $_ = "CASE: $_"; # Restore CASE: label
774 next;
6b09c160
YST
775 }
776 last if $_ eq "$END:";
e6de4093
JK
777 death( $self,
778 /^$self->{BLOCK_re}/o ? "Misplaced `$1:'" : "Junk at end of function ($_)");
6b09c160 779 }
1efd22b7 780
9710e530 781 print Q(<<"EOF") if $self->{except};
6b09c160 782# if (errbuf[0])
1efd22b7 783# Perl_croak(aTHX_ errbuf);
6b09c160 784EOF
1efd22b7 785
6b09c160
YST
786 if ($xsreturn) {
787 print Q(<<"EOF") unless $PPCODE;
788# XSRETURN($xsreturn);
789EOF
34fa6cb6
JK
790 }
791 else {
6b09c160
YST
792 print Q(<<"EOF") unless $PPCODE;
793# XSRETURN_EMPTY;
794EOF
795 }
796
797 print Q(<<"EOF");
798#]]
799#
800EOF
801
ffd4b99c 802 $self->{newXS} = "newXS";
6e449812 803 $self->{proto} = "";
1efd22b7 804
6b09c160 805 # Build the prototype string for the xsub
cdfe2888 806 if ($self->{ProtoThisXSUB}) {
ffd4b99c 807 $self->{newXS} = "newXSproto_portable";
1efd22b7 808
cdfe2888 809 if ($self->{ProtoThisXSUB} eq 2) {
34fa6cb6 810 # User has specified empty prototype
6b09c160 811 }
cdfe2888 812 elsif ($self->{ProtoThisXSUB} eq 1) {
34fa6cb6
JK
813 my $s = ';';
814 if ($min_args < $num_args) {
815 $s = '';
e1b52aff 816 $self->{proto_arg}->[$min_args] .= ";";
34fa6cb6 817 }
e1b52aff 818 push @{ $self->{proto_arg} }, "$s\@"
34fa6cb6 819 if $ellipsis;
197a5a33 820
6e449812 821 $self->{proto} = join ("", grep defined, @{ $self->{proto_arg} } );
6b09c160
YST
822 }
823 else {
34fa6cb6 824 # User has specified a prototype
6e449812 825 $self->{proto} = $self->{ProtoThisXSUB};
6b09c160 826 }
6e449812 827 $self->{proto} = qq{, "$self->{proto}"};
6b09c160 828 }
28892255 829
fb9574f4
JK
830 if (%{ $self->{XsubAliases} }) {
831 $self->{XsubAliases}->{$pname} = 0
832 unless defined $self->{XsubAliases}->{$pname};
833 while ( my ($xname, $value) = each %{ $self->{XsubAliases} }) {
e1b52aff 834 push(@{ $self->{InitFileCode} }, Q(<<"EOF"));
ffd4b99c 835# cv = $self->{newXS}(\"$xname\", XS_$Full_func_name, file$self->{proto});
7c3505a2 836# XSANY.any_i32 = $value;
6b09c160 837EOF
6b09c160
YST
838 }
839 }
b8862861 840 elsif (@{ $self->{Attributes} }) {
e1b52aff 841 push(@{ $self->{InitFileCode} }, Q(<<"EOF"));
ffd4b99c 842# cv = $self->{newXS}(\"$pname\", XS_$Full_func_name, file$self->{proto});
b8862861 843# apply_attrs_string("$Package", cv, "@{ $self->{Attributes} }", 0);
6b09c160
YST
844EOF
845 }
cdfe2888 846 elsif ($self->{interface}) {
fb9574f4 847 while ( my ($yname, $value) = each %{ $self->{Interfaces} }) {
534bb3f4 848 $yname = "$Package\::$yname" unless $yname =~ /::/;
e1b52aff 849 push(@{ $self->{InitFileCode} }, Q(<<"EOF"));
ffd4b99c 850# cv = $self->{newXS}(\"$yname\", XS_$Full_func_name, file$self->{proto});
cdfe2888 851# $self->{interface_macro_set}(cv,$value);
6b09c160 852EOF
6b09c160
YST
853 }
854 }
ffd4b99c 855 elsif($self->{newXS} eq 'newXS'){ # work around P5NCI's empty newXS macro
e1b52aff 856 push(@{ $self->{InitFileCode} },
ffd4b99c 857 " $self->{newXS}(\"$pname\", XS_$Full_func_name, file$self->{proto});\n");
387b6f8d 858 }
6b09c160 859 else {
e1b52aff 860 push(@{ $self->{InitFileCode} },
ffd4b99c 861 " (void)$self->{newXS}(\"$pname\", XS_$Full_func_name, file$self->{proto});\n");
6b09c160 862 }
9e831c8e 863 } # END 'PARAGRAPH' 'while' loop
6b09c160 864
c2d2fdd0 865 if ($self->{Overload}) { # make it findable with fetchmethod
6b09c160 866 print Q(<<"EOF");
3da1efaa
JK
867#XS(XS_$self->{Packid}_nil); /* prototype to pass -Wmissing-prototypes */
868#XS(XS_$self->{Packid}_nil)
6b09c160 869#{
68746769 870# dXSARGS;
6b09c160
YST
871# XSRETURN_EMPTY;
872#}
873#
874EOF
e1b52aff 875 unshift(@{ $self->{InitFileCode} }, <<"MAKE_FETCHMETHOD_WORK");
6b09c160
YST
876 /* Making a sub named "${Package}::()" allows the package */
877 /* to be findable via fetchmethod(), and causes */
878 /* overload::Overloaded("${Package}") to return true. */
3da1efaa 879 (void)$self->{newXS}("${Package}::()", XS_$self->{Packid}_nil, file$self->{proto});
6b09c160
YST
880MAKE_FETCHMETHOD_WORK
881 }
882
883 # print initialization routine
884
885 print Q(<<"EOF");
886##ifdef __cplusplus
887#extern "C"
888##endif
889EOF
890
891 print Q(<<"EOF");
ca406d08
JK
892#XS(boot_$self->{Module_cname}); /* prototype to pass -Wmissing-prototypes */
893#XS(boot_$self->{Module_cname})
6b09c160
YST
894EOF
895
896 print Q(<<"EOF");
897#[[
97aff369
JH
898##ifdef dVAR
899# dVAR; dXSARGS;
900##else
6b09c160 901# dXSARGS;
97aff369 902##endif
6b09c160
YST
903EOF
904
1cb9da9d
DG
905 #Under 5.8.x and lower, newXS is declared in proto.h as expecting a non-const
906 #file name argument. If the wrong qualifier is used, it causes breakage with
907 #C++ compilers and warnings with recent gcc.
6b09c160
YST
908 #-Wall: if there is no $Full_func_name there are no xsubs in this .xs
909 #so `file' is unused
910 print Q(<<"EOF") if $Full_func_name;
1cb9da9d 911##if (PERL_REVISION == 5 && PERL_VERSION < 9)
28892255 912# char* file = __FILE__;
1cb9da9d 913##else
f05ddbb8 914# const char* file = __FILE__;
1cb9da9d 915##endif
6b09c160
YST
916EOF
917
918 print Q("#\n");
919
920 print Q(<<"EOF");
921# PERL_UNUSED_VAR(cv); /* -W */
922# PERL_UNUSED_VAR(items); /* -W */
c9004a9b
S
923##ifdef XS_APIVERSION_BOOTCHECK
924# XS_APIVERSION_BOOTCHECK;
925##endif
6b09c160 926EOF
1efd22b7 927
c2d2fdd0 928 print Q(<<"EOF") if $self->{WantVersionChk};
7c3505a2 929# XS_VERSION_BOOTCHECK;
6b09c160
YST
930#
931EOF
932
991408f6 933 print Q(<<"EOF") if defined $self->{xsubaliases} or defined $self->{interfaces};
6b09c160 934# {
7c3505a2 935# CV * cv;
6b09c160
YST
936#
937EOF
938
c2d2fdd0 939 print Q(<<"EOF") if ($self->{Overload});
6b09c160
YST
940# /* register the overloading (type 'A') magic */
941# PL_amagic_generation++;
942# /* The magic for overload gets a GV* via gv_fetchmeth as */
943# /* mentioned above, and looks in the SV* slot of it for */
944# /* the "fallback" status. */
945# sv_setsv(
946# get_sv( "${Package}::()", TRUE ),
c2d2fdd0 947# $self->{Fallback}
6b09c160
YST
948# );
949EOF
950
e1b52aff 951 print @{ $self->{InitFileCode} };
6b09c160 952
991408f6 953 print Q(<<"EOF") if defined $self->{xsubaliases} or defined $self->{interfaces};
6b09c160
YST
954# }
955EOF
956
e8697f90 957 if (@{ $BootCode_ref }) {
7c3505a2 958 print "\n /* Initialisation Section */\n\n";
e8697f90 959 @{ $self->{line} } = @{ $BootCode_ref };
6b09c160 960 print_section();
7c3505a2 961 print "\n /* End of Initialisation Section */\n\n";
6b09c160
YST
962 }
963
1cb9da9d
DG
964 print Q(<<'EOF');
965##if (PERL_REVISION == 5 && PERL_VERSION >= 9)
966# if (PL_unitcheckav)
967# call_list(PL_scopestack_ix, PL_unitcheckav);
968##endif
0932863f 969EOF
89345840 970
6b09c160
YST
971 print Q(<<"EOF");
972# XSRETURN_YES;
973#]]
974#
975EOF
976
c2d2fdd0 977 warn("Please specify prototyping behavior for $self->{filename} (see perlxs manual)\n")
551f599a 978 unless $self->{ProtoUsed};
6b09c160
YST
979
980 chdir($orig_cwd);
981 select($orig_fh);
982 untie *PSEUDO_STDOUT if tied *PSEUDO_STDOUT;
907ce46c 983 close $FH;
6b09c160
YST
984
985 return 1;
986}
987
c2d2fdd0 988sub report_error_count { $self->{errors} }
6b09c160 989
18aa1386 990# Input: ($self, $_, @{ $self->{line} }) == unparsed input.
87931035 991# Output: ($_, @{ $self->{line} }) == (rest of line, following lines).
6b09c160
YST
992# Return: the matched keyword if found, otherwise 0
993sub check_keyword {
18aa1386 994 my $self = shift;
87931035 995 $_ = shift(@{ $self->{line} }) while !/\S/ && @{ $self->{line} };
505ef4a5 996 s/^(\s*)($_[0])\s*:\s*(?:#.*)?/$1/s && $2;
6b09c160
YST
997}
998
999sub print_section {
505ef4a5 1000 # the "do" is required for right semantics
87931035 1001 do { $_ = shift(@{ $self->{line} }) } while !/\S/ && @{ $self->{line} };
6b09c160 1002
87931035 1003 print("#line ", $self->{line_no}->[@{ $self->{line_no} } - @{ $self->{line} } -1], " \"$self->{filepathname}\"\n")
c2d2fdd0 1004 if $self->{WantLineNumbers} && !/^\s*#\s*line\b/ && !/^#if XSubPPtmp/;
87931035 1005 for (; defined($_) && !/^$self->{BLOCK_re}/o; $_ = shift(@{ $self->{line} })) {
1efd22b7 1006 print "$_\n";
505ef4a5 1007 }
c2d2fdd0 1008 print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $self->{WantLineNumbers};
6b09c160
YST
1009}
1010
1011sub merge_section {
505ef4a5 1012 my $in = '';
6b09c160 1013
87931035
JK
1014 while (!/\S/ && @{ $self->{line} }) {
1015 $_ = shift(@{ $self->{line} });
505ef4a5 1016 }
6b09c160 1017
87931035 1018 for (; defined($_) && !/^$self->{BLOCK_re}/o; $_ = shift(@{ $self->{line} })) {
505ef4a5 1019 $in .= "$_\n";
6b09c160 1020 }
505ef4a5
JK
1021 chomp $in;
1022 return $in;
1023}
6b09c160 1024
18aa1386
S
1025sub process_keyword {
1026 my($self, $pattern) = @_;
505ef4a5 1027 my $kwd;
6b09c160 1028
d710f389 1029 no strict 'refs';
505ef4a5 1030 &{"${kwd}_handler"}()
18aa1386 1031 while $kwd = $self->check_keyword($pattern);
d710f389 1032 use strict 'refs';
505ef4a5 1033}
6b09c160
YST
1034
1035sub CASE_handler {
e6de4093 1036 blurt( $self, "Error: `CASE:' after unconditional `CASE:'")
b827acfb
JK
1037 if $self->{condnum} && $self->{cond} eq '';
1038 $self->{cond} = $_;
1039 trim_whitespace($self->{cond});
1040 print " ", ($self->{condnum}++ ? " else" : ""), ($self->{cond} ? " if ($self->{cond})\n" : "\n");
7c3505a2 1041 $_ = '';
6b09c160
YST
1042}
1043
1044sub INPUT_handler {
87931035 1045 for (; !/^$self->{BLOCK_re}/o; $_ = shift(@{ $self->{line} })) {
6b09c160 1046 last if /^\s*NOT_IMPLEMENTED_YET/;
1efd22b7 1047 next unless /\S/; # skip blank lines
6b09c160 1048
1d40e528 1049 trim_whitespace($_);
9e831c8e 1050 my $ln = $_;
6b09c160
YST
1051
1052 # remove trailing semicolon if no initialisation
7c3505a2 1053 s/\s*;$//g unless /[=;+].*\S/;
6b09c160
YST
1054
1055 # Process the length(foo) declarations
1056 if (s/^([^=]*)\blength\(\s*(\w+)\s*\)\s*$/$1 XSauto_length_of_$2=NO_INIT/x) {
1057 print "\tSTRLEN\tSTRLEN_length_of_$2;\n";
fb9574f4 1058 $self->{lengthof}->{$2} = undef;
706e7216 1059 $self->{deferred} .= "\n\tXSauto_length_of_$2 = STRLEN_length_of_$2;\n";
6b09c160
YST
1060 }
1061
1062 # check for optional initialisation code
7c3505a2
JK
1063 my $var_init = '';
1064 $var_init = $1 if s/\s*([=;+].*)$//s;
6b09c160
YST
1065 $var_init =~ s/"/\\"/g;
1066
1067 s/\s+/ /g;
1068 my ($var_type, $var_addr, $var_name) = /^(.*?[^&\s])\s*(\&?)\s*\b(\w+)$/s
e6de4093 1069 or blurt( $self, "Error: invalid argument declaration '$ln'"), next;
6b09c160
YST
1070
1071 # Check for duplicate definitions
e6de4093 1072 blurt( $self, "Error: duplicate definition of argument '$var_name' ignored"), next
e1b52aff 1073 if $self->{arg_list}->{$var_name}++
197a5a33 1074 or defined $self->{argtype_seen}->{$var_name} and not $self->{processing_arg_with_types};
6b09c160 1075
ecafe0ca
JK
1076 $self->{thisdone} |= $var_name eq "THIS";
1077 $self->{retvaldone} |= $var_name eq "RETVAL";
e1b52aff 1078 $self->{var_types}->{$var_name} = $var_type;
6b09c160
YST
1079 # XXXX This check is a safeguard against the unfinished conversion of
1080 # generate_init(). When generate_init() is fixed,
1081 # one can use 2-args map_type() unconditionally.
d67360fa 1082 my $printed_name;
6b09c160
YST
1083 if ($var_type =~ / \( \s* \* \s* \) /x) {
1084 # Function pointers are not yet supported with &output_init!
361d4be6 1085 print "\t" . map_type($self, $var_type, $var_name);
68f166a7 1086 $printed_name = 1;
505ef4a5
JK
1087 }
1088 else {
361d4be6 1089 print "\t" . map_type($self, $var_type, undef);
68f166a7 1090 $printed_name = 0;
6b09c160 1091 }
e1b52aff 1092 $self->{var_num} = $self->{args_match}->{$var_name};
6b09c160 1093
3e5e7357 1094 if ($self->{var_num}) {
69b19f32
S
1095 my $typemap = $self->{typemap}->get_typemap(ctype => $var_type);
1096 $self->{proto_arg}->[$self->{var_num}] = ($typemap && $typemap->proto) || "\$";
a1d55b8f 1097 }
3c98792c 1098 $self->{func_args} =~ s/\b($var_name)\b/&$1/ if $var_addr;
6b09c160 1099 if ($var_init =~ /^[=;]\s*NO_INIT\s*;?\s*$/
740dff65 1100 or $self->{in_out}->{$var_name} and $self->{in_out}->{$var_name} =~ /^OUT/
505ef4a5 1101 and $var_init !~ /\S/) {
68f166a7 1102 if ($printed_name) {
505ef4a5 1103 print ";\n";
6b09c160 1104 }
505ef4a5
JK
1105 else {
1106 print "\t$var_name;\n";
1107 }
1108 }
1109 elsif ($var_init =~ /\S/) {
87e6f370
JK
1110 output_init( {
1111 type => $var_type,
3e5e7357 1112 num => $self->{var_num},
87e6f370
JK
1113 var => $var_name,
1114 init => $var_init,
1115 printed_name => $printed_name,
1116 } );
505ef4a5 1117 }
3e5e7357 1118 elsif ($self->{var_num}) {
879afb6d
JK
1119 generate_init( {
1120 type => $var_type,
3e5e7357 1121 num => $self->{var_num},
879afb6d
JK
1122 var => $var_name,
1123 printed_name => $printed_name,
1124 } );
505ef4a5
JK
1125 }
1126 else {
6b09c160
YST
1127 print ";\n";
1128 }
1129 }
1130}
1131
1132sub OUTPUT_handler {
87931035 1133 for (; !/^$self->{BLOCK_re}/o; $_ = shift(@{ $self->{line} })) {
6b09c160
YST
1134 next unless /\S/;
1135 if (/^\s*SETMAGIC\s*:\s*(ENABLE|DISABLE)\s*/) {
44066983 1136 $self->{DoSetMagic} = ($1 eq "ENABLE" ? 1 : 0);
6b09c160
YST
1137 next;
1138 }
7c3505a2 1139 my ($outarg, $outcode) = /^\s*(\S+)\s*(.*?)\s*$/s;
e6de4093 1140 blurt( $self, "Error: duplicate OUTPUT argument '$outarg' ignored"), next
b8862861 1141 if $self->{outargs}->{$outarg}++;
cf684ec1 1142 if (!$self->{gotRETVAL} and $outarg eq 'RETVAL') {
6b09c160 1143 # deal with RETVAL last
b23f32cf 1144 $self->{RETVAL_code} = $outcode;
cf684ec1 1145 $self->{gotRETVAL} = 1;
7c3505a2 1146 next;
6b09c160 1147 }
e6de4093 1148 blurt( $self, "Error: OUTPUT $outarg not an argument"), next
e1b52aff 1149 unless defined($self->{args_match}->{$outarg});
e6de4093 1150 blurt( $self, "Error: No input definition for OUTPUT argument '$outarg' - ignored"), next
e1b52aff
JK
1151 unless defined $self->{var_types}->{$outarg};
1152 $self->{var_num} = $self->{args_match}->{$outarg};
6b09c160
YST
1153 if ($outcode) {
1154 print "\t$outcode\n";
3e5e7357 1155 print "\tSvSETMAGIC(ST(" , $self->{var_num} - 1 , "));\n" if $self->{DoSetMagic};
505ef4a5
JK
1156 }
1157 else {
879afb6d 1158 generate_output( {
e1b52aff 1159 type => $self->{var_types}->{$outarg},
3e5e7357 1160 num => $self->{var_num},
879afb6d 1161 var => $outarg,
44066983 1162 do_setmagic => $self->{DoSetMagic},
879afb6d
JK
1163 do_push => undef,
1164 } );
6b09c160 1165 }
740dff65
JK
1166 delete $self->{in_out}->{$outarg} # No need to auto-OUTPUT
1167 if exists $self->{in_out}->{$outarg} and $self->{in_out}->{$outarg} =~ /OUT$/;
6b09c160
YST
1168 }
1169}
1170
1171sub C_ARGS_handler() {
1172 my $in = merge_section();
1173
1d40e528 1174 trim_whitespace($in);
3c98792c 1175 $self->{func_args} = $in;
6b09c160
YST
1176}
1177
1178sub INTERFACE_MACRO_handler() {
1179 my $in = merge_section();
1180
1d40e528 1181 trim_whitespace($in);
1efd22b7 1182 if ($in =~ /\s/) { # two
cdfe2888 1183 ($self->{interface_macro}, $self->{interface_macro_set}) = split ' ', $in;
505ef4a5
JK
1184 }
1185 else {
cdfe2888
JK
1186 $self->{interface_macro} = $in;
1187 $self->{interface_macro_set} = 'UNKNOWN_CVT'; # catch later
6b09c160 1188 }
cdfe2888 1189 $self->{interface} = 1; # local
991408f6 1190 $self->{interfaces} = 1; # global
6b09c160
YST
1191}
1192
1193sub INTERFACE_handler() {
1194 my $in = merge_section();
1195
1d40e528 1196 trim_whitespace($in);
6b09c160
YST
1197
1198 foreach (split /[\s,]+/, $in) {
88577d04 1199 my $iface_name = $_;
cdfe2888 1200 $iface_name =~ s/^$self->{Prefix}//;
fb9574f4 1201 $self->{Interfaces}->{$iface_name} = $_;
6b09c160
YST
1202 }
1203 print Q(<<"EOF");
9316f72a 1204# XSFUNCTION = $self->{interface_macro}($self->{ret_type},cv,XSANY.any_dptr);
6b09c160 1205EOF
cdfe2888 1206 $self->{interface} = 1; # local
991408f6 1207 $self->{interfaces} = 1; # global
6b09c160
YST
1208}
1209
1210sub CLEANUP_handler() { print_section() }
1211sub PREINIT_handler() { print_section() }
1212sub POSTCALL_handler() { print_section() }
1213sub INIT_handler() { print_section() }
1214
505ef4a5
JK
1215sub GetAliases {
1216 my ($line) = @_;
1217 my ($orig) = $line;
6b09c160 1218
505ef4a5
JK
1219 # Parse alias definitions
1220 # format is
1221 # alias = value alias = value ...
6b09c160 1222
505ef4a5 1223 while ($line =~ s/^\s*([\w:]+)\s*=\s*(\w+)\s*//) {
9e831c8e
JK
1224 my ($alias, $value) = ($1, $2);
1225 my $orig_alias = $alias;
6b09c160 1226
505ef4a5 1227 # check for optional package definition in the alias
7a522819 1228 $alias = $self->{Packprefix} . $alias if $alias !~ /::/;
6b09c160 1229
505ef4a5 1230 # check for duplicate alias name & duplicate value
e6de4093 1231 Warn( $self, "Warning: Ignoring duplicate alias '$orig_alias'")
fb9574f4 1232 if defined $self->{XsubAliases}->{$alias};
6b09c160 1233
e6de4093 1234 Warn( $self, "Warning: Aliases '$orig_alias' and '$self->{XsubAliasValues}->{$value}' have identical values")
fb9574f4 1235 if $self->{XsubAliasValues}->{$value};
6b09c160 1236
44066983 1237 $self->{xsubaliases} = 1;
fb9574f4
JK
1238 $self->{XsubAliases}->{$alias} = $value;
1239 $self->{XsubAliasValues}->{$value} = $orig_alias;
6b09c160
YST
1240 }
1241
e6de4093 1242 blurt( $self, "Error: Cannot parse ALIAS definitions from '$orig'")
505ef4a5
JK
1243 if $line;
1244}
1245
1246sub ATTRS_handler () {
87931035 1247 for (; !/^$self->{BLOCK_re}/o; $_ = shift(@{ $self->{line} })) {
505ef4a5 1248 next unless /\S/;
1d40e528 1249 trim_whitespace($_);
b8862861 1250 push @{ $self->{Attributes} }, $_;
6b09c160 1251 }
505ef4a5 1252}
6b09c160 1253
505ef4a5 1254sub ALIAS_handler () {
87931035 1255 for (; !/^$self->{BLOCK_re}/o; $_ = shift(@{ $self->{line} })) {
505ef4a5 1256 next unless /\S/;
1d40e528 1257 trim_whitespace($_);
505ef4a5 1258 GetAliases($_) if $_;
6b09c160 1259 }
505ef4a5 1260}
6b09c160 1261
505ef4a5 1262sub OVERLOAD_handler() {
87931035 1263 for (; !/^$self->{BLOCK_re}/o; $_ = shift(@{ $self->{line} })) {
6b09c160 1264 next unless /\S/;
1d40e528 1265 trim_whitespace($_);
6b09c160 1266 while ( s/^\s*([\w:"\\)\+\-\*\/\%\<\>\.\&\|\^\!\~\{\}\=]+)\s*//) {
c2d2fdd0 1267 $self->{Overload} = 1 unless $self->{Overload};
7c3505a2 1268 my $overload = "$Package\::(".$1;
e1b52aff 1269 push(@{ $self->{InitFileCode} },
ffd4b99c 1270 " (void)$self->{newXS}(\"$overload\", XS_$Full_func_name, file$self->{proto});\n");
6b09c160 1271 }
1efd22b7 1272 }
6b09c160
YST
1273}
1274
505ef4a5 1275sub FALLBACK_handler() {
1efd22b7 1276 # the rest of the current line should contain either TRUE,
6b09c160 1277 # FALSE or UNDEF
1efd22b7 1278
1d40e528 1279 trim_whitespace($_);
6b09c160 1280 my %map = (
505ef4a5
JK
1281 TRUE => "&PL_sv_yes", 1 => "&PL_sv_yes",
1282 FALSE => "&PL_sv_no", 0 => "&PL_sv_no",
1283 UNDEF => "&PL_sv_undef",
1284 );
1efd22b7 1285
6b09c160 1286 # check for valid FALLBACK value
e6de4093 1287 death( $self, "Error: FALLBACK: TRUE/FALSE/UNDEF") unless exists $map{uc $_};
1efd22b7 1288
c2d2fdd0 1289 $self->{Fallback} = $map{uc $_};
6b09c160
YST
1290}
1291
1292
505ef4a5
JK
1293sub REQUIRE_handler () {
1294 # the rest of the current line should contain a version number
1295 my ($Ver) = $_;
6b09c160 1296
1d40e528 1297 trim_whitespace($Ver);
6b09c160 1298
e6de4093 1299 death( $self, "Error: REQUIRE expects a version number")
505ef4a5 1300 unless $Ver;
6b09c160 1301
505ef4a5 1302 # check that the version number is of the form n.n
e6de4093 1303 death( $self, "Error: REQUIRE: expected a number, got '$Ver'")
505ef4a5 1304 unless $Ver =~ /^\d+(\.\d*)?/;
6b09c160 1305
e6de4093 1306 death( $self, "Error: xsubpp $Ver (or better) required--this is only $VERSION.")
505ef4a5
JK
1307 unless $VERSION >= $Ver;
1308}
6b09c160 1309
505ef4a5
JK
1310sub VERSIONCHECK_handler () {
1311 # the rest of the current line should contain either ENABLE or
1312 # DISABLE
6b09c160 1313
1d40e528 1314 trim_whitespace($_);
6b09c160 1315
505ef4a5 1316 # check for ENABLE/DISABLE
e6de4093 1317 death( $self, "Error: VERSIONCHECK: ENABLE/DISABLE")
505ef4a5 1318 unless /^(ENABLE|DISABLE)/i;
6b09c160 1319
c2d2fdd0
JK
1320 $self->{WantVersionChk} = 1 if $1 eq 'ENABLE';
1321 $self->{WantVersionChk} = 0 if $1 eq 'DISABLE';
6b09c160 1322
505ef4a5 1323}
6b09c160 1324
505ef4a5
JK
1325sub PROTOTYPE_handler () {
1326 my $specified;
6b09c160 1327
e6de4093 1328 death( $self, "Error: Only 1 PROTOTYPE definition allowed per xsub")
cdfe2888 1329 if $self->{proto_in_this_xsub}++;
6b09c160 1330
87931035 1331 for (; !/^$self->{BLOCK_re}/o; $_ = shift(@{ $self->{line} })) {
505ef4a5
JK
1332 next unless /\S/;
1333 $specified = 1;
1d40e528 1334 trim_whitespace($_);
505ef4a5 1335 if ($_ eq 'DISABLE') {
cdfe2888 1336 $self->{ProtoThisXSUB} = 0;
505ef4a5
JK
1337 }
1338 elsif ($_ eq 'ENABLE') {
cdfe2888 1339 $self->{ProtoThisXSUB} = 1;
505ef4a5
JK
1340 }
1341 else {
1342 # remove any whitespace
1343 s/\s+//g;
e6de4093 1344 death( $self, "Error: Invalid prototype '$_'")
547742ac 1345 unless valid_proto_string($_);
cdfe2888 1346 $self->{ProtoThisXSUB} = C_string($_);
505ef4a5 1347 }
6b09c160
YST
1348 }
1349
505ef4a5 1350 # If no prototype specified, then assume empty prototype ""
cdfe2888 1351 $self->{ProtoThisXSUB} = 2 unless $specified;
6b09c160 1352
551f599a 1353 $self->{ProtoUsed} = 1;
505ef4a5 1354}
6b09c160 1355
505ef4a5 1356sub SCOPE_handler () {
e6de4093 1357 death( $self, "Error: Only 1 SCOPE declaration allowed per xsub")
cdfe2888 1358 if $self->{scope_in_this_xsub}++;
6b09c160 1359
1d40e528 1360 trim_whitespace($_);
2a09a23f 1361 death("Error: SCOPE: ENABLE/DISABLE")
505ef4a5 1362 unless /^(ENABLE|DISABLE)\b/i;
cdfe2888 1363 $self->{ScopeThisXSUB} = ( uc($1) eq 'ENABLE' );
505ef4a5 1364}
6b09c160 1365
505ef4a5
JK
1366sub PROTOTYPES_handler () {
1367 # the rest of the current line should contain either ENABLE or
1368 # DISABLE
6b09c160 1369
1d40e528 1370 trim_whitespace($_);
6b09c160 1371
505ef4a5 1372 # check for ENABLE/DISABLE
2a09a23f 1373 death("Error: PROTOTYPES: ENABLE/DISABLE")
505ef4a5 1374 unless /^(ENABLE|DISABLE)/i;
6b09c160 1375
c2d2fdd0
JK
1376 $self->{WantPrototypes} = 1 if $1 eq 'ENABLE';
1377 $self->{WantPrototypes} = 0 if $1 eq 'DISABLE';
551f599a
JK
1378 $self->{ProtoUsed} = 1;
1379
505ef4a5 1380}
387b6f8d 1381
505ef4a5 1382sub PushXSStack {
e749b684 1383 my $self = shift;
f0744969 1384 my %args = @_;
505ef4a5 1385 # Save the current file context.
b8862861 1386 push(@{ $self->{XSStack} }, {
505ef4a5 1387 type => 'file',
c2d2fdd0
JK
1388 LastLine => $self->{lastline},
1389 LastLineNo => $self->{lastline_no},
87931035 1390 Line => $self->{line},
b8862861 1391 LineNo => $self->{line_no},
c2d2fdd0
JK
1392 Filename => $self->{filename},
1393 Filepathname => $self->{filepathname},
505ef4a5 1394 Handle => $FH,
c2d2fdd0 1395 IsPipe => scalar($self->{filename} =~ /\|\s*$/),
505ef4a5
JK
1396 %args,
1397 });
387b6f8d 1398
505ef4a5 1399}
6b09c160 1400
505ef4a5
JK
1401sub INCLUDE_handler () {
1402 # the rest of the current line should contain a valid filename
6b09c160 1403
1d40e528 1404 trim_whitespace($_);
6b09c160 1405
e6de4093 1406 death( $self, "INCLUDE: filename missing")
505ef4a5 1407 unless $_;
6b09c160 1408
e6de4093 1409 death( $self, "INCLUDE: output pipe is illegal")
505ef4a5 1410 if /^\s*\|/;
6b09c160 1411
505ef4a5 1412 # simple minded recursion detector
e6de4093 1413 death( $self, "INCLUDE loop detected")
e1b52aff 1414 if $self->{IncludedFiles}->{$_};
6b09c160 1415
e1b52aff 1416 ++$self->{IncludedFiles}->{$_} unless /\|\s*$/;
505ef4a5
JK
1417
1418 if (/\|\s*$/ && /^\s*perl\s/) {
e6de4093
JK
1419 Warn( $self, "The INCLUDE directive with a command is discouraged." .
1420 " Use INCLUDE_COMMAND instead! In particular using 'perl'" .
1421 " in an 'INCLUDE: ... |' directive is not guaranteed to pick" .
1422 " up the correct perl. The INCLUDE_COMMAND directive allows" .
1423 " the use of \$^X as the currently running perl, see" .
1424 " 'perldoc perlxs' for details.");
505ef4a5 1425 }
387b6f8d 1426
e749b684 1427 $self->PushXSStack();
6b09c160 1428
505ef4a5 1429 $FH = Symbol::gensym();
6b09c160 1430
505ef4a5 1431 # open the new file
e6de4093 1432 open ($FH, "$_") or death( $self, "Cannot open '$_': $!");
6b09c160 1433
505ef4a5 1434 print Q(<<"EOF");
6b09c160 1435#
c2d2fdd0 1436#/* INCLUDE: Including '$_' from '$self->{filename}' */
6b09c160
YST
1437#
1438EOF
1439
c2d2fdd0
JK
1440 $self->{filename} = $_;
1441 $self->{filepathname} = File::Spec->catfile($self->{dir}, $self->{filename});
6b09c160 1442
505ef4a5
JK
1443 # Prime the pump by reading the first
1444 # non-blank line
6b09c160 1445
505ef4a5
JK
1446 # skip leading blank lines
1447 while (<$FH>) {
1448 last unless /^\s*$/;
387b6f8d
S
1449 }
1450
c2d2fdd0
JK
1451 $self->{lastline} = $_;
1452 $self->{lastline_no} = $.;
505ef4a5
JK
1453}
1454
494e8c4c 1455sub QuoteArgs {
505ef4a5
JK
1456 my $cmd = shift;
1457 my @args = split /\s+/, $cmd;
1458 $cmd = shift @args;
1459 for (@args) {
1460 $_ = q(").$_.q(") if !/^\"/ && length($_) > 0;
494e8c4c 1461 }
505ef4a5
JK
1462 return join (' ', ($cmd, @args));
1463}
494e8c4c 1464
505ef4a5
JK
1465sub INCLUDE_COMMAND_handler () {
1466 # the rest of the current line should contain a valid command
387b6f8d 1467
1d40e528 1468 trim_whitespace($_);
387b6f8d 1469
505ef4a5 1470 $_ = QuoteArgs($_) if $^O eq 'VMS';
494e8c4c 1471
e6de4093 1472 death( $self, "INCLUDE_COMMAND: command missing")
505ef4a5 1473 unless $_;
387b6f8d 1474
e6de4093 1475 death( $self, "INCLUDE_COMMAND: pipes are illegal")
505ef4a5 1476 if /^\s*\|/ or /\|\s*$/;
387b6f8d 1477
e749b684 1478 $self->PushXSStack( IsPipe => 1 );
387b6f8d 1479
505ef4a5 1480 $FH = Symbol::gensym();
387b6f8d 1481
505ef4a5
JK
1482 # If $^X is used in INCLUDE_COMMAND, we know it's supposed to be
1483 # the same perl interpreter as we're currently running
1484 s/^\s*\$\^X/$^X/;
387b6f8d 1485
505ef4a5
JK
1486 # open the new file
1487 open ($FH, "-|", "$_")
e6de4093 1488 or death( $self, "Cannot run command '$_' to include its output: $!");
387b6f8d 1489
505ef4a5 1490 print Q(<<"EOF");
387b6f8d 1491#
c2d2fdd0 1492#/* INCLUDE_COMMAND: Including output of '$_' from '$self->{filename}' */
387b6f8d
S
1493#
1494EOF
1495
c2d2fdd0
JK
1496 $self->{filename} = $_;
1497 $self->{filepathname} = $self->{filename};
1498 $self->{filepathname} =~ s/\"/\\"/g;
387b6f8d 1499
505ef4a5
JK
1500 # Prime the pump by reading the first
1501 # non-blank line
6b09c160 1502
505ef4a5
JK
1503 # skip leading blank lines
1504 while (<$FH>) {
1505 last unless /^\s*$/;
6b09c160
YST
1506 }
1507
c2d2fdd0
JK
1508 $self->{lastline} = $_;
1509 $self->{lastline_no} = $.;
505ef4a5 1510}
6b09c160 1511
e749b684 1512sub PopFile {
b8862861 1513 return 0 unless $self->{XSStack}->[-1]{type} eq 'file';
6b09c160 1514
b8862861 1515 my $data = pop @{ $self->{XSStack} };
c2d2fdd0 1516 my $ThisFile = $self->{filename};
505ef4a5 1517 my $isPipe = $data->{IsPipe};
6b09c160 1518
e1b52aff 1519 --$self->{IncludedFiles}->{$self->{filename}}
505ef4a5 1520 unless $isPipe;
6b09c160 1521
505ef4a5 1522 close $FH;
6b09c160 1523
505ef4a5
JK
1524 $FH = $data->{Handle};
1525 # $filename is the leafname, which for some reason isused for diagnostic
1526 # messages, whereas $filepathname is the full pathname, and is used for
1527 # #line directives.
c2d2fdd0
JK
1528 $self->{filename} = $data->{Filename};
1529 $self->{filepathname} = $data->{Filepathname};
1530 $self->{lastline} = $data->{LastLine};
1531 $self->{lastline_no} = $data->{LastLineNo};
87931035 1532 @{ $self->{line} } = @{ $data->{Line} };
b8862861 1533 @{ $self->{line_no} } = @{ $data->{LineNo} };
505ef4a5
JK
1534
1535 if ($isPipe and $? ) {
c2d2fdd0
JK
1536 --$self->{lastline_no};
1537 print STDERR "Error reading from pipe '$ThisFile': $! in $self->{filename}, line $self->{lastline_no}\n" ;
505ef4a5
JK
1538 exit 1;
1539 }
6b09c160 1540
505ef4a5 1541 print Q(<<"EOF");
6b09c160 1542#
c2d2fdd0 1543#/* INCLUDE: Returning to '$self->{filename}' from '$ThisFile' */
6b09c160
YST
1544#
1545EOF
1546
505ef4a5
JK
1547 return 1;
1548}
6b09c160 1549
6b09c160
YST
1550sub Q {
1551 my($text) = @_;
1552 $text =~ s/^#//gm;
1553 $text =~ s/\[\[/{/g;
1554 $text =~ s/\]\]/}/g;
1555 $text;
1556}
1557
87931035 1558# Read next xsub into @{ $self->{line} } from ($lastline, <$FH>).
6b09c160
YST
1559sub fetch_para {
1560 # parse paragraph
2a09a23f 1561 death("Error: Unterminated `#if/#ifdef/#ifndef'")
b8862861 1562 if !defined $self->{lastline} && $self->{XSStack}->[-1]{type} eq 'if';
87931035 1563 @{ $self->{line} } = ();
b8862861 1564 @{ $self->{line_no} } = ();
c2d2fdd0 1565 return PopFile() if !defined $self->{lastline};
6b09c160 1566
c2d2fdd0 1567 if ($self->{lastline} =~
6b09c160 1568 /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/) {
be5bcef7 1569 my $Module = $1;
6b09c160 1570 $Package = defined($2) ? $2 : ''; # keep -w happy
cdfe2888
JK
1571 $self->{Prefix} = defined($3) ? $3 : ''; # keep -w happy
1572 $self->{Prefix} = quotemeta $self->{Prefix};
ca406d08 1573 ($self->{Module_cname} = $Module) =~ s/\W/_/g;
3da1efaa 1574 ($self->{Packid} = $Package) =~ tr/:/_/;
7a522819
JK
1575 $self->{Packprefix} = $Package;
1576 $self->{Packprefix} .= "::" if $self->{Packprefix} ne "";
c2d2fdd0 1577 $self->{lastline} = "";
6b09c160
YST
1578 }
1579
1580 for (;;) {
1581 # Skip embedded PODs
c2d2fdd0
JK
1582 while ($self->{lastline} =~ /^=/) {
1583 while ($self->{lastline} = <$FH>) {
1584 last if ($self->{lastline} =~ /^=cut\s*$/);
6b09c160 1585 }
2a09a23f 1586 death("Error: Unterminated pod") unless $self->{lastline};
c2d2fdd0
JK
1587 $self->{lastline} = <$FH>;
1588 chomp $self->{lastline};
1589 $self->{lastline} =~ s/^\s+$//;
6b09c160 1590 }
c2d2fdd0 1591 if ($self->{lastline} !~ /^\s*#/ ||
1efd22b7
JK
1592 # CPP directives:
1593 # ANSI: if ifdef ifndef elif else endif define undef
1594 # line error pragma
1595 # gcc: warning include_next
1596 # obj-c: import
1597 # others: ident (gcc notes that some cpps have this one)
c2d2fdd0 1598 $self->{lastline} =~ /^#[ \t]*(?:(?:if|ifn?def|elif|else|endif|define|undef|pragma|error|warning|line\s+\d+|ident)\b|(?:include(?:_next)?|import)\s*["<].*[>"])/) {
87931035
JK
1599 last if $self->{lastline} =~ /^\S/ && @{ $self->{line} } && $self->{line}->[-1] eq "";
1600 push(@{ $self->{line} }, $self->{lastline});
b8862861 1601 push(@{ $self->{line_no} }, $self->{lastline_no});
6b09c160
YST
1602 }
1603
1604 # Read next line and continuation lines
c2d2fdd0
JK
1605 last unless defined($self->{lastline} = <$FH>);
1606 $self->{lastline_no} = $.;
6b09c160 1607 my $tmp_line;
c2d2fdd0
JK
1608 $self->{lastline} .= $tmp_line
1609 while ($self->{lastline} =~ /\\$/ && defined($tmp_line = <$FH>));
6b09c160 1610
c2d2fdd0
JK
1611 chomp $self->{lastline};
1612 $self->{lastline} =~ s/^\s+$//;
6b09c160 1613 }
87931035 1614 pop(@{ $self->{line} }), pop(@{ $self->{line_no} }) while @{ $self->{line} } && $self->{line}->[-1] eq "";
6b09c160
YST
1615 1;
1616}
1617
1618sub output_init {
87e6f370
JK
1619 my $argsref = shift;
1620 my ($type, $num, $var, $init, $printed_name) = (
1621 $argsref->{type},
1622 $argsref->{num},
1623 $argsref->{var},
1624 $argsref->{init},
1625 $argsref->{printed_name}
1626 );
f0744969 1627 my $arg = "ST(" . ($num - 1) . ")";
6b09c160
YST
1628
1629 if ( $init =~ /^=/ ) {
68f166a7 1630 if ($printed_name) {
6b09c160 1631 eval qq/print " $init\\n"/;
505ef4a5
JK
1632 }
1633 else {
6b09c160
YST
1634 eval qq/print "\\t$var $init\\n"/;
1635 }
9e831c8e 1636 warn $@ if $@;
505ef4a5
JK
1637 }
1638 else {
6b09c160 1639 if ( $init =~ s/^\+// && $num ) {
879afb6d
JK
1640 generate_init( {
1641 type => $type,
1642 num => $num,
1643 var => $var,
1644 printed_name => $printed_name,
1645 } );
505ef4a5 1646 }
68f166a7 1647 elsif ($printed_name) {
6b09c160
YST
1648 print ";\n";
1649 $init =~ s/^;//;
505ef4a5
JK
1650 }
1651 else {
6b09c160 1652 eval qq/print "\\t$var;\\n"/;
9e831c8e 1653 warn $@ if $@;
6b09c160
YST
1654 $init =~ s/^;//;
1655 }
706e7216 1656 $self->{deferred} .= eval qq/"\\n\\t$init\\n"/;
505ef4a5 1657 warn $@ if $@;
6b09c160
YST
1658 }
1659}
1660
6b09c160 1661sub generate_init {
879afb6d
JK
1662 my $argsref = shift;
1663 my ($type, $num, $var, $printed_name) = (
1664 $argsref->{type},
1665 $argsref->{num},
1666 $argsref->{var},
1667 $argsref->{printed_name},
1668 );
be5bcef7 1669 my $arg = "ST(" . ($num - 1) . ")";
69b19f32 1670 my ($argoff, $ntype);
be5bcef7 1671 $argoff = $num - 1;
6b09c160 1672
69b19f32
S
1673 my $typemaps = $self->{typemap};
1674
73e91d5a 1675 $type = tidy_type($type);
e6de4093 1676 blurt( $self, "Error: '$type' not in typemap"), return
69b19f32 1677 unless $typemaps->get_typemap(ctype => $type);
6b09c160
YST
1678
1679 ($ntype = $type) =~ s/\s*\*/Ptr/g;
be5bcef7 1680 my $subtype;
6b09c160 1681 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
69b19f32
S
1682 my $typem = $typemaps->get_typemap(ctype => $type);
1683 my $xstype = $typem->xstype;
1684 $xstype =~ s/OBJ$/REF/ if $func_name =~ /DESTROY$/;
1685 if ($xstype eq 'T_PV' and exists $self->{lengthof}->{$var}) {
68f166a7 1686 print "\t$var" unless $printed_name;
6b09c160
YST
1687 print " = ($type)SvPV($arg, STRLEN_length_of_$var);\n";
1688 die "default value not supported with length(NAME) supplied"
fe36d206 1689 if defined $self->{defaults}->{$var};
6b09c160
YST
1690 return;
1691 }
c2d2fdd0 1692 $type =~ tr/:/_/ unless $self->{hiertype};
69b19f32
S
1693
1694 my $inputmap = $typemaps->get_inputmap(xstype => $xstype);
1695 blurt( $self, "Error: No INPUT definition for type '$type', typekind '" . $type->xstype . "' found"), return
1696 unless defined $inputmap;
1697
1698 my $expr = $inputmap->cleaned_code;
1699 # Note: This gruesome bit either needs heavy rethinking or documentation. I vote for the former. --Steffen
6b09c160 1700 if ($expr =~ /DO_ARRAY_ELEM/) {
69b19f32
S
1701 my $subtypemap = $typemaps->get_typemap(ctype => $subtype);
1702 my $subinputmap = $typemaps->get_inputmap(xstype => $subtypemap->xstype);
e6de4093 1703 blurt( $self, "Error: '$subtype' not in typemap"), return
69b19f32
S
1704 unless $subtypemap;
1705 blurt( $self, "Error: No INPUT definition for type '$subtype', typekind '" . $subtypemap->xstype . "' found"), return
1706 unless $subinputmap;
1707 my $subexpr = $subinputmap->cleaned_code;
6b09c160
YST
1708 $subexpr =~ s/\$type/\$subtype/g;
1709 $subexpr =~ s/ntype/subtype/g;
1710 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1711 $subexpr =~ s/\n\t/\n\t\t/g;
1712 $subexpr =~ s/is not of (.*\")/[arg %d] is not of $1, ix_$var + 1/g;
1713 $subexpr =~ s/\$var/${var}[ix_$var - $argoff]/;
1714 $expr =~ s/DO_ARRAY_ELEM/$subexpr/;
1715 }
1716 if ($expr =~ m#/\*.*scope.*\*/#i) { # "scope" in C comments
cdfe2888 1717 $self->{ScopeThisXSUB} = 1;
6b09c160 1718 }
fe36d206 1719 if (defined($self->{defaults}->{$var})) {
6b09c160
YST
1720 $expr =~ s/(\t+)/$1 /g;
1721 $expr =~ s/ /\t/g;
68f166a7 1722 if ($printed_name) {
6b09c160 1723 print ";\n";
505ef4a5
JK
1724 }
1725 else {
6b09c160 1726 eval qq/print "\\t$var;\\n"/;
0bba9eb1 1727 warn $@ if $@;
6b09c160 1728 }
fe36d206 1729 if ($self->{defaults}->{$var} eq 'NO_INIT') {
706e7216 1730 $self->{deferred} .= eval qq/"\\n\\tif (items >= $num) {\\n$expr;\\n\\t}\\n"/;
505ef4a5
JK
1731 }
1732 else {
fe36d206 1733 $self->{deferred} .= eval qq/"\\n\\tif (items < $num)\\n\\t $var = $self->{defaults}->{$var};\\n\\telse {\\n$expr;\\n\\t}\\n"/;
6b09c160 1734 }
0bba9eb1 1735 warn $@ if $@;
505ef4a5 1736 }
cdfe2888 1737 elsif ($self->{ScopeThisXSUB} or $expr !~ /^\s*\$var =/) {
68f166a7 1738 if ($printed_name) {
6b09c160 1739 print ";\n";
505ef4a5
JK
1740 }
1741 else {
6b09c160 1742 eval qq/print "\\t$var;\\n"/;
0bba9eb1 1743 warn $@ if $@;
6b09c160 1744 }
706e7216 1745 $self->{deferred} .= eval qq/"\\n$expr;\\n"/;
0bba9eb1 1746 warn $@ if $@;
505ef4a5
JK
1747 }
1748 else {
6b09c160 1749 die "panic: do not know how to handle this branch for function pointers"
68f166a7 1750 if $printed_name;
6b09c160 1751 eval qq/print "$expr;\\n"/;
0bba9eb1 1752 warn $@ if $@;
6b09c160
YST
1753 }
1754}
1755
1756sub generate_output {
879afb6d
JK
1757 my $argsref = shift;
1758 my ($type, $num, $var, $do_setmagic, $do_push) = (
1759 $argsref->{type},
1760 $argsref->{num},
1761 $argsref->{var},
1762 $argsref->{do_setmagic},
1763 $argsref->{do_push}
1764 );
be5bcef7 1765 my $arg = "ST(" . ($num - ($num != 0)) . ")";
be5bcef7 1766 my $ntype;
6b09c160 1767
69b19f32
S
1768 my $typemaps = $self->{typemap};
1769
73e91d5a 1770 $type = tidy_type($type);
6b09c160
YST
1771 if ($type =~ /^array\(([^,]*),(.*)\)/) {
1772 print "\t$arg = sv_newmortal();\n";
1773 print "\tsv_setpvn($arg, (char *)$var, $2 * sizeof($1));\n";
1774 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
505ef4a5
JK
1775 }
1776 else {
69b19f32
S
1777 my $typemap = $typemaps->get_typemap(ctype => $type);
1778 my $outputmap = $typemaps->get_outputmap(xstype => $typemap->xstype);
e6de4093 1779 blurt( $self, "Error: '$type' not in typemap"), return
69b19f32
S
1780 unless $typemap;
1781 blurt( $self, "Error: No OUTPUT definition for type '$type', typekind '" . $typemap->xstype . "' found"), return
1782 unless $outputmap;
6b09c160
YST
1783 ($ntype = $type) =~ s/\s*\*/Ptr/g;
1784 $ntype =~ s/\(\)//g;
be5bcef7 1785 my $subtype;
6b09c160 1786 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
69b19f32
S
1787
1788 my $expr = $outputmap->cleaned_code;
6b09c160 1789 if ($expr =~ /DO_ARRAY_ELEM/) {
69b19f32
S
1790 my $subtypemap = $typemaps->get_typemap(ctype => $subtype);
1791 my $suboutputmap = $typemaps->get_outputmap(xstype => $subtypemap->xstype);
e6de4093 1792 blurt( $self, "Error: '$subtype' not in typemap"), return
69b19f32
S
1793 unless $subtypemap;
1794 blurt( $self, "Error: No OUTPUT definition for type '$subtype', typekind '" . $subtypemap->xstype . "' found"), return
1795 unless $suboutputmap;
1796 my $subexpr = $suboutputmap->cleaned_code;
6b09c160
YST
1797 $subexpr =~ s/ntype/subtype/g;
1798 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1799 $subexpr =~ s/\$var/${var}[ix_$var]/g;
1800 $subexpr =~ s/\n\t/\n\t\t/g;
1801 $expr =~ s/DO_ARRAY_ELEM\n/$subexpr/;
1802 eval "print qq\a$expr\a";
0bba9eb1 1803 warn $@ if $@;
6b09c160 1804 print "\t\tSvSETMAGIC(ST(ix_$var));\n" if $do_setmagic;
505ef4a5
JK
1805 }
1806 elsif ($var eq 'RETVAL') {
6b09c160 1807 if ($expr =~ /^\t\$arg = new/) {
505ef4a5
JK
1808 # We expect that $arg has refcnt 1, so we need to
1809 # mortalize it.
1810 eval "print qq\a$expr\a";
0bba9eb1 1811 warn $@ if $@;
505ef4a5
JK
1812 print "\tsv_2mortal(ST($num));\n";
1813 print "\tSvSETMAGIC(ST($num));\n" if $do_setmagic;
1814 }
1815 elsif ($expr =~ /^\s*\$arg\s*=/) {
1816 # We expect that $arg has refcnt >=1, so we need
1817 # to mortalize it!
1818 eval "print qq\a$expr\a";
0bba9eb1 1819 warn $@ if $@;
505ef4a5
JK
1820 print "\tsv_2mortal(ST(0));\n";
1821 print "\tSvSETMAGIC(ST(0));\n" if $do_setmagic;
6b09c160 1822 }
505ef4a5
JK
1823 else {
1824 # Just hope that the entry would safely write it
1825 # over an already mortalized value. By
1826 # coincidence, something like $arg = &sv_undef
1827 # works too.
1828 print "\tST(0) = sv_newmortal();\n";
1829 eval "print qq\a$expr\a";
0bba9eb1 1830 warn $@ if $@;
505ef4a5
JK
1831 # new mortals don't have set magic
1832 }
1833 }
1834 elsif ($do_push) {
6b09c160
YST
1835 print "\tPUSHs(sv_newmortal());\n";
1836 $arg = "ST($num)";
1837 eval "print qq\a$expr\a";
0bba9eb1 1838 warn $@ if $@;
6b09c160 1839 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
505ef4a5
JK
1840 }
1841 elsif ($arg =~ /^ST\(\d+\)$/) {
6b09c160 1842 eval "print qq\a$expr\a";
0bba9eb1 1843 warn $@ if $@;
6b09c160
YST
1844 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1845 }
1846 }
1847}
1848
6b09c160 18491;
27b7514f
JK
1850
1851# vim: ts=2 sw=2 et: