From 6384d7b630da07200853b1e25e73b9bb950dff43 Mon Sep 17 00:00:00 2001 From: JF Date: Sat, 28 Nov 2026 04:45:11 -0500 Subject: [PATCH 1/2] fix(python): a logpoint whose message cannot evaluate is refused when it is set, with the form that works set_breakpoint with a Python logMessage such as "stale={entry!r}" answered success, and every hit then logged "invalid syntax (, line 1)": debugpy takes the text between each pair of braces as a Python expression and evaluates it at the hit, and "entry!r" is f-string syntax (#1334). Python now implements validateLogMessage, the policy member JavaScript already uses to refuse a logpoint that cannot compile. A brace group with an f-string conversion (!r, !s, !a) or a format spec at its top level is refused, and the refusal names the replacement: {repr(x)}, {format(total, '.2f')}, {format(repr(x), '>10')}. Everything else is passed through untouched: comparisons, slices, string literals holding a colon, lambdas, :=, nested dict and set literals. The scanner follows debugpy's own brace matching. Checked as real logpoints against debugpy 1.8.20: the validator refuses exactly the messages that logged a syntax error, and each replacement it names logs the value. Written by a Gemini worker (Google, gemini-4-carbon-high) from the manager's brief and the design call on the issue. Fixes #1334. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_015BDrn82vMcRzWFDD9aUbZs --- changelog.d/1334.fixed.md | 1 + docs/python/README.md | 2 +- packages/shared/src/index.ts | 5 + .../src/interfaces/adapter-policy-python.ts | 5 + .../shared/src/interfaces/adapter-policy.ts | 4 +- packages/shared/src/utils/python-logpoint.ts | 540 ++++++++++++++++++ skills/debugging/references/python.md | 2 +- .../python-logpoint-validation.test.ts | 147 +++++ .../server/server-logpoint-gating.test.ts | 28 + tests/fixtures/python/logpoint_values.py | 34 ++ .../shared/adapter-policy-contract.test.ts | 18 + .../unit/shared/adapter-policy-python.test.ts | 6 + tests/unit/shared/python-logpoint.test.ts | 180 ++++++ 13 files changed, 969 insertions(+), 3 deletions(-) create mode 100644 changelog.d/1334.fixed.md create mode 100644 packages/shared/src/utils/python-logpoint.ts create mode 100644 tests/adapters/python/integration/python-logpoint-validation.test.ts create mode 100644 tests/fixtures/python/logpoint_values.py create mode 100644 tests/unit/shared/python-logpoint.test.ts diff --git a/changelog.d/1334.fixed.md b/changelog.d/1334.fixed.md new file mode 100644 index 000000000..4104e1688 --- /dev/null +++ b/changelog.d/1334.fixed.md @@ -0,0 +1 @@ +**Python logpoints with f-string conversions or format specs are refused at `set_breakpoint` time with the expression form that works** — debugpy evaluates the text inside each `{...}` group of a `logMessage` as a Python expression at hit time rather than parsing an f-string field, so `{entry!r}`, `{x!s}`, `{x!a}` and `{total:.2f}` succeeded when set and logged `invalid syntax (, line 1)` (or `invalid decimal literal (, line 1)`) when hit; `PythonAdapterPolicy.validateLogMessage` now refuses top-level conversions and format specs up front and names the working replacement (`{repr(entry)}`, `{str(x)}`, `{ascii(x)}`, `{format(total, '.2f')}`) (#1334) diff --git a/docs/python/README.md b/docs/python/README.md index eb5542529..3f77ad4d5 100644 --- a/docs/python/README.md +++ b/docs/python/README.md @@ -63,7 +63,7 @@ set_breakpoint { "sessionId": "...", "file": "/abs/path/script.py", "line": 15, set_breakpoint { "sessionId": "...", "file": "/abs/path/script.py", "line": 15, "logMessage": "x={x} y={y}" } ``` -A logpoint never pauses: it interpolates the `{expressions}` and writes the line to `get_output` while the program keeps running. Each hit does cost time, however — measured at 24.7 µs per hit on Python 3.13 + debugpy (`sys.monitoring`, 2.5% of a core at 1,000 hits/s), and placing a logpoint anywhere in a function slows that whole function by 58× — so keep logpoints off tight loops. When hits outrun debugpy's delivery rate (measured at 3,200–4,400 lines/s during a run and about 6,000 lines/s draining afterward), lines still queued when the program exits are lost and the session's end answer does not report the loss (issue #1265). See [Logpoints](../tool-reference.md#logpoints) for measurement conditions and what was not measured. +A logpoint never pauses: it interpolates the `{expressions}` and writes the line to `get_output` while the program keeps running. The braces take Python expressions rather than f-string fields — write `{repr(x)}` or `{format(total, '.2f')}`, not `{x!r}` or `{total:.2f}` (refused when the breakpoint is set). Each hit does cost time, however — measured at 24.7 µs per hit on Python 3.13 + debugpy (`sys.monitoring`, 2.5% of a core at 1,000 hits/s), and placing a logpoint anywhere in a function slows that whole function by 58× — so keep logpoints off tight loops. When hits outrun debugpy's delivery rate (measured at 3,200–4,400 lines/s during a run and about 6,000 lines/s draining afterward), lines still queued when the program exits are lost and the session's end answer does not report the loss (issue #1265). See [Logpoints](../tool-reference.md#logpoints) for measurement conditions and what was not measured. ### 3. Start Debugging diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 5d018463f..6223aaaf6 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -326,6 +326,11 @@ export { type LogMessagePart, type CompiledJsLogpoint } from './utils/js-logpoint.js'; +export { + extractPythonLogMessageGroups, + validatePythonLogMessage, + type PythonLogMessageGroup +} from './utils/python-logpoint.js'; // Argv marker constants shared by spawn-time tagging and the startup orphan // reapers (issues #343, #431). export { diff --git a/packages/shared/src/interfaces/adapter-policy-python.ts b/packages/shared/src/interfaces/adapter-policy-python.ts index a24703746..f85096986 100644 --- a/packages/shared/src/interfaces/adapter-policy-python.ts +++ b/packages/shared/src/interfaces/adapter-policy-python.ts @@ -9,6 +9,7 @@ import { emptyLocalVariableExtraction, extractionFromScope } from './adapter-pol import type { StackFrame, Variable } from '../models/index.js'; import type { DapClientBehavior, DapClientContext, ReverseRequestResult } from './dap-client-behavior.js'; import type { ChildAdoptionContract, ChildReport } from './child-adoption.js'; +import { validatePythonLogMessage } from '../utils/python-logpoint.js'; /** * A debugpy child report (issue #1081): a `startDebugging` whose configuration @@ -98,6 +99,10 @@ export const PythonAdapterPolicy = { // correctly, sends no `initialized`: the worker does not wait for one (#746). honoursNoDebug: true, supportsLogPoints: true, + // debugpy splices each `{...}` group into `'...' % (expr,)` and eval()s it at + // hit time, so f-string conversions (`{entry!r}`) and format specs + // (`{total:.2f}`) log `invalid syntax` only when hit (issue #1334). + validateLogMessage: (logMessage: string, _condition?: string): string | undefined => validatePythonLogMessage(logMessage), supportsFunctionBreakpoints: true, supportsReverseStartDebugging: false, // debugpy runs exactly one of these (`debugpy/adapter/clients.py`: '"program", diff --git a/packages/shared/src/interfaces/adapter-policy.ts b/packages/shared/src/interfaces/adapter-policy.ts index c510ddf07..bd1848e19 100644 --- a/packages/shared/src/interfaces/adapter-policy.ts +++ b/packages/shared/src/interfaces/adapter-policy.ts @@ -491,7 +491,9 @@ export interface AdapterPolicy { /** * Up-front check of a logMessage (and its optional condition) for a policy - * that compiles logpoints itself (issue #853): the returned text refuses + * that compiles logpoints itself (issue #853) or rejects forms its engine + * evaluates as syntax errors only when the line is hit (Python f-string + * conversions and format specs, issue #1334): the returned text refuses * set_breakpoint the way an expectedContent mismatch does, instead of the * adapter reporting the syntax error only in its output stream. Undefined * means the message is acceptable (or the policy does not pre-validate). diff --git a/packages/shared/src/utils/python-logpoint.ts b/packages/shared/src/utils/python-logpoint.ts new file mode 100644 index 000000000..858390261 --- /dev/null +++ b/packages/shared/src/utils/python-logpoint.ts @@ -0,0 +1,540 @@ +/** + * Up-front validation of Python (debugpy / pydevd) logpoint messages (issue #1334). + * + * pydevd (`_pydevd_bundle/pydevd_utils.py`, `_extract_expression_list` and + * `convert_dap_log_message_to_expression`) scans a DAP `logMessage` character by + * character: each `{...}` group is extracted by counting nested `{` and `}` + * (without string-literal awareness and without `{{` / `}}` brace escapes; empty + * groups are dropped, and unbalanced braces replace the whole message with + * `'Unbalanced braces in: ...'`), stripped of outer whitespace, and spliced into + * `repr(fmt) + " % (" + ", ".join(vars) + ",)"`. At hit time `pydevd.py`'s + * `handle_breakpoint_expression` calls `eval(...)` on that string and catches + * any exception as `str(exc)`, so a `SyntaxError` is only surfaced when the + * line runs (`invalid syntax (, line 1)` or + * `invalid decimal literal (, line 1)`). + * + * Callers frequently write f-string field suffixes inside logpoint braces — + * conversions (`{entry!r}`, `{x!s}`, `{x!a}`) and format specs (`{total:.2f}`). + * Neither is valid in a Python expression, so every such group is certain to + * fail when hit. This validator refuses only those top-level forms when the + * breakpoint is set and names the expression form that works. + */ + +const CONVERSION_FN = { + r: 'repr', + s: 'str', + a: 'ascii' +} as const; + +type FStringConversion = keyof typeof CONVERSION_FN; + +const IDENT_START_RE = /[\p{ID_Start}_]/u; +const IDENT_CONTINUE_RE = /[\p{ID_Continue}]/u; +const STRING_PREFIX_RE = /^(?:[rRuUbBfFtT]|[rR][bBfFtT]|[bBfFtT][rR])$/; +const INTERPOLATED_PREFIX_RE = /[fFtT]/; +const STATEMENT_HEADER_RE = /^(?:if|elif|else|for|while|with|try|except|finally|def|class|match|case)\b/; +const DANGLING_OPERATOR_RE = /[+\-*/%=<>&|^~@]$/; +const TRAILING_KEYWORD_RE = + /(?:^|[^.\p{ID_Continue}])(?:and|or|not|in|is|if|else|lambda|for|await|return|import|from|raise|del|pass|break|continue|assert|global|nonlocal)$/u; + +export interface PythonLogMessageGroup { + /** Exact substring between the outer `{` and `}`, as written by the caller. */ + raw: string; + /** Trimmed group text, matching pydevd's `"".join(expression).strip()`. */ + expression: string; +} + +/** + * Extract `{...}` groups using pydevd's exact nested-brace rule + * (`_extract_variable_nested_braces` / `_extract_expression_list`). Returns + * `undefined` when braces are unbalanced, matching pydevd's whole-message + * `SyntaxError` fallback. + */ +export function extractPythonLogMessageGroups(logMessage: string): PythonLogMessageGroup[] | undefined { + const groups: PythonLogMessageGroup[] = []; + let i = 0; + while (i < logMessage.length) { + if (logMessage[i] !== '{') { + i += 1; + continue; + } + let level = 0; + const start = i + 1; + i += 1; + while (i < logMessage.length) { + const ch = logMessage[i]; + if (ch === '{') { + level += 1; + } else if (ch === '}') { + level -= 1; + if (level === -1) { + break; + } + } + i += 1; + } + if (level !== -1) { + return undefined; + } + const raw = logMessage.slice(start, i); + const expression = raw.trim(); + if (expression.length > 0) { + groups.push({ raw, expression }); + } + i += 1; + } + return groups; +} + +function isConversionChar(ch: string | undefined): ch is FStringConversion { + return ch === 'r' || ch === 's' || ch === 'a'; +} + +function isIdentifierStartAt(src: string, index: number): boolean { + if (index >= src.length) { + return false; + } + const ch = String.fromCodePoint(src.codePointAt(index)!); + return IDENT_START_RE.test(ch); +} + +function readIdentifierEnd(src: string, start: number): number { + let i = start; + while (i < src.length) { + const ch = String.fromCodePoint(src.codePointAt(i)!); + if (!IDENT_CONTINUE_RE.test(ch)) { + break; + } + i += ch.length; + } + return i; +} + +function matchingOpen(closer: ')' | ']' | '}'): '(' | '[' | '{' { + if (closer === ')') return '('; + if (closer === ']') return '['; + return '{'; +} + +/** + * Index past the closing quote of a Python string literal starting at + * `quoteStart`, or `-1` when unterminated. Supports single/double and + * triple-quoted strings plus PEP 701 nested f-string / t-string fields. + */ +function skipPythonString(src: string, quoteStart: number, hasInterpolation: boolean): number { + const quoteChar = src[quoteStart]; + const triple = src[quoteStart + 1] === quoteChar && src[quoteStart + 2] === quoteChar; + let i = quoteStart + (triple ? 3 : 1); + while (i < src.length) { + const ch = src[i]; + if (ch === '\\') { + // In Python f-strings `\` does not escape `{` or `}`, so `f"\{x}"` still + // opens a replacement field at `{`. + if (hasInterpolation && (src[i + 1] === '{' || src[i + 1] === '}')) { + i += 1; + continue; + } + i += 2; + if (i > src.length) { + return -1; + } + continue; + } + if (!triple && (ch === '\n' || ch === '\r')) { + return -1; + } + if (!triple && ch === quoteChar) { + return i + 1; + } + if (triple && ch === quoteChar && src[i + 1] === quoteChar && src[i + 2] === quoteChar) { + return i + 3; + } + if (hasInterpolation) { + if (ch === '{') { + if (src[i + 1] === '{') { + i += 2; + continue; + } + const fieldEnd = skipInterpolatedField(src, i + 1); + if (fieldEnd < 0) { + return -1; + } + i = fieldEnd; + continue; + } + if (ch === '}') { + if (src[i + 1] === '}') { + i += 2; + continue; + } + return -1; + } + } + i += 1; + } + return -1; +} + +/** + * Index past the closing `}` of an f-string / t-string `{...}` replacement + * field starting right after `{`, or `-1` when malformed. + */ +function skipInterpolatedField(src: string, start: number): number { + const stack: Array<'(' | '[' | '{'> = []; + let pendingLambdas = 0; + let prevWasDot = false; + let inFormatSpec = false; + let i = start; + + while (i < src.length) { + if (inFormatSpec) { + if (src[i] === '{') { + const nested = skipInterpolatedField(src, i + 1); + if (nested < 0) { + return -1; + } + i = nested; + continue; + } + if (src[i] === '}') { + return i + 1; + } + i += 1; + continue; + } + + const ch = src[i]; + if (ch === ' ' || ch === '\t' || ch === '\r' || ch === '\n') { + i += 1; + continue; + } + if (ch === '#') { + const nl = src.indexOf('\n', i + 1); + if (nl < 0) { + return -1; + } + i = nl + 1; + continue; + } + if (ch === "'" || ch === '"') { + const end = skipPythonString(src, i, false); + if (end < 0) { + return -1; + } + prevWasDot = false; + i = end; + continue; + } + if (isIdentifierStartAt(src, i)) { + const identEnd = readIdentifierEnd(src, i); + const ident = src.slice(i, identEnd); + const next = src[identEnd]; + if ((next === "'" || next === '"') && STRING_PREFIX_RE.test(ident)) { + const end = skipPythonString(src, identEnd, INTERPOLATED_PREFIX_RE.test(ident)); + if (end < 0) { + return -1; + } + prevWasDot = false; + i = end; + continue; + } + if (stack.length === 0 && ident === 'lambda' && !prevWasDot) { + pendingLambdas += 1; + } + prevWasDot = false; + i = identEnd; + continue; + } + if (ch === '(' || ch === '[' || ch === '{') { + stack.push(ch); + prevWasDot = false; + i += 1; + continue; + } + if (ch === ')' || ch === ']' || ch === '}') { + if (ch === '}' && stack.length === 0) { + return i + 1; + } + if (stack.length === 0 || stack[stack.length - 1] !== matchingOpen(ch)) { + return -1; + } + stack.pop(); + prevWasDot = false; + i += 1; + continue; + } + if (ch === ':') { + if (src[i + 1] === '=') { + prevWasDot = false; + i += 2; + continue; + } + if (stack.length === 0) { + if (pendingLambdas > 0) { + pendingLambdas -= 1; + prevWasDot = false; + i += 1; + continue; + } + inFormatSpec = true; + i += 1; + continue; + } + prevWasDot = false; + i += 1; + continue; + } + if (ch === '.') { + if (src[i + 1] === '.' && src[i + 2] === '.') { + prevWasDot = false; + i += 3; + continue; + } + prevWasDot = true; + i += 1; + continue; + } + prevWasDot = false; + i += 1; + } + + return -1; +} + +function isPlausibleOperand(expr: string): boolean { + if (expr.length === 0) { + return false; + } + if (STATEMENT_HEADER_RE.test(expr)) { + return false; + } + if (DANGLING_OPERATOR_RE.test(expr)) { + return false; + } + if (expr.endsWith('.') && !expr.endsWith('...') && !(expr.length >= 2 && /\d$/.test(expr.slice(0, -1)))) { + return false; + } + if (TRAILING_KEYWORD_RE.test(expr)) { + return false; + } + return true; +} + +function wrapForCallArg(expr: string, hasTopLevelComma: boolean): string { + return hasTopLevelComma ? `(${expr})` : expr; +} + +function formatPythonStringLiteral(value: string): string { + const escaped = value + .replace(/\\/g, '\\\\') + .replace(/\r/g, '\\r') + .replace(/\n/g, '\\n') + .replace(/\t/g, '\\t'); + if (value.includes("'") && !value.includes('"')) { + return `"${escaped}"`; + } + return `'${escaped.replace(/'/g, "\\'")}'`; +} + +function formatSpecLiteral(spec: string): string { + const literal = formatPythonStringLiteral(spec); + return spec.includes('{') && spec.includes('}') ? `f${literal}` : literal; +} + +function inspectPythonGroup(group: PythonLogMessageGroup): string | undefined { + const src = group.expression; + const stack: Array<'(' | '[' | '{'> = []; + let pendingLambdas = 0; + let prevWasDot = false; + let firstTopLevelComma = -1; + let lastTopLevelBang = -1; + let topLevelBangCount = 0; + let i = 0; + + while (i < src.length) { + const ch = src[i]; + if (ch === ' ' || ch === '\t' || ch === '\r' || ch === '\n') { + i += 1; + continue; + } + if (ch === '#') { + const nl = src.indexOf('\n', i + 1); + if (nl < 0) { + i = src.length; + break; + } + i = nl + 1; + continue; + } + if (ch === "'" || ch === '"') { + const end = skipPythonString(src, i, false); + if (end < 0) { + return undefined; + } + prevWasDot = false; + i = end; + continue; + } + if (isIdentifierStartAt(src, i)) { + const identEnd = readIdentifierEnd(src, i); + const ident = src.slice(i, identEnd); + const next = src[identEnd]; + if ((next === "'" || next === '"') && STRING_PREFIX_RE.test(ident)) { + const end = skipPythonString(src, identEnd, INTERPOLATED_PREFIX_RE.test(ident)); + if (end < 0) { + return undefined; + } + prevWasDot = false; + i = end; + continue; + } + if (stack.length === 0 && ident === 'lambda' && !prevWasDot) { + pendingLambdas += 1; + } + prevWasDot = false; + i = identEnd; + continue; + } + if (ch === '(' || ch === '[' || ch === '{') { + stack.push(ch); + prevWasDot = false; + i += 1; + continue; + } + if (ch === ')' || ch === ']' || ch === '}') { + if (stack.length === 0 || stack[stack.length - 1] !== matchingOpen(ch)) { + return undefined; + } + stack.pop(); + prevWasDot = false; + i += 1; + continue; + } + if (ch === '!') { + if (src[i + 1] === '=') { + prevWasDot = false; + i += 2; + continue; + } + if (stack.length === 0) { + lastTopLevelBang = i; + topLevelBangCount += 1; + } + prevWasDot = false; + i += 1; + continue; + } + if (ch === ',' && stack.length === 0) { + if (firstTopLevelComma === -1) { + firstTopLevelComma = i; + } + prevWasDot = false; + i += 1; + continue; + } + if (ch === ':') { + if (src[i + 1] === '=') { + prevWasDot = false; + i += 2; + continue; + } + if (stack.length === 0) { + if (pendingLambdas > 0) { + pendingLambdas -= 1; + prevWasDot = false; + i += 1; + continue; + } + // First top-level non-lambda, non-walrus colon: everything after it is + // the format spec. Stop expression tokenizing here so format-spec fill + // characters (`'` in `{x:'<10}`, `#` in `{n:#08x}`) are not read as + // Python string quotes or comments. + const colonIndex = i; + const leftTrimEnd = src.slice(0, colonIndex).trimEnd(); + const spec = src.slice(colonIndex + 1); + const specLiteral = formatSpecLiteral(spec); + + if ( + topLevelBangCount === 1 && + lastTopLevelBang === leftTrimEnd.length - 2 && + isConversionChar(leftTrimEnd[leftTrimEnd.length - 1]) + ) { + const conv = leftTrimEnd[leftTrimEnd.length - 1] as FStringConversion; + const baseRaw = leftTrimEnd.slice(0, lastTopLevelBang).trim(); + if (!isPlausibleOperand(baseRaw)) { + return undefined; + } + const hasComma = firstTopLevelComma !== -1 && firstTopLevelComma < lastTopLevelBang; + const converted = `${CONVERSION_FN[conv]}(${wrapForCallArg(baseRaw, hasComma)})`; + return `{${group.raw}}: debugpy evaluates the text between braces as a Python expression, and !${conv}:${spec} is f-string syntax, not an expression; use {format(${converted}, ${specLiteral})} instead.`; + } + + if (topLevelBangCount > 0) { + return undefined; + } + const baseRaw = leftTrimEnd.trim(); + if (!isPlausibleOperand(baseRaw)) { + return undefined; + } + const hasComma = firstTopLevelComma !== -1 && firstTopLevelComma < colonIndex; + const badSuffix = spec.length > 0 ? `:${spec}` : "':'"; + return `{${group.raw}}: debugpy evaluates the text between braces as a Python expression, and ${badSuffix} is f-string syntax, not an expression; use {format(${wrapForCallArg(baseRaw, hasComma)}, ${specLiteral})} instead.`; + } + prevWasDot = false; + i += 1; + continue; + } + if (ch === '.') { + if (src[i + 1] === '.' && src[i + 2] === '.') { + prevWasDot = false; + i += 3; + continue; + } + prevWasDot = true; + i += 1; + continue; + } + prevWasDot = false; + i += 1; + } + + if (stack.length !== 0 || pendingLambdas !== 0) { + return undefined; + } + + if ( + topLevelBangCount === 1 && + lastTopLevelBang === src.length - 2 && + isConversionChar(src[src.length - 1]) + ) { + const conv = src[src.length - 1] as FStringConversion; + const baseRaw = src.slice(0, lastTopLevelBang).trim(); + if (!isPlausibleOperand(baseRaw)) { + return undefined; + } + const hasComma = firstTopLevelComma !== -1 && firstTopLevelComma < lastTopLevelBang; + return `{${group.raw}}: debugpy evaluates the text between braces as a Python expression, and !${conv} is f-string syntax, not an expression; use {${CONVERSION_FN[conv]}(${wrapForCallArg(baseRaw, hasComma)})} instead.`; + } + + return undefined; +} + +/** + * Return a refusal message naming the working expression form when a `{...}` + * group in a Python `logMessage` uses a top-level f-string conversion (`!r`, + * `!s`, `!a`) or format spec (`:spec`), or `undefined` when no group is + * certain to fail for that reason. + */ +export function validatePythonLogMessage(logMessage: string): string | undefined { + const groups = extractPythonLogMessageGroups(logMessage); + if (!groups) { + return undefined; + } + for (const group of groups) { + const problem = inspectPythonGroup(group); + if (problem !== undefined) { + return problem; + } + } + return undefined; +} diff --git a/skills/debugging/references/python.md b/skills/debugging/references/python.md index 086243002..de1fd4388 100644 --- a/skills/debugging/references/python.md +++ b/skills/debugging/references/python.md @@ -67,7 +67,7 @@ Shorthand: `create_debug_session { "language": "python", "host": "127.0.0.1", "p - **Set breakpoints on executable lines** (assignments, calls, returns). Comments, blank lines, and bare `def`/`class` lines misbehave. - **evaluate_expression** runs in debugpy's `variables` (watch-style) context by default. Reads and arithmetic are reliable; whether mutations like `x = 5` take effect depends on debugpy — verify with a follow-up evaluate before relying on one. Collections are truncated at 300 items. - **Output capture works for Python** (`redirectOutput`): `print()` and stderr land in `get_output` entries, readable during and after the run until the session closes. -- Logpoints work: `set_breakpoint` with `logMessage: "x={x}"` logs interpolated values to `get_output` without pausing. Each hit costs about 24.7 µs (2.5% of a core at 1,000 hits/s), and any logpoint in a function slows that whole function by 58× on Python 3.13 + debugpy (`sys.monitoring`) — keep logpoints off tight loops. When hits outrun debugpy's delivery rate (measured at 3,200–4,400 lines/s during a run, ~6,000 lines/s draining after), lines still queued at program exit are lost and the end answer does not say so (issue #1265). Full measurements: [docs/tool-reference.md#logpoints](https://github.com/debugmcp/mcp-debugger/blob/main/docs/tool-reference.md#logpoints). +- Logpoints work: `set_breakpoint` with `logMessage: "x={x}"` logs interpolated values to `get_output` without pausing. Each `{...}` group takes a Python expression, not an f-string field — write `{repr(x)}` or `{format(total, '.2f')}`, not `{x!r}` or `{total:.2f}` (refused at `set_breakpoint` time). Each hit costs about 24.7 µs (2.5% of a core at 1,000 hits/s), and any logpoint in a function slows that whole function by 58× on Python 3.13 + debugpy (`sys.monitoring`) — keep logpoints off tight loops. When hits outrun debugpy's delivery rate (measured at 3,200–4,400 lines/s during a run, ~6,000 lines/s draining after), lines still queued at program exit are lost and the end answer does not say so (issue #1265). Full measurements: [docs/tool-reference.md#logpoints](https://github.com/debugmcp/mcp-debugger/blob/main/docs/tool-reference.md#logpoints). - **Child processes are debug sessions by default.** debugpy's sub-process debugging is on: each Python child the program starts (`subprocess`, `multiprocessing`, pytest-xdist workers) becomes a child debug session — `list_debug_sessions` lists it with `parentSessionId`, it stops on this session's breakpoints, and `wait_for_stop` on this session reports the child's stop with `sessionId` naming the child (inspect and step with that id) and `children` listing the tree; a child can still be waited on by its own id. `dapLaunchArgs: { subProcess: false }` opts a launch out (the children run undebugged; the answer's warning says so); an attach target decides for itself (`python -m debugpy --listen … --configure-subProcess false`). `DEBUG_MCP_MAX_CHILD_SESSIONS=0` turns adoption off server-wide. ## Troubleshooting diff --git a/tests/adapters/python/integration/python-logpoint-validation.test.ts b/tests/adapters/python/integration/python-logpoint-validation.test.ts new file mode 100644 index 000000000..bfa3f111d --- /dev/null +++ b/tests/adapters/python/integration/python-logpoint-validation.test.ts @@ -0,0 +1,147 @@ +/** + * Real debugpy coverage for issue #1334: setting a Python logpoint whose brace + * group uses an f-string conversion (`{x!r}`) or format spec (`{total:.2f}`) + * is refused up front on a launched session with the expression form that + * works, and setting that replacement logs the evaluated value. + */ +import { afterEach, describe, expect, it } from 'vitest'; +import path from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; +import { + startStdioClient, + type StdioClientHandle, + type ToolAnswer +} from '../../../test-utils/helpers/mcp-stdio-client.js'; +import { ensurePythonOnPath } from './env-utils.js'; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.resolve(here, '../../../fixtures/python/logpoint_values.py'); + +function hasDebugpy(): boolean { + const env: Record = {}; + for (const [k, v] of Object.entries(process.env)) { + if (v !== undefined) env[k] = v; + } + ensurePythonOnPath(env); + for (const python of [process.env.PYTHON_PATH, 'python', 'python3'].filter((p): p is string => Boolean(p))) { + try { + const probe = spawnSync(python, ['-c', 'import debugpy'], { + env, + timeout: 15_000, + windowsHide: true, + stdio: 'ignore' + }); + if (probe.status === 0) return true; + } catch { + // try next candidate + } + } + return false; +} + +type BreakpointAnswer = ToolAnswer & { + breakpointId?: string; + verified?: boolean; + logMessage?: string; +}; + +type EndAnswer = ToolAnswer & { + pending?: boolean; + exitCode?: number; +}; + +type OutputAnswer = ToolAnswer & { + entries?: Array<{ seq: number; category: string; output: string }>; +}; + +describe.skipIf(!hasDebugpy())('Python logpoint validation against real debugpy (issue #1334) @requires-python', () => { + let server: StdioClientHandle | undefined; + + afterEach(async () => { + await server?.close(); + server = undefined; + }); + + it('refuses {x!r} and {total:.2f} on a launched Python session with their replacements, then logs the values when the replacements are set', async () => { + const env: Record = {}; + ensurePythonOnPath(env); + server = await startStdioClient({ name: 'python-logpoint-validation', env }); + const sessionId = await server.createSession('python', 'python-logpoint-validation'); + + const started = await server.call('start_debugging', { + scriptPath: FIXTURE, + dapLaunchArgs: { stopOnEntry: true } + }); + expect(started.success, JSON.stringify(started)).toBe(true); + expect(started.state, JSON.stringify(started)).toBe('paused'); + + await expect( + server.client.callTool({ + name: 'set_breakpoint', + arguments: { + sessionId, + file: FIXTURE, + line: 11, + logMessage: '{x!r}' + } + }) + ).rejects.toThrow( + 'Invalid logpoint: {x!r}: debugpy evaluates the text between braces as a Python expression, and !r is f-string syntax, not an expression; use {repr(x)} instead.' + ); + + await expect( + server.client.callTool({ + name: 'set_breakpoint', + arguments: { + sessionId, + file: FIXTURE, + line: 15, + logMessage: '{total:.2f}' + } + }) + ).rejects.toThrow( + "Invalid logpoint: {total:.2f}: debugpy evaluates the text between braces as a Python expression, and :.2f is f-string syntax, not an expression; use {format(total, '.2f')} instead." + ); + + // No refused logpoint was stored on the session. + const emptyList = await server.call('list_breakpoints'); + expect(emptyList.count).toBe(0); + + // Set the replacements named in the refusals, plus valid colon-bearing expressions. + const reprBp = await server.call('set_breakpoint', { + file: FIXTURE, + line: 11, + logMessage: '{repr(x)}' + }); + expect(reprBp.success, JSON.stringify(reprBp)).toBe(true); + expect(reprBp.verified, JSON.stringify(reprBp)).toBe(true); + + const formatBp = await server.call('set_breakpoint', { + file: FIXTURE, + line: 15, + logMessage: "{format(total, '.2f')}" + }); + expect(formatBp.success, JSON.stringify(formatBp)).toBe(true); + expect(formatBp.verified, JSON.stringify(formatBp)).toBe(true); + + const sliceBp = await server.call('set_breakpoint', { + file: FIXTURE, + line: 16, + logMessage: '{items[1:3]}' + }); + expect(sliceBp.success, JSON.stringify(sliceBp)).toBe(true); + + const resumed = await server.call('continue_execution'); + expect(resumed.success, JSON.stringify(resumed)).toBe(true); + + const ended = await server.call('wait_for_stop', { timeout: 20_000 }); + expect(ended.success, JSON.stringify(ended)).toBe(true); + expect(ended.state, JSON.stringify(ended)).toBe('stopped'); + expect(ended.exitCode, JSON.stringify(ended)).toBe(0); + + const output = await server.call('get_output', { since: 0 }); + const lines = (output.entries ?? []).map((entry) => entry.output.trim()); + expect(lines, JSON.stringify(output)).toEqual(["'café'", '3.50', '[20, 30]']); + }, 60_000); +}); diff --git a/tests/core/unit/server/server-logpoint-gating.test.ts b/tests/core/unit/server/server-logpoint-gating.test.ts index 5103890a5..1f5a81b3e 100644 --- a/tests/core/unit/server/server-logpoint-gating.test.ts +++ b/tests/core/unit/server/server-logpoint-gating.test.ts @@ -10,6 +10,7 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; import { StdioServerTransport } from '@modelcontextprotocol/server/stdio'; import { Server } from '@modelcontextprotocol/server'; +import { PythonAdapterPolicy } from '@debugmcp/shared'; import { DebugMcpServer } from '../../../../src/server.js'; import { SessionManager } from '../../../../src/session/session-manager.js'; import { createProductionDependencies, type Dependencies } from '../../../../src/container/dependencies.js'; @@ -154,6 +155,33 @@ describe('set_breakpoint logMessage gating', () => { expect(JSON.parse(result.content[0].text).success).toBe(true); }); + it('refuses Python f-string conversions and format specs with the working expression, pre- and post-launch (issue #1334)', async () => { + mockSessionManager.getSessionPolicy.mockReturnValue(PythonAdapterPolicy); + + await expect(callSetBreakpoint({ logMessage: 'stale={entry!r}' })).rejects.toThrow( + /Invalid logpoint: \{entry!r\}:[\s\S]*\{repr\(entry\)\}/ + ); + await expect(callSetBreakpoint({ logMessage: '{total:.2f}' })).rejects.toThrow( + /Invalid logpoint: \{total:\.2f\}:[\s\S]*\{format\(total, '\.2f'\)\}/ + ); + expect(mockSessionManager.setBreakpoint).not.toHaveBeenCalled(); + + // Post-launch (live supportsLogPoints: true) runs the same Python policy check. + mockSessionManager.getSession.mockReturnValue({ + run: {}, + id: 'test-session', + sessionLifecycle: 'active', + adapterCapabilities: { supportsLogPoints: true } + }); + await expect(callSetBreakpoint({ logMessage: '{x!r}' })).rejects.toThrow(/\{repr\(x\)\}/); + expect(mockSessionManager.setBreakpoint).not.toHaveBeenCalled(); + + // The replacement named in the refusal and a logpoint condition pass through. + const ok = await callSetBreakpoint({ logMessage: 'stale={repr(entry)}', condition: 'entry is not None' }); + expect(JSON.parse(ok.content[0].text).success).toBe(true); + expect(mockSessionManager.setBreakpoint).toHaveBeenCalledTimes(1); + }); + it('validates against live capabilities too: a known-supported adapter still runs the policy check', async () => { mockSessionManager.getSessionPolicy.mockReturnValue({ name: 'js-debug', diff --git a/tests/fixtures/python/logpoint_values.py b/tests/fixtures/python/logpoint_values.py new file mode 100644 index 000000000..348b192e8 --- /dev/null +++ b/tests/fixtures/python/logpoint_values.py @@ -0,0 +1,34 @@ +import time + + +def run(): + x = "café" + total = 3.5 + items = [10, 20, 30, 40] + d = {"a:b": "colon-key"} + step = 0 + step += 1 # case 1 + step += 1 # case 2 + step += 1 # case 3 + step += 1 # case 4 + step += 1 # case 5 + step += 1 # case 6 + step += 1 # case 7 + step += 1 # case 8 + step += 1 # case 9 + step += 1 # case 10 + step += 1 # case 11 + step += 1 # case 12 + step += 1 # case 13 + step += 1 # case 14 + step += 1 # case 15 + step += 1 # case 16 + step += 1 # case 17 + step += 1 # case 18 + step += 1 # case 19 + time.sleep(0.05) + return step + + +if __name__ == "__main__": + run() diff --git a/tests/unit/shared/adapter-policy-contract.test.ts b/tests/unit/shared/adapter-policy-contract.test.ts index 624ca78d2..8a2b2098d 100644 --- a/tests/unit/shared/adapter-policy-contract.test.ts +++ b/tests/unit/shared/adapter-policy-contract.test.ts @@ -141,6 +141,8 @@ interface PinnedCapabilities { supportsFunctionBreakpoints: boolean | undefined; /** Static logpoint verdict; `undefined` means "unknown, re-check live". */ supportsLogPoints: boolean | undefined; + /** Whether the policy pre-validates `logMessage` at `set_breakpoint` time (issues #853, #1334). */ + validatesLogMessage: boolean; /** Out-of-band function-breakpoint delivery; `undefined` means the standard DAP request. */ functionBreakpointsVia: 'dap' | 'cdp' | undefined; /** Whether verified:false at launch is by design rather than a warning. */ @@ -211,6 +213,7 @@ const PINNED: Record = { policyName: 'python', supportsFunctionBreakpoints: true, supportsLogPoints: true, + validatesLogMessage: true, functionBreakpointsVia: undefined, functionBreakpointsBindLate: undefined, honoursNoDebug: true, @@ -232,6 +235,7 @@ const PINNED: Record = { policyName: 'ruby', supportsFunctionBreakpoints: false, supportsLogPoints: false, + validatesLogMessage: false, functionBreakpointsVia: undefined, functionBreakpointsBindLate: undefined, honoursNoDebug: undefined, @@ -253,6 +257,7 @@ const PINNED: Record = { policyName: 'js-debug', supportsFunctionBreakpoints: true, supportsLogPoints: true, + validatesLogMessage: true, functionBreakpointsVia: 'cdp', functionBreakpointsBindLate: true, honoursNoDebug: true, @@ -274,6 +279,7 @@ const PINNED: Record = { policyName: 'rust', supportsFunctionBreakpoints: true, supportsLogPoints: true, + validatesLogMessage: false, functionBreakpointsVia: undefined, functionBreakpointsBindLate: undefined, honoursNoDebug: undefined, @@ -295,6 +301,7 @@ const PINNED: Record = { policyName: 'go', supportsFunctionBreakpoints: true, supportsLogPoints: true, + validatesLogMessage: false, functionBreakpointsVia: undefined, functionBreakpointsBindLate: undefined, honoursNoDebug: true, @@ -316,6 +323,7 @@ const PINNED: Record = { policyName: 'java', supportsFunctionBreakpoints: true, supportsLogPoints: false, + validatesLogMessage: false, functionBreakpointsVia: undefined, functionBreakpointsBindLate: true, honoursNoDebug: undefined, @@ -337,6 +345,7 @@ const PINNED: Record = { policyName: 'dotnet', supportsFunctionBreakpoints: true, supportsLogPoints: false, + validatesLogMessage: false, functionBreakpointsVia: undefined, functionBreakpointsBindLate: undefined, honoursNoDebug: undefined, @@ -358,6 +367,7 @@ const PINNED: Record = { policyName: 'cpp', supportsFunctionBreakpoints: true, supportsLogPoints: true, + validatesLogMessage: false, functionBreakpointsVia: undefined, functionBreakpointsBindLate: undefined, honoursNoDebug: true, @@ -379,6 +389,7 @@ const PINNED: Record = { policyName: 'cobol', supportsFunctionBreakpoints: true, supportsLogPoints: true, + validatesLogMessage: false, functionBreakpointsVia: undefined, functionBreakpointsBindLate: true, honoursNoDebug: true, @@ -400,6 +411,7 @@ const PINNED: Record = { policyName: 'dart', supportsFunctionBreakpoints: false, supportsLogPoints: true, + validatesLogMessage: false, functionBreakpointsVia: undefined, functionBreakpointsBindLate: undefined, honoursNoDebug: true, @@ -421,6 +433,7 @@ const PINNED: Record = { policyName: 'mock', supportsFunctionBreakpoints: true, supportsLogPoints: true, + validatesLogMessage: false, functionBreakpointsVia: undefined, functionBreakpointsBindLate: undefined, honoursNoDebug: undefined, @@ -584,6 +597,11 @@ describe.each(LANGUAGES)('AdapterPolicy contract — %s', (language) => { it('declares the pinned breakpoint capabilities', () => { expect(policy.supportsFunctionBreakpoints).toBe(pinned.supportsFunctionBreakpoints); expect(policy.supportsLogPoints).toBe(pinned.supportsLogPoints); + expect(typeof policy.validateLogMessage === 'function').toBe(pinned.validatesLogMessage); + if (policy.validateLogMessage) { + expect(policy.supportsLogPoints).toBe(true); + expect(policy.validateLogMessage('x={x}')).toBeUndefined(); + } }); it('pins whether a noDebug launch turns the debugger off', () => { diff --git a/tests/unit/shared/adapter-policy-python.test.ts b/tests/unit/shared/adapter-policy-python.test.ts index 7f227fe8f..7995e928b 100644 --- a/tests/unit/shared/adapter-policy-python.test.ts +++ b/tests/unit/shared/adapter-policy-python.test.ts @@ -89,6 +89,12 @@ describe('PythonAdapterPolicy', () => { expect(PythonAdapterPolicy.getAttachBehavior?.()).toEqual({ pauseAfterAttach: true }); }); + it('validates Python logMessage f-string forms up front and leaves condition untouched (issue #1334)', () => { + expect(PythonAdapterPolicy.validateLogMessage!('x={x}', 'x >=')).toBeUndefined(); + expect(PythonAdapterPolicy.validateLogMessage!('stale={entry!r}')).toContain('{repr(entry)}'); + expect(PythonAdapterPolicy.validateLogMessage!('{total:.2f}')).toContain("{format(total, '.2f')}"); + }); + describe('getAdapterSpawnConfig', () => { // scriptPath is required by AdapterSpawnPayload but never read by this // policy — the debuggee script reaches debugpy through the launch config. diff --git a/tests/unit/shared/python-logpoint.test.ts b/tests/unit/shared/python-logpoint.test.ts new file mode 100644 index 000000000..825f770be --- /dev/null +++ b/tests/unit/shared/python-logpoint.test.ts @@ -0,0 +1,180 @@ +import { describe, it, expect } from 'vitest'; +import { + extractPythonLogMessageGroups, + validatePythonLogMessage +} from '../../../packages/shared/src/utils/python-logpoint.js'; + +describe('extractPythonLogMessageGroups', () => { + it('extracts balanced brace groups with pydevd nested-brace rules', () => { + expect(extractPythonLogMessageGroups('x={x} stale={ entry!r }')).toEqual([ + { raw: 'x', expression: 'x' }, + { raw: ' entry!r ', expression: 'entry!r' } + ]); + expect(extractPythonLogMessageGroups('{{literal}}')).toEqual([ + { raw: '{literal}', expression: '{literal}' } + ]); + expect(extractPythonLogMessageGroups("{ {'k': total} }")).toEqual([ + { raw: " {'k': total} ", expression: "{'k': total}" } + ]); + }); + + it('drops empty and whitespace-only brace groups and ignores stray closing braces', () => { + expect(extractPythonLogMessageGroups('empty {} blank { } stray } ok={x}')).toEqual([ + { raw: 'x', expression: 'x' } + ]); + expect(extractPythonLogMessageGroups('plain message')).toEqual([]); + }); + + it('returns undefined when braces are unbalanced, matching pydevd whole-message fallback', () => { + expect(extractPythonLogMessageGroups('open {x!r')).toBeUndefined(); + expect(extractPythonLogMessageGroups('{x!r} and {unclosed')).toBeUndefined(); + }); +}); + +describe('validatePythonLogMessage', () => { + describe('debugpy proof table (issue #1334)', () => { + it.each([ + '{x}', + '{x != 1}', + '{items[1:3]}', + "{d['a:b']}", + '{(lambda v: v)(x)}', + '{{literal}}', + '{repr(x)}', + '{str(x)}', + '{ascii(x)}', + "{format(total, '.2f')}", + "{ {'k': total} }", + '{lambda v: v}', + '{y := 7}', + "{format(repr(x), '>10')}" + ])('accepts %s (no syntax error in debugpy)', (logMessage) => { + expect(validatePythonLogMessage(logMessage)).toBeUndefined(); + }); + + it('refuses top-level !r, !s and !a conversions with verbatim guidance and working replacements', () => { + expect(validatePythonLogMessage('stale={entry!r}')).toBe( + '{entry!r}: debugpy evaluates the text between braces as a Python expression, and !r is f-string syntax, not an expression; use {repr(entry)} instead.' + ); + expect(validatePythonLogMessage('{x!r}')).toBe( + '{x!r}: debugpy evaluates the text between braces as a Python expression, and !r is f-string syntax, not an expression; use {repr(x)} instead.' + ); + expect(validatePythonLogMessage('{x!s}')).toBe( + '{x!s}: debugpy evaluates the text between braces as a Python expression, and !s is f-string syntax, not an expression; use {str(x)} instead.' + ); + expect(validatePythonLogMessage('{x!a}')).toBe( + '{x!a}: debugpy evaluates the text between braces as a Python expression, and !a is f-string syntax, not an expression; use {ascii(x)} instead.' + ); + }); + + it('refuses top-level format specs with verbatim guidance and format() replacement', () => { + expect(validatePythonLogMessage('{total:.2f}')).toBe( + "{total:.2f}: debugpy evaluates the text between braces as a Python expression, and :.2f is f-string syntax, not an expression; use {format(total, '.2f')} instead." + ); + }); + + it('refuses combined top-level conversion and format spec with nested format(repr(...), ...)', () => { + expect(validatePythonLogMessage('{x!r:>10}')).toBe( + "{x!r:>10}: debugpy evaluates the text between braces as a Python expression, and !r:>10 is f-string syntax, not an expression; use {format(repr(x), '>10')} instead." + ); + }); + }); + + describe('top-level boundary cases', () => { + it.each([ + '{items[1:5:2]}', + '{matrix[1:3, 2:4]}', + '{(items[1:3])}', + "{d['a:b']}", + '{d["a:b"]}', + "{'''a:b!r'''}", + '{"""a:b:.2f"""}', + "{r'a:b!r'}", + "{b'a:b'}", + "{rb'a:b'}", + "{f'{total:.2f}'}", + '{f"{d["a:b"]}"}', + '{f"{{a:b}}"}', + '{f"{{{x}}}"}', + '{f"\\{x}"}', + '{f\'{x:"<4}\'}', + '{ {k: v for k, v in pairs} }', + '{lambda: 0}', + '{lambda a, b=1: a + b}', + '{lambda x: lambda y: x + y}', + '{lambda x=lambda a: a: x}', + '{fn if ready else lambda x: x}', + '{x:=1}', + '{x != "r"}', + '{a!=r}', + '{x # :.2f}', + '{x # !r}', + '{land!r}'.replace('!r', ''), + '{minor}' + ])('does not misclassify nested or non-format-spec constructs: %s', (logMessage) => { + expect(validatePythonLogMessage(logMessage)).toBeUndefined(); + }); + + it('catches top-level conversions and format specs after nested slices, dicts, lambdas, walrus and floats', () => { + expect(validatePythonLogMessage('{items[1:3]!r}')).toContain('use {repr(items[1:3])} instead.'); + expect(validatePythonLogMessage("{d['a:b']:.2f}")).toContain("use {format(d['a:b'], '.2f')} instead."); + expect(validatePythonLogMessage('{(lambda v: v)(total):.2f}')).toContain( + "use {format((lambda v: v)(total), '.2f')} instead." + ); + expect(validatePythonLogMessage('{(y := 3.5):.2f}')).toContain("use {format((y := 3.5), '.2f')} instead."); + expect(validatePythonLogMessage('{1.:.2f}')).toContain("use {format(1., '.2f')} instead."); + expect(validatePythonLogMessage('{land!r}')).toContain('use {repr(land)} instead.'); + expect(validatePythonLogMessage('{entrée!r}')).toContain('use {repr(entrée)} instead.'); + }); + + it('preserves caller spacing when quoting the offending group and trims the replacement operand', () => { + expect(validatePythonLogMessage('{ entry !r }')).toBe( + '{ entry !r }: debugpy evaluates the text between braces as a Python expression, and !r is f-string syntax, not an expression; use {repr(entry)} instead.' + ); + }); + + it('wraps unparenthesized top-level tuples so the suggested call takes one value argument', () => { + expect(validatePythonLogMessage('{a, b!r}')).toContain('use {repr((a, b))} instead.'); + expect(validatePythonLogMessage('{a, b:>10}')).toContain("use {format((a, b), '>10')} instead."); + // Function call commas are at depth 1, not top-level tuples. + expect(validatePythonLogMessage('{f(a, b)!r}')).toContain('use {repr(f(a, b))} instead.'); + }); + + it('quotes format specs containing colons, hashes, quotes, empty specs and nested dynamic fields', () => { + expect(validatePythonLogMessage('{dt:%Y-%m-%d %H:%M:%S}')).toContain( + "use {format(dt, '%Y-%m-%d %H:%M:%S')} instead." + ); + expect(validatePythonLogMessage('{n:#08x}')).toContain("use {format(n, '#08x')} instead."); + expect(validatePythonLogMessage("{x:'<10}")).toContain('use {format(x, "\'<10")} instead.'); + expect(validatePythonLogMessage('{x:"\'<10}')).toContain("use {format(x, '\"\\'<10')} instead."); + expect(validatePythonLogMessage('{total:}')).toBe( + "{total:}: debugpy evaluates the text between braces as a Python expression, and ':' is f-string syntax, not an expression; use {format(total, '')} instead." + ); + expect(validatePythonLogMessage('{total:.{prec}f}')).toContain( + "use {format(total, f'.{prec}f')} instead." + ); + }); + + it('reports the first invalid group in a multi-group message', () => { + expect(validatePythonLogMessage('ok={x} bad={entry!r} later={total:.2f}')).toContain('{entry!r}'); + }); + + it('accepts uncertain or malformed expressions rather than guessing a broken replacement', () => { + expect(validatePythonLogMessage('open {entry!r')).toBeUndefined(); + expect(validatePythonLogMessage('{(entry!r}')).toBeUndefined(); + expect(validatePythonLogMessage('{entry):.2f}')).toBeUndefined(); + expect(validatePythonLogMessage("{'unterminated:.2f}")).toBeUndefined(); + expect(validatePythonLogMessage('{!r}')).toBeUndefined(); + expect(validatePythonLogMessage('{:.2f}')).toBeUndefined(); + expect(validatePythonLogMessage('{entry=!r}')).toBeUndefined(); + expect(validatePythonLogMessage('{a + !r}')).toBeUndefined(); + expect(validatePythonLogMessage('{obj.:.2f}')).toBeUndefined(); + expect(validatePythonLogMessage('{if x: y}')).toBeUndefined(); + expect(validatePythonLogMessage('{x and:.2f}')).toBeUndefined(); + expect(validatePythonLogMessage('{lambda x!r}')).toBeUndefined(); + expect(validatePythonLogMessage('{a ! b!r}')).toBeUndefined(); + expect(validatePythonLogMessage('{a ! b:.2f}')).toBeUndefined(); + expect(validatePythonLogMessage('{x!repr}')).toBeUndefined(); + }); + }); +}); From b55acd783c66c4d2a9c3c98f6b2e8e6918dd26a4 Mon Sep 17 00:00:00 2001 From: JF Date: Sat, 28 Nov 2026 07:52:30 -0500 Subject: [PATCH 2/2] fix(python): the logpoint check is one small scanner, refuses the = debug form, and names the right replacement for a dict Review round on #1334. - The 540-line validator is replaced by one tokenizer of 361 lines that reads groups and f-string fields the same way. It gives the same answers on every message debugpy can evaluate (none of 780,357 generated messages that compile is refused) and drops the code the review showed had no effect. - `match` and `case` are ordinary names: `{match!r}` was accepted and logged a syntax error at every hit. - The f-string `=` form is refused with its replacement: `{x=}` becomes `x={repr(x)}`, `{total=:.2f}` becomes `total={format(total, '.2f')}`. - A top-level colon gets the advice that fits how it is written: a quoted key or several pairs is a dict and needs its own braces; nothing after the colon is a format spec; a space after it gets both forms, the format form first. - A group that does not parse alone ends the check: debugpy may read what follows differently, and a wrong refusal breaks a call that worked. - One refusal names up to three groups and counts the rest. - The unit test's tables are a live recording (debugpy 1.8.20, Python 3.13): 342 cases with what each replacement logged. The unit project executes every statement and branch of the file. Written by a Claude Opus worker (Anthropic), who had reviewed round 1 and measured the smaller scanner there; round 1 was a Gemini worker's. Fixes #1334. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_015BDrn82vMcRzWFDD9aUbZs --- changelog.d/1334.fixed.md | 2 +- docs/python/README.md | 4 +- .../src/interfaces/adapter-policy-python.ts | 6 +- .../shared/src/interfaces/adapter-policy.ts | 2 +- packages/shared/src/utils/python-logpoint.ts | 723 +++++-------- skills/debugging/references/python.md | 2 +- src/server.ts | 10 +- src/server/handlers/breakpoint-tools.ts | 3 +- .../python-logpoint-validation.test.ts | 132 ++- tests/fixtures/python/logpoint_values.py | 31 +- tests/unit/shared/python-logpoint.test.ts | 986 +++++++++++++++--- 11 files changed, 1186 insertions(+), 715 deletions(-) diff --git a/changelog.d/1334.fixed.md b/changelog.d/1334.fixed.md index 4104e1688..a68dc0d53 100644 --- a/changelog.d/1334.fixed.md +++ b/changelog.d/1334.fixed.md @@ -1 +1 @@ -**Python logpoints with f-string conversions or format specs are refused at `set_breakpoint` time with the expression form that works** — debugpy evaluates the text inside each `{...}` group of a `logMessage` as a Python expression at hit time rather than parsing an f-string field, so `{entry!r}`, `{x!s}`, `{x!a}` and `{total:.2f}` succeeded when set and logged `invalid syntax (, line 1)` (or `invalid decimal literal (, line 1)`) when hit; `PythonAdapterPolicy.validateLogMessage` now refuses top-level conversions and format specs up front and names the working replacement (`{repr(entry)}`, `{str(x)}`, `{ascii(x)}`, `{format(total, '.2f')}`) (#1334) +**A Python logpoint that cannot evaluate is refused at `set_breakpoint` time, with the form that works** — debugpy evaluates the text inside each `{...}` group of a `logMessage` as a Python expression at every hit, not as an f-string field, so `{entry!r}`, `{total:.2f}` and `{x=}` were accepted and then logged `invalid syntax (, line 1)` (or `invalid decimal literal (, line 1)`) at each hit. `set_breakpoint` now refuses a group whose top level holds an f-string conversion (`!r`, `!s`, `!a`), a format spec or the `=` debug form, and names the replacement: `{repr(entry)}`, `{format(total, '.2f')}`, `x={repr(x)}`. A group that reads as a dict with a quoted key or several pairs (`{"k": total}`) is told that a dict needs its own braces, `{ {"k": total} }`; a spec written straight after the colon (`{x:10}`) gets the format form only; an unquoted key with a space after the colon (`{k: v}`) gets both, format first. One refusal names up to three groups and counts the rest. Not caught, so debugpy still logs the syntax error at the hit: a brace inside a string literal, which splits the group; a comment; a conversion or spec inside brackets (`{str(x!r)}`); `{x:=^10}`, which reads as an assignment; and any group after one that does not parse on its own, since debugpy joins the groups into one expression (#1334) diff --git a/docs/python/README.md b/docs/python/README.md index 3f77ad4d5..6c9544bfe 100644 --- a/docs/python/README.md +++ b/docs/python/README.md @@ -63,7 +63,9 @@ set_breakpoint { "sessionId": "...", "file": "/abs/path/script.py", "line": 15, set_breakpoint { "sessionId": "...", "file": "/abs/path/script.py", "line": 15, "logMessage": "x={x} y={y}" } ``` -A logpoint never pauses: it interpolates the `{expressions}` and writes the line to `get_output` while the program keeps running. The braces take Python expressions rather than f-string fields — write `{repr(x)}` or `{format(total, '.2f')}`, not `{x!r}` or `{total:.2f}` (refused when the breakpoint is set). Each hit does cost time, however — measured at 24.7 µs per hit on Python 3.13 + debugpy (`sys.monitoring`, 2.5% of a core at 1,000 hits/s), and placing a logpoint anywhere in a function slows that whole function by 58× — so keep logpoints off tight loops. When hits outrun debugpy's delivery rate (measured at 3,200–4,400 lines/s during a run and about 6,000 lines/s draining afterward), lines still queued when the program exits are lost and the session's end answer does not report the loss (issue #1265). See [Logpoints](../tool-reference.md#logpoints) for measurement conditions and what was not measured. +A logpoint never pauses: it interpolates the `{expressions}` and writes the line to `get_output` while the program keeps running. Each hit does cost time, however — measured at 24.7 µs per hit on Python 3.13 + debugpy (`sys.monitoring`, 2.5% of a core at 1,000 hits/s), and placing a logpoint anywhere in a function slows that whole function by 58× — so keep logpoints off tight loops. When hits outrun debugpy's delivery rate (measured at 3,200–4,400 lines/s during a run and about 6,000 lines/s draining afterward), lines still queued when the program exits are lost and the session's end answer does not report the loss (issue #1265). See [Logpoints](../tool-reference.md#logpoints) for measurement conditions and what was not measured. + +The braces take Python expressions, not f-string fields: debugpy evaluates each group at every hit. `set_breakpoint` therefore refuses a group whose top level holds an f-string conversion, a format spec or the `=` form, and names the form that works: `{x!r}` → `{repr(x)}`, `{total:.2f}` → `{format(total, '.2f')}`, `{x=}` → `x={repr(x)}`. A dict needs its own braces: `{ {"k": total} }`. Not caught, so debugpy logs a syntax error at each hit instead: a brace inside a string literal (debugpy splits the group there), a comment, a conversion or spec inside brackets (`{str(x!r)}`), `{x:=^10}` (read as an assignment), and any group after one that does not parse on its own. ### 3. Start Debugging diff --git a/packages/shared/src/interfaces/adapter-policy-python.ts b/packages/shared/src/interfaces/adapter-policy-python.ts index f85096986..555b36997 100644 --- a/packages/shared/src/interfaces/adapter-policy-python.ts +++ b/packages/shared/src/interfaces/adapter-policy-python.ts @@ -99,9 +99,9 @@ export const PythonAdapterPolicy = { // correctly, sends no `initialized`: the worker does not wait for one (#746). honoursNoDebug: true, supportsLogPoints: true, - // debugpy splices each `{...}` group into `'...' % (expr,)` and eval()s it at - // hit time, so f-string conversions (`{entry!r}`) and format specs - // (`{total:.2f}`) log `invalid syntax` only when hit (issue #1334). + // debugpy joins every `{...}` group into one `'...' % (g1, g2, ...,)` and + // eval()s it at each hit, so an f-string conversion (`{entry!r}`), format spec + // (`{total:.2f}`) or `=` (`{x=}`) logs `invalid syntax` only when hit (issue #1334). validateLogMessage: (logMessage: string, _condition?: string): string | undefined => validatePythonLogMessage(logMessage), supportsFunctionBreakpoints: true, supportsReverseStartDebugging: false, diff --git a/packages/shared/src/interfaces/adapter-policy.ts b/packages/shared/src/interfaces/adapter-policy.ts index bd1848e19..d3ebb7546 100644 --- a/packages/shared/src/interfaces/adapter-policy.ts +++ b/packages/shared/src/interfaces/adapter-policy.ts @@ -493,7 +493,7 @@ export interface AdapterPolicy { * Up-front check of a logMessage (and its optional condition) for a policy * that compiles logpoints itself (issue #853) or rejects forms its engine * evaluates as syntax errors only when the line is hit (Python f-string - * conversions and format specs, issue #1334): the returned text refuses + * conversions, format specs and the `=` form, issue #1334): the returned text refuses * set_breakpoint the way an expectedContent mismatch does, instead of the * adapter reporting the syntax error only in its output stream. Undefined * means the message is acceptable (or the policy does not pre-validate). diff --git a/packages/shared/src/utils/python-logpoint.ts b/packages/shared/src/utils/python-logpoint.ts index 858390261..1482c82f5 100644 --- a/packages/shared/src/utils/python-logpoint.ts +++ b/packages/shared/src/utils/python-logpoint.ts @@ -1,41 +1,42 @@ /** * Up-front validation of Python (debugpy / pydevd) logpoint messages (issue #1334). * - * pydevd (`_pydevd_bundle/pydevd_utils.py`, `_extract_expression_list` and - * `convert_dap_log_message_to_expression`) scans a DAP `logMessage` character by - * character: each `{...}` group is extracted by counting nested `{` and `}` - * (without string-literal awareness and without `{{` / `}}` brace escapes; empty - * groups are dropped, and unbalanced braces replace the whole message with - * `'Unbalanced braces in: ...'`), stripped of outer whitespace, and spliced into - * `repr(fmt) + " % (" + ", ".join(vars) + ",)"`. At hit time `pydevd.py`'s - * `handle_breakpoint_expression` calls `eval(...)` on that string and catches - * any exception as `str(exc)`, so a `SyntaxError` is only surfaced when the - * line runs (`invalid syntax (, line 1)` or - * `invalid decimal literal (, line 1)`). + * pydevd (`_pydevd_bundle/pydevd_utils.py`, `convert_dap_log_message_to_expression`) + * splits a DAP `logMessage` at its `{...}` groups by counting braces, with no + * string awareness and no `{{` escape (an unbalanced message logs + * `Unbalanced braces in: ...`), strips each group, and joins them all into one + * expression, `'' % (g1, g2, ...,)`, which `pydevd.py` + * `handle_breakpoint_expression` eval()s at every hit, logging `str(exc)` when it + * fails. A group therefore takes a Python expression, not an f-string field: a + * conversion (`{x!r}`), a format spec (`{total:.2f}`) or the `=` debug form + * (`{x=}`) at a group's top level logs `invalid syntax` at every hit. * - * Callers frequently write f-string field suffixes inside logpoint braces — - * conversions (`{entry!r}`, `{x!s}`, `{x!a}`) and format specs (`{total:.2f}`). - * Neither is valid in a Python expression, so every such group is certain to - * fail when hit. This validator refuses only those top-level forms when the - * breakpoint is set and names the expression form that works. + * This validator refuses those forms when the breakpoint is set and names the + * form that works. It refuses nothing that evaluates: because the groups are + * joined, a group that does not parse on its own (an unterminated string, an + * open bracket, a lambda without its colon, a comment) may be continued by the + * next one, so checking stops at the first such group. Left to debugpy: groups + * a brace inside a string literal splits (pydevd counts that brace), comments, + * a conversion or spec inside brackets, and `{x:=^10}` (read as a walrus). */ -const CONVERSION_FN = { - r: 'repr', - s: 'str', - a: 'ascii' -} as const; +const CONVERSION_FN = { r: 'repr', s: 'str', a: 'ascii' } as const; +type Conversion = keyof typeof CONVERSION_FN; -type FStringConversion = keyof typeof CONVERSION_FN; - -const IDENT_START_RE = /[\p{ID_Start}_]/u; -const IDENT_CONTINUE_RE = /[\p{ID_Continue}]/u; -const STRING_PREFIX_RE = /^(?:[rRuUbBfFtT]|[rR][bBfFtT]|[bBfFtT][rR])$/; -const INTERPOLATED_PREFIX_RE = /[fFtT]/; -const STATEMENT_HEADER_RE = /^(?:if|elif|else|for|while|with|try|except|finally|def|class|match|case)\b/; +const STRING_PREFIX_RE = /^(?:[rbft]|r[bft]|[bft]r)$/i; +const WORD_CHAR_RE = /\w/; +// An operand the replacement can wrap. `match` and `case` are soft keywords: +// in an expression they are names. +const STATEMENT_HEADER_RE = /^(?:if|elif|else|for|while|with|try|except|finally|def|class)\b/; const DANGLING_OPERATOR_RE = /[+\-*/%=<>&|^~@]$/; const TRAILING_KEYWORD_RE = /(?:^|[^.\p{ID_Continue}])(?:and|or|not|in|is|if|else|lambda|for|await|return|import|from|raise|del|pass|break|continue|assert|global|nonlocal)$/u; +const NUMBER_TOKEN_RE = /^(?:0[xob][\da-f_]+|\d[\d_]*(?:e[+-]?\d*)?j?)$/i; +// How a dict key or value can begin (a spec such as `.2f` or `>10` cannot). +const EXPRESSION_START_RE = /^(?:[\p{ID_Start}_\d'"([{~+-]|\.\.\.|\.\d)/u; +// A char that forms one token with a following `=` (`==`, `<=`, `:=`, `+=`, ...). +const COMPOUND_BEFORE_EQUALS = '=!<>:+-*/%&|^@~'; +const MAX_NAMED_GROUPS = 3; export interface PythonLogMessageGroup { /** Exact substring between the outer `{` and `}`, as written by the caller. */ @@ -45,496 +46,316 @@ export interface PythonLogMessageGroup { } /** - * Extract `{...}` groups using pydevd's exact nested-brace rule + * Extract `{...}` groups with pydevd's nested-brace rule * (`_extract_variable_nested_braces` / `_extract_expression_list`). Returns * `undefined` when braces are unbalanced, matching pydevd's whole-message - * `SyntaxError` fallback. + * fallback; drops empty groups as pydevd does. */ export function extractPythonLogMessageGroups(logMessage: string): PythonLogMessageGroup[] | undefined { const groups: PythonLogMessageGroup[] = []; - let i = 0; - while (i < logMessage.length) { - if (logMessage[i] !== '{') { - i += 1; - continue; - } + for (let i = 0; i < logMessage.length; i++) { + if (logMessage[i] !== '{') continue; let level = 0; - const start = i + 1; - i += 1; - while (i < logMessage.length) { - const ch = logMessage[i]; - if (ch === '{') { - level += 1; - } else if (ch === '}') { - level -= 1; - if (level === -1) { - break; - } - } - i += 1; - } - if (level !== -1) { - return undefined; + const start = ++i; + for (; i < logMessage.length; i++) { + if (logMessage[i] === '{') level++; + else if (logMessage[i] === '}' && --level === -1) break; } + if (level !== -1) return undefined; const raw = logMessage.slice(start, i); - const expression = raw.trim(); - if (expression.length > 0) { - groups.push({ raw, expression }); - } - i += 1; + if (raw.trim()) groups.push({ raw, expression: raw.trim() }); } return groups; } -function isConversionChar(ch: string | undefined): ch is FStringConversion { - return ch === 'r' || ch === 's' || ch === 'a'; -} - -function isIdentifierStartAt(src: string, index: number): boolean { - if (index >= src.length) { - return false; - } - const ch = String.fromCodePoint(src.codePointAt(index)!); - return IDENT_START_RE.test(ch); -} - -function readIdentifierEnd(src: string, start: number): number { - let i = start; - while (i < src.length) { - const ch = String.fromCodePoint(src.codePointAt(i)!); - if (!IDENT_CONTINUE_RE.test(ch)) { - break; - } - i += ch.length; - } - return i; -} - -function matchingOpen(closer: ')' | ']' | '}'): '(' | '[' | '{' { - if (closer === ')') return '('; - if (closer === ']') return '['; - return '{'; -} - -/** - * Index past the closing quote of a Python string literal starting at - * `quoteStart`, or `-1` when unterminated. Supports single/double and - * triple-quoted strings plus PEP 701 nested f-string / t-string fields. - */ -function skipPythonString(src: string, quoteStart: number, hasInterpolation: boolean): number { - const quoteChar = src[quoteStart]; - const triple = src[quoteStart + 1] === quoteChar && src[quoteStart + 2] === quoteChar; - let i = quoteStart + (triple ? 3 : 1); - while (i < src.length) { - const ch = src[i]; - if (ch === '\\') { - // In Python f-strings `\` does not escape `{` or `}`, so `f"\{x}"` still - // opens a replacement field at `{`. - if (hasInterpolation && (src[i + 1] === '{' || src[i + 1] === '}')) { - i += 1; - continue; - } - i += 2; - if (i > src.length) { - return -1; - } +/** Index past the string literal whose opening quote is at `quote`, or -1. */ +function skipString(s: string, quote: number, interpolated: boolean): number { + const close = s.startsWith(s[quote].repeat(3), quote) ? s[quote].repeat(3) : s[quote]; + for (let i = quote + close.length; i < s.length;) { + const c = s[i]; + if (c === '\\') { + // In an f-string `\{` still opens a field. + i += interpolated && s[i + 1] === '{' ? 1 : 2; continue; } - if (!triple && (ch === '\n' || ch === '\r')) { - return -1; - } - if (!triple && ch === quoteChar) { - return i + 1; - } - if (triple && ch === quoteChar && src[i + 1] === quoteChar && src[i + 2] === quoteChar) { - return i + 3; - } - if (hasInterpolation) { - if (ch === '{') { - if (src[i + 1] === '{') { - i += 2; - continue; - } - const fieldEnd = skipInterpolatedField(src, i + 1); - if (fieldEnd < 0) { - return -1; - } - i = fieldEnd; + if (s.startsWith(close, i)) return i + close.length; + if (interpolated && c === '{') { + if (s[i + 1] === '{') { + i += 2; continue; } - if (ch === '}') { - if (src[i + 1] === '}') { - i += 2; - continue; - } - return -1; - } + i = scan(s, i + 1, 'field').end; + if (i < 0) return -1; + continue; } - i += 1; + i++; } return -1; } +type ScanMode = 'group' | 'field' | 'dict'; + +interface ScanResult { + /** -1 when the text does not parse on its own; in a field, the index past its `}`. */ + end: number; + /** Group mode: the first top-level colon that starts a format spec. */ + colon?: number; + /** Top-level `!` not part of `!=`. */ + bangs: number[]; + /** Top-level commas (in dict mode, not a lambda's parameter commas). */ + commas: number[]; + /** Dict mode: every top-level colon that is not a lambda's or a walrus. */ + colons: number[]; + /** Dict mode: the first top-level `for`. */ + forAt: number; +} + /** - * Index past the closing `}` of an f-string / t-string `{...}` replacement - * field starting right after `{`, or `-1` when malformed. + * Tokenize Python from `start`. A group scan stops at the first top-level colon + * that starts a format spec. A field scan (an f-string replacement field) ends + * past its closing `}`; a top-level colon there starts the spec, literal text + * with nested fields. A dict scan reads the whole text as a dict display body. */ -function skipInterpolatedField(src: string, start: number): number { - const stack: Array<'(' | '[' | '{'> = []; - let pendingLambdas = 0; - let prevWasDot = false; - let inFormatSpec = false; - let i = start; - - while (i < src.length) { - if (inFormatSpec) { - if (src[i] === '{') { - const nested = skipInterpolatedField(src, i + 1); - if (nested < 0) { - return -1; - } - i = nested; - continue; - } - if (src[i] === '}') { - return i + 1; - } - i += 1; +function scan(s: string, start: number, mode: ScanMode): ScanResult { + const result: ScanResult = { end: -1, bangs: [], commas: [], colons: [], forAt: -1 }; + const stack: string[] = []; + let lambdas = 0; + for (let i = start; i < s.length;) { + const c = s[i]; + if (c === '#') { + const newline = s.indexOf('\n', i); + if (newline < 0) return result; + i = newline + 1; continue; } - - const ch = src[i]; - if (ch === ' ' || ch === '\t' || ch === '\r' || ch === '\n') { - i += 1; + if (c === "'" || c === '"') { + i = skipString(s, i, false); + if (i < 0) return result; continue; } - if (ch === '#') { - const nl = src.indexOf('\n', i + 1); - if (nl < 0) { - return -1; + if (WORD_CHAR_RE.test(c)) { + let j = i; + while (j < s.length && WORD_CHAR_RE.test(s[j])) j++; + const word = s.slice(i, j); + if ((s[j] === "'" || s[j] === '"') && STRING_PREFIX_RE.test(word)) { + i = skipString(s, j, /[ft]/i.test(word)); + if (i < 0) return result; + continue; } - i = nl + 1; + if (mode === 'dict' && /\d/.test(c) && !isPythonNumber(s, i, word)) return result; + if (stack.length === 0 && mode !== 'field') { + if (word === 'lambda') lambdas++; + if (word === 'for' && result.forAt < 0) result.forAt = i; + } + i = j; continue; } - if (ch === "'" || ch === '"') { - const end = skipPythonString(src, i, false); - if (end < 0) { - return -1; - } - prevWasDot = false; - i = end; + if (c === '(' || c === '[' || c === '{') { + stack.push(c); + i++; continue; } - if (isIdentifierStartAt(src, i)) { - const identEnd = readIdentifierEnd(src, i); - const ident = src.slice(i, identEnd); - const next = src[identEnd]; - if ((next === "'" || next === '"') && STRING_PREFIX_RE.test(ident)) { - const end = skipPythonString(src, identEnd, INTERPOLATED_PREFIX_RE.test(ident)); - if (end < 0) { - return -1; - } - prevWasDot = false; - i = end; - continue; - } - if (stack.length === 0 && ident === 'lambda' && !prevWasDot) { - pendingLambdas += 1; - } - prevWasDot = false; - i = identEnd; + if (c === ')' || c === ']' || c === '}') { + if (stack.length === 0 && mode === 'field' && c === '}') return { ...result, end: i + 1 }; + if (stack.pop() !== '([{'[')]}'.indexOf(c)]) return result; + i++; continue; } - if (ch === '(' || ch === '[' || ch === '{') { - stack.push(ch); - prevWasDot = false; - i += 1; + if (c === '!' && s[i + 1] === '=') { + i += 2; continue; } - if (ch === ')' || ch === ']' || ch === '}') { - if (ch === '}' && stack.length === 0) { - return i + 1; - } - if (stack.length === 0 || stack[stack.length - 1] !== matchingOpen(ch)) { - return -1; - } - stack.pop(); - prevWasDot = false; - i += 1; + // A dict body is plain Python: no `!` outside `!=`, every `.` an attribute, + // part of a number or of `...`. + if (mode === 'dict' && s.startsWith('...', i)) { + i += 3; continue; } - if (ch === ':') { - if (src[i + 1] === '=') { - prevWasDot = false; - i += 2; - continue; - } - if (stack.length === 0) { - if (pendingLambdas > 0) { - pendingLambdas -= 1; - prevWasDot = false; - i += 1; + if (mode === 'dict' && (c === '!' || (c === '.' && !isPythonDot(s, i)))) return result; + if (stack.length === 0) { + if (c === '!') result.bangs.push(i); + if (c === ',' && (mode !== 'dict' || lambdas === 0)) result.commas.push(i); + if (c === ':') { + if (mode !== 'field' && s[i + 1] === '=') { + // A walrus: fine in a group, not unparenthesized in a dict key or value. + if (mode === 'dict') return result; + i += 2; continue; } - inFormatSpec = true; - i += 1; - continue; - } - prevWasDot = false; - i += 1; - continue; - } - if (ch === '.') { - if (src[i + 1] === '.' && src[i + 2] === '.') { - prevWasDot = false; - i += 3; - continue; + if (lambdas > 0) { + lambdas--; + } else if (mode === 'group') { + return { ...result, end: s.length, colon: i }; + } else if (mode === 'dict') { + result.colons.push(i); + } else { + // A spec that runs to the end leaves `end` at the text's length, which + // every caller reads as an unterminated string. + for (i++; i < s.length;) { + if (s[i] === '}') return { ...result, end: i + 1 }; + if (s[i] === '{') { + i = scan(s, i + 1, 'field').end; + if (i < 0) return result; + continue; + } + i++; + } + } } - prevWasDot = true; - i += 1; - continue; } - prevWasDot = false; - i += 1; + i++; } + if (stack.length > 0 || lambdas > 0) return result; + return { ...result, end: s.length }; +} - return -1; +/** True when `word`, at `start`, is a Python number token (`.` splits a float into two). */ +function isPythonNumber(s: string, start: number, word: string): boolean { + if (!NUMBER_TOKEN_RE.test(word)) return false; + // `08` is no integer, though `08.5`, `08e1` and `.08` are numbers. + return !(/^0[\d_]*[1-9][\d_]*$/.test(word) && s[start - 1] !== '.' && s[start + word.length] !== '.'); } -function isPlausibleOperand(expr: string): boolean { - if (expr.length === 0) { - return false; - } - if (STATEMENT_HEADER_RE.test(expr)) { - return false; - } - if (DANGLING_OPERATOR_RE.test(expr)) { - return false; - } - if (expr.endsWith('.') && !expr.endsWith('...') && !(expr.length >= 2 && /\d$/.test(expr.slice(0, -1)))) { - return false; - } - if (TRAILING_KEYWORD_RE.test(expr)) { - return false; - } - return true; +/** True when the `.` at `i` is the point of a number or an attribute access. */ +function isPythonDot(s: string, i: number): boolean { + const left = s.slice(0, i); + const right = s.slice(i + 1); + // Right after a decimal integer it is the number's point: `1.5`, `1.`, `1.e3`, `1.j`, not `1.real`. + if (/(?:^|[^\w.])\d[\d_]*$/.test(left)) return !/^[\p{ID_Start}_]/u.test(right) || /^[ej]/i.test(right); + // After an operand (`1.5`, `2j`, `1.` included) it is an attribute: a name follows (`x . y`, `1 .real`). + if (/(?:[\w)\]}'"]|\d\.)\s*$/.test(left)) return /^\s*[\p{ID_Start}_]/u.test(right); + // Elsewhere only a number can start with it: `.5`. + return /^\d/.test(right); } -function wrapForCallArg(expr: string, hasTopLevelComma: boolean): string { - return hasTopLevelComma ? `(${expr})` : expr; +function isPlausibleOperand(expr: string): boolean { + return ( + expr.length > 0 && + !STATEMENT_HEADER_RE.test(expr) && + !DANGLING_OPERATOR_RE.test(expr) && + !TRAILING_KEYWORD_RE.test(expr) && + !(expr.endsWith('.') && !expr.endsWith('...') && !/\d\.$/.test(expr)) + ); } -function formatPythonStringLiteral(value: string): string { - const escaped = value - .replace(/\\/g, '\\\\') - .replace(/\r/g, '\\r') - .replace(/\n/g, '\\n') - .replace(/\t/g, '\\t'); - if (value.includes("'") && !value.includes('"')) { - return `"${escaped}"`; - } - return `'${escaped.replace(/'/g, "\\'")}'`; +/** A Python string literal for `value`. */ +function pythonString(value: string): string { + const escaped = value.replace(/\\/g, '\\\\').replace(/\r/g, '\\r').replace(/\n/g, '\\n').replace(/\t/g, '\\t'); + return value.includes("'") && !value.includes('"') ? `"${escaped}"` : `'${escaped.replace(/'/g, "\\'")}'`; } -function formatSpecLiteral(spec: string): string { - const literal = formatPythonStringLiteral(spec); +/** The spec as a Python literal: an f-string when it holds nested fields. */ +function specLiteral(spec: string): string { + const literal = pythonString(spec); return spec.includes('{') && spec.includes('}') ? `f${literal}` : literal; } -function inspectPythonGroup(group: PythonLogMessageGroup): string | undefined { - const src = group.expression; - const stack: Array<'(' | '[' | '{'> = []; - let pendingLambdas = 0; - let prevWasDot = false; - let firstTopLevelComma = -1; - let lastTopLevelBang = -1; - let topLevelBangCount = 0; - let i = 0; +/** True when `expr` is one string literal, any prefix. */ +function isStringLiteral(expr: string): boolean { + const prefix = /^[a-zA-Z]{0,2}(?=['"])/.exec(expr)?.[0]; + return prefix !== undefined && skipString(expr, prefix.length, /[ft]/i.test(prefix)) === expr.length; +} - while (i < src.length) { - const ch = src[i]; - if (ch === ' ' || ch === '\t' || ch === '\r' || ch === '\n') { - i += 1; - continue; - } - if (ch === '#') { - const nl = src.indexOf('\n', i + 1); - if (nl < 0) { - i = src.length; - break; - } - i = nl + 1; - continue; - } - if (ch === "'" || ch === '"') { - const end = skipPythonString(src, i, false); - if (end < 0) { - return undefined; - } - prevWasDot = false; - i = end; - continue; - } - if (isIdentifierStartAt(src, i)) { - const identEnd = readIdentifierEnd(src, i); - const ident = src.slice(i, identEnd); - const next = src[identEnd]; - if ((next === "'" || next === '"') && STRING_PREFIX_RE.test(ident)) { - const end = skipPythonString(src, identEnd, INTERPOLATED_PREFIX_RE.test(ident)); - if (end < 0) { - return undefined; - } - prevWasDot = false; - i = end; - continue; - } - if (stack.length === 0 && ident === 'lambda' && !prevWasDot) { - pendingLambdas += 1; - } - prevWasDot = false; - i = identEnd; - continue; - } - if (ch === '(' || ch === '[' || ch === '{') { - stack.push(ch); - prevWasDot = false; - i += 1; - continue; - } - if (ch === ')' || ch === ']' || ch === '}') { - if (stack.length === 0 || stack[stack.length - 1] !== matchingOpen(ch)) { - return undefined; - } - stack.pop(); - prevWasDot = false; - i += 1; - continue; - } - if (ch === '!') { - if (src[i + 1] === '=') { - prevWasDot = false; - i += 2; - continue; - } - if (stack.length === 0) { - lastTopLevelBang = i; - topLevelBangCount += 1; - } - prevWasDot = false; - i += 1; - continue; - } - if (ch === ',' && stack.length === 0) { - if (firstTopLevelComma === -1) { - firstTopLevelComma = i; - } - prevWasDot = false; - i += 1; - continue; - } - if (ch === ':') { - if (src[i + 1] === '=') { - prevWasDot = false; - i += 2; - continue; - } - if (stack.length === 0) { - if (pendingLambdas > 0) { - pendingLambdas -= 1; - prevWasDot = false; - i += 1; - continue; - } - // First top-level non-lambda, non-walrus colon: everything after it is - // the format spec. Stop expression tokenizing here so format-spec fill - // characters (`'` in `{x:'<10}`, `#` in `{n:#08x}`) are not read as - // Python string quotes or comments. - const colonIndex = i; - const leftTrimEnd = src.slice(0, colonIndex).trimEnd(); - const spec = src.slice(colonIndex + 1); - const specLiteral = formatSpecLiteral(spec); +/** The dict scan of `s` when it reads as the body of a dict display (`k: v, ...`, `**m`, `k: v for ...`). */ +function dictBody(s: string): ScanResult | undefined { + const r = scan(s, 0, 'dict'); + if (r.end < 0) return undefined; + const operand = (text: string): boolean => EXPRESSION_START_RE.test(text) && isPlausibleOperand(text); + const pair = (from: number, to: number): boolean => { + const colons = r.colons.filter((c) => c > from && c < to); + if (colons.length === 0) return s.slice(from + 1, to).trim().startsWith('**'); + return ( + colons.length === 1 && + operand(s.slice(from + 1, colons[0]).trim()) && + operand(s.slice(colons[0] + 1, to).trim()) + ); + }; + if (r.forAt >= 0) return !r.commas.some((c) => c < r.forAt) && pair(-1, r.forAt) ? r : undefined; + const bounds = [-1, ...r.commas, s.length]; + if (s.slice(bounds[bounds.length - 2] + 1).trim() === '') bounds.pop(); + return bounds.slice(1).every((to, k) => pair(bounds[k], to)) ? r : undefined; +} - if ( - topLevelBangCount === 1 && - lastTopLevelBang === leftTrimEnd.length - 2 && - isConversionChar(leftTrimEnd[leftTrimEnd.length - 1]) - ) { - const conv = leftTrimEnd[leftTrimEnd.length - 1] as FStringConversion; - const baseRaw = leftTrimEnd.slice(0, lastTopLevelBang).trim(); - if (!isPlausibleOperand(baseRaw)) { - return undefined; - } - const hasComma = firstTopLevelComma !== -1 && firstTopLevelComma < lastTopLevelBang; - const converted = `${CONVERSION_FN[conv]}(${wrapForCallArg(baseRaw, hasComma)})`; - return `{${group.raw}}: debugpy evaluates the text between braces as a Python expression, and !${conv}:${spec} is f-string syntax, not an expression; use {format(${converted}, ${specLiteral})} instead.`; - } +function sentence(raw: string, bad: string, use: string): string { + return `{${raw}}: debugpy evaluates the text between braces as a Python expression, and ${bad} is f-string syntax, not an expression; use ${use} instead.`; +} - if (topLevelBangCount > 0) { - return undefined; - } - const baseRaw = leftTrimEnd.trim(); - if (!isPlausibleOperand(baseRaw)) { - return undefined; - } - const hasComma = firstTopLevelComma !== -1 && firstTopLevelComma < colonIndex; - const badSuffix = spec.length > 0 ? `:${spec}` : "':'"; - return `{${group.raw}}: debugpy evaluates the text between braces as a Python expression, and ${badSuffix} is f-string syntax, not an expression; use {format(${wrapForCallArg(baseRaw, hasComma)}, ${specLiteral})} instead.`; - } - prevWasDot = false; - i += 1; - continue; - } - if (ch === '.') { - if (src[i + 1] === '.' && src[i + 2] === '.') { - prevWasDot = false; - i += 3; - continue; - } - prevWasDot = true; - i += 1; - continue; - } - prevWasDot = false; - i += 1; - } +interface GroupVerdict { + /** The group does not parse on its own: the next group may continue it. */ + open: boolean; + problem?: string; +} + +function inspectGroup({ raw, expression: s }: PythonLogMessageGroup): GroupVerdict { + const r = scan(s, 0, 'group'); + if (r.end < 0) return { open: true }; + const hasSpec = r.colon !== undefined; + const spec = hasSpec ? s.slice(r.colon! + 1) : ''; + let head = (hasSpec ? s.slice(0, r.colon) : s).trimEnd(); - if (stack.length !== 0 || pendingLambdas !== 0) { - return undefined; + let conv: Conversion | undefined; + if (r.bangs.length > 0) { + const bang = r.bangs[0]; + const ch = head[head.length - 1]; + if (bang !== head.length - 2 || !(ch === 'r' || ch === 's' || ch === 'a')) return { open: false }; + conv = ch; + head = head.slice(0, bang).trimEnd(); } + // The `=` debug form: a lone `=` ends the expression. + const debug = head.endsWith('=') && !COMPOUND_BEFORE_EQUALS.includes(head[head.length - 2]); + if (!conv && !hasSpec && !debug) return { open: false }; + const base = (debug ? head.slice(0, -1) : head).trim(); + // The replacement wraps the operand: it must parse alone (trimming can strip the + // newline that ended a comment). + if (!isPlausibleOperand(base) || scan(base, 0, 'group').end < 0) return { open: false }; - if ( - topLevelBangCount === 1 && - lastTopLevelBang === src.length - 2 && - isConversionChar(src[src.length - 1]) - ) { - const conv = src[src.length - 1] as FStringConversion; - const baseRaw = src.slice(0, lastTopLevelBang).trim(); - if (!isPlausibleOperand(baseRaw)) { - return undefined; + const operand = r.commas.length > 0 ? `(${base})` : base; + const value = conv ? `${CONVERSION_FN[conv]}(${operand})` : debug && !hasSpec ? `repr(${operand})` : operand; + const call = hasSpec ? `format(${value}, ${specLiteral(spec)})` : value; + const suffix = `${conv ? `!${conv}` : ''}${hasSpec ? `:${spec}` : ''}`; + + if (debug) { + // The caller's own text through `=` and the spaces after it, as the f-string shows it. + const lead = raw.length - raw.trimStart().length; + let textEnd = lead + head.length; + while (/\s/.test(raw[textEnd] ?? '')) textEnd++; + const text = raw.slice(0, textEnd); + const shown = /[{}%]/.test(text) ? `{${pythonString(text)}}` : text; + return { open: false, problem: sentence(raw, `=${suffix}`, `${shown}{${call}}`) }; + } + // A group that also reads as a dict (a conversion never does): told apart by how + // each is written. A quoted key or several pairs is a dict; a spec follows the + // colon directly, a dict value after a space, so a space leaves both readings. + const dict = dictBody(s); + if (dict) { + const dictForm = `{ {${s}} }`; + if (isStringLiteral(base) || dict.commas.length > 0) { + return { + open: false, + problem: `{${raw}}: debugpy evaluates the text between braces as a Python expression, so a dict needs its own braces; use ${dictForm} instead.` + }; + } + if (/^\s/.test(spec)) { + return { open: false, problem: sentence(raw, `:${spec}`, `{${call}} for a format spec, or ${dictForm} for a dict,`) }; } - const hasComma = firstTopLevelComma !== -1 && firstTopLevelComma < lastTopLevelBang; - return `{${group.raw}}: debugpy evaluates the text between braces as a Python expression, and !${conv} is f-string syntax, not an expression; use {${CONVERSION_FN[conv]}(${wrapForCallArg(baseRaw, hasComma)})} instead.`; } - - return undefined; + return { open: false, problem: sentence(raw, suffix === ':' ? "':'" : suffix, `{${call}}`) }; } /** - * Return a refusal message naming the working expression form when a `{...}` - * group in a Python `logMessage` uses a top-level f-string conversion (`!r`, - * `!s`, `!a`) or format spec (`:spec`), or `undefined` when no group is - * certain to fail for that reason. + * Return a refusal naming each `{...}` group of a Python `logMessage` that is + * certain to log a syntax error (an f-string conversion, format spec or `=` at + * its top level) and the form that works, or `undefined` when none is. */ export function validatePythonLogMessage(logMessage: string): string | undefined { - const groups = extractPythonLogMessageGroups(logMessage); - if (!groups) { - return undefined; - } - for (const group of groups) { - const problem = inspectPythonGroup(group); - if (problem !== undefined) { - return problem; - } + const problems: string[] = []; + for (const group of extractPythonLogMessageGroups(logMessage) ?? []) { + const verdict = inspectGroup(group); + if (verdict.problem) problems.push(verdict.problem); + if (verdict.open) break; } - return undefined; + if (problems.length === 0) return undefined; + const more = problems.length - MAX_NAMED_GROUPS; + const named = problems.slice(0, MAX_NAMED_GROUPS).join(' '); + return more > 0 ? `${named} And ${more} more like ${more === 1 ? 'it' : 'these'}.` : named; } diff --git a/skills/debugging/references/python.md b/skills/debugging/references/python.md index de1fd4388..f63adbb89 100644 --- a/skills/debugging/references/python.md +++ b/skills/debugging/references/python.md @@ -67,7 +67,7 @@ Shorthand: `create_debug_session { "language": "python", "host": "127.0.0.1", "p - **Set breakpoints on executable lines** (assignments, calls, returns). Comments, blank lines, and bare `def`/`class` lines misbehave. - **evaluate_expression** runs in debugpy's `variables` (watch-style) context by default. Reads and arithmetic are reliable; whether mutations like `x = 5` take effect depends on debugpy — verify with a follow-up evaluate before relying on one. Collections are truncated at 300 items. - **Output capture works for Python** (`redirectOutput`): `print()` and stderr land in `get_output` entries, readable during and after the run until the session closes. -- Logpoints work: `set_breakpoint` with `logMessage: "x={x}"` logs interpolated values to `get_output` without pausing. Each `{...}` group takes a Python expression, not an f-string field — write `{repr(x)}` or `{format(total, '.2f')}`, not `{x!r}` or `{total:.2f}` (refused at `set_breakpoint` time). Each hit costs about 24.7 µs (2.5% of a core at 1,000 hits/s), and any logpoint in a function slows that whole function by 58× on Python 3.13 + debugpy (`sys.monitoring`) — keep logpoints off tight loops. When hits outrun debugpy's delivery rate (measured at 3,200–4,400 lines/s during a run, ~6,000 lines/s draining after), lines still queued at program exit are lost and the end answer does not say so (issue #1265). Full measurements: [docs/tool-reference.md#logpoints](https://github.com/debugmcp/mcp-debugger/blob/main/docs/tool-reference.md#logpoints). +- Logpoints work: `set_breakpoint` with `logMessage: "x={x}"` logs interpolated values to `get_output` without pausing. Each `{...}` group takes a Python expression, not an f-string field — write `{repr(x)}`, `{format(total, '.2f')}` and `x={repr(x)}`, not `{x!r}`, `{total:.2f}` or `{x=}`, and give a dict its own braces, `{ {"k": total} }` (`set_breakpoint` refuses those forms and names the replacement; a brace inside a string, a comment, a conversion inside brackets and `{x:=^10}` are not caught). Each hit costs about 24.7 µs (2.5% of a core at 1,000 hits/s), and any logpoint in a function slows that whole function by 58× on Python 3.13 + debugpy (`sys.monitoring`) — keep logpoints off tight loops. When hits outrun debugpy's delivery rate (measured at 3,200–4,400 lines/s during a run, ~6,000 lines/s draining after), lines still queued at program exit are lost and the end answer does not say so (issue #1265). Full measurements: [docs/tool-reference.md#logpoints](https://github.com/debugmcp/mcp-debugger/blob/main/docs/tool-reference.md#logpoints). - **Child processes are debug sessions by default.** debugpy's sub-process debugging is on: each Python child the program starts (`subprocess`, `multiprocessing`, pytest-xdist workers) becomes a child debug session — `list_debug_sessions` lists it with `parentSessionId`, it stops on this session's breakpoints, and `wait_for_stop` on this session reports the child's stop with `sessionId` naming the child (inspect and step with that id) and `children` listing the tree; a child can still be waited on by its own id. `dapLaunchArgs: { subProcess: false }` opts a launch out (the children run undebugged; the answer's warning says so); an attach target decides for itself (`python -m debugpy --listen … --configure-subProcess false`). `DEBUG_MCP_MAX_CHILD_SESSIONS=0` turns adoption off server-wide. ## Troubleshooting diff --git a/src/server.ts b/src/server.ts index de0ae36bf..acc91fd21 100644 --- a/src/server.ts +++ b/src/server.ts @@ -196,10 +196,12 @@ export class DebugMcpServer implements ToolContext { const liveCaps = session?.adapterCapabilities; const policy = this.sessionManager.getSessionPolicy(sessionId); const language = session?.language ?? policy.name; - // A policy that compiles logpoints itself (js-debug, issue #850) checks - // the message up front, so a syntax error is refused here — like an - // expectedContent mismatch — instead of surfacing only in the adapter's - // stderr as an unbound breakpoint (issue #853). + // A policy that can tell up front that a message will not evaluate refuses + // it here, like an expectedContent mismatch, instead of the adapter + // reporting the error only at run time: js-debug, which compiles logpoints + // itself (issues #850, #853), and Python, where debugpy evaluates each brace + // group as an expression, so an f-string conversion, format spec or `=` + // logs a syntax error at every hit (issue #1334). const compileCheck = (): void => { const problem = logMessage !== undefined ? policy.validateLogMessage?.(logMessage, condition) : undefined; if (problem) { diff --git a/src/server/handlers/breakpoint-tools.ts b/src/server/handlers/breakpoint-tools.ts index 4940cc6c9..a91070a42 100644 --- a/src/server/handlers/breakpoint-tools.ts +++ b/src/server/handlers/breakpoint-tools.ts @@ -167,7 +167,8 @@ async function setLineBreakpointBranch(ctx: ToolContext, args: WithSessionId): P try { // Logpoint gating (issue #235): hard error for known-unsupported // adapters; a warning when support is unknown pre-launch. A policy that - // compiles logpoints itself also refuses a malformed message here (#853). + // knows a message cannot evaluate also refuses it here: js-debug's + // compiled logpoints (#853), Python's f-string forms (#1334). const logPointGate = args.logMessage !== undefined ? ctx.validateLogPointSupport(args.sessionId, args.logMessage, args.condition) : {}; diff --git a/tests/adapters/python/integration/python-logpoint-validation.test.ts b/tests/adapters/python/integration/python-logpoint-validation.test.ts index bfa3f111d..766f57f5b 100644 --- a/tests/adapters/python/integration/python-logpoint-validation.test.ts +++ b/tests/adapters/python/integration/python-logpoint-validation.test.ts @@ -1,10 +1,13 @@ /** - * Real debugpy coverage for issue #1334: setting a Python logpoint whose brace - * group uses an f-string conversion (`{x!r}`) or format spec (`{total:.2f}`) - * is refused up front on a launched session with the expression form that - * works, and setting that replacement logs the evaluated value. + * Real debugpy coverage for issue #1334: on a launched Python session, set_breakpoint + * refuses a logpoint whose brace group holds an f-string conversion, format spec or + * `=` form, or a dict without its own braces, naming every bad group and the form that + * works; leaves no breakpoint behind; and each named replacement, set as a logpoint, + * logs what the caller meant. A group that parses only joined to the next one is + * accepted and evaluates. */ import { afterEach, describe, expect, it } from 'vitest'; +import fs from 'node:fs'; import path from 'node:path'; import { spawnSync } from 'node:child_process'; import { fileURLToPath } from 'node:url'; @@ -17,6 +20,14 @@ import { ensurePythonOnPath } from './env-utils.js'; const here = path.dirname(fileURLToPath(import.meta.url)); const FIXTURE = path.resolve(here, '../../../fixtures/python/logpoint_values.py'); +const PREAMBLE = 'debugpy evaluates the text between braces as a Python expression,'; + +/** The fixture line marked `# case: `. */ +function caseLine(name: string): number { + const index = fs.readFileSync(FIXTURE, 'utf8').split(/\r?\n/).findIndex((line) => line.endsWith(`# case: ${name}`)); + if (index < 0) throw new Error(`no "# case: ${name}" line in ${FIXTURE}`); + return index + 1; +} function hasDebugpy(): boolean { const env: Record = {}; @@ -40,20 +51,34 @@ function hasDebugpy(): boolean { return false; } -type BreakpointAnswer = ToolAnswer & { - breakpointId?: string; - verified?: boolean; - logMessage?: string; -}; - -type EndAnswer = ToolAnswer & { - pending?: boolean; - exitCode?: number; -}; - -type OutputAnswer = ToolAnswer & { - entries?: Array<{ seq: number; category: string; output: string }>; -}; +type BreakpointAnswer = ToolAnswer & { breakpointId?: string; verified?: boolean }; +type EndAnswer = ToolAnswer & { exitCode?: number }; +type OutputAnswer = ToolAnswer & { entries?: Array<{ seq: number; category: string; output: string }> }; + +const REFUSALS: ReadonlyArray = [ + ['{x!r}', `{x!r}: ${PREAMBLE} and !r is f-string syntax, not an expression; use {repr(x)} instead.`], + ['stale={entry=!r}', `{entry=!r}: ${PREAMBLE} and =!r is f-string syntax, not an expression; use entry={repr(entry)} instead.`], + ['{"k": total}', `{"k": total}: ${PREAMBLE} so a dict needs its own braces; use { {"k": total} } instead.`], + [ + '{x!r} {total:.2f}', + `{x!r}: ${PREAMBLE} and !r is f-string syntax, not an expression; use {repr(x)} instead. ` + + `{total:.2f}: ${PREAMBLE} and :.2f is f-string syntax, not an expression; use {format(total, '.2f')} instead.` + ] +]; + +/** The replacements the refusals name (and two accepted forms), with what debugpy logs. */ +const LOGPOINTS: ReadonlyArray = [ + ['repr', '{repr(x)}', "'café'"], + ['format', "{format(total, '.2f')}", '3.50'], + ['debug-conversion', 'stale=entry={repr(entry)}', "stale=entry='old'"], + ['debug-spec', "total={format(total, '.2f')}", 'total=3.50'], + ['debug', 'x={repr(x)}', "x='café'"], + ['debug-call', 'len(items)={repr(len(items))}', 'len(items)=4'], + ['dict', '{ {"k": total} }', "{'k': 3.5}"], + ['slice', '{items[1:3]}', '[20, 30]'], + // pydevd joins the groups into one tuple: `(x, lambda a, b: a,)`. + ['joined', '{x, lambda a}{b: a}', /^café at 0x[0-9A-Fa-f]+>$/] +]; describe.skipIf(!hasDebugpy())('Python logpoint validation against real debugpy (issue #1334) @requires-python', () => { let server: StdioClientHandle | undefined; @@ -63,7 +88,7 @@ describe.skipIf(!hasDebugpy())('Python logpoint validation against real debugpy server = undefined; }); - it('refuses {x!r} and {total:.2f} on a launched Python session with their replacements, then logs the values when the replacements are set', async () => { + it('refuses the f-string forms on a launched session, then logs what each named replacement means', async () => { const env: Record = {}; ensurePythonOnPath(env); server = await startStdioClient({ name: 'python-logpoint-validation', env }); @@ -76,61 +101,24 @@ describe.skipIf(!hasDebugpy())('Python logpoint validation against real debugpy expect(started.success, JSON.stringify(started)).toBe(true); expect(started.state, JSON.stringify(started)).toBe('paused'); - await expect( - server.client.callTool({ - name: 'set_breakpoint', - arguments: { - sessionId, - file: FIXTURE, - line: 11, - logMessage: '{x!r}' - } - }) - ).rejects.toThrow( - 'Invalid logpoint: {x!r}: debugpy evaluates the text between braces as a Python expression, and !r is f-string syntax, not an expression; use {repr(x)} instead.' - ); - - await expect( - server.client.callTool({ - name: 'set_breakpoint', - arguments: { - sessionId, - file: FIXTURE, - line: 15, - logMessage: '{total:.2f}' - } - }) - ).rejects.toThrow( - "Invalid logpoint: {total:.2f}: debugpy evaluates the text between braces as a Python expression, and :.2f is f-string syntax, not an expression; use {format(total, '.2f')} instead." - ); + for (const [logMessage, refusal] of REFUSALS) { + await expect( + server.client.callTool({ + name: 'set_breakpoint', + arguments: { sessionId, file: FIXTURE, line: caseLine('repr'), logMessage } + }) + ).rejects.toThrow(`Invalid logpoint: ${refusal}`); + } // No refused logpoint was stored on the session. const emptyList = await server.call('list_breakpoints'); expect(emptyList.count).toBe(0); - // Set the replacements named in the refusals, plus valid colon-bearing expressions. - const reprBp = await server.call('set_breakpoint', { - file: FIXTURE, - line: 11, - logMessage: '{repr(x)}' - }); - expect(reprBp.success, JSON.stringify(reprBp)).toBe(true); - expect(reprBp.verified, JSON.stringify(reprBp)).toBe(true); - - const formatBp = await server.call('set_breakpoint', { - file: FIXTURE, - line: 15, - logMessage: "{format(total, '.2f')}" - }); - expect(formatBp.success, JSON.stringify(formatBp)).toBe(true); - expect(formatBp.verified, JSON.stringify(formatBp)).toBe(true); - - const sliceBp = await server.call('set_breakpoint', { - file: FIXTURE, - line: 16, - logMessage: '{items[1:3]}' - }); - expect(sliceBp.success, JSON.stringify(sliceBp)).toBe(true); + for (const [caseName, logMessage] of LOGPOINTS) { + const bp = await server.call('set_breakpoint', { file: FIXTURE, line: caseLine(caseName), logMessage }); + expect(bp.success, JSON.stringify(bp)).toBe(true); + expect(bp.verified, JSON.stringify(bp)).toBe(true); + } const resumed = await server.call('continue_execution'); expect(resumed.success, JSON.stringify(resumed)).toBe(true); @@ -142,6 +130,10 @@ describe.skipIf(!hasDebugpy())('Python logpoint validation against real debugpy const output = await server.call('get_output', { since: 0 }); const lines = (output.entries ?? []).map((entry) => entry.output.trim()); - expect(lines, JSON.stringify(output)).toEqual(["'café'", '3.50', '[20, 30]']); + expect(lines.length, JSON.stringify(output)).toBe(LOGPOINTS.length); + LOGPOINTS.forEach(([caseName, , logged], k) => { + if (typeof logged === 'string') expect(lines[k], caseName).toBe(logged); + else expect(lines[k], caseName).toMatch(logged); + }); }, 60_000); }); diff --git a/tests/fixtures/python/logpoint_values.py b/tests/fixtures/python/logpoint_values.py index 348b192e8..d7c8b07bf 100644 --- a/tests/fixtures/python/logpoint_values.py +++ b/tests/fixtures/python/logpoint_values.py @@ -5,27 +5,18 @@ def run(): x = "café" total = 3.5 items = [10, 20, 30, 40] - d = {"a:b": "colon-key"} + entry = "old" step = 0 - step += 1 # case 1 - step += 1 # case 2 - step += 1 # case 3 - step += 1 # case 4 - step += 1 # case 5 - step += 1 # case 6 - step += 1 # case 7 - step += 1 # case 8 - step += 1 # case 9 - step += 1 # case 10 - step += 1 # case 11 - step += 1 # case 12 - step += 1 # case 13 - step += 1 # case 14 - step += 1 # case 15 - step += 1 # case 16 - step += 1 # case 17 - step += 1 # case 18 - step += 1 # case 19 + step += 1 # case: repr + step += 1 # case: format + step += 1 # case: debug-conversion + step += 1 # case: debug-spec + step += 1 # case: debug + step += 1 # case: debug-call + step += 1 # case: dict + step += 1 # case: slice + step += 1 # case: joined + # debugpy drops logpoint lines still queued when the program exits (#1265). time.sleep(0.05) return step diff --git a/tests/unit/shared/python-logpoint.test.ts b/tests/unit/shared/python-logpoint.test.ts index 825f770be..007d0c0fa 100644 --- a/tests/unit/shared/python-logpoint.test.ts +++ b/tests/unit/shared/python-logpoint.test.ts @@ -4,177 +4,839 @@ import { validatePythonLogMessage } from '../../../packages/shared/src/utils/python-logpoint.js'; -describe('extractPythonLogMessageGroups', () => { - it('extracts balanced brace groups with pydevd nested-brace rules', () => { - expect(extractPythonLogMessageGroups('x={x} stale={ entry!r }')).toEqual([ - { raw: 'x', expression: 'x' }, - { raw: ' entry!r ', expression: 'entry!r' } - ]); - expect(extractPythonLogMessageGroups('{{literal}}')).toEqual([ - { raw: '{literal}', expression: '{literal}' } - ]); - expect(extractPythonLogMessageGroups("{ {'k': total} }")).toEqual([ - { raw: " {'k': total} ", expression: "{'k': total}" } - ]); - }); +/** + * The validator's table (issue #1334), recorded 2026-11-28 with debugpy 1.8.20 on + * CPython 3.13.12 (Windows 11). Every message was set as a real logpoint through the + * built server, once with the validator off (`logged`: what debugpy wrote at the hit) + * and once with it on (each replacement's own `logged`). The debuggee's locals: + * + * x = 'café', total = 3.5, items = [10, 20, 30, 40], d = {'a:b': 'colon-key'}, + * entry = 'old', a = 1, b = 2, w = 10, wd = {'a': 8}, prec = 2, n = 255, + * dt = datetime(2026, 11, 28, 13, 45, 7), match = re.match('(a)b', 'ab'), case = 'C', + * k = 'kk', v = 'vv', j = 'jj', pairs = [('p', 1)], matrix[key] = 'M[]', + * fn = len, ready = True, i = 1, f = lambda *aa: aa, obj = object, entrée = 'é', + * land = 'L', minor = 3, literal = 5, y = 0, c = 7, q = 9, p = 8, matches = ['m'] + * + * A lambda's address is written 0x…. ACCEPTED rows evaluate (a value, a runtime error, + * or pydevd's own `Unbalanced braces` line); LEFT_TO_DEBUGPY rows cannot evaluate but are + * not certain to be an f-string mistake, or follow a group that does not parse alone; + * REFUSED rows log a syntax error at every hit. In a refusal, `…` stands for PREAMBLE. A + * replacement logged `null` is still refused: the refusal names three groups at most. + * `t'…'` strings need Python 3.14, so on 3.13 that replacement logs `invalid syntax`. + */ +interface Refused { + message: string; + logged: string; + refusal: string; + replacements: ReadonlyArray; +} - it('drops empty and whitespace-only brace groups and ignores stray closing braces', () => { - expect(extractPythonLogMessageGroups('empty {} blank { } stray } ok={x}')).toEqual([ - { raw: 'x', expression: 'x' } - ]); - expect(extractPythonLogMessageGroups('plain message')).toEqual([]); - }); - - it('returns undefined when braces are unbalanced, matching pydevd whole-message fallback', () => { - expect(extractPythonLogMessageGroups('open {x!r')).toBeUndefined(); - expect(extractPythonLogMessageGroups('{x!r} and {unclosed')).toBeUndefined(); - }); -}); +const PREAMBLE = 'debugpy evaluates the text between braces as a Python expression,'; +const SYNTAX_ERROR = /invalid syntax|invalid decimal literal|was never closed|unterminated string literal|does not match opening parenthesis|^f-string: |^leading zeros in decimal/; -describe('validatePythonLogMessage', () => { - describe('debugpy proof table (issue #1334)', () => { - it.each([ - '{x}', - '{x != 1}', - '{items[1:3]}', - "{d['a:b']}", - '{(lambda v: v)(x)}', - '{{literal}}', - '{repr(x)}', - '{str(x)}', - '{ascii(x)}', - "{format(total, '.2f')}", - "{ {'k': total} }", - '{lambda v: v}', - '{y := 7}', - "{format(repr(x), '>10')}" - ])('accepts %s (no syntax error in debugpy)', (logMessage) => { - expect(validatePythonLogMessage(logMessage)).toBeUndefined(); - }); +const ACCEPTED: ReadonlyArray = [ + // The issue and round 1 table + ["{x != 1}", "True"], + ["{items[1:3]}", "[20, 30]"], + ["{d['a:b']}", "colon-key"], + ["{(lambda v: v)(x)}", "café"], + ["{lambda v: v}", " at 0x…>"], + ["{y := 7}", "7"], + ["{ {'k': total} }", "{'k': 3.5}"], + ["{{literal}}", "{5}"], + // Strings holding !r, : and braces + ["{'a!r'}", "a!r"], + ["{\"x:y\"}", "x:y"], + ["{'x:.2f'}", "x:.2f"], + ["{'{x!r}'}", "{x!r}"], + ["{'{}'}", "{}"], + ["{'{:.2f}'.format(total)}", "3.50"], + ["{\"{}:{}\".format(a, b)}", "1:2"], + ["{'{'}", "Unbalanced braces in: {'{'}"], + ["{'{' + x!r}", "Unbalanced braces in: {'{' + x!r}"], + // f-strings inside a group: PEP 701 nesting, specs, escapes + ["{f\"{x!r}\"}", "'café'"], + ["{f'{x!r}'}", "'café'"], + ["{f'{total:.2f}'}", "3.50"], + ["{f\"{x:{w}}\"}", "café "], + ["{f\"{x!r:>{w}}\"}", " 'café'"], + ["{f\"{f'{x!r}'}\"}", "'café'"], + ["{f'{f\"{total:.2f}\"}'}", "3.50"], + ["{f\"{d[\"a:b\"]}\"}", "colon-key"], + ["{f\"{d[\"a:b\"]!r}\"}", "'colon-key'"], + ["{f\"{{a:b}}\"}", "{a:b}"], + ["{f\"{{{x}}}\"}", "{café}"], + ["{f\"\\{x}\"}", "\\café"], + ["{f'{x:\"<4}'}", "café"], + ["{f\"{x:'^9}\"}", "''café'''"], + ["{f\"{total!=1}\"}", "True"], + ["{f\"{x:=^9}\"}", "==café==="], + ["{f\"\\N{EM DASH}\"}", "—"], + ["{rf\"\\N{x}\"}", "\\Ncafé"], + ["{f\"{x=}\"}", "x='café'"], + ["{f\"{x=!r:>12}\"}", "x= 'café'"], + ["{f'{(lambda: 1)()}'}", "1"], + ["{f'a:b' + x}", "a:bcafé"], + ["{F'{x!r}' + 'c:d'}", "'café'c:d"], + ["{fr'{x!r}:'}", "'café':"], + ["{Rf'{x}:'}", "café:"], + // Slices + ["{items[::2]}", "[10, 30]"], + ["{items[1:5:2]}", "[20, 40]"], + ["{items[::-1]}", "[40, 30, 20, 10]"], + ["{items[(i := 1):]}", "[20, 30, 40]"], + // Dict and set displays, comprehensions + ["{ {k: v for k, v in d.items()} }", "{'a:b': 'colon-key'}"], + ["{ {k: len(v) for k, v in d.items()} }", "{'a:b': 9}"], + ["{dict((k, v) for k, v in d.items())}", "{'a:b': 'colon-key'}"], + ["{ {1, 2} }", "{1, 2}"], + ["{ {'a': {'b': 1}} }", "{'a': {'b': 1}}"], + ["{ {**d} }", "{'a:b': 'colon-key'}"], + // Conditional expressions + ["{x if total > 1 else 'no'}", "café"], + ["{'a:b' if x else 'c!r'}", "a:b"], + ["{(lambda: 1) if x else (lambda: 2)}", " at 0x…>"], + // Lambdas: defaults, signatures, colons + ["{(lambda v=1: v)()}", "1"], + ["{lambda v=1: v}", " at 0x…>"], + ["{(lambda v=d['a:b']: v)()}", "colon-key"], + ["{(lambda v=items[1:3]: v)()}", "[20, 30]"], + ["{lambda: 0}", " at 0x…>"], + ["{lambda x=lambda a: a: x}", " at 0x…>"], + ["{(lambda *, kk=1: kk)()}", "1"], + ["{(lambda *aa, **kw: aa)(1)}", "(1,)"], + ["{(lambda vv, /: vv)(1)}", "1"], + ["{(lambda vv: (ww := vv))(x)}", "café"], + ["{sorted(items, key=lambda vv: -vv)}", "[40, 30, 20, 10]"], + ["{lambda vv=1: vv, total}", "not all arguments converted during string formatting"], + ["{lambda vv=lambda: 1: vv}", " at 0x…>"], + ["{lambda vv={1: 2}: vv}", " at 0x…>"], + ["{lambda a, b=1: a + b}", " at 0x…>"], + ["{lambda x: lambda y: x + y}", " at 0x…>"], + ["{fn if ready else lambda q: q}", ""], + // != chains + ["{x != 1 != 2}", "True"], + ["{total!=1}", "True"], + ["{a!=b!=x}", "True"], + ["{a!=r}", "name 'r' is not defined"], + ["{x != 'r'}", "True"], + // Triple-quoted strings + ["{'''a:b!r'''}", "a:b!r"], + ["{\"\"\"x\"y:z\"\"\"}", "x\"y:z"], + ["{\"\"\"a:b:.2f\"\"\"}", "a:b:.2f"], + ["{'''it's:''' + x}", "it's:café"], + // String prefixes + ["{r'a:b!r'}", "a:b!r"], + ["{b'a:b'}", "b'a:b'"], + ["{rb'a:b'}", "b'a:b'"], + ["{Br'a:b'}", "b'a:b'"], + ["{u'a:b'}", "a:b"], + // Unicode and keyword-like names + ["{minor}", "3"], + // A group that parses only joined to the next one (pydevd joins all groups into one tuple) + ["{x, lambda a}{b: a}", "café at 0x…>"], + ["{x, total, \"a}{b:c}{\"}", "café3.5a, b:c, "], + ["{x, total, \"a}{b!r}{\"}", "café3.5a, b!r, "], + ["{a, d[1}{2:3]}", "(1, slice(2, 3, None))"], + ["{0, (lambda p}{q: p)(1, 2)}", "01"], + // Certain failures, each caught or left to debugpy + ["{x:=10}", "10"], + ["{a, b}", "not all arguments converted during string formatting"], + ["100% {x}", "unsupported format character '%' (0x25) at index 5"], + // Messages as agents write them + ["x={x}, items={items[:2]}", "x=café, items=[10, 20]"], + ["items[{i}]={items[i]}", "items[1]=20"], + // Round 1 unit-test strings + ["{x}", "café"], + ["{repr(x)}", "'café'"], + ["{str(x)}", "café"], + ["{ascii(x)}", "'caf\\xe9'"], + ["{format(total, '.2f')}", "3.50"], + ["{format(repr(x), '>10')}", " 'café'"], + ["{matrix[1:3, 2:4]}", "M[(slice(1, 3, None), slice(2, 4, None))]"], + ["{(items[1:3])}", "[20, 30]"], + ["{d[\"a:b\"]}", "colon-key"], + ["{ {k: v for k, v in pairs} }", "{'p': 1}"], + ["{x:=1}", "1"], + ["{land}", "L"], + ["open {entry!r", "Unbalanced braces in: open {entry!r"], + // Not the = form + ["{a == b}", "False"], + ["{a <= b}", "True"], + ["{a != b}", "True"], + ["{a >= b}", "False"], + ["{y := 5}", "5"], + ["{dict(a=1)}", "{'a': 1}"], + ["{sorted(items, reverse=True)}", "[40, 30, 20, 10]"], + // f-strings inside a group: PEP 701 nesting, specs, escapes + ["{fr\"{d[\"a:b\"]}\"}", "colon-key"], + ["{rf\"{d[\"a:b\"]}\"}", "colon-key"], +]; - it('refuses top-level !r, !s and !a conversions with verbatim guidance and working replacements', () => { - expect(validatePythonLogMessage('stale={entry!r}')).toBe( - '{entry!r}: debugpy evaluates the text between braces as a Python expression, and !r is f-string syntax, not an expression; use {repr(entry)} instead.' - ); - expect(validatePythonLogMessage('{x!r}')).toBe( - '{x!r}: debugpy evaluates the text between braces as a Python expression, and !r is f-string syntax, not an expression; use {repr(x)} instead.' - ); - expect(validatePythonLogMessage('{x!s}')).toBe( - '{x!s}: debugpy evaluates the text between braces as a Python expression, and !s is f-string syntax, not an expression; use {str(x)} instead.' - ); - expect(validatePythonLogMessage('{x!a}')).toBe( - '{x!a}: debugpy evaluates the text between braces as a Python expression, and !a is f-string syntax, not an expression; use {ascii(x)} instead.' - ); - }); +const LEFT_TO_DEBUGPY: ReadonlyArray = [ + // Strings holding !r, : and braces + ["{'}'}", "unterminated string literal (detected at line 1) (, line 1)"], + ["{'}' + x!r}", "unterminated string literal (detected at line 1) (, line 1)"], + ["{'{'} {x!r}}", "closing parenthesis '}' does not match opening parenthesis '(' (, line 1)"], + // Annotation-shaped text in a lambda + ["{(lambda v: int: v)}", "invalid syntax (, line 1)"], + // Comments + ["{x # :.2f}", "'(' was never closed (, line 1)"], + ["{x # !r}", "'(' was never closed (, line 1)"], + // Certain failures, each caught or left to debugpy + ["{x # note}", "'(' was never closed (, line 1)"], + ["{str(x!r)}", "invalid syntax (, line 1)"], + ["{x! r}", "invalid syntax (, line 1)"], + ["{x:=^10}", "invalid syntax (, line 1)"], + ["{x!r!s}", "invalid syntax (, line 1)"], + ["{x!}", "invalid syntax (, line 1)"], + ["{x!R}", "invalid syntax (, line 1)"], + ["{x.!r}", "invalid syntax (, line 1)"], + ["{!r}", "invalid syntax (, line 1)"], + ["{:.2f}", "invalid decimal literal (, line 1)"], + // Format specs and their replacements + ["{x # c\n!r}", "invalid syntax (, line 2)"], + // Round 1 unit-test strings + ["{(entry!r}", "invalid syntax (, line 1)"], + ["{entry):.2f}", "invalid decimal literal (, line 1)"], + ["{'unterminated:.2f}", "unterminated string literal (detected at line 1) (, line 1)"], + ["{a + !r}", "invalid syntax (, line 1)"], + ["{obj.:.2f}", "invalid decimal literal (, line 1)"], + ["{if x: y}", "invalid syntax (, line 1)"], + ["{x and:.2f}", "invalid decimal literal (, line 1)"], + ["{lambda x!r}", "invalid syntax (, line 1)"], + ["{a ! b!r}", "invalid syntax (, line 1)"], + ["{a ! b:.2f}", "invalid decimal literal (, line 1)"], + ["{x!repr}", "invalid syntax (, line 1)"], + // Not the = form + ["{x==}", "invalid syntax (, line 1)"], + ["{x+=}", "invalid syntax (, line 1)"], + ["{x:=}", "invalid syntax (, line 1)"], + ["{=}", "invalid syntax (, line 1)"], + // Several bad groups + ["{x, lambda a}{b: a} {x!r}", "invalid syntax (, line 1)"], + // Documented misses + ["{x # note!r}", "'(' was never closed (, line 1)"], + ["{t\"{d[\"a:b\"]}\"}", "invalid syntax. Perhaps you forgot a comma? (, line 1)"], + ["{f'{x)}'!r}", "f-string: unmatched ')' (, line 1)"], + ["{f\"{lambda: '}'+'{'}\"!r}", "f-string: lambda expressions are not allowed without parentheses (, line 1)"], + ["{(x]!r}", "closing parenthesis ']' does not match opening parenthesis '(' (, line 1)"], + ["{\"a\" + f\"{x)}\"!r}", "f-string: unmatched ')' (, line 1)"], + ["{f\"{x:{)}}\"!r}", "f-string: unmatched ')' (, line 1)"], + ["{f\"{x:{'}'}\"}", "closing parenthesis ')' does not match opening parenthesis '{' (, line 1)"], +]; - it('refuses top-level format specs with verbatim guidance and format() replacement', () => { - expect(validatePythonLogMessage('{total:.2f}')).toBe( - "{total:.2f}: debugpy evaluates the text between braces as a Python expression, and :.2f is f-string syntax, not an expression; use {format(total, '.2f')} instead." - ); - }); +const REFUSED: ReadonlyArray = [ + // The issue and round 1 table + { message: "stale={entry!r}", logged: "invalid syntax (, line 1)", + refusal: "{entry!r}: … and !r is f-string syntax, not an expression; use {repr(entry)} instead.", + replacements: [["stale={repr(entry)}", "stale='old'"]] }, + { message: "{x!r}", logged: "invalid syntax (, line 1)", + refusal: "{x!r}: … and !r is f-string syntax, not an expression; use {repr(x)} instead.", + replacements: [["{repr(x)}", "'café'"]] }, + { message: "{x!s}", logged: "invalid syntax (, line 1)", + refusal: "{x!s}: … and !s is f-string syntax, not an expression; use {str(x)} instead.", + replacements: [["{str(x)}", "café"]] }, + { message: "{x!a}", logged: "invalid syntax (, line 1)", + refusal: "{x!a}: … and !a is f-string syntax, not an expression; use {ascii(x)} instead.", + replacements: [["{ascii(x)}", "'caf\\xe9'"]] }, + { message: "{total:.2f}", logged: "invalid decimal literal (, line 1)", + refusal: "{total:.2f}: … and :.2f is f-string syntax, not an expression; use {format(total, '.2f')} instead.", + replacements: [["{format(total, '.2f')}", "3.50"]] }, + { message: "{x!r:>10}", logged: "invalid syntax (, line 1)", + refusal: "{x!r:>10}: … and !r:>10 is f-string syntax, not an expression; use {format(repr(x), '>10')} instead.", + replacements: [["{format(repr(x), '>10')}", " 'café'"]] }, + // Strings holding !r, : and braces + { message: "{'{}'.format(x)!r}", logged: "invalid syntax (, line 1)", + refusal: "{'{}'.format(x)!r}: … and !r is f-string syntax, not an expression; use {repr('{}'.format(x))} instead.", + replacements: [["{repr('{}'.format(x))}", "'café'"]] }, + // Slices + { message: "{items[1:3]!r}", logged: "invalid syntax (, line 1)", + refusal: "{items[1:3]!r}: … and !r is f-string syntax, not an expression; use {repr(items[1:3])} instead.", + replacements: [["{repr(items[1:3])}", "[20, 30]"]] }, + // Conditional expressions + { message: "{x if total else 0:>8}", logged: "invalid syntax (, line 1)", + refusal: "{x if total else 0:>8}: … and :>8 is f-string syntax, not an expression; use {format(x if total else 0, '>8')} instead.", + replacements: [["{format(x if total else 0, '>8')}", " café"]] }, + // Lambdas: defaults, signatures, colons + { message: "{(lambda v: v)(total):.2f}", logged: "invalid decimal literal (, line 1)", + refusal: "{(lambda v: v)(total):.2f}: … and :.2f is f-string syntax, not an expression; use {format((lambda v: v)(total), '.2f')} instead.", + replacements: [["{format((lambda v: v)(total), '.2f')}", "3.50"]] }, + { message: "{lambda: x!r}", logged: "invalid syntax (, line 1)", + refusal: "{lambda: x!r}: … and !r is f-string syntax, not an expression; use {repr(lambda: x)} instead.", + replacements: [["{repr(lambda: x)}", " at 0x…>"]] }, + // Unicode and keyword-like names + { message: "{entrée!r}", logged: "invalid syntax (, line 1)", + refusal: "{entrée!r}: … and !r is f-string syntax, not an expression; use {repr(entrée)} instead.", + replacements: [["{repr(entrée)}", "'é'"]] }, + { message: "{land!r}", logged: "invalid syntax (, line 1)", + refusal: "{land!r}: … and !r is f-string syntax, not an expression; use {repr(land)} instead.", + replacements: [["{repr(land)}", "'L'"]] }, + // Number literals + { message: "{1.:.2f}", logged: "invalid decimal literal (, line 1)", + refusal: "{1.:.2f}: … and :.2f is f-string syntax, not an expression; use {format(1., '.2f')} instead.", + replacements: [["{format(1., '.2f')}", "1.00"]] }, + { message: "{1_000:,}", logged: "invalid syntax (, line 1)", + refusal: "{1_000:,}: … and :, is f-string syntax, not an expression; use {format(1_000, ',')} instead.", + replacements: [["{format(1_000, ',')}", "1,000"]] }, + { message: "{0x1f:#x}", logged: "invalid syntax (, line 1)", + refusal: "{0x1f:#x}: … and :#x is f-string syntax, not an expression; use {format(0x1f, '#x')} instead.", + replacements: [["{format(0x1f, '#x')}", "0x1f"]] }, + { message: "{1e3:.1f}", logged: "invalid decimal literal (, line 1)", + refusal: "{1e3:.1f}: … and :.1f is f-string syntax, not an expression; use {format(1e3, '.1f')} instead.", + replacements: [["{format(1e3, '.1f')}", "1000.0"]] }, + // Certain failures, each caught or left to debugpy + { message: "{match!r}", logged: "invalid syntax (, line 1)", + refusal: "{match!r}: … and !r is f-string syntax, not an expression; use {repr(match)} instead.", + replacements: [["{repr(match)}", ""]] }, + { message: "{match.group(0)!r}", logged: "invalid syntax (, line 1)", + refusal: "{match.group(0)!r}: … and !r is f-string syntax, not an expression; use {repr(match.group(0))} instead.", + replacements: [["{repr(match.group(0))}", "'ab'"]] }, + { message: "{case:>5}", logged: "invalid syntax (, line 1)", + refusal: "{case:>5}: … and :>5 is f-string syntax, not an expression; use {format(case, '>5')} instead.", + replacements: [["{format(case, '>5')}", " C"]] }, + { message: "{x=}", logged: "invalid syntax (, line 1)", + refusal: "{x=}: … and = is f-string syntax, not an expression; use x={repr(x)} instead.", + replacements: [["x={repr(x)}", "x='café'"]] }, + { message: "{x=!r}", logged: "invalid syntax (, line 1)", + refusal: "{x=!r}: … and =!r is f-string syntax, not an expression; use x={repr(x)} instead.", + replacements: [["x={repr(x)}", "x='café'"]] }, + { message: "{total=:.2f}", logged: "invalid decimal literal (, line 1)", + refusal: "{total=:.2f}: … and =:.2f is f-string syntax, not an expression; use total={format(total, '.2f')} instead.", + replacements: [["total={format(total, '.2f')}", "total=3.50"]] }, + { message: "{len(items)=}", logged: "invalid syntax (, line 1)", + refusal: "{len(items)=}: … and = is f-string syntax, not an expression; use len(items)={repr(len(items))} instead.", + replacements: [["len(items)={repr(len(items))}", "len(items)=4"]] }, + { message: "{type!r}", logged: "invalid syntax (, line 1)", + refusal: "{type!r}: … and !r is f-string syntax, not an expression; use {repr(type)} instead.", + replacements: [["{repr(type)}", ""]] }, + // Format specs and their replacements + { message: "{\"k\": total}", logged: "invalid syntax (, line 1)", + refusal: "{\"k\": total}: … so a dict needs its own braces; use { {\"k\": total} } instead.", + replacements: [["{ {\"k\": total} }", "{'k': 3.5}"]] }, + { message: "{k: v}", logged: "invalid syntax (, line 1)", + refusal: "{k: v}: … and : v is f-string syntax, not an expression; use {format(k, ' v')} for a format spec, or { {k: v} } for a dict, instead.", + replacements: [["{format(k, ' v')}", "Unknown format code 'v' for object of type 'str'"], ["{ {k: v} }", "{'kk': 'vv'}"]] }, + { message: "{k: v for k, v in d.items()}", logged: "invalid syntax (, line 1)", + refusal: "{k: v for k, v in d.items()}: … so a dict needs its own braces; use { {k: v for k, v in d.items()} } instead.", + replacements: [["{ {k: v for k, v in d.items()} }", "{'a:b': 'colon-key'}"]] }, + { message: "{x:{wd['a']}}", logged: "invalid syntax (, line 1)", + refusal: "{x:{wd['a']}}: … and :{wd['a']} is f-string syntax, not an expression; use {format(x, f\"{wd['a']}\")} instead.", + replacements: [["{format(x, f\"{wd['a']}\")}", "café "]] }, + { message: "{x!r:}", logged: "invalid syntax (, line 1)", + refusal: "{x!r:}: … and !r: is f-string syntax, not an expression; use {format(repr(x), '')} instead.", + replacements: [["{format(repr(x), '')}", "'café'"]] }, + { message: "{total:}", logged: "invalid syntax (, line 1)", + refusal: "{total:}: … and ':' is f-string syntax, not an expression; use {format(total, '')} instead.", + replacements: [["{format(total, '')}", "3.5"]] }, + { message: "{total:.{prec}f}", logged: "invalid syntax (, line 1)", + refusal: "{total:.{prec}f}: … and :.{prec}f is f-string syntax, not an expression; use {format(total, f'.{prec}f')} instead.", + replacements: [["{format(total, f'.{prec}f')}", "3.50"]] }, + { message: "{x:>{w}}", logged: "invalid syntax (, line 1)", + refusal: "{x:>{w}}: … and :>{w} is f-string syntax, not an expression; use {format(x, f'>{w}')} instead.", + replacements: [["{format(x, f'>{w}')}", " café"]] }, + { message: "{x!r:>{w}}", logged: "invalid syntax (, line 1)", + refusal: "{x!r:>{w}}: … and !r:>{w} is f-string syntax, not an expression; use {format(repr(x), f'>{w}')} instead.", + replacements: [["{format(repr(x), f'>{w}')}", " 'café'"]] }, + { message: "{x:{w}}", logged: "invalid syntax (, line 1)", + refusal: "{x:{w}}: … and :{w} is f-string syntax, not an expression; use {format(x, f'{w}')} instead.", + replacements: [["{format(x, f'{w}')}", "café "]] }, + { message: "{dt:%H:%M}", logged: "invalid syntax (, line 1)", + refusal: "{dt:%H:%M}: … and :%H:%M is f-string syntax, not an expression; use {format(dt, '%H:%M')} instead.", + replacements: [["{format(dt, '%H:%M')}", "13:45"]] }, + { message: "{n:#08x}", logged: "invalid syntax (, line 1)", + refusal: "{n:#08x}: … and :#08x is f-string syntax, not an expression; use {format(n, '#08x')} instead.", + replacements: [["{format(n, '#08x')}", "0x0000ff"]] }, + { message: "{x:'<10}", logged: "unterminated string literal (detected at line 1) (, line 1)", + refusal: "{x:'<10}: … and :'<10 is f-string syntax, not an expression; use {format(x, \"'<10\")} instead.", + replacements: [["{format(x, \"'<10\")}", "café''''''"]] }, + { message: "{x:\"<10}", logged: "unterminated string literal (detected at line 1) (, line 1)", + refusal: "{x:\"<10}: … and :\"<10 is f-string syntax, not an expression; use {format(x, '\"<10')} instead.", + replacements: [["{format(x, '\"<10')}", "café\"\"\"\"\"\""]] }, + { message: "{x:!<10}", logged: "invalid syntax (, line 1)", + refusal: "{x:!<10}: … and :!<10 is f-string syntax, not an expression; use {format(x, '!<10')} instead.", + replacements: [["{format(x, '!<10')}", "café!!!!!!"]] }, + { message: "{a, b!r}", logged: "invalid syntax (, line 1)", + refusal: "{a, b!r}: … and !r is f-string syntax, not an expression; use {repr((a, b))} instead.", + replacements: [["{repr((a, b))}", "(1, 2)"]] }, + { message: "{a, b:>10}", logged: "invalid syntax (, line 1)", + refusal: "{a, b:>10}: … and :>10 is f-string syntax, not an expression; use {format((a, b), '>10')} instead.", + replacements: [["{format((a, b), '>10')}", "unsupported format string passed to tuple.__format__"]] }, + { message: "{f(a, b)!r}", logged: "invalid syntax (, line 1)", + refusal: "{f(a, b)!r}: … and !r is f-string syntax, not an expression; use {repr(f(a, b))} instead.", + replacements: [["{repr(f(a, b))}", "(1, 2)"]] }, + { message: "{x!a:>12}", logged: "invalid syntax (, line 1)", + refusal: "{x!a:>12}: … and !a:>12 is f-string syntax, not an expression; use {format(ascii(x), '>12')} instead.", + replacements: [["{format(ascii(x), '>12')}", " 'caf\\xe9'"]] }, + { message: "{x!s:^9}", logged: "invalid syntax (, line 1)", + refusal: "{x!s:^9}: … and !s:^9 is f-string syntax, not an expression; use {format(str(x), '^9')} instead.", + replacements: [["{format(str(x), '^9')}", " café "]] }, + { message: "{ entry !r }", logged: "invalid syntax (, line 1)", + refusal: "{ entry !r }: … and !r is f-string syntax, not an expression; use {repr(entry)} instead.", + replacements: [["{repr(entry)}", "'old'"]] }, + { message: "{d['a:b']:.2f}", logged: "invalid decimal literal (, line 1)", + refusal: "{d['a:b']:.2f}: … and :.2f is f-string syntax, not an expression; use {format(d['a:b'], '.2f')} instead.", + replacements: [["{format(d['a:b'], '.2f')}", "Unknown format code 'f' for object of type 'str'"]] }, + { message: "{(y := 3.5):.2f}", logged: "invalid decimal literal (, line 1)", + refusal: "{(y := 3.5):.2f}: … and :.2f is f-string syntax, not an expression; use {format((y := 3.5), '.2f')} instead.", + replacements: [["{format((y := 3.5), '.2f')}", "3.50"]] }, + { message: "{x:\"'<10}", logged: "unterminated string literal (detected at line 1) (, line 1)", + refusal: "{x:\"'<10}: … and :\"'<10 is f-string syntax, not an expression; use {format(x, '\"\\'<10')} instead.", + replacements: [["{format(x, '\"\\'<10')}", "Invalid format specifier '\"'<10' for object of type 'str'"]] }, + { message: "{x:{w}.{prec}}", logged: "invalid syntax (, line 1)", + refusal: "{x:{w}.{prec}}: … and :{w}.{prec} is f-string syntax, not an expression; use {format(x, f'{w}.{prec}')} instead.", + replacements: [["{format(x, f'{w}.{prec}')}", "ca "]] }, + { message: "{total:{wd['a']}.{prec}f}", logged: "invalid syntax (, line 1)", + refusal: "{total:{wd['a']}.{prec}f}: … and :{wd['a']}.{prec}f is f-string syntax, not an expression; use {format(total, f\"{wd['a']}.{prec}f\")} instead.", + replacements: [["{format(total, f\"{wd['a']}.{prec}f\")}", " 3.50"]] }, + { message: "{x:{d[\"a:b\"]!r}}", logged: "invalid syntax (, line 1)", + refusal: "{x:{d[\"a:b\"]!r}}: … and :{d[\"a:b\"]!r} is f-string syntax, not an expression; use {format(x, f'{d[\"a:b\"]!r}')} instead.", + replacements: [["{format(x, f'{d[\"a:b\"]!r}')}", "Invalid format specifier ''colon-key'' for object of type 'str'"]] }, + // Messages as agents write them + { message: "entry={entry!r} total={total:.2f}", logged: "invalid decimal literal (, line 1)", + refusal: "{entry!r}: … and !r is f-string syntax, not an expression; use {repr(entry)} instead. {total:.2f}: … and :.2f is f-string syntax, not an expression; use {format(total, '.2f')} instead.", + replacements: [["entry={repr(entry)} total={format(total, '.2f')}", "entry='old' total=3.50"]] }, + { message: "ok={x} bad={entry!r} later={total:.2f}", logged: "invalid decimal literal (, line 1)", + refusal: "{entry!r}: … and !r is f-string syntax, not an expression; use {repr(entry)} instead. {total:.2f}: … and :.2f is f-string syntax, not an expression; use {format(total, '.2f')} instead.", + replacements: [["ok={x} bad={repr(entry)} later={format(total, '.2f')}", "ok=café bad='old' later=3.50"]] }, + { message: "{n:,} rows", logged: "invalid syntax (, line 1)", + refusal: "{n:,}: … and :, is f-string syntax, not an expression; use {format(n, ',')} instead.", + replacements: [["{format(n, ',')} rows", "255 rows"]] }, + { message: "pct={total/7:.1%}", logged: "invalid syntax (, line 1)", + refusal: "{total/7:.1%}: … and :.1% is f-string syntax, not an expression; use {format(total/7, '.1%')} instead.", + replacements: [["pct={format(total/7, '.1%')}", "pct=50.0%"]] }, + { message: "{x!r} at {dt:%Y-%m-%d}", logged: "invalid syntax (, line 1)", + refusal: "{x!r}: … and !r is f-string syntax, not an expression; use {repr(x)} instead. {dt:%Y-%m-%d}: … and :%Y-%m-%d is f-string syntax, not an expression; use {format(dt, '%Y-%m-%d')} instead.", + replacements: [["{repr(x)} at {format(dt, '%Y-%m-%d')}", "'café' at 2026-11-28"]] }, + // Round 1 unit-test strings + { message: "{dt:%Y-%m-%d %H:%M:%S}", logged: "invalid syntax (, line 1)", + refusal: "{dt:%Y-%m-%d %H:%M:%S}: … and :%Y-%m-%d %H:%M:%S is f-string syntax, not an expression; use {format(dt, '%Y-%m-%d %H:%M:%S')} instead.", + replacements: [["{format(dt, '%Y-%m-%d %H:%M:%S')}", "2026-11-28 13:45:07"]] }, + { message: "{entry=!r}", logged: "invalid syntax (, line 1)", + refusal: "{entry=!r}: … and =!r is f-string syntax, not an expression; use entry={repr(entry)} instead.", + replacements: [["entry={repr(entry)}", "entry='old'"]] }, + // A refusable form after a string or f-string the scanner must skip + { message: "{f\"{x}\"!r}", logged: "invalid syntax (, line 1)", + refusal: "{f\"{x}\"!r}: … and !r is f-string syntax, not an expression; use {repr(f\"{x}\")} instead.", + replacements: [["{repr(f\"{x}\")}", "'café'"]] }, + { message: "{f\"{x:>{w}}\":^20}", logged: "invalid syntax (, line 1)", + refusal: "{f\"{x:>{w}}\":^20}: … and :^20 is f-string syntax, not an expression; use {format(f\"{x:>{w}}\", '^20')} instead.", + replacements: [["{format(f\"{x:>{w}}\", '^20')}", " café "]] }, + { message: "{f\"{d[\"a:b\"]}\"!r}", logged: "invalid syntax (, line 1)", + refusal: "{f\"{d[\"a:b\"]}\"!r}: … and !r is f-string syntax, not an expression; use {repr(f\"{d[\"a:b\"]}\")} instead.", + replacements: [["{repr(f\"{d[\"a:b\"]}\")}", "'colon-key'"]] }, + { message: "{f'{x # c\n}'!r}", logged: "invalid syntax (, line 2)", + refusal: "{f'{x # c\n}'!r}: … and !r is f-string syntax, not an expression; use {repr(f'{x # c\n}')} instead.", + replacements: [["{repr(f'{x # c\n}')}", "'café'"]] }, + { message: "{f\"{'a'}\"!r}", logged: "invalid syntax (, line 1)", + refusal: "{f\"{'a'}\"!r}: … and !r is f-string syntax, not an expression; use {repr(f\"{'a'}\")} instead.", + replacements: [["{repr(f\"{'a'}\")}", "'a'"]] }, + { message: "{rf'{x}'!r}", logged: "invalid syntax (, line 1)", + refusal: "{rf'{x}'!r}: … and !r is f-string syntax, not an expression; use {repr(rf'{x}')} instead.", + replacements: [["{repr(rf'{x}')}", "'café'"]] }, + { message: "{f\"{x=}\"!r}", logged: "invalid syntax (, line 1)", + refusal: "{f\"{x=}\"!r}: … and !r is f-string syntax, not an expression; use {repr(f\"{x=}\")} instead.", + replacements: [["{repr(f\"{x=}\")}", "\"x='café'\""]] }, + { message: "{f\"{ x }\"!r}", logged: "invalid syntax (, line 1)", + refusal: "{f\"{ x }\"!r}: … and !r is f-string syntax, not an expression; use {repr(f\"{ x }\")} instead.", + replacements: [["{repr(f\"{ x }\")}", "'café'"]] }, + { message: "{f\"{(lambda: 1)()}\"!r}", logged: "invalid syntax (, line 1)", + refusal: "{f\"{(lambda: 1)()}\"!r}: … and !r is f-string syntax, not an expression; use {repr(f\"{(lambda: 1)()}\")} instead.", + replacements: [["{repr(f\"{(lambda: 1)()}\")}", "'1'"]] }, + { message: "{f'''{x}'''!r}", logged: "invalid syntax (, line 1)", + refusal: "{f'''{x}'''!r}: … and !r is f-string syntax, not an expression; use {repr(f'''{x}''')} instead.", + replacements: [["{repr(f'''{x}''')}", "'café'"]] }, + { message: "{'a\\'b'!r}", logged: "invalid syntax (, line 1)", + refusal: "{'a\\'b'!r}: … and !r is f-string syntax, not an expression; use {repr('a\\'b')} instead.", + replacements: [["{repr('a\\'b')}", "\"a'b\""]] }, + { message: "{'''x'y'''!r}", logged: "invalid syntax (, line 1)", + refusal: "{'''x'y'''!r}: … and !r is f-string syntax, not an expression; use {repr('''x'y''')} instead.", + replacements: [["{repr('''x'y''')}", "\"x'y\""]] }, + { message: "{\"\"\"a\"b\"\"\"!r}", logged: "invalid syntax (, line 1)", + refusal: "{\"\"\"a\"b\"\"\"!r}: … and !r is f-string syntax, not an expression; use {repr(\"\"\"a\"b\"\"\")} instead.", + replacements: [["{repr(\"\"\"a\"b\"\"\")}", "'a\"b'"]] }, + { message: "{rb'a:b'!r}", logged: "invalid syntax (, line 1)", + refusal: "{rb'a:b'!r}: … and !r is f-string syntax, not an expression; use {repr(rb'a:b')} instead.", + replacements: [["{repr(rb'a:b')}", "b'a:b'"]] }, + { message: "{fr'{x}:'!r}", logged: "invalid syntax (, line 1)", + refusal: "{fr'{x}:'!r}: … and !r is f-string syntax, not an expression; use {repr(fr'{x}:')} instead.", + replacements: [["{repr(fr'{x}:')}", "'café:'"]] }, + { message: "{Rb'x'!r}", logged: "invalid syntax (, line 1)", + refusal: "{Rb'x'!r}: … and !r is f-string syntax, not an expression; use {repr(Rb'x')} instead.", + replacements: [["{repr(Rb'x')}", "b'x'"]] }, + { message: "{f\"{x!r:{w}}\"!r}", logged: "invalid syntax (, line 1)", + refusal: "{f\"{x!r:{w}}\"!r}: … and !r is f-string syntax, not an expression; use {repr(f\"{x!r:{w}}\")} instead.", + replacements: [["{repr(f\"{x!r:{w}}\")}", "\"'café' \""]] }, + { message: "{f\"{x:{w}.{prec}}\":>30}", logged: "invalid syntax (, line 1)", + refusal: "{f\"{x:{w}.{prec}}\":>30}: … and :>30 is f-string syntax, not an expression; use {format(f\"{x:{w}.{prec}}\", '>30')} instead.", + replacements: [["{format(f\"{x:{w}.{prec}}\", '>30')}", " ca "]] }, + { message: "{f\"{{a}}\"!r}", logged: "invalid syntax (, line 1)", + refusal: "{f\"{{a}}\"!r}: … and !r is f-string syntax, not an expression; use {repr(f\"{{a}}\")} instead.", + replacements: [["{repr(f\"{{a}}\")}", "'{a}'"]] }, + { message: "{f\"\\{x}\"!r}", logged: "invalid syntax (, line 1)", + refusal: "{f\"\\{x}\"!r}: … and !r is f-string syntax, not an expression; use {repr(f\"\\{x}\")} instead.", + replacements: [["{repr(f\"\\{x}\")}", "'\\\\café'"]] }, + { message: "{f\"{items[1:3]}\"!r}", logged: "invalid syntax (, line 1)", + refusal: "{f\"{items[1:3]}\"!r}: … and !r is f-string syntax, not an expression; use {repr(f\"{items[1:3]}\")} instead.", + replacements: [["{repr(f\"{items[1:3]}\")}", "'[20, 30]'"]] }, + { message: "{f'{x!r}' + 'c:d'!r}", logged: "invalid syntax (, line 1)", + refusal: "{f'{x!r}' + 'c:d'!r}: … and !r is f-string syntax, not an expression; use {repr(f'{x!r}' + 'c:d')} instead.", + replacements: [["{repr(f'{x!r}' + 'c:d')}", "\"'café'c:d\""]] }, + { message: "{f\"{x:=^9}\"!r}", logged: "invalid syntax (, line 1)", + refusal: "{f\"{x:=^9}\"!r}: … and !r is f-string syntax, not an expression; use {repr(f\"{x:=^9}\")} instead.", + replacements: [["{repr(f\"{x:=^9}\")}", "'==café==='"]] }, + { message: "{t'{x}'!r}", logged: "invalid syntax (, line 1)", + refusal: "{t'{x}'!r}: … and !r is f-string syntax, not an expression; use {repr(t'{x}')} instead.", + replacements: [["{repr(t'{x}')}", "invalid syntax (, line 1)"]] }, + { message: "{f\"{f'{x}'}\"!r}", logged: "invalid syntax (, line 1)", + refusal: "{f\"{f'{x}'}\"!r}: … and !r is f-string syntax, not an expression; use {repr(f\"{f'{x}'}\")} instead.", + replacements: [["{repr(f\"{f'{x}'}\")}", "'café'"]] }, + { message: "{b'\\x00'!r}", logged: "invalid syntax (, line 1)", + refusal: "{b'\\x00'!r}: … and !r is f-string syntax, not an expression; use {repr(b'\\x00')} instead.", + replacements: [["{repr(b'\\x00')}", "b'\\x00'"]] }, + { message: "{\"a\\\\\"!r}", logged: "invalid syntax (, line 1)", + refusal: "{\"a\\\\\"!r}: … and !r is f-string syntax, not an expression; use {repr(\"a\\\\\")} instead.", + replacements: [["{repr(\"a\\\\\")}", "'a\\\\'"]] }, + { message: "{lambda: f'{x}'!r}", logged: "invalid syntax (, line 1)", + refusal: "{lambda: f'{x}'!r}: … and !r is f-string syntax, not an expression; use {repr(lambda: f'{x}')} instead.", + replacements: [["{repr(lambda: f'{x}')}", " at 0x…>"]] }, + { message: "{(lambda v: v)(f\"{x}\")!r}", logged: "invalid syntax (, line 1)", + refusal: "{(lambda v: v)(f\"{x}\")!r}: … and !r is f-string syntax, not an expression; use {repr((lambda v: v)(f\"{x}\"))} instead.", + replacements: [["{repr((lambda v: v)(f\"{x}\"))}", "'café'"]] }, + { message: "{'''a\nb'''!r}", logged: "invalid syntax (, line 2)", + refusal: "{'''a\nb'''!r}: … and !r is f-string syntax, not an expression; use {repr('''a\nb''')} instead.", + replacements: [["{repr('''a\nb''')}", "'a\\nb'"]] }, + { message: "{f'{x!r:\"<4}'!r}", logged: "invalid syntax (, line 1)", + refusal: "{f'{x!r:\"<4}'!r}: … and !r is f-string syntax, not an expression; use {repr(f'{x!r:\"<4}')} instead.", + replacements: [["{repr(f'{x!r:\"<4}')}", "\"'café'\""]] }, + { message: "{f'{x:{\"<\"}10}'!r}", logged: "invalid syntax (, line 1)", + refusal: "{f'{x:{\"<\"}10}'!r}: … and !r is f-string syntax, not an expression; use {repr(f'{x:{\"<\"}10}')} instead.", + replacements: [["{repr(f'{x:{\"<\"}10}')}", "'café '"]] }, + { message: "{f\"\"\"{x}\n\"\"\"!r}", logged: "invalid syntax (, line 2)", + refusal: "{f\"\"\"{x}\n\"\"\"!r}: … and !r is f-string syntax, not an expression; use {repr(f\"\"\"{x}\n\"\"\")} instead.", + replacements: [["{repr(f\"\"\"{x}\n\"\"\")}", "'café\\n'"]] }, + // The = debug form + { message: "{ x = }", logged: "invalid syntax (, line 1)", + refusal: "{ x = }: … and = is f-string syntax, not an expression; use x = {repr(x)} instead.", + replacements: [[" x = {repr(x)}", " x = 'café'"]] }, + { message: "{x=!s}", logged: "invalid syntax (, line 1)", + refusal: "{x=!s}: … and =!s is f-string syntax, not an expression; use x={str(x)} instead.", + replacements: [["x={str(x)}", "x=café"]] }, + { message: "{x=!a}", logged: "invalid syntax (, line 1)", + refusal: "{x=!a}: … and =!a is f-string syntax, not an expression; use x={ascii(x)} instead.", + replacements: [["x={ascii(x)}", "x='caf\\xe9'"]] }, + { message: "stale={entry=!r}", logged: "invalid syntax (, line 1)", + refusal: "{entry=!r}: … and =!r is f-string syntax, not an expression; use entry={repr(entry)} instead.", + replacements: [["stale=entry={repr(entry)}", "stale=entry='old'"]] }, + { message: "{x=:>10}", logged: "invalid syntax (, line 1)", + refusal: "{x=:>10}: … and =:>10 is f-string syntax, not an expression; use x={format(x, '>10')} instead.", + replacements: [["x={format(x, '>10')}", "x= café"]] }, + { message: "{x=!r:>10}", logged: "invalid syntax (, line 1)", + refusal: "{x=!r:>10}: … and =!r:>10 is f-string syntax, not an expression; use x={format(repr(x), '>10')} instead.", + replacements: [["x={format(repr(x), '>10')}", "x= 'café'"]] }, + { message: "{a == b=}", logged: "invalid syntax (, line 1)", + refusal: "{a == b=}: … and = is f-string syntax, not an expression; use a == b={repr(a == b)} instead.", + replacements: [["a == b={repr(a == b)}", "a == b=False"]] }, + { message: "{a, b=}", logged: "invalid syntax (, line 1)", + refusal: "{a, b=}: … and = is f-string syntax, not an expression; use a, b={repr((a, b))} instead.", + replacements: [["a, b={repr((a, b))}", "a, b=(1, 2)"]] }, + { message: "{x=:}", logged: "invalid syntax (, line 1)", + refusal: "{x=:}: … and =: is f-string syntax, not an expression; use x={format(x, '')} instead.", + replacements: [["x={format(x, '')}", "x=café"]] }, + { message: "{x= !r}", logged: "invalid syntax (, line 1)", + refusal: "{x= !r}: … and =!r is f-string syntax, not an expression; use x= {repr(x)} instead.", + replacements: [["x= {repr(x)}", "x= 'café'"]] }, + { message: "{d['a:b']=}", logged: "invalid syntax (, line 1)", + refusal: "{d['a:b']=}: … and = is f-string syntax, not an expression; use d['a:b']={repr(d['a:b'])} instead.", + replacements: [["d['a:b']={repr(d['a:b'])}", "d['a:b']='colon-key'"]] }, + { message: "{ {1: 2}[1]=}", logged: "invalid syntax (, line 1)", + refusal: "{ {1: 2}[1]=}: … and = is f-string syntax, not an expression; use {' {1: 2}[1]='}{repr({1: 2}[1])} instead.", + replacements: [["{' {1: 2}[1]='}{repr({1: 2}[1])}", " {1: 2}[1]=2"]] }, + { message: "{total % 2=}", logged: "invalid syntax (, line 1)", + refusal: "{total % 2=}: … and = is f-string syntax, not an expression; use {'total % 2='}{repr(total % 2)} instead.", + replacements: [["{'total % 2='}{repr(total % 2)}", "total % 2=1.5"]] }, + { message: "{match=}", logged: "invalid syntax (, line 1)", + refusal: "{match=}: … and = is f-string syntax, not an expression; use match={repr(match)} instead.", + replacements: [["match={repr(match)}", "match="]] }, + { message: "{x=:{w}}", logged: "invalid syntax (, line 1)", + refusal: "{x=:{w}}: … and =:{w} is f-string syntax, not an expression; use x={format(x, f'{w}')} instead.", + replacements: [["x={format(x, f'{w}')}", "x=café "]] }, + { message: "{(y := 3)=}", logged: "invalid syntax (, line 1)", + refusal: "{(y := 3)=}: … and = is f-string syntax, not an expression; use (y := 3)={repr((y := 3))} instead.", + replacements: [["(y := 3)={repr((y := 3))}", "(y := 3)=3"]] }, + // Dict-shaped groups: a quoted key or several pairs, no space after the colon, or a space + { message: "{'a': 1, 'b': 2}", logged: "invalid syntax (, line 1)", + refusal: "{'a': 1, 'b': 2}: … so a dict needs its own braces; use { {'a': 1, 'b': 2} } instead.", + replacements: [["{ {'a': 1, 'b': 2} }", "{'a': 1, 'b': 2}"]] }, + { message: "{1: 'a'}", logged: "invalid syntax (, line 1)", + refusal: "{1: 'a'}: … and : 'a' is f-string syntax, not an expression; use {format(1, \" 'a'\")} for a format spec, or { {1: 'a'} } for a dict, instead.", + replacements: [["{format(1, \" 'a'\")}", "Invalid format specifier ' 'a'' for object of type 'int'"], ["{ {1: 'a'} }", "{1: 'a'}"]] }, + { message: "{\"k\":total}", logged: "invalid syntax (, line 1)", + refusal: "{\"k\":total}: … so a dict needs its own braces; use { {\"k\":total} } instead.", + replacements: [["{ {\"k\":total} }", "{'k': 3.5}"]] }, + { message: "{\"k\": 5}", logged: "invalid syntax (, line 1)", + refusal: "{\"k\": 5}: … so a dict needs its own braces; use { {\"k\": 5} } instead.", + replacements: [["{ {\"k\": 5} }", "{'k': 5}"]] }, + { message: "{k: lambda: 1}", logged: "invalid syntax (, line 1)", + refusal: "{k: lambda: 1}: … and : lambda: 1 is f-string syntax, not an expression; use {format(k, ' lambda: 1')} for a format spec, or { {k: lambda: 1} } for a dict, instead.", + replacements: [["{format(k, ' lambda: 1')}", "Invalid format specifier ' lambda: 1' for object of type 'str'"], ["{ {k: lambda: 1} }", "{'kk': at 0x…>}"]] }, + { message: "{**d, \"k\": 1}", logged: "invalid syntax (, line 1)", + refusal: "{**d, \"k\": 1}: … so a dict needs its own braces; use { {**d, \"k\": 1} } instead.", + replacements: [["{ {**d, \"k\": 1} }", "{'a:b': 'colon-key', 'k': 1}"]] }, + { message: "{\"a\": {\"b\": 1}}", logged: "invalid syntax (, line 1)", + refusal: "{\"a\": {\"b\": 1}}: … so a dict needs its own braces; use { {\"a\": {\"b\": 1}} } instead.", + replacements: [["{ {\"a\": {\"b\": 1}} }", "{'a': {'b': 1}}"]] }, + { message: "{x:10}", logged: "invalid syntax (, line 1)", + refusal: "{x:10}: … and :10 is f-string syntax, not an expression; use {format(x, '10')} instead.", + replacements: [["{format(x, '10')}", "café "]] }, + { message: "{\"k\": total,}", logged: "invalid syntax (, line 1)", + refusal: "{\"k\": total,}: … so a dict needs its own braces; use { {\"k\": total,} } instead.", + replacements: [["{ {\"k\": total,} }", "{'k': 3.5}"]] }, + { message: "{k: v, j}", logged: "invalid syntax (, line 1)", + refusal: "{k: v, j}: … and : v, j is f-string syntax, not an expression; use {format(k, ' v, j')} instead.", + replacements: [["{format(k, ' v, j')}", "Invalid format specifier ' v, j' for object of type 'str'"]] }, + // match and case are names + { message: "{matches!r}", logged: "invalid syntax (, line 1)", + refusal: "{matches!r}: … and !r is f-string syntax, not an expression; use {repr(matches)} instead.", + replacements: [["{repr(matches)}", "['m']"]] }, + // Several bad groups + { message: "{a!r} {b!r} {x!r} {total!r} {entry!r}", logged: "invalid syntax (, line 1)", + refusal: "{a!r}: … and !r is f-string syntax, not an expression; use {repr(a)} instead. {b!r}: … and !r is f-string syntax, not an expression; use {repr(b)} instead. {x!r}: … and !r is f-string syntax, not an expression; use {repr(x)} instead. And 2 more like these.", + replacements: [["{repr(a)} {repr(b)} {repr(x)} {total!r} {entry!r}", null]] }, + { message: "{a!r} {b!r} {x!r} {total!r}", logged: "invalid syntax (, line 1)", + refusal: "{a!r}: … and !r is f-string syntax, not an expression; use {repr(a)} instead. {b!r}: … and !r is f-string syntax, not an expression; use {repr(b)} instead. {x!r}: … and !r is f-string syntax, not an expression; use {repr(x)} instead. And 1 more like it.", + replacements: [["{repr(a)} {repr(b)} {repr(x)} {total!r}", null]] }, + { message: "{x!r} {x, lambda a}{b: a}", logged: "invalid syntax (, line 1)", + refusal: "{x!r}: … and !r is f-string syntax, not an expression; use {repr(x)} instead.", + replacements: [["{repr(x)} {x, lambda a}{b: a}", "'café' café at 0x…>"]] }, + // Spec escapes, ellipsis + { message: "{dt:%H\\%M}", logged: "invalid syntax (, line 1)", + refusal: "{dt:%H\\%M}: … and :%H\\%M is f-string syntax, not an expression; use {format(dt, '%H\\\\%M')} instead.", + replacements: [["{format(dt, '%H\\\\%M')}", "13\\45"]] }, + { message: "{dt:%H\n%M}", logged: "invalid syntax (, line 1)", + refusal: "{dt:%H\n%M}: … and :%H\n%M is f-string syntax, not an expression; use {format(dt, '%H\\n%M')} instead.", + replacements: [["{format(dt, '%H\\n%M')}", "13\n45"]] }, + { message: "{dt:%H\t%M}", logged: "invalid syntax (, line 1)", + refusal: "{dt:%H\t%M}: … and :%H\t%M is f-string syntax, not an expression; use {format(dt, '%H\\t%M')} instead.", + replacements: [["{format(dt, '%H\\t%M')}", "13\t45"]] }, + { message: "{dt:%H\r%M}", logged: "invalid syntax (, line 1)", + refusal: "{dt:%H\r%M}: … and :%H\r%M is f-string syntax, not an expression; use {format(dt, '%H\\r%M')} instead.", + replacements: [["{format(dt, '%H\\r%M')}", "13\r45"]] }, + { message: "{...!r}", logged: "invalid syntax (, line 1)", + refusal: "{...!r}: … and !r is f-string syntax, not an expression; use {repr(...)} instead.", + replacements: [["{repr(...)}", "Ellipsis"]] }, + // Documented misses + { message: "{(x # c\n)!r}", logged: "invalid syntax (, line 2)", + refusal: "{(x # c\n)!r}: … and !r is f-string syntax, not an expression; use {repr((x # c\n))} instead.", + replacements: [["{repr((x # c\n))}", "'café'"]] }, + // Dict-shaped groups: a quoted key or several pairs, no space after the colon, or a space + { message: "{u\"k\": total}", logged: "invalid syntax (, line 1)", + refusal: "{u\"k\": total}: … so a dict needs its own braces; use { {u\"k\": total} } instead.", + replacements: [["{ {u\"k\": total} }", "{'k': 3.5}"]] }, + // Certain failures, each caught or left to debugpy + { message: "{a != b!r}", logged: "invalid syntax (, line 1)", + refusal: "{a != b!r}: … and !r is f-string syntax, not an expression; use {repr(a != b)} instead.", + replacements: [["{repr(a != b)}", "True"]] }, + { message: "{a != b:>5}", logged: "invalid syntax (, line 1)", + refusal: "{a != b:>5}: … and :>5 is f-string syntax, not an expression; use {format(a != b, '>5')} instead.", + replacements: [["{format(a != b, '>5')}", " 1"]] }, + // Dict-shaped groups: a quoted key or several pairs, no space after the colon, or a space + { message: "{lambda q, /: a: v}", logged: "invalid syntax (, line 1)", + refusal: "{lambda q, /: a: v}: … and : v is f-string syntax, not an expression; use {format((lambda q, /: a), ' v')} for a format spec, or { {lambda q, /: a: v} } for a dict, instead.", + replacements: [["{format((lambda q, /: a), ' v')}", "unsupported format string passed to function.__format__"], ["{ {lambda q, /: a: v} }", "{ at 0x…>: 'vv'}"]] }, + // Certain failures, each caught or left to debugpy + { message: "{lambda a, b: a!r}", logged: "invalid syntax (, line 1)", + refusal: "{lambda a, b: a!r}: … and !r is f-string syntax, not an expression; use {repr((lambda a, b: a))} instead.", + replacements: [["{repr((lambda a, b: a))}", " at 0x…>"]] }, + // A refusable form after a string or f-string the scanner must skip + { message: "{f\"{x:='^9}\"!r}", logged: "invalid syntax (, line 1)", + refusal: "{f\"{x:='^9}\"!r}: … and !r is f-string syntax, not an expression; use {repr(f\"{x:='^9}\")} instead.", + replacements: [["{repr(f\"{x:='^9}\")}", "Invalid format specifier '='^9' for object of type 'str'"]] }, + // Dict-shaped groups: a quoted key or several pairs, no space after the colon, or a space + { message: "{y := 1: v}", logged: "invalid syntax (, line 1)", + refusal: "{y := 1: v}: … and : v is f-string syntax, not an expression; use {format(y := 1, ' v')} instead.", + replacements: [["{format(y := 1, ' v')}", "Unknown format code 'v' for object of type 'int'"]] }, + { message: "{b\"k\": total}", logged: "invalid syntax (, line 1)", + refusal: "{b\"k\": total}: … so a dict needs its own braces; use { {b\"k\": total} } instead.", + replacements: [["{ {b\"k\": total} }", "{b'k': 3.5}"]] }, + { message: "{\"a\" + k: v}", logged: "invalid syntax (, line 1)", + refusal: "{\"a\" + k: v}: … and : v is f-string syntax, not an expression; use {format(\"a\" + k, ' v')} for a format spec, or { {\"a\" + k: v} } for a dict, instead.", + replacements: [["{format(\"a\" + k, ' v')}", "Unknown format code 'v' for object of type 'str'"], ["{ {\"a\" + k: v} }", "{'akk': 'vv'}"]] }, + { message: "{1.: v}", logged: "invalid syntax (, line 1)", + refusal: "{1.: v}: … and : v is f-string syntax, not an expression; use {format(1., ' v')} for a format spec, or { {1.: v} } for a dict, instead.", + replacements: [["{format(1., ' v')}", "Unknown format code 'v' for object of type 'float'"], ["{ {1.: v} }", "{1.0: 'vv'}"]] }, + { message: "{.5: v}", logged: "invalid syntax (, line 1)", + refusal: "{.5: v}: … and : v is f-string syntax, not an expression; use {format(.5, ' v')} for a format spec, or { {.5: v} } for a dict, instead.", + replacements: [["{format(.5, ' v')}", "Unknown format code 'v' for object of type 'float'"], ["{ {.5: v} }", "{0.5: 'vv'}"]] }, + { message: "{\"k\": x . upper()}", logged: "invalid syntax (, line 1)", + refusal: "{\"k\": x . upper()}: … so a dict needs its own braces; use { {\"k\": x . upper()} } instead.", + replacements: [["{ {\"k\": x . upper()} }", "{'k': 'CAFÉ'}"]] }, + { message: "{k: v for k, v in d.items() for z in items}", logged: "invalid syntax (, line 1)", + refusal: "{k: v for k, v in d.items() for z in items}: … so a dict needs its own braces; use { {k: v for k, v in d.items() for z in items} } instead.", + replacements: [["{ {k: v for k, v in d.items() for z in items} }", "{'a:b': 'colon-key'}"]] }, + { message: "{k: v: w}", logged: "invalid syntax (, line 1)", + refusal: "{k: v: w}: … and : v: w is f-string syntax, not an expression; use {format(k, ' v: w')} instead.", + replacements: [["{format(k, ' v: w')}", "Invalid format specifier ' v: w' for object of type 'str'"]] }, + { message: "{\"a\": 1, : 2}", logged: "invalid syntax (, line 1)", + refusal: "{\"a\": 1, : 2}: … and : 1, : 2 is f-string syntax, not an expression; use {format(\"a\", ' 1, : 2')} instead.", + replacements: [["{format(\"a\", ' 1, : 2')}", "Invalid format specifier ' 1, : 2' for object of type 'str'"]] }, + { message: "{a, k: v for k, v in d.items()}", logged: "invalid syntax (, line 1)", + refusal: "{a, k: v for k, v in d.items()}: … and : v for k, v in d.items() is f-string syntax, not an expression; use {format((a, k), ' v for k, v in d.items()')} instead.", + replacements: [["{format((a, k), ' v for k, v in d.items()')}", "unsupported format string passed to tuple.__format__"]] }, + { message: "{total:{w}.2f}", logged: "invalid decimal literal (, line 1)", + refusal: "{total:{w}.2f}: … and :{w}.2f is f-string syntax, not an expression; use {format(total, f'{w}.2f')} instead.", + replacements: [["{format(total, f'{w}.2f')}", " 3.50"]] }, + { message: "{\"k\": ...}", logged: "invalid syntax (, line 1)", + refusal: "{\"k\": ...}: … so a dict needs its own braces; use { {\"k\": ...} } instead.", + replacements: [["{ {\"k\": ...} }", "{'k': Ellipsis}"]] }, + // A refusable form after a string or f-string the scanner must skip + { message: "{f\"{{\" + f\"}}\" + x!r}", logged: "invalid syntax (, line 1)", + refusal: "{f\"{{\" + f\"}}\" + x!r}: … and !r is f-string syntax, not an expression; use {repr(f\"{{\" + f\"}}\" + x)} instead.", + replacements: [["{repr(f\"{{\" + f\"}}\" + x)}", "'{}café'"]] }, + // The = debug form + { message: "{entrée=}", logged: "invalid syntax (, line 1)", + refusal: "{entrée=}: … and = is f-string syntax, not an expression; use entrée={repr(entrée)} instead.", + replacements: [["entrée={repr(entrée)}", "entrée='é'"]] }, + // Dict-shaped groups: a quoted key or several pairs, no space after the colon, or a space + { message: "{\"k\": 1.5}", logged: "invalid syntax (, line 1)", + refusal: "{\"k\": 1.5}: … so a dict needs its own braces; use { {\"k\": 1.5} } instead.", + replacements: [["{ {\"k\": 1.5} }", "{'k': 1.5}"]] }, + { message: "{\"k\": x[0].real}", logged: "invalid syntax (, line 1)", + refusal: "{\"k\": x[0].real}: … so a dict needs its own braces; use { {\"k\": x[0].real} } instead.", + replacements: [["{ {\"k\": x[0].real} }", "'str' object has no attribute 'real'"]] }, + { message: "{\"k\": 0x1f}", logged: "invalid syntax (, line 1)", + refusal: "{\"k\": 0x1f}: … so a dict needs its own braces; use { {\"k\": 0x1f} } instead.", + replacements: [["{ {\"k\": 0x1f} }", "{'k': 31}"]] }, + { message: "{\"k\": 1e3}", logged: "invalid syntax (, line 1)", + refusal: "{\"k\": 1e3}: … so a dict needs its own braces; use { {\"k\": 1e3} } instead.", + replacements: [["{ {\"k\": 1e3} }", "{'k': 1000.0}"]] }, + { message: "{\"k\": 2j}", logged: "invalid syntax (, line 1)", + refusal: "{\"k\": 2j}: … so a dict needs its own braces; use { {\"k\": 2j} } instead.", + replacements: [["{ {\"k\": 2j} }", "{'k': 2j}"]] }, + { message: "{\"k\": 08}", logged: "leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers (, line 1)", + refusal: "{\"k\": 08}: … and : 08 is f-string syntax, not an expression; use {format(\"k\", ' 08')} instead.", + replacements: [["{format(\"k\", ' 08')}", "Space not allowed in string format specifier"]] }, + { message: "{\"k\": 08.5}", logged: "invalid syntax (, line 1)", + refusal: "{\"k\": 08.5}: … so a dict needs its own braces; use { {\"k\": 08.5} } instead.", + replacements: [["{ {\"k\": 08.5} }", "{'k': 8.5}"]] }, + { message: "{\"k\": .08}", logged: "invalid syntax (, line 1)", + refusal: "{\"k\": .08}: … so a dict needs its own braces; use { {\"k\": .08} } instead.", + replacements: [["{ {\"k\": .08} }", "{'k': 0.08}"]] }, + { message: "{\"k\": x.5}", logged: "invalid syntax (, line 1)", + refusal: "{\"k\": x.5}: … and : x.5 is f-string syntax, not an expression; use {format(\"k\", ' x.5')} instead.", + replacements: [["{format(\"k\", ' x.5')}", "Invalid format specifier ' x.5' for object of type 'str'"]] }, + // A refusable form after a string or f-string the scanner must skip + { message: "{f\"\\{'\"'}\"!r}", logged: "invalid syntax (, line 1)", + refusal: "{f\"\\{'\"'}\"!r}: … and !r is f-string syntax, not an expression; use {repr(f\"\\{'\"'}\")} instead.", + replacements: [["{repr(f\"\\{'\"'}\")}", "'\\\\\"'"]] }, + { message: "{f'''{f\"{{\"}}}'''!r}", logged: "invalid syntax (, line 1)", + refusal: "{f'''{f\"{{\"}}}'''!r}: … and !r is f-string syntax, not an expression; use {repr(f'''{f\"{{\"}}}''')} instead.", + replacements: [["{repr(f'''{f\"{{\"}}}''')}", "'{}'"]] }, + { message: "{f\"{x:{'}' + '{'}}\"!r}", logged: "invalid syntax (, line 1)", + refusal: "{f\"{x:{'}' + '{'}}\"!r}: … and !r is f-string syntax, not an expression; use {repr(f\"{x:{'}' + '{'}}\")} instead.", + replacements: [["{repr(f\"{x:{'}' + '{'}}\")}", "Invalid format specifier '}{' for object of type 'str'"]] }, + // Dict-shaped groups: a quoted key or several pairs, no space after the colon, or a space + { message: "{\"k\": 1.}", logged: "invalid syntax (, line 1)", + refusal: "{\"k\": 1.}: … so a dict needs its own braces; use { {\"k\": 1.} } instead.", + replacements: [["{ {\"k\": 1.} }", "{'k': 1.0}"]] }, + { message: "{\"k\": 1.e3}", logged: "invalid syntax (, line 1)", + refusal: "{\"k\": 1.e3}: … so a dict needs its own braces; use { {\"k\": 1.e3} } instead.", + replacements: [["{ {\"k\": 1.e3} }", "{'k': 1000.0}"]] }, + { message: "{\"k\": 1.5.real}", logged: "invalid syntax (, line 1)", + refusal: "{\"k\": 1.5.real}: … so a dict needs its own braces; use { {\"k\": 1.5.real} } instead.", + replacements: [["{ {\"k\": 1.5.real} }", "{'k': 1.5}"]] }, + { message: "{\"k\": 1..real}", logged: "invalid syntax (, line 1)", + refusal: "{\"k\": 1..real}: … so a dict needs its own braces; use { {\"k\": 1..real} } instead.", + replacements: [["{ {\"k\": 1..real} }", "{'k': 1.0}"]] }, + { message: "{\"k\": 1.real}", logged: "invalid decimal literal (, line 1)", + refusal: "{\"k\": 1.real}: … and : 1.real is f-string syntax, not an expression; use {format(\"k\", ' 1.real')} instead.", + replacements: [["{format(\"k\", ' 1.real')}", "Format specifier missing precision"]] }, + { message: "{\"k\": 1 .real}", logged: "invalid syntax (, line 1)", + refusal: "{\"k\": 1 .real}: … so a dict needs its own braces; use { {\"k\": 1 .real} } instead.", + replacements: [["{ {\"k\": 1 .real} }", "{'k': 1}"]] }, + { message: "{\"k\": x1.real}", logged: "invalid syntax (, line 1)", + refusal: "{\"k\": x1.real}: … so a dict needs its own braces; use { {\"k\": x1.real} } instead.", + replacements: [["{ {\"k\": x1.real} }", "name 'x1' is not defined"]] }, + { message: "{\"k\": 2j.real}", logged: "invalid syntax (, line 1)", + refusal: "{\"k\": 2j.real}: … so a dict needs its own braces; use { {\"k\": 2j.real} } instead.", + replacements: [["{ {\"k\": 2j.real} }", "{'k': 0.0}"]] }, + { message: "{\"k\": 0x1f.real}", logged: "invalid syntax (, line 1)", + refusal: "{\"k\": 0x1f.real}: … so a dict needs its own braces; use { {\"k\": 0x1f.real} } instead.", + replacements: [["{ {\"k\": 0x1f.real} }", "{'k': 31}"]] }, + { message: "{k: v, j: w}", logged: "invalid syntax (, line 1)", + refusal: "{k: v, j: w}: … so a dict needs its own braces; use { {k: v, j: w} } instead.", + replacements: [["{ {k: v, j: w} }", "{'kk': 'vv', 'jj': 10}"]] }, + { message: "{k:v,j:w}", logged: "invalid syntax (, line 1)", + refusal: "{k:v,j:w}: … so a dict needs its own braces; use { {k:v,j:w} } instead.", + replacements: [["{ {k:v,j:w} }", "{'kk': 'vv', 'jj': 10}"]] }, + { message: "{f\"{d[\"a:b\"]}\": total}", logged: "invalid syntax (, line 1)", + refusal: "{f\"{d[\"a:b\"]}\": total}: … so a dict needs its own braces; use { {f\"{d[\"a:b\"]}\": total} } instead.", + replacements: [["{ {f\"{d[\"a:b\"]}\": total} }", "{'colon-key': 3.5}"]] }, + { message: "{t\"{d[\"a:b\"]}\": total}", logged: "invalid syntax. Perhaps you forgot a comma? (, line 1)", + refusal: "{t\"{d[\"a:b\"]}\": total}: … so a dict needs its own braces; use { {t\"{d[\"a:b\"]}\": total} } instead.", + replacements: [["{ {t\"{d[\"a:b\"]}\": total} }", "invalid syntax. Perhaps you forgot a comma? (, line 1)"]] }, + { message: "{k: v for k in d}", logged: "invalid syntax (, line 1)", + refusal: "{k: v for k in d}: … and : v for k in d is f-string syntax, not an expression; use {format(k, ' v for k in d')} for a format spec, or { {k: v for k in d} } for a dict, instead.", + replacements: [["{format(k, ' v for k in d')}", "Invalid format specifier ' v for k in d' for object of type 'str'"], ["{ {k: v for k in d} }", "{'a:b': 'vv'}"]] }, + { message: "{k:v}", logged: "invalid syntax (, line 1)", + refusal: "{k:v}: … and :v is f-string syntax, not an expression; use {format(k, 'v')} instead.", + replacements: [["{format(k, 'v')}", "Unknown format code 'v' for object of type 'str'"]] }, + { message: "{1:'a'}", logged: "invalid syntax (, line 1)", + refusal: "{1:'a'}: … and :'a' is f-string syntax, not an expression; use {format(1, \"'a'\")} instead.", + replacements: [["{format(1, \"'a'\")}", "Invalid format specifier ''a'' for object of type 'int'"]] }, + { message: "{x:d}", logged: "invalid syntax (, line 1)", + refusal: "{x:d}: … and :d is f-string syntax, not an expression; use {format(x, 'd')} instead.", + replacements: [["{format(x, 'd')}", "Unknown format code 'd' for object of type 'str'"]] }, + { message: "{x: 10}", logged: "invalid syntax (, line 1)", + refusal: "{x: 10}: … and : 10 is f-string syntax, not an expression; use {format(x, ' 10')} for a format spec, or { {x: 10} } for a dict, instead.", + replacements: [["{format(x, ' 10')}", "Space not allowed in string format specifier"], ["{ {x: 10} }", "{'café': 10}"]] }, + { message: "{k:\tv}", logged: "invalid syntax (, line 1)", + refusal: "{k:\tv}: … and :\tv is f-string syntax, not an expression; use {format(k, '\\tv')} for a format spec, or { {k:\tv} } for a dict, instead.", + replacements: [["{format(k, '\\tv')}", "Invalid format specifier '\tv' for object of type 'str'"], ["{ {k:\tv} }", "{'kk': 'vv'}"]] }, + { message: "{x: >10}", logged: "invalid syntax (, line 1)", + refusal: "{x: >10}: … and : >10 is f-string syntax, not an expression; use {format(x, ' >10')} instead.", + replacements: [["{format(x, ' >10')}", " café"]] }, +]; - it('refuses combined top-level conversion and format spec with nested format(repr(...), ...)', () => { - expect(validatePythonLogMessage('{x!r:>10}')).toBe( - "{x!r:>10}: debugpy evaluates the text between braces as a Python expression, and !r:>10 is f-string syntax, not an expression; use {format(repr(x), '>10')} instead." - ); - }); +describe('validatePythonLogMessage: the recorded table', () => { + it.each(ACCEPTED)('accepts %j (debugpy logged %j)', (message, logged) => { + expect(SYNTAX_ERROR.test(logged)).toBe(false); + expect(validatePythonLogMessage(message)).toBeUndefined(); }); - describe('top-level boundary cases', () => { - it.each([ - '{items[1:5:2]}', - '{matrix[1:3, 2:4]}', - '{(items[1:3])}', - "{d['a:b']}", - '{d["a:b"]}', - "{'''a:b!r'''}", - '{"""a:b:.2f"""}', - "{r'a:b!r'}", - "{b'a:b'}", - "{rb'a:b'}", - "{f'{total:.2f}'}", - '{f"{d["a:b"]}"}', - '{f"{{a:b}}"}', - '{f"{{{x}}}"}', - '{f"\\{x}"}', - '{f\'{x:"<4}\'}', - '{ {k: v for k, v in pairs} }', - '{lambda: 0}', - '{lambda a, b=1: a + b}', - '{lambda x: lambda y: x + y}', - '{lambda x=lambda a: a: x}', - '{fn if ready else lambda x: x}', - '{x:=1}', - '{x != "r"}', - '{a!=r}', - '{x # :.2f}', - '{x # !r}', - '{land!r}'.replace('!r', ''), - '{minor}' - ])('does not misclassify nested or non-format-spec constructs: %s', (logMessage) => { - expect(validatePythonLogMessage(logMessage)).toBeUndefined(); - }); - - it('catches top-level conversions and format specs after nested slices, dicts, lambdas, walrus and floats', () => { - expect(validatePythonLogMessage('{items[1:3]!r}')).toContain('use {repr(items[1:3])} instead.'); - expect(validatePythonLogMessage("{d['a:b']:.2f}")).toContain("use {format(d['a:b'], '.2f')} instead."); - expect(validatePythonLogMessage('{(lambda v: v)(total):.2f}')).toContain( - "use {format((lambda v: v)(total), '.2f')} instead." - ); - expect(validatePythonLogMessage('{(y := 3.5):.2f}')).toContain("use {format((y := 3.5), '.2f')} instead."); - expect(validatePythonLogMessage('{1.:.2f}')).toContain("use {format(1., '.2f')} instead."); - expect(validatePythonLogMessage('{land!r}')).toContain('use {repr(land)} instead.'); - expect(validatePythonLogMessage('{entrée!r}')).toContain('use {repr(entrée)} instead.'); - }); - - it('preserves caller spacing when quoting the offending group and trims the replacement operand', () => { - expect(validatePythonLogMessage('{ entry !r }')).toBe( - '{ entry !r }: debugpy evaluates the text between braces as a Python expression, and !r is f-string syntax, not an expression; use {repr(entry)} instead.' - ); - }); - - it('wraps unparenthesized top-level tuples so the suggested call takes one value argument', () => { - expect(validatePythonLogMessage('{a, b!r}')).toContain('use {repr((a, b))} instead.'); - expect(validatePythonLogMessage('{a, b:>10}')).toContain("use {format((a, b), '>10')} instead."); - // Function call commas are at depth 1, not top-level tuples. - expect(validatePythonLogMessage('{f(a, b)!r}')).toContain('use {repr(f(a, b))} instead.'); - }); + it.each(LEFT_TO_DEBUGPY)('leaves %j to debugpy (it logged %j)', (message, logged) => { + expect(logged).toMatch(SYNTAX_ERROR); + expect(validatePythonLogMessage(message)).toBeUndefined(); + }); - it('quotes format specs containing colons, hashes, quotes, empty specs and nested dynamic fields', () => { - expect(validatePythonLogMessage('{dt:%Y-%m-%d %H:%M:%S}')).toContain( - "use {format(dt, '%Y-%m-%d %H:%M:%S')} instead." - ); - expect(validatePythonLogMessage('{n:#08x}')).toContain("use {format(n, '#08x')} instead."); - expect(validatePythonLogMessage("{x:'<10}")).toContain('use {format(x, "\'<10")} instead.'); - expect(validatePythonLogMessage('{x:"\'<10}')).toContain("use {format(x, '\"\\'<10')} instead."); - expect(validatePythonLogMessage('{total:}')).toBe( - "{total:}: debugpy evaluates the text between braces as a Python expression, and ':' is f-string syntax, not an expression; use {format(total, '')} instead." - ); - expect(validatePythonLogMessage('{total:.{prec}f}')).toContain( - "use {format(total, f'.{prec}f')} instead." - ); - }); + it.each(REFUSED.map((row) => [row.message, row] as const))('refuses %j with the form that works', (_message, row) => { + expect(row.logged).toMatch(SYNTAX_ERROR); + expect(validatePythonLogMessage(row.message)).toBe(row.refusal.split('…').join(PREAMBLE)); + for (const [replacement, logged] of row.replacements) { + if (logged === null) { + expect(validatePythonLogMessage(replacement)).toBeDefined(); + } else { + expect(validatePythonLogMessage(replacement)).toBeUndefined(); + } + } + }); +}); - it('reports the first invalid group in a multi-group message', () => { - expect(validatePythonLogMessage('ok={x} bad={entry!r} later={total:.2f}')).toContain('{entry!r}'); - }); +describe('extractPythonLogMessageGroups', () => { + it("splits at braces the way pydevd does: nested braces count, string quotes don't, empty groups drop", () => { + expect(extractPythonLogMessageGroups('x={x} stale={ entry!r }')).toEqual([ + { raw: 'x', expression: 'x' }, + { raw: ' entry!r ', expression: 'entry!r' } + ]); + expect(extractPythonLogMessageGroups('{{literal}}')).toEqual([{ raw: '{literal}', expression: '{literal}' }]); + expect(extractPythonLogMessageGroups("{'}'}")).toEqual([{ raw: "'", expression: "'" }]); + expect(extractPythonLogMessageGroups('empty {} blank { } stray } ok={x}')).toEqual([{ raw: 'x', expression: 'x' }]); + expect(extractPythonLogMessageGroups('plain message')).toEqual([]); + }); - it('accepts uncertain or malformed expressions rather than guessing a broken replacement', () => { - expect(validatePythonLogMessage('open {entry!r')).toBeUndefined(); - expect(validatePythonLogMessage('{(entry!r}')).toBeUndefined(); - expect(validatePythonLogMessage('{entry):.2f}')).toBeUndefined(); - expect(validatePythonLogMessage("{'unterminated:.2f}")).toBeUndefined(); - expect(validatePythonLogMessage('{!r}')).toBeUndefined(); - expect(validatePythonLogMessage('{:.2f}')).toBeUndefined(); - expect(validatePythonLogMessage('{entry=!r}')).toBeUndefined(); - expect(validatePythonLogMessage('{a + !r}')).toBeUndefined(); - expect(validatePythonLogMessage('{obj.:.2f}')).toBeUndefined(); - expect(validatePythonLogMessage('{if x: y}')).toBeUndefined(); - expect(validatePythonLogMessage('{x and:.2f}')).toBeUndefined(); - expect(validatePythonLogMessage('{lambda x!r}')).toBeUndefined(); - expect(validatePythonLogMessage('{a ! b!r}')).toBeUndefined(); - expect(validatePythonLogMessage('{a ! b:.2f}')).toBeUndefined(); - expect(validatePythonLogMessage('{x!repr}')).toBeUndefined(); - }); + it('returns undefined when the braces do not balance (pydevd logs "Unbalanced braces in: ...")', () => { + expect(extractPythonLogMessageGroups('open {x!r')).toBeUndefined(); + expect(extractPythonLogMessageGroups('{x!r} and {unclosed')).toBeUndefined(); + expect(validatePythonLogMessage('{x!r} and {unclosed')).toBeUndefined(); }); });