Skip to content

Commit f2db8f9

Browse files
committed
Comment on the funkiness of the t-string grammar
1 parent 394f835 commit f2db8f9

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

Doc/reference/lexical_analysis.rst

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1085,8 +1085,8 @@ Formal grammar for f-strings
10851085

10861086
F-strings are handled partly by the :term:`lexical analyzer`, which produces the
10871087
tokens :py:data:`~token.FSTRING_START`, :py:data:`~token.FSTRING_MIDDLE`
1088-
and :py:data:`~token.FSTRING_END`, and the parser, which handles expressions
1089-
in the replacement field.
1088+
and :py:data:`~token.FSTRING_END`, and partly by the parser, which handles
1089+
expressions in the replacement field.
10901090
The exact way the work is split is a CPython implementation detail.
10911091

10921092
Correspondingly, the f-string grammar is a mix of
@@ -1109,6 +1109,12 @@ Whitespace is significant in these situations:
11091109
retrieved from the source code using locations of the ``{`` token
11101110
and the token after ``=``.
11111111

1112+
1113+
The ``FSTRING_MIDDLE`` definition uses
1114+
:ref:`negative lookaheads <lexical-lookaheads>` (``!``)
1115+
to indicate special characters (backslash, newline, ``{``, ``}``) and
1116+
sequences (``f_quote``).
1117+
11121118
.. grammar-snippet:: python-grammar
11131119
:group: python-grammar
11141120

@@ -1143,6 +1149,15 @@ Whitespace is significant in these situations:
11431149
| ','.(`conditional_expression` | "*" `or_expr`)+ [","]
11441150
| `yield_expression`
11451151
1152+
.. note::
1153+
1154+
In the above grammar snippet, the ``f_quote`` and ``FSTRING_MIDDLE`` rules
1155+
are context-sensitive -- they depend on the contents of ``FSTRING_START``
1156+
of the nearest enclosing ``fstring``.
1157+
1158+
Constructing a more traditional formal grammar from this template is left
1159+
as an exercise for the reader.
1160+
11461161

11471162
.. _t-strings:
11481163
.. _template-string-literals:

0 commit comments

Comments
 (0)