Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1763 lines
47 KiB

  1. #!./miniperl
  2. =head1 NAME
  3. xsubpp - compiler to convert Perl XS code into C code
  4. =head1 SYNOPSIS
  5. B<xsubpp> [B<-v>] [B<-C++>] [B<-except>] [B<-s pattern>] [B<-prototypes>] [B<-noversioncheck>] [B<-nolinenumbers>] [B<-nooptimize>] [B<-typemap typemap>] ... file.xs
  6. =head1 DESCRIPTION
  7. This compiler is typically run by the makefiles created by L<ExtUtils::MakeMaker>.
  8. I<xsubpp> will compile XS code into C code by embedding the constructs
  9. necessary to let C functions manipulate Perl values and creates the glue
  10. necessary to let Perl access those functions. The compiler uses typemaps to
  11. determine how to map C function parameters and variables to Perl values.
  12. The compiler will search for typemap files called I<typemap>. It will use
  13. the following search path to find default typemaps, with the rightmost
  14. typemap taking precedence.
  15. ../../../typemap:../../typemap:../typemap:typemap
  16. =head1 OPTIONS
  17. Note that the C<XSOPT> MakeMaker option may be used to add these options to
  18. any makefiles generated by MakeMaker.
  19. =over 5
  20. =item B<-C++>
  21. Adds ``extern "C"'' to the C code.
  22. =item B<-except>
  23. Adds exception handling stubs to the C code.
  24. =item B<-typemap typemap>
  25. Indicates that a user-supplied typemap should take precedence over the
  26. default typemaps. This option may be used multiple times, with the last
  27. typemap having the highest precedence.
  28. =item B<-v>
  29. Prints the I<xsubpp> version number to standard output, then exits.
  30. =item B<-prototypes>
  31. By default I<xsubpp> will not automatically generate prototype code for
  32. all xsubs. This flag will enable prototypes.
  33. =item B<-noversioncheck>
  34. Disables the run time test that determines if the object file (derived
  35. from the C<.xs> file) and the C<.pm> files have the same version
  36. number.
  37. =item B<-nolinenumbers>
  38. Prevents the inclusion of `#line' directives in the output.
  39. =item B<-nooptimize>
  40. Disables certain optimizations. The only optimization that is currently
  41. affected is the use of I<target>s by the output C code (see L<perlguts>).
  42. This may significantly slow down the generated code, but this is the way
  43. B<xsubpp> of 5.005 and earlier operated.
  44. =item B<-noinout>
  45. Disable recognition of C<IN>, C<OUT_LIST> and C<INOUT_LIST> declarations.
  46. =item B<-noargtypes>
  47. Disable recognition of ANSI-like descriptions of function signature.
  48. =back
  49. =head1 ENVIRONMENT
  50. No environment variables are used.
  51. =head1 AUTHOR
  52. Larry Wall
  53. =head1 MODIFICATION HISTORY
  54. See the file F<changes.pod>.
  55. =head1 SEE ALSO
  56. perl(1), perlxs(1), perlxstut(1)
  57. =cut
  58. require 5.002;
  59. use Cwd;
  60. use vars '$cplusplus';
  61. use vars '%v';
  62. use Config;
  63. sub Q ;
  64. # Global Constants
  65. $XSUBPP_version = "1.9508";
  66. my ($Is_VMS, $SymSet);
  67. if ($^O eq 'VMS') {
  68. $Is_VMS = 1;
  69. # Establish set of global symbols with max length 28, since xsubpp
  70. # will later add the 'XS_' prefix.
  71. require ExtUtils::XSSymSet;
  72. $SymSet = new ExtUtils::XSSymSet 28;
  73. }
  74. $FH = 'File0000' ;
  75. $usage = "Usage: xsubpp [-v] [-C++] [-except] [-prototypes] [-noversioncheck] [-nolinenumbers] [-nooptimize] [-noinout] [-noargtypes] [-s pattern] [-typemap typemap]... file.xs\n";
  76. $proto_re = "[" . quotemeta('\$%&*@;') . "]" ;
  77. # mjn
  78. $OBJ = 1 if $Config{'ccflags'} =~ /PERL_OBJECT/i;
  79. $except = "";
  80. $WantPrototypes = -1 ;
  81. $WantVersionChk = 1 ;
  82. $ProtoUsed = 0 ;
  83. $WantLineNumbers = 1 ;
  84. $WantOptimize = 1 ;
  85. my $process_inout = 1;
  86. my $process_argtypes = 1;
  87. SWITCH: while (@ARGV and $ARGV[0] =~ /^-./) {
  88. $flag = shift @ARGV;
  89. $flag =~ s/^-// ;
  90. $spat = quotemeta shift, next SWITCH if $flag eq 's';
  91. $cplusplus = 1, next SWITCH if $flag eq 'C++';
  92. $WantPrototypes = 0, next SWITCH if $flag eq 'noprototypes';
  93. $WantPrototypes = 1, next SWITCH if $flag eq 'prototypes';
  94. $WantVersionChk = 0, next SWITCH if $flag eq 'noversioncheck';
  95. $WantVersionChk = 1, next SWITCH if $flag eq 'versioncheck';
  96. # XXX left this in for compat
  97. $WantCAPI = 1, next SWITCH if $flag eq 'object_capi';
  98. $except = " TRY", next SWITCH if $flag eq 'except';
  99. push(@tm,shift), next SWITCH if $flag eq 'typemap';
  100. $WantLineNumbers = 0, next SWITCH if $flag eq 'nolinenumbers';
  101. $WantLineNumbers = 1, next SWITCH if $flag eq 'linenumbers';
  102. $WantOptimize = 0, next SWITCH if $flag eq 'nooptimize';
  103. $WantOptimize = 1, next SWITCH if $flag eq 'optimize';
  104. $process_inout = 0, next SWITCH if $flag eq 'noinout';
  105. $process_inout = 1, next SWITCH if $flag eq 'inout';
  106. $process_argtypes = 0, next SWITCH if $flag eq 'noargtypes';
  107. $process_argtypes = 1, next SWITCH if $flag eq 'argtypes';
  108. (print "xsubpp version $XSUBPP_version\n"), exit
  109. if $flag eq 'v';
  110. die $usage;
  111. }
  112. if ($WantPrototypes == -1)
  113. { $WantPrototypes = 0}
  114. else
  115. { $ProtoUsed = 1 }
  116. @ARGV == 1 or die $usage;
  117. ($dir, $filename) = $ARGV[0] =~ m#(.*)/(.*)#
  118. or ($dir, $filename) = $ARGV[0] =~ m#(.*)\\(.*)#
  119. or ($dir, $filename) = $ARGV[0] =~ m#(.*[>\]])(.*)#
  120. or ($dir, $filename) = ('.', $ARGV[0]);
  121. chdir($dir);
  122. $pwd = cwd();
  123. ++ $IncludedFiles{$ARGV[0]} ;
  124. my(@XSStack) = ({type => 'none'}); # Stack of conditionals and INCLUDEs
  125. my($XSS_work_idx, $cpp_next_tmp) = (0, "XSubPPtmpAAAA");
  126. sub TrimWhitespace
  127. {
  128. $_[0] =~ s/^\s+|\s+$//go ;
  129. }
  130. sub TidyType
  131. {
  132. local ($_) = @_ ;
  133. # rationalise any '*' by joining them into bunches and removing whitespace
  134. s#\s*(\*+)\s*#$1#g;
  135. s#(\*+)# $1 #g ;
  136. # change multiple whitespace into a single space
  137. s/\s+/ /g ;
  138. # trim leading & trailing whitespace
  139. TrimWhitespace($_) ;
  140. $_ ;
  141. }
  142. $typemap = shift @ARGV;
  143. foreach $typemap (@tm) {
  144. die "Can't find $typemap in $pwd\n" unless -r $typemap;
  145. }
  146. unshift @tm, qw(../../../../lib/ExtUtils/typemap ../../../lib/ExtUtils/typemap
  147. ../../lib/ExtUtils/typemap ../../../typemap ../../typemap
  148. ../typemap typemap);
  149. foreach $typemap (@tm) {
  150. next unless -e $typemap ;
  151. # skip directories, binary files etc.
  152. warn("Warning: ignoring non-text typemap file '$typemap'\n"), next
  153. unless -T $typemap ;
  154. open(TYPEMAP, $typemap)
  155. or warn ("Warning: could not open typemap file '$typemap': $!\n"), next;
  156. $mode = 'Typemap';
  157. $junk = "" ;
  158. $current = \$junk;
  159. while (<TYPEMAP>) {
  160. next if /^\s*#/;
  161. my $line_no = $. + 1;
  162. if (/^INPUT\s*$/) { $mode = 'Input'; $current = \$junk; next; }
  163. if (/^OUTPUT\s*$/) { $mode = 'Output'; $current = \$junk; next; }
  164. if (/^TYPEMAP\s*$/) { $mode = 'Typemap'; $current = \$junk; next; }
  165. if ($mode eq 'Typemap') {
  166. chomp;
  167. my $line = $_ ;
  168. TrimWhitespace($_) ;
  169. # skip blank lines and comment lines
  170. next if /^$/ or /^#/ ;
  171. my($type,$kind, $proto) = /^\s*(.*?\S)\s+(\S+)\s*($proto_re*)\s*$/ or
  172. warn("Warning: File '$typemap' Line $. '$line' TYPEMAP entry needs 2 or 3 columns\n"), next;
  173. $type = TidyType($type) ;
  174. $type_kind{$type} = $kind ;
  175. # prototype defaults to '$'
  176. $proto = "\$" unless $proto ;
  177. warn("Warning: File '$typemap' Line $. '$line' Invalid prototype '$proto'\n")
  178. unless ValidProtoString($proto) ;
  179. $proto_letter{$type} = C_string($proto) ;
  180. }
  181. elsif (/^\s/) {
  182. $$current .= $_;
  183. }
  184. elsif ($mode eq 'Input') {
  185. s/\s+$//;
  186. $input_expr{$_} = '';
  187. $current = \$input_expr{$_};
  188. }
  189. else {
  190. s/\s+$//;
  191. $output_expr{$_} = '';
  192. $current = \$output_expr{$_};
  193. }
  194. }
  195. close(TYPEMAP);
  196. }
  197. foreach $key (keys %input_expr) {
  198. $input_expr{$key} =~ s/\n+$//;
  199. }
  200. $bal = qr[(?:(?>[^()]+)|\((??{ $bal })\))*]; # ()-balanced
  201. $cast = qr[(?:\(\s*SV\s*\*\s*\)\s*)?]; # Optional (SV*) cast
  202. $size = qr[,\s* (??{ $bal }) ]x; # Third arg (to setpvn)
  203. foreach $key (keys %output_expr) {
  204. use re 'eval';
  205. my ($t, $with_size, $arg, $sarg) =
  206. ($output_expr{$key} =~
  207. m[^ \s+ sv_set ( [iunp] ) v (n)? # Type, is_setpvn
  208. \s* \( \s* $cast \$arg \s* ,
  209. \s* ( (??{ $bal }) ) # Set from
  210. ( (??{ $size }) )? # Possible sizeof set-from
  211. \) \s* ; \s* $
  212. ]x);
  213. $targetable{$key} = [$t, $with_size, $arg, $sarg] if $t;
  214. }
  215. $END = "!End!\n\n"; # "impossible" keyword (multiple newline)
  216. # Match an XS keyword
  217. $BLOCK_re= '\s*(' . join('|', qw(
  218. REQUIRE BOOT CASE PREINIT INPUT INIT CODE PPCODE OUTPUT
  219. CLEANUP ALIAS ATTRS PROTOTYPES PROTOTYPE VERSIONCHECK INCLUDE
  220. SCOPE INTERFACE INTERFACE_MACRO C_ARGS POSTCALL
  221. )) . "|$END)\\s*:";
  222. # Input: ($_, @line) == unparsed input.
  223. # Output: ($_, @line) == (rest of line, following lines).
  224. # Return: the matched keyword if found, otherwise 0
  225. sub check_keyword {
  226. $_ = shift(@line) while !/\S/ && @line;
  227. s/^(\s*)($_[0])\s*:\s*(?:#.*)?/$1/s && $2;
  228. }
  229. my ($C_group_rex, $C_arg);
  230. # Group in C (no support for comments or literals)
  231. $C_group_rex = qr/ [({\[]
  232. (?: (?> [^()\[\]{}]+ ) | (??{ $C_group_rex }) )*
  233. [)}\]] /x ;
  234. # Chunk in C without comma at toplevel (no comments):
  235. $C_arg = qr/ (?: (?> [^()\[\]{},"']+ )
  236. | (??{ $C_group_rex })
  237. | " (?: (?> [^\\"]+ )
  238. | \\.
  239. )* " # String literal
  240. | ' (?: (?> [^\\']+ ) | \\. )* ' # Char literal
  241. )* /xs;
  242. if ($WantLineNumbers) {
  243. {
  244. package xsubpp::counter;
  245. sub TIEHANDLE {
  246. my ($class, $cfile) = @_;
  247. my $buf = "";
  248. $SECTION_END_MARKER = "#line --- \"$cfile\"";
  249. $line_no = 1;
  250. bless \$buf;
  251. }
  252. sub PRINT {
  253. my $self = shift;
  254. for (@_) {
  255. $$self .= $_;
  256. while ($$self =~ s/^([^\n]*\n)//) {
  257. my $line = $1;
  258. ++ $line_no;
  259. $line =~ s|^\#line\s+---(?=\s)|#line $line_no|;
  260. print STDOUT $line;
  261. }
  262. }
  263. }
  264. sub PRINTF {
  265. my $self = shift;
  266. my $fmt = shift;
  267. $self->PRINT(sprintf($fmt, @_));
  268. }
  269. sub DESTROY {
  270. # Not necessary if we're careful to end with a "\n"
  271. my $self = shift;
  272. print STDOUT $$self;
  273. }
  274. }
  275. my $cfile = $filename;
  276. $cfile =~ s/\.xs$/.c/i or $cfile .= ".c";
  277. tie(*PSEUDO_STDOUT, 'xsubpp::counter', $cfile);
  278. select PSEUDO_STDOUT;
  279. }
  280. sub print_section {
  281. # the "do" is required for right semantics
  282. do { $_ = shift(@line) } while !/\S/ && @line;
  283. print("#line ", $line_no[@line_no - @line -1], " \"$filename\"\n")
  284. if $WantLineNumbers && !/^\s*#\s*line\b/ && !/^#if XSubPPtmp/;
  285. for (; defined($_) && !/^$BLOCK_re/o; $_ = shift(@line)) {
  286. print "$_\n";
  287. }
  288. print "$xsubpp::counter::SECTION_END_MARKER\n" if $WantLineNumbers;
  289. }
  290. sub merge_section {
  291. my $in = '';
  292. while (!/\S/ && @line) {
  293. $_ = shift(@line);
  294. }
  295. for (; defined($_) && !/^$BLOCK_re/o; $_ = shift(@line)) {
  296. $in .= "$_\n";
  297. }
  298. chomp $in;
  299. return $in;
  300. }
  301. sub process_keyword($)
  302. {
  303. my($pattern) = @_ ;
  304. my $kwd ;
  305. &{"${kwd}_handler"}()
  306. while $kwd = check_keyword($pattern) ;
  307. }
  308. sub CASE_handler {
  309. blurt ("Error: `CASE:' after unconditional `CASE:'")
  310. if $condnum && $cond eq '';
  311. $cond = $_;
  312. TrimWhitespace($cond);
  313. print " ", ($condnum++ ? " else" : ""), ($cond ? " if ($cond)\n" : "\n");
  314. $_ = '' ;
  315. }
  316. sub INPUT_handler {
  317. for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
  318. last if /^\s*NOT_IMPLEMENTED_YET/;
  319. next unless /\S/; # skip blank lines
  320. TrimWhitespace($_) ;
  321. my $line = $_ ;
  322. # remove trailing semicolon if no initialisation
  323. s/\s*;$//g unless /[=;+].*\S/ ;
  324. # check for optional initialisation code
  325. my $var_init = '' ;
  326. $var_init = $1 if s/\s*([=;+].*)$//s ;
  327. $var_init =~ s/"/\\"/g;
  328. s/\s+/ /g;
  329. my ($var_type, $var_addr, $var_name) = /^(.*?[^&\s])\s*(\&?)\s*\b(\w+)$/s
  330. or blurt("Error: invalid argument declaration '$line'"), next;
  331. # Check for duplicate definitions
  332. blurt ("Error: duplicate definition of argument '$var_name' ignored"), next
  333. if $arg_list{$var_name}++
  334. or defined $arg_types{$var_name} and not $processing_arg_with_types;
  335. $thisdone |= $var_name eq "THIS";
  336. $retvaldone |= $var_name eq "RETVAL";
  337. $var_types{$var_name} = $var_type;
  338. # XXXX This check is a safeguard against the unfinished conversion of
  339. # generate_init(). When generate_init() is fixed,
  340. # one can use 2-args map_type() unconditionally.
  341. if ($var_type =~ / \( \s* \* \s* \) /x) {
  342. # Function pointers are not yet supported with &output_init!
  343. print "\t" . &map_type($var_type, $var_name);
  344. $name_printed = 1;
  345. } else {
  346. print "\t" . &map_type($var_type);
  347. $name_printed = 0;
  348. }
  349. $var_num = $args_match{$var_name};
  350. $proto_arg[$var_num] = ProtoString($var_type)
  351. if $var_num ;
  352. $func_args =~ s/\b($var_name)\b/&$1/ if $var_addr;
  353. if ($var_init =~ /^[=;]\s*NO_INIT\s*;?\s*$/
  354. or $in_out{$var_name} and $in_out{$var_name} =~ /^OUT/
  355. and $var_init !~ /\S/) {
  356. if ($name_printed) {
  357. print ";\n";
  358. } else {
  359. print "\t$var_name;\n";
  360. }
  361. } elsif ($var_init =~ /\S/) {
  362. &output_init($var_type, $var_num, $var_name, $var_init, $name_printed);
  363. } elsif ($var_num) {
  364. # generate initialization code
  365. &generate_init($var_type, $var_num, $var_name, $name_printed);
  366. } else {
  367. print ";\n";
  368. }
  369. }
  370. }
  371. sub OUTPUT_handler {
  372. for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
  373. next unless /\S/;
  374. if (/^\s*SETMAGIC\s*:\s*(ENABLE|DISABLE)\s*/) {
  375. $DoSetMagic = ($1 eq "ENABLE" ? 1 : 0);
  376. next;
  377. }
  378. my ($outarg, $outcode) = /^\s*(\S+)\s*(.*?)\s*$/s ;
  379. blurt ("Error: duplicate OUTPUT argument '$outarg' ignored"), next
  380. if $outargs{$outarg} ++ ;
  381. if (!$gotRETVAL and $outarg eq 'RETVAL') {
  382. # deal with RETVAL last
  383. $RETVAL_code = $outcode ;
  384. $gotRETVAL = 1 ;
  385. next ;
  386. }
  387. blurt ("Error: OUTPUT $outarg not an argument"), next
  388. unless defined($args_match{$outarg});
  389. blurt("Error: No input definition for OUTPUT argument '$outarg' - ignored"), next
  390. unless defined $var_types{$outarg} ;
  391. $var_num = $args_match{$outarg};
  392. if ($outcode) {
  393. print "\t$outcode\n";
  394. print "\tSvSETMAGIC(ST(" , $var_num-1 , "));\n" if $DoSetMagic;
  395. } else {
  396. &generate_output($var_types{$outarg}, $var_num, $outarg, $DoSetMagic);
  397. }
  398. delete $in_out{$outarg} # No need to auto-OUTPUT
  399. if exists $in_out{$outarg} and $in_out{$outarg} =~ /OUT$/;
  400. }
  401. }
  402. sub C_ARGS_handler() {
  403. my $in = merge_section();
  404. TrimWhitespace($in);
  405. $func_args = $in;
  406. }
  407. sub INTERFACE_MACRO_handler() {
  408. my $in = merge_section();
  409. TrimWhitespace($in);
  410. if ($in =~ /\s/) { # two
  411. ($interface_macro, $interface_macro_set) = split ' ', $in;
  412. } else {
  413. $interface_macro = $in;
  414. $interface_macro_set = 'UNKNOWN_CVT'; # catch later
  415. }
  416. $interface = 1; # local
  417. $Interfaces = 1; # global
  418. }
  419. sub INTERFACE_handler() {
  420. my $in = merge_section();
  421. TrimWhitespace($in);
  422. foreach (split /[\s,]+/, $in) {
  423. $Interfaces{$_} = $_;
  424. }
  425. print Q<<"EOF";
  426. # XSFUNCTION = $interface_macro($ret_type,cv,XSANY.any_dptr);
  427. EOF
  428. $interface = 1; # local
  429. $Interfaces = 1; # global
  430. }
  431. sub CLEANUP_handler() { print_section() }
  432. sub PREINIT_handler() { print_section() }
  433. sub POSTCALL_handler() { print_section() }
  434. sub INIT_handler() { print_section() }
  435. sub GetAliases
  436. {
  437. my ($line) = @_ ;
  438. my ($orig) = $line ;
  439. my ($alias) ;
  440. my ($value) ;
  441. # Parse alias definitions
  442. # format is
  443. # alias = value alias = value ...
  444. while ($line =~ s/^\s*([\w:]+)\s*=\s*(\w+)\s*//) {
  445. $alias = $1 ;
  446. $orig_alias = $alias ;
  447. $value = $2 ;
  448. # check for optional package definition in the alias
  449. $alias = $Packprefix . $alias if $alias !~ /::/ ;
  450. # check for duplicate alias name & duplicate value
  451. Warn("Warning: Ignoring duplicate alias '$orig_alias'")
  452. if defined $XsubAliases{$alias} ;
  453. Warn("Warning: Aliases '$orig_alias' and '$XsubAliasValues{$value}' have identical values")
  454. if $XsubAliasValues{$value} ;
  455. $XsubAliases = 1;
  456. $XsubAliases{$alias} = $value ;
  457. $XsubAliasValues{$value} = $orig_alias ;
  458. }
  459. blurt("Error: Cannot parse ALIAS definitions from '$orig'")
  460. if $line ;
  461. }
  462. sub ATTRS_handler ()
  463. {
  464. for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
  465. next unless /\S/;
  466. TrimWhitespace($_) ;
  467. push @Attributes, $_;
  468. }
  469. }
  470. sub ALIAS_handler ()
  471. {
  472. for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
  473. next unless /\S/;
  474. TrimWhitespace($_) ;
  475. GetAliases($_) if $_ ;
  476. }
  477. }
  478. sub REQUIRE_handler ()
  479. {
  480. # the rest of the current line should contain a version number
  481. my ($Ver) = $_ ;
  482. TrimWhitespace($Ver) ;
  483. death ("Error: REQUIRE expects a version number")
  484. unless $Ver ;
  485. # check that the version number is of the form n.n
  486. death ("Error: REQUIRE: expected a number, got '$Ver'")
  487. unless $Ver =~ /^\d+(\.\d*)?/ ;
  488. death ("Error: xsubpp $Ver (or better) required--this is only $XSUBPP_version.")
  489. unless $XSUBPP_version >= $Ver ;
  490. }
  491. sub VERSIONCHECK_handler ()
  492. {
  493. # the rest of the current line should contain either ENABLE or
  494. # DISABLE
  495. TrimWhitespace($_) ;
  496. # check for ENABLE/DISABLE
  497. death ("Error: VERSIONCHECK: ENABLE/DISABLE")
  498. unless /^(ENABLE|DISABLE)/i ;
  499. $WantVersionChk = 1 if $1 eq 'ENABLE' ;
  500. $WantVersionChk = 0 if $1 eq 'DISABLE' ;
  501. }
  502. sub PROTOTYPE_handler ()
  503. {
  504. my $specified ;
  505. death("Error: Only 1 PROTOTYPE definition allowed per xsub")
  506. if $proto_in_this_xsub ++ ;
  507. for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
  508. next unless /\S/;
  509. $specified = 1 ;
  510. TrimWhitespace($_) ;
  511. if ($_ eq 'DISABLE') {
  512. $ProtoThisXSUB = 0
  513. }
  514. elsif ($_ eq 'ENABLE') {
  515. $ProtoThisXSUB = 1
  516. }
  517. else {
  518. # remove any whitespace
  519. s/\s+//g ;
  520. death("Error: Invalid prototype '$_'")
  521. unless ValidProtoString($_) ;
  522. $ProtoThisXSUB = C_string($_) ;
  523. }
  524. }
  525. # If no prototype specified, then assume empty prototype ""
  526. $ProtoThisXSUB = 2 unless $specified ;
  527. $ProtoUsed = 1 ;
  528. }
  529. sub SCOPE_handler ()
  530. {
  531. death("Error: Only 1 SCOPE declaration allowed per xsub")
  532. if $scope_in_this_xsub ++ ;
  533. for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
  534. next unless /\S/;
  535. TrimWhitespace($_) ;
  536. if ($_ =~ /^DISABLE/i) {
  537. $ScopeThisXSUB = 0
  538. }
  539. elsif ($_ =~ /^ENABLE/i) {
  540. $ScopeThisXSUB = 1
  541. }
  542. }
  543. }
  544. sub PROTOTYPES_handler ()
  545. {
  546. # the rest of the current line should contain either ENABLE or
  547. # DISABLE
  548. TrimWhitespace($_) ;
  549. # check for ENABLE/DISABLE
  550. death ("Error: PROTOTYPES: ENABLE/DISABLE")
  551. unless /^(ENABLE|DISABLE)/i ;
  552. $WantPrototypes = 1 if $1 eq 'ENABLE' ;
  553. $WantPrototypes = 0 if $1 eq 'DISABLE' ;
  554. $ProtoUsed = 1 ;
  555. }
  556. sub INCLUDE_handler ()
  557. {
  558. # the rest of the current line should contain a valid filename
  559. TrimWhitespace($_) ;
  560. death("INCLUDE: filename missing")
  561. unless $_ ;
  562. death("INCLUDE: output pipe is illegal")
  563. if /^\s*\|/ ;
  564. # simple minded recursion detector
  565. death("INCLUDE loop detected")
  566. if $IncludedFiles{$_} ;
  567. ++ $IncludedFiles{$_} unless /\|\s*$/ ;
  568. # Save the current file context.
  569. push(@XSStack, {
  570. type => 'file',
  571. LastLine => $lastline,
  572. LastLineNo => $lastline_no,
  573. Line => \@line,
  574. LineNo => \@line_no,
  575. Filename => $filename,
  576. Handle => $FH,
  577. }) ;
  578. ++ $FH ;
  579. # open the new file
  580. open ($FH, "$_") or death("Cannot open '$_': $!") ;
  581. print Q<<"EOF" ;
  582. #
  583. #/* INCLUDE: Including '$_' from '$filename' */
  584. #
  585. EOF
  586. $filename = $_ ;
  587. # Prime the pump by reading the first
  588. # non-blank line
  589. # skip leading blank lines
  590. while (<$FH>) {
  591. last unless /^\s*$/ ;
  592. }
  593. $lastline = $_ ;
  594. $lastline_no = $. ;
  595. }
  596. sub PopFile()
  597. {
  598. return 0 unless $XSStack[-1]{type} eq 'file' ;
  599. my $data = pop @XSStack ;
  600. my $ThisFile = $filename ;
  601. my $isPipe = ($filename =~ /\|\s*$/) ;
  602. -- $IncludedFiles{$filename}
  603. unless $isPipe ;
  604. close $FH ;
  605. $FH = $data->{Handle} ;
  606. $filename = $data->{Filename} ;
  607. $lastline = $data->{LastLine} ;
  608. $lastline_no = $data->{LastLineNo} ;
  609. @line = @{ $data->{Line} } ;
  610. @line_no = @{ $data->{LineNo} } ;
  611. if ($isPipe and $? ) {
  612. -- $lastline_no ;
  613. print STDERR "Error reading from pipe '$ThisFile': $! in $filename, line $lastline_no\n" ;
  614. exit 1 ;
  615. }
  616. print Q<<"EOF" ;
  617. #
  618. #/* INCLUDE: Returning to '$filename' from '$ThisFile' */
  619. #
  620. EOF
  621. return 1 ;
  622. }
  623. sub ValidProtoString ($)
  624. {
  625. my($string) = @_ ;
  626. if ( $string =~ /^$proto_re+$/ ) {
  627. return $string ;
  628. }
  629. return 0 ;
  630. }
  631. sub C_string ($)
  632. {
  633. my($string) = @_ ;
  634. $string =~ s[\\][\\\\]g ;
  635. $string ;
  636. }
  637. sub ProtoString ($)
  638. {
  639. my ($type) = @_ ;
  640. $proto_letter{$type} or "\$" ;
  641. }
  642. sub check_cpp {
  643. my @cpp = grep(/^\#\s*(?:if|e\w+)/, @line);
  644. if (@cpp) {
  645. my ($cpp, $cpplevel);
  646. for $cpp (@cpp) {
  647. if ($cpp =~ /^\#\s*if/) {
  648. $cpplevel++;
  649. } elsif (!$cpplevel) {
  650. Warn("Warning: #else/elif/endif without #if in this function");
  651. print STDERR " (precede it with a blank line if the matching #if is outside the function)\n"
  652. if $XSStack[-1]{type} eq 'if';
  653. return;
  654. } elsif ($cpp =~ /^\#\s*endif/) {
  655. $cpplevel--;
  656. }
  657. }
  658. Warn("Warning: #if without #endif in this function") if $cpplevel;
  659. }
  660. }
  661. sub Q {
  662. my($text) = @_;
  663. $text =~ s/^#//gm;
  664. $text =~ s/\[\[/{/g;
  665. $text =~ s/\]\]/}/g;
  666. $text;
  667. }
  668. open($FH, $filename) or die "cannot open $filename: $!\n";
  669. # Identify the version of xsubpp used
  670. print <<EOM ;
  671. /*
  672. * This file was generated automatically by xsubpp version $XSUBPP_version from the
  673. * contents of $filename. Do not edit this file, edit $filename instead.
  674. *
  675. * ANY CHANGES MADE HERE WILL BE LOST!
  676. *
  677. */
  678. EOM
  679. print("#line 1 \"$filename\"\n")
  680. if $WantLineNumbers;
  681. firstmodule:
  682. while (<$FH>) {
  683. if (/^=/) {
  684. my $podstartline = $.;
  685. do {
  686. if (/^=cut\s*$/) {
  687. print("/* Skipped embedded POD. */\n");
  688. printf("#line %d \"$filename\"\n", $. + 1)
  689. if $WantLineNumbers;
  690. next firstmodule
  691. }
  692. } while (<$FH>);
  693. # At this point $. is at end of file so die won't state the start
  694. # of the problem, and as we haven't yet read any lines &death won't
  695. # show the correct line in the message either.
  696. die ("Error: Unterminated pod in $filename, line $podstartline\n")
  697. unless $lastline;
  698. }
  699. last if ($Module, $Package, $Prefix) =
  700. /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/;
  701. if ($OBJ) {
  702. s/#if(?:def\s|\s+defined)\s*(\(__cplusplus\)|__cplusplus)/#if defined(__cplusplus) && !defined(PERL_OBJECT)/;
  703. }
  704. print $_;
  705. }
  706. &Exit unless defined $_;
  707. print "$xsubpp::counter::SECTION_END_MARKER\n" if $WantLineNumbers;
  708. $lastline = $_;
  709. $lastline_no = $.;
  710. # Read next xsub into @line from ($lastline, <$FH>).
  711. sub fetch_para {
  712. # parse paragraph
  713. death ("Error: Unterminated `#if/#ifdef/#ifndef'")
  714. if !defined $lastline && $XSStack[-1]{type} eq 'if';
  715. @line = ();
  716. @line_no = () ;
  717. return PopFile() if !defined $lastline;
  718. if ($lastline =~
  719. /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/) {
  720. $Module = $1;
  721. $Package = defined($2) ? $2 : ''; # keep -w happy
  722. $Prefix = defined($3) ? $3 : ''; # keep -w happy
  723. $Prefix = quotemeta $Prefix ;
  724. ($Module_cname = $Module) =~ s/\W/_/g;
  725. ($Packid = $Package) =~ tr/:/_/;
  726. $Packprefix = $Package;
  727. $Packprefix .= "::" if $Packprefix ne "";
  728. $lastline = "";
  729. }
  730. for(;;) {
  731. # Skip embedded PODs
  732. while ($lastline =~ /^=/) {
  733. while ($lastline = <$FH>) {
  734. last if ($lastline =~ /^=cut\s*$/);
  735. }
  736. death ("Error: Unterminated pod") unless $lastline;
  737. $lastline = <$FH>;
  738. chomp $lastline;
  739. $lastline =~ s/^\s+$//;
  740. }
  741. if ($lastline !~ /^\s*#/ ||
  742. # CPP directives:
  743. # ANSI: if ifdef ifndef elif else endif define undef
  744. # line error pragma
  745. # gcc: warning include_next
  746. # obj-c: import
  747. # others: ident (gcc notes that some cpps have this one)
  748. $lastline =~ /^#[ \t]*(?:(?:if|ifn?def|elif|else|endif|define|undef|pragma|error|warning|line\s+\d+|ident)\b|(?:include(?:_next)?|import)\s*["<].*[>"])/) {
  749. last if $lastline =~ /^\S/ && @line && $line[-1] eq "";
  750. push(@line, $lastline);
  751. push(@line_no, $lastline_no) ;
  752. }
  753. # Read next line and continuation lines
  754. last unless defined($lastline = <$FH>);
  755. $lastline_no = $.;
  756. my $tmp_line;
  757. $lastline .= $tmp_line
  758. while ($lastline =~ /\\$/ && defined($tmp_line = <$FH>));
  759. chomp $lastline;
  760. $lastline =~ s/^\s+$//;
  761. }
  762. pop(@line), pop(@line_no) while @line && $line[-1] eq "";
  763. 1;
  764. }
  765. PARAGRAPH:
  766. while (fetch_para()) {
  767. # Print initial preprocessor statements and blank lines
  768. while (@line && $line[0] !~ /^[^\#]/) {
  769. my $line = shift(@line);
  770. print $line, "\n";
  771. next unless $line =~ /^\#\s*((if)(?:n?def)?|elsif|else|endif)\b/;
  772. my $statement = $+;
  773. if ($statement eq 'if') {
  774. $XSS_work_idx = @XSStack;
  775. push(@XSStack, {type => 'if'});
  776. } else {
  777. death ("Error: `$statement' with no matching `if'")
  778. if $XSStack[-1]{type} ne 'if';
  779. if ($XSStack[-1]{varname}) {
  780. push(@InitFileCode, "#endif\n");
  781. push(@BootCode, "#endif");
  782. }
  783. my(@fns) = keys %{$XSStack[-1]{functions}};
  784. if ($statement ne 'endif') {
  785. # Hide the functions defined in other #if branches, and reset.
  786. @{$XSStack[-1]{other_functions}}{@fns} = (1) x @fns;
  787. @{$XSStack[-1]}{qw(varname functions)} = ('', {});
  788. } else {
  789. my($tmp) = pop(@XSStack);
  790. 0 while (--$XSS_work_idx
  791. && $XSStack[$XSS_work_idx]{type} ne 'if');
  792. # Keep all new defined functions
  793. push(@fns, keys %{$tmp->{other_functions}});
  794. @{$XSStack[$XSS_work_idx]{functions}}{@fns} = (1) x @fns;
  795. }
  796. }
  797. }
  798. next PARAGRAPH unless @line;
  799. if ($XSS_work_idx && !$XSStack[$XSS_work_idx]{varname}) {
  800. # We are inside an #if, but have not yet #defined its xsubpp variable.
  801. print "#define $cpp_next_tmp 1\n\n";
  802. push(@InitFileCode, "#if $cpp_next_tmp\n");
  803. push(@BootCode, "#if $cpp_next_tmp");
  804. $XSStack[$XSS_work_idx]{varname} = $cpp_next_tmp++;
  805. }
  806. death ("Code is not inside a function"
  807. ." (maybe last function was ended by a blank line "
  808. ." followed by a a statement on column one?)")
  809. if $line[0] =~ /^\s/;
  810. # initialize info arrays
  811. undef(%args_match);
  812. undef(%var_types);
  813. undef(%defaults);
  814. undef($class);
  815. undef($static);
  816. undef($elipsis);
  817. undef($wantRETVAL) ;
  818. undef($RETVAL_no_return) ;
  819. undef(%arg_list) ;
  820. undef(@proto_arg) ;
  821. undef(@arg_with_types) ;
  822. undef($processing_arg_with_types) ;
  823. undef(%arg_types) ;
  824. undef(@outlist) ;
  825. undef(%in_out) ;
  826. undef($proto_in_this_xsub) ;
  827. undef($scope_in_this_xsub) ;
  828. undef($interface);
  829. undef($prepush_done);
  830. $interface_macro = 'XSINTERFACE_FUNC' ;
  831. $interface_macro_set = 'XSINTERFACE_FUNC_SET' ;
  832. $ProtoThisXSUB = $WantPrototypes ;
  833. $ScopeThisXSUB = 0;
  834. $xsreturn = 0;
  835. $_ = shift(@line);
  836. while ($kwd = check_keyword("REQUIRE|PROTOTYPES|VERSIONCHECK|INCLUDE")) {
  837. &{"${kwd}_handler"}() ;
  838. next PARAGRAPH unless @line ;
  839. $_ = shift(@line);
  840. }
  841. if (check_keyword("BOOT")) {
  842. &check_cpp;
  843. push (@BootCode, "#line $line_no[@line_no - @line] \"$filename\"")
  844. if $WantLineNumbers && $line[0] !~ /^\s*#\s*line\b/;
  845. push (@BootCode, @line, "") ;
  846. next PARAGRAPH ;
  847. }
  848. # extract return type, function name and arguments
  849. ($ret_type) = TidyType($_);
  850. $RETVAL_no_return = 1 if $ret_type =~ s/^NO_OUTPUT\s+//;
  851. # Allow one-line ANSI-like declaration
  852. unshift @line, $2
  853. if $process_argtypes
  854. and $ret_type =~ s/^(.*?\w.*?)\s*\b(\w+\s*\(.*)/$1/s;
  855. # a function definition needs at least 2 lines
  856. blurt ("Error: Function definition too short '$ret_type'"), next PARAGRAPH
  857. unless @line ;
  858. $static = 1 if $ret_type =~ s/^static\s+//;
  859. $func_header = shift(@line);
  860. blurt ("Error: Cannot parse function definition from '$func_header'"), next PARAGRAPH
  861. unless $func_header =~ /^(?:([\w:]*)::)?(\w+)\s*\(\s*(.*?)\s*\)\s*(const)?\s*(;\s*)?$/s;
  862. ($class, $func_name, $orig_args) = ($1, $2, $3) ;
  863. $class = "$4 $class" if $4;
  864. ($pname = $func_name) =~ s/^($Prefix)?/$Packprefix/;
  865. ($clean_func_name = $func_name) =~ s/^$Prefix//;
  866. $Full_func_name = "${Packid}_$clean_func_name";
  867. if ($Is_VMS) { $Full_func_name = $SymSet->addsym($Full_func_name); }
  868. # Check for duplicate function definition
  869. for $tmp (@XSStack) {
  870. next unless defined $tmp->{functions}{$Full_func_name};
  871. Warn("Warning: duplicate function definition '$clean_func_name' detected");
  872. last;
  873. }
  874. $XSStack[$XSS_work_idx]{functions}{$Full_func_name} ++ ;
  875. %XsubAliases = %XsubAliasValues = %Interfaces = @Attributes = ();
  876. $DoSetMagic = 1;
  877. $orig_args =~ s/\\\s*/ /g; # process line continuations
  878. my %only_outlist;
  879. if ($process_argtypes and $orig_args =~ /\S/) {
  880. my $args = "$orig_args ,";
  881. if ($args =~ /^( (??{ $C_arg }) , )* $ /x) {
  882. @args = ($args =~ /\G ( (??{ $C_arg }) ) , /xg);
  883. for ( @args ) {
  884. s/^\s+//;
  885. s/\s+$//;
  886. my $arg = $_;
  887. my $default;
  888. ($arg, $default) = / ( [^=]* ) ( (?: = .* )? ) /x;
  889. my ($pre, $name) = ($arg =~ /(.*?) \s* \b(\w+) \s* $ /x);
  890. next unless length $pre;
  891. my $out_type;
  892. my $inout_var;
  893. if ($process_inout and s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\s+//) {
  894. my $type = $1;
  895. $out_type = $type if $type ne 'IN';
  896. $arg =~ s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\s+//;
  897. }
  898. if (/\W/) { # Has a type
  899. push @arg_with_types, $arg;
  900. # warn "pushing '$arg'\n";
  901. $arg_types{$name} = $arg;
  902. $_ = "$name$default";
  903. }
  904. $only_outlist{$_} = 1 if $out_type eq "OUTLIST";
  905. push @outlist, $name if $out_type =~ /OUTLIST$/;
  906. $in_out{$name} = $out_type if $out_type;
  907. }
  908. } else {
  909. @args = split(/\s*,\s*/, $orig_args);
  910. Warn("Warning: cannot parse argument list '$orig_args', fallback to split");
  911. }
  912. } else {
  913. @args = split(/\s*,\s*/, $orig_args);
  914. for (@args) {
  915. if ($process_inout and s/^(IN|IN_OUTLIST|OUTLIST|IN_OUT|OUT)\s+//) {
  916. my $out_type = $1;
  917. next if $out_type eq 'IN';
  918. $only_outlist{$_} = 1 if $out_type eq "OUTLIST";
  919. push @outlist, $name if $out_type =~ /OUTLIST$/;
  920. $in_out{$_} = $out_type;
  921. }
  922. }
  923. }
  924. if (defined($class)) {
  925. my $arg0 = ((defined($static) or $func_name eq 'new')
  926. ? "CLASS" : "THIS");
  927. unshift(@args, $arg0);
  928. ($report_args = "$arg0, $report_args") =~ s/^\w+, $/$arg0/;
  929. }
  930. my $extra_args = 0;
  931. @args_num = ();
  932. $num_args = 0;
  933. my $report_args = '';
  934. foreach $i (0 .. $#args) {
  935. if ($args[$i] =~ s/\.\.\.//) {
  936. $elipsis = 1;
  937. if ($args[$i] eq '' && $i == $#args) {
  938. $report_args .= ", ...";
  939. pop(@args);
  940. last;
  941. }
  942. }
  943. if ($only_outlist{$args[$i]}) {
  944. push @args_num, undef;
  945. } else {
  946. push @args_num, ++$num_args;
  947. $report_args .= ", $args[$i]";
  948. }
  949. if ($args[$i] =~ /^([^=]*[^\s=])\s*=\s*(.*)/s) {
  950. $extra_args++;
  951. $args[$i] = $1;
  952. $defaults{$args[$i]} = $2;
  953. $defaults{$args[$i]} =~ s/"/\\"/g;
  954. }
  955. $proto_arg[$i+1] = "\$" ;
  956. }
  957. $min_args = $num_args - $extra_args;
  958. $report_args =~ s/"/\\"/g;
  959. $report_args =~ s/^,\s+//;
  960. my @func_args = @args;
  961. shift @func_args if defined($class);
  962. for (@func_args) {
  963. s/^/&/ if $in_out{$_};
  964. }
  965. $func_args = join(", ", @func_args);
  966. @args_match{@args} = @args_num;
  967. $PPCODE = grep(/^\s*PPCODE\s*:/, @line);
  968. $CODE = grep(/^\s*CODE\s*:/, @line);
  969. # Detect CODE: blocks which use ST(n)= or XST_m*(n,v)
  970. # to set explicit return values.
  971. $EXPLICIT_RETURN = ($CODE &&
  972. ("@line" =~ /(\bST\s*\([^;]*=) | (\bXST_m\w+\s*\()/x ));
  973. $ALIAS = grep(/^\s*ALIAS\s*:/, @line);
  974. $INTERFACE = grep(/^\s*INTERFACE\s*:/, @line);
  975. $xsreturn = 1 if $EXPLICIT_RETURN;
  976. # print function header
  977. print Q<<"EOF";
  978. #XS(XS_${Full_func_name})
  979. #[[
  980. # dXSARGS;
  981. EOF
  982. print Q<<"EOF" if $ALIAS ;
  983. # dXSI32;
  984. EOF
  985. print Q<<"EOF" if $INTERFACE ;
  986. # dXSFUNCTION($ret_type);
  987. EOF
  988. if ($elipsis) {
  989. $cond = ($min_args ? qq(items < $min_args) : 0);
  990. }
  991. elsif ($min_args == $num_args) {
  992. $cond = qq(items != $min_args);
  993. }
  994. else {
  995. $cond = qq(items < $min_args || items > $num_args);
  996. }
  997. print Q<<"EOF" if $except;
  998. # char errbuf[1024];
  999. # *errbuf = '\0';
  1000. EOF
  1001. if ($ALIAS)
  1002. { print Q<<"EOF" if $cond }
  1003. # if ($cond)
  1004. # Perl_croak(aTHX_ "Usage: %s($report_args)", GvNAME(CvGV(cv)));
  1005. EOF
  1006. else
  1007. { print Q<<"EOF" if $cond }
  1008. # if ($cond)
  1009. # Perl_croak(aTHX_ "Usage: $pname($report_args)");
  1010. EOF
  1011. print Q<<"EOF" if $PPCODE;
  1012. # SP -= items;
  1013. EOF
  1014. # Now do a block of some sort.
  1015. $condnum = 0;
  1016. $cond = ''; # last CASE: condidional
  1017. push(@line, "$END:");
  1018. push(@line_no, $line_no[-1]);
  1019. $_ = '';
  1020. &check_cpp;
  1021. while (@line) {
  1022. &CASE_handler if check_keyword("CASE");
  1023. print Q<<"EOF";
  1024. # $except [[
  1025. EOF
  1026. # do initialization of input variables
  1027. $thisdone = 0;
  1028. $retvaldone = 0;
  1029. $deferred = "";
  1030. %arg_list = () ;
  1031. $gotRETVAL = 0;
  1032. INPUT_handler() ;
  1033. process_keyword("INPUT|PREINIT|INTERFACE_MACRO|C_ARGS|ALIAS|ATTRS|PROTOTYPE|SCOPE") ;
  1034. print Q<<"EOF" if $ScopeThisXSUB;
  1035. # ENTER;
  1036. # [[
  1037. EOF
  1038. if (!$thisdone && defined($class)) {
  1039. if (defined($static) or $func_name eq 'new') {
  1040. print "\tchar *";
  1041. $var_types{"CLASS"} = "char *";
  1042. &generate_init("char *", 1, "CLASS");
  1043. }
  1044. else {
  1045. print "\t$class *";
  1046. $var_types{"THIS"} = "$class *";
  1047. &generate_init("$class *", 1, "THIS");
  1048. }
  1049. }
  1050. # do code
  1051. if (/^\s*NOT_IMPLEMENTED_YET/) {
  1052. print "\n\tPerl_croak(aTHX_ \"$pname: not implemented yet\");\n";
  1053. $_ = '' ;
  1054. } else {
  1055. if ($ret_type ne "void") {
  1056. print "\t" . &map_type($ret_type, 'RETVAL') . ";\n"
  1057. if !$retvaldone;
  1058. $args_match{"RETVAL"} = 0;
  1059. $var_types{"RETVAL"} = $ret_type;
  1060. print "\tdXSTARG;\n"
  1061. if $WantOptimize and $targetable{$type_kind{$ret_type}};
  1062. }
  1063. if (@arg_with_types) {
  1064. unshift @line, @arg_with_types, $_;
  1065. $_ = "";
  1066. $processing_arg_with_types = 1;
  1067. INPUT_handler() ;
  1068. }
  1069. print $deferred;
  1070. process_keyword("INIT|ALIAS|ATTRS|PROTOTYPE|INTERFACE_MACRO|INTERFACE|C_ARGS") ;
  1071. if (check_keyword("PPCODE")) {
  1072. print_section();
  1073. death ("PPCODE must be last thing") if @line;
  1074. print "\tLEAVE;\n" if $ScopeThisXSUB;
  1075. print "\tPUTBACK;\n\treturn;\n";
  1076. } elsif (check_keyword("CODE")) {
  1077. print_section() ;
  1078. } elsif (defined($class) and $func_name eq "DESTROY") {
  1079. print "\n\t";
  1080. print "delete THIS;\n";
  1081. } else {
  1082. print "\n\t";
  1083. if ($ret_type ne "void") {
  1084. print "RETVAL = ";
  1085. $wantRETVAL = 1;
  1086. }
  1087. if (defined($static)) {
  1088. if ($func_name eq 'new') {
  1089. $func_name = "$class";
  1090. } else {
  1091. print "${class}::";
  1092. }
  1093. } elsif (defined($class)) {
  1094. if ($func_name eq 'new') {
  1095. $func_name .= " $class";
  1096. } else {
  1097. print "THIS->";
  1098. }
  1099. }
  1100. $func_name =~ s/^($spat)//
  1101. if defined($spat);
  1102. $func_name = 'XSFUNCTION' if $interface;
  1103. print "$func_name($func_args);\n";
  1104. }
  1105. }
  1106. # do output variables
  1107. $gotRETVAL = 0; # 1 if RETVAL seen in OUTPUT section;
  1108. undef $RETVAL_code ; # code to set RETVAL (from OUTPUT section);
  1109. # $wantRETVAL set if 'RETVAL =' autogenerated
  1110. ($wantRETVAL, $ret_type) = (0, 'void') if $RETVAL_no_return;
  1111. undef %outargs ;
  1112. process_keyword("POSTCALL|OUTPUT|ALIAS|ATTRS|PROTOTYPE");
  1113. &generate_output($var_types{$_}, $args_match{$_}, $_, $DoSetMagic)
  1114. for grep $in_out{$_} =~ /OUT$/, keys %in_out;
  1115. # all OUTPUT done, so now push the return value on the stack
  1116. if ($gotRETVAL && $RETVAL_code) {
  1117. print "\t$RETVAL_code\n";
  1118. } elsif ($gotRETVAL || $wantRETVAL) {
  1119. my $t = $WantOptimize && $targetable{$type_kind{$ret_type}};
  1120. my $var = 'RETVAL';
  1121. my $type = $ret_type;
  1122. # 0: type, 1: with_size, 2: how, 3: how_size
  1123. if ($t and not $t->[1] and $t->[0] eq 'p') {
  1124. # PUSHp corresponds to setpvn. Treate setpv directly
  1125. my $what = eval qq("$t->[2]");
  1126. warn $@ if $@;
  1127. print "\tsv_setpv(TARG, $what); XSprePUSH; PUSHTARG;\n";
  1128. $prepush_done = 1;
  1129. }
  1130. elsif ($t) {
  1131. my $what = eval qq("$t->[2]");
  1132. warn $@ if $@;
  1133. my $size = $t->[3];
  1134. $size = '' unless defined $size;
  1135. $size = eval qq("$size");
  1136. warn $@ if $@;
  1137. print "\tXSprePUSH; PUSH$t->[0]($what$size);\n";
  1138. $prepush_done = 1;
  1139. }
  1140. else {
  1141. # RETVAL almost never needs SvSETMAGIC()
  1142. &generate_output($ret_type, 0, 'RETVAL', 0);
  1143. }
  1144. }
  1145. $xsreturn = 1 if $ret_type ne "void";
  1146. my $num = $xsreturn;
  1147. my $c = @outlist;
  1148. print "\tXSprePUSH;" if $c and not $prepush_done;
  1149. print "\tEXTEND(SP,$c);\n" if $c;
  1150. $xsreturn += $c;
  1151. generate_output($var_types{$_}, $num++, $_, 0, 1) for @outlist;
  1152. # do cleanup
  1153. process_keyword("CLEANUP|ALIAS|ATTRS|PROTOTYPE") ;
  1154. print Q<<"EOF" if $ScopeThisXSUB;
  1155. # ]]
  1156. EOF
  1157. print Q<<"EOF" if $ScopeThisXSUB and not $PPCODE;
  1158. # LEAVE;
  1159. EOF
  1160. # print function trailer
  1161. print Q<<EOF;
  1162. # ]]
  1163. EOF
  1164. print Q<<EOF if $except;
  1165. # BEGHANDLERS
  1166. # CATCHALL
  1167. # sprintf(errbuf, "%s: %s\\tpropagated", Xname, Xreason);
  1168. # ENDHANDLERS
  1169. EOF
  1170. if (check_keyword("CASE")) {
  1171. blurt ("Error: No `CASE:' at top of function")
  1172. unless $condnum;
  1173. $_ = "CASE: $_"; # Restore CASE: label
  1174. next;
  1175. }
  1176. last if $_ eq "$END:";
  1177. death(/^$BLOCK_re/o ? "Misplaced `$1:'" : "Junk at end of function");
  1178. }
  1179. print Q<<EOF if $except;
  1180. # if (errbuf[0])
  1181. # Perl_croak(aTHX_ errbuf);
  1182. EOF
  1183. if ($xsreturn) {
  1184. print Q<<EOF unless $PPCODE;
  1185. # XSRETURN($xsreturn);
  1186. EOF
  1187. } else {
  1188. print Q<<EOF unless $PPCODE;
  1189. # XSRETURN_EMPTY;
  1190. EOF
  1191. }
  1192. print Q<<EOF;
  1193. #]]
  1194. #
  1195. EOF
  1196. my $newXS = "newXS" ;
  1197. my $proto = "" ;
  1198. # Build the prototype string for the xsub
  1199. if ($ProtoThisXSUB) {
  1200. $newXS = "newXSproto";
  1201. if ($ProtoThisXSUB eq 2) {
  1202. # User has specified empty prototype
  1203. $proto = ', ""' ;
  1204. }
  1205. elsif ($ProtoThisXSUB ne 1) {
  1206. # User has specified a prototype
  1207. $proto = ', "' . $ProtoThisXSUB . '"';
  1208. }
  1209. else {
  1210. my $s = ';';
  1211. if ($min_args < $num_args) {
  1212. $s = '';
  1213. $proto_arg[$min_args] .= ";" ;
  1214. }
  1215. push @proto_arg, "$s\@"
  1216. if $elipsis ;
  1217. $proto = ', "' . join ("", @proto_arg) . '"';
  1218. }
  1219. }
  1220. if (%XsubAliases) {
  1221. $XsubAliases{$pname} = 0
  1222. unless defined $XsubAliases{$pname} ;
  1223. while ( ($name, $value) = each %XsubAliases) {
  1224. push(@InitFileCode, Q<<"EOF");
  1225. # cv = newXS(\"$name\", XS_$Full_func_name, file);
  1226. # XSANY.any_i32 = $value ;
  1227. EOF
  1228. push(@InitFileCode, Q<<"EOF") if $proto;
  1229. # sv_setpv((SV*)cv$proto) ;
  1230. EOF
  1231. }
  1232. }
  1233. elsif (@Attributes) {
  1234. push(@InitFileCode, Q<<"EOF");
  1235. # cv = newXS(\"$pname\", XS_$Full_func_name, file);
  1236. # apply_attrs_string("$Package", cv, "@Attributes", 0);
  1237. EOF
  1238. }
  1239. elsif ($interface) {
  1240. while ( ($name, $value) = each %Interfaces) {
  1241. $name = "$Package\::$name" unless $name =~ /::/;
  1242. push(@InitFileCode, Q<<"EOF");
  1243. # cv = newXS(\"$name\", XS_$Full_func_name, file);
  1244. # $interface_macro_set(cv,$value) ;
  1245. EOF
  1246. push(@InitFileCode, Q<<"EOF") if $proto;
  1247. # sv_setpv((SV*)cv$proto) ;
  1248. EOF
  1249. }
  1250. }
  1251. else {
  1252. push(@InitFileCode,
  1253. " ${newXS}(\"$pname\", XS_$Full_func_name, file$proto);\n");
  1254. }
  1255. }
  1256. # print initialization routine
  1257. print Q<<"EOF";
  1258. ##ifdef __cplusplus
  1259. #extern "C"
  1260. ##endif
  1261. EOF
  1262. print Q<<"EOF";
  1263. #XS(boot_$Module_cname)
  1264. EOF
  1265. print Q<<"EOF";
  1266. #[[
  1267. # dXSARGS;
  1268. # char* file = __FILE__;
  1269. #
  1270. EOF
  1271. print Q<<"EOF" if $WantVersionChk ;
  1272. # XS_VERSION_BOOTCHECK ;
  1273. #
  1274. EOF
  1275. print Q<<"EOF" if defined $XsubAliases or defined $Interfaces ;
  1276. # {
  1277. # CV * cv ;
  1278. #
  1279. EOF
  1280. print @InitFileCode;
  1281. print Q<<"EOF" if defined $XsubAliases or defined $Interfaces ;
  1282. # }
  1283. EOF
  1284. if (@BootCode)
  1285. {
  1286. print "\n /* Initialisation Section */\n\n" ;
  1287. @line = @BootCode;
  1288. print_section();
  1289. print "\n /* End of Initialisation Section */\n\n" ;
  1290. }
  1291. print Q<<"EOF";;
  1292. # XSRETURN_YES;
  1293. #]]
  1294. #
  1295. EOF
  1296. warn("Please specify prototyping behavior for $filename (see perlxs manual)\n")
  1297. unless $ProtoUsed ;
  1298. &Exit;
  1299. sub output_init {
  1300. local($type, $num, $var, $init, $name_printed) = @_;
  1301. local($arg) = "ST(" . ($num - 1) . ")";
  1302. if( $init =~ /^=/ ) {
  1303. if ($name_printed) {
  1304. eval qq/print " $init\\n"/;
  1305. } else {
  1306. eval qq/print "\\t$var $init\\n"/;
  1307. }
  1308. warn $@ if $@;
  1309. } else {
  1310. if( $init =~ s/^\+// && $num ) {
  1311. &generate_init($type, $num, $var, $name_printed);
  1312. } elsif ($name_printed) {
  1313. print ";\n";
  1314. $init =~ s/^;//;
  1315. } else {
  1316. eval qq/print "\\t$var;\\n"/;
  1317. warn $@ if $@;
  1318. $init =~ s/^;//;
  1319. }
  1320. $deferred .= eval qq/"\\n\\t$init\\n"/;
  1321. warn $@ if $@;
  1322. }
  1323. }
  1324. sub Warn
  1325. {
  1326. # work out the line number
  1327. my $line_no = $line_no[@line_no - @line -1] ;
  1328. print STDERR "@_ in $filename, line $line_no\n" ;
  1329. }
  1330. sub blurt
  1331. {
  1332. Warn @_ ;
  1333. $errors ++
  1334. }
  1335. sub death
  1336. {
  1337. Warn @_ ;
  1338. exit 1 ;
  1339. }
  1340. sub generate_init {
  1341. local($type, $num, $var) = @_;
  1342. local($arg) = "ST(" . ($num - 1) . ")";
  1343. local($argoff) = $num - 1;
  1344. local($ntype);
  1345. local($tk);
  1346. $type = TidyType($type) ;
  1347. blurt("Error: '$type' not in typemap"), return
  1348. unless defined($type_kind{$type});
  1349. ($ntype = $type) =~ s/\s*\*/Ptr/g;
  1350. ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
  1351. $tk = $type_kind{$type};
  1352. $tk =~ s/OBJ$/REF/ if $func_name =~ /DESTROY$/;
  1353. $type =~ tr/:/_/;
  1354. blurt("Error: No INPUT definition for type '$type', typekind '$type_kind{$type}' found"), return
  1355. unless defined $input_expr{$tk} ;
  1356. $expr = $input_expr{$tk};
  1357. if ($expr =~ /DO_ARRAY_ELEM/) {
  1358. blurt("Error: '$subtype' not in typemap"), return
  1359. unless defined($type_kind{$subtype});
  1360. blurt("Error: No INPUT definition for type '$subtype', typekind '$type_kind{$subtype}' found"), return
  1361. unless defined $input_expr{$type_kind{$subtype}} ;
  1362. $subexpr = $input_expr{$type_kind{$subtype}};
  1363. $subexpr =~ s/ntype/subtype/g;
  1364. $subexpr =~ s/\$arg/ST(ix_$var)/g;
  1365. $subexpr =~ s/\n\t/\n\t\t/g;
  1366. $subexpr =~ s/is not of (.*\")/[arg %d] is not of $1, ix_$var + 1/g;
  1367. $subexpr =~ s/\$var/${var}[ix_$var - $argoff]/;
  1368. $expr =~ s/DO_ARRAY_ELEM/$subexpr/;
  1369. }
  1370. if ($expr =~ m#/\*.*scope.*\*/#i) { # "scope" in C comments
  1371. $ScopeThisXSUB = 1;
  1372. }
  1373. if (defined($defaults{$var})) {
  1374. $expr =~ s/(\t+)/$1 /g;
  1375. $expr =~ s/ /\t/g;
  1376. if ($name_printed) {
  1377. print ";\n";
  1378. } else {
  1379. eval qq/print "\\t$var;\\n"/;
  1380. warn $@ if $@;
  1381. }
  1382. if ($defaults{$var} eq 'NO_INIT') {
  1383. $deferred .= eval qq/"\\n\\tif (items >= $num) {\\n$expr;\\n\\t}\\n"/;
  1384. } else {
  1385. $deferred .= eval qq/"\\n\\tif (items < $num)\\n\\t $var = $defaults{$var};\\n\\telse {\\n$expr;\\n\\t}\\n"/;
  1386. }
  1387. warn $@ if $@;
  1388. } elsif ($ScopeThisXSUB or $expr !~ /^\t\$var =/) {
  1389. if ($name_printed) {
  1390. print ";\n";
  1391. } else {
  1392. eval qq/print "\\t$var;\\n"/;
  1393. warn $@ if $@;
  1394. }
  1395. $deferred .= eval qq/"\\n$expr;\\n"/;
  1396. warn $@ if $@;
  1397. } else {
  1398. die "panic: do not know how to handle this branch for function pointers"
  1399. if $name_printed;
  1400. eval qq/print "$expr;\\n"/;
  1401. warn $@ if $@;
  1402. }
  1403. }
  1404. sub generate_output {
  1405. local($type, $num, $var, $do_setmagic, $do_push) = @_;
  1406. local($arg) = "ST(" . ($num - ($num != 0)) . ")";
  1407. local($argoff) = $num - 1;
  1408. local($ntype);
  1409. $type = TidyType($type) ;
  1410. if ($type =~ /^array\(([^,]*),(.*)\)/) {
  1411. print "\tsv_setpvn($arg, (char *)$var, $2 * sizeof($1));\n";
  1412. print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
  1413. } else {
  1414. blurt("Error: '$type' not in typemap"), return
  1415. unless defined($type_kind{$type});
  1416. blurt("Error: No OUTPUT definition for type '$type', typekind '$type_kind{$type}' found"), return
  1417. unless defined $output_expr{$type_kind{$type}} ;
  1418. ($ntype = $type) =~ s/\s*\*/Ptr/g;
  1419. $ntype =~ s/\(\)//g;
  1420. ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
  1421. $expr = $output_expr{$type_kind{$type}};
  1422. if ($expr =~ /DO_ARRAY_ELEM/) {
  1423. blurt("Error: '$subtype' not in typemap"), return
  1424. unless defined($type_kind{$subtype});
  1425. blurt("Error: No OUTPUT definition for type '$subtype', typekind '$type_kind{$subtype}' found"), return
  1426. unless defined $output_expr{$type_kind{$subtype}} ;
  1427. $subexpr = $output_expr{$type_kind{$subtype}};
  1428. $subexpr =~ s/ntype/subtype/g;
  1429. $subexpr =~ s/\$arg/ST(ix_$var)/g;
  1430. $subexpr =~ s/\$var/${var}[ix_$var]/g;
  1431. $subexpr =~ s/\n\t/\n\t\t/g;
  1432. $expr =~ s/DO_ARRAY_ELEM\n/$subexpr/;
  1433. eval "print qq\a$expr\a";
  1434. warn $@ if $@;
  1435. print "\t\tSvSETMAGIC(ST(ix_$var));\n" if $do_setmagic;
  1436. }
  1437. elsif ($var eq 'RETVAL') {
  1438. if ($expr =~ /^\t\$arg = new/) {
  1439. # We expect that $arg has refcnt 1, so we need to
  1440. # mortalize it.
  1441. eval "print qq\a$expr\a";
  1442. warn $@ if $@;
  1443. print "\tsv_2mortal(ST($num));\n";
  1444. print "\tSvSETMAGIC(ST($num));\n" if $do_setmagic;
  1445. }
  1446. elsif ($expr =~ /^\s*\$arg\s*=/) {
  1447. # We expect that $arg has refcnt >=1, so we need
  1448. # to mortalize it!
  1449. eval "print qq\a$expr\a";
  1450. warn $@ if $@;
  1451. print "\tsv_2mortal(ST(0));\n";
  1452. print "\tSvSETMAGIC(ST(0));\n" if $do_setmagic;
  1453. }
  1454. else {
  1455. # Just hope that the entry would safely write it
  1456. # over an already mortalized value. By
  1457. # coincidence, something like $arg = &sv_undef
  1458. # works too.
  1459. print "\tST(0) = sv_newmortal();\n";
  1460. eval "print qq\a$expr\a";
  1461. warn $@ if $@;
  1462. # new mortals don't have set magic
  1463. }
  1464. }
  1465. elsif ($do_push) {
  1466. print "\tPUSHs(sv_newmortal());\n";
  1467. $arg = "ST($num)";
  1468. eval "print qq\a$expr\a";
  1469. warn $@ if $@;
  1470. print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
  1471. }
  1472. elsif ($arg =~ /^ST\(\d+\)$/) {
  1473. eval "print qq\a$expr\a";
  1474. warn $@ if $@;
  1475. print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
  1476. }
  1477. }
  1478. }
  1479. sub map_type {
  1480. my($type, $varname) = @_;
  1481. $type =~ tr/:/_/;
  1482. $type =~ s/^array\(([^,]*),(.*)\).*/$1 */s;
  1483. if ($varname) {
  1484. if ($varname && $type =~ / \( \s* \* (?= \s* \) ) /xg) {
  1485. (substr $type, pos $type, 0) = " $varname ";
  1486. } else {
  1487. $type .= "\t$varname";
  1488. }
  1489. }
  1490. $type;
  1491. }
  1492. sub Exit {
  1493. # If this is VMS, the exit status has meaning to the shell, so we
  1494. # use a predictable value (SS$_Normal or SS$_Abort) rather than an
  1495. # arbitrary number.
  1496. # exit ($Is_VMS ? ($errors ? 44 : 1) : $errors) ;
  1497. exit ($errors ? 1 : 0);
  1498. }