Using look-ahead
================

When a PEG_ is parsing a symbol, it can “look ahead” as far in the
input as it needs to in order to decide what this symbol means. There's
a modest example of this in ``pacc.pacc`` itself.

.. _peg: /article/glossary#peg

You may have noticed that definitions in a **pacc** grammar are not
terminated by a ``;`` semi-colon. You might have suspected that each
definition must end with a newline, but this is not the case. (I
certainly recommend that you do, in fact, end each definition with a
newline, but this is for the benefit of any humans reading the grammar,
not **pacc** itself!)

So this is a perfectly good grammar, consisting of 3 definitions::

 S ← yes {1} / no {0} yes ← "yes" / "oui" no ← "non" / "no"

**pacc** can tell that the first ``yes`` is a call to another rule,
whereas the second ``yes`` is the definition of that rule, because of
the ``←`` that comes after the second ``yes``. This is expressed in
``pacc.pacc`` as follows::

 Rule5
     ← n:Name !lArrow !ColCol { s_text(call, n) }
     / ...

In words, a bare Name is a call, only if it is *not* followed by a left
arrow or a double colon. Otherwise, it starts a new definition; this
will be picked up by a different rule.

You might look at this example and think that **pacc** is looking just
one token ahead here, and an LALR(1) parser can do *that*. But bear in
mind that the definition of ``Name`` itself is expressed in this very
same PEG, not in a separate “lexer”. Effectively there are no tokens,
only characters, and we are already looking an arbitrary number of
characters ahead.

In any case, although in this particular case the look-ahead involves
(negative) assertions based on the relatively simple “lexical” rules
``lArrow`` and ``ColCol``, they could in general be as complicated as
you want. Positive assertions can also be used for look-ahead, of
course.

The miracle of packrat_ parsing means that, even in the face of this
arbitrary look-ahead, the parser is *linear*, that is, *O*\(*n*) for time
and space, where *n* is the size of the input.

.. _packrat: /article/glossary#packrat
