Sub-MANIFEST-tweak.
[p5sagit/p5-mst-13.2.git] / ext / Encode / compile
1 #!../../perl -w
2 BEGIN {
3     unshift @INC, qw(../../lib ../../../lib);
4     $ENV{PATH} .= ';../..;../../..' if $^O eq 'MSWin32';
5 }
6 use strict;
7 use Getopt::Std;
8 my @orig_ARGV = @ARGV;
9
10 sub encode_U
11 {
12  # UTF-8 encode long hand - only covers part of perl's range
13  my $uv = shift;
14  # chr() works in native space so convert value from table
15  # into that space before using chr().
16  my $ch = chr(utf8::unicode_to_native($uv));
17  # Now get core perl to encode that the way it likes.
18  utf8::encode($ch);
19  return $ch;
20 }
21
22 sub encode_S
23 {
24  # encode single byte
25  my ($ch,$page) = @_;
26  return chr($ch);
27 }
28
29 sub encode_D
30 {
31  # encode double byte MS byte first
32  my ($ch,$page) = @_;
33  return chr($page).chr($ch);
34 }
35
36 sub encode_M
37 {
38  # encode Multi-byte - single for 0..255 otherwise double
39  my ($ch,$page) = @_;
40  return &encode_D if $page;
41  return &encode_S;
42 }
43
44 # Win32 does not expand globs on command line
45 eval "\@ARGV = map(glob(\$_),\@ARGV)" if ($^O eq 'MSWin32');
46
47 my %opt;
48 getopts('qo:f:n:',\%opt);
49 my $cname = (exists $opt{'o'}) ? $opt{'o'} : shift(@ARGV);
50 chmod(0666,$cname) if -f $cname && !-w $cname;
51 open(C,">$cname") || die "Cannot open $cname:$!";
52
53
54 my $dname = $cname;
55 $dname =~ s/(\.[^\.]*)?$/_def.h/;
56
57 my ($doC,$doEnc,$doUcm,$doPet);
58
59 if ($cname =~ /\.(c|xs)$/)
60  {
61   $doC = 1;
62   chmod(0666,$dname) if -f $cname && !-w $dname;
63   open(D,">$dname") || die "Cannot open $dname:$!";
64   my $hname = $cname;
65   $hname =~ s/(\.[^\.]*)?$/.h/;
66   chmod(0666,$hname) if -f $cname && !-w $hname;
67   open(H,">$hname") || die "Cannot open $hname:$!";
68
69   foreach my $fh (\*C,\*D,\*H)
70   {
71    print $fh <<"END" unless $opt{'q'};
72 /*
73  !!!!!!!   DO NOT EDIT THIS FILE   !!!!!!!
74  This file was autogenerated by:
75  $^X $0 @orig_ARGV
76 */
77 END
78   }
79
80   if ($cname =~ /(\w+)\.xs$/)
81    {
82     print C "#include <EXTERN.h>\n";
83     print C "#include <perl.h>\n";
84     print C "#include <XSUB.h>\n";
85     print C "#define U8 U8\n";
86    }
87   print C "#include \"encode.h\"\n";
88
89  }
90 elsif ($cname =~ /\.enc$/)
91  {
92   $doEnc = 1;
93  }
94 elsif ($cname =~ /\.ucm$/)
95  {
96   $doUcm = 1;
97  }
98 elsif ($cname =~ /\.pet$/)
99  {
100   $doPet = 1;
101  }
102
103 my @encfiles;
104 if (exists $opt{'f'})
105  {
106   # -F is followed by name of file containing list of filenames
107   my $flist = $opt{'f'};
108   open(FLIST,$flist) || die "Cannot open $flist:$!";
109   chomp(@encfiles = <FLIST>);
110   close(FLIST);
111  }
112 else
113  {
114   @encfiles = @ARGV;
115  }
116
117 my %encoding;
118 my %strings;
119 my $saved = 0;
120 my $subsave = 0;
121 my $strings = 0;
122
123 sub cmp_name
124 {
125  if ($a =~ /^.*-(\d+)/)
126   {
127    my $an = $1;
128    if ($b =~ /^.*-(\d+)/)
129     {
130      my $r = $an <=> $1;
131      return $r if $r;
132     }
133   }
134  return $a cmp $b;
135 }
136
137
138 foreach my $enc (sort cmp_name @encfiles)
139  {
140   my ($name,$sfx) = $enc =~ /^.*?([\w-]+)\.(enc|ucm)$/;
141   $name = $opt{'n'} if exists $opt{'n'};
142   if (open(E,$enc))
143    {
144     if ($sfx eq 'enc')
145      {
146       compile_enc(\*E,lc($name));
147      }
148     else
149      {
150       compile_ucm(\*E,lc($name));
151      }
152    }
153   else
154    {
155     warn "Cannot open $enc for $name:$!";
156    }
157  }
158
159 if ($doC)
160  {
161   print STDERR "Writing compiled form\n";
162   foreach my $name (sort cmp_name keys %encoding)
163    {
164     my ($e2u,$u2e,$erep,$min_el,$max_el) = @{$encoding{$name}};
165     output(\*C,$name.'_utf8',$e2u);
166     output(\*C,'utf8_'.$name,$u2e);
167     push(@{$encoding{$name}},outstring(\*C,$e2u->{Cname}.'_def',$erep));
168    }
169   foreach my $enc (sort cmp_name keys %encoding)
170    {
171     my ($e2u,$u2e,$rep,$min_el,$max_el,$rsym) = @{$encoding{$enc}};
172     my @info = ($e2u->{Cname},$u2e->{Cname},$rsym,length($rep),$min_el,$max_el);
173     my $sym = "${enc}_encoding";
174     $sym =~ s/\W+/_/g;
175     print C "encode_t $sym = \n";
176     print C " {",join(',',@info,"{\"$enc\",(const char *)0}"),"};\n\n";
177    }
178
179   foreach my $enc (sort cmp_name keys %encoding)
180    {
181     my $sym = "${enc}_encoding";
182     $sym =~ s/\W+/_/g;
183     print H "extern encode_t $sym;\n";
184     print D " Encode_XSEncoding(aTHX_ &$sym);\n";
185    }
186
187   if ($cname =~ /(\w+)\.xs$/)
188    {
189     my $mod = $1;
190     print C <<'END';
191
192 static void
193 Encode_XSEncoding(pTHX_ encode_t *enc)
194 {
195  dSP;
196  HV *stash = gv_stashpv("Encode::XS", TRUE);
197  SV *sv    = sv_bless(newRV_noinc(newSViv(PTR2IV(enc))),stash);
198  int i = 0;
199  PUSHMARK(sp);
200  XPUSHs(sv);
201  while (enc->name[i])
202   {
203    const char *name = enc->name[i++];
204    XPUSHs(sv_2mortal(newSVpvn(name,strlen(name))));
205   }
206  PUTBACK;
207  call_pv("Encode::define_encoding",G_DISCARD);
208  SvREFCNT_dec(sv);
209 }
210
211 END
212
213     print C "\nMODULE = Encode::$mod\tPACKAGE = Encode::$mod\n\n";
214     print C "BOOT:\n{\n";
215     print C "#include \"$dname\"\n";
216     print C "}\n";
217    }
218   close(D);
219   close(H);
220   printf STDERR "%d bytes in string tables\n",$strings;
221   printf STDERR "%d bytes (%.3g%%) saved spotting duplicates\n",$saved,100*$saved/$strings if $saved;
222   printf STDERR "%d bytes (%.3g%%) saved using substrings\n",$subsave,100*$subsave/$strings if $subsave;
223  }
224 elsif ($doEnc)
225  {
226   foreach my $name (sort cmp_name keys %encoding)
227    {
228     my ($e2u,$u2e,$erep,$min_el,$max_el) = @{$encoding{$name}};
229     output_enc(\*C,$name,$e2u);
230    }
231  }
232 elsif ($doUcm)
233  {
234   foreach my $name (sort cmp_name keys %encoding)
235    {
236     my ($e2u,$u2e,$erep,$min_el,$max_el) = @{$encoding{$name}};
237     output_ucm(\*C,$name,$u2e,$erep,$min_el,$max_el);
238    }
239  }
240
241 close(C);
242
243
244
245 sub compile_ucm
246 {
247  my ($fh,$name) = @_;
248  my $e2u = {};
249  my $u2e = {};
250  my $cs;
251  my %attr;
252  while (<$fh>)
253   {
254    s/#.*$//;
255    last if /^\s*CHARMAP\s*$/i;
256    if (/^\s*<(\w+)>\s+"?([^"]*)"?\s*$/i)
257     {
258      $attr{$1} = $2;
259     }
260   }
261  if (!defined($cs =  $attr{'code_set_name'}))
262   {
263    warn "No <code_set_name> in $name\n";
264   }
265  else
266   {
267    $name = $cs unless exists $opt{'n'};
268   }
269  my $erep;
270  my $urep;
271  my $max_el;
272  my $min_el;
273  if (exists $attr{'subchar'})
274   {
275    my @byte;
276    $attr{'subchar'} =~ /^\s*/cg;
277    push(@byte,$1) while $attr{'subchar'} =~ /\G\\x([0-9a-f]+)/icg;
278    $erep = join('',map(chr(hex($_)),@byte));
279   }
280  print "Reading $name ($cs)\n";
281  my $nfb = 0;
282  my $hfb = 0;
283  while (<$fh>)
284   {
285    s/#.*$//;
286    last if /^\s*END\s+CHARMAP\s*$/i;
287    next if /^\s*$/;
288    my ($u,@byte);
289    my $fb = '';
290    $u = $1 if (/^<U([0-9a-f]+)>\s+/igc);
291    push(@byte,$1) while /\G\\x([0-9a-f]+)/igc;
292    $fb = $1 if /\G\s*(\|[0-3])/gc;
293    # warn "$_: $u @byte | $fb\n";
294    die "Bad line:$_" unless /\G\s*(#.*)?$/gc;
295    if (defined($u))
296     {
297      my $uch = encode_U(hex($u));
298      my $ech = join('',map(chr(hex($_)),@byte));
299      my $el  = length($ech);
300      $max_el = $el if (!defined($max_el) || $el > $max_el);
301      $min_el = $el if (!defined($min_el) || $el < $min_el);
302      if (length($fb))
303       {
304        $fb = substr($fb,1);
305        $hfb++;
306       }
307      else
308       {
309        $nfb++;
310        $fb = '0';
311       }
312      # $fb is fallback flag
313      # 0 - round trip safe
314      # 1 - fallback for unicode -> enc
315      # 2 - skip sub-char mapping
316      # 3 - fallback enc -> unicode
317      enter($u2e,$uch,$ech,$u2e,$fb+0) if ($fb =~ /[01]/);
318      enter($e2u,$ech,$uch,$e2u,$fb+0) if ($fb =~ /[03]/);
319     }
320    else
321     {
322      warn $_;
323     }
324   }
325  if ($nfb && $hfb)
326   {
327    die "$nfb entries without fallback, $hfb entries with\n";
328   }
329  $encoding{$name} = [$e2u,$u2e,$erep,$min_el,$max_el];
330 }
331
332 sub compile_enc
333 {
334  my ($fh,$name) = @_;
335  my $e2u = {};
336  my $u2e = {};
337
338  my $type;
339  while ($type = <$fh>)
340   {
341    last if $type !~ /^\s*#/;
342   }
343  chomp($type);
344  return if $type eq 'E';
345  my ($def,$sym,$pages) = split(/\s+/,scalar(<$fh>));
346  warn "$type encoded $name\n";
347  my $rep = '';
348  my $min_el;
349  my $max_el;
350  {
351   my $v = hex($def);
352   no strict 'refs';
353   $rep = &{"encode_$type"}($v & 0xFF, ($v >> 8) & 0xffe);
354  }
355  my %seen;
356  while ($pages--)
357   {
358    my $line = <$fh>;
359    chomp($line);
360    my $page = hex($line);
361    my $ch = 0;
362    for (my $i = 0; $i < 16; $i++)
363     {
364      my $line = <$fh>;
365      for (my $j = 0; $j < 16; $j++)
366       {
367        no strict 'refs';
368        my $ech = &{"encode_$type"}($ch,$page);
369        my $val = hex(substr($line,0,4,''));
370        next if $val == 0xFFFD;
371        if ($val || (!$ch && !$page))
372         {
373          my $el  = length($ech);
374          $max_el = $el if (!defined($max_el) || $el > $max_el);
375          $min_el = $el if (!defined($min_el) || $el < $min_el);
376          my $uch = encode_U($val);
377          if (exists $seen{$uch})
378           {
379            warn sprintf("U%04X is %02X%02X and %02X%02X\n",
380                         $val,$page,$ch,@{$seen{$uch}});
381           }
382          else
383           {
384            $seen{$uch} = [$page,$ch];
385           }
386          enter($e2u,$ech,$uch,$e2u,0);
387          enter($u2e,$uch,$ech,$u2e,0);
388         }
389        else
390         {
391          # No character at this position
392          # enter($e2u,$ech,undef,$e2u);
393         }
394        $ch++;
395       }
396     }
397   }
398  $encoding{$name} = [$e2u,$u2e,$rep,$min_el,$max_el];
399 }
400
401 sub enter
402 {
403  my ($a,$s,$d,$t,$fb) = @_;
404  $t = $a if @_ < 4;
405  my $b = substr($s,0,1);
406  my $e = $a->{$b};
407  unless ($e)
408   {     # 0  1  2  3         4  5
409    $e = [$b,$b,'',{},length($s),0,$fb];
410    $a->{$b} = $e;
411   }
412  if (length($s) > 1)
413   {
414    enter($e->[3],substr($s,1),$d,$t,$fb);
415   }
416  else
417   {
418    $e->[2] = $d;
419    $e->[3] = $t;
420    $e->[5] = length($d);
421   }
422 }
423
424
425
426 sub outstring
427 {
428  my ($fh,$name,$s) = @_;
429  my $sym = $strings{$s};
430  if ($sym)
431   {
432    $saved += length($s);
433   }
434  else
435   {
436    foreach my $o (keys %strings)
437     {
438      my $i = index($o,$s);
439      if ($i >= 0)
440       {
441        $sym = $strings{$o};
442        $sym .= sprintf("+0x%02x",$i) if ($i);
443        $subsave += length($s);
444        return $sym;
445       }
446     }
447    $strings{$s} = $sym = $name;
448    $strings += length($s);
449    printf $fh "\nstatic const U8 %s[%d] =\n",$name,length($s);
450    # Do in chunks of 16 chars to constrain line length
451    # Assumes ANSI C adjacent string litteral concatenation
452    while (length($s))
453     {
454      my $c = substr($s,0,16,'');
455      print  $fh '"',join('',map(sprintf('\x%02x',ord($_)),split(//,$c))),'"';
456      print  $fh "\n" if length($s);
457     }
458    printf $fh ";\n";
459   }
460  return $sym;
461 }
462
463 sub process
464 {
465  my ($name,$a) = @_;
466  $name =~ s/\W+/_/g;
467  $a->{Cname} = $name;
468  my @keys = grep(ref($a->{$_}),sort keys %$a);
469  my $l;
470  my @ent;
471  foreach my $b (@keys)
472   {
473    my ($s,$f,$out,$t,$end) = @{$a->{$b}};
474    if (defined($l) &&
475        ord($b) == ord($a->{$l}[1])+1 &&
476        $a->{$l}[3] == $a->{$b}[3] &&
477        $a->{$l}[4] == $a->{$b}[4] &&
478        $a->{$l}[5] == $a->{$b}[5] &&
479        $a->{$l}[6] == $a->{$b}[6]
480        # && length($a->{$l}[2]) < 16
481       )
482     {
483      my $i = ord($b)-ord($a->{$l}[0]);
484      $a->{$l}[1]  = $b;
485      $a->{$l}[2] .= $a->{$b}[2];
486     }
487    else
488     {
489      $l = $b;
490      push(@ent,$b);
491     }
492    if (exists $t->{Cname})
493     {
494      $t->{'Forward'} = 1 if $t != $a;
495     }
496    else
497     {
498      process(sprintf("%s_%02x",$name,ord($s)),$t);
499     }
500   }
501  if (ord($keys[-1]) < 255)
502   {
503    my $t = chr(ord($keys[-1])+1);
504    $a->{$t} = [$t,chr(255),undef,$a,0,0];
505    push(@ent,$t);
506   }
507  $a->{'Entries'} = \@ent;
508 }
509
510 sub outtable
511 {
512  my ($fh,$a) = @_;
513  my $name = $a->{'Cname'};
514  # String tables
515  foreach my $b (@{$a->{'Entries'}})
516   {
517    next unless $a->{$b}[5];
518    my $s = ord($a->{$b}[0]);
519    my $e = ord($a->{$b}[1]);
520    outstring($fh,sprintf("%s__%02x_%02x",$name,$s,$e),$a->{$b}[2]);
521   }
522  if ($a->{'Forward'})
523   {
524    print $fh "\nstatic encpage_t $name\[",scalar(@{$a->{'Entries'}}),"];\n";
525   }
526  $a->{'Done'} = 1;
527  foreach my $b (@{$a->{'Entries'}})
528   {
529    my ($s,$e,$out,$t,$end,$l) = @{$a->{$b}};
530    outtable($fh,$t) unless $t->{'Done'};
531   }
532  print $fh "\nstatic encpage_t $name\[",scalar(@{$a->{'Entries'}}),"] = {\n";
533  foreach my $b (@{$a->{'Entries'}})
534   {
535    my ($s,$e,$out,$t,$end,$l,$fb) = @{$a->{$b}};
536    my $sc = ord($s);
537    my $ec = ord($e);
538    $end |= 0x80 if $fb;
539    print  $fh "{";
540    if ($l)
541     {
542      printf $fh outstring($fh,'',$out);
543     }
544    else
545     {
546      print  $fh "0";
547     }
548    print  $fh ",",$t->{Cname};
549    printf $fh ",0x%02x,0x%02x,$l,$end},\n",$sc,$ec;
550   }
551  print $fh "};\n";
552 }
553
554 sub output
555 {
556  my ($fh,$name,$a) = @_;
557  process($name,$a);
558  # Sub-tables
559  outtable($fh,$a);
560 }
561
562 sub output_enc
563 {
564  my ($fh,$name,$a) = @_;
565  foreach my $b (sort keys %$a)
566   {
567    my ($s,$e,$out,$t,$end,$l,$fb) = @{$a->{$b}};
568   }
569 }
570
571 sub decode_U
572 {
573  my $s = shift;
574 }
575
576 my @uname;
577 sub char_names
578 {
579  my $s = do "unicore/Name.pl";
580  die "char_names: unicore/Name.pl: $!\n" unless defined $s;
581  pos($s) = 0;
582  while ($s =~ /\G([0-9a-f]+)\t([0-9a-f]*)\t(.*?)\s*\n/igc)
583   {
584    my $name = $3;
585    my $s = hex($1);
586    last if $s >= 0x10000;
587    my $e = length($2) ? hex($2) : $s;
588    for (my $i = $s; $i <= $e; $i++)
589     {
590      $uname[$i] = $name;
591 #    print sprintf("U%04X $name\n",$i);
592     }
593   }
594 }
595
596 sub output_ucm_page
597 {
598  my ($cmap,$a,$t,$pre) = @_;
599  # warn sprintf("Page %x\n",$pre);
600  foreach my $b (sort keys %$t)
601   {
602    my ($s,$e,$out,$n,$end,$l,$fb) = @{$t->{$b}};
603    die "oops $s $e" unless $s eq $e;
604    my $u = ord($s);
605    if ($n != $a && $n != $t)
606     {
607      output_ucm_page($cmap,$a,$n,(($pre|($u &0x3F)) << 6)&0xFFFF);
608     }
609    elsif (length($out))
610     {
611      if ($pre)
612       {
613        $u = $pre|($u &0x3f);
614       }
615      my $s = sprintf "<U%04X> ",$u;
616      foreach my $c (split(//,$out))
617       {
618        $s .= sprintf "\\x%02X",ord($c);
619       }
620      $s .= sprintf " |%d # %s\n",($fb ? 1 : 0),$uname[$u];
621      push(@$cmap,$s);
622     }
623    else
624     {
625      warn join(',',@{$t->{$b}},$a,$t);
626     }
627   }
628 }
629
630 sub output_ucm
631 {
632  my ($fh,$name,$h,$rep,$min_el,$max_el) = @_;
633  print $fh "# $0 @orig_ARGV\n" unless $opt{'q'};
634  print $fh "<code_set_name> \"$name\"\n";
635  char_names();
636  if (defined $min_el)
637   {
638    print $fh "<mb_cur_min> $min_el\n";
639   }
640  if (defined $max_el)
641   {
642    print $fh "<mb_cur_max> $max_el\n";
643   }
644  if (defined $rep)
645   {
646    print $fh "<subchar> ";
647    foreach my $c (split(//,$rep))
648     {
649      printf $fh "\\x%02X",ord($c);
650     }
651    print $fh "\n";
652   }
653  my @cmap;
654  output_ucm_page(\@cmap,$h,$h,0);
655  print $fh "#\nCHARMAP\n";
656  foreach my $line (sort { substr($a,8) cmp substr($b,8) } @cmap)
657   {
658    print $fh $line;
659   }
660  print $fh "END CHARMAP\n";
661 }
662