forked from quxiucheng/apache-calcite-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCalculator.jj
executable file
·99 lines (85 loc) · 1.4 KB
/
Calculator.jj
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
PARSER_BEGIN(Calculator)
package com.github.quxiucheng.parser.javacc.calc;
import java.io.* ;
public class Calculator {
public Calculator(String expr) {
this((Reader)(new StringReader(expr)));
}
public static void main(String[] args) throws Exception {
Calculator calc = new Calculator(args[0]);
System.out.println(calc.calc());
}
}
PARSER_END(Calculator)
// 忽律的字符
SKIP:{
" "
| "\t"
| "\n"
| "\r"
| "\r\n"
}
// 关键字
TOKEN:{
<ADD :"+">
| <SUB :"-">
| <MUL :"*">
| <DIV :"/">
| <NUMBER :
<DIGITS>
| <DIGITS> "." <DIGITS>
| <DIGITS> "."
| "." <DIGITS>
>
| <#DIGITS : (["0"-"9"])+ >
}
// 计算
double calc():
{
Double value ;
Double result = 0.0;
}
{
result = term()
// 加减
(
<ADD>
value = term()
{result += value;}
|
<SUB>
value =term()
{result -= value;}
)*
{return result;}
}
// 乘除
double term():
{
double value;
double result;
}
{
result = getNumber()
(
<MUL>
value = getNumber()
{result *= value;}
|
<DIV>
value = getNumber()
{result /= value;}
)*
{return result;}
}
// 获取字符串
double getNumber():
{
double number;
Token t;
}
{
t = <NUMBER>
{number = Double.parseDouble(t.image);
return number;}
}