Blame view

src/InputOutput/IHMImpl/Tools/IHMExpressionParserClass.php 23.5 KB
22521f1c   Benjamin Renard   First commit
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
<?php

/**
 * @class IHMExpressionParserClass
 * @brief Parser for IHM expression
 * @details
 */
class IHMExpressionParserClass
{
	//constants
	private static $constantTag     = '@';
	private static $constantNode    = 'constant';
	private static $constantNameAtt = 'name';

	//aliases
	private static $aliasTag     = '#';
	private static $aliasNode    = 'alias';
	private static $aliasNameAtt = 'name';

	//functions
	private static $functionsNode    = 'function';
	private static $functionsNameAtt = 'name';
	private static $functionsArgsAtt = 'args';
	private static $functionsNewKernelNode = 'new_kernel';

	//operator
	private static $operators = array(
			//standard operators
			"+" => array("type" => "operator"),
			"-" => array("type" => "operator"),
			"*" => array("type" => "operator"),
			"/" => array("type" => "operator"),
			//operators that's need to be translate by a function for the kernel
			"^" => array("type" => "function", "function" => "pow"),
			"<" => array("type" => "function", "function" => "lower_than"),
			">" => array("type" => "function", "function" => "greater_than"),
			"&" => array("type" => "function", "function" => "And"),
			"|" => array("type" => "function", "function" => "Or")
	);

	private $constantsArray;

	private $aliasesArray;

	private $functionsArray;
e4545ed5   Benjamin Renard   Implement templat...
46
47
	
	private $templatedParamMgr = NULL;
ffc5cb81   Elena.Budnik   temporary commit
48
	private $impexParamMgr = NULL;
f25e55ba   Benjamin Renard   Add sum in table ...
49
50
	
	private $isTest = FALSE;
22521f1c   Benjamin Renard   First commit
51
52
53
54

	/*
	 * @brief Constructor
	*/
f25e55ba   Benjamin Renard   Add sum in table ...
55
	function __construct($isTest = FALSE)
22521f1c   Benjamin Renard   First commit
56
	{
f25e55ba   Benjamin Renard   Add sum in table ...
57
58
59
		$this->isTest = $isTest;
		if (!$isTest)
			$this->templatedParamMgr = new IHMParamTemplateClass();
22521f1c   Benjamin Renard   First commit
60
61
62
63
64
65
66
67
68
	}

