diff --git a/AGENTS.md b/AGENTS.md index 75a5b5a..1420c32 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -73,6 +73,11 @@ npx prettier --write - `src/symbolFiles.ts` – symbol files from the debug configuration, sent to the agent's memory map. - `src/settings.ts` – VS Code settings passed to the debug adapter. +- `src/contextQuery.ts` – checks and completes typed TCF context queries, + including the Simics `IDList` attribute (no `vscode` dependency, also used + by the launch configurations editor's webview). The completions' contexts + and attributes come from the `getContextQueryData` request; the + `runContextQuery` request returns what the agent selects with a query. - `src/targetMemory/` – Target Memory panels and commands (extension side). - `src/webview/targetMemory/` – Target Memory UI (React), bundled to `out/target-memory.{js,css}`. @@ -246,6 +251,11 @@ Works like "Load symbols" in the Eclipse TCF client: attaching, for each listed context, or for all contexts (`""`) with a `ContextQuery`. `MemoryMap.set` takes a single context, so a file with several contexts is set in each one's map. +- The agent matches a region's `ContextQuery` only against memory contexts + (`CONTEXT_GROUP_PROCESS`, reported as a `ProcessID` equal to the ID): + Simics processors, OS awareness processes. Threads use their process's + map, so a query that selects only threads adds the file nowhere. A query + the agent cannot parse matches every context. - The region has `FileName`, plus `BaseAddress` for an offset (as Simics `add-symbol-file -relative` uses) or `Addr` for an absolute load address. The agent removes the regions when the session ends. diff --git a/CHANGELOG.md b/CHANGELOG.md index 8366679..1439aee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,18 @@ All notable changes to the Simics Target Debug extension will be documented here ### Added +- Context queries are checked as you type them in the context picker and + the launch configurations editor. The wrong parts are marked, hovering + over them tells what is wrong, and a query with problems is not saved. + The Simics `IDList` attribute is checked too. +- While a session to the agent runs, the agent checks a context query too + (`ContextQuery.query`). The launch configurations editor lists the + contexts it selects below the query, and for a symbol file which of them + get the file. The context picker tells how many. +- Context queries get suggestions as you type them: wildcards, the + attributes the agent compares (`ContextQuery.getAttrNames`), the names of + the contexts a part can match, and values such as context IDs. An + `IDList` suggests the IDs of the contexts with state. - The Call Stack view shows the run control context hierarchy: each context with child contexts, such as a process of the Linux tracker, is a nested session with its threads. Turn it off with the setting diff --git a/docs/configuration/contexts.md b/docs/configuration/contexts.md index dbce1d9..2689218 100644 --- a/docs/configuration/contexts.md +++ b/docs/configuration/contexts.md @@ -41,10 +41,57 @@ A context query is evaluated by the agent. Some examples: | `/server/**/HasState=true` | Such contexts below the top-level context named `server`. | | `ID=cpu0` | The context with the ID `cpu0`. | | `ID=cpu0,HasState=true` | The context with the ID `cpu0`, if it can run and be stopped. | +| `ID="board.cpu[0]"` | The context with the ID `board.cpu[0]`. | +| `IDList="[cpu0, cpu1]"` | The contexts `cpu0` and `cpu1`. Simics only. | + +Names and values with other characters than letters, digits and `_`, such +as `.` and `[`, must be in double quotes. Inside them, write `"` as `\"` and +`\` as `\\`. Values are compared exactly, they +have no wildcards. `HasState` is `true` or `false`; the agent takes any +other value, such as `True`, as `false`. In `IDList`, the IDs have no +quotes, and the whole query matches nothing if one of the IDs does not +exist. The syntax is described with the Context Query service in the [TCF documentation](https://download.eclipse.org/tools/tcf/tcf-docs/). +The context picker and the launch configurations editor check a query as +you type it. When you stop typing for five seconds, or press Enter or leave +the box, the wrong parts are marked and the problems are listed below the +box. In the launch configurations editor, hover over a marked part to see +what is wrong with it. A query with problems is not saved. + +While a session to the agent runs, the agent checks the query too, shortly +after you stop typing. A query it refuses is marked like the other +problems. The launch configurations editor shows how many contexts the +query selects below the box; open it to list their IDs and names. In the +context picker, the first item tells how many. + +For a symbol file, they also tell which of the selected contexts get it. +The agent adds a symbol file only to contexts with a memory map of their +own, such as processors; threads use the memory map of their process. In +the list, these contexts come first and are marked "gets the symbol file". +A query that selects nothing, or no context that gets the symbol file, is +shown as a warning. + +Both also suggest what to type next: `*` and `**`, the attributes the agent +compares, such as `HasState=` and `ID=`, the names of the contexts the part +can match, and values such as `true` and `false` for `HasState`, context IDs +for `ID` and the IDs in an `IDList`. Names and IDs that need double quotes +get them. An `IDList` suggests the IDs of the contexts that can run and be +stopped, without quotes around them. It adds the `"[` when you type an ID +without it, as in `IDList="cpu`, and the `]"` when the list is not closed +yet. Contexts come from a running session to the agent; without one, +only the wildcards and the attributes `ID`, `ParentID`, `ProcessID`, `Name`, +`HasState` and `IDList` are suggested. + +- In the context picker, the suggestions are listed below the query. The + first item uses the query as typed; select a suggestion to put it in the + query. +- In the launch configurations editor, the suggestions show while you type, + or with Ctrl+Space. Use the arrow keys and Enter or Tab to put one in the + query, or Escape to close the list. + ## The context picker While debugging, the commands that need contexts open the same picker. This diff --git a/docs/configuration/launch-configurations.md b/docs/configuration/launch-configurations.md index eb69f14..01e999c 100644 --- a/docs/configuration/launch-configurations.md +++ b/docs/configuration/launch-configurations.md @@ -86,7 +86,8 @@ file or rule. marked. - The **Contexts** column chooses what the row applies to: all contexts, a list of contexts separated by commas, or a context query, see - [Selecting contexts](/configuration/contexts). + [Selecting contexts](/configuration/contexts). The list or query is typed + in a box below the row. - **Pick Contexts...** next to it opens the [context picker](/configuration/contexts#the-context-picker) with the contexts of the target. It needs a running debug session to the agent of diff --git a/scripts/docs-screenshots/capture.mjs b/scripts/docs-screenshots/capture.mjs index 7c2ff91..e4d57ba 100644 --- a/scripts/docs-screenshots/capture.mjs +++ b/scripts/docs-screenshots/capture.mjs @@ -754,7 +754,7 @@ try { const table = form.locator(".object-list").first(); const th = await table.locator("th", { hasText: "Contexts" }).boundingBox(); const column = [th]; - for (const cell of await table.locator(".context-scope").all()) { + for (const cell of await table.locator(".context-scope, .context-scope-text").all()) { column.push(await cell.boundingBox()); } remove = await callouts( diff --git a/src/contextPicker.ts b/src/contextPicker.ts index 4c0bf71..040223d 100644 --- a/src/contextPicker.ts +++ b/src/contextPicker.ts @@ -8,6 +8,19 @@ import { pickedValues, scopeMenuItems, } from "./contextChoices"; +import { + CONTEXT_QUERY_AGENT_DELAY_MS, + CONTEXT_QUERY_CHECK_DELAY_MS, + ContextQueryCompletion, + ContextQueryData, + ContextQueryResult, + DEFAULT_QUERY_ATTRIBUTES, + checkContextQuery, + contextQueryCompletionPoint, + contextQueryCompletions, + describeContextQueryResult, + formatContextQueryProblem, +} from "./contextQuery"; /** * The contexts of a session to pick from: the cores (contexts with state), @@ -20,6 +33,44 @@ export function listContexts(session: vscode.DebugSession, includeContainers = f ) as Promise; } +/** + * Returns what to complete a context query with in `session`, for a part + * after `parentQuery`. Without a session, or if it fails, only the attributes + * that most agents have are offered. + */ +export async function contextQueryData( + session: vscode.DebugSession | undefined, + parentQuery: string, +): Promise { + try { + if (session) { + return (await session.customRequest("getContextQueryData", { parentQuery })) as ContextQueryData; + } + } catch { + // Completions are only a help, the query can still be typed. + } + return { attributes: DEFAULT_QUERY_ATTRIBUTES, contexts: [] }; +} + +/** + * Returns the contexts the agent of `session` selects with `query`, or why + * it refuses the query; undefined without a session or if the agent cannot + * tell. + */ +export async function runContextQuery( + session: vscode.DebugSession | undefined, + query: string, +): Promise { + try { + if (session) { + return (await session.customRequest("runContextQuery", { query })) as ContextQueryResult; + } + } catch { + // The query is still checked without the agent. + } + return undefined; +} + export interface PickContextsOptions { title: string; /** The contexts to offer. Checked entries that are not among them are kept as extra items. */ @@ -34,6 +85,10 @@ export interface PickContextsOptions { allowTyped?: boolean; /** Typed text is a context ID only, not a name. */ idsOnly?: boolean; + /** The session whose contexts and query attributes complete a context query. */ + session?: vscode.DebugSession; + /** The contexts are those of a symbol file, so a query tells which of them get it. */ + symbolFile?: boolean; } /** The scope picked, Back, or undefined when cancelled. */ @@ -180,39 +235,168 @@ function check(options: PickContextsOptions, initial: readonly string[]): Promis }); } +type QueryItem = vscode.QuickPickItem & { + /** Accepting the item uses the typed query. */ + use?: true; + /** Accepting the item puts it in the query, at `start` to `end`. */ + completion?: ContextQueryCompletion & { start: number; end: number }; +}; + +/** + * Asks for a context query. The first item uses the typed query, or shows + * its first problem; with a session it also tells what the agent selects + * with the query. The items below it complete the name or value being + * typed, from the session's contexts and the attributes its agent compares. + */ function enterQuery(options: PickContextsOptions, initial: string): Promise> { return new Promise((resolve) => { - const input = vscode.window.createInputBox(); - input.title = options.title; - input.prompt = "TCF context query"; - input.placeholder = "Context query"; - input.value = initial; - input.buttons = [vscode.QuickInputButtons.Back]; + const picker = vscode.window.createQuickPick(); + picker.title = options.title; + picker.placeholder = "TCF context query, for example **/HasState=true"; + picker.value = initial; + picker.buttons = [vscode.QuickInputButtons.Back]; let finished = false; + let timer: ReturnType | undefined; + let agentTimer: ReturnType | undefined; + let problemsShown = false; + let emptyShown = false; + let completions: QueryItem[] = []; + /** What the agent made of the query, while it is the typed one. */ + let agent: { query: string; result: ContextQueryResult } | undefined; + /** Increased for each change of the text, so that completions for older text are dropped. */ + let generation = 0; + const cache = new Map>(); + const data = (parentQuery: string) => { + let result = cache.get(parentQuery); + if (!result) { + result = contextQueryData(options.session, parentQuery); + cache.set(parentQuery, result); + } + return result; + }; function finish(step: Step): void { if (finished) { return; } finished = true; - input.hide(); - input.dispose(); + clearTimeout(timer); + clearTimeout(agentTimer); + picker.hide(); + picker.dispose(); resolve(step); } - input.onDidChangeValue(() => { - input.validationMessage = undefined; - }); - input.onDidTriggerButton(() => finish({ back: input.value.trim() })); - input.onDidAccept(() => { - const query = input.value.trim(); + /** The agent's reason to refuse the typed query, if it has answered for it. */ + function agentError(query: string): string | undefined { + return agent?.query === query ? agent.result.error : undefined; + } + + function showItems(): void { + const query = picker.value; + const problems = problemsShown ? checkContextQuery(query) : []; + const refused = problemsShown ? agentError(query.trim()) : undefined; + let first: QueryItem | undefined; + if (problems.length > 0) { + const more = problems.length > 1 ? ` (and ${problems.length - 1} more)` : ""; + first = { label: `$(error) ${formatContextQueryProblem(query, problems[0])}${more}` }; + } else if (refused !== undefined) { + first = { label: `$(error) The agent refuses the query: ${refused}` }; + } else if (query.trim()) { + const result = agent?.query === query.trim() && !agent.result.error ? agent.result : undefined; + first = { + label: query.trim(), + description: "Use this query", + ...(result && { detail: describeContextQueryResult(result, options.symbolFile) }), + use: true, + }; + } else if (emptyShown) { + first = { label: "$(error) Enter a context query" }; + } + picker.items = [...(first ? [{ ...first, alwaysShow: true }] : []), ...completions]; + } + + /** Asks the agent what the typed query selects once the user stops typing. */ + function askAgent(): void { + clearTimeout(agentTimer); + const query = picker.value.trim(); + if (!options.session || !query || checkContextQuery(query).length > 0) { + return; + } + agentTimer = setTimeout(() => { + void runContextQuery(options.session, query).then((result) => { + if (!finished && picker.value.trim() === query) { + agent = result && { query, result }; + showItems(); + } + }); + }, CONTEXT_QUERY_AGENT_DELAY_MS); + } + + async function complete(): Promise { + const current = ++generation; + const text = picker.value; + const point = contextQueryCompletionPoint(text, text.length); + const found = point ? contextQueryCompletions(point, await data(point.parentQuery)) : []; + if (current !== generation || finished || !point) { + return; + } + completions = found.map((c) => ({ + label: c.label, + description: c.detail, + alwaysShow: true, + completion: { ...c, start: point.start, end: point.end }, + })); + showItems(); + } + + // Problems wait until the user stops typing, but once shown they follow the text. + function changed(): void { + clearTimeout(timer); + emptyShown = false; + completions = []; + if (!problemsShown || (checkContextQuery(picker.value).length === 0 && !agentError(picker.value.trim()))) { + problemsShown = false; + timer = setTimeout(() => { + problemsShown = true; + showItems(); + }, CONTEXT_QUERY_CHECK_DELAY_MS); + } + showItems(); + askAgent(); + void complete(); + } + + picker.onDidChangeValue(changed); + picker.onDidTriggerButton(() => finish({ back: picker.value.trim() })); + picker.onDidAccept(() => { + const item = picker.activeItems[0]; + const text = picker.value; + if (item?.completion) { + const { start, end, text: inserted } = item.completion; + picker.value = text.slice(0, start) + inserted + text.slice(end); + changed(); + return; + } + if (item && !item.use) { + return; + } + const query = text.trim(); if (!query) { - input.validationMessage = "Enter a context query"; + emptyShown = true; + } else if (checkContextQuery(query).length === 0 && agentError(query) === undefined) { + finish({ scope: { contextQuery: query } }); return; } - finish({ scope: { contextQuery: query } }); + clearTimeout(timer); + problemsShown = true; + showItems(); }); - input.onDidHide(() => finish(undefined)); - input.show(); + picker.onDidHide(() => finish(undefined)); + problemsShown = checkContextQuery(initial).length > 0; + showItems(); + askAgent(); + void complete(); + picker.show(); }); } diff --git a/src/contextQuery.ts b/src/contextQuery.ts new file mode 100644 index 0000000..eaa2eb6 --- /dev/null +++ b/src/contextQuery.ts @@ -0,0 +1,682 @@ +/* + * Checks TCF context queries as the user types them, so that mistakes are + * shown before the agent gets the query. The grammar is the one of the + * Context Query service; where the agent's parser (tcf/services/contextquery.c) + * is more lenient than the grammar, for example names that start with a + * digit, the agent's parser is followed. The Simics agent's IDList attribute + * and its HasState comparison are checked too. + */ + +/** A wrong part of a context query, as offsets into the checked text. */ +export interface ContextQueryProblem { + start: number; + end: number; + message: string; +} + +/** A name or value of a query and where it is: `offsets` has the offset of each character of `value`. */ +interface Text { + value: string; + quoted: boolean; + start: number; + end: number; + offsets: number[]; +} + +const SEPARATORS = "/,="; + +/** How long after the last key press the problems of a typed query are shown. */ +export const CONTEXT_QUERY_CHECK_DELAY_MS = 5000; + +class QuerySyntaxError extends Error { + constructor(readonly problem: ContextQueryProblem) { + super(problem.message); + } +} + +/** + * Returns the problems of the context query `text`, in the order they occur, + * or none if the agent accepts it. Parsing stops at the first syntax error, + * so only the problems before it and that error are reported. Space around + * the query is ignored, like the callers trim it before saving. + */ +export function checkContextQuery(text: string): ContextQueryProblem[] { + const offset = text.length - text.trimStart().length; + const parser = new Parser(text.trim()); + parser.parse(); + return parser.problems + .sort((a, b) => a.start - b.start) + .map((p) => ({ ...p, start: p.start + offset, end: p.end + offset })); +} + +/** Describes `problem` of `query` in one line, for places that cannot highlight it. */ +export function formatContextQueryProblem(query: string, problem: ContextQueryProblem): string { + return `Column ${problem.start + 1}, '${query.slice(problem.start, problem.end)}': ${problem.message}`; +} + +/** A context a query can select, for completions. */ +export interface QueryContext { + id: string; + /** The Name property of the context, if it has one. */ + name?: string; + /** True if the context can run and be stopped (HasState). */ + hasState?: boolean; +} + +/** What completions of a context query are made of, from the getContextQueryData request. */ +export interface ContextQueryData { + /** The attributes the agent compares, from ContextQuery.getAttrNames. */ + attributes: string[]; + /** All contexts of the session. */ + contexts: QueryContext[]; + /** The IDs of the contexts the part at the cursor can select, if the agent could tell. */ + partContextIds?: string[]; +} + +/** The attributes offered without an agent that lists them: RunControl context properties and Simics IDList. */ +export const DEFAULT_QUERY_ATTRIBUTES = ["ID", "ParentID", "ProcessID", "Name", "HasState", "IDList"]; + +/** A context a query selects, from the runContextQuery request. */ +export interface ContextQueryMatch { + id: string; + name?: string; + /** + * True if the context has a memory map of its own (its ProcessID is its + * ID). The agent adds a symbol file scoped by a query only to the memory + * maps of such contexts; their threads use it from there. Unset if the + * agent does not report the ProcessID. + */ + ownMemoryMap?: boolean; +} + +/** What the agent makes of a context query: the contexts it selects, or why it refuses the query. */ +export interface ContextQueryResult { + error?: string; + matches: ContextQueryMatch[]; +} + +/** How long after the last key press a typed query is sent to the agent. */ +export const CONTEXT_QUERY_AGENT_DELAY_MS = 300; + +/** + * Returns the contexts with `ids`, as ContextQuery.query replies them, in the + * order of `order` and with the properties `info` knows. IDs not in `order` + * come last, in the agent's order. + */ +export function contextQueryMatches( + ids: readonly string[], + info: (id: string) => { Name?: string; ProcessID?: string } | undefined, + order: readonly string[], +): ContextQueryMatch[] { + const position = new Map(order.map((id, i) => [id, i])); + const rank = (id: string) => position.get(id) ?? order.length; + return [...new Set(ids)] + .sort((a, b) => rank(a) - rank(b)) + .map((id) => { + const ctx = info(id); + return { + id, + ...(ctx?.Name !== undefined && { name: ctx.Name }), + ...(ctx?.ProcessID !== undefined && { ownMemoryMap: ctx.ProcessID === id }), + }; + }); +} + +/** + * Describes `result` in one line. For a symbol file it also tells which of + * the selected contexts get the file, see ContextQueryMatch.ownMemoryMap. + */ +export function describeContextQueryResult(result: ContextQueryResult, symbolFile = false): string { + if (result.error !== undefined) { + return `The agent refuses the query: ${result.error}`; + } + const n = result.matches.length; + const selects = n === 0 ? "Selects no contexts" : `Selects ${n} context${n === 1 ? "" : "s"}`; + if (!symbolFile || n === 0 || result.matches.every((m) => m.ownMemoryMap === undefined)) { + return selects; + } + const added = result.matches.filter((m) => m.ownMemoryMap).length; + if (added === 0) { + return `${selects}, but none has a memory map of its own, so the symbol file is added to none`; + } + const which = + added === n + ? n === 1 + ? "it" + : "all of them" + : added === 1 + ? "the one with a memory map of its own" + : `the ${added} with a memory map of their own`; + return `${selects}; the symbol file is added to ${which}`; +} + +/** True if `result` is worth a warning: the query selects nothing, or no context gets the symbol file. */ +export function contextQueryResultIsEmpty(result: ContextQueryResult, symbolFile = false): boolean { + return result.matches.length === 0 || (symbolFile && result.matches.every((m) => m.ownMemoryMap === false)); +} + +/** Where a completion goes in a context query. */ +export interface ContextQueryCompletionPoint { + /** + * A part's first name (a wildcard, a context name or an attribute), an + * attribute after ',', an attribute's value, or an ID in an IDList value. + */ + kind: "part" | "attribute" | "value" | "listedId"; + /** The offsets of the text a completion replaces. */ + start: number; + end: number; + /** The text before the cursor that completions must match, without quotes and escapes. */ + typed: string; + /** The attribute of a value. */ + attribute?: string; + /** True for the first ID of an IDList whose '[' is not typed yet, so completions add it. */ + opensList?: boolean; + /** What completions add after an IDList's ID when the list is not closed yet: ']"' or ']'. */ + listEnd?: string; + /** The parts before the cursor's part: "" if there are none, "/" for a part below the root. */ + parentQuery: string; +} + +export interface ContextQueryCompletion { + label: string; + /** Replaces the text from the start to the end of the completion point. */ + text: string; + detail?: string; + /** True if more is to be typed right after it, such as the value after "HasState=". */ + continues?: boolean; +} + +/** The end of the quoted string at `start`: after the closing quote, or the end of `text`. */ +function quotedEnd(text: string, start: number): number { + for (let i = start + 1; i < text.length; i++) { + if (text[i] === "\\") { + i++; + } else if (text[i] === '"') { + return i + 1; + } + } + return text.length; +} + +/** The text of a name or value without quotes and escapes, and the offset in `raw` of each character. */ +function unquote(raw: string): { value: string; offsets: number[] } { + if (!raw.startsWith('"')) { + return { value: raw, offsets: Array.from({ length: raw.length }, (_, k) => k) }; + } + let value = ""; + const offsets: number[] = []; + for (let k = 1; k < raw.length && raw[k] !== '"'; k++) { + if (raw[k] === "\\" && k + 1 < raw.length) { + k++; + } + value += raw[k]; + offsets.push(k); + } + return { value, offsets }; +} + +/** `text` as a name or value of a query: quoted unless it is a symbol. */ +function quoteQueryText(text: string): string { + return /^[A-Za-z_][A-Za-z0-9_]*$/.test(text) ? text : `"${text.replace(/[\\"]/g, "\\$&")}"`; +} + +/** + * Returns where a completion at offset `cursor` of the query `text` goes, or + * undefined if nothing can be completed there. Only the text before the + * cursor decides; the rest of the name or value at the cursor is replaced. + */ +export function contextQueryCompletionPoint(text: string, cursor: number): ContextQueryCompletionPoint | undefined { + const first = text.length - text.trimStart().length; + if (cursor < first || cursor > text.length) { + return undefined; + } + let partStart = first; + let tokenStart = first; + let kind: "part" | "attribute" | "value" = "part"; + let attribute: string | undefined; + let inQuotes = false; + for (let i = first; i < cursor;) { + const c = text[i]; + if (c === '"') { + const end = quotedEnd(text, i); + if (end > cursor || text[end - 1] !== '"' || end === i + 1) { + inQuotes = true; + break; + } + i = end; + continue; + } + if (c === "/") { + partStart = tokenStart = i + 1; + kind = "part"; + attribute = undefined; + } else if (c === ",") { + tokenStart = i + 1; + kind = "attribute"; + attribute = undefined; + } else if (c === "=") { + attribute = unquote(text.slice(tokenStart, i)).value; + tokenStart = i + 1; + kind = "value"; + } + i++; + } + const parentQuery = partStart === first ? "" : partStart - 1 === first ? "/" : text.slice(first, partStart - 1); + const raw = text.slice(tokenStart, cursor); + const { value: typed, offsets } = unquote(raw); + const opensList = !typed.startsWith("["); + if (attribute?.toLowerCase() === "idlist" && inQuotes && !(opensList && typed.includes(","))) { + let from = opensList ? 0 : Math.max(typed.lastIndexOf(","), 0) + 1; + while (typed[from] === " ") { + from++; + } + // IDs can have brackets, so only a ']' right before the closing quote ends the list. + let end = cursor; + while (end < text.length && !',"'.includes(text[end])) { + end++; + } + if (end > cursor && text[end - 1] === "]" && text[end] !== ",") { + end--; + } + const start = from < typed.length ? tokenStart + offsets[from] : cursor; + const listEnd = end === text.length ? ']"' : text[end] === '"' ? "]" : undefined; + return { + kind: "listedId", + start, + end, + typed: typed.slice(from), + attribute, + ...(opensList && { opensList }), + ...(listEnd && { listEnd }), + parentQuery, + }; + } + let end = tokenStart; + while (end < text.length && !SEPARATORS.includes(text[end])) { + end = text[end] === '"' ? quotedEnd(text, end) : end + 1; + } + return { kind, start: tokenStart, end: Math.max(end, cursor), typed, attribute, parentQuery }; +} + +/** + * Returns the query that selects the contexts a part after `parentQuery` + * can match, or undefined if it can match any context. + */ +export function partContextsQuery(parentQuery: string): string | undefined { + return parentQuery === "" ? undefined : parentQuery === "/" ? "/*" : `${parentQuery}/*`; +} + +/** + * Returns the completions for `point` from `data`: those whose label starts + * with the typed text first, then those that contain it, ignoring case. + */ +export function contextQueryCompletions( + point: ContextQueryCompletionPoint, + data: ContextQueryData, +): ContextQueryCompletion[] { + const partIds = data.partContextIds && new Set(data.partContextIds); + const partContexts = data.contexts.filter((c) => !partIds || partIds.has(c.id)); + const attributes = [...new Set(data.attributes.filter((a) => a !== "*"))].map((a) => ({ + label: `${a}=`, + text: `${quoteQueryText(a)}=`, + detail: "Attribute", + continues: true, + })); + const ids = (contexts: QueryContext[]) => + contexts.map((c) => ({ label: c.id, text: quoteQueryText(c.id), detail: c.name })); + // The Simics agent splits an IDList at ',' and ' ' and has no escapes. + const listedIds = (prefix: string, suffix = "") => + data.contexts + .filter((c) => c.hasState && !/[\s,"\\]/.test(c.id)) + .map((c) => ({ label: c.id, text: prefix + c.id + suffix, detail: c.name })); + let items: ContextQueryCompletion[]; + switch (point.kind) { + case "part": + items = [ + { label: "*", text: "*", detail: "Any context" }, + { label: "**", text: "**", detail: "Any number of contexts, also none" }, + ...attributes, + ...contextNames(partContexts), + ]; + break; + case "attribute": + items = attributes; + break; + case "listedId": + items = listedIds(point.opensList ? "[" : "", point.listEnd); + break; + case "value": + switch (point.attribute?.toLowerCase()) { + case "hasstate": + items = [ + { label: "true", text: "true", detail: "Contexts that can run and be stopped" }, + { label: "false", text: "false", detail: "Contexts that cannot" }, + ]; + break; + case "id": + items = ids(partContexts); + break; + case "parentid": + case "processid": + case "creatorid": + items = ids(data.contexts); + break; + case "name": + items = contextNames(partContexts); + break; + case "idlist": + items = [ + { label: '"[...]"', text: '"[', detail: "Context IDs", continues: true }, + ...listedIds('"[', ']"'), + ]; + break; + default: + items = []; + } + break; + } + const typed = point.typed.toLowerCase(); + const starting: ContextQueryCompletion[] = []; + const containing: ContextQueryCompletion[] = []; + for (const item of items) { + const label = item.label.toLowerCase(); + if (item.label === point.typed && !item.continues) { + continue; + } + if (label.startsWith(typed)) { + starting.push(item); + } else if (label.includes(typed)) { + containing.push(item); + } + } + return [...starting, ...containing]; +} + +/** The names of `contexts` as completions, each once, with the ID of the context that has it. */ +function contextNames(contexts: QueryContext[]): ContextQueryCompletion[] { + const byName = new Map(); + for (const c of contexts) { + if (c.name) { + byName.set(c.name, [...(byName.get(c.name) ?? []), c.id]); + } + } + return [...byName].map(([name, named]) => ({ + label: name, + text: quoteQueryText(name), + detail: named.length === 1 ? named[0] : `${named.length} contexts`, + })); +} + +class Parser { + readonly problems: ContextQueryProblem[] = []; + private i = 0; + + constructor(private readonly q: string) {} + + parse(): void { + if (!this.q) { + return; + } + try { + if (this.q[this.i] === "/") { + this.i++; + } + this.part(); + while (this.i < this.q.length) { + // part() stops at a '/' or the end. + this.i++; + this.part(); + } + } catch (e) { + if (!(e instanceof QuerySyntaxError)) { + throw e; + } + this.problems.push(e.problem); + } + } + + private fail(start: number, end: number, message: string): never { + throw new QuerySyntaxError({ start, end: Math.max(end, start + 1), message }); + } + + private atSeparatorOrEnd(): boolean { + return this.i >= this.q.length || SEPARATORS.includes(this.q[this.i]); + } + + /** Fails unless something other than a separator comes next. */ + private expect(what: string): void { + if (!this.atSeparatorOrEnd()) { + return; + } + if (this.i >= this.q.length) { + this.fail(this.q.length - 1, this.q.length, `Expected ${what} after '${this.q[this.q.length - 1]}'`); + } + this.fail(this.i, this.i + 1, `Expected ${what}, not '${this.q[this.i]}'`); + } + + /** The end of the text from `from` up to the next separator. */ + private tokenEnd(from: number): number { + let end = from; + while (end < this.q.length && !SEPARATORS.includes(this.q[end])) { + end++; + } + return end; + } + + private part(): void { + this.expect("a context name, a property or a wildcard"); + if (this.q[this.i] === "*") { + const start = this.i++; + if (this.q[this.i] === "*") { + this.i++; + } + if (this.i < this.q.length && this.q[this.i] !== "/") { + this.fail(start, this.tokenEnd(start), "* and ** are the only wildcards, and stand alone between '/'"); + } + return; + } + for (;;) { + this.property(); + if (this.i >= this.q.length || this.q[this.i] === "/") { + return; + } + if (this.q[this.i] !== ",") { + this.fail(this.i, this.tokenEnd(this.i), "Expected ',' or '/' here"); + } + this.i++; + this.expect("a property"); + } + } + + private property(): void { + const name = this.q[this.i] === '"' ? this.quoted() : this.symbol(); + if (this.q[this.i] !== "=") { + return; + } + this.i++; + this.expect("a value"); + const value = this.value(name.value); + if (this.q[this.i] === "=") { + this.fail(this.i, this.tokenEnd(this.i + 1), "A property can have only one value"); + } + this.checkAttribute(name, value); + } + + private value(attribute: string): Text { + const c = this.q[this.i]; + if (c >= "0" && c <= "9") { + return this.number(); + } + return c === '"' ? this.quoted(attribute) : this.symbol(); + } + + private symbol(): Text { + const start = this.i; + while (this.i < this.q.length && /[A-Za-z0-9_]/.test(this.q[this.i])) { + this.i++; + } + if (!this.atSeparatorOrEnd()) { + const end = this.tokenEnd(start); + this.fail( + start, + end, + this.q.slice(start, end).includes("*") + ? "Names and values have no wildcards, they are compared exactly" + : "Unquoted text can only have letters, digits and '_': put it in double quotes", + ); + } + return this.text(start, false); + } + + private number(): Text { + const start = this.i; + while (this.q[this.i] >= "0" && this.q[this.i] <= "9") { + this.i++; + } + if (this.q[this.i] === "=") { + this.fail(this.i, this.tokenEnd(this.i + 1), "A property can have only one value"); + } + if (!this.atSeparatorOrEnd()) { + this.fail( + start, + this.tokenEnd(start), + "A value that starts with a digit is a number: put text in double quotes", + ); + } + return this.text(start, false); + } + + private text(start: number, quoted: boolean): Text { + const offsets = Array.from({ length: this.i - start }, (_, k) => start + k); + return { value: this.q.slice(start, this.i), quoted, start, end: this.i, offsets }; + } + + /** Reads quoted text; `attribute` is the property name when the text is its value. */ + private quoted(attribute?: string): Text { + const start = this.i++; + let value = ""; + const offsets: number[] = []; + for (;;) { + if (this.i >= this.q.length) { + this.fail(start, this.q.length, "Missing closing '\"'"); + } + const c = this.q[this.i]; + if (c === '"') { + this.i++; + if (!this.atSeparatorOrEnd()) { + this.checkInnerQuotes(start, attribute); + } + return { value, quoted: true, start, end: this.i, offsets }; + } + if (c === "\\") { + const next = this.q[this.i + 1]; + if (next !== '"' && next !== "\\") { + this.fail(this.i, Math.min(this.i + 2, this.q.length), 'Only \\" and \\\\ can be escaped'); + } + offsets.push(this.i + 1); + value += next; + this.i += 2; + } else { + offsets.push(this.i); + value += c; + this.i++; + } + } + } + + /** + * Fails with the escaped text if the quoted text at `start`, which ended + * at a '"' with more text after it, seems meant to go on to a later '"', + * as in IDList="["a"]". That '"' is the last one before the next '=' + * that a separator or the end follows. An IDList gets its IDs without + * quotes, as the Simics agent keeps escaped quotes in the IDs. + */ + private checkInnerQuotes(start: number, attribute?: string): void { + const nextEquals = this.q.indexOf("=", this.i); + const limit = nextEquals < 0 ? this.q.length : nextEquals; + let end = -1; + for (let k = this.i; k < limit; k++) { + if (this.q[k] === '"' && (k + 1 >= this.q.length || SEPARATORS.includes(this.q[k + 1]))) { + end = k + 1; + } + } + if (end < 0) { + return; + } + if (attribute?.toLowerCase() === "idlist") { + const list = this.q.slice(start + 1, end - 1).replace(/\\?"/g, ""); + this.fail(start, end, `Write the context IDs of an IDList without quotes: "${list}"`); + } + let escaped = ""; + for (let k = start + 1; k < end - 1; k++) { + if (this.q[k] === "\\" && (this.q[k + 1] === '"' || this.q[k + 1] === "\\")) { + escaped += this.q[k] + this.q[++k]; + } else { + escaped += this.q[k] === '"' ? '\\"' : this.q[k]; + } + } + this.fail(start, end, `Write a '"' inside double quotes as \\": "${escaped}"`); + } + + private checkAttribute(name: Text, value: Text): void { + switch (name.value.toLowerCase()) { + case "hasstate": + if (!["true", "false", "1", "0"].includes(value.value)) { + this.problems.push({ + start: value.start, + end: value.end, + message: `HasState is true or false: the agent takes '${value.value}' as false`, + }); + } + break; + case "idlist": + this.checkIdList(value); + break; + } + } + + /** Checks the list of the Simics IDList attribute, like the Simics agent parses it. */ + private checkIdList(value: Text): void { + const v = value.value; + if (v.length < 2 || v[0] !== "[" || v[v.length - 1] !== "]") { + this.problems.push({ + start: value.start, + end: value.end, + message: 'IDList is a list of context IDs in brackets, in double quotes: "[id1, id2]"', + }); + return; + } + const last = v.length - 1; + const at = (from: number, to: number, message: string) => + this.problems.push({ start: value.offsets[from], end: value.offsets[to - 1] + 1, message }); + for (let i = 1; i < last;) { + let start = i; + while (start < last && v[start] === " ") { + start++; + } + let end = start; + while (end < last && v[end] !== ",") { + end++; + } + let idEnd = end; + while (idEnd > start && v[idEnd - 1] === " ") { + idEnd--; + } + if (idEnd === start) { + const sep = Math.min(end, last); + at(sep, sep + 1, v[sep] === "," ? "Missing context ID before ','" : "Missing context ID"); + } else if (v.slice(start, idEnd).includes('"')) { + at(start, idEnd, "Write the context IDs of an IDList without quotes"); + } else if (v.slice(start, idEnd).includes(" ")) { + at(start, idEnd, "A context ID cannot have spaces"); + } + if (end === last) { + break; + } + i = end + 1; + if (i === last) { + at(end, end + 1, "Missing context ID after ','"); + } + } + } +} diff --git a/src/extension.ts b/src/extension.ts index 6f83019..bad0f11 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -268,6 +268,7 @@ async function addFunctionBreakpointInContext( const scope = symbolFile ? symbolFileBreakpointScope(symbolFile.file, contexts) : await pickBreakpointContexts( + session, "Function Breakpoint Contexts", contexts, { contexts: selected ? [selected.id] : [] }, @@ -299,6 +300,7 @@ async function addFunctionBreakpointInContext( /** Returns the context IDs (empty for all contexts) or context query, or undefined if cancelled. */ function pickBreakpointContexts( + session: vscode.DebugSession, title: string, contexts: TargetContext[], scope: ContextScope, @@ -310,6 +312,7 @@ function pickBreakpointContexts( scope, selectedId: selected?.id, placeholder: "Check the cores to stop in", + session, }); } @@ -367,6 +370,7 @@ async function editFunctionBreakpointContexts(): Promise { const threadId = active?.session.id === session.id ? active.threadId : undefined; const selected = contexts.find((context) => threadId !== undefined && context.threadId === threadId); const scope = await pickBreakpointContexts( + session, `Contexts for ${location}`, contexts, functionBreakpointScope(parsed), @@ -813,6 +817,8 @@ async function promptSymbolScope(session: vscode.DebugSession, scope: ContextSco selectedId: contexts.find((context) => threadId !== undefined && context.threadId === threadId)?.id, placeholder: "Check the contexts the symbols apply to, or check none for all contexts", allowTyped: true, + session, + symbolFile: true, }); } diff --git a/src/launchSettings/editorProvider.ts b/src/launchSettings/editorProvider.ts index 9eaec35..066b688 100644 --- a/src/launchSettings/editorProvider.ts +++ b/src/launchSettings/editorProvider.ts @@ -15,8 +15,8 @@ import { } from "./launchJson"; import { isContextSession } from "@/contextSessionManager"; import { TargetContext } from "@/contextChoices"; -import { listContexts, pickContexts } from "@/contextPicker"; -import { StateMessage, WebviewMessage } from "./protocol"; +import { contextQueryData, listContexts, pickContexts, runContextQuery } from "@/contextPicker"; +import { ContextQueryDataMessage, ContextQueryResultMessage, StateMessage, WebviewMessage } from "./protocol"; import { Field, agentAddress, @@ -168,6 +168,15 @@ class LaunchSettingsEditorProvider implements vscode.CustomTextEditorProvider { } }), webview.onDidReceiveMessage((message: WebviewMessage) => { + // Not queued, so that completions do not wait for edits to be saved. + if (message.type === "contextQueryData") { + void answerContextQueryData(document, message).then((reply) => webview.postMessage(reply)); + return; + } + if (message.type === "runContextQuery") { + void answerRunContextQuery(document, message).then((reply) => webview.postMessage(reply)); + return; + } queue = queue .then(() => this.handle( @@ -308,6 +317,39 @@ class LaunchSettingsEditorProvider implements vscode.CustomTextEditorProvider { } } +/** Returns the session to the agent of the configuration at `index` named `name`, if one runs. */ +function agentSession(document: vscode.TextDocument, index: number, name: string): vscode.DebugSession | undefined { + const config = readConfigurations(document.getText()).configurations?.find( + (c) => c.index === index && c.name === name, + ); + const agent = config && agentAddress(config.values); + return [...tcfSessions].find((s) => agentAddress(s.configuration) === agent); +} + +/** + * Returns what to complete a context query of the configuration with, from a + * session to its agent if one runs. + */ +async function answerContextQueryData( + document: vscode.TextDocument, + message: Extract, +): Promise { + return { + type: "contextQueryData", + requestId: message.requestId, + data: await contextQueryData(agentSession(document, message.index, message.name), message.parentQuery), + }; +} + +/** Returns what a session to the configuration's agent selects with the query, if one runs. */ +async function answerRunContextQuery( + document: vscode.TextDocument, + message: Extract, +): Promise { + const result = await runContextQuery(agentSession(document, message.index, message.name), message.query); + return { type: "contextQueryResult", requestId: message.requestId, ...(result && { result }) }; +} + /** * Lets the user pick the contexts of the list item at `path`, such as a * symbol file, from those of a running session to the configuration's agent. @@ -356,6 +398,8 @@ async function pickItemContexts( placeholder: "Check the contexts", allowTyped: true, idsOnly: itemPath[0] === "pathMap", + session, + symbolFile: itemPath[0] === "symbolFiles", }); if (scope === undefined) { return; diff --git a/src/launchSettings/protocol.ts b/src/launchSettings/protocol.ts index 47613e0..9e04462 100644 --- a/src/launchSettings/protocol.ts +++ b/src/launchSettings/protocol.ts @@ -1,3 +1,4 @@ +import type { ContextQueryData, ContextQueryResult } from "@/contextQuery"; import type { LaunchConfiguration } from "./launchJson"; import type { Field } from "./schema"; @@ -16,6 +17,22 @@ export interface StateMessage { busyAgents: string[]; } +/** The reply to a contextQueryData message of the launch form. */ +export interface ContextQueryDataMessage { + type: "contextQueryData"; + requestId: number; + data: ContextQueryData; +} + +/** The reply to a runContextQuery message, without a result if no session to the agent can tell. */ +export interface ContextQueryResultMessage { + type: "contextQueryResult"; + requestId: number; + result?: ContextQueryResult; +} + +export type ExtensionMessage = StateMessage | ContextQueryDataMessage | ContextQueryResultMessage; + export type JsonPath = (string | number)[]; /** @@ -30,6 +47,10 @@ export type WebviewMessage = | { type: "browse"; index: number; name: string; path: JsonPath; pick: "file" | "folder" } /** Pick the contexts of the list item at `path` from a session to the configuration's agent. */ | { type: "pickContexts"; index: number; name: string; path: JsonPath } + /** Get what to complete a context query with, from a session to the configuration's agent. */ + | { type: "contextQueryData"; index: number; name: string; requestId: number; parentQuery: string } + /** Get what a session to the configuration's agent selects with `query`. */ + | { type: "runContextQuery"; index: number; name: string; requestId: number; query: string } | { type: "add" } | { type: "duplicate"; index: number; name: string } | { type: "delete"; index: number; name: string } diff --git a/src/pathMapScope.ts b/src/pathMapScope.ts index ba226eb..f4f6f22 100644 --- a/src/pathMapScope.ts +++ b/src/pathMapScope.ts @@ -47,6 +47,7 @@ export async function promptPathMapScope( placeholder: "Check the contexts the rule applies to", allowTyped: true, idsOnly: true, + session, }); if (scope === undefined) { return undefined; diff --git a/src/tcfDebugSession.ts b/src/tcfDebugSession.ts index 2a8f222..e726671 100644 --- a/src/tcfDebugSession.ts +++ b/src/tcfDebugSession.ts @@ -54,6 +54,13 @@ import { symbolFileMapContexts, } from "./symbolFiles"; import { describeContextScope } from "./contextChoices"; +import { + ContextQueryData, + ContextQueryResult, + DEFAULT_QUERY_ATTRIBUTES, + contextQueryMatches, + partContextsQuery, +} from "./contextQuery"; import { toBigInt } from "./tcf/json"; import { scanMemory } from "./shared/targetMemory/search"; import * as req from "./tcfRequests"; @@ -654,6 +661,34 @@ export class TcfDebugSession extends DebugSession { }); return; } + if (command === "getContextQueryData") { + await this.handle( + response, + async () => { + const parentQuery = + typeof args === "object" && args !== null && "parentQuery" in args + ? args.parentQuery + : undefined; + response.body = await this.contextQueryData(typeof parentQuery === "string" ? parentQuery : ""); + }, + false, + ); + return; + } + if (command === "runContextQuery") { + await this.handle( + response, + async () => { + const query = typeof args === "object" && args !== null && "query" in args ? args.query : undefined; + if (typeof query !== "string") { + throw new Error("runContextQuery needs a query"); + } + response.body = await this.runContextQuery(query); + }, + false, + ); + return; + } if (command === "getMissingSources") { response.body = { sources: [...this.missingSources.values()] }; this.sendResponse(response); @@ -2316,6 +2351,55 @@ export class TcfDebugSession extends DebugSession { return undefined; } + /** + * Returns the attributes and contexts to complete a context query with, + * and the contexts a part after `parentQuery` can select. + */ + private async contextQueryData(parentQuery: string): Promise { + const strings = (value: unknown) => + Array.isArray(value) && value.every((v) => typeof v === "string") ? value : undefined; + const data: ContextQueryData = { + attributes: DEFAULT_QUERY_ATTRIBUTES, + contexts: this.contextOrder.map((id) => { + const ctx = this.contexts.get(id); + return { id, name: ctx?.Name, ...(ctx?.HasState && { hasState: true }) }; + }), + }; + const channel = this.channel; + if (!channel?.hasService("ContextQuery")) { + return data; + } + const [names] = await channel.command("ContextQuery", "getAttrNames").catch(() => [undefined]); + data.attributes = strings(names) ?? data.attributes; + const query = partContextsQuery(parentQuery); + if (query !== undefined) { + const [ids] = await channel.command("ContextQuery", "query", query).catch(() => [undefined]); + data.partContextIds = strings(ids); + } + return data; + } + + /** Returns the contexts the agent selects with `query`, or the agent's reason to refuse it. */ + private async runContextQuery(query: string): Promise { + const channel = this.channel; + if (!channel?.hasService("ContextQuery")) { + throw new Error("The TCF agent does not provide the ContextQuery service"); + } + let ids: unknown; + try { + [ids] = await channel.command("ContextQuery", "query", query); + } catch (err) { + if (err instanceof TcfError && !err.unsupported && err.data !== undefined) { + return { error: formatTcfError(err.data), matches: [] }; + } + throw err; + } + if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string")) { + throw new Error("Invalid ContextQuery.query response"); + } + return { matches: contextQueryMatches(ids, (id) => this.contexts.get(id), this.contextOrder) }; + } + /** Full name of a context, built from the names of its ancestors. */ private contextDisplayName(id: string): string { const names: string[] = []; diff --git a/src/test/contextQuery.test.ts b/src/test/contextQuery.test.ts new file mode 100644 index 0000000..949b806 --- /dev/null +++ b/src/test/contextQuery.test.ts @@ -0,0 +1,354 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + type ContextQueryData, + type ContextQueryResult, + checkContextQuery, + contextQueryCompletionPoint, + contextQueryCompletions, + contextQueryMatches, + contextQueryResultIsEmpty, + describeContextQueryResult, + formatContextQueryProblem, + partContextsQuery, +} from "@/contextQuery"; + +/** The problems of `query`, with the wrong part as text instead of offsets. */ +function problems(query: string): { part: string; message: string }[] { + return checkContextQuery(query).map((p) => ({ part: query.slice(p.start, p.end), message: p.message })); +} + +function assertProblem(query: string, part: string, message: RegExp): void { + const found = problems(query); + assert.equal(found.length, 1, `${query}: ${JSON.stringify(found)}`); + assert.equal(found[0].part, part, query); + assert.match(found[0].message, message, query); +} + +// The examples of the Context Query service page, and what the agents accept beyond them. +test("checkContextQuery accepts valid queries", () => { + for (const query of [ + "", + "httpd", + "pid=4711", + "/server/**", + '"Linux 2.6.14"/Kernel/*', + "pid=4711/*", + "/server/**/HasState=true", + " **/HasState=true ", + 'ID="riscs"/HasState=1', + "HasState=false,Name=cpu0", + "0abc", + 'Name="a\\"b\\\\"', + 'IDList="[riscs.third.hart[0], riscs.third.hart[1]]"', + 'HasState=true,IDList="[ a , b ]"', + 'IDList="[]"', + ]) { + assert.deepEqual(problems(query), [], query); + } +}); + +// Queries built from each rule of the grammar on the Context Query service page. +const GRAMMAR_GOOD = [ + "*", + "**", + "/*", + "/**", + "**/**", + "Linux/Kernel/*/HasState=true", + '**/"Linux 2.6.14"/**', + "Name=httpd,pid=4711", + '"httpd"', + '"pid"=4711', + 'Name="Linux 2.6.14"', + 'Name=""', + '""', + "_a_1=_b_2", + "pid=0", + 'Name="a\\\\b"', + "ID=cpu0", + "ID=0", + 'ID="qsp_v2.css.core_cluster.pkg0.core[0][0]"', + 'ID="riscs"/HasState=true', + 'ID="board.cpu[0]",HasState=true', + '**/ID="nt0.ctx7"', +]; + +/** Queries that break a rule of the grammar, and the part marked as wrong. */ +const GRAMMAR_BAD: [query: string, part: string][] = [ + ["//server", "/"], + ["server/", "/"], + ["server//Kernel", "/"], + ["server/,pid=1", ","], + ["pid=4711,", ","], + [",pid=4711", ","], + ["pid=", "="], + ["pid==4711", "="], + ["=4711", "="], + ["pid=4711=1", "=1"], + ["***", "***"], + ["*a", "*a"], + ["a*", "a*"], + ["*/", "/"], + ["**,pid=1", "**"], + ["pid=*", "*"], + ["Linux 2.6.14", "Linux 2.6.14"], + ['"Linux 2.6.14', '"Linux 2.6.14'], + ['"a\\nb"', "\\n"], + ["pid=47a1", "47a1"], + ["pid=-1", "-1"], + ["Name='httpd'", "'httpd'"], + ['"a""b"', '"a""b"'], + ["/server/** /HasState=true", "** "], + ["ID=nt0.ctx7", "nt0.ctx7"], + ["ID=board.cpu[0]/HasState=true", "board.cpu[0]"], + ["ID=", "="], + ["ID=cpu0=cpu1", "=cpu1"], + ["ID=cpu*", "cpu*"], +]; + +test("checkContextQuery follows the grammar of the Context Query service", () => { + for (const query of GRAMMAR_GOOD) { + assert.deepEqual(problems(query), [], query); + } + for (const [query, part] of GRAMMAR_BAD) { + assert.deepEqual( + problems(query).map((p) => p.part), + [part], + query, + ); + } +}); + +test("checkContextQuery marks unquoted punctuation", () => { + assertProblem("ID=riscs.third.hart[0]", "riscs.third.hart[0]", /double quotes/); + assertProblem("/zynqmp.soc/HasState=true", "zynqmp.soc", /double quotes/); + assertProblem("Name=cpu*", "cpu*", /no wildcards/); + assertProblem("ID=0x10", "0x10", /number/); +}); + +test("checkContextQuery marks missing parts", () => { + assertProblem("a/", "/", /after '\/'/); + assertProblem("/", "/", /after '\/'/); + assertProblem("ID=", "=", /a value after '='/); + assertProblem("a,", ",", /a property after ','/); + assertProblem("a//b", "/", /not '\/'/); + assertProblem("=a", "=", /not '='/); +}); + +test("checkContextQuery marks wrong wildcards, quotes and values", () => { + assertProblem("**x/a", "**x", /only wildcards/); + assertProblem("*,HasState=true", "*", /only wildcards/); + assertProblem('Name="abc', '"abc', /closing/); + assertProblem('Name="a\\x"', "\\x", /escaped/); + assertProblem('"a"b', "b", /Expected ',' or '\/'/); + assertProblem("a=b=c", "=c", /only one value/); + assertProblem("a=1=c", "=c", /only one value/); +}); + +test("checkContextQuery tells how to write quotes inside quoted text", () => { + assertProblem('Name="x"y\\"",ID="z"', '"x"y\\""', /"x\\"y\\""$/); +}); + +// The Simics agent has no escapes in an IDList, so quoted IDs would be taken with their quotes. +test("checkContextQuery tells to write the IDs of an IDList without quotes", () => { + assertProblem('IDList="["apa"]"', '"["apa"]"', /without quotes: "\[apa\]"$/); + assertProblem('IDList="["a", "b"]",HasState=true', '"["a", "b"]"', /without quotes: "\[a, b\]"$/); + assertProblem('IDList="[\\"a\\", b]"', '"a\\"', /without quotes$/); +}); + +// The agent takes any HasState value but "true" and "1" as false. +test("checkContextQuery marks HasState values that are not true or false", () => { + assertProblem("/riscs/HasState=True", "True", /as false/); + assertProblem("hasstate=yes", "yes", /as false/); + assert.deepEqual( + problems("HasState=True/a.b").map((p) => p.part), + ["True", "a.b"], + ); +}); + +test("checkContextQuery checks the Simics IDList", () => { + assertProblem("IDList=abc", "abc", /list of context IDs/); + assertProblem('IDList="a, b"', '"a, b"', /list of context IDs/); + assertProblem('IDList="[a,,b]"', ",", /before ','/); + assertProblem('IDList="[a,]"', ",", /after ','/); + assertProblem('IDList="[a, b c]"', "b c", /spaces/); + assertProblem('IDList="[ ]"', "]", /Missing context ID/); +}); + +test("formatContextQueryProblem names the column and the part", () => { + const query = " ID=a.b"; + const [problem] = checkContextQuery(query); + assert.match(formatContextQueryProblem(query, problem), /^Column 5, 'a\.b': Unquoted/); +}); + +/** Marks the cursor in the queries of the completion tests. */ +const CURSOR = "|"; + +/** What the Simics agent replies to getAttrNames, with duplicates and the default comparator "*". */ +const AGENT_ATTRIBUTES = ["IDList", "*", "Name", "ParentID", "HasState", "Name", "ID"]; + +const QUERY_DATA: ContextQueryData = { + attributes: AGENT_ATTRIBUTES, + contexts: [ + { id: "board", name: "board" }, + { id: "board.cpu[0]", name: "cpu[0]", hasState: true }, + { id: "board.cpu[1]", name: "cpu[1]", hasState: true }, + { id: "other.cpu[0]", name: "cpu[0]", hasState: true }, + ], +}; + +/** The queries that each completion at CURSOR in `query` gives. */ +function completed(query: string, data = QUERY_DATA): string[] { + const cursor = query.indexOf(CURSOR); + const text = query.replace(CURSOR, ""); + const point = contextQueryCompletionPoint(text, cursor); + if (!point) { + return []; + } + return contextQueryCompletions(point, data).map((c) => text.slice(0, point.start) + c.text + text.slice(point.end)); +} + +test("contextQueryCompletions offers wildcards, attributes and names at the start of a part", () => { + assert.deepEqual(completed(CURSOR), [ + "*", + "**", + "IDList=", + "Name=", + "ParentID=", + "HasState=", + "ID=", + "board", + '"cpu[0]"', + '"cpu[1]"', + ]); + assert.deepEqual(completed(`**/${CURSOR}`).slice(0, 2), ["**/*", "**/**"]); +}); + +test("contextQueryCompletions puts matches at the start before matches inside", () => { + assert.deepEqual(completed(`id${CURSOR}`), ["IDList=", "ID=", "ParentID="]); + assert.deepEqual(completed(`1${CURSOR}`), ['"cpu[1]"']); + assert.deepEqual(completed(`"cpu[${CURSOR}`), ['"cpu[0]"', '"cpu[1]"']); +}); + +test("contextQueryCompletions offers only attributes after a ','", () => { + assert.deepEqual(completed(`HasState=true,Na${CURSOR}`), ["HasState=true,Name="]); +}); + +test("contextQueryCompletions offers the values of an attribute", () => { + assert.deepEqual(completed(`**/HasState=${CURSOR}`), ["**/HasState=true", "**/HasState=false"]); + assert.deepEqual(completed(`HasState=t${CURSOR}rue/*`), ["HasState=true/*"]); + assert.deepEqual(completed(`HasState=true${CURSOR}`), []); + assert.deepEqual(completed(`ID="board.c${CURSOR}`), ['ID="board.cpu[0]"', 'ID="board.cpu[1]"']); + assert.deepEqual(completed(`ID=oth${CURSOR}`), ['ID="other.cpu[0]"']); + assert.deepEqual(completed(`Name=${CURSOR}`), ["Name=board", 'Name="cpu[0]"', 'Name="cpu[1]"']); + assert.deepEqual(completed(`Unknown=${CURSOR}`), []); +}); + +test("contextQueryCompletions offers the IDs of the contexts with state in a Simics IDList", () => { + assert.deepEqual(completed(`IDList=${CURSOR}`), [ + 'IDList="[', + 'IDList="[board.cpu[0]]"', + 'IDList="[board.cpu[1]]"', + 'IDList="[other.cpu[0]]"', + ]); + assert.deepEqual(completed(`IDList=oth${CURSOR}`), ['IDList="[other.cpu[0]]"']); + assert.deepEqual(completed(`IDList=${CURSOR},HasState=true`)[1], 'IDList="[board.cpu[0]]",HasState=true'); + assert.deepEqual(completed(`IDList="[board.cpu[0], oth${CURSOR}`), ['IDList="[board.cpu[0], other.cpu[0]]"']); + assert.deepEqual(completed(`IDList="[board.cpu[0], oth${CURSOR}"`), ['IDList="[board.cpu[0], other.cpu[0]]"']); + assert.deepEqual(completed(`IDList="[oth${CURSOR}]`), ['IDList="[other.cpu[0]]']); + assert.deepEqual(completed(`IDList="[oth${CURSOR}, board.cpu[0]]"`), ['IDList="[other.cpu[0], board.cpu[0]]"']); + assert.deepEqual(completed(`IDList="[board.cpu[${CURSOR}]"`), [ + 'IDList="[board.cpu[0]]"', + 'IDList="[board.cpu[1]]"', + ]); + assert.deepEqual( + completed(`IDList="[b${CURSOR}oard.cpu[0], other.cpu[0]]"`)[0], + 'IDList="[board.cpu[0], other.cpu[0]]"', + ); + assert.deepEqual(completed(`IDList="[board.cpu[0]]"${CURSOR}`), []); +}); + +test("contextQueryCompletions adds the '[' of an IDList typed without it", () => { + assert.deepEqual(completed(`IDList="oth${CURSOR}`), ['IDList="[other.cpu[0]]"']); + assert.deepEqual(completed(`IDList="oth${CURSOR}"`), ['IDList="[other.cpu[0]]"']); + assert.deepEqual(completed(`IDList="${CURSOR}`).length, 3); + assert.deepEqual(completed(`IDList="a, oth${CURSOR}`), []); +}); + +test("contextQueryCompletions offers the names of the contexts the part can select", () => { + const children = { ...QUERY_DATA, partContextIds: ["board.cpu[0]", "board.cpu[1]"] }; + assert.deepEqual( + contextQueryCompletions(contextQueryCompletionPoint("board/c", 7)!, children).map((c) => [c.label, c.detail]), + [ + ["cpu[0]", "board.cpu[0]"], + ["cpu[1]", "board.cpu[1]"], + ], + ); + assert.deepEqual( + contextQueryCompletions(contextQueryCompletionPoint("c", 1)!, QUERY_DATA).map((c) => c.detail), + ["2 contexts", "board.cpu[1]"], + ); +}); + +test("contextQueryCompletionPoint gives the query of the parts before the cursor's part", () => { + const parent = (query: string) => contextQueryCompletionPoint(query, query.length)?.parentQuery; + assert.equal(parent(""), ""); + assert.equal(parent(" boa"), ""); + assert.equal(parent("/"), "/"); + assert.equal(parent("/board/c"), "/board"); + assert.equal(parent('"a/b"/c'), '"a/b"'); + assert.equal(parent("**/HasState=true,ID="), "**"); + assert.equal(partContextsQuery(""), undefined); + assert.equal(partContextsQuery("/"), "/*"); + assert.equal(partContextsQuery("/board"), "/board/*"); +}); + +// Like Simics with OS awareness: a core has its own memory map, a thread uses its process's. +const CORE = "board.cpu[0]"; +const PROCESS = "nt0.ctx1"; +const THREAD = "nt0.ctx7"; +const RUN_CONTROL: Record = { + [CORE]: { Name: "cpu[0]", ProcessID: CORE }, + [PROCESS]: { Name: "Kernel", ProcessID: PROCESS }, + [THREAD]: { Name: CORE, ProcessID: PROCESS }, +}; +const ORDER = [CORE, PROCESS, THREAD]; +const matches = (ids: string[]) => contextQueryMatches(ids, (id) => RUN_CONTROL[id], ORDER); + +test("contextQueryMatches orders the contexts and tells which have their own memory map", () => { + const UNKNOWN = "memory"; + assert.deepEqual(matches([THREAD, UNKNOWN, CORE, THREAD]), [ + { id: CORE, name: "cpu[0]", ownMemoryMap: true }, + { id: THREAD, name: CORE, ownMemoryMap: false }, + { id: UNKNOWN }, + ]); +}); + +test("describeContextQueryResult tells which contexts get a symbol file", () => { + const describe = (ids: string[], symbolFile = true) => + describeContextQueryResult({ matches: matches(ids) }, symbolFile); + assert.equal(describe([CORE, THREAD], false), "Selects 2 contexts"); + assert.equal(describe([]), "Selects no contexts"); + assert.equal(describe([CORE]), "Selects 1 context; the symbol file is added to it"); + assert.equal(describe([CORE, PROCESS]), "Selects 2 contexts; the symbol file is added to all of them"); + assert.equal( + describe([CORE, THREAD]), + "Selects 2 contexts; the symbol file is added to the one with a memory map of its own", + ); + assert.equal( + describe([THREAD]), + "Selects 1 context, but none has a memory map of its own, so the symbol file is added to none", + ); + assert.equal(describe(["memory"]), "Selects 1 context"); + const error = "Invalid context query syntax"; + assert.equal(describeContextQueryResult({ error, matches: [] }, true), `The agent refuses the query: ${error}`); +}); + +test("contextQueryResultIsEmpty warns when nothing is selected or gets the symbol file", () => { + const result = (ids: string[]): ContextQueryResult => ({ matches: matches(ids) }); + assert.equal(contextQueryResultIsEmpty(result([])), true); + assert.equal(contextQueryResultIsEmpty(result([THREAD])), false); + assert.equal(contextQueryResultIsEmpty(result([THREAD]), true), true); + assert.equal(contextQueryResultIsEmpty(result([THREAD, CORE]), true), false); +}); diff --git a/src/webview/launchSettings/App.tsx b/src/webview/launchSettings/App.tsx index 9ef8a03..a2ea391 100644 --- a/src/webview/launchSettings/App.tsx +++ b/src/webview/launchSettings/App.tsx @@ -11,7 +11,7 @@ import { TextInput, Unsupported, } from "./components/controls"; -import { loadState, onMessage, post, saveState } from "./vscode"; +import { loadState, onMessage, post, requestContextQueryData, requestContextQueryResult, saveState } from "./vscode"; /* * The launch configurations form: configuration names on the left, the attributes @@ -294,6 +294,10 @@ function Details(props: { openText: () => post({ type: "openText" }), pickContexts: (path) => post({ type: "pickContexts", ...target, path }), canPickContexts: state.busyAgents.includes(agentAddress(config.values)), + contextQueryData: (parentQuery) => requestContextQueryData(config.index, config.name, parentQuery), + runContextQuery: state.busyAgents.includes(agentAddress(config.values)) + ? (query) => requestContextQueryResult(config.index, config.name, query) + : undefined, }; const sameName = (nameCounts(props.configs).get(config.name) ?? 0) > 1; const known = new Set(state.fields.map((f) => fieldPath(f)[0])); diff --git a/src/webview/launchSettings/components/controls.tsx b/src/webview/launchSettings/components/controls.tsx index d26fdef..f39f17a 100644 --- a/src/webview/launchSettings/components/controls.tsx +++ b/src/webview/launchSettings/components/controls.tsx @@ -1,6 +1,19 @@ import * as React from "react"; import type { JsonPath } from "@/launchSettings/protocol"; import { type ContextScope, parseContextList } from "@/contextChoices"; +import { + CONTEXT_QUERY_AGENT_DELAY_MS, + CONTEXT_QUERY_CHECK_DELAY_MS, + type ContextQueryCompletion, + type ContextQueryData, + type ContextQueryProblem, + type ContextQueryResult, + checkContextQuery, + contextQueryCompletionPoint, + contextQueryCompletions, + contextQueryResultIsEmpty, + describeContextQueryResult, +} from "@/contextQuery"; import { type Field, type FieldKind, @@ -28,6 +41,10 @@ export interface Editor { pickContexts(path: JsonPath): void; /** True if a session runs to the configuration's agent, so that pickContexts can list its contexts. */ canPickContexts: boolean; + /** What to complete a context query with, for a part after `parentQuery`. */ + contextQueryData(parentQuery: string): Promise; + /** What the agent selects with a context query, set while a session runs to the configuration's agent. */ + runContextQuery?(query: string): Promise; } /** The data-focus key of a control to focus when the next state is shown. */ @@ -317,37 +334,17 @@ function ObjectList({ field, value, edit }: { field: Field; value: unknown[] | u - - {rows.map((row, r) => ( - - {typeof row !== "object" || row === null || Array.isArray(row) ? ( - - - - ) : ( - columns.map((c) => ( - - {c.kind === "contextScope" ? ( - } - path={[field.key, r]} - edit={edit} - /> - ) : ( - )[c.key]} - path={[field.key, r, c.key]} - edit={edit} - /> - )} - - )) - )} - {removeButton(r)} - - ))} - + {rows.map((row, r) => ( + + ))} ) : (

