-
Notifications
You must be signed in to change notification settings - Fork 53
/
Grammar.pegphp
2617 lines (2386 loc) · 80.2 KB
/
Grammar.pegphp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Combined Wiki (MediaWiki) and HTML tokenizer based on pegjs. Emits several
* chunks of tokens (one chunk per top-level block matched) and eventually an
* end event. Tokens map to HTML tags as far as possible, with custom tokens
* used where further processing on the token stream is needed.
*/
{
use Wikimedia\Assert\UnreachableException;
use Wikimedia\JsonCodec\JsonCodec;
use Wikimedia\Parsoid\Config\Env;
use Wikimedia\Parsoid\Config\SiteConfig;
use Wikimedia\Parsoid\Core\DomSourceRange;
use Wikimedia\Parsoid\NodeData\DataMw;
use Wikimedia\Parsoid\NodeData\DataParsoid;
use Wikimedia\Parsoid\NodeData\TempData;
use Wikimedia\Parsoid\Tokens\CommentTk;
use Wikimedia\Parsoid\Tokens\EOFTk;
use Wikimedia\Parsoid\Tokens\EndTagTk;
use Wikimedia\Parsoid\Tokens\KV;
use Wikimedia\Parsoid\Tokens\KVSourceRange;
use Wikimedia\Parsoid\Tokens\NlTk;
use Wikimedia\Parsoid\Tokens\SelfclosingTagTk;
use Wikimedia\Parsoid\Tokens\SourceRange;
use Wikimedia\Parsoid\Tokens\TagTk;
use Wikimedia\Parsoid\Tokens\Token;
use Wikimedia\Parsoid\Utils\DOMDataUtils;
use Wikimedia\Parsoid\Utils\PHPUtils;
use Wikimedia\Parsoid\Utils\TokenUtils;
use Wikimedia\Parsoid\Utils\Utils;
use Wikimedia\Parsoid\Utils\WTUtils;
use Wikimedia\Parsoid\Wikitext\Consts;
}
{
/** @var Env */
private $env;
/** @var SiteConfig */
private $siteConfig;
/** @var array */
private $pipelineOpts;
/** @var int */
private $pipelineOffset;
private $extTags;
private $startTime;
/** @var string */
private $reUrltextLookahead;
/** @var string */
private $urltextPlainSegment = '';
/** @var bool */
private $urltextFoundAutolink = false;
protected function initialize() {
$this->env = $this->options['env'];
$this->siteConfig = $this->env->getSiteConfig();
$tokenizer = $this->options['pegTokenizer'];
$this->pipelineOpts = $tokenizer->getOptions();
// FIXME: inTemplate option may not always be set in
// standalone tokenizers user by some pipelines handlers.
$this->pipelineOffset = $this->options['pipelineOffset'] ?? 0;
$this->extTags = $this->siteConfig->getExtensionTagNameMap();
// Non-greedy text_char sequence: stop at ampersand, double-underscore,
// magic link prefix or protocol
$this->reUrltextLookahead = '!(?:' .
'([^-\'<[{\n\r:;\]}|\!=&]*?)' .
'(?:__|$|[-\'<[{\n\r:;\]}|\!=&]|(RFC|PMID|ISBN|' .
'(?i)' . $this->siteConfig->getProtocolsRegex( true ) .
')))!A';
}
private $prevOffset = 0;
private $headingIndex = 0;
public function resetState() {
$this->prevOffset = 0;
$this->headingIndex = 0;
}
private function assert( $condition, $text ) {
if ( !$condition ) {
throw new \RuntimeException( "Grammar.pegphp assertion failure: $text" );
}
}
private function unreachable() {
throw new UnreachableException( "Grammar.pegphp: this should be unreachable" );
}
// Some shorthands for legibility
private function startOffset() {
return $this->savedPos;
}
private function endOffset() {
return $this->currPos;
}
private function tsrOffsets( $flag = 'default' ): SourceRange {
switch ( $flag ) {
case 'start':
return new SourceRange( $this->savedPos, $this->savedPos );
case 'end':
return new SourceRange( $this->currPos, $this->currPos );
default:
return new SourceRange( $this->savedPos, $this->currPos );
}
}
/*
* Emit a chunk of tokens to our consumers. Once this has been done, the
* current expression can return an empty list (true).
*/
private function emitChunk( $tokens ) {
// FIXME: We don't expect nulls here, but looks like
// hack from I1c695ab6cdd3655e98877c175ddbabdee9dc44b7
// introduces them. Work around it for now!
if ( !$tokens ) {
return [];
}
// Shift tsr of all tokens by the pipeline offset
TokenUtils::shiftTokenTSR( $tokens, $this->pipelineOffset );
$this->env->log( 'trace/peg', $this->options['pipelineId'] ?? '0', '----> ', $tokens );
$i = null;
$n = count( $tokens );
// Enforce parsing resource limits
for ( $i = 0; $i < $n; $i++ ) {
TokenizerUtils::enforceParserResourceLimits( $this->env, $tokens[ $i ] );
}
return $tokens;
}
/* ------------------------------------------------------------------------
* Extension tags should be parsed with higher priority than anything else.
*
* The trick we use is to strip out the content inside a matching tag-pair
* and not tokenize it. The content, if it needs to parsed (for example,
* for <ref>, <*include*> tags), is parsed in a fresh tokenizer context
* which means any error correction that needs to happen is restricted to
* the scope of the extension content and doesn't spill over to the higher
* level. Ex: <math><!--foo</math>.
*
* IGNORE: {{ this just balances the blocks in this comment for pegjs
*
* This trick also lets us prevent extension content (that don't accept WT)
* from being parsed as wikitext (Ex: <math>\frac{foo\frac{bar}}</math>)
* We don't want the "}}" being treated as a template closing tag and
* closing outer templates.
* --------------------------------------------------------------------- */
private function isXMLTag( string $name ): bool {
$lName = mb_strtolower( $name );
return isset( Consts::$HTML['HTML5Tags'][$lName] ) ||
isset( Consts::$HTML['OlderHTMLTags'][$lName] );
}
private function maybeAnnotationOrExtensionTag( Token $t, ?bool $end, array $attribs, SourceRange $tsr ) {
$tagName = mb_strtolower( $t->getName() );
$isAnnotationTag = $this->siteConfig->isAnnotationTag( $tagName );
if ( !$isAnnotationTag ) {
$pipepos = strpos( $tagName, '|' );
if ( $pipepos ) {
$strBeforePipe = substr( $tagName, 0, $pipepos );
$isAnnotationTag = $this->siteConfig->isAnnotationTag( $strBeforePipe );
if ( $isAnnotationTag ) {
$attribs = [ new KV( "name", substr( $tagName, $pipepos + 1, strlen( $tagName ) - $pipepos - 1 ) ) ];
$tagName = $strBeforePipe;
}
}
}
if ( $isAnnotationTag ) {
$metaAttrs = [ new KV( 'typeof', 'mw:Annotation/' . $tagName . ($end ? '/End' : '') ) ];
$datamw = null;
if ( count( $attribs ) > 0 ) {
$attrMap = [];
foreach ( $attribs as $attr ) {
// If the key or the value is not a string, we replace it by the thing that generated it and
// consider that wikitext as a raw string instead.
$k = is_string( $attr->k ) ? $attr->k : $attr->ksrc;
$v = is_string( $attr->v ) ? $attr->v : $attr->vsrc;
$attrMap[$k] = $v;
}
// Possible follow-up in T295168 for attribute sanitation
// T367616: 'attrs' should be renamed to 'extAttrs'
$datamw = new DataMw( [ 'attrs' => (object)$attrMap ] );
}
$dp = new DataParsoid();
$dp->tsr = $tsr;
$this->env->hasAnnotations = true;
// FIXME: Suppress annotation meta tokens from template pipelines
// since they may not have TSR values and won't get recognized as
// annotation ranges. Without TSR, they might end up stuck in
// fosterable positions and cause havoc on edits by breaking selser.
if ( empty( $this->pipelineOpts['inTemplate'] ) ) {
return [ new SelfclosingTagTk ( 'meta', $metaAttrs, $dp, $datamw ) ];
} else {
return [];
}
}
$isInstalledExt = isset( $this->extTags[$tagName] );
$isIncludeTag = WTUtils::isIncludeTag( $tagName );
// Extensions have higher precedence when they shadow html tags.
if ( !( $isInstalledExt || $isIncludeTag ) ) {
return $t;
}
$dp = $t->dataParsoid;
$skipPos = $this->currPos;
switch ( get_class( $t ) ) {
case EndTagTk::class:
if ( $isIncludeTag ) {
return $t;
}
// Similar to TagTk, we rely on the sanitizer to convert to text
// where necessary and emit tokens to ease the wikitext escaping
// code. However, extension tags that shadow html tags will see
// their unmatched end tags dropped while tree building, since
// the sanitizer will let them through.
return $t; // not text()
case SelfclosingTagTk::class:
$dp->src = $dp->tsr->substr( $this->input );
$dp->extTagOffsets = new DomSourceRange(
$dp->tsr->start, $dp->tsr->end,
$dp->tsr->length(), 0
);
if ( $isIncludeTag ) {
return $t;
}
break;
case TagTk::class:
$endTagRE = '~.*?(</' . preg_quote( $tagName, '~' ) . '\s*>)~iusA';
$tagContentFound = preg_match( $endTagRE, $this->input, $tagContent, 0, $dp->tsr->start );
if ( !$tagContentFound ) {
$dp->src = $dp->tsr->substr( $this->input );
$dp->extTagOffsets = new DomSourceRange(
$dp->tsr->start, $dp->tsr->end,
$dp->tsr->length(), 0
);
if ( $isIncludeTag ) {
return $t;
} else {
// This is undefined behaviour. The old parser currently
// returns text here (see core commit 674e8388cba),
// whereas this results in unclosed
// extension tags that shadow html tags falling back to
// their html equivalent. The sanitizer will take care
// of converting to text where necessary. We do this to
// simplify `hasWikitextTokens` when escaping wikitext,
// which wants these as tokens because it's otherwise
// lacking in context.
return $t; // not text()
}
}
$extSrc = $tagContent[0];
$extEndOffset = $dp->tsr->start + strlen( $extSrc );
$extEndTagWidth = strlen( $tagContent[1] );
if ( !empty( $this->pipelineOpts['inTemplate'] ) ) {
// Support nesting in extensions tags while tokenizing in templates
// to support the #tag parser function.
//
// It's necessary to permit this broadly in templates because
// there's no way to distinguish whether the nesting happened
// while expanding the #tag parser function, or just a general
// syntax errors. In other words,
//
// hi<ref>ho<ref>hi</ref>ho</ref>
//
// and
//
// hi{{#tag:ref|ho<ref>hi</ref>ho}}
//
// found in template are returned indistinguishably after a
// preprocessing request, though the old parser renders them
// differently. #tag in template is probably a common enough
// use case that we want to accept these false positives,
// though another approach could be to drop this code here, and
// invoke a native #tag handler and forgo those in templates.
//
// Expand `extSrc` as long as there is a <tagName> found in the
// extension source body.
$startTagRE = '~<' . preg_quote( $tagName, '~' ) . '(?:[^/>]|/(?!>))*>~i';
$s = substr( $extSrc, $dp->tsr->end - $dp->tsr->start );
$openTags = 0;
while ( true ) {
if ( preg_match_all( $startTagRE, $s, $matches ) ) {
$openTags += count( $matches[0] );
}
if ( !$openTags ) {
break;
}
if ( !preg_match( $endTagRE, $this->input, $tagContent, 0, $extEndOffset ) ) {
break;
}
$openTags -= 1;
$s = $tagContent[0];
$extEndOffset += strlen( $s );
$extEndTagWidth = strlen( $tagContent[1] );
$extSrc .= $s;
}
}
// Extension content source
$dp->src = $extSrc;
$dp->extTagOffsets = new DomSourceRange(
$dp->tsr->start, $extEndOffset,
$dp->tsr->length(), $extEndTagWidth
);
$skipPos = $dp->extTagOffsets->innerEnd();
// If the xml-tag is a known installed (not native) extension,
// skip the end-tag as well.
if ( $isInstalledExt ) {
$skipPos = $dp->extTagOffsets->end;
}
break;
default:
$this->unreachable();
}
$this->currPos = $skipPos;
if ( $isInstalledExt ) {
// update tsr->end to span the start and end tags.
$dp->tsr->end = $this->endOffset(); // was just modified above
return new SelfclosingTagTk( 'extension', [
new KV( 'typeof', 'mw:Extension' ),
new KV( 'name', $tagName ),
new KV( 'about', $this->env->newAboutId() ),
new KV( 'source', $dp->src ),
new KV( 'options', $t->attribs )
], $dp
);
} elseif ( $isIncludeTag ) {
// Parse ext-content, strip eof, and shift tsr
$extContent = $dp->extTagOffsets->stripTags( $dp->src );
$tokenizer = new PegTokenizer( $this->env );
$tokenizer->setSourceOffsets( new SourceRange( $dp->extTagOffsets->innerStart(), $dp->extTagOffsets->innerEnd() ) );
$extContentToks = $tokenizer->tokenizeSync( $extContent );
if ( $dp->extTagOffsets->closeWidth > 0 ) {
TokenUtils::stripEOFTkFromTokens( $extContentToks );
}
array_unshift( $extContentToks, $t );
return $extContentToks;
} else {
$this->unreachable();
}
}
}
/* ********************************************************
* "start" is the top-level start rule
*
* Other allowed start rules:
* - table_start_tag
* - url
* - row_syntax_table_args
* - table_attributes
* - generic_newline_attributes
* - tplarg_or_template_or_bust
* - extlink
* - list_item
*
* These start rules are listed in lib/wt2html/tokenizer.js
* and is used during PEG grammar compilation.
* ******************************************************** */
start "start" =
t:tlb* n:newlineToken* {
if ( count( $t ) ) {
$ret = TokenizerUtils::flattenIfArray( $t );
} else {
$ret = [];
}
if ( count( $n ) ) {
PHPUtils::pushArray($ret, $n);
}
$ret[] = new EOFTk();
return $ret;
}
generic_newline_attributes "generic_newline_attributes" = generic_newline_attribute*
table_attributes "table_attributes" =
(table_attribute / optionalSpaceToken b:broken_table_attribute_name_char { return $b; })*
/*
* This rule exists to support tokenizing the document in chunks.
* The parser's streaming interface will stop tokenization after each iteration
* of the starred subexpression, and yield to the node.js event-loop to
* schedule other pending event handlers.
*/
start_async =
(
(
& {
$this->startTime = null;
if ( $this->env->profiling() ) {
$profile = $this->env->getCurrentProfile();
$this->startTime = microtime( true );
}
return true;
}
t:tlb
& {
if ( $this->env->profiling() ) {
$profile = $this->env->getCurrentProfile();
$profile->bumpTimeUse(
'PEG', 1000 * ( microtime( true ) - $this->startTime ), 'PEG' );
}
return true;
}
) { return $t; }
/ newlineToken* &{
// "tlb" matches "block" matches "sol" matches "newlineToken"
// But, "tlb" is prefixed with a !eof clause, so, we should only
// get here on eof. So, safe to unconditionally terminate the
// generator loop here.
return false;
}
)*
/*
* A document (start rule) is a sequence of toplevelblocks. Tokens are
* emitted in chunks per toplevelblock to avoid buffering the full document.
*/
tlb "tlb" =
!eof b:block {
// Clear the tokenizer's backtracking cache after matching each
// toplevelblock. There won't be any backtracking as a document is just a
// sequence of toplevelblocks, so the cache for previous toplevelblocks
// will never be needed.
$end = $this->startOffset();
for ( ; $this->prevOffset < $end; $this->prevOffset++ ) {
unset( $this->cache[$this->prevOffset] );
}
$tokens = null;
if ( is_array( $b ) && count( $b ) ) {
$tokens = TokenizerUtils::flattenIfArray( $b );
} elseif ( is_string( $b ) ) {
$tokens = [ $b ];
}
// Emit tokens for this toplevelblock. This feeds a chunk to the parser pipeline.
return $this->emitChunk( $tokens );
}
/*
* Redirects can only occur as the first thing in a document. See
* WikitextContent::getRedirectTarget()
*/
redirect =
rw:redirect_word
sp:$space_or_newline*
c:$(":" space_or_newline*)?
wl:wikilink
& {
return count( $wl ) === 1 && $wl[0] instanceof Token;
}
{
$link = $wl[0];
if ( $sp ) {
$rw .= $sp;
}
if ( $c ) {
$rw .= $c;
}
// Build a redirect token
$dp = new DataParsoid;
$dp->src = $rw;
$dp->tsr = $this->tsrOffsets();
$dp->linkTk = $link;
$redirect = new SelfclosingTagTk( 'mw:redirect',
// Put 'href' into attributes so it gets template-expanded
[ $link->getAttributeKV( 'href' ) ],
$dp
);
return $redirect;
}
/* The 'redirect' magic word.
* The leading whitespace allowed is due to the PHP trim() function.
*/
redirect_word =
$(
[ \t\n\r\0\x0b]*
rw:$(!space_or_newline ![:\[] .)+
& {
return preg_match( $this->env->getSiteConfig()->getMagicWordMatcher( 'redirect' ), $rw );
}
)
/*
* The actual contents of each block.
*/
block =
// Redirect has to be the first alternative; otherwise it gets parsed as a <ol>
// In practice, WikiContent::getRedirectTargetAndText() in MediaWiki strips
// the redirect from the source so it never sees it.
&sof r:redirect cil:sol_transparent* bl:block_line? {
return array_merge( [ $r ], $cil, $bl ?: [] );
}
/ block_lines
// Inlineline includes generic tags; wrapped into paragraphs in token
// transform and DOM postprocessor
/ inlineline
/ s:sol !sof !inline_breaks { return $s; }
/*
* A block nested in other constructs. Avoid eating end delimiters for other
* constructs by checking against inline_breaks first.
*/
nested_block = !inline_breaks b:block { return $b; }
/*
* The same, but suitable for use inside a table construct.
* Doesn't match table_heading_tag, table_row_tag, table_data_tag,
* table_caption tag, or table_end_tag, although it does allow
* table_start_tag (for nested tables).
*/
nested_block_in_table =
// XXX: don't rely on a lame look-ahead like this; use syntax stops
// instead, so that multi-line th content followed by a line prefixed with
// a comment is also handled. Alternatively, implement a sol look-behind
// assertion accepting spaces and comments.
!(sol (space* sol)? space* (pipe / "!"))
// avoid recursion via nested_block_in_table, as that can lead to stack
// overflow in large tables
// See https://phabricator.wikimedia.org/T59670
b:nested_block<tableDataBlock> {
return $b;
}
/*
* Line-based block constructs.
*/
block_lines =
s:sol
// eat an empty line before the block
s2:(os:optionalSpaceToken so:sol { return array_merge( $os, $so ); })?
bl:block_line {
return array_merge( $s, $s2 ?: [], $bl );
}
// Horizontal rules
hr =
"----" d:$"-"*
// Check if a newline or content follows
lineContent:( &sol "" { return null; } / "" { return true; } ) {
$dataParsoid = new DataParsoid;
$dataParsoid->tsr = $this->tsrOffsets();
if ( $lineContent !== null ) {
$dataParsoid->lineContent = $lineContent;
}
if ( strlen( $d ) > 0 ) {
$dataParsoid->extra_dashes = strlen( $d );
}
return [new SelfclosingTagTk( 'hr', [], $dataParsoid )];
}
/*
* Block structures with start-of-line wiki syntax
*/
block_line =
heading
/ list_item
/ hr
/ st:optionalSpaceToken &[ <{}|!] tl:table_line {
return array_merge( $st, $tl );
}
br =
s:optionalSpaceToken &newline {
$dp = new DataParsoid;
$dp->tsr = $this->tsrOffsets();
return array_merge( $s, [
new SelfclosingTagTk( 'br', [], $dp )
] );
}
inline_breaks =
& [=|!{}:;\r\n[\]\-]
(
annOrExtTag: <annOrExtTag>
h: <h>
extlink: <extlink>
intemplate: <intemplate>
preproc: <preproc>
equal: <equal>
table: <table>
templateArg: <templateArg>
tableCellArg: <tableCellArg>
semicolon: <semicolon>
arrow: <arrow>
linkdesc: <linkdesc>
colon: <colon>
th: <th>
& {
return TokenizerUtils::inlineBreaks( $this->input, $this->endOffset(), [
'annOrExtTag' => $annOrExtTag,
'h' => $h,
'extlink' => $extlink,
'intemplate' => $intemplate,
'preproc' => $preproc,
'equal' => $equal,
'table' => $table,
'templateArg' => $templateArg,
'tableCellArg' => $tableCellArg,
'semicolon' => $semicolon,
'arrow' => $arrow,
'linkdesc' => $linkdesc,
'colon' => $colon,
'th' => $th
], $this->env );
}
)
inlineline =
c:(
urltext
/ !inline_breaks
r:(inline_element / !newline s:. { return $s; }) { return $r; }
)+ {
return TokenizerUtils::flattenStringlist( $c );
}
inline_xmlish_tag =
"<" tag:(xmlish_tag<annOrExtTag> / xmlish_tag<annOrExtTag=false> / tvar_old_syntax_closing_HACK )
{ return $tag; }
inline_element =
& '<' r:( inline_xmlish_tag / comment ) { return $r; }
/ & '{' r:tplarg_or_template { return $r; }
/ & "-{" r:lang_variant_or_tpl { return $r; }
// FIXME: The old parser's handleInternalLinks2 splits on [[, resulting
// in sequences with odd number of brackets parsing as text, and sequences
// with even number of brackets having its innermost pair parse as a
// wikilink. For now, we faithfully reproduce what's found there but
// wikitext, the language, shouldn't be defined by odd tokenizing behaviour
// in the old parser. Flagging this for a future cleanup.
/ $('[[' &'[')+
/ & '[' r:( wikilink / extlink ) { return $r; }
/ & "'" r:quote { return $r; }
/* Headings */
heading =
& "=" // guard, to make sure '='+ will match.
// XXX: Also check to end to avoid inline parsing?
r:(
s:$'='+ // moved in here to make s accessible to inner action
ce:(
(ill:inlineline<h>? { return $ill ?: []; })
$'='+
)?
& { return $ce || strlen( $s ) > 2; }
endTPos:("" { return $this->endOffset(); })
spc:( space / sol_transparent )*
&eolf
{
$c = null;
$e = null;
$level = null;
if ( $ce ) {
$c = $ce[0];
$e = $ce[1];
$level = min( strlen( $s ), strlen( $e ) );
} else {
// split up equal signs into two equal parts, with at least
// one character in the middle.
$level = (int)floor( ( strlen( $s ) - 1 ) / 2 );
$c = [ str_repeat( '=', strlen( $s ) - 2 * $level ) ];
$s = $e = str_repeat( '=', $level );
}
$level = min( 6, $level );
// convert surplus equals into text
if ( strlen( $s ) > $level ) {
$extras1 = substr( $s, 0, strlen( $s ) - $level );
if ( is_string( $c[0] ) ) {
$c[0] = $extras1 . $c[0];
} else {
array_unshift( $c, $extras1 );
}
}
if ( strlen( $e ) > $level ) {
$extras2 = substr( $e, 0, strlen( $e ) - $level );
$lastElem = PHPUtils::lastItem( $c );
if ( is_string( $lastElem ) ) {
$c[count( $c ) - 1] .= $extras2;
} else {
$c[] = $extras2;
}
}
$tagDP = new DataParsoid;
$tagDP->tsr = $this->tsrOffsets( 'start' );
$tagDP->tsr->end += $level;
// Match the old parser's behavior by
// (a) making headingIndex part of tokenizer state
// (don't reuse pipeline! see $this->resetState above)
// (b) assigning the index when ==*== is tokenized,
// even if we're inside a template argument
// or other context which won't end up putting the heading
// on the output page. T213468/T214538
$this->headingIndex++;
$tagDP->getTemp()->headingIndex = $this->headingIndex;
$res = [ new TagTk( 'h' . $level, [], $tagDP ) ];
PHPUtils::pushArray( $res, $c );
$endTagDP = new DataParsoid;
$endTagDP->tsr = new SourceRange( $endTPos - $level, $endTPos );
$res[] = new EndTagTk( 'h' . $level, [], $endTagDP );
$res[] = $spc;
return $res;
}
) { return $r; }
// Behavior switches. See:
// https://www.mediawiki.org/wiki/Help:Magic_words#Behavior_switches
behavior_switch =
bs:$('__' behavior_text '__') {
if ( $this->siteConfig->isBehaviorSwitch( $bs ) ) {
$dp = new DataParsoid;
$dp->tsr = $this->tsrOffsets();
$dp->src = $bs;
$dp->magicSrc = $bs;
return [
new SelfclosingTagTk( 'behavior-switch', [ new KV( 'word', $bs ) ], $dp )
];
} else {
return [ $bs ];
}
}
// Instead of defining a charset, the old parser's doDoubleUnderscore concats a
// regexp of all the language specific aliases of the behavior switches and
// then does a match and replace. Just be as permissive as possible and let the
// BehaviorSwitchPreprocessor back out of any overreach.
behavior_text = $( !'__' ( text_char / "-" ) )+
/**************************************************************
* External (bracketed and autolinked) links
**************************************************************/
autolink =
! <extlink>
// this must be a word boundary, so previous character must be non-word
! { return Utils::isUniWord(Utils::lastUniChar( $this->input, $this->endOffset() ) ); }
r:(
autourl
/ autoref
/ isbn
) { return $r; }
extlink "extlink" =
! <extlink> // extlink cannot be nested
r:(
"["
p0:( "" { return $this->endOffset(); })
flat:(
addr:(url_protocol ipv6urladdr / "")
target:(extlink_nonipv6url<extlink> / "")
{ return TokenizerUtils::flattenString( [ $addr, $target ] ); }
)
& {
// Protocol must be valid and there ought to be at least one
// post-protocol character. So strip last char off target
// before testing protocol.
if ( is_array( $flat ) ) {
// There are templates present, alas.
return count( $flat ) > 0;
}
return Utils::isProtocolValid( substr( $flat, 0, -1 ), $this->env );
}
p1:( "" { return $this->endOffset(); })
sp:$( space / unispace )*
p2:( "" { return $this->endOffset(); })
content:inlineline<extlink>?
p3:( "" { return $this->endOffset(); })
"]" {
$tsr1 = new SourceRange( $p0, $p1 );
$tsr2 = new SourceRange( $p2, $p3 );
$dp = new DataParsoid;
$dp->tsr = $this->tsrOffsets();
$dp->extLinkContentOffsets = $tsr2;
return [
new SelfclosingTagTk(
'extlink',
[
new KV( 'href', $flat, $tsr1->expandTsrV() ),
new KV( 'mw:content', $content ?? '', $tsr2->expandTsrV() ),
new KV( 'spaces', $sp )
],
$dp
)
]; }
) { return $r; }
autoref =
ref:('RFC' / 'PMID') sp:space_or_nbsp+ identifier:$[0-9]+ end_of_word
{
$base_urls = [
'RFC' => 'https://tools.ietf.org/html/rfc%s',
'PMID' => '//www.ncbi.nlm.nih.gov/pubmed/%s?dopt=Abstract'
];
$tsr = $this->tsrOffsets();
$dp = new DataParsoid;
$dp->tsr = $tsr;
$dp->stx = 'magiclink';
return [
new SelfclosingTagTk( 'extlink', [
new KV( 'href', sprintf( $base_urls[ $ref ], $identifier ) ),
new KV( 'mw:content', TokenizerUtils::flattenString( [ $ref, $sp, $identifier ] ), $tsr->expandTsrV() ),
new KV( 'typeof', 'mw:ExtLink/' . $ref )
],
$dp
)
];
}
isbn =
'ISBN' sp:space_or_nbsp+ isbn:(
[0-9]
((space_or_nbsp_or_dash / "") [0-9])+
((space_or_nbsp_or_dash / "") [xX] / "")
)
isbncode:(
end_of_word
{
// Convert isbn token-and-entity array to stripped string.
$stripped = '';
foreach ( TokenizerUtils::flattenStringlist( $isbn ) as $part ) {
if ( is_string( $part ) ) {
$stripped .= $part;
}
}
return strtoupper( preg_replace( '/[^\dX]/i', '', $stripped ) );
}
)
&{
// ISBNs can only be 10 or 13 digits long (with a specific format)
return strlen( $isbncode ) === 10
|| ( strlen( $isbncode ) === 13 && preg_match( '/^97[89]/', $isbncode ) );
}
{
$tsr = $this->tsrOffsets();
$dp = new DataParsoid;
$dp->stx = 'magiclink';
$dp->tsr = $tsr;
return [
new SelfclosingTagTk( 'extlink', [
new KV( 'href', 'Special:BookSources/' . $isbncode ),
new KV( 'mw:content', TokenizerUtils::flattenString( [ 'ISBN', $sp, $isbn ] ), $tsr->expandTsrV() ),
new KV( 'typeof', 'mw:WikiLink/ISBN' )
],
$dp
)
];
}
/* Default URL protocols in MediaWiki (see DefaultSettings). Normally
* these can be configured dynamically. */
url_protocol =
p:$( '//' / [A-Za-z] [-A-Za-z0-9+.]* ':' '//'? )
& { return Utils::isProtocolValid( $p, $this->env ); }
{ return $p; }
// no punctuation, and '{<' to trigger directives
no_punctuation_char = [^ \]\[\r\n"'<>\x00-\x20\x7f&\u00A0\u1680\u180E\u2000-\u200A\u202F\u205F\u3000{]
// this is the general url rule
// on the PHP side, the path part matches EXT_LINK_URL_CLASS
// which is '[^][<>"\\x00-\\x20\\x7F\p{Zs}]'
url =
proto:url_protocol
addr:(ipv6urladdr / "")
path:(
!inline_breaks c:(
no_punctuation_char
/ comment
/ tplarg_or_template
/ ['{]
/ ! ( "&" ( [lL][tT] / [gG][tT] ) ";" )
r:(
& "&" he:htmlentity { return $he; }
/ "&"
) { return $r; }
) { return $c; }
)*
// Must be at least one character after the protocol
& { return $addr !== '' || count( $path ) > 0; }
{
return TokenizerUtils::flattenString( array_merge( [ $proto, $addr ], $path ) );
}
// this is the somewhat-restricted rule used in autolinks
// See Parser::doMagicLinks and Parser.php::makeFreeExternalLink.
// The `path` portion matches EXT_LINK_URL_CLASS, as in the general
// url rule. As in PHP, we do some fancy fixup to yank out
// trailing punctuation, perhaps including parentheses.
autourl =
! '//' // protocol-relative autolinks not allowed (T32269)
r:(
proto:url_protocol
addr:(ipv6urladdr / "")
path:(
!inline_breaks c:(
no_punctuation_char
/ comment
/ tplarg_or_template
/ $("'" !"'") // single quotes are ok, double quotes are bad
/ "{"
/ ! ( rhe:raw_htmlentity &{ return $rhe === '<' || $rhe === '>' || $rhe === "\u{A0}"; } )
r:(
& "&" he:htmlentity { return $he; }
/ "&"
) { return $r; }
) { return $c; }
)*
{
// as in Parser.php::makeFreeExternalLink, we're going to
// yank trailing punctuation out of this match.
$url = TokenizerUtils::flattenStringlist( array_merge( [ $proto, $addr ], $path ) );
// only need to look at last element; HTML entities are strip-proof.
$last = PHPUtils::lastItem( $url );
$trim = 0;
if ( is_string( $last ) ) {
$strip = TokenizerUtils::getAutoUrlTerminatingChars( in_array( '(', $path, true ) );
$trim = strspn( strrev( $last ), $strip );
$url[ count( $url ) - 1 ] = substr( $last, 0, strlen( $last ) - $trim );
}
$url = TokenizerUtils::flattenStringlist( $url );
if ( count( $url ) === 1 && is_string( $url[0] ) && strlen( $url[0] ) <= strlen( $proto ) ) {
return null; // ensure we haven't stripped everything: T106945
}
$this->currPos -= $trim;
return $url;
}
)
&{ return $r !== null; }
{
$tsr = $this->tsrOffsets();
$dp = new DataParsoid;
$dp->tsr = $tsr;
$res = [ new SelfclosingTagTk( 'urllink', [ new KV( 'href', $r, $tsr->expandTsrV() ) ], $dp ) ];
return $res;
}
// This is extracted from EXT_LINK_ADDR in Parser.php: a simplified
// expression to match an IPv6 address. The IPv4 address and "at least
// one character of a host name" portions are punted to the `path`
// component of the `autourl` and `url` productions
ipv6urladdr =
$( "[" [0-9A-Fa-f:.]+ "]" )
/**************************************************************
* Templates, -arguments and wikilinks
**************************************************************/
/*
* Precedence: template arguments win over templates. See
* http://www.mediawiki.org/wiki/Preprocessor_ABNF#Ideal_precedence
* 4: {{{{·}}}} → {·{{{·}}}·}
* 5: {{{{{·}}}}} → {{·{{{·}}}·}}
* 6: {{{{{{·}}}}}} → {{{·{{{·}}}·}}}
* 7: {{{{{{{·}}}}}}} → {·{{{·{{{·}}}·}}}·}
* This is only if close has > 3 braces; otherwise we just match open
* and close as we find them.
*/
tplarg_or_template =