Debian Codegraph @

extensions/Math/src/WikiTexVC/Nodes/TexArray.php

raw symbols SCIP
1 <?php
2
3 declare( strict_types = 1 );
4
5 namespace MediaWiki\Extension\Math\WikiTexVC\Nodes;
6
7 use Generator;
8 use InvalidArgumentException;
9 use MediaWiki\Extension\Math\WikiTexVC\MMLmappings\Util\MMLParsingUtil;
10 use MediaWiki\Extension\Math\WikiTexVC\MMLmappings\Util\MMLutil;
11 use MediaWiki\Extension\Math\WikiTexVC\MMLnodes\MMLmo;
12 use MediaWiki\Extension\Math\WikiTexVC\MMLnodes\MMLmrow;
13 use MediaWiki\Extension\Math\WikiTexVC\MMLnodes\MMLmstyle;
14 use MediaWiki\Extension\Math\WikiTexVC\MMLnodes\MMLmsup;
15 use MediaWiki\Extension\Math\WikiTexVC\TexUtil;
16
17 /**
18 *
19 */
20 class TexArray extends TexNode implements \ArrayAccess, \IteratorAggregate {
21 protected bool $curly = false;
22 private ?LengthSpec $rowSpecs = null;
23
24 /**
25 * @param TexNode|string ...$args
26 * @return self
27 */
28 public static function newCurly( ...$args ) {
29 $node = new self( ...$args );
30 $node->curly = true;
31 return $node;
32 }
33
34 /** @inheritDoc */
35 public function __construct( ...$args ) {
36 $nargs = [];
37
38 foreach ( $args as &$arg ) {
39 if ( $arg !== null ) {
40 array_push( $nargs, $arg );
41 }
42 }
43
44 self::checkInput( $nargs );
45 parent::__construct( ...$nargs );
46 }
47
48 public function checkForStyleArgs( TexNode $node ): ?array {
49 if ( $node instanceof Literal ) {
50 $name = trim( $node->getArg() );
51 switch ( $name ) {
52 case "\\displaystyle":
53 return [ "displaystyle" => "true", "scriptlevel" => "0" ];
54 case "\\scriptstyle":
55 return [ "displaystyle" => "false", "scriptlevel" => "1" ];
56 case "\\scriptscriptstyle":
57 return [ "displaystyle" => "false", "scriptlevel" => "2" ];
58 case "\\textstyle":
59 return [ "displaystyle" => "false", "scriptlevel" => "0" ];
60 }
61 }
62 return null;
63 }
64
65 /**
66 * Checks if an TexNode of Literal contains color information (color, pagecolor)
67 * and returns info how to continue with the parsing.
68 * @param TexNode $node node to check if it contains color info
69 * @return array index 0: (bool) was color element found, index 1: (string) specified color
70 */
71 public function checkForColor( TexNode $node ) {
72 if ( $node instanceof Literal ) {
73 $name = trim( $node->getArg() );
74 if ( str_contains( $name, "\\color" ) ) {
75 $foundOperatorContent = MMLutil::initalParseLiteralExpression( $node->getArg() );
76 if ( !$foundOperatorContent ) {
77 // discarding color elements which not specify color
78 return [ true, null ];
79 } else {
80 return [ true, $foundOperatorContent[2][0] ];
81 }
82 } elseif ( str_contains( $name, "\\pagecolor" ) ) {
83 return [ true, null ];
84 }
85 }
86 return [ false, null ];
87 }
88
89 public function checkForColorDefinition( TexNode $node ): ?array {
90 if ( $node instanceof Literal ) {
91 $name = trim( $node->getArg() );
92 if ( str_contains( $name, "\\definecolor" ) ) {
93 return MMLParsingUtil::parseDefineColorExpression( $node->getArg() );
94 }
95 }
96 return null;
97 }
98
99 /**
100 * Checks two sequential nodes in TexArray if they contain information on sideset expressions.
101 * @param TexNode $currentNode first node in array to check (for sideset expression)
102 * @param TexNode|null $nextNode second node in array to check (for succeeding operator)
103 * @return TexNode|null the succeeding operator for further Parsing or null if sideset not found or invalid
104 */
105 public function checkForSideset( TexNode $currentNode, ?TexNode $nextNode ): ?TexNode {
106 if ( !( $currentNode instanceof Fun2nb && $currentNode->getFname() == "\\sideset" ) ) {
107 return null;
108 }
109 if ( $nextNode instanceof Literal ||
110 $nextNode instanceof DQ ||
111 $nextNode instanceof UQ ||
112 $nextNode instanceof FQ ) {
113 return $nextNode;
114 }
115 return null;
116 }
117
118 public function checkForLimits( TexNode $currentNode, ?TexNode $nextNode ): array {
119 // Preceding 'lim' in example: "\\lim_{x \\to 2}"
120 if ( ( $currentNode instanceof DQ || $currentNode instanceof FQ )
121 && $currentNode->containsFunc( "\\lim" ) ) {
122
123 if ( $currentNode->getBase() instanceof TexArray ) {
124 return [ $currentNode->getBase()->getArgs()[0], false ];
125 } else {
126 return [ $currentNode->getBase(), false ];
127 }
128 }
129
130 /** Find cases which have preceding Literals with nullary_macro-type operators i.e.:
131 * "\iint\limits_D \, dx\,dy"
132 */
133 $tu = TexUtil::getInstance();
134
135 // Check whether the current node is a possible preceding literal
136 if ( !(
137 // logically superfluous brackets were inserted to improve readability
138 ( $currentNode instanceof Literal &&
139 // Check if the current node is a nullary macro such as \iint, \sum, \prod, etc.
140 ( $tu->nullary_macro( trim( $currentNode->getArg() ) )
141 // or a limit operator
142 || ( trim( $currentNode->getArg() ) == "\\lim" ) ) ) ||
143 // or the special case of \operatorname
144 ( $currentNode instanceof Fun1nb && $currentNode->getFname() == "\\operatorname" )
145 ) ) {
146 return [ null, false ];
147 }
148
149 // Check whether the next node is a possible limits construct
150 if ( !( ( $nextNode instanceof DQ || $nextNode instanceof FQ )
151 && $nextNode->getBase() instanceof Literal
152 && ( $nextNode->containsFunc( "\\limits" ) || $nextNode->containsFunc( "\\nolimits" ) )
153 ) ) {
154 return [ null, false ];
155
156 }
157 return [ $currentNode, true ];
158 }
159
160 public function checkForNot( TexNode $currentNode ): bool {
161 if ( $currentNode instanceof Literal && trim( $currentNode->getArg() ) == "\\not" ) {
162 return true;
163 }
164 return false;
165 }
166
167 public function checkForDerivatives( int $iStart, array $args ): int {
168 $ctr = 0;
169 for ( $i = $iStart, $count = count( $this->args ); $i < $count; $i++ ) {
170 $followUp = $args[$i];
171 if ( $followUp instanceof Literal && $followUp->getArg() === "'" ) {
172 $ctr++;
173 } else {
174 break;
175 }
176 }
177
178 return $ctr;
179 }
180
181 public function checkForNamedFctArgs( TexNode $currentNode, ?TexNode $nextNode ): array {
182 // Check if current node is named function
183 $hasNamedFct = false;
184 if ( $currentNode instanceof TexArray && count( $currentNode->args ) == 2 ) {
185 $tu = TexUtil::getInstance();
186 $currentNodeContent = $currentNode[0];
187 if ( $currentNodeContent instanceof Literal &&
188 $tu->latex_function_names( $currentNodeContent->getArg() ) ) {
189 $hasNamedFct = true;
190 }
191 } elseif ( $currentNode instanceof Fun1nb && $currentNode->getFname() === '\\operatorname' ) {
192 $hasNamedFct = true;
193 }
194
195 // Check if there is a valid argument as next parameter
196 $hasValidParameters = false;
197 if ( !$hasNamedFct ) {
198 return [ $hasNamedFct, $hasValidParameters ];
199 }
200
201 if ( $nextNode && !( $nextNode instanceof Literal && $nextNode->getArg() === "'" ) ) {
202 $hasValidParameters = true;
203 }
204
205 return [ $hasNamedFct, $hasValidParameters ];
206 }
207
208 private function squashLiterals() {
209 $tmp = '';
210 foreach ( $this->args as $arg ) {
211 if ( !( $arg instanceof Literal ) ) {
212 return;
213 }
214 // Don't squash if there is a macro in the literal
215 if ( preg_match( "/[\\\\]/", $arg->getArg() ) ) {
216 return;
217 }
218 $tmp .= $arg->getArg();
219 }
220 $this->args = [ new Literal( $tmp ) ];
221 $this->curly = false;
222 }
223
224 /** @inheritDoc */
225 public function renderMML( $arguments = [], &$state = [] ) {
226 // Everything here is for parsing displaystyle, probably refactored to WikiTexVC grammar later
227 $fullRenderedArray = "";
228 $mmlStyles = [];
229 $currentColor = null;
230
231 if ( array_key_exists( 'squashLiterals', $state ) ) {
232 $this->squashLiterals();
233 }
234
235 for ( $i = 0, $count = count( $this->args ); $i < $count; $i++ ) {
236 $current = $this->args[$i];
237 if ( isset( $this->args[$i + 1] ) ) {
238 $next = $this->args[$i + 1];
239 } else {
240 $next = null;
241 }
242 // Check for sideset
243 $foundSideset = $this->checkForSideset( $current, $next );
244 if ( $foundSideset ) {
245 $state["sideset"] = $foundSideset;
246 // Skipping the succeeding Literal
247 $i++;
248 }
249
250 // Check for limits
251 $foundLimits = $this->checkForLimits( $current, $next );
252 if ( $foundLimits[0] ) {
253 $state["limits"] = $foundLimits[0];
254 if ( $foundLimits[1] ) {
255 continue;
256 }
257 }
258
259 // Check for Not
260 $foundNot = $this->checkForNot( $current );
261 if ( $foundNot ) {
262 $state["not"] = true;
263 continue;
264 }
265
266 // Check for derivatives
267 $foundDeriv = $this->checkForDerivatives( $i + 1, $this->args );
268 if ( $foundDeriv > 0 ) {
269 // skip the next indices which are derivative characters
270 $i += $foundDeriv;
271 $state["deriv"] = $foundDeriv;
272 }
273
274 // Check if there is a new color definition and add it to state
275 $foundColorDef = $this->checkForColorDefinition( $current );
276 if ( $foundColorDef ) {
277 $state["colorDefinitions"][$foundColorDef["name"]] = $foundColorDef;
278 continue;
279 }
280 // Pass preceding color info to state
281 $foundColor = $this->checkForColor( $current );
282 if ( $foundColor[0] ) {
283 $currentColor = $foundColor[1];
284 // Skipping the color element itself for rendering
285 continue;
286 }
287 $styleArguments = $this->checkForStyleArgs( $current );
288
289 $foundNamedFct = $this->checkForNamedFctArgs( $current, $next );
290 if ( $foundNamedFct[0] ) {
291 $state["foundNamedFct"] = $foundNamedFct;
292 }
293
294 if ( $styleArguments ) {
295 $state["styleargs"] = $styleArguments;
296 $mmlStyle = new MMLmstyle( "", $styleArguments );
297 $fullRenderedArray .= $mmlStyle->getStart();
298 if ( $next instanceof TexNode && $next->isCurly() ) {
299 // Wrap with style-tags when the next element is a Curly which determines start and end tag.
300 $fullRenderedArray .= $this->createMMLwithContext( $currentColor, $next, $state, $arguments );
301 $fullRenderedArray .= $mmlStyle->getEnd();
302 $mmlStyle = null;
303 unset( $state["styleargs"] );
304 $i++;
305 } else {
306 // Start the style indicator in cases like \textstyle abc
307 $mmlStyles[] = $mmlStyle->getEnd();
308
309 }
310 } else {
311 $fullRenderedArray .= $this->createMMLwithContext( $currentColor, $current, $state, $arguments );
312 }
313
314 if ( array_key_exists( "not", $state ) ) {
315 unset( $state["not"] );
316 }
317 if ( array_key_exists( "limits", $state ) ) {
318 unset( $state["limits"] );
319 }
320 if ( array_key_exists( "deriv", $state ) ) {
321 unset( $state["deriv"] );
322 }
323 }
324
325 foreach ( array_reverse( $mmlStyles ) as $mmlStyleEnd ) {
326 $fullRenderedArray .= $mmlStyleEnd;
327 }
328 if ( $this->curly && $this->getLength() > 1 ) {
329 $mmlRow = new MMLmrow();
330 return $mmlRow->encapsulateRaw( $fullRenderedArray );
331 }
332
333 return $fullRenderedArray;
334 }
335
336 private function createMMLwithContext(
337 ?string $currentColor, TexNode $currentNode, array &$state, array $arguments
338 ): string {
339 if ( $currentColor ) {
340 if ( array_key_exists( "colorDefinitions", $state )
341 && is_array( $state["colorDefinitions"] )
342 && array_key_exists( $currentColor, $state["colorDefinitions"] ?? [] )
343 && is_array( $state["colorDefinitions"][$currentColor] )
344 && array_key_exists( "hex", $state["colorDefinitions"][$currentColor] )
345 ) {
346 $displayedColor = $state["colorDefinitions"][$currentColor]["hex"];
347
348 } else {
349 $resColor = TexUtil::getInstance()->color( ucfirst( $currentColor ) );
350 $displayedColor = $resColor ?: $currentColor;
351 }
352 $mmlStyleColor = new MMLmstyle( "", [ "mathcolor" => $displayedColor ] );
353 $ret = $mmlStyleColor->encapsulateRaw( $currentNode->renderMML( $arguments, $state ) );
354 } else {
355 $ret = $currentNode->renderMML( $arguments, $state );
356 }
357
358 return $this->addDerivativesContext( $state, $ret );
359 }
360
361 /**
362 * If derivative was recognized, add the corresponding derivative math operator
363 * to the mml and wrap with msup element.
364 * @param array &$state state indicator which indicates derivative
365 * @param string $mml mathml input
366 * @return string mml with additional mml-elements for derivatives
367 */
368 public function addDerivativesContext( array &$state, string $mml ): string {
369 if ( array_key_exists( "deriv", $state ) && $state["deriv"] > 0 ) {
370 $msup = new MMLmsup();
371 $moDeriv = new MMLmo();
372
373 if ( $state["deriv"] == 1 ) {
374 $derInfo = "&#x2032;";
375 } elseif ( $state["deriv"] == 2 ) {
376 $derInfo = "&#x2033;";
377 } elseif ( $state["deriv"] == 3 ) {
378 $derInfo = "&#x2034;";
379 } elseif ( $state["deriv"] == 4 ) {
380 $derInfo = "&#x2057;";
381 } else {
382 $derInfo = str_repeat( "&#x2032;", $state["deriv"] );
383 }
384
385 $mml = $msup->encapsulateRaw( $mml . $moDeriv->encapsulateRaw( $derInfo ) );
386 if ( ( $state['foundNamedFct'][0] ?? false ) && !( $state['foundNamedFct'][1] ?? true ) ) {
387 $mml .= MMLParsingUtil::renderApplyFunction();
388 }
389 }
390 return $mml;
391 }
392
393 /** @inheritDoc */
394 public function inCurlies() {
395 if ( isset( $this->args[0] ) && count( $this->args ) == 1 ) {
396 return $this->args[0]->inCurlies();
397 } else {
398 return '{' . parent::render() . '}';
399 }
400 }
401
402 /** @inheritDoc */
403 public function extractSubscripts() {
404 $y = [];
405
406 foreach ( $this->args as $x ) {
407 $y = array_merge( $y, $x->extractSubscripts() );
408 }
409 if ( isset( $this->args[0] ) && ( count( $this->args ) == count( $y ) ) ) {
410 return implode( '', $y );
411 }
412 return [];
413 }
414
415 /** @inheritDoc */
416 public function extractIdentifiers( $args = null ) {
417 if ( $args == null ) {
418 $args = $this->args;
419 }
420 $list = parent::extractIdentifiers( $args );
421 $outpos = 0;
422 $offset = 0;
423 $int = 0;
424
425 for ( $inpos = 0; $inpos < count( $list ); $inpos++ ) {
426 $outpos = $inpos - $offset;
427 switch ( $list[$inpos] ) {
428 case '\'':
429 $list[$outpos - 1] .= '\'';
430 $offset++;
431 break;
432 case '\\int':
433 $int++;
434 $offset++;
435 break;
436 case '\\mathrm{d}':
437 case 'd':
438 if ( $int ) {
439 $int--;
440 $offset++;
441 break;
442 }
443 // no break
444 default:
445 if ( isset( $list[0] ) ) {
446 $list[$outpos] = $list[$inpos];
447 }
448 }
449 }
450 return array_slice( $list, 0, count( $list ) - $offset );
451 }
452
453 /** @inheritDoc */
454 public function getModIdent() {
455 $y = [];
456
457 foreach ( $this->args as $x ) {
458 $y = array_merge( $y, $x->getModIdent() );
459 }
460
461 if ( isset( $this->args[0] ) && ( count( $this->args ) == count( $y ) ) ) {
462 return implode( "", $y );
463 }
464 return [];
465 }
466
467 /**
468 * @param TexNode|string ...$elements
469 */
470 public function push( ...$elements ): TexArray {
471 self::checkInput( $elements );
472
473 array_push( $this->args, ...$elements );
474 return $this;
475 }
476
477 public function pop() {
478 array_splice( $this->args, 0, 1 );
479 }
480
481 /**
482 * @return TexNode|null first value
483 */
484 public function first() {
485 return $this->args[0] ?? null;
486 }
487
488 /**
489 * @return TexNode|null second value
490 */
491 public function second() {
492 return $this->args[1] ?? null;
493 }
494
495 /**
496 * @param TexNode|string ...$elements
497 */
498 public function unshift( ...$elements ): TexArray {
499 array_unshift( $this->args, ...$elements );
500 return $this;
501 }
502
503 /**
504 * @throws InvalidArgumentException if args not of correct type
505 * @param TexNode[] $args input args
506 * @return void
507 */
508 private static function checkInput( $args ): void {
509 foreach ( $args as $arg ) {
510 if ( !( $arg instanceof TexNode ) ) {
511 throw new InvalidArgumentException( 'Wrong input type specified in input elements.' );
512 }
513 }
514 }
515
516 public function render() {
517 if ( $this->curly ) {
518 return $this->inCurlies();
519 }
520 return parent::render();
521 }
522
523 public function isCurly(): bool {
524 return $this->curly;
525 }
526
527 public function setCurly( bool $curly = true ): TexArray {
528 $this->curly = $curly;
529 return $this;
530 }
531
532 /**
533 * @return Generator<TexNode>
534 */
535 public function getIterator(): Generator {
536 yield from $this->args;
537 }
538
539 /**
540 * @return TexNode[]
541 */
542 public function getArgs(): array {
543 return parent::getArgs();
544 }
545
546 /** @inheritDoc */
547 public function offsetExists( $offset ): bool {
548 return isset( $this->args[$offset] );
549 }
550
551 /** @inheritDoc */
552 public function offsetGet( $offset ): ?TexNode {
553 return $this->args[$offset] ?? null;
554 }
555
556 /** @inheritDoc */
557 public function offsetSet( $offset, $value ): void {
558 if ( !( $value instanceof TexNode ) ) {
559 throw new InvalidArgumentException( 'TexArray elements must be of type TexNode.' );
560 }
561 $this->args[$offset] = $value;
562 }
563
564 /** @inheritDoc */
565 public function offsetUnset( $offset ): void {
566 unset( $this->args[$offset] );
567 }
568
569 public function setRowSpecs( ?LengthSpec $r ) {
570 $this->rowSpecs = $r;
571 }
572
573 public function getRowSpecs(): ?LengthSpec {
574 return $this->rowSpecs;
575 }
576 }