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

"Sidecar" objects for accumulative parsing #45

Open
goodmami opened this issue Jan 11, 2024 · 0 comments
Open

"Sidecar" objects for accumulative parsing #45

goodmami opened this issue Jan 11, 2024 · 0 comments
Labels
enhancement New feature or request

Comments

@goodmami
Copy link
Owner

This is a feature where an object is created as parsing begins and it can be used in actions during parsing.

Imagine parsing something like a large TOML file, where the top-level object is not created until the full file has been read in. You won't know if there's a table or key collision until the very end. Instead, if we could create an object that assembles the document as it parses, we could check as we go. E.g.:

from pe.actions import Sidecar
...

class TOMLSidecar:
    def __init__(self):
        self.doc = {}
    def register_table(self, name: str) -> None:
        if name in doc:  # simplified for convenience
            raise TOMLDecodeError(f"table already defined: {name}")
        self.doc[name] = {}
    ...

TOML_GRAMMAR = """
...
Table <- "[" WS Key WS "]"
...
"""

toml_parser = pe.compile(
    TOML_GRAMMAR,
    actions={
        "Table": Sidecar.call("register_table"),
        ...
    },
    sidecar_factory=TOMLSidecar,
)

The Sidecar.call("register_table") does something like this at parse time:

getattr(self.sidecar, "register_table")(*args, **kwargs)

This would probably subsume the use case of #10.

Some notes:

  1. The mutability of the sidecar object means that it might be changed by parsing paths that ultimately fail.
  2. It's not an Action object even though it is used in actions={...}, so maybe it doesn't belong in pe.actions
  3. The "sidecar" name is not certain. It's not the same as the Sidecar Pattern for applications. Alternatives:
    • "Parse-time object" is a bit long
    • "Proxy object"?
@goodmami goodmami added the enhancement New feature or request label Jan 11, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant