/
ParseXS.pm
1995 lines (1727 loc) · 60 KB
/
ParseXS.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package ExtUtils::ParseXS;
use strict;
use 5.006001;
use Cwd;
use Config;
use Exporter;
use File::Basename;
use File::Spec;
use Symbol;
our $VERSION;
BEGIN {
$VERSION = '3.18';
}
use ExtUtils::ParseXS::Constants $VERSION;
use ExtUtils::ParseXS::CountLines $VERSION;
use ExtUtils::ParseXS::Utilities $VERSION;
$VERSION = eval $VERSION if $VERSION =~ /_/;
use ExtUtils::ParseXS::Utilities qw(
standard_typemap_locations
trim_whitespace
tidy_type
C_string
valid_proto_string
process_typemaps
make_targetable
map_type
standard_XS_defs
assign_func_args
analyze_preprocessor_statements
set_cond
Warn
current_line_number
blurt
death
check_conditional_preprocessor_statements
escape_file_for_line_directive
report_typemap_failure
);
our @ISA = qw(Exporter);
our @EXPORT_OK = qw(
process_file
report_error_count
);
# The scalars in the line below remain as 'our' variables because pulling
# them into $self led to build problems. In most cases, strings being
# 'eval'-ed contain the variables' names hard-coded.
our (
$Package, $func_name, $Full_func_name, $pname, $ALIAS,
);
our $self = bless {} => __PACKAGE__;
sub process_file {
# Allow for $package->process_file(%hash) in the future
my ($pkg, %options) = @_ % 2 ? @_ : (__PACKAGE__, @_);
$self->{ProtoUsed} = exists $options{prototypes};
# Set defaults.
my %args = (
argtypes => 1,
csuffix => '.c',
except => 0,
hiertype => 0,
inout => 1,
linenumbers => 1,
optimize => 1,
output => \*STDOUT,
prototypes => 0,
typemap => [],
versioncheck => 1,
FH => Symbol::gensym(),
%options,
);
$args{except} = $args{except} ? ' TRY' : '';
# Global Constants
my ($Is_VMS, $SymSet);
if ($^O eq 'VMS') {
$Is_VMS = 1;
# Establish set of global symbols with max length 28, since xsubpp
# will later add the 'XS_' prefix.
require ExtUtils::XSSymSet;
$SymSet = ExtUtils::XSSymSet->new(28);
}
@{ $self->{XSStack} } = ({type => 'none'});
$self->{InitFileCode} = [ @ExtUtils::ParseXS::Constants::InitFileCode ];
$self->{Overload} = 0;
$self->{errors} = 0;
$self->{Fallback} = '&PL_sv_undef';
# Most of the 1500 lines below uses these globals. We'll have to
# clean this up sometime, probably. For now, we just pull them out
# of %args. -Ken
$self->{hiertype} = $args{hiertype};
$self->{WantPrototypes} = $args{prototypes};
$self->{WantVersionChk} = $args{versioncheck};
$self->{WantLineNumbers} = $args{linenumbers};
$self->{IncludedFiles} = {};
die "Missing required parameter 'filename'" unless $args{filename};
$self->{filepathname} = $args{filename};
($self->{dir}, $self->{filename}) =
(dirname($args{filename}), basename($args{filename}));
$self->{filepathname} =~ s/\\/\\\\/g;
$self->{IncludedFiles}->{$args{filename}}++;
# Open the output file if given as a string. If they provide some
# other kind of reference, trust them that we can print to it.
if (not ref $args{output}) {
open my($fh), "> $args{output}" or die "Can't create $args{output}: $!";
$args{outfile} = $args{output};
$args{output} = $fh;
}
# Really, we shouldn't have to chdir() or select() in the first
# place. For now, just save and restore.
my $orig_cwd = cwd();
my $orig_fh = select();
chdir($self->{dir});
my $pwd = cwd();
my $csuffix = $args{csuffix};
if ($self->{WantLineNumbers}) {
my $cfile;
if ( $args{outfile} ) {
$cfile = $args{outfile};
}
else {
$cfile = $args{filename};
$cfile =~ s/\.xs$/$csuffix/i or $cfile .= $csuffix;
}
tie(*PSEUDO_STDOUT, 'ExtUtils::ParseXS::CountLines', $cfile, $args{output});
select PSEUDO_STDOUT;
}
else {
select $args{output};
}
$self->{typemap} = process_typemaps( $args{typemap}, $pwd );
my $END = "!End!\n\n"; # "impossible" keyword (multiple newline)
# Match an XS keyword
$self->{BLOCK_re} = '\s*(' .
join('|' => @ExtUtils::ParseXS::Constants::XSKeywords) .
"|$END)\\s*:";
our ($C_group_rex, $C_arg);
# Group in C (no support for comments or literals)
$C_group_rex = qr/ [({\[]
(?: (?> [^()\[\]{}]+ ) | (??{ $C_group_rex }) )*
[)}\]] /x;
# Chunk in C without comma at toplevel (no comments):
$C_arg = qr/ (?: (?> [^()\[\]{},"']+ )
| (??{ $C_group_rex })
| " (?: (?> [^\\"]+ )
| \\.
)* " # String literal
| ' (?: (?> [^\\']+ ) | \\. )* ' # Char literal
)* /xs;
# Since at this point we're ready to begin printing to the output file and
# reading from the input file, I want to get as much data as possible into
# the proto-object $self. That means assigning to $self and elements of
# %args referenced below this point.
# HOWEVER: This resulted in an error when I tried:
# $args{'s'} ---> $self->{s}.
# Use of uninitialized value in quotemeta at
# .../blib/lib/ExtUtils/ParseXS.pm line 733
foreach my $datum ( qw| argtypes except inout optimize | ) {
$self->{$datum} = $args{$datum};
}
# Identify the version of xsubpp used
print <<EOM;
/*
* This file was generated automatically by ExtUtils::ParseXS version $VERSION from the
* contents of $self->{filename}. Do not edit this file, edit $self->{filename} instead.
*
* ANY CHANGES MADE HERE WILL BE LOST!
*
*/
EOM
print("#line 1 \"" . escape_file_for_line_directive($self->{filepathname}) . "\"\n")
if $self->{WantLineNumbers};
# Open the input file (using $self->{filename} which
# is a basename'd $args{filename} due to chdir above)
open($self->{FH}, '<', $self->{filename}) or die "cannot open $self->{filename}: $!\n";
firstmodule:
while (readline($self->{FH})) {
if (/^=/) {
my $podstartline = $.;
do {
if (/^=cut\s*$/) {
# We can't just write out a /* */ comment, as our embedded
# POD might itself be in a comment. We can't put a /**/
# comment inside #if 0, as the C standard says that the source
# file is decomposed into preprocessing characters in the stage
# before preprocessing commands are executed.
# I don't want to leave the text as barewords, because the spec
# isn't clear whether macros are expanded before or after
# preprocessing commands are executed, and someone pathological
# may just have defined one of the 3 words as a macro that does
# something strange. Multiline strings are illegal in C, so
# the "" we write must be a string literal. And they aren't
# concatenated until 2 steps later, so we are safe.
# - Nicholas Clark
print("#if 0\n \"Skipped embedded POD.\"\n#endif\n");
printf("#line %d \"%s\"\n", $. + 1, escape_file_for_line_directive($self->{filepathname}))
if $self->{WantLineNumbers};
next firstmodule
}
} while (readline($self->{FH}));
# At this point $. is at end of file so die won't state the start
# of the problem, and as we haven't yet read any lines &death won't
# show the correct line in the message either.
die ("Error: Unterminated pod in $self->{filename}, line $podstartline\n")
unless $self->{lastline};
}
last if ($Package, $self->{Prefix}) =
/^MODULE\s*=\s*[\w:]+(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/;
print $_;
}
unless (defined $_) {
warn "Didn't find a 'MODULE ... PACKAGE ... PREFIX' line\n";
exit 0; # Not a fatal error for the caller process
}
print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $self->{WantLineNumbers};
standard_XS_defs();
print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $self->{WantLineNumbers};
$self->{lastline} = $_;
$self->{lastline_no} = $.;
my $BootCode_ref = [];
my $XSS_work_idx = 0;
my $cpp_next_tmp = 'XSubPPtmpAAAA';
PARAGRAPH:
while ($self->fetch_para()) {
my $outlist_ref = [];
# Print initial preprocessor statements and blank lines
while (@{ $self->{line} } && $self->{line}->[0] !~ /^[^\#]/) {
my $ln = shift(@{ $self->{line} });
print $ln, "\n";
next unless $ln =~ /^\#\s*((if)(?:n?def)?|elsif|else|endif)\b/;
my $statement = $+;
( $self, $XSS_work_idx, $BootCode_ref ) =
analyze_preprocessor_statements(
$self, $statement, $XSS_work_idx, $BootCode_ref
);
}
next PARAGRAPH unless @{ $self->{line} };
if ($XSS_work_idx && !$self->{XSStack}->[$XSS_work_idx]{varname}) {
# We are inside an #if, but have not yet #defined its xsubpp variable.
print "#define $cpp_next_tmp 1\n\n";
push(@{ $self->{InitFileCode} }, "#if $cpp_next_tmp\n");
push(@{ $BootCode_ref }, "#if $cpp_next_tmp");
$self->{XSStack}->[$XSS_work_idx]{varname} = $cpp_next_tmp++;
}
$self->death(
"Code is not inside a function"
." (maybe last function was ended by a blank line "
." followed by a statement on column one?)")
if $self->{line}->[0] =~ /^\s/;
# initialize info arrays
foreach my $member (qw(args_match var_types defaults arg_list
argtype_seen in_out lengthof))
{
$self->{$member} = {};
}
$self->{proto_arg} = [];
$self->{processing_arg_with_types} = undef;
$self->{proto_in_this_xsub} = undef;
$self->{scope_in_this_xsub} = undef;
$self->{interface} = undef;
$self->{interface_macro} = 'XSINTERFACE_FUNC';
$self->{interface_macro_set} = 'XSINTERFACE_FUNC_SET';
$self->{ProtoThisXSUB} = $self->{WantPrototypes};
$self->{ScopeThisXSUB} = 0;
my $xsreturn = 0;
$_ = shift(@{ $self->{line} });
while (my $kwd = $self->check_keyword("REQUIRE|PROTOTYPES|EXPORT_XSUB_SYMBOLS|FALLBACK|VERSIONCHECK|INCLUDE(?:_COMMAND)?|SCOPE")) {
my $method = $kwd . "_handler";
$self->$method($_);
next PARAGRAPH unless @{ $self->{line} };
$_ = shift(@{ $self->{line} });
}
if ($self->check_keyword("BOOT")) {
check_conditional_preprocessor_statements($self);
push (@{ $BootCode_ref }, "#line $self->{line_no}->[@{ $self->{line_no} } - @{ $self->{line} }] \""
. escape_file_for_line_directive($self->{filepathname}) . "\"")
if $self->{WantLineNumbers} && $self->{line}->[0] !~ /^\s*#\s*line\b/;
push (@{ $BootCode_ref }, @{ $self->{line} }, "");
next PARAGRAPH;
}
# extract return type, function name and arguments
($self->{ret_type}) = tidy_type($_);
my $RETVAL_no_return = 1 if $self->{ret_type} =~ s/^NO_OUTPUT\s+//;
# Allow one-line ANSI-like declaration
unshift @{ $self->{line} }, $2
if $self->{argtypes}
and $self->{ret_type} =~ s/^(.*?\w.*?)\s*\b(\w+\s*\(.*)/$1/s;
# a function definition needs at least 2 lines
$self->blurt("Error: Function definition too short '$self->{ret_type}'"), next PARAGRAPH
unless @{ $self->{line} };
my $externC = 1 if $self->{ret_type} =~ s/^extern "C"\s+//;
my $static = 1 if $self->{ret_type} =~ s/^static\s+//;
my $func_header = shift(@{ $self->{line} });
$self->blurt("Error: Cannot parse function definition from '$func_header'"), next PARAGRAPH
unless $func_header =~ /^(?:([\w:]*)::)?(\w+)\s*\(\s*(.*?)\s*\)\s*(const)?\s*(;\s*)?$/s;
my ($class, $orig_args);
($class, $func_name, $orig_args) = ($1, $2, $3);
$class = "$4 $class" if $4;
($pname = $func_name) =~ s/^($self->{Prefix})?/$self->{Packprefix}/;
my $clean_func_name;
($clean_func_name = $func_name) =~ s/^$self->{Prefix}//;
$Full_func_name = "$self->{Packid}_$clean_func_name";
if ($Is_VMS) {
$Full_func_name = $SymSet->addsym($Full_func_name);
}
# Check for duplicate function definition
for my $tmp (@{ $self->{XSStack} }) {
next unless defined $tmp->{functions}{$Full_func_name};
Warn( $self, "Warning: duplicate function definition '$clean_func_name' detected");
last;
}
$self->{XSStack}->[$XSS_work_idx]{functions}{$Full_func_name}++;
%{ $self->{XsubAliases} } = ();
%{ $self->{XsubAliasValues} } = ();
%{ $self->{Interfaces} } = ();
@{ $self->{Attributes} } = ();
$self->{DoSetMagic} = 1;
$orig_args =~ s/\\\s*/ /g; # process line continuations
my @args;
my (@fake_INPUT_pre); # For length(s) generated variables
my (@fake_INPUT);
my $only_C_inlist_ref = {}; # Not in the signature of Perl function
if ($self->{argtypes} and $orig_args =~ /\S/) {
my $args = "$orig_args ,";
if ($args =~ /^( (??{ $C_arg }) , )* $ /x) {
@args = ($args =~ /\G ( (??{ $C_arg }) ) , /xg);
for ( @args ) {
s/^\s+//;
s/\s+$//;
my ($arg, $default) = ($_ =~ m/ ( [^=]* ) ( (?: = .* )? ) /x);
my ($pre, $len_name) = ($arg =~ /(.*?) \s*
\b ( \w+ | length\( \s*\w+\s* \) )
\s* $ /x);
next unless defined($pre) && length($pre);
my $out_type = '';
my $inout_var;
if ($self->{inout} and s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\b\s*//) {
my $type = $1;
$out_type = $type if $type ne 'IN';
$arg =~ s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\b\s*//;
$pre =~ s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\b\s*//;
}
my $islength;
if ($len_name =~ /^length\( \s* (\w+) \s* \)\z/x) {
$len_name = "XSauto_length_of_$1";
$islength = 1;
die "Default value on length() argument: '$_'"
if length $default;
}
if (length $pre or $islength) { # Has a type
if ($islength) {
push @fake_INPUT_pre, $arg;
}
else {
push @fake_INPUT, $arg;
}
# warn "pushing '$arg'\n";
$self->{argtype_seen}->{$len_name}++;
$_ = "$len_name$default"; # Assigns to @args
}
$only_C_inlist_ref->{$_} = 1 if $out_type eq "OUTLIST" or $islength;
push @{ $outlist_ref }, $len_name if $out_type =~ /OUTLIST$/;
$self->{in_out}->{$len_name} = $out_type if $out_type;
}
}
else {
@args = split(/\s*,\s*/, $orig_args);
Warn( $self, "Warning: cannot parse argument list '$orig_args', fallback to split");
}
}
else {
@args = split(/\s*,\s*/, $orig_args);
for (@args) {
if ($self->{inout} and s/^(IN|IN_OUTLIST|OUTLIST|IN_OUT|OUT)\b\s*//) {
my $out_type = $1;
next if $out_type eq 'IN';
$only_C_inlist_ref->{$_} = 1 if $out_type eq "OUTLIST";
if ($out_type =~ /OUTLIST$/) {
push @{ $outlist_ref }, undef;
}
$self->{in_out}->{$_} = $out_type;
}
}
}
if (defined($class)) {
my $arg0 = ((defined($static) or $func_name eq 'new')
? "CLASS" : "THIS");
unshift(@args, $arg0);
}
my $extra_args = 0;
my @args_num = ();
my $num_args = 0;
my $report_args = '';
my $ellipsis;
foreach my $i (0 .. $#args) {
if ($args[$i] =~ s/\.\.\.//) {
$ellipsis = 1;
if ($args[$i] eq '' && $i == $#args) {
$report_args .= ", ...";
pop(@args);
last;
}
}
if ($only_C_inlist_ref->{$args[$i]}) {
push @args_num, undef;
}
else {
push @args_num, ++$num_args;
$report_args .= ", $args[$i]";
}
if ($args[$i] =~ /^([^=]*[^\s=])\s*=\s*(.*)/s) {
$extra_args++;
$args[$i] = $1;
$self->{defaults}->{$args[$i]} = $2;
$self->{defaults}->{$args[$i]} =~ s/"/\\"/g;
}
$self->{proto_arg}->[$i+1] = '$';
}
my $min_args = $num_args - $extra_args;
$report_args =~ s/"/\\"/g;
$report_args =~ s/^,\s+//;
$self->{func_args} = assign_func_args($self, \@args, $class);
@{ $self->{args_match} }{@args} = @args_num;
my $PPCODE = grep(/^\s*PPCODE\s*:/, @{ $self->{line} });
my $CODE = grep(/^\s*CODE\s*:/, @{ $self->{line} });
# Detect CODE: blocks which use ST(n)= or XST_m*(n,v)
# to set explicit return values.
my $EXPLICIT_RETURN = ($CODE &&
("@{ $self->{line} }" =~ /(\bST\s*\([^;]*=) | (\bXST_m\w+\s*\()/x ));
# The $ALIAS which follows is only explicitly called within the scope of
# process_file(). In principle, it ought to be a lexical, i.e., 'my
# $ALIAS' like the other nearby variables. However, implementing that
# change produced a slight difference in the resulting .c output in at
# least two distributions: B/BD/BDFOY/Crypt-Rijndael and
# G/GF/GFUJI/Hash-FieldHash. The difference is, arguably, an improvement
# in the resulting C code. Example:
# 388c388
# < GvNAME(CvGV(cv)),
# ---
# > "Crypt::Rijndael::encrypt",
# But at this point we're committed to generating the *same* C code that
# the current version of ParseXS.pm does. So we're declaring it as 'our'.
$ALIAS = grep(/^\s*ALIAS\s*:/, @{ $self->{line} });
my $INTERFACE = grep(/^\s*INTERFACE\s*:/, @{ $self->{line} });
$xsreturn = 1 if $EXPLICIT_RETURN;
$externC = $externC ? qq[extern "C"] : "";
# print function header
print Q(<<"EOF");
#$externC
#XS_EUPXS(XS_${Full_func_name}); /* prototype to pass -Wmissing-prototypes */
#XS_EUPXS(XS_${Full_func_name})
#[[
# dVAR; dXSARGS;
EOF
print Q(<<"EOF") if $ALIAS;
# dXSI32;
EOF
print Q(<<"EOF") if $INTERFACE;
# dXSFUNCTION($self->{ret_type});
EOF
$self->{cond} = set_cond($ellipsis, $min_args, $num_args);
print Q(<<"EOF") if $self->{except};
# char errbuf[1024];
# *errbuf = '\\0';
EOF
if($self->{cond}) {
print Q(<<"EOF");
# if ($self->{cond})
# croak_xs_usage(cv, "$report_args");
EOF
}
else {
# cv likely to be unused
print Q(<<"EOF");
# PERL_UNUSED_VAR(cv); /* -W */
EOF
}
#gcc -Wall: if an xsub has PPCODE is used
#it is possible none of ST, XSRETURN or XSprePUSH macros are used
#hence 'ax' (setup by dXSARGS) is unused
#XXX: could breakup the dXSARGS; into dSP;dMARK;dITEMS
#but such a move could break third-party extensions
print Q(<<"EOF") if $PPCODE;
# PERL_UNUSED_VAR(ax); /* -Wall */
EOF
print Q(<<"EOF") if $PPCODE;
# SP -= items;
EOF
# Now do a block of some sort.
$self->{condnum} = 0;
$self->{cond} = ''; # last CASE: conditional
push(@{ $self->{line} }, "$END:");
push(@{ $self->{line_no} }, $self->{line_no}->[-1]);
$_ = '';
check_conditional_preprocessor_statements();
while (@{ $self->{line} }) {
$self->CASE_handler($_) if $self->check_keyword("CASE");
print Q(<<"EOF");
# $self->{except} [[
EOF
# do initialization of input variables
$self->{thisdone} = 0;
$self->{retvaldone} = 0;
$self->{deferred} = "";
%{ $self->{arg_list} } = ();
$self->{gotRETVAL} = 0;
$self->INPUT_handler($_);
$self->process_keyword("INPUT|PREINIT|INTERFACE_MACRO|C_ARGS|ALIAS|ATTRS|PROTOTYPE|SCOPE|OVERLOAD");
print Q(<<"EOF") if $self->{ScopeThisXSUB};
# ENTER;
# [[
EOF
if (!$self->{thisdone} && defined($class)) {
if (defined($static) or $func_name eq 'new') {
print "\tchar *";
$self->{var_types}->{"CLASS"} = "char *";
generate_init( {
type => "char *",
num => 1,
var => "CLASS",
printed_name => undef,
} );
}
else {
print "\t$class *";
$self->{var_types}->{"THIS"} = "$class *";
generate_init( {
type => "$class *",
num => 1,
var => "THIS",
printed_name => undef,
} );
}
}
# These are set if OUTPUT is found and/or CODE using RETVAL
$self->{have_OUTPUT} = $self->{have_CODE_with_RETVAL} = 0;
my ($wantRETVAL);
# do code
if (/^\s*NOT_IMPLEMENTED_YET/) {
print "\n\tPerl_croak(aTHX_ \"$pname: not implemented yet\");\n";
$_ = '';
}
else {
if ($self->{ret_type} ne "void") {
print "\t" . map_type($self, $self->{ret_type}, 'RETVAL') . ";\n"
if !$self->{retvaldone};
$self->{args_match}->{"RETVAL"} = 0;
$self->{var_types}->{"RETVAL"} = $self->{ret_type};
my $outputmap = $self->{typemap}->get_outputmap( ctype => $self->{ret_type} );
print "\tdXSTARG;\n"
if $self->{optimize} and $outputmap and $outputmap->targetable;
}
if (@fake_INPUT or @fake_INPUT_pre) {
unshift @{ $self->{line} }, @fake_INPUT_pre, @fake_INPUT, $_;
$_ = "";
$self->{processing_arg_with_types} = 1;
$self->INPUT_handler($_);
}
print $self->{deferred};
$self->process_keyword("INIT|ALIAS|ATTRS|PROTOTYPE|INTERFACE_MACRO|INTERFACE|C_ARGS|OVERLOAD");
if ($self->check_keyword("PPCODE")) {
$self->print_section();
$self->death("PPCODE must be last thing") if @{ $self->{line} };
print "\tLEAVE;\n" if $self->{ScopeThisXSUB};
print "\tPUTBACK;\n\treturn;\n";
}
elsif ($self->check_keyword("CODE")) {
my $consumed_code = $self->print_section();
if ($consumed_code =~ /\bRETVAL\b/) {
$self->{have_CODE_with_RETVAL} = 1;
}
}
elsif (defined($class) and $func_name eq "DESTROY") {
print "\n\t";
print "delete THIS;\n";
}
else {
print "\n\t";
if ($self->{ret_type} ne "void") {
print "RETVAL = ";
$wantRETVAL = 1;
}
if (defined($static)) {
if ($func_name eq 'new') {
$func_name = "$class";
}
else {
print "${class}::";
}
}
elsif (defined($class)) {
if ($func_name eq 'new') {
$func_name .= " $class";
}
else {
print "THIS->";
}
}
$func_name =~ s/^\Q$args{'s'}//
if exists $args{'s'};
$func_name = 'XSFUNCTION' if $self->{interface};
print "$func_name($self->{func_args});\n";
}
}
# do output variables
$self->{gotRETVAL} = 0; # 1 if RETVAL seen in OUTPUT section;
undef $self->{RETVAL_code} ; # code to set RETVAL (from OUTPUT section);
# $wantRETVAL set if 'RETVAL =' autogenerated
($wantRETVAL, $self->{ret_type}) = (0, 'void') if $RETVAL_no_return;
undef %{ $self->{outargs} };
$self->process_keyword("POSTCALL|OUTPUT|ALIAS|ATTRS|PROTOTYPE|OVERLOAD");
# A CODE section with RETVAL, but no OUTPUT? FAIL!
if ($self->{have_CODE_with_RETVAL} and not $self->{have_OUTPUT} and $self->{ret_type} ne 'void') {
$self->Warn("Warning: Found a 'CODE' section which seems to be using 'RETVAL' but no 'OUTPUT' section.");
}
generate_output( {
type => $self->{var_types}->{$_},
num => $self->{args_match}->{$_},
var => $_,
do_setmagic => $self->{DoSetMagic},
do_push => undef,
} ) for grep $self->{in_out}->{$_} =~ /OUT$/, keys %{ $self->{in_out} };
my $prepush_done;
# all OUTPUT done, so now push the return value on the stack
if ($self->{gotRETVAL} && $self->{RETVAL_code}) {
print "\t$self->{RETVAL_code}\n";
}
elsif ($self->{gotRETVAL} || $wantRETVAL) {
my $outputmap = $self->{typemap}->get_outputmap( ctype => $self->{ret_type} );
my $t = $self->{optimize} && $outputmap && $outputmap->targetable;
# Although the '$var' declared in the next line is never explicitly
# used within this 'elsif' block, commenting it out leads to
# disaster, starting with the first 'eval qq' inside the 'elsif' block
# below.
# It appears that this is related to the fact that at this point the
# value of $t is a reference to an array whose [2] element includes
# '$var' as a substring:
# <i> <> <(IV)$var>
my $var = 'RETVAL';
my $type = $self->{ret_type};
if ($t and not $t->{with_size} and $t->{type} eq 'p') {
# PUSHp corresponds to setpvn. Treat setpv directly
my $what = eval qq("$t->{what}");
warn $@ if $@;
print "\tsv_setpv(TARG, $what); XSprePUSH; PUSHTARG;\n";
$prepush_done = 1;
}
elsif ($t) {
my $what = eval qq("$t->{what}");
warn $@ if $@;
my $tsize = $t->{what_size};
$tsize = '' unless defined $tsize;
$tsize = eval qq("$tsize");
warn $@ if $@;
print "\tXSprePUSH; PUSH$t->{type}($what$tsize);\n";
$prepush_done = 1;
}
else {
# RETVAL almost never needs SvSETMAGIC()
generate_output( {
type => $self->{ret_type},
num => 0,
var => 'RETVAL',
do_setmagic => 0,
do_push => undef,
} );
}
}
$xsreturn = 1 if $self->{ret_type} ne "void";
my $num = $xsreturn;
my $c = @{ $outlist_ref };
print "\tXSprePUSH;" if $c and not $prepush_done;
print "\tEXTEND(SP,$c);\n" if $c;
$xsreturn += $c;
generate_output( {
type => $self->{var_types}->{$_},
num => $num++,
var => $_,
do_setmagic => 0,
do_push => 1,
} ) for @{ $outlist_ref };
# do cleanup
$self->process_keyword("CLEANUP|ALIAS|ATTRS|PROTOTYPE|OVERLOAD");
print Q(<<"EOF") if $self->{ScopeThisXSUB};
# ]]
EOF
print Q(<<"EOF") if $self->{ScopeThisXSUB} and not $PPCODE;
# LEAVE;
EOF
# print function trailer
print Q(<<"EOF");
# ]]
EOF
print Q(<<"EOF") if $self->{except};
# BEGHANDLERS
# CATCHALL
# sprintf(errbuf, "%s: %s\\tpropagated", Xname, Xreason);
# ENDHANDLERS
EOF
if ($self->check_keyword("CASE")) {
$self->blurt("Error: No 'CASE:' at top of function")
unless $self->{condnum};
$_ = "CASE: $_"; # Restore CASE: label
next;
}
last if $_ eq "$END:";
$self->death(/^$self->{BLOCK_re}/o ? "Misplaced '$1:'" : "Junk at end of function ($_)");
}
print Q(<<"EOF") if $self->{except};
# if (errbuf[0])
# Perl_croak(aTHX_ errbuf);
EOF
if ($xsreturn) {
print Q(<<"EOF") unless $PPCODE;
# XSRETURN($xsreturn);
EOF
}
else {
print Q(<<"EOF") unless $PPCODE;
# XSRETURN_EMPTY;
EOF
}
print Q(<<"EOF");
#]]
#
EOF
$self->{newXS} = "newXS";
$self->{proto} = "";
# Build the prototype string for the xsub
if ($self->{ProtoThisXSUB}) {
$self->{newXS} = "newXSproto_portable";
if ($self->{ProtoThisXSUB} eq 2) {
# User has specified empty prototype
}
elsif ($self->{ProtoThisXSUB} eq 1) {
my $s = ';';
if ($min_args < $num_args) {
$s = '';
$self->{proto_arg}->[$min_args] .= ";";
}
push @{ $self->{proto_arg} }, "$s\@"
if $ellipsis;
$self->{proto} = join ("", grep defined, @{ $self->{proto_arg} } );
}
else {
# User has specified a prototype
$self->{proto} = $self->{ProtoThisXSUB};
}
$self->{proto} = qq{, "$self->{proto}"};
}
if (%{ $self->{XsubAliases} }) {
$self->{XsubAliases}->{$pname} = 0
unless defined $self->{XsubAliases}->{$pname};
while ( my ($xname, $value) = each %{ $self->{XsubAliases} }) {
push(@{ $self->{InitFileCode} }, Q(<<"EOF"));
# cv = $self->{newXS}(\"$xname\", XS_$Full_func_name, file$self->{proto});
# XSANY.any_i32 = $value;
EOF
}
}
elsif (@{ $self->{Attributes} }) {
push(@{ $self->{InitFileCode} }, Q(<<"EOF"));
# cv = $self->{newXS}(\"$pname\", XS_$Full_func_name, file$self->{proto});
# apply_attrs_string("$Package", cv, "@{ $self->{Attributes} }", 0);
EOF
}
elsif ($self->{interface}) {
while ( my ($yname, $value) = each %{ $self->{Interfaces} }) {
$yname = "$Package\::$yname" unless $yname =~ /::/;
push(@{ $self->{InitFileCode} }, Q(<<"EOF"));
# cv = $self->{newXS}(\"$yname\", XS_$Full_func_name, file$self->{proto});
# $self->{interface_macro_set}(cv,$value);
EOF
}
}
elsif($self->{newXS} eq 'newXS'){ # work around P5NCI's empty newXS macro
push(@{ $self->{InitFileCode} },
" $self->{newXS}(\"$pname\", XS_$Full_func_name, file$self->{proto});\n");
}
else {
push(@{ $self->{InitFileCode} },
" (void)$self->{newXS}(\"$pname\", XS_$Full_func_name, file$self->{proto});\n");
}
} # END 'PARAGRAPH' 'while' loop
if ($self->{Overload}) { # make it findable with fetchmethod
print Q(<<"EOF");
#XS_EUPXS(XS_$self->{Packid}_nil); /* prototype to pass -Wmissing-prototypes */
#XS_EUPXS(XS_$self->{Packid}_nil)
#{
# dXSARGS;
# XSRETURN_EMPTY;
#}
#
EOF
unshift(@{ $self->{InitFileCode} }, <<"MAKE_FETCHMETHOD_WORK");
/* Making a sub named "${Package}::()" allows the package */
/* to be findable via fetchmethod(), and causes */
/* overload::Overloaded("${Package}") to return true. */
(void)$self->{newXS}("${Package}::()", XS_$self->{Packid}_nil, file$self->{proto});
MAKE_FETCHMETHOD_WORK
}
# print initialization routine
print Q(<<"EOF");
##ifdef __cplusplus
#extern "C"
##endif
EOF
print Q(<<"EOF");
#XS_EXTERNAL(boot_$self->{Module_cname}); /* prototype to pass -Wmissing-prototypes */
#XS_EXTERNAL(boot_$self->{Module_cname})
EOF
print Q(<<"EOF");
#[[
# dVAR; dXSARGS;
EOF
#Under 5.8.x and lower, newXS is declared in proto.h as expecting a non-const
#file name argument. If the wrong qualifier is used, it causes breakage with
#C++ compilers and warnings with recent gcc.
#-Wall: if there is no $Full_func_name there are no xsubs in this .xs
#so 'file' is unused
print Q(<<"EOF") if $Full_func_name;
##if (PERL_REVISION == 5 && PERL_VERSION < 9)
# char* file = __FILE__;
##else
# const char* file = __FILE__;
##endif
EOF
print Q("#\n");
print Q(<<"EOF");
# PERL_UNUSED_VAR(cv); /* -W */
# PERL_UNUSED_VAR(items); /* -W */
##ifdef XS_APIVERSION_BOOTCHECK
# XS_APIVERSION_BOOTCHECK;
##endif
EOF
print Q(<<"EOF") if $self->{WantVersionChk};
# XS_VERSION_BOOTCHECK;
#
EOF
print Q(<<"EOF") if defined $self->{xsubaliases} or defined $self->{interfaces};
# {
# CV * cv;
#
EOF
print Q(<<"EOF") if ($self->{Overload});
# /* register the overloading (type 'A') magic */
##if (PERL_REVISION == 5 && PERL_VERSION < 9)
# PL_amagic_generation++;
##endif
# /* The magic for overload gets a GV* via gv_fetchmeth as */
# /* mentioned above, and looks in the SV* slot of it for */
# /* the "fallback" status. */
# sv_setsv(
# get_sv( "${Package}::()", TRUE ),
# $self->{Fallback}
# );
EOF
print @{ $self->{InitFileCode} };
print Q(<<"EOF") if defined $self->{xsubaliases} or defined $self->{interfaces};
# }
EOF
if (@{ $BootCode_ref }) {
print "\n /* Initialisation Section */\n\n";
@{ $self->{line} } = @{ $BootCode_ref };
$self->print_section();
print "\n /* End of Initialisation Section */\n\n";
}
print Q(<<'EOF');
##if (PERL_REVISION == 5 && PERL_VERSION >= 9)
# if (PL_unitcheckav)
# call_list(PL_scopestack_ix, PL_unitcheckav);
##endif
EOF
print Q(<<"EOF");
# XSRETURN_YES;
#]]
#
EOF
warn("Please specify prototyping behavior for $self->{filename} (see perlxs manual)\n")
unless $self->{ProtoUsed};
chdir($orig_cwd);
select($orig_fh);
untie *PSEUDO_STDOUT if tied *PSEUDO_STDOUT;
close $self->{FH};
return 1;
}