/
test_gen_calc.rb
63 lines (50 loc) · 1.74 KB
/
test_gen_calc.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
require 'minitest/autorun'
require 'kpeg'
require 'kpeg/format_parser'
require 'kpeg/code_generator'
require 'stringio'
class TestKPegCodeGenerator < MiniTest::Unit::TestCase
GRAMMAR = <<-'STR'
Stmt = - Expr:e EOL { @answers << e }
| ( !EOL . )* EOL { puts "error" }
Expr = ID:i ASSIGN Sum:s { @vars[i] = s }
| Sum:s { s }
Sum = Product:l
( PLUS Product:r { l += r }
| MINUS Product:r { l -= r }
)* { l }
Product = Value:l
( TIMES Value:r { l *= r }
| DIVIDE Value:r { l /= r }
)* { l }
Value = NUMBER:i { i }
| ID:i !ASSIGN { @vars[i] }
| OPEN Expr:i CLOSE { i }
NUMBER = < [0-9]+ > - { text.to_i }
ID = < [a-z] > - { text }
ASSIGN = '=' -
PLUS = '+' -
MINUS = '-' -
TIMES = '*' -
DIVIDE = '/' -
OPEN = '(' -
CLOSE = ')' -
- = (' ' | '\t')*
EOL = ('\n' | '\r\n' | '\r' | ';') -
root = Stmt+
STR
def test_parse
parc = KPeg::FormatParser.new(GRAMMAR)
assert parc.parse, "Unable to parse"
gram = parc.grammar
# gr = KPeg::GrammarRenderer.new(gram)
# puts
# gr.render(STDOUT)
cg = KPeg::CodeGenerator.new "TestCalc", gram
code = cg.make("i = 3+4; j = i*8; i + j * 2;")
code.instance_variable_set(:@vars, {})
code.instance_variable_set(:@answers, [])
assert_equal true, code.parse
assert_equal [7,56,119], code.instance_variable_get(:@answers)
end
end