	/*
	 * @brief test function
	*/
	public function test()
	{
		//tests
		$tests = array(
f25e55ba   Benjamin Renard   Add sum in table ...
69
70
71
72
73
74
75
76
77
78
79
80
81
				"dst>3" => array ("expression" => "greater_than(\$dst,3)", "params" => array(array("paramid" => "dst"))),
				"@const_1<dst" => array("expression" => "(lower_than(1.0E-10,\$dst))", "params" => array(array("paramid" =>"dst"))),
				"dst^#alias_2" => array("expression" => "(pow(\$dst,\$imf[1]))", "params" => array(array("paramid" => "dst"),array("paramid" => "imf"))),
				"dst^2+@const_2" => array("expression" => "(pow(\$dst,2))+-2.8", "params" => array(array("paramid" => "dst"))),
				"atan(imf(2)/imf(1))+speed/100.0" => array("expression" => "atan((\$imf[2]/\$imf[1]))+(\$speed/100.0)", "params" => array(array("paramid" => "imf"), array("paramid" => "speed"))),
				"shiftT_(clust1_hia_pad,60)" => array("expression" => "#timeShift(\$clust1_hia_pad;60)", "params" => array(array("paramid" => "clust1_hia_pad"))),
				"smooth_(density,1200)" => array("expression" => "#boxcar(\$density;1200)", "params" => array(array("paramid" => "density"))),
				"shiftT_(density,-600)" => array("expression" => "#timeShift(\$density;-600)", "params" => array(array("paramid" => "density"))),
				"deriv(density)" => array("expression" => "#deriv(\$density)", "params" => array(array("paramid" => "density"))),
				"abs(dst)" =>array("expression" => "abs(\$dst)", "params" => array(array("paramid" => "dst"))),
				"density*speed+(density^2-1.0)/speed" => array("expression" => "(\$density*\$speed)+((pow(\$density,2))-1.0)/\$speed", "params" => array(array("paramid" => "density"),array("paramid" => "speed"))),
				"(-7<dst)&(dst<-3)" => array("expression" => "And((lower_than(-7,\$dst)),(lower_than(\$dst,-3)))", "params" => array(array("paramid" => "dst"))),
				"cass_caps_elssec4(range[0,10])" => array("expression" => "\$sum_into_table_range_cass_caps_elssec4_0_0_10", "params" => array(array("paramid" => "sum_into_table_range_cass_caps_elssec4_0_0_10")))
22521f1c   Benjamin Renard   First commit
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
		);

		//init constants, aliases and functions for test
		$this->constantsArray = array(
				"@const_1" => 1e-10,
				"@const_2" => -2.8
		);

		$this->aliasesArray = array(
				"#alias_1" => "dst",
				"#alias_2" => "imf(1)"
		);

		$this->functionsArray = array(
				"func_old" => array("kernel_name" => "func_new", "nb_args" => 0),
				"atan" => array("kernel_name" => "atan", "nb_args" => 0),
				"shiftT_" => array("kernel_name" => "#timeShift", "nb_args" => 1),
				"smooth_" => array("kernel_name" => "#boxcar", "nb_args" => 1),
				"deriv" => array("kernel_name" => "#deriv", "nb_args" => 0),
				"abs" => array("kernel_name" => "abs", "nb_args" => 0)
		);

		//add operator to change in function
		foreach (self::$operators as $operator)
		{
			if ($operator["type"] == "function")
				$this->functionsArray[$operator["function"]] = 
					array("kernel_name" => $operator["function"], "nb_args" => 0);
		}

		//
		foreach ($tests as $key => $value)
		{
			echo "==> Test : ".$key.PHP_EOL;

			$res = $this->parse($key);
				
			echo "Result : ".$res["expression"].PHP_EOL;
				
			echo json_encode($value).PHP_EOL.json_encode($res).PHP_EOL;
				
			if (json_encode($value) == json_encode($res))
				echo "OK !".PHP_EOL;
			else
				echo "ERROR !".PHP_EOL;
		}
	}

	/*
	 * @brief main method to parse a IHM expression
	*/
	public function parse($expression)
	{
		//echo "Source expression : ".$expression.PHP_EOL;
		//clean expression and replace constants and aliases by associated value
		$this->clean($expression);
		$this->replaceConstants($expression);
		$this->replaceAliases($expression);
		$this->clean($expression);

		//explode expression
		$elements = $this->explodeExpression($expression);
		
		//group elements in tree
		$tree = $this->buildTreeElements($elements);
ffc5cb81   Elena.Budnik   temporary commit
147
 	
22521f1c   Benjamin Renard   First commit
148
149
150
		//translate
		$params_full = array();
		$translated = $this->translate($tree,$params_full);
ffc5cb81   Elena.Budnik   temporary commit
151
	
22521f1c   Benjamin Renard   First commit
152
153
		//keep only params id
		$params = array();
ffc5cb81   Elena.Budnik   temporary commit
154
		foreach ($params_full as $param_full) { 		 
f25e55ba   Benjamin Renard   Add sum in table ...
155
156
157
158
159
			if (array_key_exists("template_args", $param_full)) {
				$params[] = array(
					"paramid" => $param_full['id'],
					"fullparamid" => $param_full['fullparamid'],
					"template_args" => $param_full['template_args']
ffc5cb81   Elena.Budnik   temporary commit
160
				);			
f25e55ba   Benjamin Renard   Add sum in table ...
161
162
			}
			else if (!$this->isTest && (($templated_param_info = $this->templatedParamMgr->parseTemplatedParam($param_full["id"])) !== FALSE)) {
ffc5cb81   Elena.Budnik   temporary commit
163
164
165
166
167
168
169
170
171
172
				$params[] = $templated_param_info;					
			}
			else if ($this->isImpexParam($param_full["id"]))
			{
				if (!$this->impexParamMgr) 
				{
					$this->impexParamMgr = new IHMImpexParamClass();					
				}
				$templated_param_info = $this->impexParamMgr->parseImpexParam($param_full["id"]);
				$params[] = $templated_param_info;	
e4545ed5   Benjamin Renard   Implement templat...
173
174
175
176
			}
			else
				$params[] = array("paramid" => $param_full["id"]);
		}
ffc5cb81   Elena.Budnik   temporary commit
177
		 	
22521f1c   Benjamin Renard   First commit
178
179
		return array("expression" => $translated, "params" => $params);
	}
ffc5cb81   Elena.Budnik   temporary commit
180
181
182
183
184
185
	
