forked from Perl/perl5
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCollate.pm
2138 lines (1668 loc) · 63.7 KB
/
Collate.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package Unicode::Collate;
BEGIN {
unless ("A" eq pack('U', 0x41)) {
die "Unicode::Collate cannot stringify a Unicode code point\n";
}
unless (0x41 == unpack('U', 'A')) {
die "Unicode::Collate cannot get a Unicode code point\n";
}
}
use 5.006;
use strict;
use warnings;
use Carp;
use File::Spec;
no warnings 'utf8';
our $VERSION = '1.27';
our $PACKAGE = __PACKAGE__;
### begin XS only ###
use XSLoader ();
XSLoader::load('Unicode::Collate', $VERSION);
### end XS only ###
my @Path = qw(Unicode Collate);
my $KeyFile = 'allkeys.txt';
# Perl's boolean
use constant TRUE => 1;
use constant FALSE => "";
use constant NOMATCHPOS => -1;
# A coderef to get combining class imported from Unicode::Normalize
# (i.e. \&Unicode::Normalize::getCombinClass).
# This is also used as a HAS_UNICODE_NORMALIZE flag.
my $CVgetCombinClass;
# Supported Levels
use constant MinLevel => 1;
use constant MaxLevel => 4;
# Minimum weights at level 2 and 3, respectively
use constant Min2Wt => 0x20;
use constant Min3Wt => 0x02;
# Shifted weight at 4th level
use constant Shift4Wt => 0xFFFF;
# A boolean for Variable and 16-bit weights at 4 levels of Collation Element
use constant VCE_TEMPLATE => 'Cn4';
# A sort key: 16-bit weights
use constant KEY_TEMPLATE => 'n*';
# The tie-breaking: 32-bit weights
use constant TIE_TEMPLATE => 'N*';
# Level separator in a sort key:
# i.e. pack(KEY_TEMPLATE, 0)
use constant LEVEL_SEP => "\0\0";
# As Unicode code point separator for hash keys.
# A joined code point string (denoted by JCPS below)
# like "65;768" is used for internal processing
# instead of Perl's Unicode string like "\x41\x{300}",
# as the native code point is different from the Unicode code point
# on EBCDIC platform.
# This character must not be included in any stringified
# representation of an integer.
use constant CODE_SEP => ';';
# NOTE: in regex /;/ is used for $jcps!
# boolean values of variable weights
use constant NON_VAR => 0; # Non-Variable character
use constant VAR => 1; # Variable character
# specific code points
use constant Hangul_SIni => 0xAC00;
use constant Hangul_SFin => 0xD7A3;
# Logical_Order_Exception in PropList.txt
my $DefaultRearrange = [ 0x0E40..0x0E44, 0x0EC0..0x0EC4 ];
# for highestFFFF and minimalFFFE
my $HighestVCE = pack(VCE_TEMPLATE, 0, 0xFFFE, 0x20, 0x5, 0xFFFF);
my $minimalVCE = pack(VCE_TEMPLATE, 0, 1, 0x20, 0x5, 0xFFFE);
sub UCA_Version { '36' }
sub Base_Unicode_Version { '10.0.0' }
######
sub pack_U {
return pack('U*', @_);
}
sub unpack_U {
return unpack('U*', shift(@_).pack('U*'));
}
######
my (%VariableOK);
@VariableOK{ qw/
blanked non-ignorable shifted shift-trimmed
/ } = (); # keys lowercased
our @ChangeOK = qw/
alternate backwards level normalization rearrange
katakana_before_hiragana upper_before_lower ignore_level2
overrideCJK overrideHangul overrideOut preprocess UCA_Version
hangul_terminator variable identical highestFFFF minimalFFFE
long_contraction
/;
our @ChangeNG = qw/
entry mapping table maxlength contraction
ignoreChar ignoreName undefChar undefName rewrite
versionTable alternateTable backwardsTable forwardsTable
rearrangeTable variableTable
derivCode normCode rearrangeHash backwardsFlag
suppress suppressHash
__useXS /; ### XS only
# The hash key 'ignored' was deleted at v 0.21.
# The hash key 'isShift' was deleted at v 0.23.
# The hash key 'combining' was deleted at v 0.24.
# The hash key 'entries' was deleted at v 0.30.
# The hash key 'L3_ignorable' was deleted at v 0.40.
sub version {
my $self = shift;
return $self->{versionTable} || 'unknown';
}
my (%ChangeOK, %ChangeNG);
@ChangeOK{ @ChangeOK } = ();
@ChangeNG{ @ChangeNG } = ();
sub change {
my $self = shift;
my %hash = @_;
my %old;
if (exists $hash{alternate}) {
if (exists $hash{variable}) {
delete $hash{alternate};
} else {
$hash{variable} = $hash{alternate};
}
}
foreach my $k (keys %hash) {
if (exists $ChangeOK{$k}) {
$old{$k} = $self->{$k};
$self->{$k} = $hash{$k};
} elsif (exists $ChangeNG{$k}) {
croak "change of $k via change() is not allowed!";
}
# else => ignored
}
$self->checkCollator();
return wantarray ? %old : $self;
}
sub _checkLevel {
my $level = shift;
my $key = shift; # 'level' or 'backwards'
MinLevel <= $level or croak sprintf
"Illegal level %d (in value for key '%s') lower than %d.",
$level, $key, MinLevel;
$level <= MaxLevel or croak sprintf
"Unsupported level %d (in value for key '%s') higher than %d.",
$level, $key, MaxLevel;
}
my %DerivCode = (
8 => \&_derivCE_8,
9 => \&_derivCE_9,
11 => \&_derivCE_9, # 11 == 9
14 => \&_derivCE_14,
16 => \&_derivCE_14, # 16 == 14
18 => \&_derivCE_18,
20 => \&_derivCE_20,
22 => \&_derivCE_22,
24 => \&_derivCE_24,
26 => \&_derivCE_24, # 26 == 24
28 => \&_derivCE_24, # 28 == 24
30 => \&_derivCE_24, # 30 == 24
32 => \&_derivCE_32,
34 => \&_derivCE_34,
36 => \&_derivCE_36,
);
sub checkCollator {
my $self = shift;
_checkLevel($self->{level}, 'level');
$self->{derivCode} = $DerivCode{ $self->{UCA_Version} }
or croak "Illegal UCA version (passed $self->{UCA_Version}).";
$self->{variable} ||= $self->{alternate} || $self->{variableTable} ||
$self->{alternateTable} || 'shifted';
$self->{variable} = $self->{alternate} = lc($self->{variable});
exists $VariableOK{ $self->{variable} }
or croak "$PACKAGE unknown variable parameter name: $self->{variable}";
if (! defined $self->{backwards}) {
$self->{backwardsFlag} = 0;
} elsif (! ref $self->{backwards}) {
_checkLevel($self->{backwards}, 'backwards');
$self->{backwardsFlag} = 1 << $self->{backwards};
} else {
my %level;
$self->{backwardsFlag} = 0;
for my $b (@{ $self->{backwards} }) {
_checkLevel($b, 'backwards');
$level{$b} = 1;
}
for my $v (sort keys %level) {
$self->{backwardsFlag} += 1 << $v;
}
}
defined $self->{rearrange} or $self->{rearrange} = [];
ref $self->{rearrange}
or croak "$PACKAGE: list for rearrangement must be store in ARRAYREF";
# keys of $self->{rearrangeHash} are $self->{rearrange}.
$self->{rearrangeHash} = undef;
if (@{ $self->{rearrange} }) {
@{ $self->{rearrangeHash} }{ @{ $self->{rearrange} } } = ();
}
$self->{normCode} = undef;
if (defined $self->{normalization}) {
eval { require Unicode::Normalize };
$@ and croak "Unicode::Normalize is required to normalize strings";
$CVgetCombinClass ||= \&Unicode::Normalize::getCombinClass;
if ($self->{normalization} =~ /^(?:NF)D\z/) { # tweak for default
$self->{normCode} = \&Unicode::Normalize::NFD;
}
elsif ($self->{normalization} ne 'prenormalized') {
my $norm = $self->{normalization};
$self->{normCode} = sub {
Unicode::Normalize::normalize($norm, shift);
};
eval { $self->{normCode}->("") }; # try
$@ and croak "$PACKAGE unknown normalization form name: $norm";
}
}
return;
}
sub new
{
my $class = shift;
my $self = bless { @_ }, $class;
### begin XS only ###
if (! exists $self->{table} && !defined $self->{rewrite} &&
!defined $self->{undefName} && !defined $self->{ignoreName} &&
!defined $self->{undefChar} && !defined $self->{ignoreChar}) {
$self->{__useXS} = \&_fetch_simple;
} else {
$self->{__useXS} = undef;
}
### end XS only ###
# keys of $self->{suppressHash} are $self->{suppress}.
if ($self->{suppress} && @{ $self->{suppress} }) {
@{ $self->{suppressHash} }{ @{ $self->{suppress} } } = ();
} # before read_table()
# If undef is passed explicitly, no file is read.
$self->{table} = $KeyFile if ! exists $self->{table};
$self->read_table() if defined $self->{table};
if ($self->{entry}) {
while ($self->{entry} =~ /([^\n]+)/g) {
$self->parseEntry($1, TRUE);
}
}
# only in new(), not in change()
$self->{level} ||= MaxLevel;
$self->{UCA_Version} ||= UCA_Version();
$self->{overrideHangul} = FALSE
if ! exists $self->{overrideHangul};
$self->{overrideCJK} = FALSE
if ! exists $self->{overrideCJK};
$self->{normalization} = 'NFD'
if ! exists $self->{normalization};
$self->{rearrange} = $self->{rearrangeTable} ||
($self->{UCA_Version} <= 11 ? $DefaultRearrange : [])
if ! exists $self->{rearrange};
$self->{backwards} = $self->{backwardsTable}
if ! exists $self->{backwards};
exists $self->{long_contraction} or $self->{long_contraction}
= 22 <= $self->{UCA_Version} && $self->{UCA_Version} <= 24;
# checkCollator() will be called in change()
$self->checkCollator();
return $self;
}
sub parseAtmark {
my $self = shift;
my $line = shift; # after s/^\s*\@//
if ($line =~ /^version\s*(\S*)/) {
$self->{versionTable} ||= $1;
}
elsif ($line =~ /^variable\s+(\S*)/) { # since UTS #10-9
$self->{variableTable} ||= $1;
}
elsif ($line =~ /^alternate\s+(\S*)/) { # till UTS #10-8
$self->{alternateTable} ||= $1;
}
elsif ($line =~ /^backwards\s+(\S*)/) {
push @{ $self->{backwardsTable} }, $1;
}
elsif ($line =~ /^forwards\s+(\S*)/) { # perhaps no use
push @{ $self->{forwardsTable} }, $1;
}
elsif ($line =~ /^rearrange\s+(.*)/) { # (\S*) is NG
push @{ $self->{rearrangeTable} }, _getHexArray($1);
}
}
sub read_table {
my $self = shift;
### begin XS only ###
if ($self->{__useXS}) {
my @rest = _fetch_rest(); # complex matter need to parse
for my $line (@rest) {
next if $line =~ /^\s*#/;
if ($line =~ s/^\s*\@//) {
$self->parseAtmark($line);
} else {
$self->parseEntry($line);
}
}
return;
}
### end XS only ###
my($f, $fh);
foreach my $d (@INC) {
$f = File::Spec->catfile($d, @Path, $self->{table});
last if open($fh, $f);
$f = undef;
}
if (!defined $f) {
$f = File::Spec->catfile(@Path, $self->{table});
croak("$PACKAGE: Can't locate $f in \@INC (\@INC contains: @INC)");
}
while (my $line = <$fh>) {
next if $line =~ /^\s*#/;
if ($line =~ s/^\s*\@//) {
$self->parseAtmark($line);
} else {
$self->parseEntry($line);
}
}
close $fh;
}
##
## get $line, parse it, and write an entry in $self
##
sub parseEntry
{
my $self = shift;
my $line = shift;
my $tailoring = shift;
my($name, $entry, @uv, @key);
if (defined $self->{rewrite}) {
$line = $self->{rewrite}->($line);
}
return if $line !~ /^\s*[0-9A-Fa-f]/;
# removes comment and gets name
$name = $1
if $line =~ s/[#%]\s*(.*)//;
return if defined $self->{undefName} && $name =~ /$self->{undefName}/;
# gets element
my($e, $k) = split /;/, $line;
croak "Wrong Entry: <charList> must be separated by ';' from <collElement>"
if ! $k;
@uv = _getHexArray($e);
return if !@uv;
return if @uv > 1 && $self->{suppressHash} && !$tailoring &&
exists $self->{suppressHash}{$uv[0]};
$entry = join(CODE_SEP, @uv); # in JCPS
if (defined $self->{undefChar} || defined $self->{ignoreChar}) {
my $ele = pack_U(@uv);
# regarded as if it were not stored in the table
return
if defined $self->{undefChar} && $ele =~ /$self->{undefChar}/;
# replaced as completely ignorable
$k = '[.0000.0000.0000.0000]'
if defined $self->{ignoreChar} && $ele =~ /$self->{ignoreChar}/;
}
# replaced as completely ignorable
$k = '[.0000.0000.0000.0000]'
if defined $self->{ignoreName} && $name =~ /$self->{ignoreName}/;
my $is_L3_ignorable = TRUE;
foreach my $arr ($k =~ /\[([^\[\]]+)\]/g) { # SPACEs allowed
my $var = $arr =~ /\*/; # exactly /^\*/ but be lenient.
my @wt = _getHexArray($arr);
push @key, pack(VCE_TEMPLATE, $var, @wt);
$is_L3_ignorable = FALSE
if $wt[0] || $wt[1] || $wt[2];
# Conformance Test for 3.1.1 and 4.0.0 shows Level 3 ignorable
# is completely ignorable.
# For expansion, an entry $is_L3_ignorable
# if and only if "all" CEs are [.0000.0000.0000].
}
# mapping: be an array ref or not exists (any false value is disallowed)
$self->{mapping}{$entry} = $is_L3_ignorable ? [] : \@key;
# maxlength: be more than 1 or not exists (any false value is disallowed)
if (@uv > 1) {
if (!$self->{maxlength}{$uv[0]} || $self->{maxlength}{$uv[0]} < @uv) {
$self->{maxlength}{$uv[0]} = @uv;
}
}
# contraction: be 1 or not exists (any false value is disallowed)
while (@uv > 2) {
pop @uv;
my $fake_entry = join(CODE_SEP, @uv); # in JCPS
$self->{contraction}{$fake_entry} = 1;
}
}
sub viewSortKey
{
my $self = shift;
my $str = shift;
$self->visualizeSortKey($self->getSortKey($str));
}
sub process
{
my $self = shift;
my $str = shift;
my $prep = $self->{preprocess};
my $norm = $self->{normCode};
$str = &$prep($str) if ref $prep;
$str = &$norm($str) if ref $norm;
return $str;
}
##
## arrayref of JCPS = splitEnt(string to be collated)
## arrayref of arrayref[JCPS, ini_pos, fin_pos] = splitEnt(string, TRUE)
##
sub splitEnt
{
my $self = shift;
my $str = shift;
my $wLen = shift; # with Length
my $map = $self->{mapping};
my $max = $self->{maxlength};
my $reH = $self->{rearrangeHash};
my $vers = $self->{UCA_Version};
my $ver9 = $vers >= 9 && $vers <= 11;
my $long = $self->{long_contraction};
my $uXS = $self->{__useXS}; ### XS only
my @buf;
# get array of Unicode code point of string.
my @src = unpack_U($str);
# rearrangement:
# Character positions are not kept if rearranged,
# then neglected if $wLen is true.
if ($reH && ! $wLen) {
for (my $i = 0; $i < @src; $i++) {
if (exists $reH->{ $src[$i] } && $i + 1 < @src) {
($src[$i], $src[$i+1]) = ($src[$i+1], $src[$i]);
$i++;
}
}
}
# remove a code point marked as a completely ignorable.
for (my $i = 0; $i < @src; $i++) {
if ($vers <= 20 && _isIllegal($src[$i])) {
$src[$i] = undef;
} elsif ($ver9) {
$src[$i] = undef if exists $map->{ $src[$i] }
? @{ $map->{ $src[$i] } } == 0
: $uXS && _ignorable_simple($src[$i]); ### XS only
}
}
for (my $i = 0; $i < @src; $i++) {
my $jcps = $src[$i];
# skip removed code point
if (! defined $jcps) {
if ($wLen && @buf) {
$buf[-1][2] = $i + 1;
}
next;
}
my $i_orig = $i;
# find contraction
if (exists $max->{$jcps}) {
my $temp_jcps = $jcps;
my $jcpsLen = 1;
my $maxLen = $max->{$jcps};
for (my $p = $i + 1; $jcpsLen < $maxLen && $p < @src; $p++) {
next if ! defined $src[$p];
$temp_jcps .= CODE_SEP . $src[$p];
$jcpsLen++;
if (exists $map->{$temp_jcps}) {
$jcps = $temp_jcps;
$i = $p;
}
}
# discontiguous contraction with Combining Char (cf. UTS#10, S2.1).
# This process requires Unicode::Normalize.
# If "normalization" is undef, here should be skipped *always*
# (in spite of bool value of $CVgetCombinClass),
# since canonical ordering cannot be expected.
# Blocked combining character should not be contracted.
# $self->{normCode} is false in the case of "prenormalized".
if ($self->{normalization}) {
my $cont = $self->{contraction};
my $preCC = 0;
my $preCC_uc = 0;
my $jcps_uc = $jcps;
my(@out, @out_uc);
for (my $p = $i + 1; $p < @src; $p++) {
next if ! defined $src[$p];
my $curCC = $CVgetCombinClass->($src[$p]);
last unless $curCC;
my $tail = CODE_SEP . $src[$p];
if ($preCC != $curCC && exists $map->{$jcps.$tail}) {
$jcps .= $tail;
push @out, $p;
} else {
$preCC = $curCC;
}
next if !$long;
if ($preCC_uc != $curCC &&
(exists $map->{$jcps_uc.$tail} ||
exists $cont->{$jcps_uc.$tail})) {
$jcps_uc .= $tail;
push @out_uc, $p;
} else {
$preCC_uc = $curCC;
}
}
if (@out_uc && exists $map->{$jcps_uc}) {
$jcps = $jcps_uc;
$src[$_] = undef for @out_uc;
} else {
$src[$_] = undef for @out;
}
}
}
# skip completely ignorable
if (exists $map->{$jcps} ? @{ $map->{$jcps} } == 0 :
$uXS && $jcps !~ /;/ && _ignorable_simple($jcps)) { ### XS only
if ($wLen && @buf) {
$buf[-1][2] = $i + 1;
}
next;
}
push @buf, $wLen ? [$jcps, $i_orig, $i + 1] : $jcps;
}
return \@buf;
}
##
## VCE = _pack_override(input, codepoint, derivCode)
##
sub _pack_override ($$$) {
my $r = shift;
my $u = shift;
my $der = shift;
if (ref $r) {
return pack(VCE_TEMPLATE, NON_VAR, @$r);
} elsif (defined $r) {
return pack(VCE_TEMPLATE, NON_VAR, $r, Min2Wt, Min3Wt, $u);
} else {
$u = 0xFFFD if 0x10FFFF < $u;
return $der->($u);
}
}
##
## list of VCE = getWt(JCPS)
##
sub getWt
{
my $self = shift;
my $u = shift;
my $map = $self->{mapping};
my $der = $self->{derivCode};
my $out = $self->{overrideOut};
my $uXS = $self->{__useXS}; ### XS only
return if !defined $u;
return $self->varCE($HighestVCE) if $u eq 0xFFFF && $self->{highestFFFF};
return $self->varCE($minimalVCE) if $u eq 0xFFFE && $self->{minimalFFFE};
$u = 0xFFFD if $u !~ /;/ && 0x10FFFF < $u && !$out;
my @ce;
if (exists $map->{$u}) {
@ce = @{ $map->{$u} }; # $u may be a contraction
### begin XS only ###
} elsif ($uXS && _exists_simple($u)) {
@ce = _fetch_simple($u);
### end XS only ###
} elsif (Hangul_SIni <= $u && $u <= Hangul_SFin) {
my $hang = $self->{overrideHangul};
if ($hang) {
@ce = map _pack_override($_, $u, $der), $hang->($u);
} elsif (!defined $hang) {
@ce = $der->($u);
} else {
my $max = $self->{maxlength};
my @decH = _decompHangul($u);
if (@decH == 2) {
my $contract = join(CODE_SEP, @decH);
@decH = ($contract) if exists $map->{$contract};
} else { # must be <@decH == 3>
if (exists $max->{$decH[0]}) {
my $contract = join(CODE_SEP, @decH);
if (exists $map->{$contract}) {
@decH = ($contract);
} else {
$contract = join(CODE_SEP, @decH[0,1]);
exists $map->{$contract} and @decH = ($contract, $decH[2]);
}
# even if V's ignorable, LT contraction is not supported.
# If such a situation were required, NFD should be used.
}
if (@decH == 3 && exists $max->{$decH[1]}) {
my $contract = join(CODE_SEP, @decH[1,2]);
exists $map->{$contract} and @decH = ($decH[0], $contract);
}
}
@ce = map({
exists $map->{$_} ? @{ $map->{$_} } :
$uXS && _exists_simple($_) ? _fetch_simple($_) : ### XS only
$der->($_);
} @decH);
}
} elsif ($out && 0x10FFFF < $u) {
@ce = map _pack_override($_, $u, $der), $out->($u);
} else {
my $cjk = $self->{overrideCJK};
my $vers = $self->{UCA_Version};
if ($cjk && _isUIdeo($u, $vers)) {
@ce = map _pack_override($_, $u, $der), $cjk->($u);
} elsif ($vers == 8 && defined $cjk && _isUIdeo($u, 0)) {
@ce = _uideoCE_8($u);
} else {
@ce = $der->($u);
}
}
return map $self->varCE($_), @ce;
}
##
## string sortkey = getSortKey(string arg)
##
sub getSortKey
{
my $self = shift;
my $orig = shift;
my $str = $self->process($orig);
my $rEnt = $self->splitEnt($str); # get an arrayref of JCPS
my $vers = $self->{UCA_Version};
my $term = $self->{hangul_terminator};
my $lev = $self->{level};
my $iden = $self->{identical};
my @buf; # weight arrays
if ($term) {
my $preHST = '';
my $termCE = $self->varCE(pack(VCE_TEMPLATE, NON_VAR, $term, 0,0,0));
foreach my $jcps (@$rEnt) {
# weird things like VL, TL-contraction are not considered!
my $curHST = join '', map getHST($_, $vers), split /;/, $jcps;
if ($preHST && !$curHST || # hangul before non-hangul
$preHST =~ /L\z/ && $curHST =~ /^T/ ||
$preHST =~ /V\z/ && $curHST =~ /^L/ ||
$preHST =~ /T\z/ && $curHST =~ /^[LV]/) {
push @buf, $termCE;
}
$preHST = $curHST;
push @buf, $self->getWt($jcps);
}
push @buf, $termCE if $preHST; # end at hangul
} else {
foreach my $jcps (@$rEnt) {
push @buf, $self->getWt($jcps);
}
}
my $rkey = $self->mk_SortKey(\@buf); ### XS only
if ($iden || $vers >= 26 && $lev == MaxLevel) {
$rkey .= LEVEL_SEP;
$rkey .= pack(TIE_TEMPLATE, unpack_U($str)) if $iden;
}
return $rkey;
}
##
## int compare = cmp(string a, string b)
##
sub cmp { $_[0]->getSortKey($_[1]) cmp $_[0]->getSortKey($_[2]) }
sub eq { $_[0]->getSortKey($_[1]) eq $_[0]->getSortKey($_[2]) }
sub ne { $_[0]->getSortKey($_[1]) ne $_[0]->getSortKey($_[2]) }
sub lt { $_[0]->getSortKey($_[1]) lt $_[0]->getSortKey($_[2]) }
sub le { $_[0]->getSortKey($_[1]) le $_[0]->getSortKey($_[2]) }
sub gt { $_[0]->getSortKey($_[1]) gt $_[0]->getSortKey($_[2]) }
sub ge { $_[0]->getSortKey($_[1]) ge $_[0]->getSortKey($_[2]) }
##
## list[strings] sorted = sort(list[strings] arg)
##
sub sort {
my $obj = shift;
return
map { $_->[1] }
sort{ $a->[0] cmp $b->[0] }
map [ $obj->getSortKey($_), $_ ], @_;
}
##
## bool _nonIgnorAtLevel(arrayref weights, int level)
##
sub _nonIgnorAtLevel($$)
{
my $wt = shift;
return if ! defined $wt;
my $lv = shift;
return grep($wt->[$_-1] != 0, MinLevel..$lv) ? TRUE : FALSE;
}
##
## bool _eqArray(
## arrayref of arrayref[weights] source,
## arrayref of arrayref[weights] substr,
## int level)
## * comparison of graphemes vs graphemes.
## @$source >= @$substr must be true (check it before call this);
##
sub _eqArray($$$)
{
my $source = shift;
my $substr = shift;
my $lev = shift;
for my $g (0..@$substr-1){
# Do the $g'th graphemes have the same number of AV weights?
return if @{ $source->[$g] } != @{ $substr->[$g] };
for my $w (0..@{ $substr->[$g] }-1) {
for my $v (0..$lev-1) {
return if $source->[$g][$w][$v] != $substr->[$g][$w][$v];
}
}
}
return 1;
}
##
## (int position, int length)
## int position = index(string, substring, position, [undoc'ed global])
##
## With "global" (only for the list context),
## returns list of arrayref[position, length].
##
sub index
{
my $self = shift;
$self->{preprocess} and
croak "Don't use Preprocess with index(), match(), etc.";
$self->{normCode} and
croak "Don't use Normalization with index(), match(), etc.";
my $str = shift;
my $len = length($str);
my $sub = shift;
my $subE = $self->splitEnt($sub);
my $pos = @_ ? shift : 0;
$pos = 0 if $pos < 0;
my $glob = shift;
my $lev = $self->{level};
my $v2i = $self->{UCA_Version} >= 9 &&
$self->{variable} ne 'non-ignorable';
if (! @$subE) {
my $temp = $pos <= 0 ? 0 : $len <= $pos ? $len : $pos;
return $glob
? map([$_, 0], $temp..$len)
: wantarray ? ($temp,0) : $temp;
}
$len < $pos
and return wantarray ? () : NOMATCHPOS;
my $strE = $self->splitEnt($pos ? substr($str, $pos) : $str, TRUE);
@$strE
or return wantarray ? () : NOMATCHPOS;
my(@strWt, @iniPos, @finPos, @subWt, @g_ret);
my $last_is_variable;
for my $vwt (map $self->getWt($_), @$subE) {
my($var, @wt) = unpack(VCE_TEMPLATE, $vwt);
my $to_be_pushed = _nonIgnorAtLevel(\@wt,$lev);
# "Ignorable (L1, L2) after Variable" since track. v. 9
if ($v2i) {
if ($var) {
$last_is_variable = TRUE;
}
elsif (!$wt[0]) { # ignorable
$to_be_pushed = FALSE if $last_is_variable;
}
else {
$last_is_variable = FALSE;
}
}
if (@subWt && !$var && !$wt[0]) {
push @{ $subWt[-1] }, \@wt if $to_be_pushed;
} elsif ($to_be_pushed) {
push @subWt, [ \@wt ];
}
# else ===> skipped
}
my $count = 0;
my $end = @$strE - 1;
$last_is_variable = FALSE; # reuse
for (my $i = 0; $i <= $end; ) { # no $i++
my $found_base = 0;
# fetch a grapheme
while ($i <= $end && $found_base == 0) {
for my $vwt ($self->getWt($strE->[$i][0])) {
my($var, @wt) = unpack(VCE_TEMPLATE, $vwt);
my $to_be_pushed = _nonIgnorAtLevel(\@wt,$lev);
# "Ignorable (L1, L2) after Variable" since track. v. 9
if ($v2i) {
if ($var) {
$last_is_variable = TRUE;
}
elsif (!$wt[0]) { # ignorable
$to_be_pushed = FALSE if $last_is_variable;
}
else {
$last_is_variable = FALSE;
}
}
if (@strWt && !$var && !$wt[0]) {
push @{ $strWt[-1] }, \@wt if $to_be_pushed;
$finPos[-1] = $strE->[$i][2];
} elsif ($to_be_pushed) {
push @strWt, [ \@wt ];
push @iniPos, $found_base ? NOMATCHPOS : $strE->[$i][1];
$finPos[-1] = NOMATCHPOS if $found_base;
push @finPos, $strE->[$i][2];
$found_base++;
}
# else ===> no-op
}
$i++;
}
# try to match
while ( @strWt > @subWt || (@strWt == @subWt && $i > $end) ) {
if ($iniPos[0] != NOMATCHPOS &&
$finPos[$#subWt] != NOMATCHPOS &&
_eqArray(\@strWt, \@subWt, $lev)) {
my $temp = $iniPos[0] + $pos;
if ($glob) {
push @g_ret, [$temp, $finPos[$#subWt] - $iniPos[0]];
splice @strWt, 0, $#subWt;
splice @iniPos, 0, $#subWt;
splice @finPos, 0, $#subWt;
}
else {
return wantarray
? ($temp, $finPos[$#subWt] - $iniPos[0])
: $temp;
}
}
shift @strWt;
shift @iniPos;
shift @finPos;
}
}
return $glob
? @g_ret
: wantarray ? () : NOMATCHPOS;
}
##
## scalarref to matching part = match(string, substring)
##
sub match
{
my $self = shift;
if (my($pos,$len) = $self->index($_[0], $_[1])) {
my $temp = substr($_[0], $pos, $len);
return wantarray ? $temp : \$temp;
# An lvalue ref \substr should be avoided,
# since its value is affected by modification of its referent.
}
else {
return;
}
}
##
## arrayref matching parts = gmatch(string, substring)
##
sub gmatch
{
my $self = shift;
my $str = shift;
my $sub = shift;
return map substr($str, $_->[0], $_->[1]),
$self->index($str, $sub, 0, 'g');
}
##
## bool subst'ed = subst(string, substring, replace)
##
sub subst
{
my $self = shift;
my $code = ref $_[2] eq 'CODE' ? $_[2] : FALSE;
if (my($pos,$len) = $self->index($_[0], $_[1])) {
if ($code) {