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