	private function isImpexParam($paramID)
	{
		return preg_match("#^".IHMImpexParamClass::$paramPrefix."#",$paramID);
	}
	
22521f1c   Benjamin Renard   First commit
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
	/*
	 * @brief clean expression
	*/
	private function clean(&$expression)
	{
		//remove all " "
		$expression = str_replace(" ", "", $expression);

		//replace [ and { by (
		$expression = str_replace(array("[","{"), "(", $expression);

		//replace ] and } by )
		$expression = str_replace(array("]","}"), ")", $expression);
	}

	/*
	 * @brief detect if some constants are defined in the expression
	*/
	private function isConstantDetected($expression)
	{
		return preg_match('/'.self::$constantTag.'/', $expression);
	}

	/*
	 * @brief replace constants by real values in expression
	*/
	private function replaceConstants(&$expression)
	{
		if (!$this->isConstantDetected($expression))
			return;

		if (!isset($this->constantsArray))
		{
			//load constants array
			$dom = new DomDocument("1.0");
			$constantsXMLFile = IHMConfigClass::getConstantsFilePath();
			if (!$dom->load($constantsXMLFile))
				throw new Exception('Cannot load constants file');
				
			$this->constantsArray = array();
				
			$constants_ = $dom->getElementsByTagName(self::$constantNode);
			for ($i = 1; $i <  $constants_->length; $i++)
				$this->constantsArray[self::$constantTag.$constants_->item($i)->getAttribute(self::$constantNameAtt)] = $constants_->item($i)->nodeValue;
		}

		//replace
		$expression = strtr($expression, $this->constantsArray);

		//be sure that all constants are replaced
		if ($this->isConstantDetected($expression))
			throw new Exception('Cannot replace some constants : '.$expression);
	}

	/*
	 * @brief detect if at least one aliases is defined in the expression
	*/
	private function isAliasDetected($expression)
	{
		return preg_match('/'.self::$aliasTag.'/', $expression);
	}

	/*
	 * @brief replace aliases by real parameter id in expression
	*/
	private function replaceAliases(&$expression)
	{
		if (!$this->isAliasDetected($expression))
			return;

		if (!isset($this->aliasesArray))
		{
			//load aliases array
			$dom = new DomDocument("1.0");
			$aliasesXMLFile = IHMConfigClass::getUserAliasesFilePath();
			if (!$dom->load($aliasesXMLFile))
				throw new Exception('Cannot load aliases file');
				
			$this->aliasesArray = array();
				
			$aliases_ = $dom->getElementsByTagName(self::$aliasNode);
			for ($i = 1; $i <  $aliases_->length; $i++)
				$this->aliasesArray[self::$alias_tag.$aliases_->item($i)->getAttribute(self::$aliasNameAtt)] = $aliases_->item($i)->nodeValue;
		}

		//replace
		$expression = strtr($expression, $this->aliasesArray);

		//be sure that all aliases are replaced
		if ($this->isAliasDetected($expression))
			throw new Exception('Cannot replace some aliases : '.$expression);
	}

