Localisation updates from https://translatewiki.net.
[mediawiki.git] / includes / parser / Preprocessor_Hash.php
blobefad965144547318042cc283899b8e2f2b35313e
1 <?php
2 /**
3 * Preprocessor using PHP arrays
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
20 * @file
21 * @ingroup Parser
24 namespace MediaWiki\Parser;
26 use Wikimedia\ObjectCache\WANObjectCache;
28 /**
29 * Differences from DOM schema:
30 * * attribute nodes are children
31 * * "<h>" nodes that aren't at the top are replaced with <possible-h>
33 * Nodes are stored in a recursive array data structure. A node store is an
34 * array where each element may be either a scalar (representing a text node)
35 * or a "descriptor", which is a two-element array where the first element is
36 * the node name and the second element is the node store for the children.
38 * Attributes are represented as children that have a node name starting with
39 * "@", and a single text node child.
41 * @todo: Consider replacing descriptor arrays with objects of a new class.
42 * Benchmark and measure resulting memory impact.
44 * @ingroup Parser
46 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
47 class Preprocessor_Hash extends Preprocessor {
48 /** Cache format version */
49 protected const CACHE_VERSION = 4;
51 /** @var int|false Min wikitext size for which to cache DOM tree */
52 protected $cacheThreshold;
54 /**
55 * @see Preprocessor::__construct()
56 * @param Parser $parser
57 * @param WANObjectCache|null $wanCache
58 * @param array $options Additional options include:
59 * - cacheThreshold: min text size for which to cache DOMs. [Default: false]
61 public function __construct(
62 Parser $parser,
63 ?WANObjectCache $wanCache = null,
64 array $options = []
65 ) {
66 parent::__construct( $parser, $wanCache, $options );
68 $this->cacheThreshold = $options['cacheThreshold'] ?? false;
71 /**
72 * @return PPFrame_Hash
74 public function newFrame() {
75 return new PPFrame_Hash( $this );
78 /**
79 * @param array $args
80 * @return PPCustomFrame_Hash
82 public function newCustomFrame( $args ) {
83 return new PPCustomFrame_Hash( $this, $args );
86 /**
87 * @param array $values
88 * @return PPNode_Hash_Array
90 public function newPartNodeArray( $values ) {
91 $list = [];
93 foreach ( $values as $k => $val ) {
94 if ( is_int( $k ) ) {
95 $store = [ [ 'part', [
96 [ 'name', [ [ '@index', [ $k ] ] ] ],
97 [ 'value', [ strval( $val ) ] ],
98 ] ] ];
99 } else {
100 $store = [ [ 'part', [
101 [ 'name', [ strval( $k ) ] ],
102 '=',
103 [ 'value', [ strval( $val ) ] ],
104 ] ] ];
107 $list[] = new PPNode_Hash_Tree( $store, 0 );
110 return new PPNode_Hash_Array( $list );
113 public function preprocessToObj( $text, $flags = 0 ) {
114 if ( $this->disableLangConversion ) {
115 // Language conversions are globally disabled; implicitly set flag
116 $flags |= self::DOM_LANG_CONVERSION_DISABLED;
119 $domTreeArray = null;
120 if (
121 $this->cacheThreshold !== false &&
122 strlen( $text ) >= $this->cacheThreshold &&
123 ( $flags & self::DOM_UNCACHED ) != self::DOM_UNCACHED
125 $domTreeJson = $this->wanCache->getWithSetCallback(
126 $this->wanCache->makeKey( 'preprocess-hash', sha1( $text ), $flags ),
127 $this->wanCache::TTL_DAY,
128 function () use ( $text, $flags, &$domTreeArray ) {
129 $domTreeArray = $this->buildDomTreeArrayFromText( $text, $flags );
131 return json_encode(
132 $domTreeArray,
133 JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
136 [ 'version' => self::CACHE_VERSION, 'segmentable' => true ]
138 $domTreeArray ??= json_decode( $domTreeJson );
141 $domTreeArray ??= $this->buildDomTreeArrayFromText( $text, $flags );
143 return new PPNode_Hash_Tree( $domTreeArray, 0 );
147 * @param string $text Wikitext
148 * @param int $flags Bit field of Preprocessor::DOM_* flags
149 * @return array JSON-serializable document object model array
151 private function buildDomTreeArrayFromText( $text, $flags ) {
152 $forInclusion = ( $flags & self::DOM_FOR_INCLUSION );
153 $langConversionDisabled = ( $flags & self::DOM_LANG_CONVERSION_DISABLED );
155 $xmlishElements = $this->parser->getStripList();
156 $xmlishAllowMissingEndTag = [ 'includeonly', 'noinclude', 'onlyinclude' ];
157 $enableOnlyinclude = false;
158 if ( $forInclusion ) {
159 $ignoredTags = [ 'includeonly', '/includeonly' ];
160 $ignoredElements = [ 'noinclude' ];
161 $xmlishElements[] = 'noinclude';
162 if ( str_contains( $text, '<onlyinclude>' )
163 && str_contains( $text, '</onlyinclude>' )
165 $enableOnlyinclude = true;
167 } else {
168 $ignoredTags = [ 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' ];
169 $ignoredElements = [ 'includeonly' ];
170 $xmlishElements[] = 'includeonly';
172 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
174 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
175 $elementsRegex = "~(?:$xmlishRegex)(?=\s|\/>|>)|!--~iA";
177 $stack = new PPDStack_Hash;
179 $searchBase = "[{<\n";
180 if ( !$langConversionDisabled ) {
181 $searchBase .= '-';
184 // For fast reverse searches
185 $revText = strrev( $text );
186 $lengthText = strlen( $text );
188 // Input pointer, starts out pointing to a pseudo-newline before the start
189 $i = 0;
190 // Current accumulator. See the doc comment for Preprocessor_Hash for the format.
191 $accum =& $stack->getAccum();
192 // True to find equals signs in arguments
193 $findEquals = false;
194 // True to take notice of pipe characters
195 $findPipe = false;
196 $headingIndex = 1;
197 // True if $i is inside a possible heading
198 $inHeading = false;
199 // True if there are no more greater-than (>) signs right of $i
200 $noMoreGT = false;
201 // Map of tag name => true if there are no more closing tags of given type right of $i
202 $noMoreClosingTag = [];
203 // True to ignore all input up to the next <onlyinclude>
204 $findOnlyinclude = $enableOnlyinclude;
205 // Do a line-start run without outputting an LF character
206 $fakeLineStart = true;
208 while ( true ) {
209 if ( $findOnlyinclude ) {
210 // Ignore all input up to the next <onlyinclude>
211 $startPos = strpos( $text, '<onlyinclude>', $i );
212 if ( $startPos === false ) {
213 // Ignored section runs to the end
214 $accum[] = [ 'ignore', [ substr( $text, $i ) ] ];
215 break;
217 $tagEndPos = $startPos + 13; // past-the-end of <onlyinclude>
218 $accum[] = [ 'ignore', [ substr( $text, $i, $tagEndPos - $i ) ] ];
219 $i = $tagEndPos;
220 $findOnlyinclude = false;
223 if ( $fakeLineStart ) {
224 $found = 'line-start';
225 $curChar = '';
226 } else {
227 # Find next opening brace, closing brace or pipe
228 $search = $searchBase;
229 if ( $stack->top === false ) {
230 $currentClosing = '';
231 } else {
232 $currentClosing = $stack->top->close;
233 $search .= $currentClosing;
235 if ( $findPipe ) {
236 $search .= '|';
238 if ( $findEquals ) {
239 // First equals will be for the template
240 $search .= '=';
242 $rule = null;
243 # Output literal section, advance input counter
244 $literalLength = strcspn( $text, $search, $i );
245 if ( $literalLength > 0 ) {
246 self::addLiteral( $accum, substr( $text, $i, $literalLength ) );
247 $i += $literalLength;
249 if ( $i >= $lengthText ) {
250 if ( $currentClosing === "\n" ) {
251 // Do a past-the-end run to finish off the heading
252 $curChar = '';
253 $found = 'line-end';
254 } else {
255 # All done
256 break;
258 } else {
259 $curChar = $curTwoChar = $text[$i];
260 if ( $i + 1 < $lengthText ) {
261 $curTwoChar .= $text[$i + 1];
263 if ( $curChar === '|' ) {
264 $found = 'pipe';
265 } elseif ( $curChar === '=' ) {
266 $found = 'equals';
267 } elseif ( $curChar === '<' ) {
268 $found = 'angle';
269 } elseif ( $curChar === "\n" ) {
270 if ( $inHeading ) {
271 $found = 'line-end';
272 } else {
273 $found = 'line-start';
275 } elseif ( $curTwoChar === $currentClosing ) {
276 $found = 'close';
277 $curChar = $curTwoChar;
278 } elseif ( $curChar === $currentClosing ) {
279 $found = 'close';
280 } elseif ( isset( $this->rules[$curTwoChar] ) ) {
281 $curChar = $curTwoChar;
282 $found = 'open';
283 $rule = $this->rules[$curChar];
284 } elseif ( isset( $this->rules[$curChar] ) ) {
285 $found = 'open';
286 $rule = $this->rules[$curChar];
287 } else {
288 # Some versions of PHP have a strcspn which stops on
289 # null characters; ignore these and continue.
290 # We also may get '-' and '}' characters here which
291 # don't match -{ or $currentClosing. Add these to
292 # output and continue.
293 if ( $curChar === '-' || $curChar === '}' ) {
294 self::addLiteral( $accum, $curChar );
296 ++$i;
297 continue;
302 if ( $found === 'angle' ) {
303 // Handle </onlyinclude>
304 if ( $enableOnlyinclude
305 && substr_compare( $text, '</onlyinclude>', $i, 14 ) === 0
307 $findOnlyinclude = true;
308 continue;
311 // Determine element name
312 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i + 1 ) ) {
313 // Element name missing or not listed
314 self::addLiteral( $accum, '<' );
315 ++$i;
316 continue;
318 $name = $matches[0];
319 // Handle comments
320 if ( $name === '!--' ) {
321 // To avoid leaving blank lines, when a sequence of
322 // space-separated comments is both preceded and followed by
323 // a newline (ignoring spaces), then
324 // trim leading and trailing spaces and the trailing newline.
326 // Find the end
327 $endPos = strpos( $text, '-->', $i + 4 );
328 if ( $endPos === false ) {
329 // Unclosed comment in input, runs to end
330 $inner = substr( $text, $i );
331 $accum[] = [ 'comment', [ $inner ] ];
332 $i = $lengthText;
333 } else {
334 // Search backwards for leading whitespace
335 // $wsStart is the first char of the comment (first of the leading space or '<')
336 $wsStart = $i ? ( $i - strspn( $revText, " \t", $lengthText - $i ) ) : 0;
338 // $wsEnd will be the char *after* the comment (after last space or the '>' if there's no space)
339 $wsEnd = $endPos + 3; // add length of -->
340 // Search forwards for trailing whitespace
341 $wsEnd += strspn( $text, " \t", $wsEnd );
343 // Keep looking forward as long as we're finding more comments on the line
344 $comments = [ [ $wsStart, $wsEnd ] ];
345 while ( substr_compare( $text, '<!--', $wsEnd, 4 ) === 0 ) {
346 $c = strpos( $text, '-->', $wsEnd + 4 );
347 if ( $c === false ) {
348 break;
350 $c += 3; // add length of -->
351 // Search forwards for trailing whitespace
352 $c += strspn( $text, " \t", $c );
353 $comments[] = [ $wsEnd, $c ];
354 $wsEnd = $c;
357 // Eat the line if possible
358 // TODO: This could theoretically be done if $wsStart === 0, i.e. for comments at
359 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
360 // it's a possible beneficial b/c break.
361 if ( $wsStart > 0 && substr_compare( $text, "\n", $wsStart - 1, 1 ) === 0
362 && substr_compare( $text, "\n", $wsEnd, 1 ) === 0
364 // Remove leading whitespace from the end of the accumulator
365 $wsLength = $i - $wsStart;
366 $endIndex = count( $accum ) - 1;
368 if ( $wsLength > 0
369 && $endIndex >= 0
370 && is_string( $accum[$endIndex] )
371 && strspn( $accum[$endIndex], " \t", -$wsLength ) === $wsLength
373 $accum[$endIndex] = substr( $accum[$endIndex], 0, -$wsLength );
376 // Dump all but the last comment to the accumulator
377 // $endPos includes the newline from the if above, want also eat that
378 [ $startPos, $endPos ] = array_pop( $comments );
379 foreach ( $comments as [ $cStartPos, $cEndPos ] ) {
380 // $cEndPos is the next char, no +1 needed to get correct length between start/end
381 $inner = substr( $text, $cStartPos, $cEndPos - $cStartPos );
382 $accum[] = [ 'comment', [ $inner ] ];
385 // Do a line-start run next time to look for headings after the comment
386 $fakeLineStart = true;
387 } else {
388 // No line to eat, just take the comment itself
389 $startPos = $i;
390 $endPos += 2;
393 if ( $stack->top ) {
394 $part = $stack->top->getCurrentPart();
395 if ( $part->commentEnd !== $wsStart - 1 ) {
396 $part->visualEnd = $wsStart;
398 // Else comments abutting, no change in visual end
399 $part->commentEnd = $endPos;
401 $i = $endPos + 1;
402 $inner = substr( $text, $startPos, $endPos - $startPos + 1 );
403 $accum[] = [ 'comment', [ $inner ] ];
405 continue;
407 $attrStart = $i + strlen( $name ) + 1;
409 // Find end of tag
410 $tagEndPos = $noMoreGT ? false : strpos( $text, '>', $attrStart );
411 if ( $tagEndPos === false ) {
412 // Infinite backtrack
413 // Disable tag search to prevent worst-case O(N^2) performance
414 $noMoreGT = true;
415 self::addLiteral( $accum, '<' );
416 ++$i;
417 continue;
420 $lowerName = strtolower( $name );
421 // Handle ignored tags
422 if ( in_array( $lowerName, $ignoredTags ) ) {
423 $accum[] = [ 'ignore', [ substr( $text, $i, $tagEndPos - $i + 1 ) ] ];
424 $i = $tagEndPos + 1;
425 continue;
428 $tagStartPos = $i;
429 if ( $text[$tagEndPos - 1] === '/' ) {
430 // Short end tag
431 $attrEnd = $tagEndPos - 1;
432 $inner = null;
433 $i = $tagEndPos + 1;
434 $close = null;
435 } else {
436 $attrEnd = $tagEndPos;
437 // Find closing tag
438 if (
439 !isset( $noMoreClosingTag[$lowerName] ) &&
440 preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
441 $text, $matches, PREG_OFFSET_CAPTURE, $tagEndPos + 1 )
443 [ $close, $closeTagStartPos ] = $matches[0];
444 $inner = substr( $text, $tagEndPos + 1, $closeTagStartPos - $tagEndPos - 1 );
445 $i = $closeTagStartPos + strlen( $close );
446 } else {
447 // No end tag
448 if ( in_array( $name, $xmlishAllowMissingEndTag ) ) {
449 // Let it run out to the end of the text.
450 $inner = substr( $text, $tagEndPos + 1 );
451 $i = $lengthText;
452 $close = null;
453 } else {
454 // Don't match the tag, treat opening tag as literal and resume parsing.
455 $i = $tagEndPos + 1;
456 self::addLiteral( $accum, substr( $text, $tagStartPos, $tagEndPos + 1 - $tagStartPos ) );
457 // Cache results, otherwise we have O(N^2) performance for input like <foo><foo><foo>...
458 $noMoreClosingTag[$lowerName] = true;
459 continue;
463 // <includeonly> and <noinclude> just become <ignore> tags
464 if ( in_array( $lowerName, $ignoredElements ) ) {
465 $accum[] = [ 'ignore', [ substr( $text, $tagStartPos, $i - $tagStartPos ) ] ];
466 continue;
469 if ( $attrEnd <= $attrStart ) {
470 $attr = '';
471 } else {
472 // Note that the attr element contains the whitespace between name and attribute,
473 // this is necessary for precise reconstruction during pre-save transform.
474 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
477 $children = [
478 [ 'name', [ $name ] ],
479 [ 'attr', [ $attr ] ],
481 if ( $inner !== null ) {
482 $children[] = [ 'inner', [ $inner ] ];
484 if ( $close !== null ) {
485 $children[] = [ 'close', [ $close ] ];
487 $accum[] = [ 'ext', $children ];
488 } elseif ( $found === 'line-start' ) {
489 // Is this the start of a heading?
490 // Line break belongs before the heading element in any case
491 if ( $fakeLineStart ) {
492 $fakeLineStart = false;
493 } else {
494 self::addLiteral( $accum, $curChar );
495 $i++;
498 // Examine upto 6 characters
499 $count = strspn( $text, '=', $i, min( $lengthText, 6 ) );
500 if ( $count === 1 && $findEquals ) {
501 // DWIM: This looks kind of like a name/value separator.
502 // Let's let the equals handler have it and break the potential
503 // heading. This is heuristic, but AFAICT the methods for
504 // completely correct disambiguation are very complex.
505 } elseif ( $count > 0 ) {
506 $piece = [
507 'open' => "\n",
508 'close' => "\n",
509 'parts' => [ new PPDPart_Hash( str_repeat( '=', $count ) ) ],
510 'startPos' => $i,
511 'count' => $count,
513 $stack->push( $piece );
514 $accum =& $stack->getAccum();
515 $stackFlags = $stack->getFlags();
516 if ( isset( $stackFlags['findEquals'] ) ) {
517 $findEquals = $stackFlags['findEquals'];
519 if ( isset( $stackFlags['findPipe'] ) ) {
520 $findPipe = $stackFlags['findPipe'];
522 if ( isset( $stackFlags['inHeading'] ) ) {
523 $inHeading = $stackFlags['inHeading'];
525 $i += $count;
527 } elseif ( $found === 'line-end' ) {
528 $piece = $stack->top;
529 // A heading must be open, otherwise \n wouldn't have been in the search list
530 // FIXME: Don't use assert()
531 // phpcs:ignore MediaWiki.Usage.ForbiddenFunctions.assert
532 assert( $piece->open === "\n" );
533 $part = $piece->getCurrentPart();
534 // Search back through the input to see if it has a proper close.
535 // Do this using the reversed string since the other solutions
536 // (end anchor, etc.) are inefficient.
537 $wsLength = strspn( $revText, " \t", $lengthText - $i );
538 $searchStart = $i - $wsLength;
539 if ( $part->commentEnd === $searchStart - 1 ) {
540 // Comment found at line end
541 // Search for equals signs before the comment
542 $searchStart = $part->visualEnd;
543 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
545 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
546 if ( $equalsLength > 0 ) {
547 if ( $searchStart - $equalsLength === $piece->startPos ) {
548 // This is just a single string of equals signs on its own line
549 // Replicate the doHeadings behavior /={count}(.+)={count}/
550 // First find out how many equals signs there really are (don't stop at 6)
551 if ( $equalsLength < 3 ) {
552 $count = 0;
553 } else {
554 $count = min( 6, intval( ( $equalsLength - 1 ) / 2 ) );
556 } else {
557 $count = min( $equalsLength, $piece->count );
559 if ( $count > 0 ) {
560 // Normal match, output <h>
561 $element = [ [ 'possible-h',
562 array_merge(
564 [ '@level', [ $count ] ],
565 [ '@i', [ $headingIndex++ ] ]
567 $accum
569 ] ];
570 } else {
571 // Single equals sign on its own line, count=0
572 $element = $accum;
574 } else {
575 // No match, no <h>, just pass down the inner text
576 $element = $accum;
578 // Unwind the stack
579 $stack->pop();
580 $accum =& $stack->getAccum();
581 $stackFlags = $stack->getFlags();
582 if ( isset( $stackFlags['findEquals'] ) ) {
583 $findEquals = $stackFlags['findEquals'];
585 if ( isset( $stackFlags['findPipe'] ) ) {
586 $findPipe = $stackFlags['findPipe'];
588 if ( isset( $stackFlags['inHeading'] ) ) {
589 $inHeading = $stackFlags['inHeading'];
592 // Append the result to the enclosing accumulator
593 array_splice( $accum, count( $accum ), 0, $element );
595 // Note that we do NOT increment the input pointer.
596 // This is because the closing linebreak could be the opening linebreak of
597 // another heading. Infinite loops are avoided because the next iteration MUST
598 // hit the heading open case above, which unconditionally increments the
599 // input pointer.
600 } elseif ( $found === 'open' ) {
601 # count opening brace characters
602 $curLen = strlen( $curChar );
603 $count = $curLen > 1
604 # allow the final character to repeat
605 ? strspn( $text, $curChar[$curLen - 1], $i + 1 ) + 1
606 : strspn( $text, $curChar, $i );
608 $savedPrefix = '';
609 $lineStart = $i > 0 && $text[$i - 1] === "\n";
611 if ( $curChar === "-{" && $count > $curLen ) {
612 // -{ => {{ transition because rightmost wins
613 $savedPrefix = '-';
614 $i++;
615 $curChar = '{';
616 $count--;
617 $rule = $this->rules[$curChar];
620 # we need to add to stack only if opening brace count is enough for one of the rules
621 if ( $count >= $rule['min'] ) {
622 # Add it to the stack
623 $piece = [
624 'open' => $curChar,
625 'close' => $rule['end'],
626 'savedPrefix' => $savedPrefix,
627 'count' => $count,
628 'lineStart' => $lineStart,
631 $stack->push( $piece );
632 $accum =& $stack->getAccum();
633 $stackFlags = $stack->getFlags();
634 if ( isset( $stackFlags['findEquals'] ) ) {
635 $findEquals = $stackFlags['findEquals'];
637 if ( isset( $stackFlags['findPipe'] ) ) {
638 $findPipe = $stackFlags['findPipe'];
640 if ( isset( $stackFlags['inHeading'] ) ) {
641 $inHeading = $stackFlags['inHeading'];
643 } else {
644 # Add literal brace(s)
645 self::addLiteral( $accum, $savedPrefix . str_repeat( $curChar, $count ) );
647 $i += $count;
648 } elseif ( $found === 'close' ) {
649 /** @var PPDStackElement_Hash $piece */
650 $piece = $stack->top;
651 '@phan-var PPDStackElement_Hash $piece';
652 # lets check if there are enough characters for closing brace
653 $maxCount = $piece->count;
654 if ( $piece->close === '}-' && $curChar === '}' ) {
655 $maxCount--; # don't try to match closing '-' as a '}'
657 $curLen = strlen( $curChar );
658 $count = $curLen > 1
659 ? $curLen
660 : strspn( $text, $curChar, $i, $maxCount );
662 # check for maximum matching characters (if there are 5 closing
663 # characters, we will probably need only 3 - depending on the rules)
664 $rule = $this->rules[$piece->open];
665 if ( $count > $rule['max'] ) {
666 # The specified maximum exists in the callback array, unless the caller
667 # has made an error
668 $matchingCount = $rule['max'];
669 } else {
670 # Count is less than the maximum
671 # Skip any gaps in the callback array to find the true largest match
672 # Need to use array_key_exists not isset because the callback can be null
673 $matchingCount = $count;
674 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
675 --$matchingCount;
679 if ( $matchingCount <= 0 ) {
680 # No matching element found in callback array
681 # Output a literal closing brace and continue
682 $endText = substr( $text, $i, $count );
683 self::addLiteral( $accum, $endText );
684 $i += $count;
685 continue;
687 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
688 $name = $rule['names'][$matchingCount];
689 if ( $name === null ) {
690 // No element, just literal text
691 $endText = substr( $text, $i, $matchingCount );
692 $element = $piece->breakSyntax( $matchingCount );
693 self::addLiteral( $element, $endText );
694 } else {
695 # Create XML element
696 $parts = $piece->parts;
697 $titleAccum = $parts[0]->out;
698 unset( $parts[0] );
700 $children = [];
702 # The invocation is at the start of the line if lineStart is set in
703 # the stack, and all opening brackets are used up.
704 if ( $maxCount === $matchingCount &&
705 $piece->lineStart &&
706 $piece->savedPrefix === ''
708 $children[] = [ '@lineStart', [ 1 ] ];
710 $titleNode = [ 'title', $titleAccum ];
711 $children[] = $titleNode;
712 $argIndex = 1;
713 foreach ( $parts as $part ) {
714 if ( $part->eqpos !== null ) {
715 $equalsNode = $part->out[$part->eqpos];
716 $nameNode = [ 'name', array_slice( $part->out, 0, $part->eqpos ) ];
717 $valueNode = [ 'value', array_slice( $part->out, $part->eqpos + 1 ) ];
718 $partNode = [ 'part', [ $nameNode, $equalsNode, $valueNode ] ];
719 $children[] = $partNode;
720 } else {
721 $nameNode = [ 'name', [ [ '@index', [ $argIndex++ ] ] ] ];
722 $valueNode = [ 'value', $part->out ];
723 $partNode = [ 'part', [ $nameNode, $valueNode ] ];
724 $children[] = $partNode;
727 $element = [ [ $name, $children ] ];
730 # Advance input pointer
731 $i += $matchingCount;
733 # Unwind the stack
734 $stack->pop();
735 $accum =& $stack->getAccum();
737 # Re-add the old stack element if it still has unmatched opening characters remaining
738 if ( $matchingCount < $piece->count ) {
739 $piece->parts = [ new PPDPart_Hash ];
740 $piece->count -= $matchingCount;
741 # do we still qualify for any callback with remaining count?
742 $min = $this->rules[$piece->open]['min'];
743 if ( $piece->count >= $min ) {
744 $stack->push( $piece );
745 $accum =& $stack->getAccum();
746 } elseif ( $piece->count === 1 && $piece->open === '{' && $piece->savedPrefix === '-' ) {
747 $piece->savedPrefix = '';
748 $piece->open = '-{';
749 $piece->count = 2;
750 $piece->close = $this->rules[$piece->open]['end'];
751 $stack->push( $piece );
752 $accum =& $stack->getAccum();
753 } else {
754 $s = substr( $piece->open, 0, -1 );
755 $s .= str_repeat(
756 substr( $piece->open, -1 ),
757 $piece->count - strlen( $s )
759 self::addLiteral( $accum, $piece->savedPrefix . $s );
761 } elseif ( $piece->savedPrefix !== '' ) {
762 self::addLiteral( $accum, $piece->savedPrefix );
765 $stackFlags = $stack->getFlags();
766 if ( isset( $stackFlags['findEquals'] ) ) {
767 $findEquals = $stackFlags['findEquals'];
769 if ( isset( $stackFlags['findPipe'] ) ) {
770 $findPipe = $stackFlags['findPipe'];
772 if ( isset( $stackFlags['inHeading'] ) ) {
773 $inHeading = $stackFlags['inHeading'];
776 # Add XML element to the enclosing accumulator
777 array_splice( $accum, count( $accum ), 0, $element );
778 } elseif ( $found === 'pipe' ) {
779 $findEquals = true; // shortcut for getFlags()
780 $stack->addPart();
781 $accum =& $stack->getAccum();
782 ++$i;
783 } elseif ( $found === 'equals' ) {
784 $findEquals = false; // shortcut for getFlags()
785 $accum[] = [ 'equals', [ '=' ] ];
786 $stack->getCurrentPart()->eqpos = count( $accum ) - 1;
787 ++$i;
791 # Output any remaining unclosed brackets
792 foreach ( $stack->stack as $piece ) {
793 array_splice( $stack->rootAccum, count( $stack->rootAccum ), 0, $piece->breakSyntax() );
796 # Enable top-level headings
797 foreach ( $stack->rootAccum as &$node ) {
798 if ( is_array( $node ) && $node[PPNode_Hash_Tree::NAME] === 'possible-h' ) {
799 $node[PPNode_Hash_Tree::NAME] = 'h';
803 return [ [ 'root', $stack->rootAccum ] ];
806 private static function addLiteral( array &$accum, $text ) {
807 $n = count( $accum );
808 if ( $n && is_string( $accum[$n - 1] ) ) {
809 $accum[$n - 1] .= $text;
810 } else {
811 $accum[] = $text;
816 /** @deprecated class alias since 1.43 */
817 class_alias( Preprocessor_Hash::class, 'Preprocessor_Hash' );