require 'test/unit' require 'rockit/dparser' class ATestOperatorGrammar < Test::Unit::TestCase MaybeTestGrammar = Rockit::DParser::Grammar.new do start :M, [[:A, maybe(:Digit)]], ast(:M, 0, 1) term :A, ["a"] term :Digit, [/[0-9]+/] end def test_01_use_maybe_parser parser = MaybeTestGrammar.new_parser ast = parser.parse "a1" assert_equal("M", ast.name) assert_kind_of(parser.astclass_of_name(:M), ast) assert_equal(2, ast.num_children) assert_equal("a", ast[0]) assert_equal("1", ast[1]) ast = parser.parse "a" assert_equal("M", ast.name) assert_kind_of(parser.astclass_of_name(:M), ast) assert_equal(2, ast.num_children) assert_equal("a", ast[0]) assert_equal(nil, ast[1]) end OperatorTestGrammar = Rockit::DParser::Grammar.new do start :Str, [[:A, plus(:B), plus(:A), mult(:C), maybe(:D)]], ast(:Str, 0, 1, 3, 4) term :A, ["a"] term :B, ["b"] term :C, ["c"] term :D, ["d"] end def test_02_use_parser parser = OperatorTestGrammar.new_parser ast = parser.parse "abbbac" assert_equal("Str", ast.name) assert_kind_of(parser.astclass_of_name(:Str), ast) assert_equal(4, ast.num_children) assert_equal("a", ast[0]) assert_equal(["b", "b", "b"], ast[1]) assert_equal(["c"], ast[2]) assert_equal(nil, ast[3]) end def test_03_use_parser parser = OperatorTestGrammar.new_parser ast = parser.parse "a b a c c d" assert_equal("Str", ast.name) assert_kind_of(parser.astclass_of_name(:Str), ast) assert_equal(4, ast.num_children) assert_equal("a", ast[0]) assert_equal(["b"], ast[1]) assert_equal(["c", "c"], ast[2]) assert_equal("d", ast[3]) end end