Debian Codegraph @

extensions/Math/src/WikiTexVC/TexVC.php

raw symbols SCIP
1 <?php
2
3 declare( strict_types = 1 );
4
5 namespace MediaWiki\Extension\Math\WikiTexVC;
6
7 use Exception;
8 use MediaWiki\Extension\Math\WikiTexVC\Mhchem\MhchemParser;
9 use MediaWiki\Extension\Math\WikiTexVC\MMLmappings\Util\MMLParsingUtil;
10 use MediaWiki\Extension\Math\WikiTexVC\MMLmappings\Util\MMLutil;
11 use MediaWiki\Extension\Math\WikiTexVC\Nodes\Fun2;
12 use MediaWiki\Extension\Math\WikiTexVC\Nodes\TexArray;
13 use MediaWiki\Extension\Math\WikiTexVC\Nodes\TexNode;
14 use stdClass;
15
16 /**
17 * A TeX/LaTeX validator and MathML converter.
18 * WikiTexVC takes user input and validates it while replacing
19 * MediaWiki-specific functions. The validator component is a PHP port of the JavaScript port of texvc,
20 * which was originally written in Ocaml for the Math extension.
21 *
22 * @author Johannes Stegmüller
23 */
24 class TexVC {
25 /** @var Parser */
26 private $parser;
27 /** @var TexUtil */
28 private $tu;
29
30 public function __construct() {
31 $this->parser = new Parser();
32 $this->tu = TexUtil::getInstance();
33 }
34
35 /**
36 * Usually this step is done implicitly within the check-method.
37 * @param string $input tex-string as input for the grammar
38 * @param null|array $options array options for the grammar.
39 * @return mixed output of the grammar.
40 * @throws SyntaxError when SyntaxError in the input
41 */
42 public function parse( $input, $options = null ) {
43 return $this->parser->parse( $input, $options );
44 }
45
46 /** status is one character:
47 * + : success! result is in 'output'
48 * E : Lexer exception raised
49 * F : TeX function not recognized
50 * S : Parsing error
51 * - : Generic/Default failure code. Might be an invalid argument,
52 * output file already exist, a problem with an external
53 * command ...
54 * @param string|TexArray|stdClass $input tex to be checked as string,
55 * can also be the output of former parser call
56 * @param array $options array options for settings of the check
57 * @param array &$warnings reference on warnings occurring during the check
58 * @param bool $texifyMhchem create TeX for mhchem in input before checking further
59 * @return array|string[] output with information status (see above)
60 * @throws Exception in case of a major problem with the check and activated debug option.
61 */
62 public function check( $input, $options = [], &$warnings = [], bool $texifyMhchem = false ) {
63 try {
64 if ( $texifyMhchem && isset( $options["usemhchem"] ) && $options["usemhchem"] ) {
65 // Parse the chemical equations to TeX with mhChemParser in PHP as preprocessor
66 $mhChemParser = new MHChemParser();
67 $input = $mhChemParser->toTex( $input, "tex", true );
68 }
69
70 $options = ParserUtil::createOptions( $options );
71 if ( is_string( $input ) ) {
72 $input = $this->parser->parse( $input, $options );
73 }
74 $output = $input->render();
75
76 $result = [
77 'inputN' => $input,
78 'status' => '+',
79 'output' => $output,
80 'warnings' => $warnings,
81 'input' => $input,
82 'success' => true,
83 ];
84
85 if ( $options['report_required'] ) {
86 $pkgs = [ 'ams', 'cancel', 'color', 'euro', 'teubner',
87 'mhchem', 'mathoid', 'mhchemtexified', "intent" ];
88
89 foreach ( $pkgs as $pkg ) {
90 $pkg .= '_required';
91 $tuRef = $this->tu->getBaseElements()[$pkg];
92 $result[$pkg] = $input->containsFunc( $tuRef );
93 }
94 }
95
96 if ( !$options['usemhchem'] ) {
97 if ( $result['mhchem_required'] ??
98 $input->containsFunc( $this->tu->getBaseElements()['mhchem_required'] )
99 ) {
100 return [
101 'status' => 'C',
102 'details' => 'mhchem package required.'
103 ];
104 }
105 }
106 if ( !$options['usemhchemtexified'] ) {
107 if ( $result['mhchemtexified_required'] ??
108 $input->containsFunc( $this->tu->getBaseElements()['mhchemtexified_required'] )
109 ) {
110 return [
111 'status' => 'C',
112 'details' => 'virtual mhchemtexified package required.'
113 ];
114 }
115 }
116
117 if ( !$options['useintent'] ) {
118 if ( $result['intent_required'] ??
119 $input->containsFunc( $this->tu->getBaseElements()['intent_required'] )
120 ) {
121 return [
122 'status' => 'C',
123 'details' => 'virtual intent package required.'
124 ];
125 }
126 } else {
127 // Preliminary post-checks of correct intent-syntax
128 if ( $input->containsFunc( $this->tu->getBaseElements()['intent_required'] ) ) {
129 $intentCheck = $this->checkTreeIntents( $input );
130 if ( !$intentCheck || ( isset( $intentCheck["success"] ) && !$intentCheck["success"] ) ) {
131 return $intentCheck;
132 }
133 }
134 }
135
136 return $result;
137 } catch ( Exception $ex ) {
138 if ( $ex instanceof SyntaxError && !$options['oldtexvc']
139 && str_starts_with( $ex->getMessage(), 'Deprecation' )
140 ) {
141 $warnings[] = [
142 'type' => 'texvc-deprecation',
143 'details' => $this->handleTexError( $ex, $options )
144 ];
145 $options['oldtexvc'] = true;
146 return $this->check( $input, $options, $warnings );
147 }
148
149 if ( $ex instanceof SyntaxError && $options['usemhchem'] && !$options['oldmhchem'] ) {
150 $warnings[] = [
151 'type' => 'mhchem-deprecation',
152 'details' => $this->handleTexError( $ex, $options )
153 ];
154 $options['oldmhchem'] = true;
155 return $this->check( $input, $options, $warnings );
156 }
157 }
158 return $this->handleTexError( $ex, $options );
159 }
160
161 /**
162 * @param string|TexNode|null $inputTree
163 * @return array|true
164 */
165 private function checkTreeIntents( $inputTree ) {
166 if ( is_string( $inputTree ) ) {
167 return true;
168 }
169 if ( !$inputTree ) {
170 return true;
171 }
172 foreach ( $inputTree->getArgs() as $value ) {
173 if ( $value instanceof Fun2 && $value->getFname() === "\\intent" ) {
174 $intentStr = MMLutil::squashLitsToUnitIntent( $value->getArg2() );
175 $intentContent = MMLParsingUtil::getIntentContent( $intentStr );
176 $intentArg = MMLParsingUtil::getIntentArgs( $intentStr );
177 $argch = self::checkIntentArg( $intentArg );
178 if ( !$argch ) {
179 $retval = [];
180 $retval["success"] = false;
181 $retval["info"] = "malformatted intent argument";
182 return $retval;
183 }
184 // do check on arg1
185 $ret = !$intentContent ? true : self::checkIntent( $intentContent );
186 if ( !$ret || ( isset( $ret["success"] ) && $ret["success"] == false ) ) {
187 return $ret;
188 }
189 return $this->checkTreeIntents( $value->getArg1() );
190 } else {
191 return self::checkTreeIntents( $value );
192 }
193 }
194 return true;
195 }
196
197 public static function checkIntentArg( ?string $input ): bool {
198 if ( !$input ) {
199 return true;
200 }
201 $matchesArgs = [];
202 // arg has roughly the same specs like NCName in parserintent.pegjs
203 $matchArg = preg_match( "/[a-zA-Z0-9._-]*/", $input, $matchesArgs );
204 if ( $matchArg ) {
205 return true;
206 }
207 return false;
208 }
209
210 /**
211 * @return true|array
212 */
213 public function checkIntent( string $input ) {
214 // Very early intent syntax checker
215 try {
216 $parserIntent = new ParserIntent();
217 $parserIntent->parse( $input );
218 return true;
219 } catch ( Exception $exception ) {
220 return $this->handleTexError( $exception, null );
221 }
222 }
223
224 private function handleTexError( Exception $e, ?array $options = null ): array {
225 if ( $options && $options['debug'] ) {
226 throw $e;
227 }
228 $report = [ 'success' => false, 'warnings' => [] ];
229 if ( $e instanceof SyntaxError ) {
230 if ( $e->getMessage() === 'Illegal TeX function' ) {
231 $report['status'] = 'F';
232 $report['details'] = $e->found;
233 $report += $this->getLocationInfo( $e );
234 } else {
235 $report['status'] = 'S';
236 $report['details'] = $e->getMessage();
237 $report += $this->getLocationInfo( $e );
238 }
239 $report['error'] = [
240 'message' => $e->getMessage(),
241 'expected' => $e->expected,
242 'found' => $e->found,
243 'location' => [
244 /** This currently only has the start location, since end is not noted in SyntaxError in PHP
245 * this issue is tracked in: https://phabricator.wikimedia.org/T321060
246 */
247 'offset' => $e->grammarOffset,
248 'line' => $e->grammarLine,
249 'column' => $e->grammarColumn
250 ],
251 'name' => $e->name
252 ];
253
254 } else {
255 $report['status'] = '-';
256 $report['details'] = $e->getMessage();
257 $report['error'] = $e;
258 }
259 return $report;
260 }
261
262 /**
263 * Gets the location information of an error object, or returns default error
264 * location if no location information was specified.
265 * @param SyntaxError $e error object
266 * @return array information on the error.
267 */
268 private function getLocationInfo( SyntaxError $e ) {
269 try {
270 return [
271 'offset' => $e->grammarOffset,
272 'line' => $e->grammarLine,
273 'column' => $e->grammarColumn
274 ];
275 } catch ( Exception $err ) {
276 return [ 'offset' => 0, 'line' => 0, 'column' => 0 ];
277 }
278 }
279
280 }