	/*
	 * @brief load list of available functions
	*/
	private function loadFunctions()
	{
		if (isset($this->functionsArray))
			return;
			
		$dom = new DomDocument("1.0");
		$functionsXMLFile = IHMConfigClass::getFunctionsFilePath();

		if (!$dom->load($functionsXMLFile))
			throw new Exception('Cannot load functions file');
			
		$this->functionsArray = array();

		$functions_ = $dom->getElementsByTagName(self::$functionsNode);
		 
		for ($i = 0; $i < $functions_->length; $i++)
		{
			$tempArr =  explode('(', $functions_->item($i)->getAttribute(self::$functionsNameAtt));
			$nbArgs  =  $functions_->item($i)->getAttribute(self::$functionsArgsAtt);
			$kernelFunctions_ = $functions_->item($i)->getElementsByTagName(self::$functionsNewKernelNode);
			if ($kernelFunctions_->length == 0)
				$kernelFunction = "";
			else
				$kernelFunction = $kernelFunctions_->item(0)->nodeValue;
			$this->functionsArray[$tempArr[0]] = array(
				"kernel_name" => $kernelFunction,
				"nb_args"     => intval($nbArgs),
				"isOperator"  => false
			);
		}

		//add operator to change in function
		foreach (self::$operators as $operator)
		{
			if ($operator["type"] == "function")
				$this->functionsArray[$operator["function"]] = array(
					"kernel_name" => $operator["function"],
					"nb_args"     => 0,
					"isOperator"  => true
			);
		}
	}

	/*
	 * @brief detect if the element is a function
	*/
	private function isFunction($element)
	{
		$this->loadFunctions();
		return array_key_exists($element,$this->functionsArray);
	}
f25e55ba   Benjamin Renard   Add sum in table ...
333
334
335
336
337
338
339
340
	
	/*
	 * @brief detect if the element is "range"
	 */
	private function isRange($element)
	{
		return ($element == "range");
	}
22521f1c   Benjamin Renard   First commit
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

	/*
	 * @brief detect if the element is an operator
	*/
	private function isOperator($c)
	{
		foreach (self::$operators as $key => $value)
		if ($key == $c)
			return true;
	}

	/*
	 * @brief get the function associated to an operator
	*/
	private function getOperatorAssociatedFunction($c)
	{
		foreach (self::$operators as $key => $value)
		if ($key == $c)
		if ($value["type"] == "function")
			return $value["function"];
		return "";
	}

	/*
	 * @brief detect if the operator needed to be replace by a function
	*/
	private function isOperatorToFunction($c)
	{
		return ($this->getOperatorAssociatedFunction($c) != "");
	}

	/*
	 * @brief detect if the element is a separator
	*/
	private function isSeparator($c)
	{
		return ($this->isOperator($c) || $c == "(" || $c == ")" || $c == ",");
	}

	/*
	 * @brief detect a decimal value
	*/
	private function isDecimal($element)
	{
		return preg_match("/^[+\-]?(?:0|[1-9]\d*)(?:\.?\d*)?(?:[eE][+\-]?\d+)?/",$element);
		//return preg_match("/[+\-]?(?:0|[1-9]\d*)(?:\.?\d*)?(?:[eE][+\-]?\d+)/",$element);
	}

	/*
	 * @brief detect an integer value
	*/
	private function isInteger($element)
	{
		return preg_match("/^\d+$/",$element);
	}

