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