3 * Maintenance script to generate first letter data files for Collation.php.
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.
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.
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
21 * @ingroup MaintenanceLanguage
24 // @codeCoverageIgnoreStart
25 require_once __DIR__
. '/../Maintenance.php';
26 // @codeCoverageIgnoreEnd
28 use Wikimedia\StaticArrayWriter
;
31 * Generate first letter data files for Collation.php
33 * @ingroup MaintenanceLanguage
35 class GenerateCollationData
extends Maintenance
{
36 /** @var string The directory with source data files in it */
39 /** @var int The primary weights, indexed by codepoint */
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
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',
61 $this->addOption( 'debug-output', 'Filename for sending debug output to',
65 public function execute() {
66 $this->dataDir
= $this->getOption( 'data-dir', '.' );
68 $allkeysPresent = file_exists( "{$this->dataDir}/allkeys.txt" );
69 $ucdallPresent = file_exists( "{$this->dataDir}/ucd.all.grouped.xml" );
71 if ( !$allkeysPresent ||
!$ucdallPresent ) {
72 $icuVersion = INTL_ICU_VERSION
;
73 $unicodeVersion = implode( '.', array_slice( IntlChar
::getUnicodeVersion(), 0, 3 ) );
77 if ( !$allkeysPresent ) {
78 $error .= "Unable to find allkeys.txt. "
79 . "Download it and specify its location with --data-dir=<DIR>. "
82 if ( !$ucdallPresent ) {
83 $error .= "Unable to find ucd.all.grouped.xml. "
84 . "Download it, unzip, and specify its location with --data-dir=<DIR>. "
88 $error .= "You are using ICU $icuVersion, intended for Unicode $unicodeVersion. "
89 . "Appropriate file(s) should be available at:\n";
91 $allkeysURL = "https://www.unicode.org/Public/UCA/$unicodeVersion/allkeys.txt";
92 $ucdallURL = "https://www.unicode.org/Public/$unicodeVersion/ucdxml/ucd.all.grouped.zip";
94 if ( !$allkeysPresent ) {
95 $error .= "* $allkeysURL\n";
97 if ( !$ucdallPresent ) {
98 $error .= "* $ucdallURL\n";
101 $this->fatalError( $error );
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" );
112 $this->generateFirstChars();
115 private function loadUcd() {
116 $uxr = new UcdXmlReader( "{$this->dataDir}/ucd.all.grouped.xml" );
117 $uxr->readChars( [ $this, 'charCallback' ] );
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'
130 $cp = hexdec( $data['cp'] );
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 ) ) {
138 // Skip the composed Hangul syllables, we will use the bare Jamo
140 if ( $data['block'] == 'Hangul Syllables' ) {
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'
156 $a = $base +
( $cp >> 15 );
157 $b = ( $cp & 0x7fff ) |
0x8000;
159 $this->weights
[$cp] = sprintf( ".%04X.%04X", $a, $b );
161 if ( $data['dm'] !== '#' ) {
162 $this->mappedChars
[$cp] = true;
165 if ( $cp %
4096 == 0 ) {
166 print "{$data['cp']}\n";
170 private function generateFirstChars() {
171 $file = fopen( "{$this->dataDir}/allkeys.txt", 'r' );
173 $this->fatalError( "Unable to open allkeys.txt" );
176 $goodTertiaryChars = [];
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 ) ) {
189 $cp = hexdec( $m[1] );
190 $allWeights = trim( $m[2] );
194 if ( !isset( $this->weights
[$cp] ) ) {
195 // Non-printable, ignore
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];
203 if ( $m[1][2] !== '0000' ) {
204 $tertiary .= '.' . $m[1][2];
208 $this->weights
[$cp] = $primary;
209 if ( $tertiary === '.0008'
210 ||
$tertiary === '.000E'
212 $goodTertiaryChars[$cp] = true;
217 // Identify groups of characters with the same primary weight
219 asort( $this->weights
, SORT_STRING
);
220 $prevWeight = reset( $this->weights
);
222 foreach ( $this->weights
as $cp => $weight ) {
223 if ( $weight !== $prevWeight ) {
224 $this->groups
[$prevWeight] = $group;
225 $prevWeight = $weight;
226 $group = $this->groups
[$weight] ??
[];
231 $this->groups
[$prevWeight] = $group;
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.
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] );
248 ksort( $this->groups
, SORT_STRING
);
250 // Identify the header character in each group
253 $tertiaryCollator = new Collator( 'root' );
254 $primaryCollator = new Collator( 'root' );
255 $primaryCollator->setStrength( Collator
::PRIMARY
);
257 foreach ( $this->groups
as $weight => $group ) {
258 $uncomposedChars = [];
260 foreach ( $group as $cp ) {
261 if ( isset( $goodTertiaryChars[$cp] ) ) {
264 if ( !isset( $this->mappedChars
[$cp] ) ) {
265 $uncomposedChars[] = $cp;
268 $x = array_intersect( $goodChars, $uncomposedChars );
270 $x = $uncomposedChars;
276 // Use ICU to pick the lowest sorting character in the selection
277 $tertiaryCollator->sort( $x );
280 $char = UtfNormal\Utils
::codepointToUtf8( $cp );
281 $headerChars[] = $char;
282 if ( $primaryCollator->compare( $char, $prevChar ) <= 0 ) {
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 ) ) ) );
293 print "Out of order: $numOutOfOrder / " . count( $headerChars ) . "\n";
296 $writer = new StaticArrayWriter();
298 "$IP/includes/collation/data/first-letters-root.php",
299 $writer->create( $headerChars, 'File created by generateCollationData.php' )
301 echo "first-letters-root: file written.\n";
312 /** @var XMLReader */
317 public $currentBlock;
319 public function __construct( $fileName ) {
320 $this->fileName
= $fileName;
323 public function readChars( $callback ) {
325 $this->currentBlock
= reset( $this->blocks
);
326 $xml = $this->open();
327 $this->callback
= $callback;
329 while ( $xml->name
!== 'repertoire' && $xml->next() );
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' ) {
338 } elseif ( $xml->nodeType
=== XMLReader
::END_ELEMENT
) {
339 if ( $xml->name
=== 'group' ) {
340 $this->groupAttrs
= [];
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}" );
352 while ( $this->xml
->name
!== 'ucd' && $this->xml
->read() );
359 * Read the attributes of the current element node and return them
363 protected function readAttributes() {
365 while ( $this->xml
->moveToNextAttribute() ) {
366 $attrs[$this->xml
->name
] = $this->xml
->value
;
372 protected function handleChar() {
373 $attrs = $this->readAttributes() +
$this->groupAttrs
;
374 if ( isset( $attrs['cp'] ) ) {
375 $first = $last = hexdec( $attrs['cp'] );
377 $first = hexdec( $attrs['first-cp'] );
378 $last = hexdec( $attrs['last-cp'] );
379 unset( $attrs['first-cp'] );
380 unset( $attrs['last-cp'] );
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] );
391 while ( $this->currentBlock
) {
392 if ( $cp < $this->currentBlock
[0] ) {
394 } elseif ( $cp <= $this->currentBlock
[1] ) {
395 $attrs['block'] = key( $this->blocks
);
398 $this->currentBlock
= next( $this->blocks
);
402 $attrs['cp'] = $hexCp;
403 call_user_func( $this->callback
, $attrs );
407 public function getBlocks() {
408 if ( $this->blocks
) {
409 return $this->blocks
;
412 $xml = $this->open();
413 while ( $xml->name
!== 'blocks' && $xml->read() );
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 ];
427 return $this->blocks
;
431 // @codeCoverageIgnoreStart
432 $maintClass = GenerateCollationData
::class;
433 require_once RUN_MAINTENANCE_IF_MAIN
;
434 // @codeCoverageIgnoreEnd