
.. DO NOT EDIT.
.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.
.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:
.. "examples/advanced/tree_forest_transformer.py"
.. LINE NUMBERS ARE GIVEN BELOW.

.. only:: html

    .. note::
        :class: sphx-glr-download-link-note

        :ref:`Go to the end <sphx_glr_download_examples_advanced_tree_forest_transformer.py>`
        to download the full example code.

.. rst-class:: sphx-glr-example-title

.. _sphx_glr_examples_advanced_tree_forest_transformer.py:


Transform a Forest
==================

This example demonstrates how to subclass ``TreeForestTransformer`` to
directly transform a SPPF.

.. GENERATED FROM PYTHON SOURCE LINES 8-59

.. code-block:: Python


    from lark import Lark
    from lark.parsers.earley_forest import TreeForestTransformer, handles_ambiguity, Discard

    class CustomTransformer(TreeForestTransformer):

        @handles_ambiguity
        def sentence(self, trees):
            return next(tree for tree in trees if tree.data == 'simple')

        def simple(self, children):
            children.append('.')
            return self.tree_class('simple', children)

        def adj(self, children):
            return Discard

        def __default_token__(self, token):
            return token.capitalize()

    grammar = """
        sentence: noun verb noun        -> simple
                | noun verb "like" noun -> comparative

        noun: adj? NOUN
        verb: VERB
        adj: ADJ

        NOUN: "flies" | "bananas" | "fruit"
        VERB: "like" | "flies"
        ADJ: "fruit"

        %import common.WS
        %ignore WS
    """

    parser = Lark(grammar, start='sentence', ambiguity='forest')
    sentence = 'fruit flies like bananas'
    forest = parser.parse(sentence)

    tree = CustomTransformer(resolve_ambiguity=False).transform(forest)
    print(tree.pretty())

    # Output:
    #
    # simple
    #   noun  Flies
    #   verb  Like
    #   noun  Bananas
    #   .
    #


.. _sphx_glr_download_examples_advanced_tree_forest_transformer.py:

.. only:: html

  .. container:: sphx-glr-footer sphx-glr-footer-example

    .. container:: sphx-glr-download sphx-glr-download-jupyter

      :download:`Download Jupyter notebook: tree_forest_transformer.ipynb <tree_forest_transformer.ipynb>`

    .. container:: sphx-glr-download sphx-glr-download-python

      :download:`Download Python source code: tree_forest_transformer.py <tree_forest_transformer.py>`

    .. container:: sphx-glr-download sphx-glr-download-zip

      :download:`Download zipped: tree_forest_transformer.zip <tree_forest_transformer.zip>`


.. only:: html

 .. rst-class:: sphx-glr-signature

    `Gallery generated by Sphinx-Gallery <https://sphinx-gallery.github.io>`_
