diff --git a/changelog.d/1334.fixed.md b/changelog.d/1334.fixed.md new file mode 100644 index 000000000..a68dc0d53 --- /dev/null +++ b/changelog.d/1334.fixed.md @@ -0,0 +1 @@ +**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 6c795ea8c..59417f7e3 100644 --- a/docs/python/README.md +++ b/docs/python/README.md @@ -65,6 +65,8 @@ set_breakpoint { "sessionId": "...", "file": "/abs/path/script.py", "line": 15, 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 Start debugging your Python script: diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index b6e4396fc..fe54a1551 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -327,6 +327,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 d10e3c015..cae8732c0 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 @@ -111,6 +112,10 @@ export const PythonAdapterPolicy = { // correctly, sends no `initialized`: the worker does not wait for one (#746). honoursNoDebug: true, supportsLogPoints: true, + // 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, // 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 cb95339a7..882909de8 100644 --- a/packages/shared/src/interfaces/adapter-policy.ts +++ b/packages/shared/src/interfaces/adapter-policy.ts @@ -505,7 +505,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, 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 new file mode 100644 index 000000000..1482c82f5 --- /dev/null +++ b/packages/shared/src/utils/python-logpoint.ts @@ -0,0 +1,361 @@ +/** + * Up-front validation of Python (debugpy / pydevd) logpoint messages (issue #1334). + * + * 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. + * + * 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; +type Conversion = keyof typeof CONVERSION_FN; + +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. */ + raw: string; + /** Trimmed group text, matching pydevd's `"".join(expression).strip()`. */ + expression: string; +} + +/** + * 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 + * fallback; drops empty groups as pydevd does. + */ +export function extractPythonLogMessageGroups(logMessage: string): PythonLogMessageGroup[] | undefined { + const groups: PythonLogMessageGroup[] = []; + for (let i = 0; i < logMessage.length; i++) { + if (logMessage[i] !== '{') continue; + let level = 0; + 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); + if (raw.trim()) groups.push({ raw, expression: raw.trim() }); + } + return groups; +} + +/** 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 (s.startsWith(close, i)) return i + close.length; + if (interpolated && c === '{') { + if (s[i + 1] === '{') { + i += 2; + continue; + } + i = scan(s, i + 1, 'field').end; + if (i < 0) return -1; + continue; + } + 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; +} + +/** + * 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 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; + } + if (c === "'" || c === '"') { + i = skipString(s, i, false); + if (i < 0) return result; + continue; + } + 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; + } + 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 (c === '(' || c === '[' || c === '{') { + stack.push(c); + i++; + continue; + } + 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 (c === '!' && s[i + 1] === '=') { + i += 2; + continue; + } + // 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 (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; + } + 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++; + } + } + } + } + i++; + } + if (stack.length > 0 || lambdas > 0) return result; + return { ...result, end: s.length }; +} + +/** 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] !== '.'); +} + +/** 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 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)) + ); +} + +/** 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, "\\'")}'`; +} + +/** 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; +} + +/** 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; +} + +/** 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; +} + +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.`; +} + +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(); + + 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 }; + + 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,`) }; + } + } + return { open: false, problem: sentence(raw, suffix === ':' ? "':'" : suffix, `{${call}}`) }; +} + +/** + * 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 problems: string[] = []; + for (const group of extractPythonLogMessageGroups(logMessage) ?? []) { + const verdict = inspectGroup(group); + if (verdict.problem) problems.push(verdict.problem); + if (verdict.open) break; + } + 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 8f4aac062..a7c233054 100644 --- a/skills/debugging/references/python.md +++ b/skills/debugging/references/python.md @@ -69,7 +69,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)}`, `{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 aa1e3fa31..b78889e78 100644 --- a/src/server.ts +++ b/src/server.ts @@ -199,10 +199,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 08817347e..b7a3ad811 100644 --- a/src/server/handlers/breakpoint-tools.ts +++ b/src/server/handlers/breakpoint-tools.ts @@ -168,7 +168,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 new file mode 100644 index 000000000..766f57f5b --- /dev/null +++ b/tests/adapters/python/integration/python-logpoint-validation.test.ts @@ -0,0 +1,139 @@ +/** + * 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'; +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'); +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 = {}; + 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 }; +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; + + afterEach(async () => { + await server?.close(); + server = undefined; + }); + + 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 }); + 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'); + + 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); + + 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); + + 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.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/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..d7c8b07bf --- /dev/null +++ b/tests/fixtures/python/logpoint_values.py @@ -0,0 +1,25 @@ +import time + + +def run(): + x = "café" + total = 3.5 + items = [10, 20, 30, 40] + entry = "old" + step = 0 + 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 + + +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 257586b38..03721e6c2 100644 --- a/tests/unit/shared/adapter-policy-contract.test.ts +++ b/tests/unit/shared/adapter-policy-contract.test.ts @@ -142,6 +142,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. */ @@ -214,6 +216,7 @@ const PINNED: Record = { policyName: 'python', supportsFunctionBreakpoints: true, supportsLogPoints: true, + validatesLogMessage: true, functionBreakpointsVia: undefined, functionBreakpointsBindLate: undefined, describeUnboundBreakpoint: true, @@ -236,6 +239,7 @@ const PINNED: Record = { policyName: 'ruby', supportsFunctionBreakpoints: false, supportsLogPoints: false, + validatesLogMessage: false, functionBreakpointsVia: undefined, functionBreakpointsBindLate: undefined, describeUnboundBreakpoint: true, @@ -258,6 +262,7 @@ const PINNED: Record = { policyName: 'js-debug', supportsFunctionBreakpoints: true, supportsLogPoints: true, + validatesLogMessage: true, functionBreakpointsVia: 'cdp', functionBreakpointsBindLate: true, describeUnboundBreakpoint: false, @@ -280,6 +285,7 @@ const PINNED: Record = { policyName: 'rust', supportsFunctionBreakpoints: true, supportsLogPoints: true, + validatesLogMessage: false, functionBreakpointsVia: undefined, functionBreakpointsBindLate: undefined, describeUnboundBreakpoint: false, @@ -302,6 +308,7 @@ const PINNED: Record = { policyName: 'go', supportsFunctionBreakpoints: true, supportsLogPoints: true, + validatesLogMessage: false, functionBreakpointsVia: undefined, functionBreakpointsBindLate: undefined, describeUnboundBreakpoint: false, @@ -324,6 +331,7 @@ const PINNED: Record = { policyName: 'java', supportsFunctionBreakpoints: true, supportsLogPoints: false, + validatesLogMessage: false, functionBreakpointsVia: undefined, functionBreakpointsBindLate: true, describeUnboundBreakpoint: false, @@ -346,6 +354,7 @@ const PINNED: Record = { policyName: 'dotnet', supportsFunctionBreakpoints: true, supportsLogPoints: false, + validatesLogMessage: false, functionBreakpointsVia: undefined, functionBreakpointsBindLate: undefined, describeUnboundBreakpoint: false, @@ -368,6 +377,7 @@ const PINNED: Record = { policyName: 'cpp', supportsFunctionBreakpoints: true, supportsLogPoints: true, + validatesLogMessage: false, functionBreakpointsVia: undefined, functionBreakpointsBindLate: undefined, describeUnboundBreakpoint: false, @@ -390,6 +400,7 @@ const PINNED: Record = { policyName: 'cobol', supportsFunctionBreakpoints: true, supportsLogPoints: true, + validatesLogMessage: false, functionBreakpointsVia: undefined, functionBreakpointsBindLate: true, describeUnboundBreakpoint: false, @@ -412,6 +423,7 @@ const PINNED: Record = { policyName: 'dart', supportsFunctionBreakpoints: false, supportsLogPoints: true, + validatesLogMessage: false, functionBreakpointsVia: undefined, functionBreakpointsBindLate: undefined, describeUnboundBreakpoint: false, @@ -434,6 +446,7 @@ const PINNED: Record = { policyName: 'mock', supportsFunctionBreakpoints: true, supportsLogPoints: true, + validatesLogMessage: false, functionBreakpointsVia: undefined, functionBreakpointsBindLate: undefined, describeUnboundBreakpoint: false, @@ -598,6 +611,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 880dac5fd..40a0e35dd 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('describeStepInFilter (issue #1328)', () => { it('explains debugpy justMyCode filtering conditionally on launch unless disabled', () => { const defaultHint = PythonAdapterPolicy.describeStepInFilter({ attachMode: false }); diff --git a/tests/unit/shared/python-logpoint.test.ts b/tests/unit/shared/python-logpoint.test.ts new file mode 100644 index 000000000..007d0c0fa --- /dev/null +++ b/tests/unit/shared/python-logpoint.test.ts @@ -0,0 +1,842 @@ +import { describe, it, expect } from 'vitest'; +import { + extractPythonLogMessageGroups, + validatePythonLogMessage +} from '../../../packages/shared/src/utils/python-logpoint.js'; + +/** + * 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; +} + +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/; + +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"], +]; + +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)"], +]; + +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é"]] }, +]; + +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(); + }); + + it.each(LEFT_TO_DEBUGPY)('leaves %j to debugpy (it logged %j)', (message, logged) => { + expect(logged).toMatch(SYNTAX_ERROR); + expect(validatePythonLogMessage(message)).toBeUndefined(); + }); + + 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(); + } + } + }); +}); + +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('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(); + }); +});