Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 200
0.00% covered (danger)
0.00%
0 / 11
CRAP
0.00% covered (danger)
0.00%
0 / 2
GenerateCollationData
0.00% covered (danger)
0.00%
0 / 140
0.00% covered (danger)
0.00%
0 / 5
2162
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
 execute
0.00% covered (danger)
0.00%
0 / 31
0.00% covered (danger)
0.00%
0 / 1
90
 loadUcd
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 charCallback
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
110
 generateFirstChars
0.00% covered (danger)
0.00%
0 / 79
0.00% covered (danger)
0.00%
0 / 1
650
UcdXmlReader
0.00% covered (danger)
0.00%
0 / 60
0.00% covered (danger)
0.00%
0 / 6
992
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 readChars
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
90
 open
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
20
 readAttributes
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 handleChar
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
72
 getBlocks
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
56
1<?php
2/**
3 * Maintenance script to generate first letter data files for Collation.php.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup MaintenanceLanguage
22 */
23
24// @codeCoverageIgnoreStart
25require_once __DIR__ . '/../Maintenance.php';
26// @codeCoverageIgnoreEnd
27
28use Wikimedia\StaticArrayWriter;
29
30/**
31 * Generate first letter data files for Collation.php
32 *
33 * @ingroup MaintenanceLanguage
34 */
35class GenerateCollationData extends Maintenance {
36    /** @var string The directory with source data files in it */
37    public $dataDir;
38
39    /** @var int The primary weights, indexed by codepoint */
40    public $weights;
41
42    /**
43     * A hashtable keyed by codepoint, where presence indicates that a character
44     * has a decomposition mapping. This makes it non-preferred for group header
45     * selection.
46     * @var string[]
47     */
48    public $mappedChars;
49
50    /** @var string */
51    public $debugOutFile;
52
53    /** @var string[] */
54    private $groups;
55
56    public function __construct() {
57        parent::__construct();
58        $this->addOption( 'data-dir', 'A directory on the local filesystem ' .
59            'containing allkeys.txt and ucd.all.grouped.xml from unicode.org',
60            false, true );
61        $this->addOption( 'debug-output', 'Filename for sending debug output to',
62            false, true );
63    }
64
65    public function execute() {
66        $this->dataDir = $this->getOption( 'data-dir', '.' );
67
68        $allkeysPresent = file_exists( "{$this->dataDir}/allkeys.txt" );
69        $ucdallPresent = file_exists( "{$this->dataDir}/ucd.all.grouped.xml" );
70
71        if ( !$allkeysPresent || !$ucdallPresent ) {
72            $icuVersion = INTL_ICU_VERSION;
73            $unicodeVersion = implode( '.', array_slice( IntlChar::getUnicodeVersion(), 0, 3 ) );
74
75            $error = "";
76
77            if ( !$allkeysPresent ) {
78                $error .= "Unable to find allkeys.txt. "
79                    . "Download it and specify its location with --data-dir=<DIR>. "
80                    . "\n\n";
81            }
82            if ( !$ucdallPresent ) {
83                $error .= "Unable to find ucd.all.grouped.xml. "
84                    . "Download it, unzip, and specify its location with --data-dir=<DIR>. "
85                    . "\n\n";
86            }
87
88            $error .= "You are using ICU $icuVersion, intended for Unicode $unicodeVersion"
89                . "Appropriate file(s) should be available at:\n";
90
91            $allkeysURL = "https://www.unicode.org/Public/UCA/$unicodeVersion/allkeys.txt";
92            $ucdallURL = "https://www.unicode.org/Public/$unicodeVersion/ucdxml/ucd.all.grouped.zip";
93
94            if ( !$allkeysPresent ) {
95                $error .= "$allkeysURL\n";
96            }
97            if ( !$ucdallPresent ) {
98                $error .= "$ucdallURL\n";
99            }
100
101            $this->fatalError( $error );
102        }
103
104        $debugOutFileName = $this->getOption( 'debug-output' );
105        if ( $debugOutFileName ) {
106            $this->debugOutFile = fopen( $debugOutFileName, 'w' );
107            if ( !$this->debugOutFile ) {
108                $this->fatalError( "Unable to open debug output file for writing" );
109            }
110        }
111        $this->loadUcd();
112        $this->generateFirstChars();
113    }
114
115    private function loadUcd() {
116        $uxr = new UcdXmlReader( "{$this->dataDir}/ucd.all.grouped.xml" );
117        $uxr->readChars( [ $this, 'charCallback' ] );
118    }
119
120    private function charCallback( $data ) {
121        // Skip non-printable characters,
122        // but do not skip a normal space (U+0020) since
123        // people like to use that as a fake no header symbol.
124        $category = substr( $data['gc'], 0, 1 );
125        if ( strpos( 'LNPS', $category ) === false
126            && $data['cp'] !== '0020'
127        ) {
128            return;
129        }
130        $cp = hexdec( $data['cp'] );
131
132        // Skip the CJK ideograph blocks, as an optimisation measure.
133        // UCA doesn't sort them properly anyway, without tailoring.
134        if ( IcuCollation::isCjk( $cp ) ) {
135            return;
136        }
137
138        // Skip the composed Hangul syllables, we will use the bare Jamo
139        // as first letters
140        if ( $data['block'] == 'Hangul Syllables' ) {
141            return;
142        }
143
144        // Calculate implicit weight per UTS #10 v6.0.0, sec 7.1.3
145        if ( $data['UIdeo'] === 'Y' ) {
146            if ( $data['block'] == 'CJK Unified Ideographs'
147                || $data['block'] == 'CJK Compatibility Ideographs'
148            ) {
149                $base = 0xFB40;
150            } else {
151                $base = 0xFB80;
152            }
153        } else {
154            $base = 0xFBC0;
155        }
156        $a = $base + ( $cp >> 15 );
157        $b = ( $cp & 0x7fff ) | 0x8000;
158
159        $this->weights[$cp] = sprintf( ".%04X.%04X", $a, $b );
160
161        if ( $data['dm'] !== '#' ) {
162            $this->mappedChars[$cp] = true;
163        }
164
165        if ( $cp % 4096 == 0 ) {
166            print "{$data['cp']}\n";
167        }
168    }
169
170    private function generateFirstChars() {
171        $file = fopen( "{$this->dataDir}/allkeys.txt", 'r' );
172        if ( !$file ) {
173            $this->fatalError( "Unable to open allkeys.txt" );
174        }
175
176        $goodTertiaryChars = [];
177
178        // For each character with an entry in allkeys.txt, overwrite the implicit
179        // entry in $this->weights that came from the UCD.
180        // Also gather a list of tertiary weights, for use in selecting the group header
181        // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition
182        while ( ( $line = fgets( $file ) ) !== false ) {
183            // We're only interested in single-character weights, pick them out with a regex
184            $line = trim( $line );
185            if ( !preg_match( '/^([0-9A-F]+)\s*;\s*([^#]*)/', $line, $m ) ) {
186                continue;
187            }
188
189            $cp = hexdec( $m[1] );
190            $allWeights = trim( $m[2] );
191            $primary = '';
192            $tertiary = '';
193
194            if ( !isset( $this->weights[$cp] ) ) {
195                // Non-printable, ignore
196                continue;
197            }
198            foreach ( StringUtils::explode( '[', $allWeights ) as $weightStr ) {
199                if ( preg_match_all( '/[*.]([0-9A-F]+)/', $weightStr, $m ) ) {
200                    if ( $m[1][0] !== '0000' ) {
201                        $primary .= '.' . $m[1][0];
202                    }
203                    if ( $m[1][2] !== '0000' ) {
204                        $tertiary .= '.' . $m[1][2];
205                    }
206                }
207            }
208            $this->weights[$cp] = $primary;
209            if ( $tertiary === '.0008'
210                || $tertiary === '.000E'
211            ) {
212                $goodTertiaryChars[$cp] = true;
213            }
214        }
215        fclose( $file );
216
217        // Identify groups of characters with the same primary weight
218        $this->groups = [];
219        asort( $this->weights, SORT_STRING );
220        $prevWeight = reset( $this->weights );
221        $group = [];
222        foreach ( $this->weights as $cp => $weight ) {
223            if ( $weight !== $prevWeight ) {
224                $this->groups[$prevWeight] = $group;
225                $prevWeight = $weight;
226                $group = $this->groups[$weight] ?? [];
227            }
228            $group[] = $cp;
229        }
230        if ( $group ) {
231            $this->groups[$prevWeight] = $group;
232        }
233
234        // If one character has a given primary weight sequence, and a second
235        // character has a longer primary weight sequence with an initial
236        // portion equal to the first character, then remove the second
237        // character. This avoids having characters like U+A732 (double A)
238        // polluting the basic Latin sort area.
239
240        foreach ( $this->groups as $weight => $group ) {
241            if ( preg_match( '/(\.[0-9A-F]*)\./', $weight, $m ) ) {
242                if ( isset( $this->groups[$m[1]] ) ) {
243                    unset( $this->groups[$weight] );
244                }
245            }
246        }
247
248        ksort( $this->groups, SORT_STRING );
249
250        // Identify the header character in each group
251        $headerChars = [];
252        $prevChar = "\000";
253        $tertiaryCollator = new Collator( 'root' );
254        $primaryCollator = new Collator( 'root' );
255        $primaryCollator->setStrength( Collator::PRIMARY );
256        $numOutOfOrder = 0;
257        foreach ( $this->groups as $weight => $group ) {
258            $uncomposedChars = [];
259            $goodChars = [];
260            foreach ( $group as $cp ) {
261                if ( isset( $goodTertiaryChars[$cp] ) ) {
262                    $goodChars[] = $cp;
263                }
264                if ( !isset( $this->mappedChars[$cp] ) ) {
265                    $uncomposedChars[] = $cp;
266                }
267            }
268            $x = array_intersect( $goodChars, $uncomposedChars );
269            if ( !$x ) {
270                $x = $uncomposedChars;
271                if ( !$x ) {
272                    $x = $group;
273                }
274            }
275
276            // Use ICU to pick the lowest sorting character in the selection
277            $tertiaryCollator->sort( $x );
278            $cp = $x[0];
279
280            $char = UtfNormal\Utils::codepointToUtf8( $cp );
281            $headerChars[] = $char;
282            if ( $primaryCollator->compare( $char, $prevChar ) <= 0 ) {
283                $numOutOfOrder++;
284            }
285            $prevChar = $char;
286
287            if ( $this->debugOutFile ) {
288                fwrite( $this->debugOutFile, sprintf( "%05X %s %s (%s)\n", $cp, $weight, $char,
289                    implode( ' ', array_map( [ UtfNormal\Utils::class, 'codepointToUtf8' ], $group ) ) ) );
290            }
291        }
292
293        print "Out of order: $numOutOfOrder / " . count( $headerChars ) . "\n";
294
295        global $IP;
296        $writer = new StaticArrayWriter();
297        file_put_contents(
298            "$IP/includes/collation/data/first-letters-root.php",
299            $writer->create( $headerChars, 'File created by generateCollationData.php' )
300        );
301        echo "first-letters-root: file written.\n";
302    }
303}
304
305class UcdXmlReader {
306    /** @var string */
307    public $fileName;
308    /** @var callable */
309    public $callback;
310    /** @var array */
311    public $groupAttrs;
312    /** @var XMLReader */
313    public $xml;
314    /** @var array[] */
315    public $blocks = [];
316    /** @var array */
317    public $currentBlock;
318
319    public function __construct( $fileName ) {
320        $this->fileName = $fileName;
321    }
322
323    public function readChars( $callback ) {
324        $this->getBlocks();
325        $this->currentBlock = reset( $this->blocks );
326        $xml = $this->open();
327        $this->callback = $callback;
328
329        while ( $xml->name !== 'repertoire' && $xml->next() );
330
331        while ( $xml->read() ) {
332            if ( $xml->nodeType == XMLReader::ELEMENT ) {
333                if ( $xml->name === 'group' ) {
334                    $this->groupAttrs = $this->readAttributes();
335                } elseif ( $xml->name === 'char' ) {
336                    $this->handleChar();
337                }
338            } elseif ( $xml->nodeType === XMLReader::END_ELEMENT ) {
339                if ( $xml->name === 'group' ) {
340                    $this->groupAttrs = [];
341                }
342            }
343        }
344        $xml->close();
345    }
346
347    protected function open() {
348        $this->xml = new XMLReader;
349        if ( !$this->xml->open( $this->fileName ) ) {
350            throw new RuntimeException( __METHOD__ . ": unable to open {$this->fileName}" );
351        }
352        while ( $this->xml->name !== 'ucd' && $this->xml->read() );
353        $this->xml->read();
354
355        return $this->xml;
356    }
357
358    /**
359     * Read the attributes of the current element node and return them
360     * as an array
361     * @return array
362     */
363    protected function readAttributes() {
364        $attrs = [];
365        while ( $this->xml->moveToNextAttribute() ) {
366            $attrs[$this->xml->name] = $this->xml->value;
367        }
368
369        return $attrs;
370    }
371
372    protected function handleChar() {
373        $attrs = $this->readAttributes() + $this->groupAttrs;
374        if ( isset( $attrs['cp'] ) ) {
375            $first = $last = hexdec( $attrs['cp'] );
376        } else {
377            $first = hexdec( $attrs['first-cp'] );
378            $last = hexdec( $attrs['last-cp'] );
379            unset( $attrs['first-cp'] );
380            unset( $attrs['last-cp'] );
381        }
382
383        for ( $cp = $first; $cp <= $last; $cp++ ) {
384            $hexCp = sprintf( "%04X", $cp );
385            foreach ( [ 'na', 'na1' ] as $nameProp ) {
386                if ( isset( $attrs[$nameProp] ) ) {
387                    $attrs[$nameProp] = str_replace( '#', $hexCp, $attrs[$nameProp] );
388                }
389            }
390
391            while ( $this->currentBlock ) {
392                if ( $cp < $this->currentBlock[0] ) {
393                    break;
394                } elseif ( $cp <= $this->currentBlock[1] ) {
395                    $attrs['block'] = key( $this->blocks );
396                    break;
397                } else {
398                    $this->currentBlock = next( $this->blocks );
399                }
400            }
401
402            $attrs['cp'] = $hexCp;
403            call_user_func( $this->callback, $attrs );
404        }
405    }
406
407    public function getBlocks() {
408        if ( $this->blocks ) {
409            return $this->blocks;
410        }
411
412        $xml = $this->open();
413        while ( $xml->name !== 'blocks' && $xml->read() );
414
415        while ( $xml->read() ) {
416            if ( $xml->nodeType == XMLReader::ELEMENT ) {
417                if ( $xml->name === 'block' ) {
418                    $attrs = $this->readAttributes();
419                    $first = hexdec( $attrs['first-cp'] );
420                    $last = hexdec( $attrs['last-cp'] );
421                    $this->blocks[$attrs['name']] = [ $first, $last ];
422                }
423            }
424        }
425        $xml->close();
426
427        return $this->blocks;
428    }
429}
430
431// @codeCoverageIgnoreStart
432$maintClass = GenerateCollationData::class;
433require_once RUN_MAINTENANCE_IF_MAIN;
434// @codeCoverageIgnoreEnd