python / python/cpython

Escaped quotes cause source comments to leak into debug f-string output and t-string metadata

Ouverte
#154,711 3 commentaires 0 réactions 0 personnes assignées Voir sur GitHub

Personne n'a encore pris cette issue.

interpreter-core topic-parser type-bug
Langage dominant
Python
Étoiles
77.2k
Forks
35.9k
Métriques de merge des PR
Métriques de PR en attente

Description

Bug report

Bug description:

When an f-string or t-string replacement expression contains a backslash-escaped quote, a following source comment can be copied into runtime output or t-string metadata.

Observed effects:

  • A debug f-string includes the source comment in the resulting str.
  • A debug t-string includes the comment in Template.strings.
  • A debug t-string includes both the debug = and the comment inInterpolation.expression.
  • A non-debug t-string also retains the comment inInterpolation.expression.

The replacement expression itself evaluates to the correct value. The problemappears to be in reconstruction of the replacement-field source text.

Reproducer

f_result = f"{'\'' = # c
}"

t_debug = t"{'a\'b' = # c
}"
t_plain = t"{'a\'b' # c
}"

print("debug f-string result:", repr(f_result))
print("\ndebug t-string strings:", repr(t_debug.strings))
print("\ndebug t-string expression:", repr(t_debug.interpolations[0].expression))
print("\nnon-debug t-string expression:", repr(t_plain.interpolations[0].expression))

Actual behavior

On CPython main commit b86a41c, the output contains the source text # c in all four observed values.

debug f-string result: '\'\\\'\' = # c\n"\'"'

debug t-string strings: ("'a\\'b' = # c\n", '')

debug t-string expression: "'a\\'b' = # c"

non-debug t-string expression: "'a\\'b' # c"

Possible cause

The behavior appears to be caused by inconsistent escaped-character handling between two scans in _PyLexer_set_ftstring_expr() in Parser/lexer/string.c.

The initial scan that detects a comment outside a string literal explicitly skips a backslash and the character following it:

if (ch == '\\') {
    i++;
    continue;
}

However, after a comment has been detected, the subsequent reconstruction pass that removes comments appears not to perform the equivalent skip. It changes in_string whenever it encounters a quote:

if (ch == '"' || ch == '\'') {
    if (!in_string) {
        in_string = 1;
        quote_char = ch;
    }
    else if (ch == quote_char) {
        in_string = 0;
    }
}
else if (ch == '#' && !in_string) {
    /* skip the comment */
}

For:

'a\'b' = # c

the second pass may interpret the escaped quote as the end of the string and the real closing quote as the beginning of another string:

'       begin string
\       treated as an ordinary character
'       incorrectly treated as end of string
b
'       incorrectly treated as beginning of another string
#       incorrectly considered to be inside a string

Consequently, the # is not recognized by the comment-removal branch and the comment is copied into the reconstructed text.
This also explains why the same input pattern affects both f-strings and t-strings: both use the same replacement-expression reconstruction logic.
This is a proposed root cause based on the observed behavior and source review, not a confirmed diagnosis.

CPython versions tested on:

CPython main branch, 3.16

Operating systems tested on:

Linux

Linked PRs
  • gh-154914

Guide de contribution

Ouvrir le guide de contribution

Par où commencer

  1. Lisez l'issue en entier, puis le guide de contribution du projet.
  2. Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
  3. Forkez le dépôt et travaillez sur une branche.
  4. Ouvrez une pull request qui référence le numéro de l'issue.

Piste de recherche

Commencez dans Parser/lexer/string.c, à _PyLexer_set_ftstring_expr(), en comparant l’analyse initiale des escaped characters avec la passe ultérieure de reconstruction après suppression des commentaires. Exécutez le reproducer fourni pour f-string et t-string sur CPython main. Le travail est terminé lorsque les escaped quotes ne provoquent plus l’apparition de # c dans la sortie de debug f-string, les chaînes t-string ou les métadonnées d’interpolation.

Rédigé par le modèle d'indexation à partir du texte de l'issue.

Évaluation

Stack technique
python
Domaine
compilers
Type d'issue
Bug
Difficulté
3/5
Temps estimé
1-2 jours
Activité
À l'abandon
Clarté
Clairement spécifiée
Accessibilité débutants
35/100

Recevez les nouvelles issues par e-mail

Un résumé court des issues GitHub adaptées aux débutants.