	/*
	 * @brief explode expression for parsing
	*/
	private function explodeExpression($expression)
	{
		$crt = "";
		$elements = array();
		for ($i = 0; $i < strlen($expression); ++$i)
		{
			$c = $expression[$i];
			if ($this->isSeparator($c))
			{
				if ((($c == "+") || ($c == "-")) &&
				preg_match('/^\d*\.?\d*[eE]$/',$crt))
				{
					//scientific decimal element => false positive separator
					$crt .= $c;
					continue;
				}
				//push in elements list
				if ($crt != "")
					$elements[] = $crt;
				$elements[] = $c;
				$crt = "";
				continue;
			}
			$crt .= $c;
		}
		if ($crt != "")
			$elements[] = $crt;
		
		//regroup parameters and components before to add brackets for operators priority
		$els = array();
		$i = 0;
		for ($i; $i < count($elements)-3; ++$i)
		{
			if (($elements[$i+1] == "(")          &&
				$this->isParameter($elements[$i]) &&
				$this->isInteger($elements[$i+2]) &&
				($elements[$i+3] == ")"))
			{
				$els[] = ($elements[$i].$elements[$i+1].$elements[$i+2].$elements[$i+3]);
				$i = $i+3;
				continue;
			}
			$els[] = $elements[$i];
		}

		for ($j = $i; $j < count($elements); ++$j)
			$els[] = $elements[$j];
		
		$elements = $els;
		
		//regroup negative number
		$els = array();
		$i = 0;
		for ($i; $i < count($elements)-1; ++$i)
		{
			if (($elements[$i] == "-") && (
					$this->isDecimal($elements[$i+1]) || $this->isInteger($elements[$i+1])))
			{
				if (($i == 0) || (!$this->isDecimal($elements[$i-1]) && !$this->isInteger($elements[$i-1]) && !$this->isParameter($elements[$i-1])))
				{
					$els[] = ($elements[$i].$elements[$i+1]);
					$i = $i+1;
					continue;
				}
			}
			$els[] = $elements[$i];
		}
		
		for ($j = $i; $j < count($elements); ++$j)
			$els[] = $elements[$j];
		
		$elements = $els;
		
		//add brackets for operators priority
		
		$els = array();
		$i = 0;
		for ($i; $i < count($elements)-2; ++$i)
		{
			if ($elements[$i+1] == "*" || $elements[$i+1] == "/" || $elements[$i+1] == "^" || $elements[$i+1] == "<")
			{
				if ($elements[$i] != ")")
				{
					$els[] = "(";
					$els[] = $elements[$i];
					$els[] = $elements[$i+1];
					$els[] = $elements[$i+2];
					$els[] = ")";
					$i += 2;
				}
				else
					$els[] = $elements[$i];
			}
			else
				$els[] = $elements[$i];
		}
		for ($j = $i; $j < count($elements); ++$j)
			$els[] = $elements[$j];

		//split parameters and components
		$elements = $els;
		
		$els = array();
		$i = 0;
		for ($i; $i < count($elements); ++$i)
		{
			$tmpArray = explode('(',$elements[$i]);
			if ((count($tmpArray) == 2) && ($tmpArray[0] != "") && ($tmpArray[1] != ""))
			{
				$tmpArray2 = explode(')',$tmpArray[1]);
				if ((count($tmpArray2) == 2) && ($tmpArray2[0] != "") && ($tmpArray2[1] == ""))
				{
					$els[] = "(";
					$els[] = $tmpArray[0];
					$els[] = "(";
					$els[] = $tmpArray2[0];
					$els[] = ")";
					$els[] = ")";
					continue;
				}
			}
			$els[] = $elements[$i];
		}
			
		return $els;
	}

