Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 205
0.00% covered (danger)
0.00%
0 / 16
CRAP
0.00% covered (danger)
0.00%
0 / 1
ParagraphWrapper
0.00% covered (danger)
0.00%
0 / 205
0.00% covered (danger)
0.00%
0 / 16
8742
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 onNewline
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 onEnd
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 onCompoundTk
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
30
 reset
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
 resetBuffers
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 resetCurrLine
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 processBuffers
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 flushBuffers
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
2
 processOneNlTk
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 openPTag
0.00% covered (danger)
0.00%
0 / 20
0.00% covered (danger)
0.00%
0 / 1
132
 closeOpenPTag
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
132
 onNewlineOrEOF
0.00% covered (danger)
0.00%
0 / 20
0.00% covered (danger)
0.00%
0 / 1
72
 processPendingNLs
0.00% covered (danger)
0.00%
0 / 29
0.00% covered (danger)
0.00%
0 / 1
110
 undoIndentPre
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
56
 onAny
0.00% covered (danger)
0.00%
0 / 51
0.00% covered (danger)
0.00%
0 / 1
812
1<?php
2declare( strict_types = 1 );
3
4namespace Wikimedia\Parsoid\Wt2Html\TT;
5
6use Wikimedia\Assert\Assert;
7use Wikimedia\Assert\UnreachableException;
8use Wikimedia\Parsoid\Tokens\CommentTk;
9use Wikimedia\Parsoid\Tokens\CompoundTk;
10use Wikimedia\Parsoid\Tokens\EmptyLineTk;
11use Wikimedia\Parsoid\Tokens\EndTagTk;
12use Wikimedia\Parsoid\Tokens\EOFTk;
13use Wikimedia\Parsoid\Tokens\IndentPreTk;
14use Wikimedia\Parsoid\Tokens\ListTk;
15use Wikimedia\Parsoid\Tokens\NlTk;
16use Wikimedia\Parsoid\Tokens\SelfclosingTagTk;
17use Wikimedia\Parsoid\Tokens\TagTk;
18use Wikimedia\Parsoid\Tokens\Token;
19use Wikimedia\Parsoid\Tokens\XMLTagTk;
20use Wikimedia\Parsoid\Utils\PHPUtils;
21use Wikimedia\Parsoid\Utils\TokenUtils;
22use Wikimedia\Parsoid\Utils\WTUtils;
23use Wikimedia\Parsoid\Wikitext\Consts;
24use Wikimedia\Parsoid\Wt2Html\TokenHandlerPipeline;
25
26/**
27 * Insert paragraph tags where needed -- smartly and carefully
28 * -- there is much fun to be had mimicking "wikitext visual newlines"
29 * behavior as implemented by the PHP parser.
30 */
31class ParagraphWrapper extends LineBasedHandler {
32
33    private bool $hasOpenPTag = false;
34    private bool $inBlockElem = false;
35    private bool $inBlockquote = false;
36
37    private array $tokenBuffer = [];
38    private array $nlWsTokens = [];
39    private int $newLineCount = 0;
40
41    private array $currLineTokens = [];
42    private bool $currLineHasWrappableTokens = false;
43    private bool $currLineBlockTagSeen = false;
44    private bool $currLineBlockTagOpen = false;
45
46    /**
47     * Constructor for paragraph wrapper.
48     * @param TokenHandlerPipeline $manager manager enviroment
49     * @param array $options various configuration options
50     */
51    public function __construct( TokenHandlerPipeline $manager, array $options ) {
52        parent::__construct( $manager, $options );
53        // Disable p-wrapper
54        $this->disabled = !empty( $this->options['inlineContext'] );
55        $this->reset();
56    }
57
58    /**
59     * @inheritDoc
60     */
61    public function onNewline( NlTk $token ): ?array {
62        return $this->onNewlineOrEOF( $token );
63    }
64
65    /**
66     * @inheritDoc
67     */
68    public function onEnd( EOFTk $token ): ?array {
69        return $this->onNewlineOrEOF( $token );
70    }
71
72    /**
73     * Pass through the tokens unchanged.
74     *
75     * @inheritDoc
76     */
77    public function onCompoundTk( CompoundTk $ctk, TokenHandler $tokensHandler ): ?array {
78        if ( $ctk instanceof ListTk ) {
79            if ( $ctk->isDLDDList() ) {
80                return $tokensHandler->process( $ctk->getNestedTokens() );
81            } else {
82                return null;
83            }
84        } elseif ( $ctk instanceof IndentPreTk || $ctk instanceof EmptyLineTk ) {
85            return null;
86        } else {
87            throw new UnreachableException(
88                "ParagraphWrapper: Unsupported compound token."
89            );
90        }
91    }
92
93    /**
94     * Reset the token buffer and related info
95     * This is the ordering of buffered tokens and how they should get emitted:
96     *
97     * token-buffer         (from previous lines if newLineCount > 0)
98     * newline-ws-tokens    (buffered nl+sol-transparent tokens since last non-nl-token)
99     * current-line-tokens  (all tokens after newline-ws-tokens)
100     *
101     * newline-token-count is > 0 only when we encounter multiple "empty lines".
102     *
103     * Periodically, when it is clear where an open/close p-tag is required, the buffers
104     * are collapsed and emitted. Wherever tokens are buffered/emitted, verify that this
105     *  order is preserved.
106     */
107    private function reset(): void {
108        $this->resetBuffers();
109        $this->resetCurrLine();
110        $this->hasOpenPTag = false;
111        // NOTE: This flag is the local equivalent of what we're mimicking with
112        // the 'inlineContext' pipeline option.
113        $this->inBlockElem = false;
114        $this->inBlockquote = false;
115    }
116
117    /**
118     * Reset the token buffer and new line info
119     */
120    private function resetBuffers(): void {
121        $this->tokenBuffer = [];
122        $this->nlWsTokens = [];
123        $this->newLineCount = 0;
124    }
125
126    /**
127     * Reset the current line info
128     */
129    private function resetCurrLine(): void {
130        if ( $this->currLineBlockTagSeen ) {
131            $this->inBlockElem = $this->currLineBlockTagOpen;
132        }
133        $this->currLineTokens = [];
134        $this->currLineHasWrappableTokens = false;
135        $this->currLineBlockTagSeen = false;
136        $this->currLineBlockTagOpen = false;
137    }
138
139    /**
140     * Process the current buffer contents and token provided
141     *
142     * @param Token|string $token token
143     * @param bool $flushCurrentLine option to flush current line or preserve it
144     * @return array<string|Token>
145     */
146    private function processBuffers( $token, bool $flushCurrentLine ): array {
147        $res = $this->processPendingNLs();
148        $this->currLineTokens[] = $token;
149        if ( $flushCurrentLine ) {
150            PHPUtils::pushArray( $res, $this->currLineTokens );
151            $this->resetCurrLine();
152        }
153        $this->env->trace( 'p-wrap', $this->pipelineId, '---->  ', $res );
154        return $res;
155    }
156
157    /**
158     * Process and flush existing buffer contents
159     *
160     * @param Token|string $token token
161     * @return array<string|Token>
162     */
163    private function flushBuffers( $token ): array {
164        Assert::invariant( $this->newLineCount === 0, "PWrap: Trying to flush buffers with pending newlines" );
165
166        $this->currLineTokens[] = $token;
167        // Juggle the array reference count to allow us to append to it without
168        // copying the array
169        $resToks = $this->tokenBuffer;
170        $nlWsTokens = $this->nlWsTokens;
171        $this->resetBuffers();
172        PHPUtils::pushArray( $resToks, $nlWsTokens );
173        $this->env->trace( 'p-wrap', $this->pipelineId, '---->  ', $resToks );
174        return $resToks;
175    }
176
177    /**
178     * Append tokens from the newline/whitespace buffer to the output array
179     * until a newline is encountered. Increment the offset reference. Return
180     * the newline token.
181     *
182     * @param array &$out array to append to
183     * @param int &$offset The offset reference to update
184     * @return NlTk
185     */
186    public function processOneNlTk( array &$out, &$offset ) {
187        $n = count( $this->nlWsTokens );
188        while ( $offset < $n ) {
189            $t = $this->nlWsTokens[$offset++];
190            if ( $t instanceof NlTk ) {
191                return $t;
192            } else {
193                $out[] = $t;
194            }
195        }
196        throw new UnreachableException( 'nlWsTokens was expected to contain an NlTk.' );
197    }
198
199    /**
200     * Search for the opening paragraph tag
201     *
202     * @param array &$out array to process and update
203     */
204    private function openPTag( array &$out ): void {
205        if ( !$this->hasOpenPTag ) {
206            $tplStartIndex = -1;
207            // Be careful not to expand template ranges unnecessarily.
208            // Look for open markers before starting a p-tag.
209            $countOut = count( $out );
210            for ( $i = 0; $i < $countOut; $i++ ) {
211                $t = $out[$i];
212                if ( ( $t instanceof XMLTagTk ) && $t->getName() === 'meta' ) {
213                    if ( TokenUtils::hasTypeOf( $t, 'mw:Transclusion' ) ) {
214                        // We hit a start tag and everything before it is sol-transparent.
215                        $tplStartIndex = $i;
216                        continue;
217                    } elseif ( TokenUtils::matchTypeOf( $t, '#^mw:Transclusion/#' ) ) {
218                        // End tag. All tokens before this are sol-transparent.
219                        // Let us leave them all out of the p-wrapping.
220                        $tplStartIndex = -1;
221                        continue;
222                    } elseif ( TokenUtils::isAnnotationStartToken( $t ) ) {
223                        break;
224                    }
225                }
226                // Not a transclusion meta; Check for nl/sol-transparent tokens
227                // and leave them out of the p-wrapping.
228                if ( !TokenUtils::isSolTransparent( $this->env, $t ) && !( $t instanceof NlTk ) ) {
229                    break;
230                }
231            }
232            if ( $tplStartIndex > -1 ) {
233                $i = $tplStartIndex;
234            }
235            array_splice( $out, $i, 0, [ new TagTk( 'p' ) ] );
236            $this->hasOpenPTag = true;
237        }
238    }
239
240    /**
241     * Search for the closing paragraph tag
242     *
243     * @param array &$out array to process and update
244     */
245    private function closeOpenPTag( array &$out ): void {
246        if ( $this->hasOpenPTag ) {
247            $tplEndIndex = -1;
248            // Be careful not to expand template ranges unnecessarily.
249            // Look for open markers before closing.
250            for ( $i = count( $out ) - 1; $i > -1; $i-- ) {
251                $t = $out[$i];
252                if ( ( $t instanceof XMLTagTk ) && $t->getName() === 'meta' ) {
253                    if ( TokenUtils::hasTypeOf( $t, 'mw:Transclusion' ) ) {
254                        // We hit a start tag and everything after it is sol-transparent.
255                        // Don't include the sol-transparent tags OR the start tag.
256                        $tplEndIndex = -1;
257                        continue;
258                    } elseif ( TokenUtils::matchTypeOf( $t, '#^mw:Transclusion/#' ) ) {
259                        // End tag. The rest of the tags past this are sol-transparent.
260                        // Let us leave them all out of the p-wrapping.
261                        $tplEndIndex = $i;
262                        continue;
263                    } elseif ( TokenUtils::isAnnotationEndToken( $t ) ) {
264                        break;
265                    }
266                }
267                // Not a transclusion meta; Check for nl/sol-transparent tokens
268                // and leave them out of the p-wrapping.
269                if ( !TokenUtils::isSolTransparent( $this->env, $t ) && !( $t instanceof NlTk ) ) {
270                    break;
271                }
272            }
273            if ( $tplEndIndex > -1 ) {
274                $i = $tplEndIndex;
275            }
276            array_splice( $out, $i + 1, 0, [ new EndTagTk( 'p' ) ] );
277            $this->hasOpenPTag = false;
278        }
279    }
280
281    /**
282     * Handle newline tokens
283     * @return array<string|Token>
284     */
285    private function onNewlineOrEOF( Token $token ): array {
286        $this->env->trace( 'p-wrap', $this->pipelineId, 'NL    |', $token );
287        if ( $this->currLineBlockTagSeen ) {
288            $this->closeOpenPTag( $this->currLineTokens );
289        } elseif ( !$this->inBlockElem && !$this->hasOpenPTag && $this->currLineHasWrappableTokens ) {
290            $this->openPTag( $this->currLineTokens );
291        }
292
293        // Assertion to catch bugs in p-wrapping; both cannot be true.
294        if ( $this->newLineCount > 0 && count( $this->currLineTokens ) > 0 ) {
295            $this->env->log( 'error/p-wrap', 'Failed assertion in onNewlineOrEOF: newline-count:',
296                $this->newLineCount, '; current line tokens: ', $this->currLineTokens );
297        }
298
299        PHPUtils::pushArray( $this->tokenBuffer, $this->currLineTokens );
300
301        if ( $token instanceof EOFTk ) {
302            $this->nlWsTokens[] = $token;
303            $this->closeOpenPTag( $this->tokenBuffer );
304            $res = $this->processPendingNLs();
305            $this->reset();
306            $this->env->trace( 'p-wrap', $this->pipelineId, '---->  ', $res );
307            return $res;
308        } else {
309            $this->resetCurrLine();
310            $this->newLineCount++;
311            $this->nlWsTokens[] = $token;
312            return [];
313        }
314    }
315
316    /**
317     * Process pending newlines
318     *
319     * @return array<string|Token>
320     */
321    private function processPendingNLs(): array {
322        $resToks = $this->tokenBuffer;
323        $newLineCount = $this->newLineCount;
324        $nlOffset = 0;
325
326        $this->env->trace( 'p-wrap', $this->pipelineId, '        NL-count:', $newLineCount );
327
328        if ( $newLineCount >= 2 && !$this->inBlockElem ) {
329            $this->closeOpenPTag( $resToks );
330
331            // First is emitted as a literal newline
332            $resToks[] = $this->processOneNlTk( $resToks, $nlOffset );
333            $newLineCount -= 1;
334
335            $remainder = $newLineCount % 2;
336
337            while ( $newLineCount > 0 ) {
338                $nlTk = $this->processOneNlTk( $resToks, $nlOffset );
339                if ( $newLineCount % 2 === $remainder ) {
340                    if ( $this->hasOpenPTag ) {
341                        $resToks[] = new EndTagTk( 'p' );
342                        $this->hasOpenPTag = false;
343                    }
344                    if ( $newLineCount > 1 ) {
345                        $resToks[] = new TagTk( 'p' );
346                        $this->hasOpenPTag = true;
347                    }
348                } else {
349                    $resToks[] = new SelfclosingTagTk( 'br' );
350                }
351                $resToks[] = $nlTk;
352                $newLineCount -= 1;
353            }
354        }
355
356        if ( $this->currLineBlockTagSeen ) {
357            $this->closeOpenPTag( $resToks );
358            if ( $newLineCount === 1 ) {
359                $resToks[] = $this->processOneNlTk( $resToks, $nlOffset );
360            }
361        }
362
363        // Gather remaining ws and nl tokens
364        for ( $i = $nlOffset; $i < count( $this->nlWsTokens ); $i++ ) {
365            $resToks[] = $this->nlWsTokens[$i];
366        }
367
368        // reset buffers
369        $this->resetBuffers();
370
371        return $resToks;
372    }
373
374    private function undoIndentPre( IndentPreTk $ipre ): array {
375        $ret = $this->newLineCount === 0 ? $this->flushBuffers( '' ) : [];
376
377        $this->env->trace( 'p-wrap', $this->pipelineId, '---- UNDOING PRE ----' );
378        $nestedTokens = $ipre->getNestedTokens();
379        $n = count( $nestedTokens );
380        $i = 1; // skip the <pre>
381        while ( $i < $n ) {
382            $token = $nestedTokens[$i];
383            if ( PreHandler::isIndentPreWS( $token ) ) {
384                $this->nlWsTokens[] = ' ';
385            } elseif ( $token instanceof NlTk ) {
386                PHPUtils::pushArray( $ret, $this->onNewlineOrEOF( $token ) );
387            } elseif ( $token instanceof EndTagTk && $token->getName() === 'pre' ) {
388                // Skip </pre>
389                // There may be other tokens after this in cases where
390                // tags are unbalanced in the input.
391            } else {
392                PHPUtils::pushArray( $ret, $this->onAny( $token ) );
393            }
394
395            $i++;
396        }
397
398        $this->env->trace( 'p-wrap', $this->pipelineId, '---- DONE UNDOING PRE ----' );
399        return $ret;
400    }
401
402    /**
403     * @inheritDoc
404     */
405    public function onAny( $token ): ?array {
406        $this->env->trace( 'p-wrap', $this->pipelineId, 'ANY   |', $token );
407        $tokenName = ( $token instanceof XMLTagTk ) ? $token->getName() : '';
408
409        // The conditions in TokenUtils::isSolTransparent are split between
410        // the following two blocks since certain SOL constructs swallow a
411        // newline and others do not
412
413        // 1. Inline some of the conditions of TokenUtils::isSolTransparent
414        if (
415            ( is_string( $token ) && preg_match( '/^[\t ]*$/D', $token ) ) ||
416            $token instanceof EmptyLineTk ||
417            $token instanceof CommentTk ||
418            TokenUtils::isBehaviorSwitch( $this->env, $token )
419        ) {
420            if ( $this->newLineCount === 0 ) {
421                // Since we have no pending newlines to trip us up,
422                // no need to buffer -- just flush everything
423                return $this->flushBuffers( $token );
424            } else {
425                // We are in buffering mode waiting till we are ready to
426                // process pending newlines.
427                $this->nlWsTokens[] = $token;
428                return [];
429            }
430        }
431
432        // 2. Inline the rest of the conditions of TokenUtils::isSolTransparent
433        if (
434            TokenUtils::isSolTransparentLinkTag( $token ) ||
435            // FIXME: We decided not to do template boundaries in T355099
436            // but do any other metas belong above?
437            (
438                $tokenName === 'meta' &&
439                $token instanceof SelfclosingTagTk &&
440                !WTUtils::hasLiteralHTMLMarker( $token->dataParsoid )
441            ) ||
442            // T186965: <style> behaves similarly to sol transparent tokens in
443            // that it doesn't open/close paragraphs, but also doesn't induce
444            // a new paragraph by itself.
445            $tokenName === 'style'
446        ) {
447            if ( $this->newLineCount === 0 ) {
448                // Since we have no pending newlines to trip us up,
449                // no need to buffer -- just flush everything
450                return $this->flushBuffers( $token );
451            } elseif ( $this->newLineCount === 1 ) {
452                // Swallow newline, whitespace, comments, and the current line
453                PHPUtils::pushArray( $this->tokenBuffer, $this->nlWsTokens );
454                PHPUtils::pushArray( $this->tokenBuffer, $this->currLineTokens );
455                $this->newLineCount = 0;
456                $this->nlWsTokens = [];
457                $this->resetCurrLine();
458
459                // But, don't process the new token yet.
460                $this->currLineTokens[] = $token;
461                return [];
462            } else {
463                return $this->processBuffers( $token, false );
464            }
465        }
466
467        if ( is_string( $token ) ) {
468            $this->currLineHasWrappableTokens = true;
469            return $this->processBuffers( $token, false );
470        }
471
472        // Skip the entire list token - dont process nested tokens
473        if ( $token instanceof ListTk ) {
474            $this->currLineBlockTagSeen = true;
475            return $this->processBuffers( $token, true );
476        }
477
478        // Skip the entire indent-pre token - dont process nested tokens
479        // But, if nested in blockquote, process specially
480        if ( $token instanceof IndentPreTk ) {
481            if ( $this->inBlockElem || $this->inBlockquote ) {
482                // The state machine in the PreHandler is line based and only suppresses
483                // indent-pres when encountering blocks on a line.  However, the legacy
484                // parser's `doBlockLevels` has a concept of being "$inBlockElem", which
485                // is mimicked here.  Rather than replicate that awareness in both passes,
486                // we piggyback on it here to undo indent-pres when they're found to be
487                // undesirable.
488                return $this->undoIndentPre( $token );
489            } else {
490                $this->currLineBlockTagSeen = true;
491                return $this->processBuffers( $token, true );
492            }
493        }
494
495        if ( $token instanceof EOFTk ) {
496            $this->env->log( 'trace/p-wrap', $this->pipelineId, '---->   ', $token );
497            return null;
498        }
499
500        if ( isset( Consts::$wikitextBlockElems[$tokenName] ) ) {
501            $this->currLineBlockTagSeen = true;
502            $this->currLineBlockTagOpen = true;
503            if (
504                ( isset( Consts::$blockElems[$tokenName] ) && $token instanceof EndTagTk ) ||
505                ( isset( Consts::$antiBlockElems[$tokenName] ) && !$token instanceof EndTagTk ) ||
506                isset( Consts::$neverBlockElems[$tokenName] )
507            ) {
508                $this->currLineBlockTagOpen = false;
509            }
510        }
511
512        if ( $tokenName === 'blockquote' ) {
513            $this->inBlockquote = !( $token instanceof EndTagTk );
514        }
515
516        $this->currLineHasWrappableTokens = true;
517        return $this->processBuffers( $token, false );
518    }
519}