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