Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Transform: Easier rule writing #53

Closed
trevorfancher opened this issue Sep 5, 2011 · 1 comment
Closed

Transform: Easier rule writing #53

trevorfancher opened this issue Sep 5, 2011 · 1 comment

Comments

@trevorfancher
Copy link

The key I match the parse tree with is almost always the name I want for my variable in the rule.

class Parslet::Transform
    class << self
        def expression_from_args(args)
            if args[0].kind_of? Hash
                args[0]
            else
                names = args.collect {|binder| binder.variable_name}
                expression = {}
                names.zip(args) { |key, value|
                    expression[key] = value
                }
                expression
            end
        end

        alias orig_rule rule
        def rule(*args, &block)
            orig_rule(expression_from_args(args), &block)
    end
    end

    alias orig_rule rule
    def rule(*args, &block)
        expression = self.class.expression_from_args(args)
        orig_rule(expression, &block)
    end
end

This allows me to write rules like:

    rule(simple(:proto_name),
             hash_sequence(:args, [:arg_name])) {
        args.collect! {|x| x[:arg_name]}
        Prototype.new(proto_name, args)
    }

    rule(simple(:call_name),
             sequence(:args)) {
        CallExpr.new(call_name, args)
    }

    rule(simple(:variable_name)) {
        VariableExpr.new(variable_name);
    }

    rule(simple(:number)) {
        NumberExpr.new(number.to_f)
    }

    rule(simple(:condition), simple(:then_), simple(:else_)) {
        IfExpr.new(condition, then_, else_)
    }

I will clean the code and make a patch and pull request if there is enough interest.

@kschiess
Copy link
Owner

kschiess commented Sep 6, 2011

To find out whether there is interest, I suggest you try the mailing list.

@kschiess kschiess closed this as completed Sep 6, 2011
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants