File: syntax.rst

package info (click to toggle)
python-tatsu 5.13.1%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 892 kB
  • sloc: python: 10,202; makefile: 54
file content (829 lines) | stat: -rw-r--r-- 19,099 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
.. include:: links.rst
.. highlight:: none

Grammar Syntax
--------------

|TatSu| uses a variant of the standard `EBNF`_ syntax. Syntax
definitions for `VIM`_ and for `Sublime Text`_ can be found under the
``etc/vim`` and ``etc/sublime`` directories in the source code
distribution.

Rules
~~~~~

A grammar consists of a sequence of one or more rules of the form::

  name = <expre> ;

If a *name* collides with a `Python`_ keyword, an underscore (``_``)
will be appended to it on the generated parser.

Rule names that start with an uppercase character::

  FRAGMENT = /[a-z]+/ ;

*do not* advance over whitespace before beginning to parse. This feature
becomes handy when defining complex lexical elements, as it allows
breaking them into several rules.

The parser returns an `AST`_ value for each rule depending on what was
parsed:

-  A single value
-  A list of `AST`_
-  A dict-like object for rules with named elements
-  An object, when ModelBuilderSemantics is used
-  None

See the `Abstract Syntax Trees`_ and `Building Models`_ sections for more
details.

.. _Abstract Syntax Trees: ast.html
.. _Building Models: models.html

Expressions
~~~~~~~~~~~

The expressions, in reverse order of operator precedence, can be:


``# comment``
^^^^^^^^^^^^^

`Python`_-style comments are allowed.


``e1 | e2``
^^^^^^^^^^^

Choice. Match either ``e1`` or ``e2``.

A `|` may be used before the first option if desired::

  choices
      =
      | e1
      | e2
      | e3
      ;


``e1 e2``
^^^^^^^^^

Sequence. Match ``e1`` and then match ``e2``.


``( e )``
^^^^^^^^^

Grouping. Match ``e``. For example: ``('a' | 'b')``.


``[ e ]``
^^^^^^^^^

Optionally match ``e``.


``{ e }`` or ``{ e }*``
^^^^^^^^^^^^^^^^^^^^^^^

Closure. Match ``e`` zero or more times. The `AST`_ returned for a
closure is always a ``list``.


``{ e }+``
^^^^^^^^^^

Positive closure. Match ``e`` one or more times. The `AST`_ is always
a ``list``.


``{}``
^^^^^^

Empty closure. Match nothing and produce an empty ``list`` as `AST`_.


``~``
^^^^^

The *cut* expression. Commit to the current active option and prevent
other options from being considered even if what follows fails to
parse.

In this example, other options won't be considered if a parenthesis is
parsed::

  atom
      =
      | '(' ~ @:expre ')'
      | int
      | bool
      ;

There are also options in optional expressions, because ``[foo]`` is
equivalent to ``(foo|())``.

There are options also in closures, because of a similar equivalency,
so the following rule will fail if ``expression`` is not parsed after
an ``=`` is parsed, while the version without the ``~`` would succeed
over a partial parse of the ``name '=' expression`` ahead in the
input::

  parameters
      =
      ','.{name '=' ~ expression}
      ;


``s%{ e }+``
^^^^^^^^^^^^

Positive join. Inspired by `Python`_'s ``str.join()``, it parses the
same as this expression::

  e {s ~ e}

yet the result is a single list of the form:

.. code:: python

   [e, s, e, s, e, ...]

Use grouping if `s` is more complex than a *token* or a *pattern*::

  (s t)%{ e }+


``s%{ e }`` or ``s%{ e }*``
^^^^^^^^^^^^^^^^^^^^^^^^^^^

Join. Parses the list of ``s``-separated expressions, or the empty
closure. It is equivalent to::

  s%{e}+|{}


``op<{ e }+``
^^^^^^^^^^^^^

Left join. Like the *join expression*, but the result is a
left-associative tree built with ``tuple()``, in wich the first
element is the separator (``op``), and the other two elements are the
operands.

The expression::

  '+'<{/\d+/}+

Will parse this input::

  1 + 2 + 3 + 4

To this tree:

.. code:: python

   (
      '+',
      (
          '+',
          (
              '+',
              '1',
              '2'
          ),
          '3'
      ),
      '4'
   )


``op>{ e }+``
^^^^^^^^^^^^^

Right join. Like the *join expression*, but the result is a
right-associative tree built with ``tuple()``, in wich the first
element is the separator (``op``), and the other two elements are the
operands.

The expression::

  '+'>{/\d+/}+

Will parse this input::

  1 + 2 + 3 + 4

To this tree:

.. code:: python

   (
      '+',
      '1',
      (
          '+',
          '2',
          (
              '+',
              '3',
              '4'
          )
      )
   )


``s.{ e }+``
^^^^^^^^^^^^

