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

.. only:: html

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

        Click :ref:`here <sphx_glr_download_examples_advanced_extend_python.py>`
        to download the full example code

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

.. _sphx_glr_examples_advanced_extend_python.py:


Extend the Python Grammar
==============================

This example demonstrates how to use the `%extend` statement,
to add new syntax to the example Python grammar.

.. GENERATED FROM PYTHON SOURCE LINES 9-47

.. code-block:: default


    from lark.lark import Lark
    from python_parser import PythonIndenter

    GRAMMAR = r"""
    %import python (compound_stmt, single_input, file_input, eval_input, test, suite, _NEWLINE, _INDENT, _DEDENT, COMMENT)

    %extend compound_stmt: match_stmt

    match_stmt: "match" test ":" cases
    cases: _NEWLINE _INDENT case+ _DEDENT

    case: "case" test ":" suite // test is not quite correct.

    %ignore /[\t \f]+/          // WS
    %ignore /\\[\t \f]*\r?\n/   // LINE_CONT
    %ignore COMMENT
    """

    parser = Lark(GRAMMAR, parser='lalr', start=['single_input', 'file_input', 'eval_input'], postlex=PythonIndenter())

    tree = parser.parse(r"""
    def name(n):
        match n:
            case 1:
                print("one")
            case 2:
                print("two")
            case _:
                print("number is too big")

    """, start='file_input')

    # Remove the 'python3__' prefix that was added to the implicitly imported rules.
    for t in tree.iter_subtrees():
        t.data = t.data.rsplit('__', 1)[-1]

    print(tree.pretty())


.. rst-class:: sphx-glr-timing

   **Total running time of the script:** ( 0 minutes  0.000 seconds)


.. _sphx_glr_download_examples_advanced_extend_python.py:


.. only :: html

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



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

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



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

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


.. only:: html

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

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