	/*
	 * @brief build a tree of the expression
	*/
	private function buildTreeElements($elements)
	{
		$expression_group = array();
		$crt_group = &$expression_group;
		$opened_groups = array($expression_group);
		for($i = 0; $i < count($elements); ++$i)
		{
			if ($elements[$i] == "(")
			{
				array_push($opened_groups,array());
				continue;
			}
			if ($elements[$i] == ")")
			{
				$group_to_close = $opened_groups[count($opened_groups)-1];
				array_pop($opened_groups);
				if (count($opened_groups) <= 0)
					throw new Exception('Expression error - Brackets definition');
				array_push($opened_groups[count($opened_groups)-1],$group_to_close);
				continue;
			}
			if (count($opened_groups) <= 0)
				throw new Exception('Expression error - Brackets definition');
			array_push($opened_groups[count($opened_groups)-1],$elements[$i]);
		}

		if (count($opened_groups) != 1)
			throw new Exception('Expression error - Brackets definition');
		$expression_group = $opened_groups[0];

		return $expression_group;
	}

	/*
	 * @brief detect if the element is a parameter
	*/
	private function isParameter($element)
	{
		return (!is_array($element) &&
				!$this->isDecimal($element) &&
				!$this->isOperator($element) &&
				!$this->isFunction($element) &&
f25e55ba   Benjamin Renard   Add sum in table ...
572
573
				!$this->isRange($element) &&
				($element != ",") && ($element != ";") && ($element != "("));
22521f1c   Benjamin Renard   First commit
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
	}

	/*
	 * @brief detect if the element is a component for a parameter
	*/
	private function isParameterComponent($tree, $i)
	{
		$paramId = "";
		if ($i <= 0)
			return false;
		if (!$this->isParameter($tree[$i-1]))
			return false;
		return (is_array($tree[$i]) &&
				(count($tree[$i] == 1)) &&
				$this->isInteger($tree[$i][0]));
	}
f25e55ba   Benjamin Renard   Add sum in table ...
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
	
	/*
	 * @brief detect if the element is a range for a parameter
	*/
	private function isParameterRange($tree, $i)
	{
		$paramId = "";
		if ($i <= 0)
			return false;
		if (!$this->isParameter($tree[$i-1]))
			return false;
		return (is_array($tree[$i]) &&
				(count($tree[$i] == 1)) &&
				$this->isRange($tree[$i][0]));
	}
22521f1c   Benjamin Renard   First commit
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628

	/*
	 * @brief add a parameter
	*/
	private function addParameterIdInParameterArray($paramId, &$params)
	{
		foreach ($params as $param)
		if ($param["id"] == $paramId)
			return;
		$params[] = array("id" => $paramId, "indexes" => array(), "calib_infos" => array());
	}

	/*
	 * @brief add a parameter component
	*/
	private function addParameterComponentInParameterArray($paramId, $component, &$params)
	{
		foreach ($params as &$param)
		if ($param["id"] == $paramId)
		{
			array_push($param["indexes"],$component);
			return;
		}
	}
f25e55ba   Benjamin Renard   Add sum in table ...
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
	
	/*
	 * @brief add a parameter range
	*/
	private function addParameterRangeInParameterArray($paramId, $range, &$params)
	{
		$sum_parameter_id = "";
		if ((count($range) == 2) && (count($range[1]) == 3) && ($this->isInteger($range[1][0])) && ($this->isInteger($range[1][2])) & ($range[1][1] == ",")) {
			$sum_parameter_id = "sum_into_table_range_".$paramId."_0_".$range[1][0]."_".$range[1][2];
			$params[] = array("id"      => "sum_into_table_range",
					          "fullparamid"  => $sum_parameter_id,
							  "indexes" => array(),
							  "calib_infos" => array(),
					          "template_args" => array(
					          		"paramid" => $paramId,
									"relateddim" => 0,
					          		"min" => $range[1][0],
					          		"max" => $range[1][2]
							  )
					);
		}
		return $sum_parameter_id;
	}
22521f1c   Benjamin Renard   First commit
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668

