Debian Codegraph @

vendor/wikimedia/remex-html/src/TreeBuilder/TreeBuilder.php

raw
1 <?php
2
3 namespace Wikimedia\RemexHtml\TreeBuilder;
4
5 use Wikimedia\RemexHtml\HTMLData;
6 use Wikimedia\RemexHtml\PropGuard;
7 use Wikimedia\RemexHtml\Tokenizer\Attributes;
8 use Wikimedia\RemexHtml\Tokenizer\PlainAttributes;
9 use Wikimedia\RemexHtml\Tokenizer\Tokenizer;
10
11 /**
12 * TreeBuilder is the receiver of events from the InsertionMode subclasses,
13 * and is responsible for forwarding events on to the TreeHandler, which is
14 * responsible for constructing a DOM.
15 *
16 * TreeBuilder contains most of the state referred to by the "tree construction"
17 * part of the HTML spec which is not handled elsewhere, such as the stack of
18 * open elements and the list of active formatting elements.
19 *
20 * Miscellaneous helpers for InsertionMode subclasses are also in this class.
21 *
22 * https://www.w3.org/TR/2016/REC-html51-20161101/syntax.html
23 */
24 class TreeBuilder {
25 use PropGuard;
26
27 // Quirks
28 public const NO_QUIRKS = 0;
29 public const LIMITED_QUIRKS = 1;
30 public const QUIRKS = 2;
31
32 // Insertion placement
33 public const BEFORE = 0;
34 public const UNDER = 1;
35 public const ROOT = 2;
36
37 // Configuration
38 /** @var bool */
39 public $isIframeSrcdoc;
40 /** @var bool */
41 public $scriptingFlag;
42 /** @var bool */
43 public $ignoreErrors;
44 /** @var bool */
45 public $ignoreNulls;
46
47 // Objects
48
49 public TreeHandler $handler;
50
51 /** @var SimpleStack */
52 public $stack;
53
54 public ActiveFormattingElements $afe;
55
56 /** @var Tokenizer */
57 public $tokenizer;
58
59 // State
60 /** @var bool */
61 public $isFragment = false;
62 /** @var Element|null */
63 public $fragmentContext;
64 /** @var Element|null */
65 public $headElement;
66 /** @var Element|null */
67 public $formElement;
68 /** @var bool */
69 public $framesetOK = true;
70 /** @var int */
71 public $quirks = self::NO_QUIRKS;
72 /** @var bool */
73 public $fosterParenting = false;
74 /** @var array[] */
75 public $pendingTableCharacters = [];
76
77 private const FOSTER_TRIGGERS = [
78 'table' => true,
79 'tbody' => true,
80 'tfoot' => true,
81 'thead' => true,
82 'tr' => true
83 ];
84
85 private const IMPLIED_END_TAGS = [
86 'dd' => true,
87 'dt' => true,
88 'li' => true,
89 'option' => true,
90 'optgroup' => true,
91 'p' => true,
92 'rb' => true,
93 'rp' => true,
94 'rt' => true,
95 'rtc' => true,
96 ];
97
98 private const THOROUGHLY_IMPLIED_END_TAGS = [
99 'caption' => true,
100 'colgroup' => true,
101 'dd' => true,
102 'dt' => true,
103 'li' => true,
104 'optgroup' => true,
105 'option' => true,
106 'p' => true,
107 'rb' => true,
108 'rp' => true,
109 'rt' => true,
110 'rtc' => true,
111 'tbody' => true,
112 'td' => true,
113 'tfoot' => true,
114 'th' => true,
115 'thead' => true,
116 'tr' => true
117 ];
118
119 /**
120 * @param TreeHandler $handler The handler which receives tree mutation events
121 * @param array $options Associative array of options. The options are:
122 * - isIframeSrcdoc: True if the document is an iframe srcdoc document.
123 * Default false.
124 * - scriptingFlag: True if the scripting flag is enabled. Default true.
125 * Setting this to false cause the contents of <noscript> elements to be
126 * processed as normal content. The scriptingFlag option in the
127 * Tokenizer should be set to the same value.
128 * - ignoreErrors: True to ignore errors. This improves performance.
129 * Default false.
130 * - ignoreNulls: True to ignore null characters in the input, instead of
131 * following the specified behaviour. Default false.
132 * - scopeCache: True to use an implementation of the stack of open elements
133 * which caches "in scope" predicates. False to use a simpler
134 * implementation. Default true. Setting this to false may improve
135 * performance for simple documents, although at the expense of O(N^2)
136 * instead of O(N) worst case time order.
137 */
138 public function __construct( TreeHandler $handler, $options = [] ) {
139 $this->handler = $handler;
140 $this->afe = new ActiveFormattingElements;
141 $options += [
142 'isIframeSrcdoc' => false,
143 'scriptingFlag' => true,
144 'ignoreErrors' => false,
145 'ignoreNulls' => false,
146 'scopeCache' => true,
147 ];
148
149 $this->isIframeSrcdoc = $options['isIframeSrcdoc'];
150 $this->scriptingFlag = $options['scriptingFlag'];
151 $this->ignoreErrors = $options['ignoreErrors'];
152 $this->ignoreNulls = $options['ignoreNulls'];
153
154 if ( $options['scopeCache'] ) {
155 $this->stack = new CachingStack;
156 } else {
157 $this->stack = new SimpleStack;
158 }
159 }
160
161 /**
162 * Notify TreeBuilder and later pipeline stages of the start of a document.
163 * This is called by the Dispatcher when a startDocument event is
164 * received.
165 *
166 * @param Tokenizer $tokenizer
167 * @param string $namespace
168 * @param string $name
169 */
170 public function startDocument( Tokenizer $tokenizer, $namespace, $name ) {
171 $tokenizer->setEnableCdataCallback(
172 function () {
173 $acn = $this->adjustedCurrentNode();
174 return $acn && $acn->namespace !== HTMLData::NS_HTML;
175 }
176 );
177 $this->tokenizer = $tokenizer;
178
179 $this->handler->startDocument( $namespace, $name );
180 if ( $namespace !== null ) {
181 $this->isFragment = true;
182 $this->fragmentContext = new Element( $namespace, $name, new PlainAttributes );
183 $this->fragmentContext->isVirtual = true;
184 $html = new Element( HTMLData::NS_HTML, 'html', new PlainAttributes );
185 $html->isVirtual = true;
186 $this->stack->push( $html );
187 $this->handler->insertElement( self::ROOT, null, $html, false, 0, 0 );
188 }
189 }
190
191 /**
192 * Get the adjusted current node
193 *
194 * @return Element|null
195 */
196 public function adjustedCurrentNode() {
197 $current = $this->stack->current;
198 if ( $this->isFragment && ( !$current || $current->stackIndex === 0 ) ) {
199 return $this->fragmentContext;
200 } else {
201 return $current;
202 }
203 }
204
205 /**
206 * Find the appropriate place for inserting a node.
207 *
208 * @param Element|null $target The override target
209 * @return array A list with the preposition in the first element, and the
210 * reference node in the second element.
211 */
212 private function appropriatePlace( $target = null ) {
213 $stack = $this->stack;
214 if ( $target === null ) {
215 $target = $stack->current;
216 }
217 if ( $target === null ) {
218 return [ self::ROOT, null ];
219 }
220 if ( !$this->fosterParenting ) {
221 return [ self::UNDER, $target ];
222 }
223 if ( !isset( self::FOSTER_TRIGGERS[$target->htmlName] ) ) {
224 return [ self::UNDER, $target ];
225 }
226 $node = null;
227 for ( $idx = $this->stack->length() - 1; $idx >= 0; $idx-- ) {
228 $node = $this->stack->item( $idx );
229 if ( $node->htmlName === 'table' && $idx >= 1 ) {
230 return [ self::BEFORE, $node ];
231 }
232 if ( $node->htmlName === 'template' ) {
233 return [ self::UNDER, $node ];
234 }
235 }
236 return [ self::UNDER, $node ];
237 }
238
239 /**
240 * Insert characters at the appropriate place for inserting a node.
241 *
242 * @param string $text The string which contains the emitted characters
243 * @param int $start The start of the range within $text to use
244 * @param int $length The length of the range within $text to use
245 * @param int $sourceStart The input position
246 * @param int $sourceLength The input length
247 */
248 public function insertCharacters( $text, $start, $length, $sourceStart, $sourceLength ) {
249 [ $prep, $ref ] = $this->appropriatePlace();
250 $this->handler->characters( $prep, $ref, $text, $start, $length,
251 $sourceStart, $sourceLength );
252 }
253
254 /**
255 * Insert an element in the HTML namespace, at the appropriate place for inserting a node
256 *
257 * @param string $name The element name
258 * @param Attributes $attrs The element attributes
259 * @param bool $void The void (self-closing) element hint
260 * @param int $sourceStart The input position
261 * @param int $sourceLength The input length
262 * @return Element
263 */
264 public function insertElement( $name, Attributes $attrs, $void, $sourceStart, $sourceLength ) {
265 return $this->insertForeign( HTMLData::NS_HTML, $name, $attrs, $void,
266 $sourceStart, $sourceLength );
267 }
268
269 /**
270 * Insert an element in any namespace, at the appropriate place for inserting a node.
271 *
272 * @param string $ns The namespace
273 * @param string $name The element name
274 * @param Attributes $attrs The element attributes
275 * @param bool $void The void (self-closing) element hint
276 * @param int $sourceStart The input position
277 * @param int $sourceLength The input length
278 * @return Element
279 */
280 public function insertForeign( $ns, $name, Attributes $attrs, $void,
281 $sourceStart, $sourceLength
282 ) {
283 [ $prep, $ref ] = $this->appropriatePlace();
284 $element = new Element( $ns, $name, $attrs );
285 $this->handler->insertElement( $prep, $ref, $element, $void,
286 $sourceStart, $sourceLength );
287 if ( !$void ) {
288 $this->stack->push( $element );
289 }
290 return $element;
291 }
292
293 /**
294 * Pop the current node from the stack of open elements, and notify the
295 * handler that we are done with that node.
296 *
297 * @param int $sourceStart
298 * @param int $sourceLength
299 * @return Element
300 */
301 public function pop( $sourceStart, $sourceLength ) {
302 $element = $this->stack->pop();
303 $this->handler->endTag( $element, $sourceStart, $sourceLength );
304 return $element;
305 }
306
307 /**
308 * Insert a doctype node
309 *
310 * @param string $name The doctype name
311 * @param string $public The public ID
312 * @param string $system The system ID
313 * @param int $quirks The quirks mode. May be either self::NO_QUIRKS,
314 * self::LIMITED_QUIRKS or self::QUIRKS to indicate no-quirks mode,
315 * limited-quirks mode or quirks mode respectively.
316 * @param int $sourceStart
317 * @param int $sourceLength
318 */
319 public function doctype( $name, $public, $system, $quirks, $sourceStart, $sourceLength ) {
320 $this->handler->doctype( $name, $public, $system, $quirks, $sourceStart, $sourceLength );
321 $this->quirks = $quirks;
322 }
323
324 /**
325 * Insert a comment node
326 *
327 * @param array|null $place The place where the node is to be inserted.
328 * May be either a preposition/refNode pair or null. If it is null,
329 * the node will be inserted at the "appropriate place".
330 * @param string $text The comment contents
331 * @param int $sourceStart
332 * @param int $sourceLength
333 */
334 public function comment( $place, $text, $sourceStart, $sourceLength ) {
335 [ $prep, $ref ] = $place ?? $this->appropriatePlace();
336 $this->handler->comment( $prep, $ref, $text, $sourceStart, $sourceLength );
337 }
338
339 /**
340 * Notify the handler of an error (if ignoreErrors is not set).
341 *
342 * @param string $text The error message
343 * @param int $pos The input position
344 */
345 public function error( $text, $pos ) {
346 if ( !$this->ignoreErrors ) {
347 $this->handler->error( $text, $pos );
348 }
349 }
350
351 /**
352 * Add attributes to an existing element.
353 *
354 * @param Element $elt
355 * @param Attributes $attrs
356 * @param int $sourceStart
357 * @param int $sourceLength
358 */
359 public function mergeAttributes( Element $elt, Attributes $attrs, $sourceStart, $sourceLength ) {
360 if ( $attrs->count() && !$elt->isVirtual ) {
361 $this->handler->mergeAttributes( $elt, $attrs, $sourceStart );
362 }
363 }
364
365 /**
366 * If the stack of open elements has a p element in button scope, then
367 * close a p element.
368 *
369 * The above phrase appears many times in the spec.
370 *
371 * @param int $pos The source position
372 */
373 public function closePInButtonScope( $pos ) {
374 if ( $this->stack->isInButtonScope( 'p' ) ) {
375 $this->generateImpliedEndTagsAndPop( 'p', $pos, 0 );
376 }
377 }
378
379 /**
380 * Check the stack to see if there is any element which is not on the list
381 * of allowed elements. Raise an error if any are found.
382 *
383 * @param array $allowed An array with the HTML element names in the key
384 * @param int $pos
385 */
386 public function checkUnclosed( $allowed, $pos ) {
387 if ( $this->ignoreErrors ) {
388 return;
389 }
390
391 $stack = $this->stack;
392 $unclosedErrors = [];
393 for ( $i = $stack->length() - 1; $i >= 0; $i-- ) {
394 $unclosedName = $stack->item( $i )->htmlName;
395 if ( !isset( $allowed[$unclosedName] ) ) {
396 $unclosedErrors[$unclosedName] = true;
397 }
398 }
399 if ( $unclosedErrors ) {
400 $names = implode( ', ', array_keys( $unclosedErrors ) );
401 $this->error( "closing unclosed $names", $pos );
402 }
403 }
404
405 /**
406 * Reconstruct the active formatting elements.
407 * @author C. Scott Ananian, Tim Starling
408 * @param int $sourceStart
409 */
410 public function reconstructAFE( $sourceStart ) {
411 $entry = $this->afe->getTail();
412 // If there are no entries in the list of active formatting elements,
413 // then there is nothing to reconstruct
414 if ( !$entry ) {
415 return;
416 }
417 // If the last is a marker, do nothing.
418 if ( $entry instanceof Marker ) {
419 return;
420 }
421 // Or if it is an open element, do nothing.
422 if ( $entry->stackIndex !== null ) {
423 return;
424 }
425
426 // Loop backward through the list until we find a marker or an
427 // open element
428 $foundIt = false;
429 while ( $entry->prevAFE ) {
430 $entry = $entry->prevAFE;
431 // $entry is known not to be null here (but phan doesn't know that)
432 '@phan-var Marker|Element $entry'; /** @var Marker|Element $entry */
433 if ( $entry instanceof Marker || $entry->stackIndex !== null ) {
434 $foundIt = true;
435 break;
436 }
437 }
438
439 // Now loop forward, starting from the element after the current one (or
440 // the first element if we didn't find a marker or open element),
441 // recreating formatting elements and pushing them back onto the list
442 // of open elements.
443 if ( $foundIt ) {
444 $entry = $entry->nextAFE;
445 // $entry is known not to be null here (but phan doesn't know that)
446 '@phan-var Marker|Element $entry'; /** @var Marker|Element $entry */
447 }
448 do {
449 $newElement = $this->insertForeign( HTMLData::NS_HTML, $entry->name,
450 $entry->attrs->clone(), false, $sourceStart, 0 );
451 $this->afe->replace( $entry, $newElement );
452 $entry = $newElement->nextAFE;
453 } while ( $entry );
454 }
455
456 /**
457 * Run the "adoption agency algorithm" (AAA) for the given subject
458 * tag name.
459 * @author C. Scott Ananian, Tim Starling
460 *
461 * @param string $subject The subject tag name.
462 * @param int $sourceStart
463 * @param int $sourceLength
464 */
465 public function adoptionAgency( $subject, $sourceStart, $sourceLength ) {
466 $afe = $this->afe;
467 $stack = $this->stack;
468 $handler = $this->handler;
469
470 // If the current node is an HTML element whose tag name is subject,
471 // and the current node is not in the list of active formatting
472 // elements, then pop the current node off the stack of open
473 // elements and abort these steps. [1]
474 if (
475 $stack->current->htmlName === $subject &&
476 !$afe->isInList( $stack->current )
477 ) {
478 $this->pop( $sourceStart, $sourceLength );
479 return;
480 }
481
482 // Outer loop: If outer loop counter is greater than or
483 // equal to eight, then abort these steps. [2-4]
484 for ( $outer = 0; $outer < 8; $outer++ ) {
485
486 // Let the formatting element be the last element in the list
487 // of active formatting elements that: is between the end of
488 // the list and the last scope marker in the list, if any, or
489 // the start of the list otherwise, and has the same tag name
490 // as the token. [5]
491 $fmtElt = $afe->findElementByName( $subject );
492
493 // If there is no such node, then abort these steps and instead
494 // act as described in the "any other end tag" entry above.
495 if ( !$fmtElt ) {
496 $this->anyOtherEndTag( $subject, $sourceStart, $sourceLength );
497 return;
498 }
499
500 // Otherwise, if there is such a node, but that node is not in
501 // the stack of open elements, then this is a parse error;
502 // remove the element from the list, and abort these steps. [6]
503 $fmtEltIndex = $fmtElt->stackIndex;
504 if ( $fmtEltIndex === null ) {
505 $this->error( 'closing tag matched an active formatting element ' .
506 'which is not in the stack', $sourceStart );
507 $afe->remove( $fmtElt );
508 return;
509 }
510
511 // Otherwise, if there is such a node, and that node is also in
512 // the stack of open elements, but the element is not in scope,
513 // then this is a parse error; ignore the token, and abort
514 // these steps. [7]
515 if ( !$stack->isElementInScope( $fmtElt ) ) {
516 $this->error( 'end tag matched a start tag which is not in scope',
517 $sourceStart );
518 return;
519 }
520
521 // If formatting element is not the current node, this is a parse
522 // error. (But do not abort these steps.) [8]
523 if ( $fmtElt !== $stack->current ) {
524 $this->error( 'end tag matched a formatting element which was ' .
525 'not the current node', $sourceStart );
526 }
527
528 // Let the furthest block be the topmost node in the stack of
529 // open elements that is lower in the stack than the formatting
530 // element, and is an element in the special category. There
531 // might not be one. [9]
532 $furthestBlock = null;
533 $furthestBlockIndex = -1;
534 $stackLength = $stack->length();
535
536 for ( $i = $fmtEltIndex + 1; $i < $stackLength; $i++ ) {
537 $item = $stack->item( $i );
538 if ( isset( HTMLData::SPECIAL[$item->namespace][$item->name] ) ) {
539 $furthestBlock = $item;
540 $furthestBlockIndex = $i;
541 break;
542 }
543 }
544
545 // If there is no furthest block, then the UA must skip the
546 // subsequent steps and instead just pop all the nodes from the
547 // bottom of the stack of open elements, from the current node up
548 // to and including the formatting element, and remove the
549 // formatting element from the list of active formatting
550 // elements. [10]
551 if ( !$furthestBlock ) {
552 $this->popAllUpToElement( $fmtElt, $sourceStart, $sourceLength );
553 $afe->remove( $fmtElt );
554 return;
555 }
556
557 // Let the common ancestor be the element immediately above the
558 // formatting element in the stack of open elements. [11]
559 $ancestor = $stack->item( $fmtEltIndex - 1 );
560
561 // Let a bookmark note the position of the formatting element in
562 // the list of active formatting elements relative to the elements
563 // on either side of it in the list. [12]
564 $bookmark = new Marker( 'bookmark' );
565 $afe->insertAfter( $fmtElt, $bookmark );
566
567 // Let node and last node be the furthest block. [13]
568 $lastNode = $furthestBlock;
569 $nodeIndex = $furthestBlockIndex;
570 $isAFE = false;
571 $stackRemovals = [];
572 $insertions = [];
573
574 // Inner loop
575 for ( $inner = 1; true; $inner++ ) {
576 // Let node be the element immediately above node in the stack
577 // of open elements, or if node is no longer in the stack of
578 // open elements (e.g. because it got removed by this
579 // algorithm), the element that was immediately above node in
580 // the stack of open elements before node was removed. [13.3]
581 $node = $stack->item( --$nodeIndex );
582
583 // If node is the formatting element, then go to the next step
584 // in the overall algorithm. [13.4]
585 if ( $node === $fmtElt ) {
586 break;
587 }
588
589 // If the inner loop counter is greater than three and node
590 // is in the list of active formatting elements, then remove
591 // node from the list of active formatting elements. [13.5]
592 $isAFE = $afe->isInList( $node );
593 if ( $inner > 3 && $isAFE ) {
594 $afe->remove( $node );
595 $isAFE = false;
596 }
597
598 // If node is not in the list of active formatting elements,
599 // then remove node from the stack of open elements and then
600 // go back to the step labeled inner loop. [13.6]
601 if ( !$isAFE ) {
602 $stackRemovals[$nodeIndex] = true;
603 continue;
604 }
605
606 // Create an element for the token for which the element node
607 // was created with common ancestor as the intended parent,
608 // replace the entry for node in the list of active formatting
609 // elements with an entry for the new element, replace the
610 // entry for node in the stack of open elements with an entry
611 // for the new element, and let node be the new element. [13.7]
612 $newElt = new Element(
613 $node->namespace, $node->name, $node->attrs->clone() );
614 $afe->replace( $node, $newElt );
615 $stack->replace( $node, $newElt );
616 $node = $newElt;
617
618 // If last node is the furthest block, then move the
619 // aforementioned bookmark to be immediately after the new node
620 // in the list of active formatting elements. [13.8]
621 if ( $lastNode === $furthestBlock ) {
622 $afe->remove( $bookmark );
623 $afe->insertAfter( $newElt, $bookmark );
624 }
625
626 // Insert last node into node, first removing it from its
627 // previous parent node if any. [13.9]
628 $insertions[] = [ self::UNDER, $node, $lastNode ];
629
630 // Let last node be node. [13.10]
631 $lastNode = $node;
632 }
633
634 // Insert whatever last node ended up being in the previous step at
635 // the appropriate place for inserting a node, but using common
636 // ancestor as the override target. [14]
637 [ $prep, $ref ] = $this->appropriatePlace( $ancestor );
638 $insertions[] = [ $prep, $ref, $lastNode ];
639
640 // Execute queued insertions in reverse order.
641 // This has the same effect but allows the handler to assume that
642 // elements are always in the tree.
643 for ( $i = count( $insertions ) - 1; $i >= 0; $i-- ) {
644 $ins = $insertions[$i];
645 $handler->insertElement( $ins[0], $ins[1], $ins[2], false, $sourceStart, 0 );
646 }
647
648 // Create an element for the token for which the formatting element
649 // was created, with furthest block as the intended parent. [15]
650 $newElt2 = new Element(
651 $fmtElt->namespace, $fmtElt->name, $fmtElt->attrs->clone() );
652
653 // Take all of the child nodes of the furthest block and append
654 // them to the element created in the last step. [16]
655 // Append the new element to the furthest block. [17]
656 $handler->reparentChildren( $furthestBlock, $newElt2, $sourceStart );
657
658 // Remove the formatting element from the list of active formatting
659 // elements, and insert the new element into the list of active
660 // formatting elements at the position of the aforementioned
661 // bookmark. [18]
662 $afe->remove( $fmtElt );
663 $afe->replace( $bookmark, $newElt2 );
664
665 // Remove the formatting element from the stack of open elements,
666 // and insert the new element into the stack of open elements
667 // immediately below the position of the furthest block in that
668 // stack. [19]
669
670 // Make a temporary stack with the elements we are going to push back in
671 $tempStack = [];
672
673 // Stash the elements up to the furthest block
674 for ( $index = $stack->length() - 1; $index > $furthestBlockIndex; $index-- ) {
675 $tempStack[] = $stack->pop();
676 }
677 // Add the new element
678 $tempStack[] = $newElt2;
679 // Stash the elements up to the formatting element
680 for ( 0; $index > $fmtEltIndex; $index-- ) {
681 $elt = $stack->pop();
682 // Drop elements previously marked for removal
683 if ( isset( $stackRemovals[$index] ) ) {
684 $handler->endTag( $elt, $sourceStart, 0 );
685 } else {
686 $tempStack[] = $elt;
687 }
688 }
689 // Remove the formatting element
690 $elt = $stack->pop();
691 $handler->endTag( $elt, $sourceStart, 0 );
692 // Reinsert
693 foreach ( array_reverse( $tempStack ) as $elt ) {
694 $stack->push( $elt );
695 }
696 }
697 }
698
699 /**
700 * Perform the steps required when "any other end tag" is encountered in
701 * the "in body" insertion mode.
702 *
703 * @param string $name
704 * @param int $sourceStart
705 * @param int $sourceLength
706 */
707 public function anyOtherEndTag( $name, $sourceStart, $sourceLength ) {
708 $stack = $this->stack;
709 for ( $index = $stack->length() - 1; $index >= 0; $index-- ) {
710 $node = $stack->item( $index );
711 if ( $node->htmlName === $name ) {
712 $this->generateImpliedEndTags( $name, $sourceStart );
713 // If node is not the current node, then this is a parse error
714 if ( $node !== $stack->current ) {
715 $this->error( 'end tag matched an element which was not the current node',
716 $sourceStart );
717 }
718 // Pop all the nodes from the current node up to node, including
719 // node, then stop these steps.
720 for ( $j = $stack->length() - 1; $j > $index; $j-- ) {
721 $elt = $stack->pop();
722 $this->handler->endTag( $elt, $sourceStart, 0 );
723 }
724 $elt = $stack->pop();
725 $this->handler->endTag( $elt, $sourceStart, $sourceLength );
726 return;
727 }
728
729 // If node is in the special category, then this is a parse error;
730 // ignore the token, and abort these steps
731 if ( isset( HTMLData::SPECIAL[$node->namespace][$node->name] ) ) {
732 $this->error( "cannot implicitly close a special element <{$node->htmlName}>",
733 $sourceStart );
734 return;
735 }
736 }
737 }
738
739 /**
740 * Generate implied end tags, optionally with an element to exclude.
741 *
742 * @param string|false $name The name to exclude
743 * @param int $pos The source position
744 */
745 public function generateImpliedEndTags( $name, $pos ) {
746 $stack = $this->stack;
747 $current = $stack->current;
748 while ( $current && $current->htmlName !== $name &&
749 isset( self::IMPLIED_END_TAGS[$current->htmlName] )
750 ) {
751 $popped = $stack->pop();
752 $this->handler->endTag( $popped, $pos, 0 );
753 $current = $stack->current;
754 }
755 }
756
757 /**
758 * Generate all implied end tags thoroughly. This was introduced in
759 * HTML 5.1 in order to expand the set of elements which can be implicitly
760 * closed by a </template>.
761 * @param int $pos
762 */
763 public function generateImpliedEndTagsThoroughly( $pos ) {
764 $stack = $this->stack;
765 $current = $stack->current;
766 while ( $current && isset( self::THOROUGHLY_IMPLIED_END_TAGS[$current->htmlName] ) ) {
767 $popped = $stack->pop();
768 $this->handler->endTag( $popped, $pos, 0 );
769 $current = $stack->current;
770 }
771 }
772
773 /**
774 * Generate implied end tags, with an element to exclude, and if the
775 * current element is not now the named excluded element, raise an error.
776 * Then, pop all elements until an element with the name is popped from
777 * the list.
778 *
779 * @param string $name The name to exclude
780 * @param int $sourceStart
781 * @param int $sourceLength
782 */
783 public function generateImpliedEndTagsAndPop( $name, $sourceStart, $sourceLength ) {
784 $this->generateImpliedEndTags( $name, $sourceStart );
785 if ( $this->stack->current->htmlName !== $name ) {
786 $this->error( "found </$name> but elements are open that cannot " .
787 "have implied end tags, closing them", $sourceStart );
788 }
789 $this->popAllUpToName( $name, $sourceStart, $sourceLength );
790 }
791
792 /**
793 * Pop elements from the stack until the specified element is popped.
794 *
795 * @param Element $elt
796 * @param int $sourceStart
797 * @param int $sourceLength
798 */
799 public function popAllUpToElement( Element $elt, $sourceStart, $sourceLength ) {
800 while ( true ) {
801 $popped = $this->stack->pop();
802 if ( !$popped ) {
803 break;
804 } elseif ( $popped === $elt ) {
805 $this->handler->endTag( $popped, $sourceStart, $sourceLength );
806 break;
807 } else {
808 $this->handler->endTag( $popped, $sourceStart, 0 );
809 }
810 }
811 }
812
813 /**
814 * Pop elements from the stack until an element in the HTML namespace with
815 * the specified name is popped.
816 *
817 * @param string $name
818 * @param int $sourceStart
819 * @param int $sourceLength
820 */
821 public function popAllUpToName( $name, $sourceStart, $sourceLength ) {
822 while ( true ) {
823 $popped = $this->stack->pop();
824 if ( !$popped ) {
825 break;
826 } elseif ( $popped->htmlName === $name ) {
827 $this->handler->endTag( $popped, $sourceStart, $sourceLength );
828 break;
829 } else {
830 $this->handler->endTag( $popped, $sourceStart, 0 );
831 }
832 }
833 }
834
835 /**
836 * Pop elements from the stack until an element with one of the specified
837 * names is popped.
838 *
839 * @param array $names An array with the allowed names in the keys
840 * @param int $sourceStart
841 * @param int $sourceLength
842 */
843 public function popAllUpToNames( $names, $sourceStart, $sourceLength ) {
844 while ( true ) {
845 $popped = $this->stack->pop();
846 if ( !$popped ) {
847 break;
848 } elseif ( isset( $names[$popped->htmlName] ) ) {
849 $this->handler->endTag( $popped, $sourceStart, $sourceLength );
850 break;
851 } else {
852 $this->handler->endTag( $popped, $sourceStart, 0 );
853 }
854 }
855 }
856
857 /**
858 * The "clear stack back to" algorithm used by several template insertion
859 * modes. Similar to popAllUpToName(), except that the named element is
860 * not popped, and a set of names is used instead of a single name.
861 *
862 * @param array $names
863 * @param int $pos
864 */
865 public function clearStackBack( $names, $pos ) {
866 $stack = $this->stack;
867 while ( $stack->current && !isset( $names[$stack->current->htmlName] ) ) {
868 $this->pop( $pos, 0 );
869 }
870 if ( !$stack->current ) {
871 throw new TreeBuilderError( 'clearStackBack: stack is unexpectedly empty' );
872 }
873 }
874
875 /**
876 * Take the steps required when the spec says to "stop parsing". This
877 * occurs when an end-of-file token is received, and is equivalent to
878 * the endDocument() methods elsewhere.
879 *
880 * @param int $pos
881 */
882 public function stopParsing( $pos ) {
883 $stack = $this->stack;
884 while ( $stack->current ) {
885 $popped = $stack->pop();
886 if ( !$this->isFragment || $popped->htmlName !== 'html' ) {
887 $this->handler->endTag( $popped, $pos, 0 );
888 }
889 }
890 $this->handler->endDocument( $pos );
891
892 $this->afe = new ActiveFormattingElements;
893 $this->headElement = null;
894 $this->formElement = null;
895 $this->tokenizer->setEnableCdataCallback( null );
896 // @phan-suppress-next-line PhanTypeMismatchPropertyProbablyReal clearing ref
897 $this->tokenizer = null;
898 }
899 }