13498d1d6a28c3b2128451f586f3242118af5820
[p5sagit/p5-mst-13.2.git] / ext / Encode / compile
1 #!../../perl -w
2 BEGIN {
3     unshift @INC, '../../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('qo: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/;
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 $cname @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
121 sub cmp_name
122 {
123  if ($a =~ /^.*-(\d+)/)
124   {
125    my $an = $1;
126    if ($b =~ /^.*-(\d+)/)
127     {
128      my $r = $an <=> $1;
129      return $r if $r;
130     }
131   }
132  return $a cmp $b;
133 }
134
135
136 foreach my $enc (sort cmp_name @encfiles)
137  {
138   my ($name,$sfx) = $enc =~ /^.*?([\w-]+)\.(enc|ucm)$/;
139   $name = $opt{'n'} if exists $opt{'n'};
140   if (open(E,$enc))
141    {
142     if ($sfx eq 'enc')
143      {
144       compile_enc(\*E,lc($name));
145      }
146     else
147      {
148       compile_ucm(\*E,lc($name));
149      }
150    }
151   else
152    {
153     warn "Cannot open $enc for $name:$!";
154    }
155  }
156
157 if ($doC)
158  {
159   foreach my $name (sort cmp_name keys %encoding)
160    {
161     my ($e2u,$u2e,$erep,$min_el,$max_el) = @{$encoding{$name}};
162     output(\*C,$name.'_utf8',$e2u);
163     output(\*C,'utf8_'.$name,$u2e);
164     push(@{$encoding{$name}},outstring(\*C,$e2u->{Cname}.'_def',$erep));
165    }
166   foreach my $enc (sort cmp_name keys %encoding)
167    {
168     my ($e2u,$u2e,$rep,$min_el,$max_el,$rsym) = @{$encoding{$enc}};
169     my @info = ($e2u->{Cname},$u2e->{Cname},$rsym,length($rep),$min_el,$max_el);
170     my $sym = "${enc}_encoding";
171     $sym =~ s/\W+/_/g;
172     print C "encode_t $sym = \n";
173     print C " {",join(',',@info,"{\"$enc\",(const char *)0}"),"};\n\n";
174    }
175
176   foreach my $enc (sort cmp_name keys %encoding)
177    {
178     my $sym = "${enc}_encoding";
179     $sym =~ s/\W+/_/g;
180     print H "extern encode_t $sym;\n";
181     print D " Encode_XSEncoding(aTHX_ &$sym);\n";
182    }
183
184   if ($cname =~ /(\w+)\.xs$/)
185    {
186     my $mod = $1;
187     print C <<'END';
188
189 void
190 Encode_XSEncoding(pTHX_ encode_t *enc)
191 {
192  dSP;
193  HV *stash = gv_stashpv("Encode::XS", TRUE);
194  SV *sv    = sv_bless(newRV_noinc(newSViv(PTR2IV(enc))),stash);
195  int i = 0;
196  PUSHMARK(sp);
197  XPUSHs(sv);
198  while (enc->name[i])
199   {
200    const char *name = enc->name[i++];
201    XPUSHs(sv_2mortal(newSVpvn(name,strlen(name))));
202   }
203  PUTBACK;
204  call_pv("Encode::define_encoding",G_DISCARD);
205  SvREFCNT_dec(sv);
206 }
207
208 END
209
210     print C "\nMODULE = Encode::$mod\tPACKAGE = Encode::$mod\n\n";
211     print C "BOOT:\n{\n";
212     print C "#include \"$dname\"\n";
213     print C "}\n";
214    }
215   close(D);
216   close(H);
217  }
218 elsif ($doEnc)
219  {
220   foreach my $name (sort cmp_name keys %encoding)
221    {
222     my ($e2u,$u2e,$erep,$min_el,$max_el) = @{$encoding{$name}};
223     output_enc(\*C,$name,$e2u);
224    }
225  }
226 elsif ($doUcm)
227  {
228   foreach my $name (sort cmp_name keys %encoding)
229    {
230     my ($e2u,$u2e,$erep,$min_el,$max_el) = @{$encoding{$name}};
231     output_ucm(\*C,$name,$u2e,$erep,$min_el,$max_el);
232    }
233  }
234
235 close(C);
236
237
238 sub compile_ucm
239 {
240  my ($fh,$name) = @_;
241  my $e2u = {};
242  my $u2e = {};
243  my $cs;
244  my %attr;
245  while (<$fh>)
246   {
247    s/#.*$//;
248    last if /^\s*CHARMAP\s*$/i;
249    if (/^\s*<(\w+)>\s+"?([^"]*)"?\s*$/i)
250     {
251      $attr{$1} = $2;
252     }
253   }
254  if (!defined($cs =  $attr{'code_set_name'}))
255   {
256    warn "No <code_set_name> in $name\n";
257   }
258  else
259   {
260    $name = $cs unless exists $opt{'n'};
261   }
262  my $erep;
263  my $urep;
264  my $max_el;
265  my $min_el;
266  if (exists $attr{'subchar'})
267   {
268    my @byte;
269    $attr{'subchar'} =~ /^\s*/cg;
270    push(@byte,$1) while $attr{'subchar'} =~ /\G\\x([0-9a-f]+)/icg;
271    $erep = join('',map(chr(hex($_)),@byte));
272   }
273  print "Scanning $name ($cs)\n";
274  my $nfb = 0;
275  my $hfb = 0;
276  while (<$fh>)
277   {
278    s/#.*$//;
279    last if /^\s*END\s+CHARMAP\s*$/i;
280    next if /^\s*$/;
281    my ($u,@byte);
282    my $fb = '';
283    $u = $1 if (/^<U([0-9a-f]+)>\s+/igc);
284    push(@byte,$1) while /\G\\x([0-9a-f]+)/igc;
285    $fb = $1 if /\G\s*(\|[0-3])/gc;
286    # warn "$_: $u @byte | $fb\n";
287    die "Bad line:$_" unless /\G\s*(#.*)?$/gc;
288    if (defined($u))
289     {
290      my $uch = encode_U(hex($u));
291      my $ech = join('',map(chr(hex($_)),@byte));
292      my $el  = length($ech);
293      $max_el = $el if (!defined($max_el) || $el > $max_el);
294      $min_el = $el if (!defined($min_el) || $el < $min_el);
295      if (length($fb))
296       {
297        $fb = substr($fb,1);
298        $hfb++;
299       }
300      else
301       {
302        $nfb++;
303        $fb = '0';
304       }
305      # $fb is fallback flag
306      # 0 - round trip safe
307      # 1 - fallback for unicode -> enc
308      # 2 - skip sub-char mapping
309      # 3 - fallback enc -> unicode
310      enter($u2e,$uch,$ech,$u2e,$fb+0) if ($fb =~ /[01]/);
311      enter($e2u,$ech,$uch,$e2u,$fb+0) if ($fb =~ /[03]/);
312     }
313    else
314     {
315      warn $_;
316     }
317   }
318  if ($nfb && $hfb)
319   {
320    die "$nfb entries without fallback, $hfb entries with\n";
321   }
322  $encoding{$name} = [$e2u,$u2e,$erep,$min_el,$max_el];
323 }
324
325 sub compile_enc
326 {
327  my ($fh,$name) = @_;
328  my $e2u = {};
329  my $u2e = {};
330
331  my $type;
332  while ($type = <$fh>)
333   {
334    last if $type !~ /^\s*#/;
335   }
336  chomp($type);
337  return if $type eq 'E';
338  my ($def,$sym,$pages) = split(/\s+/,scalar(<$fh>));
339  warn "$type encoded $name\n";
340  my $rep = '';
341  my $min_el;
342  my $max_el;
343  {
344   my $v = hex($def);
345   no strict 'refs';
346   $rep = &{"encode_$type"}($v & 0xFF, ($v >> 8) & 0xffe);
347  }
348  my %seen;
349  while ($pages--)
350   {
351    my $line = <$fh>;
352    chomp($line);
353    my $page = hex($line);
354    my $ch = 0;
355    for (my $i = 0; $i < 16; $i++)
356     {
357      my $line = <$fh>;
358      for (my $j = 0; $j < 16; $j++)
359       {
360        no strict 'refs';
361        my $ech = &{"encode_$type"}($ch,$page);
362        my $val = hex(substr($line,0,4,''));
363        next if $val == 0xFFFD;
364        if ($val || (!$ch && !$page))
365         {
366          my $el  = length($ech);
367          $max_el = $el if (!defined($max_el) || $el > $max_el);
368          $min_el = $el if (!defined($min_el) || $el < $min_el);
369          my $uch = encode_U($val);
370          if (exists $seen{$uch})
371           {
372            warn sprintf("U%04X is %02X%02X and %02X%02X\n",
373                         $val,$page,$ch,@{$seen{$uch}});
374           }
375          else
376           {
377            $seen{$uch} = [$page,$ch];
378           }
379          enter($e2u,$ech,$uch,$e2u,0);
380          enter($u2e,$uch,$ech,$u2e,0);
381         }
382        else
383         {
384          # No character at this position
385          # enter($e2u,$ech,undef,$e2u);
386         }
387        $ch++;
388       }
389     }
390   }
391  $encoding{$name} = [$e2u,$u2e,$rep,$min_el,$max_el];
392 }
393
394 sub enter
395 {
396  my ($a,$s,$d,$t,$fb) = @_;
397  $t = $a if @_ < 4;
398  my $b = substr($s,0,1);
399  my $e = $a->{$b};
400  unless ($e)
401   {     # 0  1  2  3         4  5
402    $e = [$b,$b,'',{},length($s),0,$fb];
403    $a->{$b} = $e;
404   }
405  if (length($s) > 1)
406   {
407    enter($e->[3],substr($s,1),$d,$t,$fb);
408   }
409  else
410   {
411    $e->[2] = $d;
412    $e->[3] = $t;
413    $e->[5] = length($d);
414   }
415 }
416
417 sub outstring
418 {
419  my ($fh,$name,$s) = @_;
420  my $sym = $strings{$s};
421  unless ($sym)
422   {
423    foreach my $o (keys %strings)
424     {
425      my $i = index($o,$s);
426      if ($i >= 0)
427       {
428        $sym = $strings{$o};
429        $sym .= sprintf("+0x%02x",$i) if ($i);
430        return $sym;
431       }
432     }
433    $strings{$s} = $sym = $name;
434    printf $fh "\nstatic const U8 %s[%d] =\n",$name,length($s);
435    # Do in chunks of 16 chars to constrain line length
436    # Assumes ANSI C adjacent string litteral concatenation
437    while (length($s))
438     {
439      my $c = substr($s,0,16,'');
440      print  $fh '"',join('',map(sprintf('\x%02x',ord($_)),split(//,$c))),'"';
441      print  $fh "\n" if length($s);
442     }
443    printf $fh ";\n";
444   }
445  return $sym;
446 }
447
448 sub process
449 {
450  my ($name,$a) = @_;
451  $name =~ s/\W+/_/g;
452  $a->{Cname} = $name;
453  my @keys = grep(ref($a->{$_}),sort keys %$a);
454  my $l;
455  my @ent;
456  foreach my $b (@keys)
457   {
458    my ($s,$f,$out,$t,$end) = @{$a->{$b}};
459    if (defined($l) &&
460        ord($b) == ord($a->{$l}[1])+1 &&
461        $a->{$l}[3] == $a->{$b}[3] &&
462        $a->{$l}[4] == $a->{$b}[4] &&
463        $a->{$l}[5] == $a->{$b}[5] &&
464        $a->{$l}[6] == $a->{$b}[6]
465        # && length($a->{$l}[2]) < 16
466       )
467     {
468      my $i = ord($b)-ord($a->{$l}[0]);
469      $a->{$l}[1]  = $b;
470      $a->{$l}[2] .= $a->{$b}[2];
471     }
472    else
473     {
474      $l = $b;
475      push(@ent,$b);
476     }
477    if (exists $t->{Cname})
478     {
479      $t->{'Forward'} = 1 if $t != $a;
480     }
481    else
482     {
483      process(sprintf("%s_%02x",$name,ord($s)),$t);
484     }
485   }
486  if (ord($keys[-1]) < 255)
487   {
488    my $t = chr(ord($keys[-1])+1);
489    $a->{$t} = [$t,chr(255),undef,$a,0,0];
490    push(@ent,$t);
491   }
492  $a->{'Entries'} = \@ent;
493 }
494
495 sub outtable
496 {
497  my ($fh,$a) = @_;
498  my $name = $a->{'Cname'};
499  # String tables
500  foreach my $b (@{$a->{'Entries'}})
501   {
502    next unless $a->{$b}[5];
503    my $s = ord($a->{$b}[0]);
504    my $e = ord($a->{$b}[1]);
505    outstring($fh,sprintf("%s__%02x_%02x",$name,$s,$e),$a->{$b}[2]);
506   }
507  if ($a->{'Forward'})
508   {
509    print $fh "\nstatic encpage_t $name\[",scalar(@{$a->{'Entries'}}),"];\n";
510   }
511  $a->{'Done'} = 1;
512  foreach my $b (@{$a->{'Entries'}})
513   {
514    my ($s,$e,$out,$t,$end,$l) = @{$a->{$b}};
515    outtable($fh,$t) unless $t->{'Done'};
516   }
517  print $fh "\nstatic encpage_t $name\[",scalar(@{$a->{'Entries'}}),"] = {\n";
518  foreach my $b (@{$a->{'Entries'}})
519   {
520    my ($s,$e,$out,$t,$end,$l,$fb) = @{$a->{$b}};
521    my $sc = ord($s);
522    my $ec = ord($e);
523    $end |= 0x80 if $fb;
524    print  $fh "{";
525    if ($l)
526     {
527      printf $fh outstring($fh,'',$out);
528     }
529    else
530     {
531      print  $fh "0";
532     }
533    print  $fh ",",$t->{Cname};
534    printf $fh ",0x%02x,0x%02x,$l,$end},\n",$sc,$ec;
535   }
536  print $fh "};\n";
537 }
538
539 sub output
540 {
541  my ($fh,$name,$a) = @_;
542  process($name,$a);
543  # Sub-tables
544  outtable($fh,$a);
545 }
546
547 sub output_enc
548 {
549  my ($fh,$name,$a) = @_;
550  foreach my $b (sort keys %$a)
551   {
552    my ($s,$e,$out,$t,$end,$l,$fb) = @{$a->{$b}};
553   }
554 }
555
556 sub decode_U
557 {
558  my $s = shift;
559 }
560
561 my @uname;
562 sub char_names
563 {
564  my $s = do "unicore/Name.pl";
565  die "char_names: unicore/Name.pl: $!\n" unless defined $s;
566  pos($s) = 0;
567  while ($s =~ /\G([0-9a-f]+)\t([0-9a-f]*)\t(.*?)\s*\n/igc)
568   {
569    my $name = $3;
570    my $s = hex($1);
571    last if $s >= 0x10000;
572    my $e = length($2) ? hex($2) : $s;
573    for (my $i = $s; $i <= $e; $i++)
574     {
575      $uname[$i] = $name;
576 #    print sprintf("U%04X $name\n",$i);
577     }
578   }
579 }
580
581 sub output_ucm_page
582 {
583  my ($cmap,$a,$t,$pre) = @_;
584  # warn sprintf("Page %x\n",$pre);
585  foreach my $b (sort keys %$t)
586   {
587    my ($s,$e,$out,$n,$end,$l,$fb) = @{$t->{$b}};
588    die "oops $s $e" unless $s eq $e;
589    my $u = ord($s);
590    if ($n != $a && $n != $t)
591     {
592      output_ucm_page($cmap,$a,$n,(($pre|($u &0x3F)) << 6)&0xFFFF);
593     }
594    elsif (length($out))
595     {
596      if ($pre)
597       {
598        $u = $pre|($u &0x3f);
599       }
600      my $s = sprintf "<U%04X> ",$u;
601      foreach my $c (split(//,$out))
602       {
603        $s .= sprintf "\\x%02X",ord($c);
604       }
605      $s .= sprintf " |%d # %s\n",($fb ? 1 : 0),$uname[$u];
606      push(@$cmap,$s);
607     }
608    else
609     {
610      warn join(',',@{$t->{$b}},$a,$t);
611     }
612   }
613 }
614
615 sub output_ucm
616 {
617  my ($fh,$name,$h,$rep,$min_el,$max_el) = @_;
618  print $fh "# $0 @orig_ARGV\n" unless $opt{'q'};
619  print $fh "<code_set_name> \"$name\"\n";
620  char_names();
621  if (defined $min_el)
622   {
623    print $fh "<mb_cur_min> $min_el\n";
624   }
625  if (defined $max_el)
626   {
627    print $fh "<mb_cur_max> $max_el\n";
628   }
629  if (defined $rep)
630   {
631    print $fh "<subchar> ";
632    foreach my $c (split(//,$rep))
633     {
634      printf $fh "\\x%02X",ord($c);
635     }
636    print $fh "\n";
637   }
638  my @cmap;
639  output_ucm_page(\@cmap,$h,$h,0);
640  print $fh "#\nCHARMAP\n";
641  foreach my $line (sort { substr($a,8) cmp substr($b,8) } @cmap)
642   {
643    print $fh $line;
644   }
645  print $fh "END CHARMAP\n";
646 }
647