Exports custom API in the grammar file

51 views
Skip to first unread message

Giovanni Giacobbi

unread,
Jul 7, 2012, 5:26:50 PM7/7/12
to pe...@googlegroups.com
Good morning or good afternoon, depending where you are.

I wrote my first grammar today with PEG and I think it's an awesome tool. Anyway, I ran into a sort of design limitation. My grammar describe a simple template parser, the problem is that I would like to isolate everything in the grammar file, and have a full template engine in that file.

This translates to a very simple requirement: being able to export a function to the public interface of the parser, which now contains only parse().
Basically what my new method would do is something like:

  function templateEngine(tpl, vars, callback) {
    var node = this.parse(tpl);
    if (node == "IfStatement") {
      callback.call("IfStatement", this.resolve(node.condition, vars));
    }
    else if ( .... )
  }

So as you can see it's very simple logic, that would otherwise need to go into my main application file or yet another file with only this two functions that wraps the generated parser.
I hope the purpose it's clear, I don't feel very expressive today. What I want is a way to publish a function to the same level of the "parse:" call.
Any ideas?
Thank you. This tool rocks.

David Majda

unread,
Jul 29, 2012, 10:47:45 AM7/29/12
to giova...@gmail.com, pe...@googlegroups.com
2012/7/7 Giovanni Giacobbi <giova...@gmail.com>:
> Anyway, I ran into a sort of design limitation. My grammar describe a simple
> template parser, the problem is that I would like to isolate everything in
> the grammar file, and have a full template engine in that file.
>
> This translates to a very simple requirement: being able to export a
> function to the public interface of the parser, which now contains only
> parse().

Parsers should just parse, period :-) Extending their interface in any
way beyond this is a violation of the single responsibility principle.
I won't add such a feature.

The correct approach is to include your parser into the object
providing the additional functionality (i.e. use composition). If you
target Node.js you can do it easily using modules, if not, there are
other ways.

--
David Majda
Entropy fighter
http://majda.cz/
Reply all
Reply to author
Forward
0 new messages