Positive *gather*. Like *positive join*, but the separator is not
included in the resulting `AST`_.

``s.{ e }`` or ``s.{ e }*``
^^^^^^^^^^^^^^^^^^^^^^^^^^^

*Gather*. Like the *join*, but the separator is not included in the
resulting `AST`_. It is equivalent to::

  s.{e}+|{}


``&e``
^^^^^^

Positive lookahead. Succeed if ``e`` can be parsed, but do not consume
any input.


``!e``
^^^^^^

Negative lookahead. Fail if ``e`` can be parsed, and do not consume
any input.


``'text'`` or ``"text"``
^^^^^^^^^^^^^^^^^^^^^^^^

Match the token *text* within the quotation marks.

Note that if *text* is alphanumeric, then |TatSu| will check that the
character following the token is not alphanumeric. This is done to
prevent tokens like *IN* matching when the text ahead is
*INITIALIZE*. This feature can be turned off by passing
``nameguard=False`` to the ``Parser`` or the ``Buffer``, or by using a
pattern expression (see below) instead of a token expression.
Alternatively, the ``@@nameguard`` or ``@@namechars`` directives may
be specified in the grammar::

  @@nameguard :: False

or to specify additional characters that should also be considered
part of names::

  @@namechars :: '$-.'


``r'text'`` or ``r"text"``
^^^^^^^^^^^^^^^^^^^^^^^^^^

Match the token *text* within the quotation marks, interpreting *text*
like `Python`_'s `raw string literal`_\ s.


``?"regexp"`` or ``?'regexp'`` or ``/regexp/``
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The *pattern* expression. Match the `Python`_ regular expression
``regexp`` at the current text position. Unlike other expressions,
this one does not advance over whitespace or comments. For that, place
the ``regexp`` as the only term in its own rule.

The *regex* is interpreted as a Python_ `raw string literal`_ and
passed the Python_ re_ module using ``match()`` at the current
position in the text. The returned AST_ has the semantics of
``re.findall(pattern, text)[0]`` (a `tuple` if there is more than one
group), so use ``(?:)`` for groups that should not be in the resulting
AST_.

Consecutive *patterns* are concatenated to form a single one.


``/./``
^^^^^^^

The *any* expression, matches the next position in the input. It works
exactly like the ``?'.'`` pattern, but is implemented at the lexical
level, without regular expressions.


``->e``
^^^^^^^

The "*skip to*" expression; useful for writing *recovery* rules.

The parser will advance over input, one character at time, until ``e``
matches. Whitespace and comments will be skipped at each
step. Advancing over input is done efficiently, with no regular
expressions are involved.

The expression is equivalent to::

  { !e /./ } e

A common form of the expression is ``->&e``, which is equivalent to::

  { !e /./ } &e

This is an example of the use of the "*skip to*" expression for
recovery::

  statement =
      | if_statement
      # ...
      ;

  if_statement
      =
      | 'if' condition 'then' statement ['else' statement]
      | 'if' statement_recovery
      ;

  statement_recovery = ->&statement ;


```constant```
^^^^^^^^^^^^^^

Match nothing, but behave as if ``constant`` had been parsed.

Constants can be used to inject elements into the concrete and
abstract syntax trees, perhaps avoiding having to write a
semantic action. For example::

  boolean_option = name ['=' (boolean|`true`) ] ;


