/
helper.rb
143 lines (119 loc) · 2.97 KB
/
helper.rb
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
lib = File.expand_path('../../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'test/unit'
require 'citrus/debug'
class Test::Unit::TestCase
include Citrus
def input(str='')
Input.new(str)
end
module TestGrammar
include Citrus::Grammar
rule :alpha do
/[a-zA-Z]/
end
rule :num do
ext(/[0-9]/) {
def value
text.to_i
end
}
end
rule :alphanum do
any(:alpha, :num)
end
end
class EqualRule
include Citrus::Rule
def initialize(value)
@value = value
end
def match(input, offset=0)
create_match(@value.to_s.dup, offset) if @value.to_s == input.string
end
end
module CalcTests
def test_int
match = Calc.parse('3')
assert(match)
assert_equal('3', match.text)
assert_equal(1, match.length)
assert_equal(3, match.value)
end
def test_float
match = Calc.parse('1.5')
assert(match)
assert_equal('1.5', match.text)
assert_equal(3, match.length)
assert_equal(1.5, match.value)
end
def test_addition
match = Calc.parse('1+2')
assert(match)
assert_equal('1+2', match.text)
assert_equal(3, match.length)
assert_equal(3, match.value)
end
def test_addition_multi
match = Calc.parse('1+2+3')
assert(match)
assert_equal('1+2+3', match.text)
assert_equal(5, match.length)
assert_equal(6, match.value)
end
def test_addition_float
match = Calc.parse('1.5+3')
assert(match)
assert_equal('1.5+3', match.text)
assert_equal(5, match.length)
assert_equal(4.5, match.value)
end
def test_subtraction
match = Calc.parse('3-2')
assert(match)
assert_equal(1, match.value)
end
def test_subtraction_float
match = Calc.parse('4.5-3')
assert(match)
assert_equal('4.5-3', match.text)
assert_equal(5, match.length)
assert_equal(1.5, match.value)
end
def test_multiplication
match = Calc.parse('2*5')
assert(match)
assert_equal(10, match.value)
end
def test_multiplication_float
match = Calc.parse('1.5*3')
assert(match)
assert_equal('1.5*3', match.text)
assert_equal(5, match.length)
assert_equal(4.5, match.value)
end
def test_division
match = Calc.parse('20/5')
assert(match)
assert_equal(4, match.value)
end
def test_division_float
match = Calc.parse('4.5/3')
assert(match)
assert_equal('4.5/3', match.text)
assert_equal(5, match.length)
assert_equal(1.5, match.value)
end
def test_complex
match = Calc.parse('7*4+3.5*(4.5/3)')
assert(match)
assert_equal('7*4+3.5*(4.5/3)', match.text)
assert_equal(33.25, match.value)
end
def test_complex_spaced
match = Calc.parse('7 * 4 + 3.5 * (4.5 / 3)')
assert(match)
assert_equal(33.25, match.value)
end
end
end