Integrate perlio:
[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('qOo: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
406  while (1) {
407   $s =~ s/(.)//s;
408   my $b = $1;
409   my $e = $a->{$b};
410   #                 0  1  2  3           4  5
411   $a->{$b} = $e = [$b,$b,'',{},1+length($s),0,$fb] unless $e;
412   unless (length($s)) {
413    $e->[2] = $d;
414    $e->[3] = $t;
415    $e->[5] = length($d);
416    return;
417   }
418   # Tail recursion.
419   $a = $e->[3];
420  }
421 }
422
423
424
425 sub outstring
426 {
427  my ($fh,$name,$s) = @_;
428  my $sym = $strings{$s};
429  if ($sym)
430   {
431    $saved += length($s);
432   }
433  else
434   {
435    if ($opt{'O'}) {
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            $strings{$s} = $sym;
445            return $sym;
446           }
447         }
448    }
449    $strings{$s} = $sym = $name;
450    $strings += length($s);
451    my $definition = sprintf "static const U8 %s[%d] = { ",$name,length($s);
452    # Maybe we should assert that these are all <256.
453    $definition .= join(',',unpack "C*",$s);
454    # We have a single long line. Split it at convenient commas.
455    $definition =~ s/(.{74,77},)/$1\n/g;
456    print $fh "$definition };\n\n";
457   }
458  return $sym;
459 }
460
461 sub process
462 {
463  my ($name,$a) = @_;
464  $name =~ s/\W+/_/g;
465  $a->{Cname} = $name;
466  my @keys = grep(ref($a->{$_}),sort keys %$a);
467  my $l;
468  my @ent;
469  foreach my $b (@keys)
470   {
471    my ($s,$f,$out,$t,$end) = @{$a->{$b}};
472    if (defined($l) &&
473        ord($b) == ord($a->{$l}[1])+1 &&
474        $a->{$l}[3] == $a->{$b}[3] &&
475        $a->{$l}[4] == $a->{$b}[4] &&
476        $a->{$l}[5] == $a->{$b}[5] &&
477        $a->{$l}[6] == $a->{$b}[6]
478        # && length($a->{$l}[2]) < 16
479       )
480     {
481      my $i = ord($b)-ord($a->{$l}[0]);
482      $a->{$l}[1]  = $b;
483      $a->{$l}[2] .= $a->{$b}[2];
484     }
485    else
486     {
487      $l = $b;
488      push(@ent,$b);
489     }
490    if (exists $t->{Cname})
491     {
492      $t->{'Forward'} = 1 if $t != $a;
493     }
494    else
495     {
496      process(sprintf("%s_%02x",$name,ord($s)),$t);
497     }
498   }
499  if (ord($keys[-1]) < 255)
500   {
501    my $t = chr(ord($keys[-1])+1);
502    $a->{$t} = [$t,chr(255),undef,$a,0,0];
503    push(@ent,$t);
504   }
505  $a->{'Entries'} = \@ent;
506 }
507
508 sub outtable
509 {
510  my ($fh,$a) = @_;
511  my $name = $a->{'Cname'};
512  # String tables
513  foreach my $b (@{$a->{'Entries'}})
514   {
515    next unless $a->{$b}[5];
516    my $s = ord($a->{$b}[0]);
517    my $e = ord($a->{$b}[1]);
518    outstring($fh,sprintf("%s__%02x_%02x",$name,$s,$e),$a->{$b}[2]);
519   }
520  if ($a->{'Forward'})
521   {
522    print $fh "\nstatic encpage_t $name\[",scalar(@{$a->{'Entries'}}),"];\n";
523   }
524  $a->{'Done'} = 1;
525  foreach my $b (@{$a->{'Entries'}})
526   {
527    my ($s,$e,$out,$t,$end,$l) = @{$a->{$b}};
528    outtable($fh,$t) unless $t->{'Done'};
529   }
530  print $fh "\nstatic encpage_t $name\[",scalar(@{$a->{'Entries'}}),"] = {\n";
531  foreach my $b (@{$a->{'Entries'}})
532   {
533    my ($s,$e,$out,$t,$end,$l,$fb) = @{$a->{$b}};
534    my $sc = ord($s);
535    my $ec = ord($e);
536    $end |= 0x80 if $fb;
537    print  $fh "{";
538    if ($l)
539     {
540      printf $fh outstring($fh,'',$out);
541     }
542    else
543     {
544      print  $fh "0";
545     }
546    print  $fh ",",$t->{Cname};
547    printf $fh ",0x%02x,0x%02x,$l,$end},\n",$sc,$ec;
548   }
549  print $fh "};\n";
550 }
551
552 sub output
553 {
554  my ($fh,$name,$a) = @_;
555  process($name,$a);
556  # Sub-tables
557  outtable($fh,$a);
558 }
559
560 sub output_enc
561 {
562  my ($fh,$name,$a) = @_;
563  foreach my $b (sort keys %$a)
564   {
565    my ($s,$e,$out,$t,$end,$l,$fb) = @{$a->{$b}};
566   }
567 }
568
569 sub decode_U
570 {
571  my $s = shift;
572 }
573
574 my @uname;
575 sub char_names
576 {
577  my $s = do "unicore/Name.pl";
578  die "char_names: unicore/Name.pl: $!\n" unless defined $s;
579  pos($s) = 0;
580  while ($s =~ /\G([0-9a-f]+)\t([0-9a-f]*)\t(.*?)\s*\n/igc)
581   {
582    my $name = $3;
583    my $s = hex($1);
584    last if $s >= 0x10000;
585    my $e = length($2) ? hex($2) : $s;
586    for (my $i = $s; $i <= $e; $i++)
587     {
588      $uname[$i] = $name;
589 #    print sprintf("U%04X $name\n",$i);
590     }
591   }
592 }
593
594 sub output_ucm_page
595 {
596  my ($cmap,$a,$t,$pre) = @_;
597  # warn sprintf("Page %x\n",$pre);
598  foreach my $b (sort keys %$t)
599   {
600    my ($s,$e,$out,$n,$end,$l,$fb) = @{$t->{$b}};
601    die "oops $s $e" unless $s eq $e;
602    my $u = ord($s);
603    if ($n != $a && $n != $t)
604     {
605      output_ucm_page($cmap,$a,$n,(($pre|($u &0x3F)) << 6)&0xFFFF);
606     }
607    elsif (length($out))
608     {
609      if ($pre)
610       {
611        $u = $pre|($u &0x3f);
612       }
613      my $s = sprintf "<U%04X> ",$u;
614      foreach my $c (split(//,$out))
615       {
616        $s .= sprintf "\\x%02X",ord($c);
617       }
618      $s .= sprintf " |%d # %s\n",($fb ? 1 : 0),$uname[$u];
619      push(@$cmap,$s);
620     }
621    else
622     {
623      warn join(',',@{$t->{$b}},$a,$t);
624     }
625   }
626 }
627
628 sub output_ucm
629 {
630  my ($fh,$name,$h,$rep,$min_el,$max_el) = @_;
631  print $fh "# $0 @orig_ARGV\n" unless $opt{'q'};
632  print $fh "<code_set_name> \"$name\"\n";
633  char_names();
634  if (defined $min_el)
635   {
636    print $fh "<mb_cur_min> $min_el\n";
637   }
638  if (defined $max_el)
639   {
640    print $fh "<mb_cur_max> $max_el\n";
641   }
642  if (defined $rep)
643   {
644    print $fh "<subchar> ";
645    foreach my $c (split(//,$rep))
646     {
647      printf $fh "\\x%02X",ord($c);
648     }
649    print $fh "\n";
650   }
651  my @cmap;
652  output_ucm_page(\@cmap,$h,$h,0);
653  print $fh "#\nCHARMAP\n";
654  foreach my $line (sort { substr($a,8) cmp substr($b,8) } @cmap)
655   {
656    print $fh $line;
657   }
658  print $fh "END CHARMAP\n";
659 }
660