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