lagodiuk / earley-parser-js

Tiny JavaScript implementation of context-free languages parser - Earley parser (including generation of the parsing-forest).
Apache License 2.0
118 stars 11 forks source link

Adding and removing rules from a grammar #3

Open jarble opened 8 years ago

jarble commented 8 years ago

I'm developing an application that requires the grammar rules to be modified after the grammar is created. After creating a grammar like this one, would it be possible to add or modify individual rules in the grammar?

var grammar = new tinynlp.Grammar([
   'R -> N',
   'S -> S add_sub M | M',
   'M -> M mul_div T | T',
   'N -> S lt_gt S | S',
   'T -> num | ( S )',
]);

Would I be able to add a new rule to the grammar using grammar.add('A -> B') or something similar?

lagodiuk commented 8 years ago

@jarble Excuse me for a bit delayed response.

Currently, Grammar object is implemented in such way, that it encapsulates a data structure with all grammar productions - indexed by nonterminal symbols (the left hand side of grammar rules). For example, grammar productions S -> S add_sub M | M and N -> S lt_gt S | S are internally represented in the following way:

{
  'S': [['S', 'add_sub', 'M'], ['M']],
  'N': [['S', 'lt_gt', 'S'], ['S']],
}

Please, check the source code of the constructor of Grammar objects for more implementation details: https://github.com/lagodiuk/earley-parser-js/blob/master/earley-oop.js#L4-L23

Given code can be reused for parsing of the new rules, and addition of them to the dictionary with already existing rules.

I will try to find a time within nearest days - to implement requested feature. However, a pull request with this feature will be appreciated as well.