This repository was archived by the owner on May 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexample.php
More file actions
79 lines (65 loc) · 1.81 KB
/
example.php
File metadata and controls
79 lines (65 loc) · 1.81 KB
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
<?php
include __DIR__ . '/tests/bootstrap.php';
class ArithParser extends Parsec\StringParser
{
public function __construct()
{
$factory = new Parsec\ContextFactory(array('\\'));
$lexer = new Parsec\Lexer(array(
'number' => '[0-9]+',
'plus' => '\+',
'minus' => '\-',
'multi' => '\*',
'div' => '\/',
'bracketOpen' => '\(',
'bracketClose' => '\)'
));
parent::__construct($lexer, $factory);
}
public function parse($string)
{
return parent::parse($string, 'Expression');
}
}
class Expression extends Parsec\Context
{
protected $number;
public function tokenNumber($value)
{
$this->number = $value;
}
public function tokenPlus()
{
$this->exitContext($this->number + $this->enterContext('Expression'));
}
public function tokenMinus()
{
$this->exitContext($this->number - $this->enterContext('Expression'));
}
public function tokenMulti()
{
$this->exitContext($this->number * $this->enterContext('Expression'));
}
public function tokenDiv()
{
$this->exitContext($this->number / $this->enterContext('Expression'));
}
public function tokenBracketOpen()
{
if ($this->number === null) {
$this->number = 1;
}
$this->exitContext($this->number * $this->enterContext('Expression'));
}
public function tokenBracketClose()
{
$this->exitContext($this->number);
}
public function tokenEos($text)
{
$this->exitContext($this->number);
}
}
$parser = new ArithParser();
printf("3 + 4 = %s\n", $parser->parse('3 + 4'));
printf("6 * (2 / 3) = %s\n", $parser->parse('6 * (2 / 3)'));