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