MediaWiki master
generateCollationData.php
Go to the documentation of this file.
1<?php
10// @codeCoverageIgnoreStart
11require_once __DIR__ . '/../Maintenance.php';
12// @codeCoverageIgnoreEnd
13
18
26 public $dataDir;
27
29 public $weights;
30
38
41
43 private $groups;
44
45 public function __construct() {
46 parent::__construct();
47 $this->addOption( 'data-dir', 'A directory on the local filesystem ' .
48 'containing allkeys.txt and ucd.all.grouped.xml from unicode.org',
49 false, true );
50 $this->addOption( 'debug-output', 'Filename for sending debug output to',
51 false, true );
52 }
53
54 public function execute() {
55 $this->dataDir = $this->getOption( 'data-dir', '.' );
56
57 $allkeysPresent = file_exists( "{$this->dataDir}/allkeys.txt" );
58 $ucdallPresent = file_exists( "{$this->dataDir}/ucd.all.grouped.xml" );
59
60 if ( !$allkeysPresent || !$ucdallPresent ) {
61 $icuVersion = INTL_ICU_VERSION;
62 $unicodeVersion = implode( '.', array_slice( IntlChar::getUnicodeVersion(), 0, 3 ) );
63
64 $error = "";
65
66 if ( !$allkeysPresent ) {
67 $error .= "Unable to find allkeys.txt. "
68 . "Download it and specify its location with --data-dir=<DIR>. "
69 . "\n\n";
70 }
71 if ( !$ucdallPresent ) {
72 $error .= "Unable to find ucd.all.grouped.xml. "
73 . "Download it, unzip, and specify its location with --data-dir=<DIR>. "
74 . "\n\n";
75 }
76
77 $error .= "You are using ICU $icuVersion, intended for Unicode $unicodeVersion. "
78 . "Appropriate file(s) should be available at:\n";
79
80 $allkeysURL = "https://www.unicode.org/Public/UCA/$unicodeVersion/allkeys.txt";
81 $ucdallURL = "https://www.unicode.org/Public/$unicodeVersion/ucdxml/ucd.all.grouped.zip";
82
83 if ( !$allkeysPresent ) {
84 $error .= "* $allkeysURL\n";
85 }
86 if ( !$ucdallPresent ) {
87 $error .= "* $ucdallURL\n";
88 }
89
90 $this->fatalError( $error );
91 }
92
93 $debugOutFileName = $this->getOption( 'debug-output' );
94 if ( $debugOutFileName ) {
95 $this->debugOutFile = fopen( $debugOutFileName, 'w' );
96 if ( !$this->debugOutFile ) {
97 $this->fatalError( "Unable to open debug output file for writing" );
98 }
99 }
100 $this->loadUcd();
101 $this->generateFirstChars();
102 }
103
104 private function loadUcd() {
105 $uxr = new UcdXmlReader( "{$this->dataDir}/ucd.all.grouped.xml" );
106 $uxr->readChars( $this->charCallback( ... ) );
107 }
108
109 private function charCallback( array $data ) {
110 // Skip non-printable characters,
111 // but do not skip a normal space (U+0020) since
112 // people like to use that as a fake no header symbol.
113 $category = substr( $data['gc'], 0, 1 );
114 if ( !str_contains( 'LNPS', $category )
115 && $data['cp'] !== '0020'
116 ) {
117 return;
118 }
119 $cp = hexdec( $data['cp'] );
120
121 // Skip the CJK ideograph blocks, as an optimisation measure.
122 // UCA doesn't sort them properly anyway, without tailoring.
123 if ( IcuCollation::isCjk( $cp ) ) {
124 return;
125 }
126
127 // Skip the composed Hangul syllables, we will use the bare Jamo
128 // as first letters
129 if ( $data['block'] == 'Hangul Syllables' ) {
130 return;
131 }
132
133 // Skip characters that mapped to a single character we skipped above.
134 // e.g. U+2329 -> U+3008 (from CJK Symbols and Punctuation)
135 if ( $data['dm'] !== '#' && !str_contains( $data['dm'], ' ' ) &&
136 !isset( $this->weights[ hexdec( $data['dm'] ) ] )
137 ) {
138 return;
139 }
140
141 // Calculate implicit weight per UTS #10 v6.0.0, sec 7.1.3
142 $a = 0xFBC0 + ( $cp >> 15 );
143 $b = ( $cp & 0x7fff ) | 0x8000;
144
145 $this->weights[$cp] = sprintf( ".%04X.%04X", $a, $b );
146
147 if ( $data['dm'] !== '#' ) {
148 $this->mappedChars[$cp] = true;
149 }
150
151 if ( $cp % 4096 == 0 ) {
152 print "{$data['cp']}\n";
153 }
154 }
155
156 private function generateFirstChars() {
157 $file = fopen( "{$this->dataDir}/allkeys.txt", 'r' );
158 if ( !$file ) {
159 $this->fatalError( "Unable to open allkeys.txt" );
160 }
161
162 $goodTertiaryChars = [];
163
164 // For each character with an entry in allkeys.txt, overwrite the implicit
165 // entry in $this->weights that came from the UCD.
166 // Also gather a list of tertiary weights, for use in selecting the group header
167 // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition
168 while ( ( $line = fgets( $file ) ) !== false ) {
169 // We're only interested in single-character weights, pick them out with a regex
170 $line = trim( $line );
171 if ( !preg_match( '/^([0-9A-F]+)\s*;\s*([^#]*)/', $line, $m ) ) {
172 continue;
173 }
174
175 $cp = hexdec( $m[1] );
176 $allWeights = trim( $m[2] );
177 $primary = '';
178 $tertiary = '';
179
180 if ( !isset( $this->weights[$cp] ) ) {
181 // Non-printable, ignore
182 continue;
183 }
184 foreach ( StringUtils::explode( '[', $allWeights ) as $weightStr ) {
185 if ( preg_match_all( '/[*.]([0-9A-F]+)/', $weightStr, $m ) ) {
186 if ( $m[1][0] !== '0000' ) {
187 $primary .= '.' . $m[1][0];
188 }
189 if ( $m[1][2] !== '0000' ) {
190 $tertiary .= '.' . $m[1][2];
191 }
192 }
193 }
194 $this->weights[$cp] = $primary;
195 if ( $tertiary === '.0008'
196 || $tertiary === '.000E'
197 ) {
198 $goodTertiaryChars[$cp] = true;
199 }
200 }
201 fclose( $file );
202
203 // Identify groups of characters with the same primary weight
204 $this->groups = [];
205 asort( $this->weights, SORT_STRING );
206 $prevWeight = reset( $this->weights );
207 $group = [];
208 foreach ( $this->weights as $cp => $weight ) {
209 if ( $weight !== $prevWeight ) {
210 $this->groups[$prevWeight] = $group;
211 $prevWeight = $weight;
212 $group = $this->groups[$weight] ?? [];
213 }
214 $group[] = $cp;
215 }
216 if ( $group ) {
217 $this->groups[$prevWeight] = $group;
218 }
219
220 // If one character has a given primary weight sequence, and a second
221 // character has a longer primary weight sequence with an initial
222 // portion equal to the first character, then remove the second
223 // character. This avoids having characters like U+A732 (double A)
224 // polluting the basic Latin sort area.
225
226 foreach ( $this->groups as $weight => $group ) {
227 if ( preg_match( '/(\.[0-9A-F]*)\./', $weight, $m ) ) {
228 if ( isset( $this->groups[$m[1]] ) ) {
229 unset( $this->groups[$weight] );
230 }
231 }
232 }
233
234 ksort( $this->groups, SORT_STRING );
235
236 // Identify the header character in each group
237 $headerChars = [];
238 $prevChar = "\000";
239 $tertiaryCollator = new Collator( 'root' );
240 $primaryCollator = new Collator( 'root' );
241 $primaryCollator->setStrength( Collator::PRIMARY );
242 $numOutOfOrder = 0;
243 foreach ( $this->groups as $weight => $group ) {
244 $uncomposedChars = [];
245 $goodChars = [];
246 foreach ( $group as $cp ) {
247 if ( isset( $goodTertiaryChars[$cp] ) ) {
248 $goodChars[] = $cp;
249 }
250 if ( !isset( $this->mappedChars[$cp] ) ) {
251 $uncomposedChars[] = $cp;
252 }
253 }
254 $x = array_intersect( $goodChars, $uncomposedChars );
255 if ( !$x ) {
256 $x = $uncomposedChars;
257 if ( !$x ) {
258 $x = $group;
259 }
260 }
261
262 // Use ICU to pick the lowest sorting character in the selection
263 $tertiaryCollator->sort( $x );
264 $cp = $x[0];
265
266 $char = UtfNormal\Utils::codepointToUtf8( $cp );
267 $headerChars[] = $char;
268 if ( $primaryCollator->compare( $char, $prevChar ) <= 0 ) {
269 $numOutOfOrder++;
270 }
271 $prevChar = $char;
272
273 if ( $this->debugOutFile ) {
274 fwrite( $this->debugOutFile, sprintf( "%05X %s %s (%s)\n", $cp, $weight, $char,
275 implode( ' ', array_map( [ UtfNormal\Utils::class, 'codepointToUtf8' ], $group ) ) ) );
276 }
277 }
278
279 print "Out of order: $numOutOfOrder / " . count( $headerChars ) . "\n";
280
281 $writer = new StaticArrayWriter();
282 file_put_contents(
283 MW_INSTALL_PATH . '/languages/data/first-letters-root.php',
284 $writer->create(
285 $headerChars,
286 "File created by maintenance/language/generateCollationData.php\n"
287 . "@codeCoverageIgnore"
288 )
289 );
290 echo "first-letters-root: file written.\n";
291 }
292}
293
296 public $fileName;
298 public $callback;
302 public $xml;
304 public $blocks = [];
307
308 public function __construct( string $fileName ) {
309 $this->fileName = $fileName;
310 }
311
312 public function readChars( callable $callback ) {
313 $this->getBlocks();
314 $this->currentBlock = reset( $this->blocks );
315 $xml = $this->open();
316 $this->callback = $callback;
317
318 while ( $xml->name !== 'repertoire' && $xml->next() );
319
320 while ( $xml->read() ) {
321 if ( $xml->nodeType == XMLReader::ELEMENT ) {
322 if ( $xml->name === 'group' ) {
323 $this->groupAttrs = $this->readAttributes();
324 } elseif ( $xml->name === 'char' ) {
325 $this->handleChar();
326 }
327 } elseif ( $xml->nodeType === XMLReader::END_ELEMENT ) {
328 if ( $xml->name === 'group' ) {
329 $this->groupAttrs = [];
330 }
331 }
332 }
333 $xml->close();
334 }
335
336 protected function open(): XMLReader {
337 $this->xml = new XMLReader;
338 if ( !$this->xml->open( $this->fileName ) ) {
339 throw new RuntimeException( __METHOD__ . ": unable to open {$this->fileName}" );
340 }
341 while ( $this->xml->name !== 'ucd' && $this->xml->read() );
342 $this->xml->read();
343
344 return $this->xml;
345 }
346
352 protected function readAttributes() {
353 $attrs = [];
354 while ( $this->xml->moveToNextAttribute() ) {
355 $attrs[$this->xml->name] = $this->xml->value;
356 }
357
358 return $attrs;
359 }
360
361 protected function handleChar() {
362 $attrs = $this->readAttributes() + $this->groupAttrs;
363 if ( isset( $attrs['cp'] ) ) {
364 $first = $last = hexdec( $attrs['cp'] );
365 } else {
366 $first = hexdec( $attrs['first-cp'] );
367 $last = hexdec( $attrs['last-cp'] );
368 unset( $attrs['first-cp'] );
369 unset( $attrs['last-cp'] );
370 }
371
372 for ( $cp = $first; $cp <= $last; $cp++ ) {
373 $hexCp = sprintf( "%04X", $cp );
374 foreach ( [ 'na', 'na1' ] as $nameProp ) {
375 if ( isset( $attrs[$nameProp] ) ) {
376 $attrs[$nameProp] = str_replace( '#', $hexCp, $attrs[$nameProp] );
377 }
378 }
379
380 while ( $this->currentBlock ) {
381 if ( $cp < $this->currentBlock[0] ) {
382 break;
383 } elseif ( $cp <= $this->currentBlock[1] ) {
384 $attrs['block'] = key( $this->blocks );
385 break;
386 } else {
387 $this->currentBlock = next( $this->blocks );
388 }
389 }
390
391 $attrs['cp'] = $hexCp;
392 ( $this->callback )( $attrs );
393 }
394 }
395
396 public function getBlocks(): array {
397 if ( $this->blocks ) {
398 return $this->blocks;
399 }
400
401 $xml = $this->open();
402 while ( $xml->name !== 'blocks' && $xml->read() );
403
404 while ( $xml->read() ) {
405 if ( $xml->nodeType == XMLReader::ELEMENT ) {
406 if ( $xml->name === 'block' ) {
407 $attrs = $this->readAttributes();
408 $first = hexdec( $attrs['first-cp'] );
409 $last = hexdec( $attrs['last-cp'] );
410 $this->blocks[$attrs['name']] = [ $first, $last ];
411 }
412 }
413 }
414 $xml->close();
415
416 return $this->blocks;
417 }
418}
419
420// @codeCoverageIgnoreStart
421$maintClass = GenerateCollationData::class;
422require_once RUN_MAINTENANCE_IF_MAIN;
423// @codeCoverageIgnoreEnd
if(!defined('MW_SETUP_CALLBACK'))
Definition WebStart.php:69
Generate first letter data files for Collation.php.
__construct()
Default constructor.
string[] $mappedChars
A hashtable keyed by codepoint, where presence indicates that a character has a decomposition mapping...
execute()
Do the actual work.
int $weights
The primary weights, indexed by codepoint.
string $dataDir
The directory with source data files in it.
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
getOption( $name, $default=null)
Get an option, or return the default.
__construct(string $fileName)
readChars(callable $callback)
readAttributes()
Read the attributes of the current element node and return them as an array.
Format a static PHP array to be written to a file.
A collection of static methods to play with strings.