If the text evaluates to a Python literal (with ``ast.literal_eval()``), that
will be the returned value.  Otherwise, string interpolation in the style of
``str.format()`` over the names in the current `AST`_ is applied for
*constant* elements. Occurrences of the ``{`` character must be scaped to
``\{`` if they are not intended for interpolation. A *constant* expression
that hast type ``str`` is evaluated using::

  eval(f'{"f" + repr(text)}', {}, ast)


`````constant`````
^^^^^^^^^^^^^^^^^^

A multiline version of ```constant```.


^ ```constant``` and ^ `````constant`````
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

An alert. There will be no token returned by the parser, but an alert
will be registed in the parse context and added to the current node's
``parseinfo``.

The ``^`` character may appear more than once to indicate the alert
level::

  assignment = identifier '=' (
      | value
      | ->'&; ^^^`could not parse value in assignment to {identifier}`


``rulename``
^^^^^^^^^^^^

Invoke the rule named ``rulename``. To help with lexical aspects of
grammars, rules with names that begin with an uppercase letter will
not advance the input over whitespace or comments.


``>rulename``
^^^^^^^^^^^^^

The include operator. Include the *right hand side* of rule
``rulename`` at this point.

The following set of declarations::

  includable = exp1 ;

  expanded = exp0 >includable exp2 ;

Has the same effect as defining *expanded* as::

  expanded = exp0 exp1 exp2 ;

Note that the included rule must be defined before the rule that
includes it.


``()``
^^^^^^

The empty expression. Succeed without advancing over input. Its value
is ``None``.


``!()``
^^^^^^^

The *fail* expression. This is actually ``!`` applied to ``()``, which
always fails.


``name:e``
^^^^^^^^^^

Add the result of ``e`` to the `AST`_ using ``name`` as key. If
``name`` collides with any attribute or method of ``dict``, or is a
`Python`_ keyword, an underscore (``_``) will be appended to the name.

When there are no named items in a rule, the `AST`_ consists of the
elements parsed by the rule, either a single item or a ``list``. This
default behavior makes it easier to write simple rules::

  number = /[0-9]+/ ;

Without having to write::

  number = number:/[0-9]+/ ;

When a rule has named elements, the unnamed ones are excluded from the
`AST`_ (they are ignored).


``name+:e``
^^^^^^^^^^^

Add the result of ``e`` to the `AST`_ using ``name`` as key. Force the
entry to be a ``list`` even if only one element is added. Collisions
with ``dict`` attributes or `Python`_ keywords are resolved by
appending an underscore to ``name``.


``@:e``
^^^^^^^

The override operator. Make the `AST`_ for the complete rule be the
`AST`_ for ``e``.

The override operator is useful to recover only part of the right hand
side of a rule without the need to name it, or add a semantic
action. This is a typical use of the override operator::

  subexp = '(' @:expre ')' ;

The `AST`_ returned for the ``subexp`` rule will be the `AST`_
recovered from invoking ``expre``.


``@+:e``
^^^^^^^^

Like ``@:e``, but make the `AST`_ always be a ``list``.

This operator is convenient in cases such as::

  arglist = '(' @+:arg {',' @+:arg}* ')' ;

In which the delimiting tokens are of no interest.


``$``
^^^^^

The *end of text* symbol. Verify that the end of the input text has
been reached.

..
    Deprecated Expressions
    ~~~~~~~~~~~~~~~~~~~~~~

    The following expressions are still recognized in grammars, but they are
    considered deprecated, and will be removed in a future version of
    |TatSu|.


    ``?/regexp/?``
    ^^^^^^^^^^^^^^

    Another form of the pattern expression that can be used when there
    are slashes (``/``) in the pattern. Use the ``?"regexp"`` or
    ``?'regexp'`` forms instead.


    ``+?"regexp"`` or ``+?'regexp'`` or ``+/regexp/``
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    Concatenate the given pattern with the preceding one.


    ``(* comment *)``
    ^^^^^^^^^^^^^^^^^^^^^^^

    Comments may appear anywhere in the text. Use the `Python`_-style
    comments instead.


Rules with Arguments
~~~~~~~~~~~~~~~~~~~~

|TatSu| allows rules to specify `Python`_-style arguments::

  addition(Add, op='+')
      =
      addend '+' addend
      ;

The arguments values are fixed at grammar-compilation time. An
alternative syntax is available if no *keyword parameters* are
required::

  addition::Add, '+'
      =
      addend '+' addend
      ;

Semantic methods must be ready to receive any arguments declared in
the corresponding rule:

.. code:: python

   def addition(self, ast, name, op=None):
       ...

When working with rule arguments, it is good to define a
``_default()`` method that is ready to take any combination of
standard and keyword arguments:

.. code:: python

   def _default(self, ast, *args, **kwargs):
       ...


Based Rules
~~~~~~~~~~~

Rules may extend previously defined rules using the ``<`` operator.
The *base rule* must be defined previously in the grammar.

The following set of declarations::

  base::Param = exp1 ;

  extended < base = exp2 ;

Has the same effect as defining *extended* as::

  extended::Param = exp1 exp2 ;

Parameters from the *base rule* are copied to the new rule if the new
rule doesn't define its own. Repeated inheritance should be possible,
but it *hasn't been tested*.


Memoization
~~~~~~~~~~~

|TatSu| is a packrat parser. The result of parsing a rule at a given
position in the input is cached, so the next time the parser visits
the same input position with the same rule the same result is returned
and the input advanced, without repeating the parsing. Memoization
allows for grammars that are clearer and easier to write because
there's no fear that repeating subexpressions will impact performance.

There are rules that should not be memoized. For example, rules that
may succeed or not depending on the associated semantic action should
not be memoized if sucess depends on more than just the input.

The ``@nomemo`` decorator turns off memoization for a particular rule::

  @nomemo
  INDENT = () ;

  @nomemo
  DEDENT = () ;


Rule Overrides
~~~~~~~~~~~~~~

A grammar rule may be redefined by using the ``@override`` decorator::

  start = ab $;

  ab = 'xyz' ;

  @override
  ab = @:'a' {@:'b'} ;

When combined with the ``#include`` directive, rule overrides can be
used to create a modified grammar without altering the original.


Grammar Name
~~~~~~~~~~~~

The prefix to be used in classes generated by |TatSu| can be passed to
the command-line tool using the ``-m`` option:

.. code:: bash

   $ tatsu -m MyLanguage mygrammar.ebnf

will generate:

.. code:: python

   class MyLanguageParser(Parser):
       ...

The name can also be specified within the grammar using the
``@@grammar`` directive::

  @@grammar :: MyLanguage


Whitespace
~~~~~~~~~~

By default, |TatSu| generated parsers skip the usual whitespace
characters with the regular expression ``r'\s+'`` using the
``re.UNICODE`` flag (or with the ``Pattern_White_Space`` property if the
`regex`_ module is available), but you can change that behavior by
passing a ``whitespace`` parameter to your parser.

For example, the following will skip over *tab* (``\t``) and *space*
characters, but not so with other typical whitespace characters such as
*newline* (``\n``):

.. code:: python

   parser = MyParser(text, whitespace='\t ')

The character string is converted into a regular expression character
set before starting to parse.

You can also provide a regular expression directly instead of a string.
The following is equivalent to the above example:

.. code:: python

   parser = MyParser(text, whitespace=re.compile(r'[\t ]+'))

Note that the regular expression must be pre-compiled to let |TatSu|
distinguish it from plain string.

If you do not define any whitespace characters, then you will have to
handle whitespace in your grammar rules (as it's often done in `PEG`_
parsers):

.. code:: python

   parser = MyParser(text, whitespace='')

Whitespace may also be specified within the grammar using the
``@@whitespace`` directive, although any of the above methods will
overwrite the setting in the grammar::

  @@whitespace :: /[\t ]+/

If no ``whitespace`` or ``@@whitespace`` is specified, |TatSu| will use
``r'(?m)\s+'`` as a default. Use ``None`` to have *no whitespace definition*.


.. code:: python

   parser = MyParser(text, whitespace=None)

or:

.. code::

    @@whitespace :: None

Case Sensitivity
~~~~~~~~~~~~~~~~

If the source language is case insensitive, it can be specified in the
parser by using the ``ignorecase`` parameter:

.. code:: python

   parser = MyParser(text, ignorecase=True)

You may also specify case insensitivity within the grammar using the
``@@ignorecase`` directive::

  @@ignorecase :: True

The change will affect token matching, but not pattern matching. Use `(?i)`
in patterns that should ignore case.

Comments
~~~~~~~~

Parsers will skip over comments specified as a regular expression using
the ``comments`` parameter:

.. code:: python

   parser = MyParser(text, comments="\(\*.*?\*\)")

For more complex comment handling, you can override the
``Buffer.eat_comments()`` method.

For flexibility, it is possible to specify a pattern for end-of-line
comments separately:

.. code:: python

   parser = MyParser(
       text,
       comments="\(\*.*?\*\)",
       eol_comments="#.*?$"
   )

Both patterns may also be specified within a grammar using the
``@@comments`` and ``@@eol_comments`` directives::

  @@comments :: /\(\*.*?\*\)/
  @@eol_comments :: /#.*?$/


Reserved Words and Keywords
~~~~~~~~~~~~~~~~~~~~~~~~~~~

Some languages must reserve the use of certain tokens as valid
identifiers because the tokens are used to mark particular constructs in
the language. Those reserved tokens are known as `Reserved Words`_ or
`Keywords`_

|TatSu| provides support for preventing the use of `keywords`_ as
identifiers though the ``@@keyword`` directive,and the ``@name``
decorator.

A grammar may specify reserved tokens providing a list of them in one or
more ``@@keyword`` directives::

  @@keyword :: if endif
  @@keyword :: else elseif

The ``@name`` decorator checks that the result of a grammar rule does
not match a token defined as a `keyword`_::

  @name
  identifier = /(?!\d)\w+/ ;

There are situations in which a token is reserved only in a very
specific context. In those cases, a negative lookahead will prevent the
use of the token::

  statements = {!'END' statement}+ ;

Include Directive
~~~~~~~~~~~~~~~~~

|TatSu| grammars support file inclusion through the include directive::

  #include :: "filename"

The resolution of the *filename* is relative to the directory/folder of
the source. Absolute paths and ``../`` navigations are honored.

The functionality required for implementing includes is available to all
|TatSu|-generated parsers through the ``Buffer`` class; see the
``EBNFBuffer`` class in the ``tatsu.parser`` module for an example.


Left Recursion
~~~~~~~~~~~~~~

|TatSu| supports left recursion in `PEG`_
grammars. The algorithm used is `Warth et al`_'s.

Sometimes, while debugging a grammar, it is useful to turn
left-recursion support on or off:

.. code:: python

   parser = MyParser(
       text,
       left_recursion=True,
   )

Left recursion can also be turned off from within the grammar using the
``@@left_recursion`` directive::

  @@left_recursion :: False