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

.. only:: html

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

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

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

.. _sphx_glr_examples_advanced_conf_lalr.py:


LALR’s contextual lexer
=======================

This example demonstrates the power of LALR's contextual lexer,
by parsing a toy configuration language.

The terminals `NAME` and `VALUE` overlap. They can match the same input.
A basic lexer would arbitrarily choose one over the other, based on priority,
which would lead to a (confusing) parse error.
However, due to the unambiguous structure of the grammar, Lark's LALR(1) algorithm knows
which one of them to expect at each point during the parse.
The lexer then only matches the tokens that the parser expects.
The result is a correct parse, something that is impossible with a regular lexer.

Another approach is to use the Earley algorithm.
It will handle more cases than the contextual lexer, but at the cost of performance.
See examples/conf_earley.py for an example of that approach.

.. GENERATED FROM PYTHON SOURCE LINES 20-44

.. code-block:: default

    from lark import Lark

    parser = Lark(r"""
            start: _NL? section+
            section: "[" NAME "]" _NL item+
            item: NAME "=" VALUE? _NL

            NAME: /\w/+
            VALUE: /./+

            %import common.NEWLINE -> _NL
            %import common.WS_INLINE
            %ignore WS_INLINE
        """, parser="lalr")


    sample_conf = """
    [bla]
    a=Hello
    this="that",4
    empty=
    """

    print(parser.parse(sample_conf).pretty())


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

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


.. _sphx_glr_download_examples_advanced_conf_lalr.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: conf_lalr.py <conf_lalr.py>`



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

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


.. only:: html

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

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