-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcomplex_grammar.pegjs
44 lines (33 loc) · 1.52 KB
/
complex_grammar.pegjs
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
start
= SPACE a:additive SPACE { var code = "(function(z) {return " + a + ";})"; var f = eval(code); f.code = code; return f}
// = SPACE a:additive SPACE { return eval("(function(z) {return " + a + ";})"); }
additive
= left:negative SPACE "+" SPACE right:additive { return "Complex.add(" + left + ", " + right + ")"; }
/ left:negative SPACE "-" SPACE right:additive { return "Complex.add(" + left + ", Complex.negative(" + right + "))"; }
/ negative
negative
= "-" SPACE c:multiplicative { return "Complex.negative(" + c + ")"; }
/ multiplicative
multiplicative
= left:exponential SPACE "*"? SPACE right:multiplicative { return "Complex.multiply(" + left + ", " + right + ")"; }
/ left:exponential SPACE "/" SPACE right:multiplicative { return "Complex.divide(" + left + ", " + right + ")"; }
/ exponential
exponential
= left:function_call SPACE ("**"/"^") SPACE right:function_call { return "Complex.pow(" + left + ", " + right + ")"; }
/ function_call
function_call
= f:function SPACE z:primary { return f + "(" + z + ")"; }
/ primary
primary
= number
/ variable
/ "(" SPACE a:additive SPACE ")" { return "(" + a + ")"; }
number "number"
= before:[0-9]* "." after:[0-9]+ { return "(new Complex(" + before.join("") + "." + after.join("") + ", 0))"; }
/ digits:[0-9]+ "."? { return "(new Complex(" + digits.join("") + ", 0))"; }
variable
= "z" { return "z"; }
/ cnst:("i"/"pi"/"e") { return "Complex." + cnst; }
function
= fn:("exp"/"re"/"im"/"abs"/"conj"/"log") { return "Complex." + fn; }
SPACE = " "*