-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalc.phpy
61 lines (48 loc) · 1.04 KB
/
calc.phpy
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
/*
* calculator
*/
%token NUMBER
%left '+' '-'
%left '*' '/'
%%
start: lines;
lines: /* empty */
| lines line
;
line : expr { return $1; }
| '\n' { return '(empty line ignored)'; }
| error { return false; }
;
expr : expr '+' expr { $$ = $1 + $3; }
| expr '-' expr { $$ = $1 - $3; }
| expr '*' expr { $$ = $1 * $3; }
| expr '/' expr { $$ = $1 / $3; }
| '(' expr ')' { $$ = $2; }
| NUMBER { $$ = $1; }
;
%%
protected static function yylex()
{
$lexbuf = self::$lexbuf;
if (preg_match('/^(\d+)/', $lexbuf, $matches)) {
self::$yylval = (int)$matches[1];
self::$lexbuf = substr($lexbuf, strlen($matches[1]));
return self::NUMBER;
}
$ret = ord($lexbuf);
self::$lexbuf = substr($lexbuf, 1);
return $ret;
}
protected static function yyerror($msg)
{
throw new Exception($msg);
}
}
$lexbuf = rand(1000, 9999).'+'.rand(1000, 9999);
$resultKMyacc = KMyacc::yyparse($lexbuf);
$resultPHP = eval('return '.$lexbuf. ';');
var_dump(
'raw : ' . $lexbuf,
'KMyacc : ' . $resultKMyacc,
'PHP : ' . $resultPHP
);