	/*
	 * @brief process used to treat parameter components
	*/
	private function regroupParameterAndComponent($tree,&$params,&$result)
	{
		for ($i = 0; $i < count($tree); ++$i)
		{
			if (is_array($tree[$i]) && (count($tree[$i]) > 0))
			{
				$res = array();
				$this->regroupParameterAndComponent($tree[$i],$params,$res);
				$result[] = $res;
			}
			else if ($this->isParameter($tree[$i]))
			{
				$param = $tree[$i];
f25e55ba   Benjamin Renard   Add sum in table ...
669
				
22521f1c   Benjamin Renard   First commit
670
671
				if ($i < count($tree) - 1)
				{
f25e55ba   Benjamin Renard   Add sum in table ...
672
					if ($this->isParameterRange($tree,$i+1))
22521f1c   Benjamin Renard   First commit
673
					{
f25e55ba   Benjamin Renard   Add sum in table ...
674
675
						$sum_parameter_id = $this->addParameterRangeInParameterArray($param, $tree[$i+1], $params);
						$param = $sum_parameter_id;
22521f1c   Benjamin Renard   First commit
676
677
						++$i;
					}
f25e55ba   Benjamin Renard   Add sum in table ...
678
679
680
681
682
683
684
685
686
687
					else
					{
						$this->addParameterIdInParameterArray($param,$params);
						if ($this->isParameterComponent($tree,$i+1))
						{
							$this->addParameterComponentInParameterArray($param, $tree[$i+1][0], $params);
							$param .= ("[".$tree[$i+1][0]."]");
							++$i;
						}
					}
22521f1c   Benjamin Renard   First commit
688
				}
f25e55ba   Benjamin Renard   Add sum in table ...
689
690
691
				else 
					$this->addParameterIdInParameterArray($param,$params);
					
22521f1c   Benjamin Renard   First commit
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
				$result[] = $param;
			}
			else
			{
				$result[] = $tree[$i];
			}
		}
	}

	/*
	 * @brief replace all operators that's needed to be replace by a function
	*/
	private function fixOperatorToFunction($tree,&$result)
	{
		$i = 0;
		for ($i; $i < count($tree)-1; ++$i)
		{
			if ($this->isOperatorToFunction($tree[$i+1]))
			{
				if ($i >= count($tree)-2)
					throw new Exception('Expression error - Error in operator definition');
				
				if (is_array($tree[$i]))
				{
					$left = array();
					$this->fixOperatorToFunction($tree[$i],$left);
				}
				else
					$left     = $tree[$i];
				$function = $this->getOperatorAssociatedFunction($tree[$i+1]);
				if (is_array($tree[$i+2]))
				{
					$right = array();
					$this->fixOperatorToFunction($tree[$i+2],$right);
				}
				else
					$right    = $tree[$i+2];
				$result[] = $function;
				$result[] = array($left,",",$right);
				$i += 2;
			}
			else
			{
				if (is_array($tree[$i]))
				{
					$res = array();
					$this->fixOperatorToFunction($tree[$i],$res);
					$result[] = $res;
				}
				else
					$result[] = $tree[$i];
			}
		}

		for ($j = $i; $j < count($tree); ++$j)
		{
			if (is_array($tree[$j]))
			{
				$res = array();
				$this->fixOperatorToFunction($tree[$j],$res);
				$result[] = $res;			
			}
			else
				$result[] = $tree[$j];
		}
	}
	
	/*
	 * @brief process used to replace "," by ";" for function
	*/
	private function fixComaFunction($tree,$isFunctionGroup,&$result)
	{
		for ($i = 0; $i < count($tree); ++$i)
		{
			if (is_array($tree[$i]) && (count($tree[$i]) > 0))
			{
				$groupFunc = false;
				if (($i > 0) && (!is_array($tree[$i-1])))
				{
					$groupFunc = $this->isFunction($tree[$i-1]);
				}
				$res = array();
				$this->fixComaFunction($tree[$i],$groupFunc,$res);
				$result[] = $res;
			}
			else
			{
				if ($isFunctionGroup && ($tree[$i] == ','))
					$result[] = ';';
				else
					$result[] = $tree[$i];
			}
		}
	}

