calculatie-parser
index.php
Code (php)
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
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
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 'on');
include 'lib.php';
$str = $_SERVER['QUERY_STRING'];
$parser = new Parser();
$fac = function($v){
$n = round($v[0]);
if($n > 0) {
$return = $n;
while(--$n > 0) {
$return *= $n;
}
return $return;
} elseif($n == 0) {
return 1;
} else {
throw new Exception('Faculty using neg. number');
return false;
}
};
$parser ->addOperator('Multiply', '*', 2, function($v){return $v[0]*$v[1];})
->addOperator('Division', '/', 2, function($v){if($v[1] == 0) {throw new Exception('Division by 0');} return $v[0]/$v[1];})
->addOperator('Plus', '+', 1, function($v){return $v[0]+$v[1];})
->addOperator('Minus', '-', 1, function($v){return $v[0]-$v[1];})
->addOperator('Power', '^', 3, function($v){return pow($v[0],$v[1]);})
->addOperator('Faculty', '!', 4, $fac, OperatorRule::VAR_BEFORE)
->addOperator('SquareRoot', 'W', 3, function($v){if($v[0] < 0) {throw new Exception('Irreal result');} return sqrt($v[0]);}, OperatorRule::VAR_AFTER)
->addOperator('Logarithm', 'log', 4, function($v){if($v[0] < 0 || $v[1] < 0) {throw new Exception('Irreal result');} return log($v[0],$v[1]);})
->addOperator('Pi', 'pi', null, function($v){return M_PI;}, OperatorRule::VAR_NONE)
->addOperator('E', 'e', null, function($v){return M_E;}, OperatorRule::VAR_NONE)
->addOperator('Equation', '=', 0, function($v){return ($v[0]==$v[1])?1:0;});
try {
$res = $parser->parse($str);
echo $str.' = '.$res;
} catch(Exception $e) {
echo $e->getMessage();
}
?>
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 'on');
include 'lib.php';
$str = $_SERVER['QUERY_STRING'];
$parser = new Parser();
$fac = function($v){
$n = round($v[0]);
if($n > 0) {
$return = $n;
while(--$n > 0) {
$return *= $n;
}
return $return;
} elseif($n == 0) {
return 1;
} else {
throw new Exception('Faculty using neg. number');
return false;
}
};
$parser ->addOperator('Multiply', '*', 2, function($v){return $v[0]*$v[1];})
->addOperator('Division', '/', 2, function($v){if($v[1] == 0) {throw new Exception('Division by 0');} return $v[0]/$v[1];})
->addOperator('Plus', '+', 1, function($v){return $v[0]+$v[1];})
->addOperator('Minus', '-', 1, function($v){return $v[0]-$v[1];})
->addOperator('Power', '^', 3, function($v){return pow($v[0],$v[1]);})
->addOperator('Faculty', '!', 4, $fac, OperatorRule::VAR_BEFORE)
->addOperator('SquareRoot', 'W', 3, function($v){if($v[0] < 0) {throw new Exception('Irreal result');} return sqrt($v[0]);}, OperatorRule::VAR_AFTER)
->addOperator('Logarithm', 'log', 4, function($v){if($v[0] < 0 || $v[1] < 0) {throw new Exception('Irreal result');} return log($v[0],$v[1]);})
->addOperator('Pi', 'pi', null, function($v){return M_PI;}, OperatorRule::VAR_NONE)
->addOperator('E', 'e', null, function($v){return M_E;}, OperatorRule::VAR_NONE)
->addOperator('Equation', '=', 0, function($v){return ($v[0]==$v[1])?1:0;});
try {
$res = $parser->parse($str);
echo $str.' = '.$res;
} catch(Exception $e) {
echo $e->getMessage();
}
?>
index_old.ph
Code (php)
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
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
<?php
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 'on');
include 'lib.php';
$str = $_SERVER['QUERY_STRING'];
$parser = new Parser();
function calcMultiply($v) {
return $v[0]*$v[1];
}
function calcDivision($v) {
if($v[1] == 0) {
throw new Exception('Division by 0');
}
return $v[0]/$v[1];
}
function calcPlus($v) {
return $v[0]+$v[1];
}
function calcMinus($v) {
return $v[0]-$v[1];
}
function calcPower($v) {
return pow($v[0], $v[1]);
}
function calcFaculty($v){
$n = round($v[0]);
if($n > 0) {
$return = $n;
while(--$n > 0) {
$return *= $n;
}
return $return;
} elseif($n == 0) {
return 1;
} else {
throw new Exception('Faculty using neg. number');
return false;
}
};
function calcSquareRoot($v) {
if($v[0] < 0) {
throw new Exception('Irreal result');
}
return sqrt($v[0]);
}
function calcLogarithm($v) {
if($v[0] < 0 || $v[1] < 0) {
throw new Exception('Irreal result');
}
return log($v[0], $v[1]);
}
function calcE($v) {
return M_E;
}
function calcEquation($v) {
return ($v[0]==$v[1])?1:0;
}
$parser ->addOperator('Multiply', '*', 2, 'calcMultiply')
->addOperator('Division', '/', 2, 'calcDivision')
->addOperator('Plus', '+', 1, 'calcPlus')
->addOperator('Minus', '-', 1, 'calcMinus')
->addOperator('Power', '^', 3, 'calcPower')
->addOperator('Faculty', '!', 4, 'calcFaculty', OperatorRule::VAR_BEFORE)
->addOperator('SquareRoot', 'W', 3, 'calcSquareRoot', OperatorRule::VAR_AFTER)
->addOperator('Logarithm', 'log', 4, 'calcLogarithm')
->addOperator('Pi', 'pi', null, 'pi', OperatorRule::VAR_NONE)
->addOperator('E', 'e', null, 'calcE', OperatorRule::VAR_NONE)
->addOperator('Equation', '=', 0, 'calcEquation');
try {
$res = $parser->parse($str);
echo $str.' = '.$res;
} catch(Exception $e) {
echo $e->getMessage();
}
?>
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 'on');
include 'lib.php';
$str = $_SERVER['QUERY_STRING'];
$parser = new Parser();
function calcMultiply($v) {
return $v[0]*$v[1];
}
function calcDivision($v) {
if($v[1] == 0) {
throw new Exception('Division by 0');
}
return $v[0]/$v[1];
}
function calcPlus($v) {
return $v[0]+$v[1];
}
function calcMinus($v) {
return $v[0]-$v[1];
}
function calcPower($v) {
return pow($v[0], $v[1]);
}
function calcFaculty($v){
$n = round($v[0]);
if($n > 0) {
$return = $n;
while(--$n > 0) {
$return *= $n;
}
return $return;
} elseif($n == 0) {
return 1;
} else {
throw new Exception('Faculty using neg. number');
return false;
}
};
function calcSquareRoot($v) {
if($v[0] < 0) {
throw new Exception('Irreal result');
}
return sqrt($v[0]);
}
function calcLogarithm($v) {
if($v[0] < 0 || $v[1] < 0) {
throw new Exception('Irreal result');
}
return log($v[0], $v[1]);
}
function calcE($v) {
return M_E;
}
function calcEquation($v) {
return ($v[0]==$v[1])?1:0;
}
$parser ->addOperator('Multiply', '*', 2, 'calcMultiply')
->addOperator('Division', '/', 2, 'calcDivision')
->addOperator('Plus', '+', 1, 'calcPlus')
->addOperator('Minus', '-', 1, 'calcMinus')
->addOperator('Power', '^', 3, 'calcPower')
->addOperator('Faculty', '!', 4, 'calcFaculty', OperatorRule::VAR_BEFORE)
->addOperator('SquareRoot', 'W', 3, 'calcSquareRoot', OperatorRule::VAR_AFTER)
->addOperator('Logarithm', 'log', 4, 'calcLogarithm')
->addOperator('Pi', 'pi', null, 'pi', OperatorRule::VAR_NONE)
->addOperator('E', 'e', null, 'calcE', OperatorRule::VAR_NONE)
->addOperator('Equation', '=', 0, 'calcEquation');
try {
$res = $parser->parse($str);
echo $str.' = '.$res;
} catch(Exception $e) {
echo $e->getMessage();
}
?>
lib.php
Code (php)
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
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
<?php
/**
* CalculationParser
*
* @autor Pim de Haan <[email protected]>
* @version 1.0
* @package CalculationParser
*
* @todo Support for argumented operators, e.g. x(a, b)
* @todo Improving error messages
* @todo Seperate Lexer and part handler
*/
/**
* The Parser class
* @package CalculationParser
*/
class Parser {
/**
* Storing the lexer
* @var Lexer
*/
private $_lex;
/**
* List of added {@link OperatorRule}
* @var array
*/
private $_operators = array();
/**
* Constructor sets up the {@link $_lex}
*/
public function __construct() {
$this->_lex = new Lexer;
}
/**
* Adds an {@link OperatorRule} to {@link $_operators}
* Return itself for chained calls
*
* @param string $name Name
* @param string $symbol Symbol
* @param int $hierarchy Hierarchy level
* @param Closure $function The anonymous function which provides the actual operation
* @param int $varPos Providing where the operators elements are located
* @return Parser
*/
public function addOperator($name, $symbol, $hierarchy, $function, $varPos = null) {
$this->_operators[$symbol] = new OperatorRule($name, $symbol, $hierarchy, $function, $varPos);
return $this;
}
/**
* Return the array of operator symbols
* @return array
*/
private function _operatorArray() {
$return = array();
foreach($this->_operators as $op) {
$return[] = $op->getSymbol();
}
}
/**
* The actual parsing.
* At first, splits the input string by the {@link Lexer}
* Then loops following code until only a single float remains:
* <ul>
*
* <li>All tokens, {@link Token}, are retrieved one by one.
* <ul>
* <li>If the token is a operator, {@link OperatorToken}, a new {@link Operator} is added to the operators array along with its hierarchy and part offset.</li>
* <li>If it is a parentesis, {@link OpenToken} or {@link CloseToken}, the parenthesesOpen variable is modified, which alters the next operators hierarchy.</li>
* </ul></li>
*
* <li>Then the operator with the higherst hierarchy is selected.</li>
*
* <li>If the operator has a variable in front of it, the next actions are exectued
* <ul>
* <li>The number in front of it is retrieved</li>
* <li>It is tested wether it's a number</li>
* <li>It is deleted from the {@link Lexer}s parts list</li>
* <li>It is added as a variable to the operator</li>
* </ul>
* This is also executed if it has a variable after it</li>
*
* <li>The operators result is calculated</li>
* <li>The result replaces the operator in the {@link Lexer}s parts list</li>
* <li>The parenteses behind and after it are deleted from the {@link Lexer}s parts list</li>
*
* </ul>
*
* @return int
*/
public function parse($text) {
$this->_lex->lex($text, array_keys($this->_operators));
while(false === $res = $this->_lex->done()) {
$parenthesesOpen = 0;
$operators = array();
$this->_lex->reset();
while(false !== $token = $this->_lex->getToken()) {
if($token instanceof OperatorToken) {
$hierarchy = $this->_operators[$token->getOperation()]->getHierarchy() + 20*$parenthesesOpen;
$operators[] = new Operator($this->_operators[$token->getOperation()], $hierarchy, $token->getOffset());
} elseif($token instanceof OpenToken) {
$parenthesesOpen++;
} elseif($token instanceof CloseToken) {
if($parenthesesOpen-- == 0) {
throw new Exception('Syntax Error');
}
}
}
if(empty($operators)) {
throw new Exception('Syntax Error');
}
$highestOperator = null;
$highestHierarchy = -10;
foreach($operators as $operator) {
if($operator->getHierarchy() > $highestHierarchy) {
$highestOperator = $operator;
$highestHierarchy = $operator->getHierarchy();
}
}
$operator = $highestOperator;
$operatorOffset = $operator->getOffset();
$varPositions = $operator->getRule()->getVarPositions();
$parenthesisBeforeOffset = 1;
$parenthesisAfterOffset = 1;
// If operator has a variable before it
if($varPositions & OperatorRule::VAR_BEFORE) {
$num = $this->_lex->getToken($operatorOffset-1);
if(!is_float($num)) {
throw new Exception('Syntax error');
}
$this->_lex->delete($operatorOffset-1);
$operator->addVar($num);
$parenthesisBeforeOffset = 2;
}
// If operator has a variable after it
if($varPositions & OperatorRule::VAR_AFTER) {
$num = $this->_lex->getToken($operatorOffset+1);
if(!is_float($num)) {
throw new Exception('Syntax error');
}
$this->_lex->delete($operatorOffset+1);
$operator->addVar($num);
$parenthesisAfterOffset = 2;
}
$res = $operator->calc();
$this->_lex->replace($operatorOffset, $res);
// Delete Haakjes
if($this->_lex->getToken($operatorOffset-$parenthesisBeforeOffset) instanceof OpenToken &&
$this->_lex->getToken($operatorOffset+$parenthesisAfterOffset) instanceof CloseToken) {
$this->_lex->delete($operatorOffset-$parenthesisBeforeOffset)->delete($operatorOffset+$parenthesisAfterOffset);
}
$this->_lex->update();
}
return $res;
}
}
/**
* The lexer wich splits the input text into parts and provides and modifies these parts
* @package CalculationParser
*/
class Lexer {
/**
* The list of parts
* @var array
*/
private $_parts;
/**
* The amount of parts
* @var int
*/
private $_partsCount;
/**
* The internal pointer
* @var int
*/
private $_pointer = -1;
/**
* The list of operator symbols
* @var array
*/
private $_operators;
/**
* The lexer function, which:
* <ul>
* <li>Removes spaces</li>
* <li>Modefies the shorthand writing, 4(5+2) to 4*(5+2)</li>
* <li>Prepares the operator list using {@link $_operators} to be used in the regex</li>
* <li>Splits using preg_match_all</li>
* <li>Checks wether parts are remaining and if so, throw an excpetion</li>
* <li>Fills {@link $_parts} and {@link $_partsCount}</li>
* </ul>
*
* @param string $text The input text
* @param array $operators The array of operator symbols {@link $_operators}
*/
public function lex($text, $operators) {
$text = str_replace(' ', '', $text);
$text = preg_replace('/([0-9|\)])\(/', '$1*(', $text);
$this->_operators = $operators;
$tokenList = implode('|', array_map('preg_quote', $operators));
/**
* Explanation regex:
* Define part if string:
* - is a Operator
* - is a Parentesis
* - is a number may or may not be followed by a dot and another number
* following a minus sign, which is not following by a number
*
* followed by a E and a positive or negative number
* - is a dot follewed by a number may or may not be following a minus sign, which is not following a number
*/
$reg = '#((?<!\d)\-)?((\d+(\.?\d+)?)|(\.\d+))(E[\+\-]?\d+?)?|'.$tokenList.'|\(|\)#';
preg_match_all($reg, $text, $matches);
// Checks for remaining parts
$total = 0;
foreach($matches[0] as $match) {
$total += strlen($match);
}
if($total != strlen($text)) {
throw new Exception('Syntax error');
}
$this->_parts = $matches[0];
$this->_partsCount = count($this->_parts);
if($this->_partsCount == 0) {
throw new Exception('No input given');
}
}
/**
* Detemines wether only one float is left and if so, returns its value
*
* @return int|false
*/
public function done() {
if($this->_partsCount == 1 && is_numeric($this->_parts[0])) {
return ((float)$this->_parts[0]);
} else {
return false;
}
}
/**
* Analyzes {@link _analyze()} and returns next {@link Token} or the token at the specified offset
*
* @param int $offset The optional offset
* @return Token
*/
public function getToken($offset = null) {
if(is_null($offset)) {
$offset = ++$this->_pointer;
}
if(isset($this->_parts[$offset])) {
return $this->_analyze($this->_parts[$offset], $offset);
} else {
return false;
}
}
/**
* Analyses the given string and returns a {@link Token} or float
*
* @param string $token The input string
* @param int $offset The strings offset
* @return float|OpenToken|CloseToken|OperatorToken
*/
private function _analyze($token, $offset) {
if(is_numeric($token)) {
return (float) $token;
} elseif($token == '(') {
return new OpenToken;
} elseif($token == ')') {
return new CloseToken;
} else {
if(!in_array($token, $this->_operators)) {
throw new Exception('Foute operator: "'.$token.'"');
return;
} else {
return new OperatorToken($token, $offset);
}
}
}
/**
* Updates {@link $_parts} by removing empty parts
*
* @return Lexer
*/
public function update() {
$new = array();
foreach($this->_parts as $part) {
$new[] = $part;
}
$this->_parts = $new;
$this->_partsCount = count($this->_parts);
return $this;
}
/**
* Deletes part from {@link $_parts} at given offset
*
* @param int $offset Offset
* @return Lexer
*/
public function delete($offset) {
if(isset($this->_parts[$offset])) {
unset($this->_parts[$offset]);
}
return $this;
}
/**
* Resets internal {@link $_pointer}
*
* @return Lexer
*/
public function reset() {
$this->_pointer = -1;
return $this;
}
/**
* Replaces part at given offset with given part
*
* @param int $offset Offset
* @param float|string $part Replacement value
*/
public function replace($offset, $part) {
$this->_parts[$offset] = $part;
return $this;
}
}
/**
* Currently empty abstract class which is extends by specified Token classes
*
* Tokens are parts returned by {@link Lexer::_getToken()} which contain a certain part of the input string
* @package CalculationParser
*/
abstract class Token {}
/**
* Token for an opening parentesis
* @package CalculationParser
*/
class OpenToken extends Token {}
/**
* Token for an closing parentesis
* @package CalculationParser
*/
class CloseToken extends Token {}
/**
* Token for an operator
* @package CalculationParser
*/
class OperatorToken extends Token {
/**
* The operation symbol
* @var string
*/
private $_operation;
/**
* The offset in the {@link Lexer::$_parts}
* @var string
*/
private $_offset;
/**
* The constructor, sets {@link $_operation} and {@link $_offset}
*
* @param string $operation The operation symbol
* @param int $offset The offset
*/
public function __construct($operation, $offset) {
$this->_operation = $operation;
$this->_offset = $offset;
}
/**
* Returns {@link $_operation}
* @return string
*/
public function getOperation() {
return $this->_operation;
}
/**
* Returns {@link $_offset}
* @return int
*/
public function getOffset() {
return $this->_offset;
}
}
/**
* The operator in {@link Parser::parse()}
* @package CalculationParser
*/
class Operator {
/**
* The {@link OperatorRule}
* @var OperatorRule
*/
private $_rule;
/**
* The hierarchy
* @var int
*/
private $_hierarchy;
/**
* The offset in the {@link Lexer::$_parts}
* @var int
*/
private $_offset;
/**
* The variables
* @var array
*/
private $_vars = array();
/**
* The constructor, sets {@link $_rule}, {@link $_hierarchy} and {@link $_offset}
*
* @param OperatorRule $rule The OperatorRule
* @param int $hierarchy The hierarchy
* @param int $offset The offset
*/
public function __construct(OperatorRule $rule, $hierarchy, $offset) {
$this->_rule = $rule;
$this->_hierarchy = $hierarchy;
$this->_offset = $offset;
}
/**
* Returns {@link $_rule}
* @return OperatorRule
*/
public function getRule() {
return $this->_rule;
}
/**
* Returns {@link $_hierarchy}
* @return int
*/
public function getHierarchy() {
return $this->_hierarchy;
}
/**
* Returns {@link $_offset}
* @return int
*/
public function getOffset() {
return $this->_offset;
}
/**
* Adds a variable to {@link $_vars}
*
* @param float $var The variable
* @return Operator
*/
public function addVar($var) {
$this->_vars[] = $var;
return $this;
}
/**
* Do the calculation based on {@link $_vars} by calling the anonymous funtion in the {@link $_rule}
*/
public function calc() {
return $this->_rule->calc($this->_vars);
}
}
/**
* Class for defining operations
* @package CalculationParser
*/
class OperatorRule {
/**
* The name
* @var string
*/
private $_name;
/**
* The symbol
* @var string
*/
private $_symbol;
/**
* The base hierarchy
* @var int
*/
private $_hierarchy;
/**
* The anonymous function
* @var Closure
*/
private $_function;
/**
* The positions of the variables, bitwise
* @var int
*/
private $_varPositions;
/**
* The constant for the variable position 'before'
* @see $_varPositions
*
* @var int
*/
const VAR_BEFORE = 1;
/**
* The constant for the variable position 'after'
* @see $_varPositions
*
* @var int
*/
const VAR_AFTER = 2;
/**
* The constant for the variable position 'after' and 'before'
* @see $_varPositions
*
* @var int
*/
const VAR_BOTH = 3;
/**
* The constant for no variable positions, meaning the operator is a constant
* @see $_varPositions
*
* @var int
*/
const VAR_NONE = 0;
/**
* The constructor, sets {@link $_name}, {@link $_symbol}, {@link $_hierarchy}, {@link $_function}, and optionally {@link $_varPositions}
* If the operator is a constant, the hierarchy is very high
*
* @param string $name The name
* @param string $symbol The symbol
* @param int $hierarchy The hierarchy
* @param Closure $function The anonymous function
* @param int $varPositions The optional variable positions
*/
public function __construct($name, $symbol, $hierarchy, $function, $varPositions = null) {
$this->_name = $name;
$this->_symbol = $symbol;
$this->_hierarchy = ($varPositions === self::VAR_NONE)?1000:$hierarchy;
$this->_function = $function;
$this->_varPositions = (!is_null($varPositions) ? $varPositions : self::VAR_BOTH);
}
/**
* Returns {@link $_name}
* @return string
*/
public function getName() {
return $this->_name;
}
/**
* Returns {@link $_symbol}
* @return string
*/
public function getSymbol() {
return $this->_symbol;
}
/**
* Returns {@link $_hierarchy}
* @return int
*/
public function getHierarchy() {
return $this->_hierarchy;
}
/**
* Returns {@link $_varPositions}
* @return int
*/
public function getVarPositions() {
return $this->_varPositions;
}
/**
* Do the calculation by executing the {@link $_function} and give the arguments to this method as arguments to the anonymous function
* @param float $v,... The variables
* @return float The result
*/
public function calc() {
$args = func_get_args();
return (float) call_user_func_array($this->_function, $args);
}
}
?>
/**
* CalculationParser
*
* @autor Pim de Haan <[email protected]>
* @version 1.0
* @package CalculationParser
*
* @todo Support for argumented operators, e.g. x(a, b)
* @todo Improving error messages
* @todo Seperate Lexer and part handler
*/
/**
* The Parser class
* @package CalculationParser
*/
class Parser {
/**
* Storing the lexer
* @var Lexer
*/
private $_lex;
/**
* List of added {@link OperatorRule}
* @var array
*/
private $_operators = array();
/**
* Constructor sets up the {@link $_lex}
*/
public function __construct() {
$this->_lex = new Lexer;
}
/**
* Adds an {@link OperatorRule} to {@link $_operators}
* Return itself for chained calls
*
* @param string $name Name
* @param string $symbol Symbol
* @param int $hierarchy Hierarchy level
* @param Closure $function The anonymous function which provides the actual operation
* @param int $varPos Providing where the operators elements are located
* @return Parser
*/
public function addOperator($name, $symbol, $hierarchy, $function, $varPos = null) {
$this->_operators[$symbol] = new OperatorRule($name, $symbol, $hierarchy, $function, $varPos);
return $this;
}
/**
* Return the array of operator symbols
* @return array
*/
private function _operatorArray() {
$return = array();
foreach($this->_operators as $op) {
$return[] = $op->getSymbol();
}
}
/**
* The actual parsing.
* At first, splits the input string by the {@link Lexer}
* Then loops following code until only a single float remains:
* <ul>
*
* <li>All tokens, {@link Token}, are retrieved one by one.
* <ul>
* <li>If the token is a operator, {@link OperatorToken}, a new {@link Operator} is added to the operators array along with its hierarchy and part offset.</li>
* <li>If it is a parentesis, {@link OpenToken} or {@link CloseToken}, the parenthesesOpen variable is modified, which alters the next operators hierarchy.</li>
* </ul></li>
*
* <li>Then the operator with the higherst hierarchy is selected.</li>
*
* <li>If the operator has a variable in front of it, the next actions are exectued
* <ul>
* <li>The number in front of it is retrieved</li>
* <li>It is tested wether it's a number</li>
* <li>It is deleted from the {@link Lexer}s parts list</li>
* <li>It is added as a variable to the operator</li>
* </ul>
* This is also executed if it has a variable after it</li>
*
* <li>The operators result is calculated</li>
* <li>The result replaces the operator in the {@link Lexer}s parts list</li>
* <li>The parenteses behind and after it are deleted from the {@link Lexer}s parts list</li>
*
* </ul>
*
* @return int
*/
public function parse($text) {
$this->_lex->lex($text, array_keys($this->_operators));
while(false === $res = $this->_lex->done()) {
$parenthesesOpen = 0;
$operators = array();
$this->_lex->reset();
while(false !== $token = $this->_lex->getToken()) {
if($token instanceof OperatorToken) {
$hierarchy = $this->_operators[$token->getOperation()]->getHierarchy() + 20*$parenthesesOpen;
$operators[] = new Operator($this->_operators[$token->getOperation()], $hierarchy, $token->getOffset());
} elseif($token instanceof OpenToken) {
$parenthesesOpen++;
} elseif($token instanceof CloseToken) {
if($parenthesesOpen-- == 0) {
throw new Exception('Syntax Error');
}
}
}
if(empty($operators)) {
throw new Exception('Syntax Error');
}
$highestOperator = null;
$highestHierarchy = -10;
foreach($operators as $operator) {
if($operator->getHierarchy() > $highestHierarchy) {
$highestOperator = $operator;
$highestHierarchy = $operator->getHierarchy();
}
}
$operator = $highestOperator;
$operatorOffset = $operator->getOffset();
$varPositions = $operator->getRule()->getVarPositions();
$parenthesisBeforeOffset = 1;
$parenthesisAfterOffset = 1;
// If operator has a variable before it
if($varPositions & OperatorRule::VAR_BEFORE) {
$num = $this->_lex->getToken($operatorOffset-1);
if(!is_float($num)) {
throw new Exception('Syntax error');
}
$this->_lex->delete($operatorOffset-1);
$operator->addVar($num);
$parenthesisBeforeOffset = 2;
}
// If operator has a variable after it
if($varPositions & OperatorRule::VAR_AFTER) {
$num = $this->_lex->getToken($operatorOffset+1);
if(!is_float($num)) {
throw new Exception('Syntax error');
}
$this->_lex->delete($operatorOffset+1);
$operator->addVar($num);
$parenthesisAfterOffset = 2;
}
$res = $operator->calc();
$this->_lex->replace($operatorOffset, $res);
// Delete Haakjes
if($this->_lex->getToken($operatorOffset-$parenthesisBeforeOffset) instanceof OpenToken &&
$this->_lex->getToken($operatorOffset+$parenthesisAfterOffset) instanceof CloseToken) {
$this->_lex->delete($operatorOffset-$parenthesisBeforeOffset)->delete($operatorOffset+$parenthesisAfterOffset);
}
$this->_lex->update();
}
return $res;
}
}
/**
* The lexer wich splits the input text into parts and provides and modifies these parts
* @package CalculationParser
*/
class Lexer {
/**
* The list of parts
* @var array
*/
private $_parts;
/**
* The amount of parts
* @var int
*/
private $_partsCount;
/**
* The internal pointer
* @var int
*/
private $_pointer = -1;
/**
* The list of operator symbols
* @var array
*/
private $_operators;
/**
* The lexer function, which:
* <ul>
* <li>Removes spaces</li>
* <li>Modefies the shorthand writing, 4(5+2) to 4*(5+2)</li>
* <li>Prepares the operator list using {@link $_operators} to be used in the regex</li>
* <li>Splits using preg_match_all</li>
* <li>Checks wether parts are remaining and if so, throw an excpetion</li>
* <li>Fills {@link $_parts} and {@link $_partsCount}</li>
* </ul>
*
* @param string $text The input text
* @param array $operators The array of operator symbols {@link $_operators}
*/
public function lex($text, $operators) {
$text = str_replace(' ', '', $text);
$text = preg_replace('/([0-9|\)])\(/', '$1*(', $text);
$this->_operators = $operators;
$tokenList = implode('|', array_map('preg_quote', $operators));
/**
* Explanation regex:
* Define part if string:
* - is a Operator
* - is a Parentesis
* - is a number may or may not be followed by a dot and another number
* following a minus sign, which is not following by a number
*
* followed by a E and a positive or negative number
* - is a dot follewed by a number may or may not be following a minus sign, which is not following a number
*/
$reg = '#((?<!\d)\-)?((\d+(\.?\d+)?)|(\.\d+))(E[\+\-]?\d+?)?|'.$tokenList.'|\(|\)#';
preg_match_all($reg, $text, $matches);
// Checks for remaining parts
$total = 0;
foreach($matches[0] as $match) {
$total += strlen($match);
}
if($total != strlen($text)) {
throw new Exception('Syntax error');
}
$this->_parts = $matches[0];
$this->_partsCount = count($this->_parts);
if($this->_partsCount == 0) {
throw new Exception('No input given');
}
}
/**
* Detemines wether only one float is left and if so, returns its value
*
* @return int|false
*/
public function done() {
if($this->_partsCount == 1 && is_numeric($this->_parts[0])) {
return ((float)$this->_parts[0]);
} else {
return false;
}
}
/**
* Analyzes {@link _analyze()} and returns next {@link Token} or the token at the specified offset
*
* @param int $offset The optional offset
* @return Token
*/
public function getToken($offset = null) {
if(is_null($offset)) {
$offset = ++$this->_pointer;
}
if(isset($this->_parts[$offset])) {
return $this->_analyze($this->_parts[$offset], $offset);
} else {
return false;
}
}
/**
* Analyses the given string and returns a {@link Token} or float
*
* @param string $token The input string
* @param int $offset The strings offset
* @return float|OpenToken|CloseToken|OperatorToken
*/
private function _analyze($token, $offset) {
if(is_numeric($token)) {
return (float) $token;
} elseif($token == '(') {
return new OpenToken;
} elseif($token == ')') {
return new CloseToken;
} else {
if(!in_array($token, $this->_operators)) {
throw new Exception('Foute operator: "'.$token.'"');
return;
} else {
return new OperatorToken($token, $offset);
}
}
}
/**
* Updates {@link $_parts} by removing empty parts
*
* @return Lexer
*/
public function update() {
$new = array();
foreach($this->_parts as $part) {
$new[] = $part;
}
$this->_parts = $new;
$this->_partsCount = count($this->_parts);
return $this;
}
/**
* Deletes part from {@link $_parts} at given offset
*
* @param int $offset Offset
* @return Lexer
*/
public function delete($offset) {
if(isset($this->_parts[$offset])) {
unset($this->_parts[$offset]);
}
return $this;
}
/**
* Resets internal {@link $_pointer}
*
* @return Lexer
*/
public function reset() {
$this->_pointer = -1;
return $this;
}
/**
* Replaces part at given offset with given part
*
* @param int $offset Offset
* @param float|string $part Replacement value
*/
public function replace($offset, $part) {
$this->_parts[$offset] = $part;
return $this;
}
}
/**
* Currently empty abstract class which is extends by specified Token classes
*
* Tokens are parts returned by {@link Lexer::_getToken()} which contain a certain part of the input string
* @package CalculationParser
*/
abstract class Token {}
/**
* Token for an opening parentesis
* @package CalculationParser
*/
class OpenToken extends Token {}
/**
* Token for an closing parentesis
* @package CalculationParser
*/
class CloseToken extends Token {}
/**
* Token for an operator
* @package CalculationParser
*/
class OperatorToken extends Token {
/**
* The operation symbol
* @var string
*/
private $_operation;
/**
* The offset in the {@link Lexer::$_parts}
* @var string
*/
private $_offset;
/**
* The constructor, sets {@link $_operation} and {@link $_offset}
*
* @param string $operation The operation symbol
* @param int $offset The offset
*/
public function __construct($operation, $offset) {
$this->_operation = $operation;
$this->_offset = $offset;
}
/**
* Returns {@link $_operation}
* @return string
*/
public function getOperation() {
return $this->_operation;
}
/**
* Returns {@link $_offset}
* @return int
*/
public function getOffset() {
return $this->_offset;
}
}
/**
* The operator in {@link Parser::parse()}
* @package CalculationParser
*/
class Operator {
/**
* The {@link OperatorRule}
* @var OperatorRule
*/
private $_rule;
/**
* The hierarchy
* @var int
*/
private $_hierarchy;
/**
* The offset in the {@link Lexer::$_parts}
* @var int
*/
private $_offset;
/**
* The variables
* @var array
*/
private $_vars = array();
/**
* The constructor, sets {@link $_rule}, {@link $_hierarchy} and {@link $_offset}
*
* @param OperatorRule $rule The OperatorRule
* @param int $hierarchy The hierarchy
* @param int $offset The offset
*/
public function __construct(OperatorRule $rule, $hierarchy, $offset) {
$this->_rule = $rule;
$this->_hierarchy = $hierarchy;
$this->_offset = $offset;
}
/**
* Returns {@link $_rule}
* @return OperatorRule
*/
public function getRule() {
return $this->_rule;
}
/**
* Returns {@link $_hierarchy}
* @return int
*/
public function getHierarchy() {
return $this->_hierarchy;
}
/**
* Returns {@link $_offset}
* @return int
*/
public function getOffset() {
return $this->_offset;
}
/**
* Adds a variable to {@link $_vars}
*
* @param float $var The variable
* @return Operator
*/
public function addVar($var) {
$this->_vars[] = $var;
return $this;
}
/**
* Do the calculation based on {@link $_vars} by calling the anonymous funtion in the {@link $_rule}
*/
public function calc() {
return $this->_rule->calc($this->_vars);
}
}
/**
* Class for defining operations
* @package CalculationParser
*/
class OperatorRule {
/**
* The name
* @var string
*/
private $_name;
/**
* The symbol
* @var string
*/
private $_symbol;
/**
* The base hierarchy
* @var int
*/
private $_hierarchy;
/**
* The anonymous function
* @var Closure
*/
private $_function;
/**
* The positions of the variables, bitwise
* @var int
*/
private $_varPositions;
/**
* The constant for the variable position 'before'
* @see $_varPositions
*
* @var int
*/
const VAR_BEFORE = 1;
/**
* The constant for the variable position 'after'
* @see $_varPositions
*
* @var int
*/
const VAR_AFTER = 2;
/**
* The constant for the variable position 'after' and 'before'
* @see $_varPositions
*
* @var int
*/
const VAR_BOTH = 3;
/**
* The constant for no variable positions, meaning the operator is a constant
* @see $_varPositions
*
* @var int
*/
const VAR_NONE = 0;
/**
* The constructor, sets {@link $_name}, {@link $_symbol}, {@link $_hierarchy}, {@link $_function}, and optionally {@link $_varPositions}
* If the operator is a constant, the hierarchy is very high
*
* @param string $name The name
* @param string $symbol The symbol
* @param int $hierarchy The hierarchy
* @param Closure $function The anonymous function
* @param int $varPositions The optional variable positions
*/
public function __construct($name, $symbol, $hierarchy, $function, $varPositions = null) {
$this->_name = $name;
$this->_symbol = $symbol;
$this->_hierarchy = ($varPositions === self::VAR_NONE)?1000:$hierarchy;
$this->_function = $function;
$this->_varPositions = (!is_null($varPositions) ? $varPositions : self::VAR_BOTH);
}
/**
* Returns {@link $_name}
* @return string
*/
public function getName() {
return $this->_name;
}
/**
* Returns {@link $_symbol}
* @return string
*/
public function getSymbol() {
return $this->_symbol;
}
/**
* Returns {@link $_hierarchy}
* @return int
*/
public function getHierarchy() {
return $this->_hierarchy;
}
/**
* Returns {@link $_varPositions}
* @return int
*/
public function getVarPositions() {
return $this->_varPositions;
}
/**
* Do the calculation by executing the {@link $_function} and give the arguments to this method as arguments to the anonymous function
* @param float $v,... The variables
* @return float The result
*/
public function calc() {
$args = func_get_args();
return (float) call_user_func_array($this->_function, $args);
}
}
?>