No items.

@@ -357,6 +354,71 @@ function ObjectList({ field, value, edit }: { field: Field; value: unknown[] | u ); } +/** + * The rows of a list item: one with a cell per property, and below it the + * text box of the contexts or context query, as wide as the cells from the + * contexts column to the last property. + */ +function ObjectItem({ + field, + columns, + row, + index, + edit, + removeButton, +}: { + field: Field; + columns: Field[]; + row: unknown; + index: number; + edit: Editor; + removeButton: React.ReactNode; +}) { + /** The contexts choice made while nothing is saved for it yet, such as Contexts before any is typed. */ + const [chosenScope, setChosenScope] = React.useState("all"); + if (typeof row !== "object" || row === null || Array.isArray(row)) { + return ( + + + + + + {removeButton} + + + ); + } + const item = row as Record; + const scopeColumn = columns.findIndex((c) => c.kind === "contextScope"); + const scope = + scopeColumn < 0 ? undefined : contextScopeControls(item, [field.key, index], edit, chosenScope, setChosenScope); + return ( + + + {columns.map((c) => ( + + {c.kind === "contextScope" ? ( + scope?.choice + ) : ( + + )} + + ))} + {removeButton} + + {scope?.text && ( + + {scopeColumn > 0 && } + + {scope.text} + + + + )} + + ); +} + function Cell(props: InputProps) { switch (props.field.kind) { case "boolean": @@ -376,18 +438,23 @@ const CONTEXTS_INPUT: Field = { kind: "string", default: "Separated by commas", }; -const QUERY_INPUT: Field = { key: "contextQuery", label: "Context Query", kind: "string" }; /** - * The contexts of a list item: all, listed IDs or names, or a context query. - * Each change writes the whole item, so that the attributes of the other - * choices are removed at the same time. + * The controls of the contexts of a list item: the choice of all, listed IDs + * or names, or a context query, and the text box of the latter two. `chosen` + * is the choice made while nothing is saved for it yet. Each change writes + * the whole item, so that the attributes of the other choices are removed at + * the same time. */ -function ContextScopeCell({ item, path, edit }: { item: Record; path: JsonPath; edit: Editor }) { +function contextScopeControls( + item: Record, + path: JsonPath, + edit: Editor, + chosen: ScopeMode, + setChosen: (mode: ScopeMode) => void, +): { choice: React.ReactNode; text?: React.ReactNode } { const scope = readContextScope(item); const saved: ScopeMode = "contextQuery" in scope ? "query" : scope.contexts.length > 0 ? "contexts" : "all"; - /** The choice made while nothing is saved for it yet, such as Contexts before any is typed. */ - const [chosen, setChosen] = React.useState("all"); const mode = saved === "all" ? chosen : saved; const write = (next: ContextScope) => edit.set(path, withContextScope(item, next)); const textEditor = (toScope: (text: string) => ContextScope): Editor => ({ @@ -396,50 +463,406 @@ function ContextScopeCell({ item, path, edit }: { item: Record; remove: () => write({ contexts: [] }), isMissing: () => false, }); + const choice = ( +
+ + edit.pickContexts(path)} + /> +
+ ); + if (mode === "contexts") { + const text = ( + 0 ? scope.contexts.join(", ") : undefined} + path={[...path, "contexts"]} + edit={textEditor((text) => ({ contexts: parseContextList(text) }))} + /> + ); + return { choice, text }; + } + if (mode === "query") { + const text = ( + write(text.trim() ? { contextQuery: text.trim() } : { contexts: [] })} + data={edit.contextQueryData} + run={edit.runContextQuery} + symbolFile={path[0] === "symbolFiles"} + /> + ); + return { choice, text }; + } + return { choice }; +} + +/** The text of `text`, with the parts that have problems marked for the mirror of the query box. */ +function markProblems(text: string, problems: readonly ContextQueryProblem[]): React.ReactNode[] { + const nodes: React.ReactNode[] = []; + let at = 0; + for (const p of problems) { + if (p.start < at) { + continue; + } + nodes.push(text.slice(at, p.start)); + nodes.push( + + {text.slice(p.start, p.end)} + , + ); + at = p.end; + } + nodes.push(text.slice(at)); + return nodes; +} + +/** The most suggestions shown below a context query. */ +const MAX_SUGGESTIONS = 200; + +/** The most contexts listed below a context query. */ +const MAX_MATCHES = 200; + +/** + * What the agent selects with a context query, folded down below the query + * box. For a symbol file, the contexts that get it come first and are marked. + */ +function QueryMatches({ result, symbolFile }: { result: ContextQueryResult; symbolFile: boolean }) { + const summary = describeContextQueryResult(result, symbolFile); + const className = `query-matches${contextQueryResultIsEmpty(result, symbolFile) ? " note" : ""}`; + if (result.matches.length === 0) { + return
{summary}
; + } + const matches = symbolFile + ? [...result.matches].sort((a, b) => Number(b.ownMemoryMap === true) - Number(a.ownMemoryMap === true)) + : result.matches; + const more = matches.length - MAX_MATCHES; + return ( +
+ {summary} +
    + {matches.slice(0, MAX_MATCHES).map((m) => ( +
  • + {m.id} + {m.name !== undefined && m.name !== m.id && {m.name}} + {symbolFile && m.ownMemoryMap && gets the symbol file} +
  • + ))} +
+ {more > 0 &&
and {more} more
} +
+ ); +} + +/** Suggestions shown below a context query, which replace its text from `start` to `end`. */ +interface Suggestions { + start: number; + end: number; + items: ContextQueryCompletion[]; + active: number; +} + +/** + * The text box of a context query, written when it loses focus or Enter is + * pressed. Problems show once the user stops typing for a while or tries to + * write the query, and then follow the text until it is right: the wrong + * parts are underlined, with the problem on hover and below the box. A query + * with problems is not written. While typing, or on Ctrl+Space, a list + * below the box suggests names and values from `data`. With `run`, the + * agent checks the query too, and the contexts it selects fold down below + * the box. + */ +function ContextQueryInput({ + value, + path, + write, + data, + run, + symbolFile, +}: { + value: string | undefined; + path: JsonPath; + write(text: string): void; + data(parentQuery: string): Promise; + run?(query: string): Promise; + symbolFile: boolean; +}) { + const shown = value ?? ""; + const [text, setText] = React.useState(shown); + const [revealed, setRevealed] = React.useState(() => checkContextQuery(shown).length > 0); + const [hover, setHover] = React.useState<{ message: string; left: number }>(); + const [suggest, setSuggest] = React.useState(); + const input = React.useRef(null); + const mirror = React.useRef(null); + const timer = React.useRef>(undefined); + /** The text written last, so leaving the box after Enter does not write it again. */ + const written = React.useRef(undefined); + /** Where to put the cursor once a picked suggestion is shown. */ + const pendingCursor = React.useRef(undefined); + /** Increased for each change of the suggestions, so that data arriving for older text is dropped. */ + const suggestGeneration = React.useRef(0); + const queryData = React.useRef(new Map>()); + const problemsId = React.useId(); + const suggestId = React.useId(); + const [agent, setAgent] = React.useState<{ query: string; result: ContextQueryResult }>(); + const query = text.trim(); + const result = agent?.query === query ? agent.result : undefined; + const problems = React.useMemo(() => { + const found = checkContextQuery(text); + if (found.length > 0 || result?.error === undefined) { + return found; + } + const start = text.length - text.trimStart().length; + return [{ start, end: start + query.length, message: `The agent refuses the query: ${result.error}` }]; + }, [text, result]); + const visible = revealed ? problems : []; + + // The agent checks the query once the user stops typing, if it passes the checks here. + const canRun = run !== undefined; + React.useEffect(() => { + if (!run || !query || checkContextQuery(query).length > 0) { + return; + } + let current = true; + const t = setTimeout(() => { + void run(query).then((found) => { + if (current) { + setAgent(found && { query, result: found }); + } + }); + }, CONTEXT_QUERY_AGENT_DELAY_MS); + return () => { + current = false; + clearTimeout(t); + }; + }, [query, canRun]); + + // A new saved value replaces the text, unless it is being typed or was refused. + React.useEffect(() => { + written.current = undefined; + if (document.activeElement !== input.current && problems.length === 0) { + setText(shown); + setRevealed(checkContextQuery(shown).length > 0); + } + }, [shown]); + React.useEffect(() => () => clearTimeout(timer.current), []); + const syncScroll = () => { + if (mirror.current && input.current) { + mirror.current.scrollLeft = input.current.scrollLeft; + } + }; + React.useLayoutEffect(() => { + if (pendingCursor.current !== undefined) { + input.current?.setSelectionRange(pendingCursor.current, pendingCursor.current); + pendingCursor.current = undefined; + } + syncScroll(); + }); + React.useLayoutEffect(() => { + if (suggest) { + document.getElementById(`${suggestId}-${suggest.active}`)?.scrollIntoView({ block: "nearest" }); + } + }, [suggest?.active, suggest?.items]); + + const change = (next: string) => { + setText(next); + clearTimeout(timer.current); + if (revealed && checkContextQuery(next).length > 0) { + return; + } + setRevealed(false); + timer.current = setTimeout(() => setRevealed(true), CONTEXT_QUERY_CHECK_DELAY_MS); + }; + const closeSuggestions = () => { + suggestGeneration.current++; + setSuggest(undefined); + }; + const openSuggestions = (query: string, cursor: number) => { + const current = ++suggestGeneration.current; + const point = contextQueryCompletionPoint(query, cursor); + if (!point) { + setSuggest(undefined); + return; + } + let found = queryData.current.get(point.parentQuery); + if (!found) { + found = data(point.parentQuery); + queryData.current.set(point.parentQuery, found); + } + void found.then((d) => { + if (current === suggestGeneration.current) { + const items = contextQueryCompletions(point, d).slice(0, MAX_SUGGESTIONS); + setSuggest(items.length > 0 ? { start: point.start, end: point.end, items, active: 0 } : undefined); + } + }); + }; + const pick = (item: ContextQueryCompletion) => { + if (!suggest) { + return; + } + const next = text.slice(0, suggest.start) + item.text + text.slice(suggest.end); + const cursor = suggest.start + item.text.length; + pendingCursor.current = cursor; + change(next); + if (item.continues) { + openSuggestions(next, cursor); + } else { + closeSuggestions(); + } + }; + const suggestKey = (e: React.KeyboardEvent): boolean => { + if (!suggest) { + return false; + } + const count = suggest.items.length; + switch (e.key) { + case "ArrowDown": + case "ArrowUp": + setSuggest({ ...suggest, active: (suggest.active + (e.key === "ArrowDown" ? 1 : count - 1)) % count }); + break; + case "Enter": + case "Tab": + pick(suggest.items[suggest.active]); + break; + case "Escape": + e.stopPropagation(); + closeSuggestions(); + break; + case "ArrowLeft": + case "ArrowRight": + case "Home": + case "End": + closeSuggestions(); + return true; + default: + return false; + } + e.preventDefault(); + return true; + }; + + const save = () => { + clearTimeout(timer.current); + if (problems.length > 0) { + setRevealed(true); + } else if (text.trim() !== shown && text !== written.current) { + written.current = text; + write(text); + } + }; + const showHover = (e: React.MouseEvent) => { + const box = e.currentTarget.getBoundingClientRect(); + for (const span of mirror.current?.querySelectorAll("[data-problem]") ?? []) { + const r = span.getBoundingClientRect(); + if (e.clientX >= Math.max(r.left, box.left) && e.clientX < Math.min(r.right, box.right)) { + setHover({ message: span.dataset.problem ?? "", left: Math.max(r.left, box.left) - box.left }); + return; + } + } + setHover(undefined); + }; + return ( -
-
- 0 ? "invalid" : undefined} + value={text} + spellCheck={false} + role="combobox" + aria-label="Context Query" + aria-autocomplete="list" + aria-expanded={suggest !== undefined} + aria-controls={suggest ? suggestId : undefined} + aria-activedescendant={suggest ? `${suggestId}-${suggest.active}` : undefined} + aria-invalid={visible.length > 0} + aria-describedby={visible.length > 0 ? problemsId : undefined} + data-focus={focusKey(path)} onChange={(e) => { - setChosen(e.target.value as ScopeMode); - if (saved !== "all") { - write({ contexts: [] }); + change(e.target.value); + openSuggestions(e.target.value, e.target.selectionStart ?? e.target.value.length); + }} + onKeyDown={(e) => { + if (suggestKey(e)) { + return; + } + if (e.key === " " && e.ctrlKey) { + e.preventDefault(); + openSuggestions(text, e.currentTarget.selectionStart ?? text.length); + } else if (e.key === "Enter") { + save(); } }} - > - - - - - edit.pickContexts(path)} + onFocus={() => queryData.current.clear()} + onBlur={() => { + closeSuggestions(); + save(); + }} + onMouseDown={closeSuggestions} + onScroll={syncScroll} + onSelect={syncScroll} + onMouseMove={visible.length > 0 ? showHover : undefined} + onMouseLeave={() => setHover(undefined)} /> + + {hover && visible.length > 0 && !suggest && ( +
+ {hover.message} +
+ )} + {suggest && ( +
    + {suggest.items.map((item, i) => ( +
  • e.preventDefault()} + onClick={() => pick(item)} + > + {item.label} + {item.detail && {item.detail}} +
  • + ))} +
+ )}
- {mode === "contexts" && ( - 0 ? scope.contexts.join(", ") : undefined} - path={[...path, "contexts"]} - edit={textEditor((text) => ({ contexts: parseContextList(text) }))} - /> - )} - {mode === "query" && ( - (text.trim() ? { contextQuery: text.trim() } : { contexts: [] }))} - /> + + {result && result.error === undefined && problems.length === 0 && ( + )}
); diff --git a/src/webview/launchSettings/styles.css b/src/webview/launchSettings/styles.css index a4577d6..35bbcb1 100644 --- a/src/webview/launchSettings/styles.css +++ b/src/webview/launchSettings/styles.css @@ -246,12 +246,12 @@ input.invalid { border-color: var(--vscode-inputValidation-errorBorder); } -/* While the user is still editing a table row, its problems wait until focus leaves the row. */ -.object-list tr:focus-within .problem input[type="text"] { +/* While the user is still editing a list item, its problems wait until focus leaves the item. */ +.object-list tbody:focus-within .problem input[type="text"] { border-color: var(--vscode-settings-textInputBorder, var(--vscode-input-border, transparent)); } -.object-list tr:focus-within .problem-text { +.object-list tbody:focus-within .problem-text { display: none; } @@ -361,7 +361,6 @@ button:disabled { } /* The first property is usually a path, give it the most room. */ -.object-list td:first-child, .object-list th:first-child { width: 45%; } @@ -371,17 +370,136 @@ button:disabled { max-width: none; } -.context-scope { - display: flex; - flex-direction: column; - gap: 2px; -} - .context-scope select { flex: 1; min-width: 0; } +.query-input { + position: relative; +} + +/* Lies over the query box with the same text, transparent except for the marks on wrong parts. */ +.query-mirror { + position: absolute; + inset: 0; + box-sizing: border-box; + padding: 4px 6px; + overflow: hidden; + color: transparent; + font: inherit; + line-height: normal; + white-space: pre; + border: 1px solid transparent; + pointer-events: none; +} + +.query-input input[type="text"] { + line-height: normal; +} + +.query-problem { + background: color-mix(in srgb, var(--vscode-editorError-foreground) 20%, transparent); + text-decoration: wavy underline var(--vscode-editorError-foreground); + text-decoration-skip-ink: none; +} + +.query-hover { + position: absolute; + top: 100%; + z-index: 10; + max-width: 360px; + margin-top: 2px; + padding: 4px 8px; + color: var(--vscode-editorHoverWidget-foreground); + background: var(--vscode-editorHoverWidget-background); + border: 1px solid var(--vscode-editorHoverWidget-border); + pointer-events: none; +} + +.query-suggest { + position: absolute; + top: 100%; + left: 0; + z-index: 10; + min-width: 100%; + max-width: 600px; + max-height: 240px; + margin: 2px 0 0; + padding: 0; + overflow-y: auto; + list-style: none; + color: var(--vscode-editorSuggestWidget-foreground); + background: var(--vscode-editorSuggestWidget-background); + border: 1px solid var(--vscode-editorSuggestWidget-border); +} + +.query-suggest li { + display: flex; + gap: 12px; + justify-content: space-between; + padding: 2px 6px; + white-space: nowrap; + cursor: pointer; +} + +.query-suggest li:hover { + background: var(--vscode-list-hoverBackground); +} + +.query-suggest li[aria-selected="true"] { + color: var(--vscode-editorSuggestWidget-selectedForeground); + background: var(--vscode-editorSuggestWidget-selectedBackground); +} + +.suggest-label { + font-family: var(--vscode-editor-font-family); +} + +.suggest-detail { + overflow: hidden; + text-overflow: ellipsis; + opacity: 0.7; +} + +.query-matches { + margin-top: 4px; + color: var(--vscode-descriptionForeground); +} + +.query-matches.note { + color: var(--vscode-editorWarning-foreground); +} + +.query-matches > summary { + cursor: pointer; + user-select: none; +} + +.query-matches ul { + max-height: 240px; + margin: 2px 0 0; + padding: 0 0 0 16px; + overflow-y: auto; + list-style: none; + color: var(--vscode-foreground); +} + +.query-matches li { + display: flex; + gap: 12px; + white-space: nowrap; +} + +.match-mark { + color: var(--vscode-descriptionForeground); + font-style: italic; +} + +.match-more { + padding-left: 16px; +} + .fold-down { max-width: 800px; margin-top: 16px; diff --git a/src/webview/launchSettings/vscode.ts b/src/webview/launchSettings/vscode.ts index b62c89b..0929b47 100644 --- a/src/webview/launchSettings/vscode.ts +++ b/src/webview/launchSettings/vscode.ts @@ -1,4 +1,5 @@ -import type { StateMessage, WebviewMessage } from "@/launchSettings/protocol"; +import type { ContextQueryData, ContextQueryResult } from "@/contextQuery"; +import type { ExtensionMessage, WebviewMessage } from "@/launchSettings/protocol"; interface VsCodeApi { postMessage(message: WebviewMessage): void; @@ -14,12 +15,48 @@ export function post(message: WebviewMessage): void { api.postMessage(message); } -export function onMessage(handler: (message: StateMessage) => void): () => void { - const listener = (e: MessageEvent) => handler(e.data); +export function onMessage(handler: (message: ExtensionMessage) => void): () => void { + const listener = (e: MessageEvent) => handler(e.data); window.addEventListener("message", listener); return () => window.removeEventListener("message", listener); } +let lastRequestId = 0; +const pendingQueryData = new Map void>(); +const pendingQueryResults = new Map void>(); + +onMessage((message) => { + if (message.type === "contextQueryData") { + pendingQueryData.get(message.requestId)?.(message.data); + pendingQueryData.delete(message.requestId); + } else if (message.type === "contextQueryResult") { + pendingQueryResults.get(message.requestId)?.(message.result); + pendingQueryResults.delete(message.requestId); + } +}); + +/** Asks the extension what to complete a context query of the configuration with. */ +export function requestContextQueryData(index: number, name: string, parentQuery: string): Promise { + const requestId = ++lastRequestId; + return new Promise((resolve) => { + pendingQueryData.set(requestId, resolve); + post({ type: "contextQueryData", index, name, requestId, parentQuery }); + }); +} + +/** Asks the extension what a session to the configuration's agent selects with `query`. */ +export function requestContextQueryResult( + index: number, + name: string, + query: string, +): Promise { + const requestId = ++lastRequestId; + return new Promise((resolve) => { + pendingQueryResults.set(requestId, resolve); + post({ type: "runContextQuery", index, name, requestId, query }); + }); +} + /** The state VS Code keeps while the webview is hidden or reloaded. */ export function loadState(): Partial { return (api.getState() as Partial | undefined) ?? {};