[JsonCodec] Hide TYPE_ANNOTATION from the unserialization methods
[mediawiki.git] / includes / parser / PPFrame_Hash.php
blob3a9daa95b441f6828174e662a6672b75668364d0
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
18 * @file
19 * @ingroup Parser
22 use MediaWiki\Parser\Parser;
23 use MediaWiki\Title\Title;
25 /**
26 * An expansion frame, used as a context to expand the result of preprocessToObj()
27 * @ingroup Parser
29 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
30 class PPFrame_Hash implements PPFrame {
32 /**
33 * @var Parser
35 public $parser;
37 /**
38 * @var Preprocessor
40 public $preprocessor;
42 /**
43 * @var Title
45 public $title;
47 /**
48 * @var (string|false)[]
50 public $titleCache;
52 /**
53 * Hashtable listing templates which are disallowed for expansion in this frame,
54 * having been encountered previously in parent frames.
55 * @var true[]
57 public $loopCheckHash;
59 /**
60 * Recursion depth of this frame, top = 0
61 * Note that this is NOT the same as expansion depth in expand()
62 * @var int
64 public $depth;
66 /** @var bool */
67 private $volatile = false;
68 /** @var int|null */
69 private $ttl = null;
71 /**
72 * @var array
74 protected $childExpansionCache;
75 /**
76 * @var int
78 private $maxPPNodeCount;
79 /**
80 * @var int
82 private $maxPPExpandDepth;
84 /**
85 * @param Preprocessor $preprocessor The parent preprocessor
87 public function __construct( $preprocessor ) {
88 $this->preprocessor = $preprocessor;
89 $this->parser = $preprocessor->parser;
90 $this->title = $this->parser->getTitle();
91 $this->maxPPNodeCount = $this->parser->getOptions()->getMaxPPNodeCount();
92 $this->maxPPExpandDepth = $this->parser->getOptions()->getMaxPPExpandDepth();
93 $this->titleCache = [ $this->title ? $this->title->getPrefixedDBkey() : false ];
94 $this->loopCheckHash = [];
95 $this->depth = 0;
96 $this->childExpansionCache = [];
99 /**
100 * Create a new child frame
101 * $args is optionally a multi-root PPNode or array containing the template arguments
103 * @param PPNode[]|false|PPNode_Hash_Array $args
104 * @param Title|false $title
105 * @param int $indexOffset
106 * @return PPTemplateFrame_Hash
108 public function newChild( $args = false, $title = false, $indexOffset = 0 ) {
109 $namedArgs = [];
110 $numberedArgs = [];
111 if ( $title === false ) {
112 $title = $this->title;
114 if ( $args !== false ) {
115 if ( $args instanceof PPNode_Hash_Array ) {
116 $args = $args->value;
117 } elseif ( !is_array( $args ) ) {
118 throw new InvalidArgumentException( __METHOD__ . ': $args must be array or PPNode_Hash_Array' );
120 foreach ( $args as $arg ) {
121 $bits = $arg->splitArg();
122 if ( $bits['index'] !== '' ) {
123 // Numbered parameter
124 $index = $bits['index'] - $indexOffset;
125 if ( isset( $namedArgs[$index] ) || isset( $numberedArgs[$index] ) ) {
126 $this->parser->getOutput()->addWarningMsg(
127 'duplicate-args-warning',
128 Message::plaintextParam( (string)$this->title ),
129 Message::plaintextParam( (string)$title ),
130 Message::numParam( $index )
132 $this->parser->addTrackingCategory( 'duplicate-args-category' );
134 $numberedArgs[$index] = $bits['value'];
135 unset( $namedArgs[$index] );
136 } else {
137 // Named parameter
138 $name = trim( $this->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
139 if ( isset( $namedArgs[$name] ) || isset( $numberedArgs[$name] ) ) {
140 $this->parser->getOutput()->addWarningMsg(
141 'duplicate-args-warning',
142 Message::plaintextParam( (string)$this->title ),
143 Message::plaintextParam( (string)$title ),
144 Message::plaintextParam( $name )
146 $this->parser->addTrackingCategory( 'duplicate-args-category' );
148 $namedArgs[$name] = $bits['value'];
149 unset( $numberedArgs[$name] );
153 return new PPTemplateFrame_Hash( $this->preprocessor, $this, $numberedArgs, $namedArgs, $title );
157 * @param string|int $key
158 * @param string|PPNode $root
159 * @param int $flags
160 * @return string
162 public function cachedExpand( $key, $root, $flags = 0 ) {
163 // we don't have a parent, so we don't have a cache
164 return $this->expand( $root, $flags );
168 * @param string|PPNode $root
169 * @param int $flags
170 * @return string
172 public function expand( $root, $flags = 0 ) {
173 static $expansionDepth = 0;
174 if ( is_string( $root ) ) {
175 return $root;
178 if ( ++$this->parser->mPPNodeCount > $this->maxPPNodeCount ) {
179 $this->parser->limitationWarn( 'node-count-exceeded',
180 $this->parser->mPPNodeCount,
181 $this->maxPPNodeCount
183 return '<span class="error">Node-count limit exceeded</span>';
185 if ( $expansionDepth > $this->maxPPExpandDepth ) {
186 $this->parser->limitationWarn( 'expansion-depth-exceeded',
187 $expansionDepth,
188 $this->maxPPExpandDepth
190 return '<span class="error">Expansion depth limit exceeded</span>';
192 ++$expansionDepth;
193 if ( $expansionDepth > $this->parser->mHighestExpansionDepth ) {
194 $this->parser->mHighestExpansionDepth = $expansionDepth;
197 $outStack = [ '', '' ];
198 $iteratorStack = [ false, $root ];
199 $indexStack = [ 0, 0 ];
201 while ( count( $iteratorStack ) > 1 ) {
202 $level = count( $outStack ) - 1;
203 $iteratorNode =& $iteratorStack[$level];
204 $out =& $outStack[$level];
205 $index =& $indexStack[$level];
207 if ( is_array( $iteratorNode ) ) {
208 if ( $index >= count( $iteratorNode ) ) {
209 // All done with this iterator
210 $iteratorStack[$level] = false;
211 $contextNode = false;
212 } else {
213 $contextNode = $iteratorNode[$index];
214 $index++;
216 } elseif ( $iteratorNode instanceof PPNode_Hash_Array ) {
217 if ( $index >= $iteratorNode->getLength() ) {
218 // All done with this iterator
219 $iteratorStack[$level] = false;
220 $contextNode = false;
221 } else {
222 $contextNode = $iteratorNode->item( $index );
223 $index++;
225 } else {
226 // Copy to $contextNode and then delete from iterator stack,
227 // because this is not an iterator but we do have to execute it once
228 $contextNode = $iteratorStack[$level];
229 $iteratorStack[$level] = false;
232 $newIterator = false;
233 $contextName = false;
234 $contextChildren = false;
236 if ( $contextNode === false ) {
237 // nothing to do
238 } elseif ( is_string( $contextNode ) ) {
239 $out .= $contextNode;
240 } elseif ( $contextNode instanceof PPNode_Hash_Array ) {
241 $newIterator = $contextNode;
242 } elseif ( $contextNode instanceof PPNode_Hash_Attr ) {
243 // No output
244 } elseif ( $contextNode instanceof PPNode_Hash_Text ) {
245 $out .= $contextNode->value;
246 } elseif ( $contextNode instanceof PPNode_Hash_Tree ) {
247 $contextName = $contextNode->name;
248 $contextChildren = $contextNode->getRawChildren();
249 } elseif ( is_array( $contextNode ) ) {
250 // Node descriptor array
251 if ( count( $contextNode ) !== 2 ) {
252 throw new RuntimeException( __METHOD__ .
253 ': found an array where a node descriptor should be' );
255 [ $contextName, $contextChildren ] = $contextNode;
256 } else {
257 throw new RuntimeException( __METHOD__ . ': Invalid parameter type' );
260 // Handle node descriptor array or tree object
261 if ( $contextName === false ) {
262 // Not a node, already handled above
263 } elseif ( $contextName[0] === '@' ) {
264 // Attribute: no output
265 } elseif ( $contextName === 'template' ) {
266 # Double-brace expansion
267 $bits = PPNode_Hash_Tree::splitRawTemplate( $contextChildren );
268 if ( $flags & PPFrame::NO_TEMPLATES ) {
269 $newIterator = $this->virtualBracketedImplode(
270 '{{', '|', '}}',
271 $bits['title'],
272 $bits['parts']
274 } else {
275 $ret = $this->parser->braceSubstitution( $bits, $this );
276 if ( isset( $ret['object'] ) ) {
277 $newIterator = $ret['object'];
278 } else {
279 $out .= $ret['text'];
282 } elseif ( $contextName === 'tplarg' ) {
283 # Triple-brace expansion
284 $bits = PPNode_Hash_Tree::splitRawTemplate( $contextChildren );
285 if ( $flags & PPFrame::NO_ARGS ) {
286 $newIterator = $this->virtualBracketedImplode(
287 '{{{', '|', '}}}',
288 $bits['title'],
289 $bits['parts']
291 } else {
292 $ret = $this->parser->argSubstitution( $bits, $this );
293 if ( isset( $ret['object'] ) ) {
294 $newIterator = $ret['object'];
295 } else {
296 $out .= $ret['text'];
299 } elseif ( $contextName === 'comment' ) {
300 # HTML-style comment
301 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
302 # Not in RECOVER_COMMENTS mode (msgnw) though.
303 if ( ( $this->parser->getOutputType() === Parser::OT_HTML
304 || ( $this->parser->getOutputType() === Parser::OT_PREPROCESS &&
305 $this->parser->getOptions()->getRemoveComments() )
306 || ( $flags & PPFrame::STRIP_COMMENTS )
307 ) && !( $flags & PPFrame::RECOVER_COMMENTS )
309 $out .= '';
310 } elseif (
311 $this->parser->getOutputType() === Parser::OT_WIKI &&
312 !( $flags & PPFrame::RECOVER_COMMENTS )
314 # Add a strip marker in PST mode so that pstPass2() can
315 # run some old-fashioned regexes on the result.
316 # Not in RECOVER_COMMENTS mode (extractSections) though.
317 $out .= $this->parser->insertStripItem( $contextChildren[0] );
318 } else {
319 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
320 $out .= $contextChildren[0];
322 } elseif ( $contextName === 'ignore' ) {
323 # Output suppression used by <includeonly> etc.
324 # OT_WIKI will only respect <ignore> in substed templates.
325 # The other output types respect it unless NO_IGNORE is set.
326 # extractSections() sets NO_IGNORE and so never respects it.
327 if ( ( !isset( $this->parent ) && $this->parser->getOutputType() === Parser::OT_WIKI )
328 || ( $flags & PPFrame::NO_IGNORE )
330 $out .= $contextChildren[0];
331 } else {
332 // $out .= '';
334 } elseif ( $contextName === 'ext' ) {
335 # Extension tag
336 $bits = PPNode_Hash_Tree::splitRawExt( $contextChildren ) +
337 [ 'attr' => null, 'inner' => null, 'close' => null ];
338 if ( $flags & PPFrame::NO_TAGS ) {
339 $s = '<' . $bits['name']->getFirstChild()->value;
340 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
341 if ( $bits['attr'] ) {
342 $s .= $bits['attr']->getFirstChild()->value;
344 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
345 if ( $bits['inner'] ) {
346 $s .= '>' . $bits['inner']->getFirstChild()->value;
347 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
348 if ( $bits['close'] ) {
349 $s .= $bits['close']->getFirstChild()->value;
351 } else {
352 $s .= '/>';
354 $out .= $s;
355 } else {
356 $out .= $this->parser->extensionSubstitution( $bits, $this,
357 (bool)( $flags & PPFrame::PROCESS_NOWIKI ) );
359 } elseif ( $contextName === 'h' ) {
360 # Heading
361 if ( $this->parser->getOutputType() === Parser::OT_HTML ) {
362 # Expand immediately and insert heading index marker
363 $s = $this->expand( $contextChildren, $flags );
364 $bits = PPNode_Hash_Tree::splitRawHeading( $contextChildren );
365 $titleText = $this->title->getPrefixedDBkey();
366 $this->parser->mHeadings[] = [ $titleText, $bits['i'] ];
367 $serial = count( $this->parser->mHeadings ) - 1;
368 $marker = Parser::MARKER_PREFIX . "-h-$serial-" . Parser::MARKER_SUFFIX;
369 $s = substr( $s, 0, $bits['level'] ) . $marker . substr( $s, $bits['level'] );
370 $this->parser->getStripState()->addGeneral( $marker, '' );
371 $out .= $s;
372 } else {
373 # Expand in virtual stack
374 $newIterator = $contextChildren;
376 } else {
377 # Generic recursive expansion
378 $newIterator = $contextChildren;
381 if ( $newIterator !== false ) {
382 $outStack[] = '';
383 $iteratorStack[] = $newIterator;
384 $indexStack[] = 0;
385 } elseif ( $iteratorStack[$level] === false ) {
386 // Return accumulated value to parent
387 // With tail recursion
388 while ( $iteratorStack[$level] === false && $level > 0 ) {
389 $outStack[$level - 1] .= $out;
390 array_pop( $outStack );
391 array_pop( $iteratorStack );
392 array_pop( $indexStack );
393 $level--;
397 --$expansionDepth;
398 return $outStack[0];
402 * @param string $sep
403 * @param int $flags
404 * @param string|PPNode ...$args
405 * @return string
407 public function implodeWithFlags( $sep, $flags, ...$args ) {
408 $first = true;
409 $s = '';
410 foreach ( $args as $root ) {
411 if ( $root instanceof PPNode_Hash_Array ) {
412 $root = $root->value;
414 if ( !is_array( $root ) ) {
415 $root = [ $root ];
417 foreach ( $root as $node ) {
418 if ( $first ) {
419 $first = false;
420 } else {
421 $s .= $sep;
423 $s .= $this->expand( $node, $flags );
426 return $s;
430 * Implode with no flags specified
431 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
432 * @param string $sep
433 * @param string|PPNode ...$args
434 * @return string
436 public function implode( $sep, ...$args ) {
437 $first = true;
438 $s = '';
439 foreach ( $args as $root ) {
440 if ( $root instanceof PPNode_Hash_Array ) {
441 $root = $root->value;
443 if ( !is_array( $root ) ) {
444 $root = [ $root ];
446 foreach ( $root as $node ) {
447 if ( $first ) {
448 $first = false;
449 } else {
450 $s .= $sep;
452 $s .= $this->expand( $node );
455 return $s;
459 * Makes an object that, when expand()ed, will be the same as one obtained
460 * with implode()
462 * @param string $sep
463 * @param string|PPNode ...$args
464 * @return PPNode_Hash_Array
466 public function virtualImplode( $sep, ...$args ) {
467 $out = [];
468 $first = true;
470 foreach ( $args as $root ) {
471 if ( $root instanceof PPNode_Hash_Array ) {
472 $root = $root->value;
474 if ( !is_array( $root ) ) {
475 $root = [ $root ];
477 foreach ( $root as $node ) {
478 if ( $first ) {
479 $first = false;
480 } else {
481 $out[] = $sep;
483 $out[] = $node;
486 return new PPNode_Hash_Array( $out );
490 * Virtual implode with brackets
492 * @param string $start
493 * @param string $sep
494 * @param string $end
495 * @param string|PPNode ...$args
496 * @return PPNode_Hash_Array
498 public function virtualBracketedImplode( $start, $sep, $end, ...$args ) {
499 $out = [ $start ];
500 $first = true;
502 foreach ( $args as $root ) {
503 if ( $root instanceof PPNode_Hash_Array ) {
504 $root = $root->value;
506 if ( !is_array( $root ) ) {
507 $root = [ $root ];
509 foreach ( $root as $node ) {
510 if ( $first ) {
511 $first = false;
512 } else {
513 $out[] = $sep;
515 $out[] = $node;
518 $out[] = $end;
519 return new PPNode_Hash_Array( $out );
522 public function __toString() {
523 return 'frame{}';
527 * @param string|false $level
528 * @return false|string
530 public function getPDBK( $level = false ) {
531 if ( $level === false ) {
532 return $this->title->getPrefixedDBkey();
533 } else {
534 return $this->titleCache[$level] ?? false;
539 * @return array
541 public function getArguments() {
542 return [];
546 * @return array
548 public function getNumberedArguments() {
549 return [];
553 * @return array
555 public function getNamedArguments() {
556 return [];
560 * Returns true if there are no arguments in this frame
562 * @return bool
564 public function isEmpty() {
565 return true;
569 * @param int|string $name
570 * @return bool Always false in this implementation.
572 public function getArgument( $name ) {
573 return false;
577 * Returns true if the infinite loop check is OK, false if a loop is detected
579 * @param Title $title
581 * @return bool
583 public function loopCheck( $title ) {
584 return !isset( $this->loopCheckHash[$title->getPrefixedDBkey()] );
588 * Return true if the frame is a template frame
590 * @return bool
592 public function isTemplate() {
593 return false;
597 * Get a title of frame
599 * @return Title
601 public function getTitle() {
602 return $this->title;
606 * Set the volatile flag
608 * @param bool $flag
610 public function setVolatile( $flag = true ) {
611 $this->volatile = $flag;
615 * Get the volatile flag
617 * @return bool
619 public function isVolatile() {
620 return $this->volatile;
624 * @param int $ttl
626 public function setTTL( $ttl ) {
627 if ( $ttl !== null && ( $this->ttl === null || $ttl < $this->ttl ) ) {
628 $this->ttl = $ttl;
633 * @return int|null
635 public function getTTL() {
636 return $this->ttl;