	/*
	 * @brief write the result expression from tree elements
	*/
	private function writeTranslate($tree,$params)
	{
		$translated = "";
		
		for ($i = 0; $i < count($tree); ++$i)
		{
			//echo "=> ".$tree[$i].PHP_EOL;
			if (is_array($tree[$i]))
			{
				//echo "ARRAY".PHP_EOL;
				if ((count($tree[$i]) > 1) || 
					(count($tree[$i]) == 1) && ($i>0) && (!is_array($tree[$i-1]) && $this->isFunction($tree[$i-1])))
					$translated .= ("(".$this->writeTranslate($tree[$i],$params).")");
				else
					$translated .= ($this->writeTranslate($tree[$i],$params));
			}
			else if ($this->isDecimal($tree[$i]))
			{
				//echo "DECIMAL ".$tree[$i].PHP_EOL;
				$translated .= $tree[$i];
			}
			else if ($this->isOperator($tree[$i]))
			{
				//echo "OPERATOR".PHP_EOL;
				$translated .= $tree[$i];
			}
			else if ($tree[$i] == ",")
			{
				//echo "COMA".PHP_EOL;
				$translated .= ",";
			}
			else if ($tree[$i] == ";")
			{
f25e55ba   Benjamin Renard   Add sum in table ...
823
				echo "DOT COMA".PHP_EOL;
22521f1c   Benjamin Renard   First commit
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
				$translated .= ";";
			}
			else if ($this->isFunction($tree[$i]))
			{
				//echo "FUNCTION".PHP_EOL;
				$kernelFunction = $this->functionsArray[$tree[$i]]["kernel_name"];
				if ($kernelFunction == "")
					throw new Exception('Expression error - Function '.$tree[$i]." not implemented");
				$firstArgForFunc = ($this->functionsArray[$tree[$i]]["nb_args"] != 0);
				$translated .= $kernelFunction;
			}
			else
			{
				$founded = false;
				foreach ($params as $param)
				{
					//echo "TEST ".$param["id"].PHP_EOL;

f25e55ba   Benjamin Renard   Add sum in table ...
842
843
844
845
846
847
848
					if (array_key_exists("template_args", $param))
					{
						$founded = true;
						$translated .= "\$".$param["fullparamid"];
						break;
					}
					else if ($param["id"] == $tree[$i])
22521f1c   Benjamin Renard   First commit
849
850
851
852
853
					{
						$founded = true;
						$translated .= ("\$".$tree[$i]);
						break;
					}
f25e55ba   Benjamin Renard   Add sum in table ...
854
					
22521f1c   Benjamin Renard   First commit
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
					foreach ($param["indexes"] as $index)
					{
						$temp = "";
						$temp .= ($param["id"]."[".$index."]");
						//echo "TEST 2 ".$temp.PHP_EOL;
						if ($temp == $tree[$i])
						{
							$founded = true;
							$translated .= ("\$".$tree[$i]);
							break;
						}
					}
					if ($founded)
						break;
				}
				if (!$founded)
				{
					throw new Exception('Expression error - Unknown element '.$tree[$i]);
				}
			}
		}

		return $translated;
	}

	/*
	 * @brief sequence used to translate a tree elements
	*/
	private function translate($tree,&$params)
	{
		$res_1 = array();
		$this->regroupParameterAndComponent($tree,$params,$res_1);
		
		$res_2 = array();
		$this->fixComaFunction($res_1,false,$res_2);

		$res_3 = array();
		$this->fixOperatorToFunction($res_2,$res_3);
		
		return $this->writeTranslate($res_3,$params);
	}
}

f25e55ba   Benjamin Renard   Add sum in table ...
898
/*$parser = new IHMExpressionParserClass(TRUE);
22521f1c   Benjamin Renard   First commit
899
900
901
902
903
904
905
 try {
$parser->test();
} catch (Exception $e) {
echo 'Exception detected : '.$e->getMessage().PHP_EOL;
}*/

?>