-
Notifications
You must be signed in to change notification settings - Fork 0
/
Calc.yp
65 lines (57 loc) · 1.58 KB
/
Calc.yp
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
#
# Calc.yp
#
# Parse::Yapp input grammar example.
#
# This file is PUBLIC DOMAIN
#
#
%right '='
%left '-' '+'
%left '*' '/'
%left NEG
%right '^'
%%
input: #empty
| input line { $_[1][] = $_[2];
return $_[1]; }
;
line: '\n'
| exp '\n' { print "$_[1]\n" }
| error '\n' { $this->YYErrok() }
;
exp: NUM
| VAR { $this->YYData->VARS->{$_[1]} = null }
| VAR '=' exp { $this->YYData->VARS->{$_[1]} = $_[3] }
| exp '+' exp { return $_[1] + $_[3] }
| exp '-' exp { return $_[1] - $_[3] }
| exp '*' exp { return $_[1] * $_[3] }
| exp '/' exp {
if ($_[3]) {
return $_[1] / $_[3];
}
$this->YYData->ERRMSG = "Illegal division by zero.\n";
$this->YYError();
}
| '-' exp %prec NEG { return -$_[2] }
| exp '^' exp { return $_[1] ** $_[3] }
| '(' exp ')' { return $_[2] }
;
%%
public function _Error()
{
if (!isset($this->YYData->ERRMSG)) {
print "Syntax error.\n";
} else {
echo $this->YYData->ERRMSG, "\n";
unset($this->YYData->ERRMSG);
}
}
public function _Lexer(MyParser $parser)
{
return ['', undef];
}
public function Run()
{
return $this->YYParse(['yylex' => [$this, '_Lexer'], 'yyerror' => [$this, '_Error']]);
}