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 // @phan-suppress-next-line PhanParamSuspiciousOrder False positive
115 if ( !str_contains( 'LNPS', $category )
116 && $data['cp'] !== '0020'
117 ) {
118 return;
119 }
120 $cp = (int)hexdec( $data['cp'] );
121
122 // Skip the CJK ideograph blocks, as an optimisation measure.
123 // UCA doesn't sort them properly anyway, without tailoring.
124 if ( IcuCollation::isCjk( $cp ) ) {
125 return;
126 }
127
128 // Skip the composed Hangul syllables, we will use the bare Jamo
129 // as first letters
130 if ( $data['block'] == 'Hangul Syllables' ) {
131 return;
132 }
133
134 // Skip characters that mapped to a single character we skipped above.
135 // e.g. U+2329 -> U+3008 (from CJK Symbols and Punctuation)
136 if ( $data['dm'] !== '#' && !str_contains( $data['dm'], ' ' ) &&
137 !isset( $this->weights[ hexdec( $data['dm'] ) ] )
138 ) {
139 return;
140 }
141
142 // Calculate implicit weight per UTS #10 v6.0.0, sec 7.1.3
143 $a = 0xFBC0 + ( $cp >> 15 );
144 $b = ( $cp & 0x7fff ) | 0x8000;
145
146 $this->weights[$cp] = sprintf( ".%04X.%04X", $a, $b );
147
148 if ( $data['dm'] !== '#' ) {
149 $this->mappedChars[$cp] = true;
150 }
151
152 if ( $cp % 4096 == 0 ) {
153 print "{$data['cp']}\n";
154 }
155 }
156
157 private function generateFirstChars() {
158 $file = fopen( "{$this->dataDir}/allkeys.txt", 'r' );
159 if ( !$file ) {
160 $this->fatalError( "Unable to open allkeys.txt" );
161 }
162
163 $goodTertiaryChars = [];
164
165 // For each character with an entry in allkeys.txt, overwrite the implicit
166 // entry in $this->weights that came from the UCD.
167 // Also gather a list of tertiary weights, for use in selecting the group header
168 // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition
169 while ( ( $line = fgets( $file ) ) !== false ) {
170 // We're only interested in single-character weights, pick them out with a regex
171 $line = trim( $line );
172 if ( !preg_match( '/^([0-9A-F]+)\s*;\s*([^#]*)/', $line, $m ) ) {
173 continue;
174 }
175
176 $cp = (int)hexdec( $m[1] );
177 $allWeights = trim( $m[2] );
178 $primary = '';
179 $tertiary = '';
180
181 if ( !isset( $this->weights[$cp] ) ) {
182 // Non-printable, ignore
183 continue;
184 }
185 foreach ( StringUtils::explode( '[', $allWeights ) as $weightStr ) {
186 if ( preg_match_all( '/[*.]([0-9A-F]+)/', $weightStr, $m ) ) {
187 if ( $m[1][0] !== '0000' ) {
188 $primary .= '.' . $m[1][0];
189 }
190 if ( $m[1][2] !== '0000' ) {
191 $tertiary .= '.' . $m[1][2];
192 }
193 }
194 }
195 $this->weights[$cp] = $primary;
196 if ( $tertiary === '.0008'
197 || $tertiary === '.000E'
198 ) {
199 $goodTertiaryChars[$cp] = true;
200 }
201 }
202 fclose( $file );
203
204 // Identify groups of characters with the same primary weight
205 $this->groups = [];
206 asort( $this->weights, SORT_STRING );
207 $prevWeight = reset( $this->weights );
208 $group = [];
209 foreach ( $this->weights as $cp => $weight ) {
210 if ( $weight !== $prevWeight ) {
211 $this->groups[$prevWeight] = $group;
212 $prevWeight = $weight;
213 $group = $this->groups[$weight] ?? [];
214 }
215 $group[] = $cp;
216 }
217 if ( $group ) {
218 $this->groups[$prevWeight] = $group;
219 }
220
221 // If one character has a given primary weight sequence, and a second
222 // character has a longer primary weight sequence with an initial
223 // portion equal to the first character, then remove the second
224 // character. This avoids having characters like U+A732 (double A)
225 // polluting the basic Latin sort area.
226
227 foreach ( $this->groups as $weight => $group ) {
228 if ( preg_match( '/(\.[0-9A-F]*)\./', $weight, $m ) ) {
229 if ( isset( $this->groups[$m[1]] ) ) {
230 unset( $this->groups[$weight] );
231 }
232 }
233 }
234
235 ksort( $this->groups, SORT_STRING );
236
237 // Identify the header character in each group
238 $headerChars = [];
239 $prevChar = "\000";
240 $tertiaryCollator = new Collator( 'root' );
241 $primaryCollator = new Collator( 'root' );
242 $primaryCollator->setStrength( Collator::PRIMARY );
243 $numOutOfOrder = 0;
244 foreach ( $this->groups as $weight => $group ) {
245 $uncomposedChars = [];
246 $goodChars = [];
247 foreach ( $group as $cp ) {
248 if ( isset( $goodTertiaryChars[$cp] ) ) {
249 $goodChars[] = $cp;
250 }
251 if ( !isset( $this->mappedChars[$cp] ) ) {
252 $uncomposedChars[] = $cp;
253 }
254 }
255 $x = array_intersect( $goodChars, $uncomposedChars );
256 if ( !$x ) {
257 $x = $uncomposedChars;
258 if ( !$x ) {
259 $x = $group;
260 }
261 }
262
263 // Use ICU to pick the lowest sorting character in the selection
264 $tertiaryCollator->sort( $x );
265 $cp = $x[0];
266
267 $char = UtfNormal\Utils::codepointToUtf8( $cp );
268 $headerChars[] = $char;
269 if ( $primaryCollator->compare( $char, $prevChar ) <= 0 ) {
270 $numOutOfOrder++;
271 }
272 $prevChar = $char;
273
274 if ( $this->debugOutFile ) {
275 fwrite( $this->debugOutFile, sprintf( "%05X %s %s (%s)\n", $cp, $weight, $char,
276 implode( ' ', array_map( [ UtfNormal\Utils::class, 'codepointToUtf8' ], $group ) ) ) );
277 }
278 }
279
280 print "Out of order: $numOutOfOrder / " . count( $headerChars ) . "\n";
281
282 $writer = new StaticArrayWriter();
283 file_put_contents(
284 MW_INSTALL_PATH . '/languages/data/first-letters-root.php',
285 $writer->create(
286 $headerChars,
287 "File created by maintenance/language/generateCollationData.php\n"
288 . "@codeCoverageIgnore"
289 )
290 );
291 echo "first-letters-root: file written.\n";
292 }
293}
294
297 public $fileName;
299 public $callback;
303 public $xml;
305 public $blocks = [];
308
309 public function __construct( string $fileName ) {
310 $this->fileName = $fileName;
311 }
312
313 public function readChars( callable $callback ) {
314 $this->getBlocks();
315 $this->currentBlock = reset( $this->blocks );
316 $xml = $this->open();
317 $this->callback = $callback;
318
319 while ( $xml->name !== 'repertoire' && $xml->next() );
320
321 while ( $xml->read() ) {
322 if ( $xml->nodeType == XMLReader::ELEMENT ) {
323 if ( $xml->name === 'group' ) {
324 $this->groupAttrs = $this->readAttributes();
325 } elseif ( $xml->name === 'char' ) {
326 $this->handleChar();
327 }
328 } elseif ( $xml->nodeType === XMLReader::END_ELEMENT ) {
329 if ( $xml->name === 'group' ) {
330 $this->groupAttrs = [];
331 }
332 }
333 }
334 $xml->close();
335 }
336
337 protected function open(): XMLReader {
338 $this->xml = new XMLReader;
339 if ( !$this->xml->open( $this->fileName ) ) {
340 throw new RuntimeException( __METHOD__ . ": unable to open {$this->fileName}" );
341 }
342 while ( $this->xml->name !== 'ucd' && $this->xml->read() );
343 $this->xml->read();
344
345 return $this->xml;
346 }
347
353 protected function readAttributes() {
354 $attrs = [];
355 while ( $this->xml->moveToNextAttribute() ) {
356 $attrs[$this->xml->name] = $this->xml->value;
357 }
358
359 return $attrs;
360 }
361
362 protected function handleChar() {
363 $attrs = $this->readAttributes() + $this->groupAttrs;
364 if ( isset( $attrs['cp'] ) ) {
365 $first = $last = hexdec( $attrs['cp'] );
366 } else {
367 $first = hexdec( $attrs['first-cp'] );
368 $last = hexdec( $attrs['last-cp'] );
369 unset( $attrs['first-cp'] );
370 unset( $attrs['last-cp'] );
371 }
372
373 for ( $cp = $first; $cp <= $last; $cp++ ) {
374 $hexCp = sprintf( "%04X", $cp );
375 foreach ( [ 'na', 'na1' ] as $nameProp ) {
376 if ( isset( $attrs[$nameProp] ) ) {
377 $attrs[$nameProp] = str_replace( '#', $hexCp, $attrs[$nameProp] );
378 }
379 }
380
381 while ( $this->currentBlock ) {
382 if ( $cp < $this->currentBlock[0] ) {
383 break;
384 } elseif ( $cp <= $this->currentBlock[1] ) {
385 $attrs['block'] = key( $this->blocks );
386 break;
387 } else {
388 $this->currentBlock = next( $this->blocks );
389 }
390 }
391
392 $attrs['cp'] = $hexCp;
393 ( $this->callback )( $attrs );
394 }
395 }
396
397 public function getBlocks(): array {
398 if ( $this->blocks ) {
399 return $this->blocks;
400 }
401
402 $xml = $this->open();
403 while ( $xml->name !== 'blocks' && $xml->read() );
404
405 while ( $xml->read() ) {
406 if ( $xml->nodeType == XMLReader::ELEMENT ) {
407 if ( $xml->name === 'block' ) {
408 $attrs = $this->readAttributes();
409 $first = hexdec( $attrs['first-cp'] );
410 $last = hexdec( $attrs['last-cp'] );
411 $this->blocks[$attrs['name']] = [ $first, $last ];
412 }
413 }
414 }
415 $xml->close();
416
417 return $this->blocks;
418 }
419}
420
421// @codeCoverageIgnoreStart
422$maintClass = GenerateCollationData::class;
423require_once RUN_MAINTENANCE_IF_MAIN;
424// @codeCoverageIgnoreEnd
if(!defined('MW_SETUP_CALLBACK'))
Definition WebStart.php:71
Generate first letter data files for Collation.php.
__construct()
Default constructor.
execute()
Do the actual work.
array< int, bool > $mappedChars
A hashtable keyed by codepoint, where presence indicates that a character has a decomposition mapping...
array< int, string > $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.