diff --git a/src/grammar_base.jl b/src/grammar_base.jl index acc9ef6..8258b15 100644 --- a/src/grammar_base.jl +++ b/src/grammar_base.jl @@ -235,7 +235,25 @@ function add_rule!(g::AbstractGrammar, e::Expr) return g end + +""" + add_rule(grammar, tree) + +Extends a given grammar with an `AbstractRuleNode`. The type of the rule is inferred from the root-type. +# Arguments +- `grammar::AbstractGrammar`: the grammar to extend +- `tree::RuleNode`: the Herb tree +""" +function add_rule!(grammar::AbstractGrammar, tree::AbstractRuleNode) + type = return_type(grammar, tree.ind) + new_grammar_rule = rulenode2expr(tree, grammar) + add_rule!(grammar, :($type = $new_grammar_rule)) +end + + """ + add_rule!(g::AbstractGrammar, p::Real, e::Expr) + Adds a probabilistic derivation rule. """ function add_rule!(g::AbstractGrammar, p::Real, e::Expr) diff --git a/test/test_csg.jl b/test/test_csg.jl index 071090b..87e064f 100644 --- a/test/test_csg.jl +++ b/test/test_csg.jl @@ -275,4 +275,18 @@ add_rule!(g, :(A = 2)) @test g.rules == [:(1 + A), :(2 * B), 1, 1, 2, 2] end + + @testset "Add tree to grammar" begin + g = @cfgrammar begin + Number = |(1:2) + Number = x + Number = Number + Number + Number = Number * Number + end + hole = Hole(get_domain(g, g.bytype[:Number])) + test_ast = RuleNode(4, [RuleNode(1), hole]) + + add_rule!(g, test_ast) + @test g.rules[6] == :(1 + Number) + end end