forked from ingydotnet/pegex-cd
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpegjs-arithmetic.coffee
63 lines (58 loc) · 1.47 KB
/
pegjs-arithmetic.coffee
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
# From https://github.com/dmajda/pegjs/blob/master/examples/arithmetics.pegjs
# /*
# * Classic example grammar, which recognizes simple arithmetic expressions like
# * "2*(3+4)". The parser generated from this grammar then computes their value.
# */
#
# start
# = additive
#
# additive
# = left:multiplicative "+" right:additive { return left + right; }
# / multiplicative
#
# multiplicative
# = left:primary "*" right:multiplicative { return left * right; }
# / primary
#
# primary
# = integer
# / "(" additive:additive ")" { return additive; }
#
# integer "integer"
# = digits:[0-9]+ { return parseInt(digits.join(""), 10); }
# Here is the closest Pegex analog:
{pegex} = require '../lib/Pegex'
grammar = """
# start: additive # Not needed. First rule is start rule by default.
additive:
( multiplicative <PLUS> additive )
| multiplicative
multiplicative:
( primary <STAR> multiplicative )
| primary
primary:
integer
| ( <LPAREN> additive <RPAREN> )
integer:
/(<DIGIT>+)/
"""
class code
got_integer: (int) -> Number int
got_additive: (pair) ->
return pair unless pair instanceof Array
[a, b] = pair
a + b
got_multiplicative: (pair) ->
return pair unless pair instanceof Array
[a, b] = pair
a * b
# Code to test the parser.
test = (expression) ->
result = pegex(grammar, {receiver: (new code)}).parse expression
console.log "#{expression} = #{result}"
# This passes:
test '(2+3)*4'
test '2+3*4'
# This fails:
test '2+(3*4)'