lark icon indicating copy to clipboard operation
lark copied to clipboard

Empties in Earley - predictable Transformer arguments

Open night199uk opened this issue 7 years ago • 12 comments

Earley as in the upcoming 0.7b will somewhat correctly handle empty tokens. This issue though is how rules that match empty should be represented in the output tree, especially with regard to visitors & [in-line] transformers and some thoughts/discussion. I'm testing some potential patches here that I think make matching empty a lot simpler with regards to Transformers.

I use in-line Transformers heavily as they make life easier. Viz a simple CSV parser (okay, no-one writes a CSV parser like this - but hopefully it will demo the use case): transformer:

class User(object):
  def __init__(self, first_name, last_name, address):
    self.first_name = first_name
    self.last_name = last_name
    self.address = address

@v_args
class MyTransformer(Transformer):
  to_list = lambda *i: list(i)
  user = User

grammar:

_CS: _COMMA _SPACE?
?first_name: /[a-zA-Z]+/
?last_name: /[a-zA-Z]+/
?address: /[a-zA-Z0-9]+/
users: user* -> to_list
user: first_name _CS last_name _CS address _EOL

input:

Bob,Smith,123MadeUpstreet

The ? ensures the individual items are inlined, and the result of this parse is a list of users with very little code. However, the problem comes if I might have empty fields:

user: first_name? _CS last_name? _CS address?

input: ,Smith,123MadeUpstreet When modifying this in such a way, with the argument inliner and SingleExpander as they stand, empty arguments disappear. This breaks the constructor, as with the sample above it is now called with:

User('Smith','123MadeUpstreet')  # note the empty first_name disappears, python exception.

This could be modified a few ways, but today there doesn't seem to be a decent way to keep the args consistent so you end up with much more complicated parsing in the constructors. Viz, allowing the individual items to match empty:

?first_name: [ /[a-zA-Z]+/ ]
?last_name: [ /[a-zA-Z]+/ ]
?address: [ /[a-zA-Z0-9]+/ ]
users: user* -> to_list
user: first_name _CS last_name _CS address _EOL

Now in this case, each field can match empty. However, now because the SingleExpander checks explicitly for len(children) == 1, I get: User(Tree('first_name', []), 'Smith', '123MadeUpstreet')

Again, this sucks. What I'd like to have is this: User(None, 'Smith', '123MadeUpstreet')

I guess this is achievable with the horrible (untested, but should work):

...
class MyTransformer(Transformer):
...
   to_none = lambda: None
?first_name: /[a-zA-Z]+/
           | -> to_none
?last_name: /[a-zA-Z]+/
          | -> to_none
?address: /[a-zA-Z0-9]+/
        | -> to_none

This makes my arguments to the Transformer consistent and predictable, and makes it MUCH easier to write grammars/transformers.

There are a couple of ways to implement this:

  1. Change the SingleExpander to return None when in-lining empty trees (would affect LALR and Earley)
  2. Change to Earley parser to use a specific Empty token when matching empty, which is how it was originally designed. Earley Empty () eventually became python 'None' during implementation, which was probably a bad choice as None is also used elsewhere in the Forest to mean No Value. Would only impact Earley.
  3. Do either/both of the above and make it optional behind a 'empty_matches_none' flag or similar. The problem is I hate having lots of options; and I kind of wonder if empty_matches_none should be the default? Is 'None' a better choice for expanding an empty tree?

Would appreciate thoughts and feedback? To me; allowing more predictable arguments with the InlineTransformer makes for simpler parsers in Python; so this would be a big win, but I can't visualise any bad impacts right now, and I don't use LALR so I can't comment there.

night199uk avatar Dec 05 '18 13:12 night199uk

This is something I've thought about before, and it's relevant to both LALR and Earley.

How about option 4?

  1. Add a rule modifier that replaces omitted subrules with None.

For example:

*rule: "a"? b "c"?
>>> parser.parse('bc')
Tree('rule', [None, 'b', 'c'])

(pseudocode of course)

erezsh avatar Dec 06 '18 07:12 erezsh

I think that'd be awesome as well. :-) It'd really help a lot of creating predictable Transformers.

night199uk avatar Dec 18 '18 05:12 night199uk

Implemented it in master !

I'm pretty happy with it, because it works with post-processing, so it doesn't add any empty rules which might degrade performance, and it can still handle repetition correctly (from initial checks.. we'll see how it holds up to scrutiny).

Let me know what you think!

erezsh avatar Dec 19 '18 13:12 erezsh

Btw you can look at the tests to see how it's used:

https://github.com/lark-parser/lark/blob/master/tests/test_parser.py#L1251

erezsh avatar Dec 19 '18 13:12 erezsh

Okay, I take it back. Even though the idea is good, there are still lots of holes in the implementation.

I'll have to put some more work in before this can be used properly.

erezsh avatar Dec 19 '18 17:12 erezsh

I untake it back! :)

I closed all the holes I could find, and I think it should work for all cases now. Please verify!

erezsh avatar Dec 19 '18 23:12 erezsh

One (big) downside right now that I noticed without using it yet is that the addition of hash and eq to Rule in their current implementation adds approximately a 20-25% slowdown to Earley, because Rules are used in Item and SymbolNode keys (s) for Earley. We create millions of Items & SymbolNodes on a large parse in Earley. I looked at implementing caching for the hash in Rule as it's done elsewhere which largely mitigates the impact:

    def __init__(self, origin, expansion, alias=None, options=None):
..
        self._hash = hash((self.origin, tuple(self.expansion)))
..
    def __hash__(self):
        return self._hash

However this breaks just a few of my parses hitting this breaks in load_grammar in:

                if any(empty_indices):
                    assert options

I need to try and take a deeper look today and see if the performance regression can be countered and why this assert triggers, but let me know if you beat me to it.

night199uk avatar Dec 22 '18 06:12 night199uk

Actually, it seems I hit the assert regardless of the hash optimisation, which makes sense. Let me dig.

night199uk avatar Dec 22 '18 07:12 night199uk

2 fixes in our 0.7c branch.

night199uk avatar Dec 22 '18 07:12 night199uk

So this feature seems to be working well so far. The only issue with it is granularity: Sometimes we want it, and sometimes we don't.

So, one option is to specify it on a rule basis, by adding another special symbol.

But another option, which I really like, is that the ? and [ ] operators will act differently in that regard. So

rule1: [A] B    # if no A, just return ['B']
rule2: A? B      # placeholder. if no A, return [None, 'B'] 

I think that will allow a lot flexibility, and still keep the syntax clean.

I can also swap their meanings, but I feel like this way makes more sense.

What do you think?

erezsh avatar Jan 12 '19 12:01 erezsh

So can I use the * rule today in 2022 to guarantee a None and keep the arguments consistent ?

qorrect avatar Mar 20 '22 17:03 qorrect

@qorrect See maybe_placeholders in https://lark-parser.readthedocs.io/en/latest/classes.html

erezsh avatar Mar 20 '22 17:03 erezsh