From a68a58fcacbafca70dc6be1412cb20933530df1b Mon Sep 17 00:00:00 2001 From: Walter Aquino Date: Fri, 27 Nov 2026 10:27:06 -0300 Subject: [PATCH 01/24] =?UTF-8?q?fix(app):=20un=20solo=20men=C3=BA=20abier?= =?UTF-8?q?to=20entre=20Nuevo=20y=20la=20barra=20de=20men=C3=BAs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit El botón Nuevo frenaba el mousedown y la barra no cerraba su menú. Abrir la barra con Alt tampoco cerraba Nuevo. Co-Authored-By: Claude Opus 5.5 --- app/src/App.test.tsx | 29 +++++++++++++++++++++++++++++ app/src/App.tsx | 6 ++++-- app/src/components/ContextMenu.tsx | 7 ++++++- app/src/components/MenuBar.tsx | 6 +++++- 4 files changed, 44 insertions(+), 4 deletions(-) diff --git a/app/src/App.test.tsx b/app/src/App.test.tsx index 8babf52..cab4e11 100644 --- a/app/src/App.test.tsx +++ b/app/src/App.test.tsx @@ -1210,3 +1210,32 @@ test("Ayuda > Buscar actualizaciones avisa si está al día o si falla", async ( await checkUpdatesFromMenu(); expect(await screen.findByRole("alert")).toHaveTextContent("No se pudo buscar actualizaciones"); }); + +test("Abrir un menú de la barra cierra Nuevo", async () => { + windowEvents.close.mockResolvedValue(() => {}); + render(); + fireEvent.click(await screen.findByRole("button", { name: "Cancelar" })); + fireEvent.click(screen.getByRole("button", { name: "Nuevo" })); + const archivo = screen.getByRole("button", { name: "Archivo" }); + fireEvent.mouseDown(archivo); fireEvent.click(archivo); + expect(screen.queryByRole("menu", { name: "Archivo" })).toBeInTheDocument(); + expect(screen.queryByRole("menu", { name: "Nuevo" })).not.toBeInTheDocument(); +}); +test("Abrir Nuevo cierra el menú de la barra", async () => { + windowEvents.close.mockResolvedValue(() => {}); + render(); + fireEvent.click(await screen.findByRole("button", { name: "Cancelar" })); + fireEvent.click(screen.getByRole("button", { name: "Archivo" })); + const nuevo = screen.getByRole("button", { name: "Nuevo" }); + fireEvent.mouseDown(nuevo); fireEvent.click(nuevo); + expect(screen.queryByRole("menu", { name: "Nuevo" })).toBeInTheDocument(); + expect(screen.queryByRole("menu", { name: "Archivo" })).not.toBeInTheDocument(); +}); +test("Alt cierra Nuevo al abrir la barra", async () => { + windowEvents.close.mockResolvedValue(() => {}); + render(); + fireEvent.click(await screen.findByRole("button", { name: "Cancelar" })); + fireEvent.click(screen.getByRole("button", { name: "Nuevo" })); + fireEvent.keyDown(document, { key: "Alt" }); fireEvent.keyUp(document, { key: "Alt" }); + expect(screen.queryByRole("menu", { name: "Nuevo" })).not.toBeInTheDocument(); +}); diff --git a/app/src/App.tsx b/app/src/App.tsx index 553dec9..2d075b1 100644 --- a/app/src/App.tsx +++ b/app/src/App.tsx @@ -182,6 +182,7 @@ export default function App() { } | null>(null); const closeRoutineOptions = useCallback(() => setRoutineOptions(null), []); const closeNewMenu = useCallback(() => setNewMenu(null), []); + const newButton = useRef(null); const pick = (run: () => void) => () => { setNewMenu(null); run(); @@ -1126,12 +1127,12 @@ export default function App() {
- + + {pendingUpdate && ( + { if (updateProgress === undefined) setUpdateOffer(pendingUpdate); }} + /> + )} {newMenu && ( { + const onOpen = vi.fn(); + render(); + fireEvent.click(screen.getByRole("button", { name: "Actualización disponible: 1.0.0-beta.8" })); + expect(onOpen).toHaveBeenCalledOnce(); +}); diff --git a/app/src/components/UpdateBadge.tsx b/app/src/components/UpdateBadge.tsx new file mode 100644 index 0000000..8e24f0d --- /dev/null +++ b/app/src/components/UpdateBadge.tsx @@ -0,0 +1,11 @@ +import { ArrowCircleUp } from "@phosphor-icons/react"; + +/** Recordatorio de versión nueva en la barra superior; abre el diálogo de actualización. */ +export function UpdateBadge({ version, onOpen }: { version: string; onOpen: () => void }) { + const name = `Actualización disponible: ${version}`; + return ( + + ); +} diff --git a/docs/ESTADO.md b/docs/ESTADO.md index a23a243..761c013 100644 --- a/docs/ESTADO.md +++ b/docs/ESTADO.md @@ -1,9 +1,11 @@ # Estado de OpenPL -Última actualización: 2026-11-26 (auditoría UX en `feat/auditoria-ux`, briefs 1 a 60). Mantener este archivo al día al terminar cada bloque de trabajo. +Última actualización: 2026-11-27 (beta 8: ícono de actualización y menú Nuevo; diseño del editor inteligente). ## Resumen +- 1.0.0-beta.8 (WAL-118, WAL-120): con una versión nueva, la barra superior muestra un ícono que da un salto corto y abre el diálogo de actualización. "Más tarde" deja el ícono. Nuevo y los menús de la barra ya no quedan abiertos a la vez. + - Auditoría UX: los briefs 1 a 59 del [plan de 61 briefs](superpowers/plans/2026-11-25-openpl-auditoria-ux.md) están implementados en `feat/auditoria-ux`, un commit por brief. El brief 60 deja esta documentación y la [auditoría antislop](../anti-slop/audit-auditoria-ux-2026-11-24.md). From 9027a3fc458cb679f088db1470e07975128f784a Mon Sep 17 00:00:00 2001 From: Walter Aquino Date: Fri, 27 Nov 2026 10:41:31 -0300 Subject: [PATCH 05/24] =?UTF-8?q?feat(app):=20WAL-119=20analizador=20de=20?= =?UTF-8?q?s=C3=ADmbolos=20PL/SQL?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- app/src/programStructure.ts | 18 +- app/src/programSymbols.test.ts | 148 ++++++++++++ app/src/programSymbols.ts | 416 +++++++++++++++++++++++++++++++++ 3 files changed, 573 insertions(+), 9 deletions(-) create mode 100644 app/src/programSymbols.test.ts create mode 100644 app/src/programSymbols.ts diff --git a/app/src/programStructure.ts b/app/src/programStructure.ts index 94f2d97..ab97ed1 100644 --- a/app/src/programStructure.ts +++ b/app/src/programStructure.ts @@ -26,11 +26,11 @@ export interface Token { from: number; } -const isIdentifier = (token: Token | undefined): token is Token => +export const isIdentifier = (token: Token | undefined): token is Token => !!token && /^(?:"[^"]+"|[\p{L}][\p{L}\p{N}_$#]*)$/u.test(token.text); -const nameOf = (token: Token) => +export const nameOf = (token: Token) => token.text.startsWith('"') ? token.text.slice(1, -1) : token.key; -const storedUnits = new Set([ +export const storedUnits = new Set([ "PROCEDURE", "FUNCTION", "TRIGGER", @@ -39,7 +39,7 @@ const storedUnits = new Set([ ]); const routines = new Set(["PROCEDURE", "FUNCTION", "CURSOR"]); const bodyMarkers = new Set([";", "AS", "IS"]); -const signatureModifiers = new Set([ +export const signatureModifiers = new Set([ "ACCESSIBLE", "AUTHID", "DETERMINISTIC", @@ -74,7 +74,7 @@ export function tokenize(source: string) { return tokens; } -function boundary( +export function boundary( tokens: Token[], start: number, markers: Set, @@ -105,7 +105,7 @@ function parameters(tokens: Token[], start: number, end: number) { return { parts, after: end }; } -function format(tokens: Token[]) { +export function format(tokens: Token[]) { return tokens .map((token, i) => { const before = tokens[i - 1]?.key; @@ -128,7 +128,7 @@ function normalizedParameter(tokens: Token[]) { .map((token) => token.key); } -function readName(tokens: Token[], start: number) { +export function readName(tokens: Token[], start: number) { return tokens[start + 1]?.key === "." && isIdentifier(tokens[start + 2]) ? start + 2 : start; @@ -179,7 +179,7 @@ function afterStatement(tokens: Token[], start: number) { } const statementEnd = new Set([";"]); -function matchingBlocks(tokens: Token[]) { +export function matchingBlocks(tokens: Token[]) { const ends = new Map(); const stack: { kind: string; index: number }[] = []; for (let i = 0; i < tokens.length; i += 1) { @@ -388,7 +388,7 @@ export function programFoldRanges( return ranges; } -function findCreatedUnit(tokens: Token[]) { +export function findCreatedUnit(tokens: Token[]) { for (let i = 0; i < tokens.length; i += 1) { if (tokens[i].key !== "CREATE") continue; let unit = i + 1; diff --git a/app/src/programSymbols.test.ts b/app/src/programSymbols.test.ts new file mode 100644 index 0000000..e9a8eca --- /dev/null +++ b/app/src/programSymbols.test.ts @@ -0,0 +1,148 @@ +import { expect, test } from "vitest"; +import { programSymbols, type ProgramSymbol } from "./programSymbols"; + +const find = (symbols: ProgramSymbol[], name: string) => + symbols.filter((symbol) => symbol.name === name); +const one = (symbols: ProgramSymbol[], name: string) => { + const found = find(symbols, name); + expect(found).toHaveLength(1); + return found[0]; +}; + +const spec = (members: string) => + `CREATE OR REPLACE PACKAGE pkg_ventas IS\n${members}\nEND pkg_ventas;`; +const body = (members: string) => + `CREATE OR REPLACE PACKAGE BODY pkg_ventas IS\n${members}\nEND pkg_ventas;`; + +test("constante con valor y tipo", () => { + const symbol = one(programSymbols(spec(" c_max CONSTANT NUMBER := 3;")), "C_MAX"); + expect(symbol).toMatchObject({ + kind: "constant", + dataType: "NUMBER", + value: "3", + scope: null, + }); +}); + +test("variable con DEFAULT y variable sin valor", () => { + const symbols = programSymbols( + spec(" g_modo VARCHAR2(10) DEFAULT 'A';\n g_total NUMBER;"), + ); + expect(one(symbols, "G_MODO")).toMatchObject({ + kind: "variable", + dataType: "VARCHAR2(10)", + value: "'A'", + }); + expect(one(symbols, "G_TOTAL")).toMatchObject({ + kind: "variable", + dataType: "NUMBER", + value: null, + }); +}); + +test("firma de función con modos y comentario", () => { + const symbols = programSymbols( + spec( + " -- Calcula el total\n FUNCTION calcular(p_id IN NUMBER, p_out OUT VARCHAR2) RETURN NUMBER;", + ), + ); + expect(one(symbols, "CALCULAR")).toMatchObject({ + kind: "function", + signature: + "FUNCTION calcular(p_id IN NUMBER, p_out OUT VARCHAR2) RETURN NUMBER", + comment: "Calcula el total", + definition: false, + }); + expect(one(symbols, "P_ID")).toMatchObject({ + kind: "parameter", + container: "CALCULAR", + dataType: "NUMBER", + }); + expect(one(symbols, "P_OUT")).toMatchObject({ + kind: "parameter", + container: "CALCULAR", + dataType: "VARCHAR2", + }); +}); + +test("cuerpo de rutina y locales con alcance", () => { + const source = body(" PROCEDURE p IS v_x NUMBER := 1; BEGIN NULL; END;"); + const symbols = programSymbols(source); + expect(one(symbols, "P")).toMatchObject({ kind: "procedure", definition: true }); + const local = one(symbols, "V_X"); + expect(local.scope).not.toBeNull(); + expect(local.scope!.from).toBeLessThanOrEqual(source.indexOf(" IS v_x")); + expect(local.scope!.to).toBeGreaterThanOrEqual(source.indexOf("END;") + 4); + expect(local.scope!.to).toBeLessThan(source.indexOf("END pkg_ventas")); +}); + +test("sobrecargas producen dos símbolos", () => { + const symbols = programSymbols( + spec(" PROCEDURE p(a NUMBER);\n PROCEDURE p(a VARCHAR2);"), + ); + const overloads = find(symbols, "P"); + expect(overloads.map((symbol) => symbol.signature)).toEqual([ + "PROCEDURE p(a NUMBER)", + "PROCEDURE p(a VARCHAR2)", + ]); +}); + +test("record y sus campos", () => { + const symbols = programSymbols( + spec(" TYPE t_rec IS RECORD (id NUMBER, nombre VARCHAR2(50));"), + ); + expect(one(symbols, "T_REC")).toMatchObject({ kind: "type" }); + expect(one(symbols, "ID")).toMatchObject({ + kind: "field", + container: "T_REC", + dataType: "NUMBER", + }); + expect(one(symbols, "NOMBRE")).toMatchObject({ + kind: "field", + container: "T_REC", + dataType: "VARCHAR2(50)", + }); +}); + +test("cursor con parámetros y consulta", () => { + const symbols = programSymbols( + spec( + " CURSOR c_cli(p_id NUMBER) IS SELECT id, nombre n FROM clientes WHERE id = p_id;", + ), + ); + const cursor = one(symbols, "C_CLI"); + expect(cursor.kind).toBe("cursor"); + expect(cursor.query?.startsWith("SELECT id, nombre n FROM clientes")).toBe(true); +}); + +test("subtype y %TYPE", () => { + const symbols = programSymbols( + spec(" SUBTYPE t_monto IS NUMBER(12,2);\n v_c clientes.id%TYPE;"), + ); + expect(one(symbols, "T_MONTO")).toMatchObject({ + kind: "subtype", + dataType: "NUMBER(12,2)", + }); + expect(one(symbols, "V_C")).toMatchObject({ dataType: "clientes.id%TYPE" }); +}); + +test("FOR de cursor declara su registro", () => { + const source = body( + " CURSOR c_cli(p NUMBER) IS SELECT id FROM clientes;\n PROCEDURE p IS BEGIN\n FOR r IN c_cli(1) LOOP NULL; END LOOP;\n END;", + ); + const record = one(programSymbols(source), "R"); + expect(record).toMatchObject({ kind: "variable", dataType: "C_CLI%ROWTYPE" }); + expect(record.scope!.from).toBe(source.indexOf("FOR r")); + expect(record.scope!.to).toBe(source.indexOf("END LOOP;") + "END LOOP;".length); +}); + +test("bloque anónimo declara locales", () => { + const source = "DECLARE v NUMBER := 1; BEGIN v := 2; END;"; + const local = one(programSymbols(source), "V"); + expect(local).toMatchObject({ kind: "variable", value: "1" }); + expect(local.scope).toEqual({ from: 0, to: source.length }); +}); + +test("texto incompleto no lanza", () => { + expect(Array.isArray(programSymbols("PACKAGE BODY x IS PROCEDURE p(a NUMBER"))).toBe(true); +}); diff --git a/app/src/programSymbols.ts b/app/src/programSymbols.ts new file mode 100644 index 0000000..21db946 --- /dev/null +++ b/app/src/programSymbols.ts @@ -0,0 +1,416 @@ +import { oracleDialect } from "./editorReference"; +import { + boundary, + findCreatedUnit, + format, + isIdentifier, + matchingBlocks, + nameOf, + readName, + signatureModifiers, + storedUnits, + tokenize, + type Token, +} from "./programStructure"; + +export type SymbolKind = + | "package" | "procedure" | "function" | "cursor" | "type" | "subtype" + | "variable" | "constant" | "exception" | "parameter" | "field"; + +export interface SymbolScope { + from: number; + to: number; +} + +export interface ProgramSymbol { + kind: SymbolKind; + /** Clave Oracle: mayúsculas, o tal cual si venía entre comillas. */ + name: string; + signature: string; + dataType: string | null; + /** Texto tras := o DEFAULT. */ + value: string | null; + comment: string | null; + /** Posición del nombre. */ + from: number; + /** null: nivel de unidad (global de paquete). */ + scope: SymbolScope | null; + definition: boolean; + /** Rutina, cursor o tipo dueño de parámetros y campos. */ + container: string | null; + query?: string; +} + +interface Span { + from: number; + to: number; + text: string; +} + +const tokenEnd = (token: Token) => token.from + token.text.length; +const statementEnd = new Set([";"]); +const routineMarkers = new Set([";", "IS", "AS"]); +const parameterModes = new Set(["IN", "OUT", "NOCOPY"]); + +function commentSpans(source: string): Span[] { + const spans: Span[] = []; + oracleDialect.language.parser.parse(source).iterate({ + enter(node) { + if (node.name !== "LineComment" && node.name !== "BlockComment") return; + spans.push({ from: node.from, to: node.to, text: source.slice(node.from, node.to) }); + }, + }); + return spans; +} + +function commentText(text: string) { + if (text.startsWith("--")) return text.slice(2).trim(); + return text + .replace(/^\/\*+/, "") + .replace(/\*+\/$/, "") + .split(/\r?\n/) + .map((line) => line.replace(/^\s*\*?\s?/, "").trimEnd()) + .join("\n") + .trim(); +} + +/** Comentario pegado arriba de `start` o al final de la línea que termina en `end`. */ +function attachedComment(source: string, spans: Span[], start: number, end: number) { + const above: Span[] = []; + let limit = start; + for (let i = spans.length - 1; i >= 0; i -= 1) { + const span = spans[i]; + if (span.to > limit) continue; + const gap = source.slice(span.to, limit); + if (!/^\s*$/.test(gap) || (gap.match(/\n/g) ?? []).length > 1) break; + above.unshift(span); + limit = span.from; + } + if (above.length) return above.map((span) => commentText(span.text)).join("\n") || null; + const trailing = spans.find( + (span) => span.from >= end && !/\n/.test(source.slice(end, span.from)), + ); + return trailing ? commentText(trailing.text) || null : null; +} + +class Analyzer { + readonly out: ProgramSymbol[] = []; + private readonly tokens: Token[]; + private readonly blocks: ReadonlyMap; + private readonly comments: Span[]; + + constructor(private readonly source: string) { + this.tokens = tokenize(source); + this.blocks = matchingBlocks(this.tokens); + this.comments = commentSpans(source); + } + + run() { + const { tokens } = this; + const unit = storedUnits.has(tokens[0]?.key) ? 0 : findCreatedUnit(tokens); + if (unit >= 0) this.unit(unit); + tokens.forEach((token, i) => { + if (token.key === "DECLARE") this.anonymousBlock(i); + if (token.key === "FOR") this.forLoop(i); + }); + return this.out.sort((a, b) => a.from - b.from); + } + + private text(start: number, end: number) { + if (start >= end || start >= this.tokens.length) return ""; + const last = this.tokens[Math.min(end, this.tokens.length) - 1]; + return this.source.slice(this.tokens[start].from, tokenEnd(last)); + } + + private endOf(index: number) { + const token = this.tokens[index]; + return token ? tokenEnd(token) : this.source.length; + } + + private statementEnd(start: number) { + return boundary(this.tokens, start, statementEnd); + } + + /** Índice de := o DEFAULT en profundidad cero, con su largo en tokens. */ + private assignment(start: number, end: number) { + let depth = 0; + for (let i = start; i < end; i += 1) { + const { key } = this.tokens[i]; + if (key === "(") depth += 1; + if (key === ")") depth -= 1; + if (depth) continue; + if (key === "DEFAULT") return { at: i, size: 1 }; + if (key === ":" && this.tokens[i + 1]?.key === "=") return { at: i, size: 2 }; + } + return null; + } + + /** Sin un NOT NULL final. */ + private typeEnd(start: number, end: number) { + const { tokens } = this; + return end - 2 >= start && tokens[end - 2].key === "NOT" && tokens[end - 1].key === "NULL" + ? end - 2 + : end; + } + + private comment(start: number, end: number) { + return attachedComment(this.source, this.comments, this.tokens[start].from, this.endOf(end)); + } + + private push(symbol: Omit & { comment?: string | null }) { + this.out.push({ comment: null, ...symbol }); + } + + /** Elementos separados por comas dentro del paréntesis que abre en `open`. */ + private list(open: number) { + const items: [number, number][] = []; + if (this.tokens[open]?.key !== "(") return { items, after: open }; + let depth = 0; + let start = open + 1; + for (let i = open; i < this.tokens.length; i += 1) { + const { key } = this.tokens[i]; + if (key === "(") depth += 1; + else if (key === ")") depth -= 1; + if ((key === "," && depth === 1) || depth === 0) { + if (i > start) items.push([start, i]); + start = i + 1; + if (depth === 0) return { items, after: i + 1 }; + } + } + return { items, after: this.tokens.length }; + } + + private unit(unit: number) { + const { tokens } = this; + const kind = tokens[unit].key; + if (kind === "PROCEDURE" || kind === "FUNCTION") { + this.routine(unit, null); + return; + } + if (kind !== "PACKAGE") return; + const isBody = tokens[unit + 1]?.key === "BODY"; + const nameIndex = readName(tokens, unit + (isBody ? 2 : 1)); + const name = tokens[nameIndex]; + if (!isIdentifier(name)) return; + this.push({ + kind: "package", + name: nameOf(name), + signature: `PACKAGE${isBody ? " BODY" : ""} ${this.text(unit + (isBody ? 2 : 1), nameIndex + 1)}`, + dataType: null, + value: null, + comment: this.comment(unit, nameIndex), + from: name.from, + scope: null, + definition: isBody, + container: null, + }); + const header = boundary(tokens, nameIndex + 1, routineMarkers); + if (tokens[header]?.key === "IS" || tokens[header]?.key === "AS") this.section(header + 1, null); + } + + /** Declaraciones hasta BEGIN o END; devuelve el índice donde se detuvo. */ + private section(start: number, scope: SymbolScope | null) { + const { tokens } = this; + let i = start; + while (i < tokens.length) { + const { key } = tokens[i]; + if (key === "BEGIN" || key === "END" || key === "WRAPPED") return i; + if (key === "PROCEDURE" || key === "FUNCTION" || key === "CURSOR") { + i = this.routine(i, scope); + } else if (key === "TYPE" || key === "SUBTYPE") { + i = this.type(i, scope); + } else if (key !== "PRAGMA" && isIdentifier(tokens[i]) && isIdentifier(tokens[i + 1])) { + i = this.variable(i, scope); + } else { + i = this.statementEnd(i) + 1; + } + } + return tokens.length; + } + + private variable(start: number, scope: SymbolScope | null) { + const { tokens } = this; + const name = tokens[start]; + const end = this.statementEnd(start); + const constant = tokens[start + 1].key === "CONSTANT"; + const base = { + name: nameOf(name), + from: name.from, + scope, + definition: false, + container: null, + comment: this.comment(start, end), + }; + if (tokens[start + 1].key === "EXCEPTION") { + this.push({ ...base, kind: "exception", signature: `${name.text} EXCEPTION`, dataType: null, value: null }); + return end + 1; + } + const typeStart = start + (constant ? 2 : 1); + const assign = this.assignment(typeStart, end); + const dataType = this.text(typeStart, this.typeEnd(typeStart, assign?.at ?? end)) || null; + const value = assign ? this.text(assign.at + assign.size, end) || null : null; + this.push({ + ...base, + kind: constant ? "constant" : "variable", + signature: `${name.text} ${constant ? "CONSTANT " : ""}${dataType ?? ""}${value ? ` := ${value}` : ""}`, + dataType, + value, + }); + return end + 1; + } + + private type(start: number, scope: SymbolScope | null) { + const { tokens } = this; + const name = tokens[start + 1]; + const end = this.statementEnd(start); + if (!isIdentifier(name) || tokens[start + 2]?.key !== "IS") return end + 1; + const subtype = tokens[start].key === "SUBTYPE"; + const definitionStart = start + 3; + const typeName = nameOf(name); + this.push({ + kind: subtype ? "subtype" : "type", + name: typeName, + signature: format(tokens.slice(start, end)), + dataType: this.text(definitionStart, subtype ? this.typeEnd(definitionStart, end) : end) || null, + value: null, + comment: this.comment(start, end), + from: name.from, + scope, + definition: false, + container: null, + }); + if (!subtype && tokens[definitionStart]?.key === "RECORD") { + for (const [from, to] of this.list(definitionStart + 1).items) this.member(from, to, "field", typeName, scope); + } + return end + 1; + } + + /** Campo de un RECORD o parámetro de una rutina, en tokens [from, to). */ + private member(from: number, to: number, kind: "field" | "parameter", container: string, scope: SymbolScope | null) { + const { tokens } = this; + const name = tokens[from]; + if (!isIdentifier(name)) return; + let typeStart = from + 1; + if (kind === "parameter") while (typeStart < to && parameterModes.has(tokens[typeStart].key)) typeStart += 1; + const assign = this.assignment(typeStart, to); + const typeEnd = this.typeEnd(typeStart, assign?.at ?? to); + this.push({ + kind, + name: nameOf(name), + signature: format(tokens.slice(from, assign?.at ?? to)), + dataType: this.text(typeStart, typeEnd) || null, + value: assign ? this.text(assign.at + assign.size, to) || null : null, + from: name.from, + scope, + definition: false, + container, + }); + } + + private routine(start: number, scope: SymbolScope | null) { + const { tokens } = this; + const kind = tokens[start].key; + const nameIndex = readName(tokens, start + 1); + const name = tokens[nameIndex]; + if (!isIdentifier(name)) return this.statementEnd(start) + 1; + const { items, after } = this.list(nameIndex + 1); + const marker = boundary(tokens, after, routineMarkers); + const returns = tokens[after]?.key === "RETURN" ? tokens.slice(after + 1, marker) : []; + const modifier = returns.findIndex((token) => signatureModifiers.has(token.key)); + if (modifier >= 0) returns.length = modifier; + const parameters = items.map(([from, to]) => format(tokens.slice(from, to))); + const signature = + `${kind} ${this.text(start + 1, nameIndex + 1)}` + + (parameters.length ? `(${parameters.join(", ")})` : "") + + (returns.length ? ` RETURN ${format(returns)}` : ""); + const opensBody = tokens[marker]?.key === "IS" || tokens[marker]?.key === "AS"; + const definition = opensBody && kind !== "CURSOR"; + const routineName = nameOf(name); + const own: SymbolScope = { from: tokens[start].from, to: this.endOf(marker) }; + const symbol: ProgramSymbol = { + kind: kind === "CURSOR" ? "cursor" : kind === "FUNCTION" ? "function" : "procedure", + name: routineName, + signature, + dataType: returns.length ? format(returns) : null, + value: null, + comment: this.comment(start, marker), + from: name.from, + scope, + definition, + container: null, + }; + this.out.push(symbol); + for (const [from, to] of items) this.member(from, to, "parameter", routineName, own); + + if (kind === "CURSOR" && opensBody) { + const end = this.statementEnd(marker + 1); + symbol.query = this.text(marker + 1, end); + own.to = this.endOf(end); + return end + 1; + } + if (!definition) return marker + 1; + own.to = this.source.length; + const stop = this.section(marker + 1, own); + const closing = tokens[stop]?.key === "BEGIN" ? this.blocks.get(stop) : tokens[stop]?.key === "END" ? stop : undefined; + if (closing === undefined) return tokens.length; + const end = this.statementEnd(closing); + own.to = this.endOf(end); + return end + 1; + } + + private anonymousBlock(start: number) { + const scope: SymbolScope = { from: this.tokens[start].from, to: this.source.length }; + const stop = this.section(start + 1, scope); + const closing = this.tokens[stop]?.key === "BEGIN" ? this.blocks.get(stop) : undefined; + if (closing !== undefined) scope.to = this.endOf(this.statementEnd(closing)); + } + + private forLoop(start: number) { + const { tokens } = this; + const name = tokens[start + 1]; + if (!isIdentifier(name) || tokens[start + 2]?.key !== "IN") return; + const loop = boundary(tokens, start + 3, new Set(["LOOP"])); + if (loop >= tokens.length) return; + const closing = this.blocks.get(loop); + const scope: SymbolScope = { + from: tokens[start].from, + to: closing === undefined ? this.source.length : this.endOf(this.statementEnd(closing)), + }; + let first = start + 3; + if (tokens[first]?.key === "REVERSE") first += 1; + const iterator = this.text(first, loop); + let dataType: string | null = null; + let query: string | undefined; + if (tokens[first]?.key === "(") { + query = this.text(first + 1, this.list(first).after - 1); + } else if (iterator.includes("..")) { + dataType = "PLS_INTEGER"; + } else if (isIdentifier(tokens[first])) { + const cursor = tokens[first + 1]?.key === "." && isIdentifier(tokens[first + 2]) + ? `${nameOf(tokens[first])}.${nameOf(tokens[first + 2])}` + : nameOf(tokens[first]); + dataType = `${cursor}%ROWTYPE`; + } + this.push({ + kind: "variable", + name: nameOf(name), + signature: `${name.text} IN ${iterator}`, + dataType, + value: null, + from: name.from, + scope, + definition: false, + container: null, + ...(query === undefined ? {} : { query }), + }); + } +} + +/** Símbolos declarados en el texto: unidad principal, bloques anónimos y variables de FOR. */ +export function programSymbols(source: string): ProgramSymbol[] { + try { + return new Analyzer(source).run(); + } catch { + return []; + } +} From ca171ea61c50e6c9b9af55c5bb81e78e11685849 Mon Sep 17 00:00:00 2001 From: Walter Aquino Date: Fri, 27 Nov 2026 10:42:56 -0300 Subject: [PATCH 06/24] feat(app): WAL-119 camino de nombre de hasta tres partes Co-Authored-By: Claude Opus 5.5 --- app/src/editorReference.test.ts | 47 ++++++++++++++- app/src/editorReference.ts | 104 ++++++++++++++++++++++++++++++++ 2 files changed, 150 insertions(+), 1 deletion(-) diff --git a/app/src/editorReference.test.ts b/app/src/editorReference.test.ts index 495ad15..ff0b896 100644 --- a/app/src/editorReference.test.ts +++ b/app/src/editorReference.test.ts @@ -1,7 +1,7 @@ import { EditorState } from "@codemirror/state"; import { sql } from "@codemirror/lang-sql"; import { expect, test } from "vitest"; -import { editorReference, oracleDialect } from "./editorReference"; +import { editorPath, editorReference, oracleDialect } from "./editorReference"; function reference(source: string, word: string) { const state = EditorState.create({ @@ -42,3 +42,48 @@ test.each([ ])("omite referencias ajenas al catálogo local en %s", (source, token) => { expect(reference(source, token)).toBeNull(); }); + +function path(source: string, word: string) { + const state = EditorState.create({ + doc: source, + extensions: [sql({ dialect: oracleDialect })], + }); + return editorPath(state, source.indexOf(word) + 1); +} + +test("tres partes con el cursor en la del medio", () => { + const source = "x := hr.pkg_ventas.calcular(1);"; + expect(path(source, "pkg_ventas")).toEqual({ + parts: ["HR", "PKG_VENTAS", "CALCULAR"], + index: 1, + from: source.indexOf("pkg_ventas"), + to: source.indexOf("pkg_ventas") + "pkg_ventas".length, + }); +}); + +test("campo de registro tras índice", () => { + expect(path("x := t_tab(i).nombre;", "nombre")).toMatchObject({ + parts: ["T_TAB", "NOMBRE"], + index: 1, + }); + expect(path("x := t_tab(i).nombre;", "t_tab")).toMatchObject({ + parts: ["T_TAB", "NOMBRE"], + index: 0, + }); +}); + +test("comillas conservan mayúsculas", () => { + expect(path('x := "MiPaquete".calcular;', "calcular")).toMatchObject({ + parts: ["MiPaquete", "CALCULAR"], + index: 1, + }); +}); + +test("bind y cuatro partes devuelven null", () => { + expect(path("x := :p_id;", "p_id")).toBeNull(); + expect(path("x := a.b.c.d;", "b")).toBeNull(); +}); + +test("una llamada con argumentos no se une al nombre siguiente", () => { + expect(path("calcular(v_x) ;", "v_x")).toMatchObject({ parts: ["V_X"], index: 0 }); +}); diff --git a/app/src/editorReference.ts b/app/src/editorReference.ts index 8ff79c5..b0e14f2 100644 --- a/app/src/editorReference.ts +++ b/app/src/editorReference.ts @@ -50,3 +50,107 @@ export function editorReference( name: names[names.length - 1], }; } + +/** Nombre de hasta tres partes bajo el cursor, saltando índices: `t_tab(i).campo`. */ +export interface NamePath { + parts: string[]; + /** Parte sobre la que está el cursor. */ + index: number; + from: number; + to: number; +} + +const namePattern = /"[^"]+"|[\p{L}][\p{L}\p{N}_$#]*/uy; +const nameBefore = /(?:"[^"]+"|[\p{L}][\p{L}\p{N}_$#]*)$/u; +const nameKey = (text: string) => + text.startsWith('"') ? text.slice(1, -1) : text.toUpperCase(); + +function skipSpaceBack(text: string, at: number) { + while (at > 0 && /\s/.test(text[at - 1])) at -= 1; + return at; +} + +function skipSpace(text: string, at: number) { + while (at < text.length && /\s/.test(text[at])) at += 1; + return at; +} + +/** Posición tras el paréntesis que cierra el que abre en `at`, o -1. */ +function closeGroup(text: string, at: number) { + let depth = 0; + for (let i = at; i < text.length; i += 1) { + if (text[i] === "(") depth += 1; + else if (text[i] === ")" && --depth === 0) return i + 1; + } + return -1; +} + +/** Posición del paréntesis que abre el que cierra justo antes de `at`, o -1. */ +function openGroup(text: string, at: number) { + let depth = 0; + for (let i = at - 1; i >= 0; i -= 1) { + if (text[i] === ")") depth += 1; + else if (text[i] === "(" && --depth === 0) return i; + } + return -1; +} + +export function editorPath(state: EditorState, position: number): NamePath | null { + const line = state.doc.lineAt(position); + const tree = ensureSyntaxTree(state, line.to, 50); + const token = tree?.resolveInner(position, 1); + if (!token || (token.name !== "Identifier" && token.name !== "QuotedIdentifier")) return null; + + const text = line.text; + const start = token.from - line.from; + const end = token.to - line.from; + const parts: { text: string; from: number; to: number }[] = [ + { text: text.slice(start, end), from: start, to: end }, + ]; + + // Hacia atrás: ". nombre" con un índice opcional entre medio. + for (let at = start; ;) { + const dot = skipSpaceBack(text, at); + if (text[dot - 1] !== ".") break; + let before = skipSpaceBack(text, dot - 1); + if (text[before - 1] === ")") { + const open = openGroup(text, before); + if (open < 0) break; + before = skipSpaceBack(text, open); + } + const match = nameBefore.exec(text.slice(0, before)); + if (!match) break; + const from = before - match[0].length; + parts.unshift({ text: match[0], from, to: before }); + at = from; + } + const index = parts.length - 1; + + // Hacia adelante: índice opcional, ". nombre". + for (let at = end; ;) { + let next = skipSpace(text, at); + if (text[next] === "(") { + const close = closeGroup(text, next); + if (close < 0) break; + const afterGroup = skipSpace(text, close); + if (text[afterGroup] !== ".") break; + next = afterGroup; + } + if (text[next] !== ".") break; + namePattern.lastIndex = skipSpace(text, next + 1); + const match = namePattern.exec(text); + if (!match) break; + parts.push({ text: match[0], from: match.index, to: match.index + match[0].length }); + at = match.index + match[0].length; + } + + if (parts.length > 3) return null; + const first = skipSpaceBack(text, parts[0].from); + if (/[@:]$/.test(text.slice(0, first)) || /^\s*@/.test(text.slice(parts[parts.length - 1].to))) return null; + return { + parts: parts.map((part) => nameKey(part.text)), + index, + from: token.from, + to: token.to, + }; +} From 042b1c8de6e0f59b338fcf8083289aecf102c35d Mon Sep 17 00:00:00 2001 From: Walter Aquino Date: Fri, 27 Nov 2026 10:45:59 -0300 Subject: [PATCH 07/24] =?UTF-8?q?feat(app):=20WAL-119=20fuentes=20de=20s?= =?UTF-8?q?=C3=ADmbolos=20con=20cach=C3=A9=20por=20conexi=C3=B3n?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- app/src/App.tsx | 17 ++++- app/src/components/ProgramWindow.test.tsx | 19 +++++ app/src/components/ProgramWindow.tsx | 13 +++- app/src/symbolSources.test.ts | 90 +++++++++++++++++++++++ app/src/symbolSources.ts | 84 +++++++++++++++++++++ 5 files changed, 221 insertions(+), 2 deletions(-) create mode 100644 app/src/symbolSources.test.ts create mode 100644 app/src/symbolSources.ts diff --git a/app/src/App.tsx b/app/src/App.tsx index 5026fce..1c0e2cd 100644 --- a/app/src/App.tsx +++ b/app/src/App.tsx @@ -4,6 +4,7 @@ import { useCallback, useEffect, useLayoutEffect, + useMemo, useRef, useState, } from "react"; @@ -42,6 +43,7 @@ import { newWindowTemplates } from "./newWindows"; import { TransactionDialog } from "./components/TransactionDialog"; import { UpdateDialog } from "./components/UpdateDialog"; import { UpdateBadge } from "./components/UpdateBadge"; +import { createSymbolSources } from "./symbolSources"; import { runCheck, tauriUpdater, type AvailableUpdate } from "./updater"; import { ThemeDialog, toggleThemeMode } from "./components/ThemeDialog"; import { activeTheme } from "./themes"; @@ -190,6 +192,7 @@ export default function App() { }; const [explorerVisible, setExplorerVisible] = useState(true); const [refreshTick, setRefreshTick] = useState(0); + const symbolSources = useMemo(() => createSymbolSources(api), []); const [notice, setNotice] = useState<{ message: string; kind: "info" | "error" } | null>(null); const noticeTimer = useRef | undefined>(undefined); const errorVisible = useRef(false); @@ -339,7 +342,10 @@ export default function App() { ? () => setPrograms((current) => reorder(current, tabIndex, tabIndex + 1)) : undefined, connect: () => setShowLogin(true), toggleExplorer: active ? () => setExplorerVisible((v) => !v) : undefined, - refreshExplorer: active ? () => setRefreshTick((t) => t + 1) : undefined, + refreshExplorer: active ? () => { + symbolSources.invalidate(active.sessionId); + setRefreshTick((t) => t + 1); + } : undefined, disconnect: active ? () => void disconnect(active.sessionId) : undefined, reconnect: active ? () => void reconnectConnection(active.sessionId) : undefined, customizeUi: () => setShowTheme(true), @@ -457,6 +463,7 @@ export default function App() { try { await api.reconnect(id); setStates((s) => ({ ...s, [id]: "Connected" })); + symbolSources.invalidate(id); setReconnectErrors(({ [id]: _old, ...rest }) => rest); setRefreshTick((t) => t + 1); return true; @@ -1029,6 +1036,7 @@ export default function App() { try { return await api.sqlExecute(id, sql, []); } finally { + symbolSources.invalidate(sessionId); compileSession.current = null; try { await api.sqlClose(id); @@ -1424,6 +1432,13 @@ export default function App() { Cargando editor…

}> symbolSources.register({ + connection: tab.connection!.sessionId, + owner: tab.object!.owner, + name: tab.object!.name, + }, read) + : undefined} readOnly={tab.readOnly} onReadOnlyChange={(readOnly) => updateProgram(tab.id, { readOnly })} fileName={tab.fileName} diff --git a/app/src/components/ProgramWindow.test.tsx b/app/src/components/ProgramWindow.test.tsx index 960f8b0..25aad19 100644 --- a/app/src/components/ProgramWindow.test.tsx +++ b/app/src/components/ProgramWindow.test.tsx @@ -769,3 +769,22 @@ describe("búsqueda y reemplazo desde ProgramActions", () => { expect(view.state.selection.main.from).toBe(firstFrom); }); }); + +test("registra su texto vivo y se da de baja al cerrarse", () => { + const release = vi.fn(); + const registerSource = vi.fn().mockReturnValue(release); + const { unmount } = render( + , + ); + expect(registerSource).toHaveBeenCalledOnce(); + const read = registerSource.mock.calls[0][0] as () => { kind: string; source: string }[]; + const editor = screen.getByRole("textbox", { name: "Spec" }); + const view = EditorView.findFromDOM(editor.closest(".cm-editor")!)!; + act(() => view.dispatch({ changes: { from: 0, insert: "-- nuevo\n" } })); + expect(read()).toEqual([ + { kind: "PACKAGE", source: `-- nuevo\n${parts[0].source}` }, + { kind: "PACKAGE BODY", source: parts[1].source }, + ]); + unmount(); + expect(release).toHaveBeenCalledOnce(); +}); diff --git a/app/src/components/ProgramWindow.tsx b/app/src/components/ProgramWindow.tsx index d9d6c8e..0376bd6 100644 --- a/app/src/components/ProgramWindow.tsx +++ b/app/src/components/ProgramWindow.tsx @@ -18,6 +18,7 @@ import { compileStatement, type CompilationTarget } from "../programScript"; import { programStructure, type DeclarationKind, type ProgramDeclaration } from "../programStructure"; import { useCompletionCatalog } from "../useCompletionCatalog"; import { ContextMenu } from "./ContextMenu"; +import type { SourcePart } from "../symbolSources"; export type ProgramActions = Partial void>> & { hasPending?: () => boolean }; @@ -59,6 +60,8 @@ interface Props { readCurrentProgram?: () => Promise; compilationTarget?: CompilationTarget; compile?: ProgramCompiler; + /** Registra el texto vivo para la ficha y la navegación de otras ventanas. */ + registerSource?: (read: () => SourcePart[]) => () => void; } const caption = (kind: string) => { @@ -98,7 +101,7 @@ interface DeclarationTarget { } export function ProgramWindow({ - parts, readOnly, onReadOnlyChange, onDirty, onWorkspaceChange, ref, fileName, catalog, active = true, readCurrentProgram, compilationTarget, compile, onTestRoutine, + parts, readOnly, onReadOnlyChange, onDirty, onWorkspaceChange, ref, fileName, catalog, active = true, readCurrentProgram, compilationTarget, compile, onTestRoutine, registerSource, }: Props) { const [baselines, setBaselines] = useState(() => parts.map(baselineOf)); const [compiling, setCompiling] = useState(false); @@ -138,6 +141,14 @@ export function ProgramWindow({ const root = useRef(null); const shownParts = useRef(parts); const wasActive = useRef(active); + const liveParts = useRef(parts); + liveParts.current = parts; + const registerRef = useRef(registerSource); + registerRef.current = registerSource; + useEffect(() => registerRef.current?.(() => liveParts.current.map((entry, index) => ({ + kind: entry.kind, + source: views.current[index]?.state.doc.toString() ?? entry.source, + }))), []); function currentTexts() { return parts.map((entry, index) => views.current[index]?.state.doc.toString() ?? entry.source); diff --git a/app/src/symbolSources.test.ts b/app/src/symbolSources.test.ts new file mode 100644 index 0000000..4721501 --- /dev/null +++ b/app/src/symbolSources.test.ts @@ -0,0 +1,90 @@ +import { expect, test, vi } from "vitest"; +import { createSymbolSources } from "./symbolSources"; +import type { ObjectInfo } from "./types"; + +const pkg: ObjectInfo = { + owner: "HR", + name: "PKG", + object_type: "Package", + status: "Valid", + last_ddl_time: "", +}; + +function fakeApi() { + return { + editorObject: vi.fn().mockResolvedValue(pkg), + programSource: vi.fn().mockResolvedValue([ + { kind: "PACKAGE", source: "oracle", last_ddl_time: null, diagnostics: [] }, + ]), + describeColumns: vi.fn().mockResolvedValue([ + { name: "ID", data_type: "NUMBER", nullable: false }, + ]), + }; +} + +test("un objeto abierto se lee del editor, no de Oracle", async () => { + const api = fakeApi(); + const sources = createSymbolSources(api); + sources.register({ connection: "c", owner: "HR", name: "PKG" }, () => [ + { kind: "PACKAGE", source: "nuevo" }, + ]); + expect(await sources.lookup("c", null).parts(pkg)).toEqual([ + { kind: "PACKAGE", source: "nuevo" }, + ]); + expect(api.programSource).not.toHaveBeenCalled(); +}); + +test("la fuente de Oracle se pide una vez por conexión", async () => { + const api = fakeApi(); + const sources = createSymbolSources(api); + const lookup = sources.lookup("c", null); + expect(await lookup.parts(pkg)).toEqual([{ kind: "PACKAGE", source: "oracle" }]); + await lookup.parts(pkg); + expect(api.programSource).toHaveBeenCalledTimes(1); + expect(api.programSource).toHaveBeenCalledWith("c", "Package", "HR", "PKG"); + sources.invalidate("c", "HR", "PKG"); + await lookup.parts(pkg); + expect(api.programSource).toHaveBeenCalledTimes(2); + await sources.lookup("otra", null).parts(pkg); + expect(api.programSource).toHaveBeenCalledTimes(3); +}); + +test("dar de baja vuelve a la caché", async () => { + const api = fakeApi(); + const sources = createSymbolSources(api); + const release = sources.register({ connection: "c", owner: "HR", name: "PKG" }, () => [ + { kind: "PACKAGE", source: "nuevo" }, + ]); + release(); + expect(await sources.lookup("c", null).parts(pkg)).toEqual([ + { kind: "PACKAGE", source: "oracle" }, + ]); +}); + +test("un fallo de fuente devuelve lista vacía", async () => { + const api = fakeApi(); + api.programSource.mockRejectedValueOnce(new Error("ORA-00942")); + const lookup = createSymbolSources(api).lookup("c", null); + expect(await lookup.parts(pkg)).toEqual([]); + expect(await lookup.parts(pkg)).toEqual([{ kind: "PACKAGE", source: "oracle" }]); +}); + +test("columnas cacheadas por conexión", async () => { + const api = fakeApi(); + const lookup = createSymbolSources(api).lookup("c", null); + await lookup.columns("HR", "CLIENTES"); + expect(await lookup.columns("HR", "CLIENTES")).toHaveLength(1); + expect(api.describeColumns).toHaveBeenCalledTimes(1); +}); + +test("objetos del catálogo con el esquema de contexto", async () => { + const api = fakeApi(); + const sources = createSymbolSources(api); + expect(await sources.lookup("c", "HR").object(null, "PKG")).toEqual(pkg); + expect(api.editorObject).toHaveBeenCalledWith("c", { owner: null, name: "PKG" }, "HR"); + await sources.lookup("c", "HR").object(null, "PKG"); + expect(api.editorObject).toHaveBeenCalledTimes(1); + sources.invalidate("c"); + await sources.lookup("c", "HR").object(null, "PKG"); + expect(api.editorObject).toHaveBeenCalledTimes(2); +}); diff --git a/app/src/symbolSources.ts b/app/src/symbolSources.ts new file mode 100644 index 0000000..cf0aaf5 --- /dev/null +++ b/app/src/symbolSources.ts @@ -0,0 +1,84 @@ +import type { api as appApi } from "./api"; +import type { ObjectColumn, ObjectInfo } from "./types"; + +export interface SourcePart { + /** Como `ProgramPart.kind`: "PACKAGE", "PACKAGE BODY", "SQL"… */ + kind: string; + source: string; +} + +export interface ObjectKey { + connection: string; + owner: string; + name: string; +} + +export interface SymbolLookup { + object(owner: string | null, name: string): Promise; + /** Lista vacía: fuente no disponible. */ + parts(object: ObjectInfo): Promise; + columns(owner: string, name: string): Promise; +} + +export interface SymbolSources { + /** Registra el texto vivo de un objeto abierto; devuelve la función para darlo de baja. */ + register(key: ObjectKey, read: () => SourcePart[]): () => void; + lookup(connection: string, contextOwner: string | null): SymbolLookup; + invalidate(connection: string, owner?: string, name?: string): void; +} + +export type SymbolApi = Pick; + +const keyOf = (...parts: (string | null)[]) => JSON.stringify(parts); + +/** Fuentes para resolver nombres: editores abiertos primero, después Oracle con caché por conexión. */ +export function createSymbolSources(api: SymbolApi): SymbolSources { + const open = new Map SourcePart[]>(); + const cache = new Map }>(); + + function cached(connection: string, owner: string | null, name: string, kind: string, load: () => Promise) { + const key = keyOf(kind, connection, owner, name); + const hit = cache.get(key); + if (hit) return hit.value as Promise; + const value = load(); + cache.set(key, { connection, owner, name, value }); + value.catch(() => { if (cache.get(key)?.value === value) cache.delete(key); }); + return value; + } + + return { + register(key, read) { + const id = keyOf(key.connection, key.owner, key.name); + open.set(id, read); + return () => { if (open.get(id) === read) open.delete(id); }; + }, + lookup(connection, contextOwner) { + return { + object: (owner, name) => + cached(connection, owner ?? contextOwner, name, "object", () => + api.editorObject(connection, { owner, name }, contextOwner)), + parts: async (object) => { + const live = open.get(keyOf(connection, object.owner, object.name)); + if (live) return live(); + try { + const parts = await cached(connection, object.owner, object.name, "source", () => + api.programSource(connection, object.object_type, object.owner, object.name)); + return parts.map(({ kind, source }) => ({ kind, source })); + } catch { + return []; + } + }, + columns: (owner, name) => + cached(connection, owner, name, "columns", () => api.describeColumns(connection, owner, name)), + }; + }, + invalidate(connection, owner, name) { + for (const [key, entry] of cache) { + if (entry.connection !== connection) continue; + if (owner !== undefined && entry.owner !== owner) continue; + if (name !== undefined && entry.name !== name) continue; + cache.delete(key); + } + }, + }; +} From ec998580d78514cfa1018cfa4d32d107cab82bdc Mon Sep 17 00:00:00 2001 From: Walter Aquino Date: Fri, 27 Nov 2026 10:49:47 -0300 Subject: [PATCH 08/24] =?UTF-8?q?feat(app):=20WAL-119=20resoluci=C3=B3n=20?= =?UTF-8?q?de=20nombres=20con=20campos=20y=20columnas?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- app/src/symbolResolve.test.ts | 178 +++++++++++++++++ app/src/symbolResolve.ts | 360 ++++++++++++++++++++++++++++++++++ 2 files changed, 538 insertions(+) create mode 100644 app/src/symbolResolve.test.ts create mode 100644 app/src/symbolResolve.ts diff --git a/app/src/symbolResolve.test.ts b/app/src/symbolResolve.test.ts new file mode 100644 index 0000000..57e188b --- /dev/null +++ b/app/src/symbolResolve.test.ts @@ -0,0 +1,178 @@ +import { expect, test, vi } from "vitest"; +import { resolveSymbol, type ResolveContext } from "./symbolResolve"; +import type { SourcePart, SymbolLookup } from "./symbolSources"; +import type { ObjectColumn, ObjectInfo, ObjectType } from "./types"; + +const info = (name: string, object_type: ObjectType, owner = "HR"): ObjectInfo => ({ + owner, name, object_type, status: "Valid", last_ddl_time: "", +}); + +const clientes: ObjectColumn[] = [ + { name: "ID", data_type: "NUMBER", nullable: false }, + { name: "NOMBRE", data_type: "VARCHAR2(100)", nullable: true }, +]; + +function fakeLookup( + objects: Record = {}, + sources: Record = {}, +): SymbolLookup & { object: ReturnType } { + return { + object: vi.fn(async (owner: string | null, name: string) => + objects[owner ? `${owner}.${name}` : name] ?? null), + parts: vi.fn(async (object: ObjectInfo) => sources[object.name] ?? []), + columns: vi.fn(async (_owner: string, name: string) => (name === "CLIENTES" ? clientes : [])), + }; +} + +/** Contexto con el cursor sobre la aparición número `nth` de `word` en la parte `current`. */ +function at( + texts: string[], + word: string, + options: { current?: number; nth?: number; lookup?: SymbolLookup | null; kinds?: string[] } = {}, +): ResolveContext { + const current = options.current ?? texts.length - 1; + let position = -1; + for (let n = 0; n <= (options.nth ?? 0); n += 1) position = texts[current].indexOf(word, position + 1); + const kinds = options.kinds ?? (texts.length === 2 ? ["PACKAGE", "PACKAGE BODY"] : ["SQL"]); + return { + parts: texts.map((source, index) => ({ kind: kinds[index], source })), + current, + position: position + 1, + self: null, + lookup: options.lookup === undefined ? fakeLookup() : options.lookup, + }; +} + +const path = (parts: string[], index = parts.length - 1) => ({ parts, index, from: 0, to: 0 }); + +test("local tapa a global dentro de su bloque", async () => { + const body = + "PACKAGE BODY pkg IS\n v NUMBER;\n PROCEDURE p IS v VARCHAR2(1); BEGIN v := 'x'; END;\n PROCEDURE q IS BEGIN v := 1; END;\nEND;"; + const inside = await resolveSymbol(at(["PACKAGE pkg IS END;", body], "v :=", {}), path(["V"])); + expect(inside).toHaveLength(1); + expect(inside[0]).toMatchObject({ kind: "symbol", symbol: { dataType: "VARCHAR2(1)" } }); + const outside = await resolveSymbol(at(["PACKAGE pkg IS END;", body], "v :=", { nth: 1 }), path(["V"])); + expect(outside).toHaveLength(1); + expect(outside[0]).toMatchObject({ kind: "symbol", symbol: { dataType: "NUMBER" } }); +}); + +test("llamada a rutina del mismo paquete devuelve spec y body", async () => { + const spec = "PACKAGE pkg IS\n FUNCTION calcular RETURN NUMBER;\nEND;"; + const body = + "PACKAGE BODY pkg IS\n FUNCTION calcular RETURN NUMBER IS BEGIN RETURN 1; END;\n PROCEDURE p IS x NUMBER; BEGIN x := calcular; END;\nEND;"; + const found = await resolveSymbol(at([spec, body], "calcular;"), path(["CALCULAR"])); + expect(found.map((item) => item.kind === "symbol" && item.location)).toEqual([ + { where: "here", part: 0, from: spec.indexOf("calcular"), line: 2 }, + { where: "here", part: 1, from: body.indexOf("calcular"), line: 2 }, + ]); +}); + +test("miembro de otro paquete", async () => { + const lookup = fakeLookup( + { PKG_VENTAS: info("PKG_VENTAS", "Package") }, + { PKG_VENTAS: [{ kind: "PACKAGE", source: "PACKAGE pkg_ventas IS\n c_max CONSTANT NUMBER := 3;\nEND;" }] }, + ); + const found = await resolveSymbol( + at(["BEGIN x := pkg_ventas.c_max; END;"], "c_max", { lookup }), + path(["PKG_VENTAS", "C_MAX"]), + ); + expect(lookup.object).toHaveBeenCalledWith(null, "PKG_VENTAS"); + expect(found).toHaveLength(1); + expect(found[0]).toMatchObject({ + kind: "symbol", + symbol: { name: "C_MAX", value: "3" }, + location: { where: "object", partKind: "PACKAGE", line: 2, object: { name: "PKG_VENTAS" } }, + }); +}); + +test("campo de %ROWTYPE de tabla", async () => { + const lookup = fakeLookup({ CLIENTES: info("CLIENTES", "Table") }); + const found = await resolveSymbol( + at(["DECLARE v_cli clientes%ROWTYPE; BEGIN x := v_cli.nombre; END;"], "nombre", { lookup }), + path(["V_CLI", "NOMBRE"]), + ); + expect(found).toEqual([ + { kind: "column", table: "CLIENTES", column: { name: "NOMBRE", data_type: "VARCHAR2(100)", nullable: true } }, + ]); +}); + +test("campo de registro propio", async () => { + const source = + "DECLARE TYPE t_rec IS RECORD (id NUMBER, nombre VARCHAR2(5)); v_r t_rec; BEGIN x := v_r.id; END;"; + const found = await resolveSymbol(at([source], "id;"), path(["V_R", "ID"])); + expect(found).toHaveLength(1); + expect(found[0]).toMatchObject({ kind: "symbol", symbol: { kind: "field", name: "ID", container: "T_REC" } }); +}); + +test("campo tras índice de colección", async () => { + const source = + "DECLARE TYPE t_rec IS RECORD (id NUMBER); TYPE t_tab IS TABLE OF t_rec INDEX BY PLS_INTEGER; v t_tab; BEGIN x := v(1).id; END;"; + const found = await resolveSymbol(at([source], "id;"), path(["V", "ID"])); + expect(found[0]).toMatchObject({ kind: "symbol", symbol: { kind: "field", name: "ID" } }); +}); + +test("columna de cursor en FOR", async () => { + const lookup = fakeLookup({ CLIENTES: info("CLIENTES", "Table") }); + const source = + "DECLARE CURSOR c_cli IS SELECT id, nombre n, id * 2 doble FROM clientes; BEGIN FOR r IN c_cli LOOP x := r.n; y := r.doble; END LOOP; END;"; + const named = await resolveSymbol(at([source], "n;", { lookup }), path(["R", "N"])); + expect(named).toEqual([ + { kind: "column", table: "CLIENTES", column: { name: "NOMBRE", data_type: "VARCHAR2(100)", nullable: true } }, + ]); + const expression = await resolveSymbol(at([source], "doble;", { lookup }), path(["R", "DOBLE"])); + expect(expression).toEqual([ + { kind: "column", table: "C_CLI", column: { name: "DOBLE", data_type: "Expresión", nullable: true } }, + ]); +}); + +test("alias en SELECT", async () => { + const lookup = fakeLookup({ CLIENTES: info("CLIENTES", "Table") }); + const found = await resolveSymbol( + at(["SELECT c.nombre FROM clientes c"], "nombre", { lookup }), + path(["C", "NOMBRE"]), + ); + expect(found).toEqual([ + { kind: "column", table: "CLIENTES", column: { name: "NOMBRE", data_type: "VARCHAR2(100)", nullable: true } }, + ]); +}); + +test("tabla devuelve sus columnas", async () => { + const lookup = fakeLookup({ CLIENTES: info("CLIENTES", "Table") }); + const found = await resolveSymbol(at(["SELECT * FROM clientes"], "clientes", { lookup }), path(["CLIENTES"])); + expect(found).toEqual([{ kind: "relation", object: info("CLIENTES", "Table"), columns: clientes }]); +}); + +test("mayúsculas y comillas", async () => { + const lookup = fakeLookup(); + await resolveSymbol(at(["BEGIN PKG_Ventas.CALCULAR; END;"], "CALCULAR", { lookup }), path(["PKG_VENTAS", "CALCULAR"])); + await resolveSymbol(at(['BEGIN "MiPaquete".calcular; END;'], "calcular", { lookup }), path(["MiPaquete", "CALCULAR"])); + expect(lookup.object).toHaveBeenCalledWith(null, "PKG_VENTAS"); + expect(lookup.object).toHaveBeenCalledWith(null, "MiPaquete"); +}); + +test("esquema, paquete y rutina", async () => { + const lookup = fakeLookup( + { "HR.PKG_VENTAS": info("PKG_VENTAS", "Package") }, + { PKG_VENTAS: [{ kind: "PACKAGE", source: "PACKAGE pkg_ventas IS\n PROCEDURE calcular;\nEND;" }] }, + ); + const found = await resolveSymbol( + at(["BEGIN hr.pkg_ventas.calcular; END;"], "calcular", { lookup }), + path(["HR", "PKG_VENTAS", "CALCULAR"]), + ); + expect(found[0]).toMatchObject({ kind: "symbol", symbol: { name: "CALCULAR" }, location: { where: "object" } }); +}); + +test("sin conexión o con error solo lo local", async () => { + const offline = await resolveSymbol(at(["BEGIN pkg.f; END;"], "f;", { lookup: null }), path(["PKG", "F"])); + expect(offline).toEqual([]); + const failing = fakeLookup(); + failing.object.mockRejectedValue(new Error("ORA-03113")); + const broken = await resolveSymbol(at(["BEGIN pkg.f; END;"], "f;", { lookup: failing }), path(["PKG", "F"])); + expect(broken).toEqual([]); +}); + +test("fuente envuelta", async () => { + const lookup = fakeLookup({ PKG_W: info("PKG_W", "Package") }); + const found = await resolveSymbol(at(["BEGIN pkg_w.f; END;"], "pkg_w", { lookup }), path(["PKG_W", "F"], 0)); + expect(found).toEqual([{ kind: "object", object: info("PKG_W", "Package"), note: "Fuente no disponible" }]); +}); diff --git a/app/src/symbolResolve.ts b/app/src/symbolResolve.ts new file mode 100644 index 0000000..aec1d0b --- /dev/null +++ b/app/src/symbolResolve.ts @@ -0,0 +1,360 @@ +import type { NamePath } from "./editorReference"; +import { statementAliases, statementTables } from "./programCompletion"; +import { isIdentifier, nameOf, tokenize, type Token } from "./programStructure"; +import { programSymbols, type ProgramSymbol } from "./programSymbols"; +import type { SourcePart, SymbolLookup } from "./symbolSources"; +import type { ObjectColumn, ObjectInfo, ObjectType } from "./types"; + +export type SymbolLocation = + | { where: "here"; part: number; from: number; line: number } + | { where: "object"; object: ObjectInfo; partKind: string; from: number; line: number }; + +export type Resolved = + | { kind: "symbol"; symbol: ProgramSymbol; location: SymbolLocation } + | { kind: "column"; table: string; column: ObjectColumn } + | { kind: "relation"; object: ObjectInfo; columns: ObjectColumn[] } + | { kind: "object"; object: ObjectInfo; note: "Fuente no disponible" }; + +export interface ResolveContext { + /** Partes del documento abierto (SQL: una sola). */ + parts: SourcePart[]; + /** Parte donde está el cursor. */ + current: number; + /** Posición dentro de esa parte. */ + position: number; + /** Objeto del documento abierto, si lo es. */ + self: ObjectInfo | null; + /** null sin conexión. */ + lookup: SymbolLookup | null; +} + +const relationTypes = new Set(["Table", "View", "MaterializedView"]); +const programTypes = new Set(["Package", "Function", "Procedure", "Type", "Trigger"]); +const memberKinds = new Set(["field", "parameter"]); +const MAX_DEPTH = 6; + +const cache = new Map(); +function symbolsOf(source: string) { + const hit = cache.get(source); + if (hit) { + cache.delete(source); + cache.set(source, hit); + return hit; + } + const symbols = programSymbols(source); + cache.set(source, symbols); + if (cache.size > 16) cache.delete(cache.keys().next().value!); + return symbols; +} + +/** Unidad donde se buscan símbolos: el documento abierto o un objeto de la base. */ +interface Home { + parts: SourcePart[]; + symbols: ProgramSymbol[][]; + object: ObjectInfo | null; +} + +type Entity = + | { t: "unit"; home: Home } + | { t: "record"; home: Home; dataType: string } + | { t: "query"; home: Home; query: string; label: string } + | { t: "relation"; owner: string | null; name: string } + | { t: "schema"; owner: string }; + +const homeOf = (parts: SourcePart[], object: ObjectInfo | null): Home => ({ + parts, + symbols: parts.map((part) => symbolsOf(part.source)), + object, +}); + +function lineAt(source: string, from: number) { + let line = 1; + for (let i = source.indexOf("\n"); i >= 0 && i < from; i = source.indexOf("\n", i + 1)) line += 1; + return line; +} + +function located(home: Home, part: number, symbol: ProgramSymbol): Resolved { + const line = lineAt(home.parts[part].source, symbol.from); + return { + kind: "symbol", + symbol, + location: home.object + ? { where: "object", object: home.object, partKind: home.parts[part].kind, from: symbol.from, line } + : { where: "here", part, from: symbol.from, line }, + }; +} + +/** Nombre con puntos, respetando comillas: `hr."Mi Tabla"` → ["HR", "Mi Tabla"]. */ +function nameParts(text: string) { + return (text.trim().match(/"[^"]+"|[^.\s]+/g) ?? []).map((part) => + part.startsWith('"') ? part.slice(1, -1) : part.toUpperCase()); +} + +/** Miembros de nivel de unidad (scope null) con ese nombre, en todas las partes. */ +function unitMembers(home: Home, name: string, kinds?: Set) { + const found: Resolved[] = []; + home.symbols.forEach((symbols, part) => { + for (const symbol of symbols) { + if (symbol.name !== name || symbol.scope || memberKinds.has(symbol.kind)) continue; + if (kinds && !kinds.has(symbol.kind)) continue; + found.push(located(home, part, symbol)); + } + }); + return found; +} + +function findSymbol(home: Home, name: string, kinds: Set) { + for (let part = 0; part < home.symbols.length; part += 1) { + const symbol = home.symbols[part].find((item) => item.name === name && kinds.has(item.kind)); + if (symbol) return { part, symbol }; + } + return null; +} + +const typeKinds = new Set(["type", "subtype"]); +const valueKinds = new Set(["variable", "constant", "parameter"]); +const cursorKinds = new Set(["cursor"]); + +class Resolver { + private readonly here: Home; + + constructor(private readonly ctx: ResolveContext) { + this.here = homeOf(ctx.parts, ctx.self); + } + + private async safe(load: (lookup: SymbolLookup) => Promise, fallback: T): Promise { + const { lookup } = this.ctx; + if (!lookup) return fallback; + try { + return await load(lookup); + } catch { + return fallback; + } + } + + private object(owner: string | null, name: string) { + return this.safe((lookup) => lookup.object(owner, name), null); + } + + private async columns(owner: string | null, name: string) { + const realOwner = owner ?? (await this.object(null, name))?.owner; + if (!realOwner) return []; + return this.safe((lookup) => lookup.columns(realOwner, name), [] as ObjectColumn[]); + } + + private async home(object: ObjectInfo) { + const parts = await this.safe((lookup) => lookup.parts(object), [] as SourcePart[]); + return parts.length ? homeOf(parts, object) : null; + } + + /** Símbolos visibles en el cursor: el alcance local más interno, o el nivel de unidad. */ + private visible(name: string): Resolved[] { + const { current, position } = this.ctx; + const local = (this.here.symbols[current] ?? []).filter( + (symbol) => symbol.name === name && symbol.kind !== "field" && symbol.scope && + symbol.scope.from <= position && position <= symbol.scope.to, + ); + if (local.length) { + const size = (symbol: ProgramSymbol) => symbol.scope!.to - symbol.scope!.from; + const inner = Math.min(...local.map(size)); + return local.filter((symbol) => size(symbol) === inner).map((symbol) => located(this.here, current, symbol)); + } + return unitMembers(this.here, name); + } + + private async objectResult(object: ObjectInfo): Promise { + if (relationTypes.has(object.object_type)) { + return [{ kind: "relation", object, columns: await this.columns(object.owner, object.name) }]; + } + if (!programTypes.has(object.object_type)) return []; + const home = await this.home(object); + if (!home) return [{ kind: "object", object, note: "Fuente no disponible" }]; + return unitMembers(home, object.name); + } + + private async entityFromObject(object: ObjectInfo | null, fallbackSchema: string | null): Promise { + if (!object) return fallbackSchema ? { t: "schema", owner: fallbackSchema } : null; + if (relationTypes.has(object.object_type)) return { t: "relation", owner: object.owner, name: object.name }; + if (object.object_type !== "Package") return null; + const home = await this.home(object); + return home ? { t: "unit", home } : null; + } + + /** Entidad de un símbolo del documento abierto. */ + private entityFromSymbol(found: Resolved | undefined): Entity | null { + if (found?.kind !== "symbol") return null; + const { symbol } = found; + const home = this.here; + if (symbol.kind === "package") return { t: "unit", home }; + if (symbol.query !== undefined && !symbol.dataType) { + return { t: "query", home, query: symbol.query, label: symbol.name }; + } + return symbol.dataType ? { t: "record", home, dataType: symbol.dataType } : null; + } + + private async firstEntity(name: string): Promise { + const visible = this.visible(name); + const fromSymbol = this.entityFromSymbol(visible.find((item) => + item.kind === "symbol" && (valueKinds.has(item.symbol.kind) || item.symbol.kind === "package"))); + if (fromSymbol) return fromSymbol; + const { current, position } = this.ctx; + const table = statementAliases(this.ctx.parts[current]?.source ?? "", position).get(name); + if (table) return { t: "relation", owner: table.owner, name: table.name }; + if (!this.ctx.lookup) return null; + return this.entityFromObject(await this.object(null, name), name); + } + + private async memberEntity(entity: Entity, name: string): Promise { + if (entity.t === "schema") return this.entityFromObject(await this.object(entity.owner, name), null); + if (entity.t === "unit") { + const [found] = unitMembers(entity.home, name, valueKinds); + return found?.kind === "symbol" && found.symbol.dataType + ? { t: "record", home: entity.home, dataType: found.symbol.dataType } + : null; + } + if (entity.t === "record") { + const [found] = await this.typeMembers(entity.home, entity.dataType, name, 0); + return found?.kind === "symbol" && found.symbol.dataType + ? { t: "record", home: entity.home, dataType: found.symbol.dataType } + : null; + } + return null; + } + + private async members(entity: Entity, name: string): Promise { + switch (entity.t) { + case "schema": { + const object = await this.object(entity.owner, name); + return object ? this.objectResult(object) : []; + } + case "unit": + return unitMembers(entity.home, name); + case "relation": { + const column = (await this.columns(entity.owner, entity.name)).find((item) => item.name === name); + return column ? [{ kind: "column", table: entity.name, column }] : []; + } + case "record": + return this.typeMembers(entity.home, entity.dataType, name, 0); + case "query": + return this.queryColumn(entity.query, name, entity.label); + } + } + + /** Campo `name` de un valor de tipo `dataType` declarado en `home`. */ + private async typeMembers(home: Home, dataType: string, name: string, depth: number): Promise { + if (depth > MAX_DEPTH) return []; + const text = dataType.trim(); + const rowType = /^(.+)%ROWTYPE$/i.exec(text); + if (rowType) { + const base = nameParts(rowType[1]); + if (base.length === 1) { + const cursor = findSymbol(home, base[0], cursorKinds); + if (cursor?.symbol.query) return this.queryColumn(cursor.symbol.query, name, cursor.symbol.name); + } + const table = base[base.length - 1]; + const column = (await this.columns(base.length > 1 ? base[0] : null, table)).find((item) => item.name === name); + return column ? [{ kind: "column", table, column }] : []; + } + const anchored = /^(.+)%TYPE$/i.exec(text); + if (anchored) { + const base = nameParts(anchored[1]); + const variable = base.length === 1 ? findSymbol(home, base[0], valueKinds) : null; + return variable?.symbol.dataType + ? this.typeMembers(home, variable.symbol.dataType, name, depth + 1) + : []; + } + const collection = + /^(?:TABLE|VARRAY\s*\([^)]*\)|VARYING\s+ARRAY\s*\([^)]*\))\s+OF\s+(.+?)(?:\s+INDEX\s+BY\s+[\s\S]*)?(?:\s+NOT\s+NULL)?$/i.exec(text); + if (collection) return this.typeMembers(home, collection[1], name, depth + 1); + + const base = nameParts(text); + let typeHome: Home | null = home; + if (base.length === 2) { + const object = await this.object(null, base[0]); + typeHome = object?.object_type === "Package" ? await this.home(object) : null; + } else if (base.length !== 1) { + return []; + } + if (!typeHome) return []; + const type = findSymbol(typeHome, base[base.length - 1], typeKinds); + if (!type) return []; + if (type.symbol.kind === "type" && /^RECORD\b/i.test(type.symbol.dataType ?? "")) { + return typeHome.symbols[type.part] + .filter((symbol) => symbol.kind === "field" && symbol.container === type.symbol.name && symbol.name === name) + .map((symbol) => located(typeHome, type.part, symbol)); + } + return type.symbol.dataType ? this.typeMembers(typeHome, type.symbol.dataType, name, depth + 1) : []; + } + + /** Columna `name` de la lista de un SELECT; tipo de la tabla si es una columna simple. */ + private async queryColumn(query: string, name: string, label: string): Promise { + const tokens = tokenize(query); + const select = tokens.findIndex((token) => token.key === "SELECT"); + if (select < 0) return []; + const items: Token[][] = []; + let depth = 0; + let item: Token[] = []; + for (let i = select + 1; i < tokens.length; i += 1) { + const { key } = tokens[i]; + if (key === "(") depth += 1; + if (key === ")") depth -= 1; + if (depth === 0 && (key === "FROM" || key === "INTO")) break; + if (depth === 0 && key === ",") { + items.push(item); + item = []; + } else { + item.push(tokens[i]); + } + } + items.push(item); + + for (const entry of items) { + if (!entry.length) continue; + const last = entry[entry.length - 1]; + const before = entry[entry.length - 2]; + const aliased = entry.length > 1 && isIdentifier(last) && before.key !== "." && before.key !== "%"; + const expression = aliased ? entry.slice(0, before.key === "AS" ? -2 : -1) : entry; + const simple = + (expression.length === 1 && isIdentifier(expression[0])) || + (expression.length === 3 && isIdentifier(expression[0]) && expression[1].key === "." && isIdentifier(expression[2])); + const columnName = simple ? nameOf(expression[expression.length - 1]) : null; + if ((aliased ? nameOf(last) : columnName) !== name) continue; + if (!columnName) return [{ kind: "column", table: label, column: { name, data_type: "Expresión", nullable: true } }]; + + const qualifier = expression.length === 3 ? nameOf(expression[0]) : null; + const tables = statementTables(query, tokens[select].from); + const table = qualifier + ? tables.find((entry) => entry.alias === qualifier || entry.ref.name === qualifier) + : tables.length === 1 ? tables[0] : undefined; + if (!table) return [{ kind: "column", table: label, column: { name, data_type: "Expresión", nullable: true } }]; + const column = (await this.columns(table.ref.owner, table.ref.name)).find((entry) => entry.name === columnName); + return column + ? [{ kind: "column", table: table.ref.name, column }] + : [{ kind: "column", table: label, column: { name, data_type: "Expresión", nullable: true } }]; + } + return []; + } + + async resolve(path: NamePath): Promise { + const target = path.parts[path.index]; + if (path.index === 0) { + const visible = this.visible(target); + if (visible.length) return visible; + if (!this.ctx.lookup) return []; + const object = await this.object(null, target); + return object ? this.objectResult(object) : []; + } + let entity = await this.firstEntity(path.parts[0]); + for (let i = 1; entity && i < path.index; i += 1) entity = await this.memberEntity(entity, path.parts[i]); + return entity ? this.members(entity, target) : []; + } +} + +/** Busca el nombre bajo el cursor: alcance local, el paquete abierto y después la base. Nunca rechaza. */ +export async function resolveSymbol(ctx: ResolveContext, path: NamePath): Promise { + try { + return await new Resolver(ctx).resolve(path); + } catch { + return []; + } +} From 0b7c56890889258fb2944dec2b64211be078a729 Mon Sep 17 00:00:00 2001 From: Walter Aquino Date: Fri, 27 Nov 2026 10:54:11 -0300 Subject: [PATCH 09/24] =?UTF-8?q?feat(app):=20WAL-119=20ficha=20de=20s?= =?UTF-8?q?=C3=ADmbolo=20al=20pasar=20el=20mouse?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- app/src/App.tsx | 6 ++ app/src/components/ProgramEditor.tsx | 4 + app/src/components/ProgramWindow.test.tsx | 12 +++ app/src/components/ProgramWindow.tsx | 29 +++++- app/src/components/SymbolCard.css | 59 ++++++++++++ app/src/components/SymbolCard.test.tsx | 61 +++++++++++++ app/src/components/SymbolCard.tsx | 104 ++++++++++++++++++++++ app/src/keymap.ts | 2 + app/src/symbolHover.test.ts | 29 ++++++ app/src/symbolHover.ts | 89 ++++++++++++++++++ app/src/symbolResolve.test.ts | 6 ++ app/src/symbolResolve.ts | 6 +- 12 files changed, 400 insertions(+), 7 deletions(-) create mode 100644 app/src/components/SymbolCard.css create mode 100644 app/src/components/SymbolCard.test.tsx create mode 100644 app/src/components/SymbolCard.tsx create mode 100644 app/src/symbolHover.test.ts create mode 100644 app/src/symbolHover.ts diff --git a/app/src/App.tsx b/app/src/App.tsx index 1c0e2cd..e79ba06 100644 --- a/app/src/App.tsx +++ b/app/src/App.tsx @@ -275,6 +275,7 @@ export default function App() { "body", "sideBySide", "goToDeclaration", + "showSymbolCard", "foldBlock", "unfoldBlock", "objectActions", @@ -314,6 +315,7 @@ export default function App() { [ "save", "goToDeclaration", + "showSymbolCard", "foldBlock", "unfoldBlock", "goToLine", @@ -1432,6 +1434,10 @@ export default function App() { Cargando editor…

}> symbolSources.register({ connection: tab.connection!.sessionId, diff --git a/app/src/components/ProgramEditor.tsx b/app/src/components/ProgramEditor.tsx index ec3f76d..02c0b73 100644 --- a/app/src/components/ProgramEditor.tsx +++ b/app/src/components/ProgramEditor.tsx @@ -16,6 +16,7 @@ import { sql } from "@codemirror/lang-sql"; import { tags } from "@lezer/highlight"; import type { ProgramPart } from "../types"; import { editorReference, oracleDialect, type EditorReference } from "../editorReference"; +import { symbolHover, type ContextFor } from "../symbolHover"; import { programFolding } from "../programFolding"; import { catalogCompletion, keywordCompletion, type CompletionCatalog } from "../programCompletion"; import { editorSearch } from "./EditorSearch"; @@ -81,6 +82,8 @@ interface Props { onSelection?: (head: number) => void; /** Marcas con posiciones absolutas; reemplazan a los diagnósticos de la parte. */ markers?: EditorMarker[]; + /** Contexto para la ficha de símbolos; sin él no hay ficha. */ + symbolContext?: ContextFor; } function markerDiagnostics(markers: EditorMarker[], length: number): Diagnostic[] { @@ -173,6 +176,7 @@ export function ProgramEditor(props: Props) { to: "a", "folded code": "Código plegado", unfold: "Desplegar", }), EditorState.allowMultipleSelections.of(true), + symbolHover(() => latest.current.symbolContext ?? null), EditorView.domEventHandlers({ focus: () => { latest.current.activate(); }, keydown: (event) => { diff --git a/app/src/components/ProgramWindow.test.tsx b/app/src/components/ProgramWindow.test.tsx index 25aad19..16943dd 100644 --- a/app/src/components/ProgramWindow.test.tsx +++ b/app/src/components/ProgramWindow.test.tsx @@ -788,3 +788,15 @@ test("registra su texto vivo y se da de baja al cerrarse", () => { unmount(); expect(release).toHaveBeenCalledOnce(); }); + +test("Mostrar ficha abre la ficha de la constante en el cursor", async () => { + const source = "PACKAGE PKG_A AS\n c_max CONSTANT NUMBER := 3;\n PROCEDURE p(x NUMBER := c_max);\nEND;"; + const ref = createRef(); + render(); + const editor = screen.getByRole("textbox", { name: "Spec" }); + const view = EditorView.findFromDOM(editor.closest(".cm-editor")!)!; + act(() => view.dispatch({ selection: { anchor: source.lastIndexOf("c_max") + 1 } })); + act(() => ref.current!.showSymbolCard!()); + expect(await screen.findByText("NUMBER := 3")).toBeInTheDocument(); + expect(screen.getByText("línea 2")).toBeInTheDocument(); +}); diff --git a/app/src/components/ProgramWindow.tsx b/app/src/components/ProgramWindow.tsx index 0376bd6..001bf41 100644 --- a/app/src/components/ProgramWindow.tsx +++ b/app/src/components/ProgramWindow.tsx @@ -18,7 +18,8 @@ import { compileStatement, type CompilationTarget } from "../programScript"; import { programStructure, type DeclarationKind, type ProgramDeclaration } from "../programStructure"; import { useCompletionCatalog } from "../useCompletionCatalog"; import { ContextMenu } from "./ContextMenu"; -import type { SourcePart } from "../symbolSources"; +import type { SourcePart, SymbolLookup } from "../symbolSources"; +import { showSymbolCard, type ContextFor } from "../symbolHover"; export type ProgramActions = Partial void>> & { hasPending?: () => boolean }; @@ -62,6 +63,10 @@ interface Props { compile?: ProgramCompiler; /** Registra el texto vivo para la ficha y la navegación de otras ventanas. */ registerSource?: (read: () => SourcePart[]) => () => void; + /** Catálogo para la ficha y la navegación; null o ausente: solo lo del documento. */ + symbols?: SymbolLookup | null; + /** Objeto que muestra la ventana, para ubicar sus propias declaraciones. */ + symbolSelf?: Pick | null; } const caption = (kind: string) => { @@ -101,7 +106,7 @@ interface DeclarationTarget { } export function ProgramWindow({ - parts, readOnly, onReadOnlyChange, onDirty, onWorkspaceChange, ref, fileName, catalog, active = true, readCurrentProgram, compilationTarget, compile, onTestRoutine, registerSource, + parts, readOnly, onReadOnlyChange, onDirty, onWorkspaceChange, ref, fileName, catalog, active = true, readCurrentProgram, compilationTarget, compile, onTestRoutine, registerSource, symbols, symbolSelf, }: Props) { const [baselines, setBaselines] = useState(() => parts.map(baselineOf)); const [compiling, setCompiling] = useState(false); @@ -145,10 +150,24 @@ export function ProgramWindow({ liveParts.current = parts; const registerRef = useRef(registerSource); registerRef.current = registerSource; - useEffect(() => registerRef.current?.(() => liveParts.current.map((entry, index) => ({ + const liveSources = useCallback(() => liveParts.current.map((entry, index) => ({ kind: entry.kind, source: views.current[index]?.state.doc.toString() ?? entry.source, - }))), []); + })), []); + useEffect(() => registerRef.current?.(liveSources), [liveSources]); + const symbolRefs = useRef({ symbols, symbolSelf }); + symbolRefs.current = { symbols, symbolSelf }; + const symbolContext = useCallback((view, position) => { + const current = views.current.indexOf(view); + if (current < 0) return null; + return { + parts: liveSources(), + current, + position, + self: symbolRefs.current.symbolSelf ?? null, + lookup: symbolRefs.current.symbols ?? null, + }; + }, [liveSources]); function currentTexts() { return parts.map((entry, index) => views.current[index]?.state.doc.toString() ?? entry.source); @@ -481,6 +500,7 @@ export function ProgramWindow({ setObjectMenu({ reference, x: coords.left, y: coords.bottom, id: ++objectRequestId.current }); }) : undefined, complete: readOnly ? undefined : runInEditor(startCompletion), + showSymbolCard: runInEditor(showSymbolCard), goToLine: runInEditor(gotoLine), find: runInEditor(openFind), findNext: runInEditor(findNextMatch), @@ -597,6 +617,7 @@ export function ProgramWindow({ {split && {caption(entry.kind)}} ): ProgramSymbol => ({ + kind: "variable", name: "X", signature: "x NUMBER", dataType: "NUMBER", value: null, + comment: null, from: 0, scope: null, definition: false, container: null, ...overrides, +}); +const here = { where: "here" as const, part: 0, from: 0, line: 1 }; + +test("constante muestra tipo y valor", () => { + const items: Resolved[] = [{ + kind: "symbol", + symbol: symbol({ kind: "constant", name: "C_MAX", signature: "c_max CONSTANT NUMBER := 3", value: "3" }), + location: here, + }]; + render(); + expect(screen.getByText("NUMBER := 3")).toBeVisible(); + expect(screen.getByText("Constante")).toBeVisible(); +}); + +test("variable sin valor", () => { + render(); + expect(screen.getByText("Sin valor inicial")).toBeVisible(); +}); + +test("ubicación con línea y comentario", () => { + const items: Resolved[] = [{ + kind: "symbol", + symbol: symbol({ kind: "function", signature: "FUNCTION calcular RETURN NUMBER", comment: "Calcula el total" }), + location: { where: "object", object: pkg, partKind: "PACKAGE BODY", from: 0, line: 12 }, + }]; + render(); + expect(screen.getByText("FUNCTION calcular RETURN NUMBER")).toBeVisible(); + expect(screen.getByText("PKG_VENTAS · Body · línea 12")).toBeVisible(); + expect(screen.getByText("Calcula el total")).toBeVisible(); +}); + +test("relación lista columnas", () => { + const items: Resolved[] = [{ + kind: "relation", + object: { ...pkg, name: "CLIENTES", object_type: "Table" }, + columns: [ + { name: "ID", data_type: "NUMBER", nullable: false }, + { name: "NOMBRE", data_type: "VARCHAR2(100)", nullable: true }, + ], + }]; + render(); + expect(screen.getAllByRole("row")).toHaveLength(2); + expect(screen.getByText("VARCHAR2(100)")).toBeVisible(); +}); + +test("objeto sin fuente", () => { + render(); + expect(screen.getByText("Fuente no disponible")).toBeVisible(); +}); diff --git a/app/src/components/SymbolCard.tsx b/app/src/components/SymbolCard.tsx new file mode 100644 index 0000000..fef48db --- /dev/null +++ b/app/src/components/SymbolCard.tsx @@ -0,0 +1,104 @@ +import type { SymbolKind } from "../programSymbols"; +import type { Resolved, SymbolLocation } from "../symbolResolve"; +import "./SymbolCard.css"; + +const KIND_LABELS: Record = { + package: "Paquete", + procedure: "Procedimiento", + function: "Función", + cursor: "Cursor", + type: "Tipo", + subtype: "Subtipo", + variable: "Variable", + constant: "Constante", + exception: "Excepción", + parameter: "Parámetro", + field: "Campo", +}; +const valueKinds = new Set(["variable", "constant", "parameter", "field"]); +const MAX_COLUMNS = 30; +const MAX_QUERY_LINES = 6; + +/** "Spec", "Body" o "Fuente", como las pestañas de la ventana de programa. */ +export function partCaption(kind: string) { + if (kind === "PACKAGE" || kind === "TYPE") return "Spec"; + if (kind.endsWith(" BODY")) return "Body"; + return "Fuente"; +} + +function place(location: SymbolLocation) { + if (location.where === "here") return `línea ${location.line}`; + return `${location.object.name} · ${partCaption(location.partKind)} · línea ${location.line}`; +} + +function shortQuery(query: string) { + const lines = query.split(/\r?\n/); + return lines.length > MAX_QUERY_LINES ? `${lines.slice(0, MAX_QUERY_LINES).join("\n")}\n…` : query; +} + +function Item({ item }: { item: Resolved }) { + if (item.kind === "column") { + return ( +
+
{item.table}.{item.column.name}Columna
+ {item.column.data_type}{item.column.nullable ? "" : " NOT NULL"} +
+ ); + } + if (item.kind === "relation") { + const shown = item.columns.slice(0, MAX_COLUMNS); + return ( +
+
{item.object.owner}.{item.object.name}
+ + {shown.map((column) => ( + + + + + + ))} +
{column.name}{column.data_type}{column.nullable ? "" : "NOT NULL"}
+ {item.columns.length > shown.length && ( +

{item.columns.length - shown.length} columnas más

+ )} +
+ ); + } + if (item.kind === "object") { + return ( +
+
{item.object.owner}.{item.object.name}
+

{item.note}

+
+ ); + } + const { symbol } = item; + const isValue = valueKinds.has(symbol.kind); + return ( +
+
+ {isValue ? symbol.signature.split(/\s/)[0] : symbol.signature} + {KIND_LABELS[symbol.kind]} +
+ {isValue && ( + {`${symbol.dataType ?? ""}${symbol.value ? ` := ${symbol.value}` : ""}`} + )} + {isValue && !symbol.value && (symbol.kind === "variable" || symbol.kind === "constant") && ( +

Sin valor inicial

+ )} + {symbol.query &&
{shortQuery(symbol.query)}
} + {symbol.comment &&

{symbol.comment}

} +

{place(item.location)}

+
+ ); +} + +/** Contenido de la ficha: un bloque por resultado (las sobrecargas suman bloques). */ +export function SymbolCard({ items }: { items: Resolved[] }) { + return ( +
+ {items.map((item, index) => )} +
+ ); +} diff --git a/app/src/keymap.ts b/app/src/keymap.ts index eba0bc6..79b3684 100644 --- a/app/src/keymap.ts +++ b/app/src/keymap.ts @@ -28,6 +28,7 @@ export type CommandId = | "body" | "sideBySide" | "goToDeclaration" + | "showSymbolCard" | "foldBlock" | "unfoldBlock" | "objectActions" @@ -101,6 +102,7 @@ const list: Command[] = [ { id: "body", label: "Body", keys: "Alt+B" }, { id: "sideBySide", label: "Spec y Body lado a lado", keys: "Ctrl+\\" }, { id: "goToDeclaration", label: "Ir a la declaración", keys: "F12" }, + { id: "showSymbolCard", label: "Mostrar ficha", keys: "Ctrl+Shift+Space" }, { id: "foldBlock", label: "Plegar bloque", keys: "Alt+Shift+P" }, { id: "unfoldBlock", label: "Desplegar bloque", keys: "Alt+Shift+A" }, { id: "objectActions", label: "Acciones del objeto", keys: "Alt+Enter" }, diff --git a/app/src/symbolHover.test.ts b/app/src/symbolHover.test.ts new file mode 100644 index 0000000..3edc0ae --- /dev/null +++ b/app/src/symbolHover.test.ts @@ -0,0 +1,29 @@ +import { EditorState } from "@codemirror/state"; +import { EditorView } from "@codemirror/view"; +import { sql } from "@codemirror/lang-sql"; +import { expect, test } from "vitest"; +import { oracleDialect } from "./editorReference"; +import { symbolHoverSource } from "./symbolHover"; + +const view = (doc: string) => + new EditorView({ state: EditorState.create({ doc, extensions: [sql({ dialect: oracleDialect })] }) }); + +test("la ficha no aparece sin contexto", async () => { + expect(await symbolHoverSource(view("DECLARE v NUMBER; BEGIN v := 1; END;"), 25, () => null)).toBeNull(); +}); + +test("la ficha no aparece fuera de un nombre", async () => { + const editor = view("DECLARE v NUMBER; BEGIN v := 1; END;"); + const context = () => ({ parts: [{ kind: "SQL", source: editor.state.doc.toString() }], current: 0, position: 27, self: null, lookup: null }); + expect(await symbolHoverSource(editor, 27, context)).toBeNull(); +}); + +test("la ficha de una variable local cubre su nombre", async () => { + const doc = "DECLARE v NUMBER := 1; BEGIN v := 2; END;"; + const editor = view(doc); + const position = doc.indexOf("v :=") ; + const context = (_view: EditorView, at: number) => ({ parts: [{ kind: "SQL", source: doc }], current: 0, position: at, self: null, lookup: null }); + const card = await symbolHoverSource(editor, position, context); + expect(card).toMatchObject({ from: position, to: position + 1 }); + expect(card!.items[0]).toMatchObject({ kind: "symbol", symbol: { name: "V", value: "1" } }); +}); diff --git a/app/src/symbolHover.ts b/app/src/symbolHover.ts new file mode 100644 index 0000000..28d4f2f --- /dev/null +++ b/app/src/symbolHover.ts @@ -0,0 +1,89 @@ +import { createElement } from "react"; +import { createRoot } from "react-dom/client"; +import { Facet, StateEffect, StateField, type Extension } from "@codemirror/state"; +import { EditorView, hoverTooltip, showTooltip, type Command, type Tooltip } from "@codemirror/view"; +import { SymbolCard } from "./components/SymbolCard"; +import { editorPath } from "./editorReference"; +import { resolveSymbol, type Resolved, type ResolveContext } from "./symbolResolve"; + +export type ContextFor = (view: EditorView, position: number) => ResolveContext | null; + +export interface SymbolCardData { + from: number; + to: number; + items: Resolved[]; +} + +/** Lo que muestra la ficha en `position`, o null si no hay nada que mostrar. */ +export async function symbolHoverSource( + view: EditorView, + position: number, + contextFor: ContextFor | null, +): Promise { + if (!contextFor) return null; + const path = editorPath(view.state, position); + if (!path) return null; + const context = contextFor(view, position); + if (!context) return null; + const items = await resolveSymbol(context, path); + return items.length ? { from: path.from, to: path.to, items } : null; +} + +function cardTooltip(card: SymbolCardData): Tooltip { + return { + pos: card.from, + end: card.to, + above: true, + create() { + const dom = document.createElement("div"); + dom.className = "cm-symbol-tooltip"; + const root = createRoot(dom); + root.render(createElement(SymbolCard, { items: card.items })); + return { dom, destroy: () => queueMicrotask(() => root.unmount()) }; + }, + }; +} + +const contextFacet = Facet.define<() => ContextFor | null, () => ContextFor | null>({ + combine: (values) => values[0] ?? (() => null), +}); + +const setCard = StateEffect.define(); +const manualCard = StateField.define({ + create: () => null, + update(value, transaction) { + for (const effect of transaction.effects) if (effect.is(setCard)) return effect.value; + return transaction.docChanged || transaction.selection ? null : value; + }, + provide: (field) => showTooltip.from(field), +}); + +/** Ficha al pasar el mouse (400 ms quieto) y la que abre `showSymbolCard`. */ +export function symbolHover(contextFor: () => ContextFor | null): Extension { + return [ + contextFacet.of(contextFor), + manualCard, + hoverTooltip(async (view, position) => { + const card = await symbolHoverSource(view, position, contextFor()); + return card ? cardTooltip(card) : null; + }, { hoverTime: 400, hideOnChange: true }), + EditorView.domEventHandlers({ + keydown(event, view) { + if (event.key !== "Escape" || !view.state.field(manualCard, false)) return false; + view.dispatch({ effects: setCard.of(null) }); + return true; + }, + }), + ]; +} + +/** Abre la ficha del nombre en el cursor. */ +export const showSymbolCard: Command = (view) => { + const contextFor = view.state.facet(contextFacet)(); + const head = view.state.selection.main.head; + void symbolHoverSource(view, head, contextFor).then((card) => { + if (!card || view.state.selection.main.head !== head) return; + view.dispatch({ effects: setCard.of(cardTooltip(card)) }); + }); + return true; +}; diff --git a/app/src/symbolResolve.test.ts b/app/src/symbolResolve.test.ts index 57e188b..6c1a602 100644 --- a/app/src/symbolResolve.test.ts +++ b/app/src/symbolResolve.test.ts @@ -176,3 +176,9 @@ test("fuente envuelta", async () => { const found = await resolveSymbol(at(["BEGIN pkg_w.f; END;"], "pkg_w", { lookup }), path(["PKG_W", "F"], 0)); expect(found).toEqual([{ kind: "object", object: info("PKG_W", "Package"), note: "Fuente no disponible" }]); }); + +test("con el objeto propio las ubicaciones siguen siendo del documento", async () => { + const context = { ...at(["DECLARE v NUMBER; BEGIN v := 1; END;"], "v :="), self: info("PKG", "Package") }; + const [found] = await resolveSymbol(context, path(["V"])); + expect(found).toMatchObject({ kind: "symbol", location: { where: "here" } }); +}); diff --git a/app/src/symbolResolve.ts b/app/src/symbolResolve.ts index aec1d0b..c61d0f3 100644 --- a/app/src/symbolResolve.ts +++ b/app/src/symbolResolve.ts @@ -22,8 +22,8 @@ export interface ResolveContext { current: number; /** Posición dentro de esa parte. */ position: number; - /** Objeto del documento abierto, si lo es. */ - self: ObjectInfo | null; + /** Objeto del documento abierto, si lo es. Sus declaraciones se ubican como "here". */ + self: Pick | null; /** null sin conexión. */ lookup: SymbolLookup | null; } @@ -119,7 +119,7 @@ class Resolver { private readonly here: Home; constructor(private readonly ctx: ResolveContext) { - this.here = homeOf(ctx.parts, ctx.self); + this.here = homeOf(ctx.parts, null); } private async safe(load: (lookup: SymbolLookup) => Promise, fallback: T): Promise { From e43cf69858ce518e84381aee47998ef78e7d8ff1 Mon Sep 17 00:00:00 2001 From: Walter Aquino Date: Fri, 27 Nov 2026 10:59:36 -0300 Subject: [PATCH 10/24] =?UTF-8?q?feat(app):=20WAL-119=20ir=20a=20definici?= =?UTF-8?q?=C3=B3n,=20declaraci=C3=B3n=20e=20implementaci=C3=B3n;=20Ctrl+c?= =?UTF-8?q?lic?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit F12 pasa a ser Ir a la definición. Ctrl+F12 va a la declaración y Ctrl+Shift+F12 a la implementación. Ctrl+clic navega y subraya el nombre con Ctrl apretado. Un destino en otro objeto lo abre en esa línea. Co-Authored-By: Claude Opus 5.5 --- app/src/App.test.tsx | 35 ++++++++ app/src/App.tsx | 18 ++++ app/src/components/EditorObjectMenu.tsx | 9 +- app/src/components/ProgramEditor.tsx | 4 + app/src/components/ProgramWindow.test.tsx | 89 +++++++++++++++++++ app/src/components/ProgramWindow.tsx | 101 +++++++++++++++------- app/src/components/SymbolCard.css | 5 ++ app/src/editorNavigation.test.ts | 54 ++++++++++++ app/src/editorNavigation.ts | 41 +++++++++ app/src/keymap.test.ts | 2 +- app/src/keymap.ts | 6 +- app/src/symbolLink.ts | 69 +++++++++++++++ 12 files changed, 396 insertions(+), 37 deletions(-) create mode 100644 app/src/editorNavigation.test.ts create mode 100644 app/src/editorNavigation.ts create mode 100644 app/src/symbolLink.ts diff --git a/app/src/App.test.tsx b/app/src/App.test.tsx index 62266f6..1fe2cdf 100644 --- a/app/src/App.test.tsx +++ b/app/src/App.test.tsx @@ -106,6 +106,8 @@ vi.mock("./api", () => ({ sessionPing: vi.fn(async () => true), listObjects: vi.fn(), programSource: vi.fn(), + editorObject: vi.fn(async () => null), + describeColumns: vi.fn(async () => []), routineOverloads: vi.fn(), completeObjects: vi.fn(), objectColumns: vi.fn(), @@ -1256,3 +1258,36 @@ test("sin actualización no hay ícono", async () => { await screen.findByRole("button", { name: "Cancelar" }); expect(screen.queryByRole("button", { name: /Actualización disponible/ })).not.toBeInTheDocument(); }); + +test("F12 sobre un miembro de otro paquete lo abre en su declaración", async () => { + windowEvents.close.mockResolvedValue(() => {}); + vi.mocked(api.programSource).mockReset(); + const pkgA = { owner: "HR", name: "PKG_A", object_type: "Package" as const, status: "Valid" as const, last_ddl_time: "2026-01-01T12:00:00" }; + const pkgOtro = { ...pkgA, name: "PKG_OTRO" }; + vi.mocked(api.listObjects).mockResolvedValue([pkgA]); + const source = "CREATE OR REPLACE PACKAGE PKG_A AS\n c NUMBER := pkg_otro.hacer;\nEND;"; + const other = "CREATE OR REPLACE PACKAGE PKG_OTRO AS\n FUNCTION hacer RETURN NUMBER;\nEND;"; + vi.mocked(api.programSource).mockImplementation(async (_session, _type, _owner, name) => [ + { kind: "PACKAGE", source: name === "PKG_OTRO" ? other : source, last_ddl_time: null, diagnostics: [] }, + ]); + vi.mocked(api.editorObject).mockImplementation(async (_session, reference) => + reference.name === "PKG_OTRO" ? pkgOtro : null); + render(); + await connectAs(); + fireEvent.click(await screen.findByRole("treeitem", { name: "Paquetes" })); + fireEvent.contextMenu(await screen.findByRole("treeitem", { name: "PKG_A" })); + fireEvent.click(screen.getByRole("menuitem", { name: "Editar Spec y Body" })); + const editor = await screen.findByRole("textbox", { name: "Spec" }); + const view = EditorView.findFromDOM(editor.closest(".cm-editor")!)!; + act(() => view.dispatch({ selection: { anchor: source.indexOf("hacer") + 1 } })); + await act(async () => { + fireEvent.keyDown(window, { key: "F12" }); + }); + await waitFor(() => { + const opened = EditorView.findFromDOM( + screen.getByRole("textbox", { name: "Spec" }).closest(".cm-editor")!, + )!; + expect(opened.state.doc.toString()).toBe(other); + expect(opened.state.selection.main.head).toBe(other.indexOf("hacer")); + }); +}); diff --git a/app/src/App.tsx b/app/src/App.tsx index e79ba06..e28491c 100644 --- a/app/src/App.tsx +++ b/app/src/App.tsx @@ -123,6 +123,8 @@ interface ProgramTab { fileName?: string; workspaceProfileId?: string; load?: symbol; + /** Posición pedida por "Ir a la definición" desde otra ventana. */ + target?: { partKind: string; from: number }; /** Ventana SQL: sesión propia, texto inicial y estado de su transacción. */ sql?: { sessionId: string; @@ -274,7 +276,9 @@ export default function App() { "spec", "body", "sideBySide", + "goToDefinition", "goToDeclaration", + "goToImplementation", "showSymbolCard", "foldBlock", "unfoldBlock", @@ -314,7 +318,9 @@ export default function App() { !program.readOnly || [ "save", + "goToDefinition", "goToDeclaration", + "goToImplementation", "showSymbolCard", "foldBlock", "unfoldBlock", @@ -945,6 +951,7 @@ export default function App() { object: ObjectInfo, mode: "view" | "edit" = "view", connection = active, + at?: { partKind: string; from: number }, ) { if (!connection) return; if (!supportsProgram.has(object.object_type)) { @@ -970,6 +977,7 @@ export default function App() { const load = Symbol(); if (existing) { setProgramId(id); + if (at) updateProgram(id, { target: { ...at } }); if (mode === "edit") updateProgram(id, { readOnly: false }); if (!existing.error) return; updateProgram(id, { error: undefined, load }); @@ -982,6 +990,7 @@ export default function App() { readOnly: mode === "view", dirty: false, load, + target: at, }); } try { @@ -1438,6 +1447,15 @@ export default function App() { ? symbolSources.lookup(editorConnection.sessionId, tab.object?.owner ?? null) : null} symbolSelf={tab.object ?? null} + initialTarget={tab.target} + onNavigate={(target) => { + const { location } = target; + if (location.where !== "object" || !editorConnection) return; + void onOpenObject(location.object, "view", editorConnection, { + partKind: location.partKind, + from: location.from, + }); + }} registerSource={tab.object && tab.connection ? (read) => symbolSources.register({ connection: tab.connection!.sessionId, diff --git a/app/src/components/EditorObjectMenu.tsx b/app/src/components/EditorObjectMenu.tsx index b5c124d..ff3e72f 100644 --- a/app/src/components/EditorObjectMenu.tsx +++ b/app/src/components/EditorObjectMenu.tsx @@ -23,13 +23,15 @@ interface Props { onDescribe: (object: ObjectInfo) => void; onMessage: (message: string) => void; readOnlyItem?: ContextItem; + /** Ir a la definición, declaración e implementación, arriba de todo. */ + navigation?: ContextItem[]; } const tableTypes = new Set(["Table", "View", "MaterializedView"]); const programTypes = new Set(["Package", "Type", "Function", "Procedure", "Trigger"]); const quote = (name: string) => `"${name.replace(/"/g, '""')}"`; -export function EditorObjectMenu({ request, catalog, onClose, onDescribe, onMessage, readOnlyItem }: Props) { +export function EditorObjectMenu({ request, catalog, onClose, onDescribe, onMessage, readOnlyItem, navigation }: Props) { const [result, setResult] = useState<{ object: ObjectInfo | null; message?: string }>(); const { reference } = request; const { sessionId, owner } = catalog; @@ -51,7 +53,10 @@ export function EditorObjectMenu({ request, catalog, onClose, onDescribe, onMess onMessage(describeError(error).message); } } - const items: (ContextItem | "sep")[] = readOnlyItem ? [readOnlyItem, "sep"] : []; + const items: (ContextItem | "sep")[] = [ + ...(readOnlyItem ? [readOnlyItem, "sep" as const] : []), + ...(navigation?.length ? [...navigation, "sep" as const] : []), + ]; if (object) { if (tableTypes.has(object.object_type)) items.push({ label: "Describir", run: () => onDescribe(object) }); if (programTypes.has(object.object_type)) items.push({ label: "Ver fuente", run: () => catalog.openProgram(object) }); diff --git a/app/src/components/ProgramEditor.tsx b/app/src/components/ProgramEditor.tsx index 02c0b73..229ca9c 100644 --- a/app/src/components/ProgramEditor.tsx +++ b/app/src/components/ProgramEditor.tsx @@ -17,6 +17,7 @@ import { tags } from "@lezer/highlight"; import type { ProgramPart } from "../types"; import { editorReference, oracleDialect, type EditorReference } from "../editorReference"; import { symbolHover, type ContextFor } from "../symbolHover"; +import { symbolLink } from "../symbolLink"; import { programFolding } from "../programFolding"; import { catalogCompletion, keywordCompletion, type CompletionCatalog } from "../programCompletion"; import { editorSearch } from "./EditorSearch"; @@ -84,6 +85,8 @@ interface Props { markers?: EditorMarker[]; /** Contexto para la ficha de símbolos; sin él no hay ficha. */ symbolContext?: ContextFor; + /** Ctrl+clic sobre un nombre: ir a su definición. */ + onCtrlClick?: (position: number) => void; } function markerDiagnostics(markers: EditorMarker[], length: number): Diagnostic[] { @@ -177,6 +180,7 @@ export function ProgramEditor(props: Props) { }), EditorState.allowMultipleSelections.of(true), symbolHover(() => latest.current.symbolContext ?? null), + symbolLink(() => latest.current.onCtrlClick), EditorView.domEventHandlers({ focus: () => { latest.current.activate(); }, keydown: (event) => { diff --git a/app/src/components/ProgramWindow.test.tsx b/app/src/components/ProgramWindow.test.tsx index 16943dd..3314251 100644 --- a/app/src/components/ProgramWindow.test.tsx +++ b/app/src/components/ProgramWindow.test.tsx @@ -800,3 +800,92 @@ test("Mostrar ficha abre la ficha de la constante en el cursor", async () => { expect(await screen.findByText("NUMBER := 3")).toBeInTheDocument(); expect(screen.getByText("línea 2")).toBeInTheDocument(); }); + +describe("ir a la definición", () => { + const spec = "PACKAGE PKG_A AS\n PROCEDURE calcular;\nEND;"; + const body = "PACKAGE BODY PKG_A AS\n PROCEDURE calcular IS BEGIN NULL; END;\nBEGIN\n calcular;\nEND;"; + const both = [{ ...parts[0], source: spec }, { ...parts[1], source: body }]; + const viewOf = (name: string) => + EditorView.findFromDOM(screen.getByRole("textbox", { name }).closest(".cm-editor")!)!; + const atCall = () => { + fireEvent.click(screen.getByRole("tab", { name: /^Body/ })); + const view = viewOf("Body"); + act(() => view.dispatch({ selection: { anchor: body.lastIndexOf("calcular") + 1 } })); + return view; + }; + + test("F12 sobre una llamada va al cuerpo", async () => { + const ref = createRef(); + render(); + const view = atCall(); + act(() => ref.current!.goToDefinition!()); + await waitFor(() => expect(view.state.selection.main.head).toBe(body.indexOf("calcular"))); + }); + + test("Ctrl+F12 va a la spec", async () => { + const ref = createRef(); + render(); + atCall(); + act(() => ref.current!.goToDeclaration!()); + await waitFor(() => expect(viewOf("Spec").state.selection.main.head).toBe(spec.indexOf("calcular"))); + }); + + test("Ir a la implementación sin cuerpo avisa", async () => { + const ref = createRef(); + const only = "PACKAGE PKG_A AS\n PROCEDURE calcular;\n PROCEDURE otro(p NUMBER := calcular);\nEND;"; + render(); + const view = viewOf("Spec"); + act(() => view.dispatch({ selection: { anchor: only.lastIndexOf("calcular") + 1 } })); + act(() => ref.current!.goToImplementation!()); + expect(await screen.findByText("Cuerpo no disponible")).toBeInTheDocument(); + expect(view.state.selection.main.head).toBe(only.indexOf("calcular")); + }); + + test("Ctrl+clic en un nombre navega", async () => { + render(); + const view = atCall(); + vi.spyOn(view, "posAtCoords").mockReturnValue(body.lastIndexOf("calcular") + 2); + fireEvent.mouseDown(view.contentDOM, { ctrlKey: true, button: 0, clientX: 5, clientY: 5 }); + await waitFor(() => expect(view.state.selection.main.head).toBe(body.indexOf("calcular"))); + }); + + test("destino en otro objeto pide abrirlo", async () => { + const ref = createRef(); + const onNavigate = vi.fn(); + const other = { owner: "HR", name: "PKG_OTRO", object_type: "Package" as const, status: "Valid" as const, last_ddl_time: "" }; + const symbols = { + object: vi.fn(async (_owner: string | null, name: string) => (name === "PKG_OTRO" ? other : null)), + parts: vi.fn(async () => [{ kind: "PACKAGE", source: "PACKAGE pkg_otro AS\n PROCEDURE hacer;\nEND;" }]), + columns: vi.fn(async () => []), + }; + const source = "PACKAGE BODY PKG_A AS\nBEGIN\n pkg_otro.hacer;\nEND;"; + render(); + const view = viewOf("Body"); + act(() => view.dispatch({ selection: { anchor: source.indexOf("hacer") + 1 } })); + act(() => ref.current!.goToDefinition!()); + await waitFor(() => expect(onNavigate).toHaveBeenCalledOnce()); + expect(onNavigate.mock.calls[0][0]).toMatchObject({ + location: { where: "object", object: other, partKind: "PACKAGE", line: 2 }, + }); + }); + + test("F12 sobre una tabla abre su descripción", async () => { + vi.spyOn(api, "describeColumns").mockResolvedValue([{ name: "ID", data_type: "NUMBER", nullable: false }]); + const ref = createRef(); + const table = { owner: "HR", name: "CLIENTES", object_type: "Table" as const, status: "Valid" as const, last_ddl_time: "" }; + const symbols = { + object: vi.fn(async () => table), + parts: vi.fn(async () => []), + columns: vi.fn(async () => [{ name: "ID", data_type: "NUMBER", nullable: false }]), + }; + const source = "PACKAGE BODY PKG_A AS\n CURSOR c IS SELECT id FROM clientes;\nEND;"; + render(); + const view = viewOf("Body"); + act(() => view.dispatch({ selection: { anchor: source.indexOf("clientes") + 1 } })); + act(() => ref.current!.goToDefinition!()); + expect(await screen.findByRole("region", { name: "Descripción de HR.CLIENTES" })).toBeInTheDocument(); + }); +}); diff --git a/app/src/components/ProgramWindow.tsx b/app/src/components/ProgramWindow.tsx index 001bf41..267c71a 100644 --- a/app/src/components/ProgramWindow.tsx +++ b/app/src/components/ProgramWindow.tsx @@ -10,7 +10,10 @@ import { copyLineDown, deleteLine, indentLess, indentMore, redo, toggleComment, import { api } from "../api"; import { commands, formatKeys, type CommandId } from "../keymap"; import { describeError, type ObjectInfo, type ProgramPart } from "../types"; -import { editorReference } from "../editorReference"; +import { editorPath, editorReference } from "../editorReference"; +import { navigationTargets, type NavigationGoal, type NavigationTarget } from "../editorNavigation"; +import { resolveSymbol } from "../symbolResolve"; +import { partCaption } from "./SymbolCard"; import { positionAt, ProgramEditor, type EditorMarker } from "./ProgramEditor"; import { EditorObjectMenu, ObjectDescription, type ObjectCatalog, type ObjectRequest } from "./EditorObjectMenu"; import { ProgramComparison, type ComparisonResult } from "./ProgramComparison"; @@ -67,6 +70,10 @@ interface Props { symbols?: SymbolLookup | null; /** Objeto que muestra la ventana, para ubicar sus propias declaraciones. */ symbolSelf?: Pick | null; + /** Destinos en otro objeto: la ventana pide abrirlo. */ + onNavigate?: (target: NavigationTarget) => void; + /** Posición a la que ir al abrir o al pedir un destino nuevo. */ + initialTarget?: { partKind: string; from: number }; } const caption = (kind: string) => { @@ -100,13 +107,15 @@ function storedOutlineWidth() { } } -interface DeclarationTarget { - index: number; - entry: ProgramDeclaration; -} +const NAVIGATION_TITLES: Record = { + definition: "Definiciones", + declaration: "Declaraciones", + implementation: "Implementaciones", +}; export function ProgramWindow({ parts, readOnly, onReadOnlyChange, onDirty, onWorkspaceChange, ref, fileName, catalog, active = true, readCurrentProgram, compilationTarget, compile, onTestRoutine, registerSource, symbols, symbolSelf, + onNavigate, initialTarget, }: Props) { const [baselines, setBaselines] = useState(() => parts.map(baselineOf)); const [compiling, setCompiling] = useState(false); @@ -117,8 +126,8 @@ export function ProgramWindow({ const [message, setMessage] = useState(""); const [saving, setSaving] = useState(false); const [comparison, setComparison] = useState<{ index: number; result: ComparisonResult } | null>(null); - const [objectMenu, setObjectMenu] = useState<(ObjectRequest & { id: number }) | null>(null); - const [declarationMenu, setDeclarationMenu] = useState<{ name: string; x: number; y: number; targets: DeclarationTarget[] } | null>(null); + const [objectMenu, setObjectMenu] = useState<(ObjectRequest & { id: number; part: number; position: number }) | null>(null); + const [declarationMenu, setDeclarationMenu] = useState<{ title: string; x: number; y: number; targets: NavigationTarget[] } | null>(null); const [routineMenu, setRoutineMenu] = useState<{ name: string; x: number; y: number } | null>(null); const closeRoutineMenu = useCallback(() => setRoutineMenu(null), []); const [description, setDescription] = useState<{ object: ObjectInfo; sessionId: string; id: number } | null>(null); @@ -298,35 +307,54 @@ export function ProgramWindow({ if (view) navigateAt(index, positionAt(view, line, column)); } - function declaration() { + function openTarget(target: NavigationTarget) { + const { location } = target; + if (location.where === "here") navigateAt(location.part, location.from); + else onNavigate?.(target); + } + + function targetLabel({ location, label }: NavigationTarget) { + if (location.where === "object") return `${location.object.name} · ${partCaption(location.partKind)} · ${label}`; + return canSplit ? `${caption(parts[location.part].kind)} · ${label}` : label; + } + + /** Definición, declaración o implementación del nombre en `at` (o en el cursor). */ + async function goTo(goal: NavigationGoal, index = selected, at?: number) { if (comparison) return; - const view = views.current[selected]; + const view = views.current[index]; if (!view) return; - const position = view.state.selection.main.from; - const reference = editorReference(view.state, position) - ?? (position > 0 ? editorReference(view.state, position - 1) : null); - if (!reference || (reference.owner && compilationTarget && reference.owner !== compilationTarget.name)) return; - - const { first, second } = structureNow(); - const bySignature = new Map(); - for (const entry of selected === 0 ? first : second) { - if (entry.name === reference.name) bySignature.set(entry.key, { index: selected, entry }); - } - if (canSplit && selected === 1) { - for (const entry of first) { - if (entry.name === reference.name) bySignature.set(entry.key, { index: 0, entry }); - } + const position = at ?? view.state.selection.main.from; + const path = editorPath(view.state, position) ?? (position > 0 ? editorPath(view.state, position - 1) : null); + const context = symbolContext(view, position); + if (!path || !context) return; + const items = await resolveSymbol(context, path); + const relation = items.find((item) => item.kind === "relation"); + if (relation?.kind === "relation") { + if (catalog) setDescription({ object: relation.object, sessionId: catalog.sessionId, id: ++objectRequestId.current }); + return; } - const targets = [...bySignature.values()]; + const { targets, notice } = navigationTargets(items, goal); + if (notice) setMessage(notice); if (targets.length === 1) { - navigateAt(targets[0].index, targets[0].entry.from); + openTarget(targets[0]); } else if (targets.length > 1) { const coords = view.coordsAtPos(position) ?? view.contentDOM.getBoundingClientRect(); closeObjectMenu(); - setDeclarationMenu({ name: reference.name, x: coords.left, y: coords.bottom, targets }); + setDeclarationMenu({ + title: `${NAVIGATION_TITLES[goal]} de ${path.parts[path.index]}`, + x: coords.left, y: coords.bottom, targets, + }); } } + useEffect(() => { + if (!initialTarget) return; + const index = parts.findIndex((part) => part.kind === initialTarget.partKind); + if (index >= 0) navigateAt(index, initialTarget.from); + // Solo al pedir un destino nuevo; `parts` llega junto con él. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [initialTarget]); + async function save() { if (saving) return; const index = selected; @@ -478,7 +506,9 @@ export function ProgramWindow({ setComparison(null); setSplit((value) => !value); } : undefined, - goToDeclaration: declaration, + goToDefinition: () => void goTo("definition"), + goToDeclaration: () => void goTo("declaration"), + goToImplementation: () => void goTo("implementation"), foldBlock: runInEditor(foldCode), unfoldBlock: runInEditor(unfoldCode), compareProgram: readCurrentProgram ? () => void compare() : undefined, @@ -497,7 +527,7 @@ export function ProgramWindow({ if (!reference) return; const coords = view.coordsAtPos(position) ?? view.contentDOM.getBoundingClientRect(); closeDeclarationMenu(); - setObjectMenu({ reference, x: coords.left, y: coords.bottom, id: ++objectRequestId.current }); + setObjectMenu({ reference, x: coords.left, y: coords.bottom, id: ++objectRequestId.current, part: selected, position }); }) : undefined, complete: readOnly ? undefined : runInEditor(startCompletion), showSymbolCard: runInEditor(showSymbolCard), @@ -632,8 +662,9 @@ export function ProgramWindow({ } closeRoutineMenu(); closeDeclarationMenu(); - setObjectMenu({ reference, x, y, id: ++objectRequestId.current }); + setObjectMenu({ reference, x, y, id: ++objectRequestId.current, part: index, position }); } : undefined} + onCtrlClick={(position) => void goTo("definition", index, position)} onView={(view) => { views.current[index] = view; const base = saved.current[index]; @@ -669,6 +700,10 @@ export function ProgramWindow({ {active && catalog && objectMenu && ( { + const id = goal === "definition" ? "goToDefinition" : goal === "declaration" ? "goToDeclaration" : "goToImplementation"; + return { label: commands[id].label, keys: commands[id].keys, run: () => void goTo(goal, objectMenu.part, objectMenu.position) }; + })} onMessage={setMessage} onDescribe={(object) => setDescription({ object, sessionId: catalog.sessionId, id: objectMenu.id })} /> )} @@ -678,10 +713,10 @@ export function ProgramWindow({ )} {active && declarationMenu && !comparison && ( ({ - label: canSplit ? `${caption(parts[index].kind)} · ${entry.label}` : entry.label, - run: () => navigateAt(index, entry.from), + label={declarationMenu.title} width={360} className="program-declaration-menu" + items={declarationMenu.targets.map((target) => ({ + label: targetLabel(target), + run: () => openTarget(target), }))} onClose={closeDeclarationMenu} /> )} diff --git a/app/src/components/SymbolCard.css b/app/src/components/SymbolCard.css index 57a601d..77c9986 100644 --- a/app/src/components/SymbolCard.css +++ b/app/src/components/SymbolCard.css @@ -57,3 +57,8 @@ padding: 1px 12px 1px 0; vertical-align: top; } +.cm-symbol-link { + text-decoration: underline; + text-underline-offset: 2px; + cursor: pointer; +} diff --git a/app/src/editorNavigation.test.ts b/app/src/editorNavigation.test.ts new file mode 100644 index 0000000..88d69a5 --- /dev/null +++ b/app/src/editorNavigation.test.ts @@ -0,0 +1,54 @@ +import { expect, test } from "vitest"; +import { navigationTargets } from "./editorNavigation"; +import type { ProgramSymbol } from "./programSymbols"; +import type { Resolved } from "./symbolResolve"; + +const routine = (part: number, definition: boolean, signature = "PROCEDURE p(a NUMBER)"): Resolved => ({ + kind: "symbol", + symbol: { + kind: "procedure", name: "P", signature, dataType: null, value: null, comment: null, + from: part * 100, scope: null, definition, container: null, + } satisfies ProgramSymbol, + location: { where: "here", part, from: part * 100, line: 1 }, +}); + +const parts = (choice: ReturnType) => + choice.targets.map((target) => target.location.where === "here" && target.location.part); + +test("definición prefiere el cuerpo", () => { + expect(parts(navigationTargets([routine(0, false), routine(1, true)], "definition"))).toEqual([1]); +}); + +test("declaración prefiere la spec", () => { + expect(parts(navigationTargets([routine(0, false), routine(1, true)], "declaration"))).toEqual([0]); +}); + +test("implementación sin cuerpo avisa", () => { + const choice = navigationTargets([routine(0, false)], "implementation"); + expect(parts(choice)).toEqual([0]); + expect(choice.notice).toBe("Cuerpo no disponible"); +}); + +test("sobrecargas dan varios destinos", () => { + const choice = navigationTargets([ + routine(0, false), routine(1, true), + routine(0, false, "PROCEDURE p(a VARCHAR2)"), routine(1, true, "PROCEDURE p(a VARCHAR2)"), + ], "definition"); + expect(parts(choice)).toEqual([1, 1]); + expect(choice.targets.map((target) => target.label)).toEqual(["PROCEDURE p(a NUMBER)", "PROCEDURE p(a VARCHAR2)"]); +}); + +test("una variable no pide cuerpo", () => { + const variable: Resolved = { + kind: "symbol", + symbol: { ...(routine(0, false) as { symbol: ProgramSymbol }).symbol, kind: "variable", signature: "v NUMBER" }, + location: { where: "here", part: 0, from: 5, line: 1 }, + }; + const choice = navigationTargets([variable], "implementation"); + expect(choice.targets).toHaveLength(1); + expect(choice.notice).toBeUndefined(); +}); + +test("columnas y tablas no dan destinos de código", () => { + expect(navigationTargets([{ kind: "column", table: "T", column: { name: "C", data_type: "NUMBER", nullable: true } }], "definition").targets).toEqual([]); +}); diff --git a/app/src/editorNavigation.ts b/app/src/editorNavigation.ts new file mode 100644 index 0000000..f315d57 --- /dev/null +++ b/app/src/editorNavigation.ts @@ -0,0 +1,41 @@ +import type { Resolved, SymbolLocation } from "./symbolResolve"; + +export type NavigationGoal = "definition" | "declaration" | "implementation"; + +export interface NavigationTarget { + location: SymbolLocation; + /** Firma del destino, para el selector cuando hay varios. */ + label: string; +} + +export interface NavigationChoice { + targets: NavigationTarget[]; + notice?: "Cuerpo no disponible"; +} + +const routineKinds = new Set(["procedure", "function"]); + +/** + * Destinos según el objetivo, uno por declaración distinta (las sobrecargas suman destinos). + * definition: el cuerpo si existe, si no la declaración. declaration: al revés. + * implementation: el cuerpo; sin cuerpo, la declaración con aviso. + */ +export function navigationTargets(items: Resolved[], goal: NavigationGoal): NavigationChoice { + const groups = new Map[]>(); + for (const item of items) { + if (item.kind !== "symbol") continue; + const key = `${item.symbol.kind}|${item.symbol.signature.replace(/\s+/g, " ").toUpperCase()}`; + groups.set(key, [...(groups.get(key) ?? []), item]); + } + let missingBody = false; + const targets: NavigationTarget[] = []; + for (const group of groups.values()) { + const body = group.find((item) => item.symbol.definition); + const declaration = group.find((item) => !item.symbol.definition); + const chosen = goal === "declaration" ? declaration ?? body : body ?? declaration; + if (!chosen) continue; + if (goal === "implementation" && !body && routineKinds.has(chosen.symbol.kind)) missingBody = true; + targets.push({ location: chosen.location, label: chosen.symbol.signature }); + } + return missingBody ? { targets, notice: "Cuerpo no disponible" } : { targets }; +} diff --git a/app/src/keymap.test.ts b/app/src/keymap.test.ts index 0efc0ab..81918c2 100644 --- a/app/src/keymap.test.ts +++ b/app/src/keymap.test.ts @@ -234,7 +234,7 @@ describe("keymap", () => { expect(find).toHaveBeenCalled(); expect(f.preventDefault).toHaveBeenCalled(); const declined = key("F12"); - expect(handleShortcut(declined, { goToDeclaration: () => false })).toBe(false); + expect(handleShortcut(declined, { goToDefinition: () => false })).toBe(false); expect(declined.preventDefault).toHaveBeenCalled(); }); diff --git a/app/src/keymap.ts b/app/src/keymap.ts index 79b3684..19a35ab 100644 --- a/app/src/keymap.ts +++ b/app/src/keymap.ts @@ -27,7 +27,9 @@ export type CommandId = | "spec" | "body" | "sideBySide" + | "goToDefinition" | "goToDeclaration" + | "goToImplementation" | "showSymbolCard" | "foldBlock" | "unfoldBlock" @@ -101,7 +103,9 @@ const list: Command[] = [ { id: "spec", label: "Spec", keys: "Alt+S" }, { id: "body", label: "Body", keys: "Alt+B" }, { id: "sideBySide", label: "Spec y Body lado a lado", keys: "Ctrl+\\" }, - { id: "goToDeclaration", label: "Ir a la declaración", keys: "F12" }, + { id: "goToDefinition", label: "Ir a la definición", keys: "F12" }, + { id: "goToDeclaration", label: "Ir a la declaración", keys: "Ctrl+F12" }, + { id: "goToImplementation", label: "Ir a la implementación", keys: "Ctrl+Shift+F12" }, { id: "showSymbolCard", label: "Mostrar ficha", keys: "Ctrl+Shift+Space" }, { id: "foldBlock", label: "Plegar bloque", keys: "Alt+Shift+P" }, { id: "unfoldBlock", label: "Desplegar bloque", keys: "Alt+Shift+A" }, diff --git a/app/src/symbolLink.ts b/app/src/symbolLink.ts new file mode 100644 index 0000000..dea7390 --- /dev/null +++ b/app/src/symbolLink.ts @@ -0,0 +1,69 @@ +import { StateEffect, StateField, type Extension } from "@codemirror/state"; +import { Decoration, EditorView, type DecorationSet } from "@codemirror/view"; +import { editorPath } from "./editorReference"; + +const setLink = StateEffect.define<{ from: number; to: number } | null>(); +const linkMark = Decoration.mark({ class: "cm-symbol-link" }); + +const linkField = StateField.define({ + create: () => Decoration.none, + update(value, transaction) { + for (const effect of transaction.effects) { + if (effect.is(setLink)) return effect.value ? Decoration.set(linkMark.range(effect.value.from, effect.value.to)) : Decoration.none; + } + return transaction.docChanged ? Decoration.none : value; + }, + provide: (field) => EditorView.decorations.from(field), +}); + +/** + * Con Ctrl apretado, subraya el nombre bajo el mouse; Ctrl+clic llama a `navigate`. + * `navigate` se lee en cada evento; sin él no hay subrayado ni clic. + */ +export function symbolLink(navigate: () => ((position: number) => void) | null | undefined): Extension { + let mouse: { x: number; y: number } | null = null; + const refresh = (view: EditorView, ctrl: boolean) => { + let range: { from: number; to: number } | null = null; + if (ctrl && mouse && navigate()) { + const position = view.posAtCoords(mouse); + const path = position === null ? null : editorPath(view.state, position); + if (path) range = { from: path.from, to: path.to }; + } + const current = view.state.field(linkField).iter(); + const same = range ? current.value && current.from === range.from && current.to === range.to : !current.value; + if (!same) view.dispatch({ effects: setLink.of(range) }); + }; + return [ + linkField, + EditorView.domEventHandlers({ + mousemove(event, view) { + mouse = { x: event.clientX, y: event.clientY }; + refresh(view, event.ctrlKey || event.metaKey); + return false; + }, + mouseleave(_event, view) { + mouse = null; + refresh(view, false); + return false; + }, + keydown(event, view) { + if (event.key === "Control" || event.key === "Meta") refresh(view, true); + return false; + }, + keyup(event, view) { + if (event.key === "Control" || event.key === "Meta") refresh(view, false); + return false; + }, + mousedown(event, view) { + const go = navigate(); + if (!go || event.button !== 0 || !(event.ctrlKey || event.metaKey) || event.shiftKey || event.altKey) return false; + const position = view.posAtCoords({ x: event.clientX, y: event.clientY }); + if (position === null || !editorPath(view.state, position)) return false; + event.preventDefault(); + refresh(view, false); + go(position); + return true; + }, + }), + ]; +} From aebbdfe7c80f20d398b739d69679dce7dadc9fbb Mon Sep 17 00:00:00 2001 From: Walter Aquino Date: Fri, 27 Nov 2026 11:02:43 -0300 Subject: [PATCH 11/24] =?UTF-8?q?feat(app):=20WAL-119=20ficha=20y=20navega?= =?UTF-8?q?ci=C3=B3n=20en=20ventanas=20SQL=20y=20de=20prueba?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- app/src/App.tsx | 11 ++++ app/src/components/ProgramWindow.tsx | 27 +++----- app/src/components/SqlWindow.test.tsx | 46 ++++++++++++++ app/src/components/SqlWindow.tsx | 89 ++++++++++++++++++++++++++- app/src/editorNavigation.ts | 40 +++++++++++- 5 files changed, 194 insertions(+), 19 deletions(-) diff --git a/app/src/App.tsx b/app/src/App.tsx index e28491c..ad18d06 100644 --- a/app/src/App.tsx +++ b/app/src/App.tsx @@ -84,6 +84,10 @@ const quoteName = (name: string) => `"${name.replace(/"/g, '""')}"`; const TAB_DRAG_TYPE = "application/x-openpl-tab"; const sqlTabActions = [ "execute", + "showSymbolCard", + "goToDefinition", + "goToDeclaration", + "goToImplementation", "executeScript", "explainPlan", "fetchAllRows", @@ -1396,6 +1400,13 @@ export default function App() { )} void onOpenObject(object, "view", tab.connection), + } : undefined} + openObject={(object, at) => void onOpenObject(object, "view", tab.connection, at)} completion={sqlCatalog(tab.sql.sessionId)} initialSql={tab.sql.initial} command={tab.sql.command} diff --git a/app/src/components/ProgramWindow.tsx b/app/src/components/ProgramWindow.tsx index 267c71a..755ece9 100644 --- a/app/src/components/ProgramWindow.tsx +++ b/app/src/components/ProgramWindow.tsx @@ -10,9 +10,11 @@ import { copyLineDown, deleteLine, indentLess, indentMore, redo, toggleComment, import { api } from "../api"; import { commands, formatKeys, type CommandId } from "../keymap"; import { describeError, type ObjectInfo, type ProgramPart } from "../types"; -import { editorPath, editorReference } from "../editorReference"; -import { navigationTargets, type NavigationGoal, type NavigationTarget } from "../editorNavigation"; -import { resolveSymbol } from "../symbolResolve"; +import { editorReference } from "../editorReference"; +import { + NAVIGATION_TITLES, navigationMenuItems, navigationTargets, resolveAt, + type NavigationGoal, type NavigationTarget, +} from "../editorNavigation"; import { partCaption } from "./SymbolCard"; import { positionAt, ProgramEditor, type EditorMarker } from "./ProgramEditor"; import { EditorObjectMenu, ObjectDescription, type ObjectCatalog, type ObjectRequest } from "./EditorObjectMenu"; @@ -107,11 +109,6 @@ function storedOutlineWidth() { } } -const NAVIGATION_TITLES: Record = { - definition: "Definiciones", - declaration: "Declaraciones", - implementation: "Implementaciones", -}; export function ProgramWindow({ parts, readOnly, onReadOnlyChange, onDirty, onWorkspaceChange, ref, fileName, catalog, active = true, readCurrentProgram, compilationTarget, compile, onTestRoutine, registerSource, symbols, symbolSelf, @@ -324,10 +321,9 @@ export function ProgramWindow({ const view = views.current[index]; if (!view) return; const position = at ?? view.state.selection.main.from; - const path = editorPath(view.state, position) ?? (position > 0 ? editorPath(view.state, position - 1) : null); - const context = symbolContext(view, position); - if (!path || !context) return; - const items = await resolveSymbol(context, path); + const found = await resolveAt(view, position, symbolContext); + if (!found) return; + const { name, items } = found; const relation = items.find((item) => item.kind === "relation"); if (relation?.kind === "relation") { if (catalog) setDescription({ object: relation.object, sessionId: catalog.sessionId, id: ++objectRequestId.current }); @@ -341,7 +337,7 @@ export function ProgramWindow({ const coords = view.coordsAtPos(position) ?? view.contentDOM.getBoundingClientRect(); closeObjectMenu(); setDeclarationMenu({ - title: `${NAVIGATION_TITLES[goal]} de ${path.parts[path.index]}`, + title: `${NAVIGATION_TITLES[goal]} de ${name}`, x: coords.left, y: coords.bottom, targets, }); } @@ -700,10 +696,7 @@ export function ProgramWindow({ {active && catalog && objectMenu && ( { - const id = goal === "definition" ? "goToDefinition" : goal === "declaration" ? "goToDeclaration" : "goToImplementation"; - return { label: commands[id].label, keys: commands[id].keys, run: () => void goTo(goal, objectMenu.part, objectMenu.position) }; - })} + navigation={navigationMenuItems((goal) => void goTo(goal, objectMenu.part, objectMenu.position))} onMessage={setMessage} onDescribe={(object) => setDescription({ object, sessionId: catalog.sessionId, id: objectMenu.id })} /> )} diff --git a/app/src/components/SqlWindow.test.tsx b/app/src/components/SqlWindow.test.tsx index 327afe9..05d0ed0 100644 --- a/app/src/components/SqlWindow.test.tsx +++ b/app/src/components/SqlWindow.test.tsx @@ -811,3 +811,49 @@ describe("WAL-115: la selección manda", () => { await waitFor(() => expect(view.dom.querySelector(".cm-lintRange-error")).not.toBeNull()); }); }); + +describe("ficha y navegación", () => { + const table = { owner: "HR", name: "CLIENTES", object_type: "Table" as const, status: "Valid" as const, last_ddl_time: "" }; + const symbols = () => ({ + object: vi.fn(async (_owner: string | null, name: string) => (name === "CLIENTES" ? table : null)), + parts: vi.fn(async () => []), + columns: vi.fn(async () => [{ name: "NOMBRE", data_type: "VARCHAR2(100)", nullable: true }]), + }); + + test("ficha de tabla en una ventana SQL", async () => { + const source = "SELECT * FROM clientes"; + const { ref, view } = setup(source, { symbols: symbols() }); + act(() => view.dispatch({ selection: { anchor: source.indexOf("clientes") + 1 } })); + act(() => ref.current!.showSymbolCard!()); + expect(await screen.findByText("VARCHAR2(100)")).toBeInTheDocument(); + }); + + test("F12 sobre una variable del bloque anónimo va a su declaración", async () => { + const source = "DECLARE v NUMBER := 1; BEGIN v := 2; END;"; + const { ref, view } = setup(source); + act(() => view.dispatch({ selection: { anchor: source.lastIndexOf("v :=") + 1 } })); + act(() => ref.current!.goToDefinition!()); + await waitFor(() => expect(view.state.selection.main.head).toBe(source.indexOf("v NUMBER"))); + }); + + test("F12 sobre una tabla la abre", async () => { + const openObject = vi.fn(); + const source = "SELECT * FROM clientes"; + const { ref, view } = setup(source, { symbols: symbols(), openObject }); + act(() => view.dispatch({ selection: { anchor: source.indexOf("clientes") + 1 } })); + act(() => ref.current!.goToDefinition!()); + await waitFor(() => expect(openObject).toHaveBeenCalledWith(table)); + }); + + test("clic derecho sobre un nombre ofrece navegación", async () => { + vi.spyOn(api, "editorObject").mockResolvedValue(table); + const source = "SELECT * FROM clientes"; + const { view } = setup(source, { + symbols: symbols(), + catalog: { sessionId: "s1", owner: null, openProgram: vi.fn() }, + }); + vi.spyOn(EditorView.prototype, "posAndSideAtCoords").mockReturnValue({ pos: source.indexOf("clientes") + 1, assoc: 1 }); + fireEvent.contextMenu(view.contentDOM, { clientX: 5, clientY: 5 }); + expect(await screen.findByRole("menuitem", { name: /Ir a la definición/ })).toBeInTheDocument(); + }); +}); diff --git a/app/src/components/SqlWindow.tsx b/app/src/components/SqlWindow.tsx index b2bcd3e..cc65c3d 100644 --- a/app/src/components/SqlWindow.tsx +++ b/app/src/components/SqlWindow.tsx @@ -19,7 +19,7 @@ import { api } from "../api"; import { commands, formatKeys, type CommandId } from "../keymap"; import { describeError, type BindKind, type BindValue, type Conflict, type EditTarget, type Environment, type ExecOutcome, - type ProgramPart, type SqlColumn, type TestOutput, type ExplainPlan, type CompletionObject, + type ProgramPart, type SqlColumn, type TestOutput, type ExplainPlan, type CompletionObject, type ObjectInfo, } from "../types"; import { editableQuery, ROWID_COLUMN } from "../sqlEdit"; import { appliedRows, buildChanges, emptyPending, pendingCount, pendingDiscardMessage, type Cell, type Pending } from "../gridEdits"; @@ -32,6 +32,14 @@ import { ProgramEditor, type EditorMarker } from "./ProgramEditor"; import type { ProgramActions } from "./ProgramWindow"; import { routineDraft } from "../routineTest"; import { serializeTestFile, type TestSettings } from "../testFile"; +import { ContextMenu } from "./ContextMenu"; +import { EditorObjectMenu, type ObjectCatalog, type ObjectRequest } from "./EditorObjectMenu"; +import { + NAVIGATION_TITLES, navigationMenuItems, navigationTargets, resolveAt, + type NavigationGoal, type NavigationTarget, +} from "../editorNavigation"; +import { showSymbolCard, type ContextFor } from "../symbolHover"; +import type { SymbolLookup } from "../symbolSources"; import "./SqlWindow.css"; interface Props { @@ -54,6 +62,12 @@ interface Props { onWorkspaceChange?: (text: string) => void; completion?: CompletionCatalog | null; ref?: Ref; + /** Catálogo de la conexión principal para la ficha y la navegación. */ + symbols?: SymbolLookup | null; + /** Menú contextual sobre nombres (Describir, Ver fuente, Copiar). */ + catalog?: ObjectCatalog; + /** Abre un objeto: tabla o vista en su descripción, programa en la posición pedida. */ + openObject?: (object: ObjectInfo, at?: { partKind: string; from: number }) => void; } interface Grid { @@ -124,6 +138,7 @@ const REASONS: Record = { const plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`; export function SqlWindow({ sessionId, command = false, active = true, onEditObject, initialSql = "", testSettings, runOnOpen, exportOnOpen, editOnOpen, environment, onTransaction, onBusy, onPendingChange, onDirty, onWorkspaceChange, completion, ref, + symbols, catalog, openObject, }: Props) { const part = useMemo(() => ({ kind: "SQL", source: initialSql, diagnostics: [], last_ddl_time: null }), // La parte inicial es fija: el editor conserva su propio texto. @@ -785,6 +800,54 @@ export function SqlWindow({ if (view.current) action(view.current); }; + const symbolsRef = useRef(symbols); + symbolsRef.current = symbols; + const symbolContext = useCallback((editor, position) => ({ + parts: [{ kind: "SQL", source: editor.state.doc.toString() }], + current: 0, + position, + self: null, + lookup: symbolsRef.current ?? null, + }), []); + const [objectMenu, setObjectMenu] = useState<(ObjectRequest & { id: number; position: number }) | null>(null); + const [targetsMenu, setTargetsMenu] = useState<{ title: string; x: number; y: number; targets: NavigationTarget[] } | null>(null); + const objectMenuId = useRef(0); + const closeObjectMenu = useCallback(() => setObjectMenu(null), []); + const closeTargetsMenu = useCallback(() => setTargetsMenu(null), []); + + function openTarget({ location }: NavigationTarget) { + const editor = view.current; + if (location.where === "object") { + openObject?.(location.object, { partKind: location.partKind, from: location.from }); + } else if (editor) { + editor.dispatch({ selection: { anchor: location.from }, scrollIntoView: true }); + editor.focus(); + } + } + + /** Definición, declaración o implementación del nombre en `at` (o en el cursor). */ + async function goTo(goal: NavigationGoal, at?: number) { + const editor = view.current; + if (!editor) return; + const position = at ?? editor.state.selection.main.from; + const found = await resolveAt(editor, position, symbolContext); + if (!found) return; + const relation = found.items.find((item) => item.kind === "relation"); + if (relation?.kind === "relation") { + openObject?.(relation.object); + return; + } + const { targets, notice } = navigationTargets(found.items, goal); + if (notice) setNotice(notice); + if (targets.length === 1) { + openTarget(targets[0]); + } else if (targets.length > 1) { + const coords = editor.coordsAtPos(position) ?? editor.contentDOM.getBoundingClientRect(); + closeObjectMenu(); + setTargetsMenu({ title: `${NAVIGATION_TITLES[goal]} de ${found.name}`, x: coords.left, y: coords.bottom, targets }); + } + } + const busy = running || fetching || applying; useEffect(() => { onBusy?.(busy); }, [busy, onBusy]); const actions: ProgramActions = { @@ -805,6 +868,10 @@ export function SqlWindow({ rollback: busy ? undefined : () => void transaction("rollback"), save: command ? undefined : () => void save(), complete: inEditor(startCompletion), + showSymbolCard: inEditor(showSymbolCard), + goToDefinition: () => void goTo("definition"), + goToDeclaration: () => void goTo("declaration"), + goToImplementation: () => void goTo("implementation"), foldBlock: inEditor(foldCode), unfoldBlock: inEditor(unfoldCode), goToLine: inEditor(gotoLine), @@ -919,6 +986,12 @@ export function SqlWindow({
{}} + symbolContext={symbolContext} + onCtrlClick={(position) => void goTo("definition", position)} + onObjectContext={catalog ? (reference, x, y, position) => { + closeTargetsMenu(); + setObjectMenu({ reference, x, y, position, id: ++objectMenuId.current }); + } : undefined} onView={onView} onSelection={setCursor} onChange={(doc) => { @@ -1136,6 +1209,20 @@ export function SqlWindow({ )}
{confirmationDialog} + {active && catalog && objectMenu && ( + void goTo(goal, objectMenu.position))} + onMessage={setNotice} + onDescribe={(object) => openObject?.(object)} /> + )} + {active && targetsMenu && ( + ({ + label: target.location.where === "object" ? `${target.location.object.name} · ${target.label}` : target.label, + run: () => openTarget(target), + }))} + onClose={closeTargetsMenu} /> + )} ); } diff --git a/app/src/editorNavigation.ts b/app/src/editorNavigation.ts index f315d57..34c0879 100644 --- a/app/src/editorNavigation.ts +++ b/app/src/editorNavigation.ts @@ -1,4 +1,9 @@ -import type { Resolved, SymbolLocation } from "./symbolResolve"; +import type { EditorView } from "@codemirror/view"; +import type { ContextItem } from "./components/ContextMenu"; +import { editorPath } from "./editorReference"; +import { commands, type CommandId } from "./keymap"; +import type { ContextFor } from "./symbolHover"; +import { resolveSymbol, type Resolved, type SymbolLocation } from "./symbolResolve"; export type NavigationGoal = "definition" | "declaration" | "implementation"; @@ -39,3 +44,36 @@ export function navigationTargets(items: Resolved[], goal: NavigationGoal): Navi } return missingBody ? { targets, notice: "Cuerpo no disponible" } : { targets }; } + +export const NAVIGATION_TITLES: Record = { + definition: "Definiciones", + declaration: "Declaraciones", + implementation: "Implementaciones", +}; + +const GOAL_COMMANDS: Record = { + definition: "goToDefinition", + declaration: "goToDeclaration", + implementation: "goToImplementation", +}; + +/** Ítems "Ir a…" del menú contextual de un nombre. */ +export function navigationMenuItems(run: (goal: NavigationGoal) => void): ContextItem[] { + return (["definition", "declaration", "implementation"] as const).map((goal) => ({ + label: commands[GOAL_COMMANDS[goal]].label, + keys: commands[GOAL_COMMANDS[goal]].keys, + run: () => run(goal), + })); +} + +/** Nombre en `position` (o justo antes) y lo que resuelve. */ +export async function resolveAt( + view: EditorView, + position: number, + contextFor: ContextFor, +): Promise<{ name: string; items: Resolved[] } | null> { + const path = editorPath(view.state, position) ?? (position > 0 ? editorPath(view.state, position - 1) : null); + const context = contextFor(view, position); + if (!path || !context) return null; + return { name: path.parts[path.index], items: await resolveSymbol(context, path) }; +} From 0547039d971a905d9fdc93971ccaf6bbe1c766e8 Mon Sep 17 00:00:00 2001 From: Walter Aquino Date: Fri, 27 Nov 2026 11:04:20 -0300 Subject: [PATCH 12/24] docs: WAL-119 editor inteligente Co-Authored-By: Claude Opus 5.5 --- .../audit-editor-inteligente-2026-11-27.md | 32 ++++++++++++ docs/ESTADO.md | 6 +++ docs/behavior/editor-inteligente.md | 49 +++++++++++++++++++ docs/behavior/programa.md | 2 +- 4 files changed, 88 insertions(+), 1 deletion(-) create mode 100644 anti-slop/audit-editor-inteligente-2026-11-27.md create mode 100644 docs/behavior/editor-inteligente.md diff --git a/anti-slop/audit-editor-inteligente-2026-11-27.md b/anti-slop/audit-editor-inteligente-2026-11-27.md new file mode 100644 index 0000000..1acfa52 --- /dev/null +++ b/anti-slop/audit-editor-inteligente-2026-11-27.md @@ -0,0 +1,32 @@ +# Auditoría antislop del editor inteligente + +Alcance: ficha de símbolo (`SymbolCard`, `.cm-symbol-tooltip`), subrayado de Ctrl+clic +(`.cm-symbol-link`) y los ítems nuevos del menú contextual. Skills: `antislop`, `antislop-ui`, +`antislop-human`. + +- **PASS, contraste de texto.** Medido con `contrast.ts` sobre `--s1`, fondo de la ficha: + + | Tema | `--text` | `--muted` | + |---|---|---| + | grafito | 9.83 | 6.35 | + | papel | 11.66 | 5.66 | + | medianoche | 11.83 | 7.30 | + | bosque | 10.84 | 6.90 | + | alto-contraste | 19.80 | 13.62 | + +- **PASS con nota, borde.** `--line2` sobre `--s1` queda entre 1.32 y 1.46 (4.61 en alto + contraste). Es el mismo borde de menús y diálogos de la app; la ficha además lleva sombra. No es + un control: no aplica el mínimo de 3:1 de componentes. +- **PASS, tokens.** Sin colores nuevos: `--s1`, `--line`, `--line2`, `--text`, `--muted`, + `--font-code`. IBM Plex Mono para firmas y tipos. +- **PASS, teclado.** La ficha se abre sin mouse con Ctrl+Shift+Espacio y se cierra con Esc. Los + tres comandos de navegación tienen atajo en `keymap.ts` y aparecen en el menú contextual con su + atajo. +- **PASS, no tapa la escritura.** La ficha se abre arriba del nombre, se cierra al escribir o + mover el cursor y no toma el foco. +- **PASS, estados.** Sin resultado no hay ficha. Fuente no legible: "Fuente no disponible". Sin + cuerpo: "Cuerpo no disponible". Sin conexión: solo lo local, nunca queda cargando. +- **PASS, copia.** Textos cortos en español: "Sin valor inicial", "Expresión", "Columna", + "N columnas más", nombres de los comandos. +- **Pendiente, escritorio.** Probar en la app real: pasar el puntero sobre una constante de un + paquete, Ctrl+clic en una llamada a otro paquete y F12 sobre una tabla en una ventana SQL. diff --git a/docs/ESTADO.md b/docs/ESTADO.md index 761c013..5e53f95 100644 --- a/docs/ESTADO.md +++ b/docs/ESTADO.md @@ -4,6 +4,8 @@ ## Resumen +- Editor inteligente (WAL-119, rama `xwhiterr/wal-119-editor-inteligente-ficha-al-pasar-el-mouse`): ficha al pasar el puntero con firma, tipo, valor declarado, comentario, campos de registros y columnas; Ir a la definición (F12, Ctrl+clic), a la declaración (Ctrl+F12) y a la implementación (Ctrl+Shift+F12) en paquetes, ventanas SQL y de prueba. [Comportamiento](behavior/editor-inteligente.md), [diseño](superpowers/specs/2026-11-27-openpl-editor-inteligente-design.md), [plan](superpowers/plans/2026-11-27-openpl-editor-inteligente.md) y [auditoría](../anti-slop/audit-editor-inteligente-2026-11-27.md). Pendiente la prueba en escritorio contra Oracle. + - 1.0.0-beta.8 (WAL-118, WAL-120): con una versión nueva, la barra superior muestra un ícono que da un salto corto y abre el diálogo de actualización. "Más tarde" deja el ícono. Nuevo y los menús de la barra ya no quedan abiertos a la vez. - Auditoría UX: los briefs 1 a 59 del [plan de 61 briefs](superpowers/plans/2026-11-25-openpl-auditoria-ux.md) @@ -124,6 +126,10 @@ Rama creada desde `main`, sin merge ni push. Auditoría: | Reemplazar | Ctrl+H | Ctrl+R (Ctrl+H sigue como alternativa) | | Refrescar explorador | Ctrl+R | Ctrl+Shift+R | | Rehacer | Ctrl+Shift+Z | Ctrl+Shift+Z o Ctrl+Y | +| Ir a la definición (WAL-119) | (F12 iba a la declaración) | F12 y Ctrl+clic | +| Ir a la declaración (WAL-119) | F12 | Ctrl+F12 | +| Ir a la implementación (WAL-119) | (no existía) | Ctrl+Shift+F12 | +| Mostrar ficha (WAL-119) | (no existía) | Ctrl+Shift+Espacio | | Ejecutar | F8 | F8 o Ctrl+Enter | | Buscar siguiente / anterior | sin atajo | F3 / Shift+F3 | | Pestaña siguiente / anterior | sin atajo | Ctrl+Tab / Ctrl+Shift+Tab | diff --git a/docs/behavior/editor-inteligente.md b/docs/behavior/editor-inteligente.md new file mode 100644 index 0000000..eec19fa --- /dev/null +++ b/docs/behavior/editor-inteligente.md @@ -0,0 +1,49 @@ +# Ficha y navegación en el editor + +Aplica a la ventana de programa, la ventana SQL y la ventana de prueba. La ventana de comando no +tiene ficha. + +## Ficha + +- Aparece al dejar el puntero quieto unos 400 ms sobre un nombre. Se cierra al moverlo o al + escribir. **Mostrar ficha** (Ctrl+Shift+Espacio) la abre en el cursor; Esc la cierra. +- **Rutinas y cursores:** firma completa con modos y tipos de parámetros y `RETURN`. Un cursor + muestra también las primeras líneas de su consulta. +- **Constantes y variables:** tipo y valor declarado (`:=` o `DEFAULT`). Sin valor declarado + dice "Sin valor inicial". No se lee el valor que tiene en una sesión. +- **Parámetros, tipos y subtipos:** su declaración. +- **Campos y columnas:** `registro.campo` resuelve el tipo del registro: `%ROWTYPE` de una tabla o + de un cursor, `RECORD` propio, colecciones (`t(i).campo`) y `%TYPE`. En un SELECT, `alias.columna` + muestra la columna de la tabla. Una columna de cursor que es una expresión muestra + "Expresión". +- **Tablas y vistas:** columnas con tipo y `NOT NULL`, hasta 30. +- Cada ficha dice dónde está la declaración (línea, y objeto y parte si es de otro objeto) y el + comentario pegado arriba de ella o al final de su línea. +- Las sobrecargas muestran una ficha por firma. +- Un objeto con la fuente envuelta o sin permiso de lectura dice "Fuente no disponible". + +## Orden de búsqueda + +1. Declaraciones locales visibles en el cursor: la más interna gana sobre una global con el + mismo nombre. +2. Declaraciones del paquete abierto, en Spec y Body. +3. Alias y tablas de la sentencia SQL. +4. Objetos del catálogo, con la conexión principal. Un paquete abierto en otra pestaña se lee del + editor, aunque tenga cambios sin guardar. + +Sin conexión solo se resuelve lo que está en el documento. La fuente de otros objetos se guarda +por conexión y se vuelve a pedir al compilar, refrescar el explorador o reconectar. + +## Navegación + +| Comando | Atajo | Destino | +|---|---|---| +| Ir a la definición | F12, Ctrl+clic | El cuerpo de la rutina; si no tiene, su declaración | +| Ir a la declaración | Ctrl+F12 | La declaración en la Spec; si no hay, el cuerpo | +| Ir a la implementación | Ctrl+Shift+F12 | El cuerpo; sin cuerpo, la declaración y el aviso "Cuerpo no disponible" | + +- Con Ctrl apretado, el nombre bajo el puntero se subraya. +- Con varias firmas, un selector lista cada destino. +- Un destino en otro objeto abre ese objeto (o activa su pestaña) en la línea de la declaración. +- Sobre una tabla o vista, los tres comandos abren su descripción. +- El menú contextual de un nombre suma los tres comandos arriba de Describir, Ver fuente y Copiar. diff --git a/docs/behavior/programa.md b/docs/behavior/programa.md index 5981f24..93d1978 100644 --- a/docs/behavior/programa.md +++ b/docs/behavior/programa.md @@ -5,7 +5,7 @@ La observación previa por uso normal está en [observaciones-referencia.md](obs - **Abrir** (Enter o doble clic) y **Ver** muestran la fuente. **Editar** habilita un borrador local. Los programas abiertos aparecen en pestañas identificadas por objeto y conexión. - Un paquete abre una ventana con **Spec** y **Body**. Se alternan con Alt+S y Alt+B. Ctrl+\ permite ver ambos. Un paquete sin cuerpo sigue abriendo su Spec. - La estructura sigue la parte activa. Los problemas obtenidos del diccionario indican línea y columna. Seleccionar una entrada lleva al editor. -- **Estructura** muestra variables y constantes de paquete, tipos, cursores y rutinas. Cada entrada lleva una letra de color según su clase (P procedimiento, F función, C cursor, V variable, N constante, T tipo, E excepción) y ocupa una línea; lo que no cabe se corta con puntos suspensivos y la firma completa aparece al pasar el puntero. En el Body solo se marcan las entradas privadas. El borde derecho del panel se arrastra para ensancharlo (también con flechas, Inicio y Fin); doble clic vuelve al ancho inicial y el ancho se recuerda. Las sobrecargas se distinguen por sus firmas. **F12** abre un selector si el nombre tiene varias declaraciones. +- **Estructura** muestra variables y constantes de paquete, tipos, cursores y rutinas. Cada entrada lleva una letra de color según su clase (P procedimiento, F función, C cursor, V variable, N constante, T tipo, E excepción) y ocupa una línea; lo que no cabe se corta con puntos suspensivos y la firma completa aparece al pasar el puntero. En el Body solo se marcan las entradas privadas. El borde derecho del panel se arrastra para ensancharlo (también con flechas, Inicio y Fin); doble clic vuelve al ancho inicial y el ancho se recuerda. Las sobrecargas se distinguen por sus firmas. **F12** va a la definición y abre un selector si el nombre tiene varias; ver [ficha y navegación](editor-inteligente.md). - **Plegar bloque** (Alt+Shift+P) y **Desplegar bloque** (Alt+Shift+A) están en **Ver** y actúan desde la línea de apertura. También se puede pulsar el indicador del margen. El plegado deja visibles las líneas de apertura y cierre. La navegación a una declaración o problema abre el código plegado que lo contiene. - **Nuevo** en la barra superior despliega Ventana SQL, Ventana de prueba y Ventana de comando (deshabilitadas hasta que existan) y plantillas de Programa en blanco, Paquete, Procedimiento, Función, Trigger, Tipo y Vista. Paquete y Tipo abren Spec y Body. **Archivo → Nuevo programa** (Ctrl+Alt+N) abre el programa en blanco. **Abrir programa** acepta archivos UTF-8 con extensión `.pks`, `.pkb` o `.sql`. El editor usa saltos de línea LF. - **Guardar** (Ctrl+S o **Archivo > Guardar**) escribe el contenido del editor activo en un archivo `.sql` local. Abre el selector del sistema con el último nombre usado (o `programa.sql`). No toca Oracle. Si se cancela el selector, el borrador conserva su estado. Cerrar la pestaña o la aplicación pide confirmación si hay cambios. From 63b66d969a781d3e966ce8a4ff265caa4b183774 Mon Sep 17 00:00:00 2001 From: Walter Aquino Date: Fri, 27 Nov 2026 11:14:04 -0300 Subject: [PATCH 13/24] =?UTF-8?q?fix(app):=20WAL-119=20correcciones=20de?= =?UTF-8?q?=20la=20revisi=C3=B3n=20del=20editor=20inteligente?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Spec y body con cabeceras distintas (IN, DEFAULT) son la misma rutina. - Campos, cursores y %TYPE se buscan desde el procedimiento actual. - Una rutina a medio escribir no oculta las siguientes. - Abrir otro objeto ubica por línea y columna, acotado al texto. - Las firmas conservan :=. Co-Authored-By: Claude Opus 5.5 --- app/src/App.tsx | 7 +-- app/src/components/ProgramWindow.test.tsx | 11 ++++ app/src/components/ProgramWindow.tsx | 4 +- app/src/components/SqlWindow.tsx | 4 +- app/src/components/SymbolCard.test.tsx | 4 +- app/src/editorNavigation.test.ts | 4 +- app/src/editorNavigation.ts | 2 +- app/src/programStructure.ts | 2 +- app/src/programSymbols.test.ts | 17 ++++++ app/src/programSymbols.ts | 32 +++++++++-- app/src/symbolResolve.test.ts | 33 +++++++++++- app/src/symbolResolve.ts | 66 +++++++++++++++-------- 12 files changed, 144 insertions(+), 42 deletions(-) diff --git a/app/src/App.tsx b/app/src/App.tsx index ad18d06..c88b4c9 100644 --- a/app/src/App.tsx +++ b/app/src/App.tsx @@ -128,7 +128,7 @@ interface ProgramTab { workspaceProfileId?: string; load?: symbol; /** Posición pedida por "Ir a la definición" desde otra ventana. */ - target?: { partKind: string; from: number }; + target?: { partKind: string; line: number; column: number }; /** Ventana SQL: sesión propia, texto inicial y estado de su transacción. */ sql?: { sessionId: string; @@ -955,7 +955,7 @@ export default function App() { object: ObjectInfo, mode: "view" | "edit" = "view", connection = active, - at?: { partKind: string; from: number }, + at?: { partKind: string; line: number; column: number }, ) { if (!connection) return; if (!supportsProgram.has(object.object_type)) { @@ -1464,7 +1464,8 @@ export default function App() { if (location.where !== "object" || !editorConnection) return; void onOpenObject(location.object, "view", editorConnection, { partKind: location.partKind, - from: location.from, + line: location.line, + column: location.column, }); }} registerSource={tab.object && tab.connection diff --git a/app/src/components/ProgramWindow.test.tsx b/app/src/components/ProgramWindow.test.tsx index 3314251..f535652 100644 --- a/app/src/components/ProgramWindow.test.tsx +++ b/app/src/components/ProgramWindow.test.tsx @@ -889,3 +889,14 @@ describe("ir a la definición", () => { expect(await screen.findByRole("region", { name: "Descripción de HR.CLIENTES" })).toBeInTheDocument(); }); }); + +test("un destino pedido se ubica por línea y columna, aunque esté fuera del texto", () => { + const source = "PACKAGE PKG_A AS\n PROCEDURE hacer;\nEND;"; + const { rerender } = render(); + const view = EditorView.findFromDOM(screen.getByRole("textbox", { name: "Spec" }).closest(".cm-editor")!)!; + expect(view.state.selection.main.head).toBe(source.indexOf("hacer")); + rerender(); + expect(view.state.selection.main.head).toBe(source.length); +}); diff --git a/app/src/components/ProgramWindow.tsx b/app/src/components/ProgramWindow.tsx index 755ece9..ec5dabd 100644 --- a/app/src/components/ProgramWindow.tsx +++ b/app/src/components/ProgramWindow.tsx @@ -75,7 +75,7 @@ interface Props { /** Destinos en otro objeto: la ventana pide abrirlo. */ onNavigate?: (target: NavigationTarget) => void; /** Posición a la que ir al abrir o al pedir un destino nuevo. */ - initialTarget?: { partKind: string; from: number }; + initialTarget?: { partKind: string; line: number; column: number }; } const caption = (kind: string) => { @@ -346,7 +346,7 @@ export function ProgramWindow({ useEffect(() => { if (!initialTarget) return; const index = parts.findIndex((part) => part.kind === initialTarget.partKind); - if (index >= 0) navigateAt(index, initialTarget.from); + if (index >= 0) navigate(index, initialTarget.line, initialTarget.column); // Solo al pedir un destino nuevo; `parts` llega junto con él. // eslint-disable-next-line react-hooks/exhaustive-deps }, [initialTarget]); diff --git a/app/src/components/SqlWindow.tsx b/app/src/components/SqlWindow.tsx index cc65c3d..80a9aef 100644 --- a/app/src/components/SqlWindow.tsx +++ b/app/src/components/SqlWindow.tsx @@ -67,7 +67,7 @@ interface Props { /** Menú contextual sobre nombres (Describir, Ver fuente, Copiar). */ catalog?: ObjectCatalog; /** Abre un objeto: tabla o vista en su descripción, programa en la posición pedida. */ - openObject?: (object: ObjectInfo, at?: { partKind: string; from: number }) => void; + openObject?: (object: ObjectInfo, at?: { partKind: string; line: number; column: number }) => void; } interface Grid { @@ -818,7 +818,7 @@ export function SqlWindow({ function openTarget({ location }: NavigationTarget) { const editor = view.current; if (location.where === "object") { - openObject?.(location.object, { partKind: location.partKind, from: location.from }); + openObject?.(location.object, { partKind: location.partKind, line: location.line, column: location.column }); } else if (editor) { editor.dispatch({ selection: { anchor: location.from }, scrollIntoView: true }); editor.focus(); diff --git a/app/src/components/SymbolCard.test.tsx b/app/src/components/SymbolCard.test.tsx index 2398407..a15110b 100644 --- a/app/src/components/SymbolCard.test.tsx +++ b/app/src/components/SymbolCard.test.tsx @@ -11,7 +11,7 @@ const symbol = (overrides: Partial): ProgramSymbol => ({ kind: "variable", name: "X", signature: "x NUMBER", dataType: "NUMBER", value: null, comment: null, from: 0, scope: null, definition: false, container: null, ...overrides, }); -const here = { where: "here" as const, part: 0, from: 0, line: 1 }; +const here = { where: "here" as const, part: 0, from: 0, line: 1, column: 1 }; test("constante muestra tipo y valor", () => { const items: Resolved[] = [{ @@ -33,7 +33,7 @@ test("ubicación con línea y comentario", () => { const items: Resolved[] = [{ kind: "symbol", symbol: symbol({ kind: "function", signature: "FUNCTION calcular RETURN NUMBER", comment: "Calcula el total" }), - location: { where: "object", object: pkg, partKind: "PACKAGE BODY", from: 0, line: 12 }, + location: { where: "object", object: pkg, partKind: "PACKAGE BODY", from: 0, line: 12, column: 1 }, }]; render(); expect(screen.getByText("FUNCTION calcular RETURN NUMBER")).toBeVisible(); diff --git a/app/src/editorNavigation.test.ts b/app/src/editorNavigation.test.ts index 88d69a5..5999a78 100644 --- a/app/src/editorNavigation.test.ts +++ b/app/src/editorNavigation.test.ts @@ -9,7 +9,7 @@ const routine = (part: number, definition: boolean, signature = "PROCEDURE p(a N kind: "procedure", name: "P", signature, dataType: null, value: null, comment: null, from: part * 100, scope: null, definition, container: null, } satisfies ProgramSymbol, - location: { where: "here", part, from: part * 100, line: 1 }, + location: { where: "here", part, from: part * 100, line: 1, column: 1 }, }); const parts = (choice: ReturnType) => @@ -42,7 +42,7 @@ test("una variable no pide cuerpo", () => { const variable: Resolved = { kind: "symbol", symbol: { ...(routine(0, false) as { symbol: ProgramSymbol }).symbol, kind: "variable", signature: "v NUMBER" }, - location: { where: "here", part: 0, from: 5, line: 1 }, + location: { where: "here", part: 0, from: 5, line: 1, column: 6 }, }; const choice = navigationTargets([variable], "implementation"); expect(choice.targets).toHaveLength(1); diff --git a/app/src/editorNavigation.ts b/app/src/editorNavigation.ts index 34c0879..aa945d8 100644 --- a/app/src/editorNavigation.ts +++ b/app/src/editorNavigation.ts @@ -29,7 +29,7 @@ export function navigationTargets(items: Resolved[], goal: NavigationGoal): Navi const groups = new Map[]>(); for (const item of items) { if (item.kind !== "symbol") continue; - const key = `${item.symbol.kind}|${item.symbol.signature.replace(/\s+/g, " ").toUpperCase()}`; + const key = item.symbol.key ?? `${item.symbol.kind}|${item.symbol.signature.replace(/\s+/g, " ").toUpperCase()}`; groups.set(key, [...(groups.get(key) ?? []), item]); } let missingBody = false; diff --git a/app/src/programStructure.ts b/app/src/programStructure.ts index ab97ed1..5730a97 100644 --- a/app/src/programStructure.ts +++ b/app/src/programStructure.ts @@ -118,7 +118,7 @@ export function format(tokens: Token[]) { .join(""); } -function normalizedParameter(tokens: Token[]) { +export function normalizedParameter(tokens: Token[]) { // IN es el modo predeterminado, pero IN OUT es distinto de OUT. return tokens .filter( diff --git a/app/src/programSymbols.test.ts b/app/src/programSymbols.test.ts index e9a8eca..6c0168e 100644 --- a/app/src/programSymbols.test.ts +++ b/app/src/programSymbols.test.ts @@ -146,3 +146,20 @@ test("bloque anónimo declara locales", () => { test("texto incompleto no lanza", () => { expect(Array.isArray(programSymbols("PACKAGE BODY x IS PROCEDURE p(a NUMBER"))).toBe(true); }); + +test("la firma conserva := en los valores por omisión", () => { + expect(one(programSymbols(spec(" PROCEDURE p(a NUMBER := 0);")), "P").signature).toBe("PROCEDURE p(a NUMBER := 0)"); +}); + +test("una lista de parámetros sin cerrar no oculta lo que sigue", () => { + const symbols = programSymbols(body(" PROCEDURE a(p NUMBER IS BEGIN NULL; END;\n PROCEDURE b IS BEGIN NULL; END;")); + expect(find(symbols, "B")).toHaveLength(1); +}); + +test("un IF sin cerrar no oculta las rutinas siguientes", () => { + const symbols = programSymbols(body( + " PROCEDURE a IS BEGIN IF x THEN NULL; END;\n PROCEDURE b IS v NUMBER; BEGIN NULL; END;\n g_fin NUMBER;", + )); + expect(find(symbols, "B")).toHaveLength(1); + expect(one(symbols, "V").scope).not.toBeNull(); +}); diff --git a/app/src/programSymbols.ts b/app/src/programSymbols.ts index 21db946..d91677c 100644 --- a/app/src/programSymbols.ts +++ b/app/src/programSymbols.ts @@ -3,6 +3,7 @@ import { boundary, findCreatedUnit, format, + normalizedParameter, isIdentifier, matchingBlocks, nameOf, @@ -39,6 +40,8 @@ export interface ProgramSymbol { /** Rutina, cursor o tipo dueño de parámetros y campos. */ container: string | null; query?: string; + /** Rutinas: identifica la misma rutina en spec y body aunque cambien IN o los valores por omisión. */ + key?: string; } interface Span { @@ -48,6 +51,10 @@ interface Span { } const tokenEnd = (token: Token) => token.from + token.text.length; +/** Como `format`, sin separar el `:=` que el tokenizador parte en dos. */ +const signatureOf = (tokens: Token[]) => format(tokens).replace(/:\s=/g, ":="); +const listStops = new Set([";", "IS", "AS"]); +const routineStarts = new Set(["PROCEDURE", "FUNCTION"]); const statementEnd = new Set([";"]); const routineMarkers = new Set([";", "IS", "AS"]); const parameterModes = new Set(["IN", "OUT", "NOCOPY"]); @@ -169,6 +176,11 @@ class Analyzer { let start = open + 1; for (let i = open; i < this.tokens.length; i += 1) { const { key } = this.tokens[i]; + // Paréntesis sin cerrar: la lista termina donde empieza el cuerpo o la sentencia. + if (listStops.has(key)) { + if (i > start) items.push([start, i]); + return { items, after: i }; + } if (key === "(") depth += 1; else if (key === ")") depth -= 1; if ((key === "," && depth === 1) || depth === 0) { @@ -270,7 +282,7 @@ class Analyzer { this.push({ kind: subtype ? "subtype" : "type", name: typeName, - signature: format(tokens.slice(start, end)), + signature: signatureOf(tokens.slice(start, end)), dataType: this.text(definitionStart, subtype ? this.typeEnd(definitionStart, end) : end) || null, value: null, comment: this.comment(start, end), @@ -297,7 +309,7 @@ class Analyzer { this.push({ kind, name: nameOf(name), - signature: format(tokens.slice(from, assign?.at ?? to)), + signature: signatureOf(tokens.slice(from, assign?.at ?? to)), dataType: this.text(typeStart, typeEnd) || null, value: assign ? this.text(assign.at + assign.size, to) || null : null, from: name.from, @@ -318,7 +330,7 @@ class Analyzer { const returns = tokens[after]?.key === "RETURN" ? tokens.slice(after + 1, marker) : []; const modifier = returns.findIndex((token) => signatureModifiers.has(token.key)); if (modifier >= 0) returns.length = modifier; - const parameters = items.map(([from, to]) => format(tokens.slice(from, to))); + const parameters = items.map(([from, to]) => signatureOf(tokens.slice(from, to))); const signature = `${kind} ${this.text(start + 1, nameIndex + 1)}` + (parameters.length ? `(${parameters.join(", ")})` : "") + @@ -338,6 +350,12 @@ class Analyzer { scope, definition, container: null, + key: JSON.stringify([ + kind, + routineName, + items.map(([from, to]) => normalizedParameter(tokens.slice(from, this.assignment(from, to)?.at ?? to))), + returns.map((token) => token.key), + ]), }; this.out.push(symbol); for (const [from, to] of items) this.member(from, to, "parameter", routineName, own); @@ -352,7 +370,13 @@ class Analyzer { own.to = this.source.length; const stop = this.section(marker + 1, own); const closing = tokens[stop]?.key === "BEGIN" ? this.blocks.get(stop) : tokens[stop]?.key === "END" ? stop : undefined; - if (closing === undefined) return tokens.length; + if (closing === undefined) { + // Cuerpo sin END (se está escribiendo): sigue en la próxima rutina que empieza una sentencia. + const next = tokens.findIndex((token, i) => i > stop && routineStarts.has(token.key) && tokens[i - 1]?.key === ";"); + if (next < 0) return tokens.length; + own.to = tokens[next].from; + return next; + } const end = this.statementEnd(closing); own.to = this.endOf(end); return end + 1; diff --git a/app/src/symbolResolve.test.ts b/app/src/symbolResolve.test.ts index 6c1a602..82376b6 100644 --- a/app/src/symbolResolve.test.ts +++ b/app/src/symbolResolve.test.ts @@ -62,8 +62,8 @@ test("llamada a rutina del mismo paquete devuelve spec y body", async () => { "PACKAGE BODY pkg IS\n FUNCTION calcular RETURN NUMBER IS BEGIN RETURN 1; END;\n PROCEDURE p IS x NUMBER; BEGIN x := calcular; END;\nEND;"; const found = await resolveSymbol(at([spec, body], "calcular;"), path(["CALCULAR"])); expect(found.map((item) => item.kind === "symbol" && item.location)).toEqual([ - { where: "here", part: 0, from: spec.indexOf("calcular"), line: 2 }, - { where: "here", part: 1, from: body.indexOf("calcular"), line: 2 }, + { where: "here", part: 0, from: spec.indexOf("calcular"), line: 2, column: 12 }, + { where: "here", part: 1, from: body.indexOf("calcular"), line: 2, column: 12 }, ]); }); @@ -182,3 +182,32 @@ test("con el objeto propio las ubicaciones siguen siendo del documento", async ( const [found] = await resolveSymbol(context, path(["V"])); expect(found).toMatchObject({ kind: "symbol", location: { where: "here" } }); }); + +test("spec y cuerpo con cabeceras distintas son la misma rutina", async () => { + const { navigationTargets } = await import("./editorNavigation"); + const spec = "PACKAGE pkg IS\n PROCEDURE registrar(p_id IN NUMBER, p_x NUMBER DEFAULT 0);\nEND;"; + const body = "PACKAGE BODY pkg IS\n PROCEDURE registrar(p_id NUMBER, p_x NUMBER := 0) IS BEGIN NULL; END;\nBEGIN\n registrar(1);\nEND;"; + const found = await resolveSymbol(at([spec, body], "registrar(1)"), path(["REGISTRAR"])); + const choice = navigationTargets(found, "definition"); + expect(choice.targets).toHaveLength(1); + expect(choice.targets[0].location).toMatchObject({ where: "here", part: 1 }); + expect(navigationTargets(found, "implementation").notice).toBeUndefined(); +}); + +test("los campos se buscan en el cursor del procedimiento actual", async () => { + const body = + "PACKAGE BODY pkg IS\n" + + " PROCEDURE a IS CURSOR c IS SELECT 1 uno FROM dual; r c%ROWTYPE; BEGIN x := r.uno; END;\n" + + " PROCEDURE b IS CURSOR c IS SELECT 2 dos FROM dual; r c%ROWTYPE; BEGIN x := r.dos; END;\n" + + "END;"; + const found = await resolveSymbol(at(["PACKAGE pkg IS END;", body], "dos;"), path(["R", "DOS"])); + expect(found).toEqual([ + { kind: "column", table: "C", column: { name: "DOS", data_type: "Expresión", nullable: true } }, + ]); +}); + +test("la ubicación incluye la columna", async () => { + const source = "DECLARE\n v NUMBER;\nBEGIN v := 1; END;"; + const [found] = await resolveSymbol(at([source], "v :="), path(["V"])); + expect(found).toMatchObject({ location: { line: 2, column: 5 } }); +}); diff --git a/app/src/symbolResolve.ts b/app/src/symbolResolve.ts index c61d0f3..9b6df9d 100644 --- a/app/src/symbolResolve.ts +++ b/app/src/symbolResolve.ts @@ -6,8 +6,8 @@ import type { SourcePart, SymbolLookup } from "./symbolSources"; import type { ObjectColumn, ObjectInfo, ObjectType } from "./types"; export type SymbolLocation = - | { where: "here"; part: number; from: number; line: number } - | { where: "object"; object: ObjectInfo; partKind: string; from: number; line: number }; + | { where: "here"; part: number; from: number; line: number; column: number } + | { where: "object"; object: ObjectInfo; partKind: string; from: number; line: number; column: number }; export type Resolved = | { kind: "symbol"; symbol: ProgramSymbol; location: SymbolLocation } @@ -54,9 +54,15 @@ interface Home { object: ObjectInfo | null; } +/** Parte y posición desde donde se busca: elige el alcance local más interno. */ +interface At { + part: number; + position: number; +} + type Entity = | { t: "unit"; home: Home } - | { t: "record"; home: Home; dataType: string } + | { t: "record"; home: Home; dataType: string; at?: At } | { t: "query"; home: Home; query: string; label: string } | { t: "relation"; owner: string | null; name: string } | { t: "schema"; owner: string }; @@ -74,13 +80,15 @@ function lineAt(source: string, from: number) { } function located(home: Home, part: number, symbol: ProgramSymbol): Resolved { - const line = lineAt(home.parts[part].source, symbol.from); + const { source } = home.parts[part]; + const line = lineAt(source, symbol.from); + const column = symbol.from - (source.lastIndexOf("\n", symbol.from - 1) + 1) + 1; return { kind: "symbol", symbol, location: home.object - ? { where: "object", object: home.object, partKind: home.parts[part].kind, from: symbol.from, line } - : { where: "here", part, from: symbol.from, line }, + ? { where: "object", object: home.object, partKind: home.parts[part].kind, from: symbol.from, line, column } + : { where: "here", part, from: symbol.from, line, column }, }; } @@ -103,12 +111,20 @@ function unitMembers(home: Home, name: string, kinds?: Set) { return found; } -function findSymbol(home: Home, name: string, kinds: Set) { - for (let part = 0; part < home.symbols.length; part += 1) { - const symbol = home.symbols[part].find((item) => item.name === name && kinds.has(item.kind)); - if (symbol) return { part, symbol }; +/** El símbolo visible desde `at` (local más interno), si no el de nivel de unidad, si no el primero. */ +function findSymbol(home: Home, name: string, kinds: Set, at?: At) { + const found: { part: number; symbol: ProgramSymbol }[] = []; + home.symbols.forEach((symbols, part) => { + for (const symbol of symbols) if (symbol.name === name && kinds.has(symbol.kind)) found.push({ part, symbol }); + }); + if (at) { + const size = ({ symbol }: { symbol: ProgramSymbol }) => symbol.scope!.to - symbol.scope!.from; + const local = found + .filter(({ part, symbol }) => part === at.part && symbol.scope && symbol.scope.from <= at.position && at.position <= symbol.scope.to) + .sort((a, b) => size(a) - size(b)); + if (local.length) return local[0]; } - return null; + return found.find(({ symbol }) => !symbol.scope) ?? found[0] ?? null; } const typeKinds = new Set(["type", "subtype"]); @@ -189,7 +205,8 @@ class Resolver { if (symbol.query !== undefined && !symbol.dataType) { return { t: "query", home, query: symbol.query, label: symbol.name }; } - return symbol.dataType ? { t: "record", home, dataType: symbol.dataType } : null; + const at = { part: this.ctx.current, position: this.ctx.position }; + return symbol.dataType ? { t: "record", home, dataType: symbol.dataType, at } : null; } private async firstEntity(name: string): Promise { @@ -213,9 +230,9 @@ class Resolver { : null; } if (entity.t === "record") { - const [found] = await this.typeMembers(entity.home, entity.dataType, name, 0); + const [found] = await this.typeMembers(entity.home, entity.dataType, name, 0, entity.at); return found?.kind === "symbol" && found.symbol.dataType - ? { t: "record", home: entity.home, dataType: found.symbol.dataType } + ? { t: "record", home: entity.home, dataType: found.symbol.dataType, at: entity.at } : null; } return null; @@ -234,21 +251,21 @@ class Resolver { return column ? [{ kind: "column", table: entity.name, column }] : []; } case "record": - return this.typeMembers(entity.home, entity.dataType, name, 0); + return this.typeMembers(entity.home, entity.dataType, name, 0, entity.at); case "query": return this.queryColumn(entity.query, name, entity.label); } } /** Campo `name` de un valor de tipo `dataType` declarado en `home`. */ - private async typeMembers(home: Home, dataType: string, name: string, depth: number): Promise { + private async typeMembers(home: Home, dataType: string, name: string, depth: number, at?: At): Promise { if (depth > MAX_DEPTH) return []; const text = dataType.trim(); const rowType = /^(.+)%ROWTYPE$/i.exec(text); if (rowType) { const base = nameParts(rowType[1]); if (base.length === 1) { - const cursor = findSymbol(home, base[0], cursorKinds); + const cursor = findSymbol(home, base[0], cursorKinds, at); if (cursor?.symbol.query) return this.queryColumn(cursor.symbol.query, name, cursor.symbol.name); } const table = base[base.length - 1]; @@ -258,32 +275,35 @@ class Resolver { const anchored = /^(.+)%TYPE$/i.exec(text); if (anchored) { const base = nameParts(anchored[1]); - const variable = base.length === 1 ? findSymbol(home, base[0], valueKinds) : null; + const variable = base.length === 1 ? findSymbol(home, base[0], valueKinds, at) : null; return variable?.symbol.dataType - ? this.typeMembers(home, variable.symbol.dataType, name, depth + 1) + ? this.typeMembers(home, variable.symbol.dataType, name, depth + 1, at) : []; } const collection = /^(?:TABLE|VARRAY\s*\([^)]*\)|VARYING\s+ARRAY\s*\([^)]*\))\s+OF\s+(.+?)(?:\s+INDEX\s+BY\s+[\s\S]*)?(?:\s+NOT\s+NULL)?$/i.exec(text); - if (collection) return this.typeMembers(home, collection[1], name, depth + 1); + if (collection) return this.typeMembers(home, collection[1], name, depth + 1, at); const base = nameParts(text); let typeHome: Home | null = home; + let typeAt = at; if (base.length === 2) { const object = await this.object(null, base[0]); typeHome = object?.object_type === "Package" ? await this.home(object) : null; + typeAt = undefined; } else if (base.length !== 1) { return []; } if (!typeHome) return []; - const type = findSymbol(typeHome, base[base.length - 1], typeKinds); + const type = findSymbol(typeHome, base[base.length - 1], typeKinds, typeAt); if (!type) return []; if (type.symbol.kind === "type" && /^RECORD\b/i.test(type.symbol.dataType ?? "")) { return typeHome.symbols[type.part] - .filter((symbol) => symbol.kind === "field" && symbol.container === type.symbol.name && symbol.name === name) + .filter((symbol) => symbol.kind === "field" && symbol.container === type.symbol.name && symbol.name === name && + symbol.scope?.from === type.symbol.scope?.from) .map((symbol) => located(typeHome, type.part, symbol)); } - return type.symbol.dataType ? this.typeMembers(typeHome, type.symbol.dataType, name, depth + 1) : []; + return type.symbol.dataType ? this.typeMembers(typeHome, type.symbol.dataType, name, depth + 1, typeAt) : []; } /** Columna `name` de la lista de un SELECT; tipo de la tabla si es una columna simple. */ From cd2d91bd395e2ab70ce848f67218012583f86ef1 Mon Sep 17 00:00:00 2001 From: Walter Aquino Date: Fri, 27 Nov 2026 11:18:59 -0300 Subject: [PATCH 14/24] =?UTF-8?q?perf(app):=20WAL-121=20an=C3=A1lisis=20de?= =?UTF-8?q?=20s=C3=ADmbolos=20sin=20reparsear?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Un solo recorrido del árbol da tokens y comentarios, la búsqueda del comentario es binaria, el editor pasa su árbol incremental y los alias se buscan solo en la sentencia actual. 14.000 líneas: 381 ms → 120 ms en frío, unos 25 ms con el árbol del editor. Co-Authored-By: Claude Opus 5.5 --- app/src/components/ProgramWindow.test.tsx | 4 +- app/src/components/ProgramWindow.tsx | 10 ++-- app/src/components/SqlWindow.tsx | 4 +- app/src/programSymbols.test.ts | 18 +++++++ app/src/programSymbols.ts | 57 ++++++++++++++++------- app/src/symbolHover.ts | 8 ++++ app/src/symbolResolve.test.ts | 17 +++++++ app/src/symbolResolve.ts | 18 +++++-- app/src/symbolSources.ts | 3 ++ 9 files changed, 109 insertions(+), 30 deletions(-) diff --git a/app/src/components/ProgramWindow.test.tsx b/app/src/components/ProgramWindow.test.tsx index f535652..f0e5dee 100644 --- a/app/src/components/ProgramWindow.test.tsx +++ b/app/src/components/ProgramWindow.test.tsx @@ -781,10 +781,12 @@ test("registra su texto vivo y se da de baja al cerrarse", () => { const editor = screen.getByRole("textbox", { name: "Spec" }); const view = EditorView.findFromDOM(editor.closest(".cm-editor")!)!; act(() => view.dispatch({ changes: { from: 0, insert: "-- nuevo\n" } })); - expect(read()).toEqual([ + const live = read(); + expect(live).toMatchObject([ { kind: "PACKAGE", source: `-- nuevo\n${parts[0].source}` }, { kind: "PACKAGE BODY", source: parts[1].source }, ]); + expect((live[0] as { tree?: unknown }).tree).toBeDefined(); unmount(); expect(release).toHaveBeenCalledOnce(); }); diff --git a/app/src/components/ProgramWindow.tsx b/app/src/components/ProgramWindow.tsx index ec5dabd..72a6e22 100644 --- a/app/src/components/ProgramWindow.tsx +++ b/app/src/components/ProgramWindow.tsx @@ -24,7 +24,7 @@ import { programStructure, type DeclarationKind, type ProgramDeclaration } from import { useCompletionCatalog } from "../useCompletionCatalog"; import { ContextMenu } from "./ContextMenu"; import type { SourcePart, SymbolLookup } from "../symbolSources"; -import { showSymbolCard, type ContextFor } from "../symbolHover"; +import { editorPart, showSymbolCard, type ContextFor } from "../symbolHover"; export type ProgramActions = Partial void>> & { hasPending?: () => boolean }; @@ -156,10 +156,10 @@ export function ProgramWindow({ liveParts.current = parts; const registerRef = useRef(registerSource); registerRef.current = registerSource; - const liveSources = useCallback(() => liveParts.current.map((entry, index) => ({ - kind: entry.kind, - source: views.current[index]?.state.doc.toString() ?? entry.source, - })), []); + const liveSources = useCallback(() => liveParts.current.map((entry, index): SourcePart => { + const view = views.current[index]; + return view ? editorPart(entry.kind, view) : { kind: entry.kind, source: entry.source }; + }), []); useEffect(() => registerRef.current?.(liveSources), [liveSources]); const symbolRefs = useRef({ symbols, symbolSelf }); symbolRefs.current = { symbols, symbolSelf }; diff --git a/app/src/components/SqlWindow.tsx b/app/src/components/SqlWindow.tsx index 80a9aef..51cd9b1 100644 --- a/app/src/components/SqlWindow.tsx +++ b/app/src/components/SqlWindow.tsx @@ -38,7 +38,7 @@ import { NAVIGATION_TITLES, navigationMenuItems, navigationTargets, resolveAt, type NavigationGoal, type NavigationTarget, } from "../editorNavigation"; -import { showSymbolCard, type ContextFor } from "../symbolHover"; +import { editorPart, showSymbolCard, type ContextFor } from "../symbolHover"; import type { SymbolLookup } from "../symbolSources"; import "./SqlWindow.css"; @@ -803,7 +803,7 @@ export function SqlWindow({ const symbolsRef = useRef(symbols); symbolsRef.current = symbols; const symbolContext = useCallback((editor, position) => ({ - parts: [{ kind: "SQL", source: editor.state.doc.toString() }], + parts: [editorPart("SQL", editor)], current: 0, position, self: null, diff --git a/app/src/programSymbols.test.ts b/app/src/programSymbols.test.ts index 6c0168e..3a25368 100644 --- a/app/src/programSymbols.test.ts +++ b/app/src/programSymbols.test.ts @@ -163,3 +163,21 @@ test("un IF sin cerrar no oculta las rutinas siguientes", () => { expect(find(symbols, "B")).toHaveLength(1); expect(one(symbols, "V").scope).not.toBeNull(); }); + +test("un paquete de 14.000 líneas se analiza rápido", () => { + const routine = (n: number) => + ` -- rutina ${n}\n PROCEDURE p${n}(a IN NUMBER, b VARCHAR2 := 'x') IS\n v NUMBER := 1;\n` + + " CURSOR c IS SELECT id, nombre FROM clientes WHERE id = a;\n BEGIN\n" + + " FOR r IN c LOOP\n IF r.id > 0 THEN v := v + 1; END IF;\n END LOOP;\n END;\n"; + let source = "CREATE OR REPLACE PACKAGE BODY pkg IS\n"; + for (let i = 0; i < 1600; i += 1) source += routine(i); + source += "END;"; + programSymbols(source.slice(0, 2000)); + const start = performance.now(); + const symbols = programSymbols(source); + const elapsed = performance.now() - start; + expect(symbols.filter((symbol) => symbol.kind === "procedure")).toHaveLength(1600); + expect(symbols.find((symbol) => symbol.name === "P1599")?.comment).toBe("rutina 1599"); + // Holgado para máquinas lentas; antes tardaba más de 300 ms. + expect(elapsed).toBeLessThan(180); +}); diff --git a/app/src/programSymbols.ts b/app/src/programSymbols.ts index d91677c..a8a6ab2 100644 --- a/app/src/programSymbols.ts +++ b/app/src/programSymbols.ts @@ -10,9 +10,12 @@ import { readName, signatureModifiers, storedUnits, - tokenize, type Token, } from "./programStructure"; +import type { syntaxTree } from "@codemirror/language"; + +/** Árbol de sintaxis de CodeMirror (el de lezer, sin depender de él directamente). */ +export type Tree = ReturnType; export type SymbolKind = | "package" | "procedure" | "function" | "cursor" | "type" | "subtype" @@ -59,15 +62,35 @@ const statementEnd = new Set([";"]); const routineMarkers = new Set([";", "IS", "AS"]); const parameterModes = new Set(["IN", "OUT", "NOCOPY"]); -function commentSpans(source: string): Span[] { - const spans: Span[] = []; - oracleDialect.language.parser.parse(source).iterate({ +/** Tokens (como `tokenize`) y comentarios en una sola pasada; reusa el árbol del editor si lo hay. */ +function scan(source: string, tree?: Tree) { + const tokens: Token[] = []; + const comments: Span[] = []; + (tree ?? oracleDialect.language.parser.parse(source)).iterate({ enter(node) { - if (node.name !== "LineComment" && node.name !== "BlockComment") return; - spans.push({ from: node.from, to: node.to, text: source.slice(node.from, node.to) }); + if (node.from === node.to) return; + if (node.name === "LineComment" || node.name === "BlockComment") { + comments.push({ from: node.from, to: node.to, text: source.slice(node.from, node.to) }); + return; + } + if (node.node.firstChild) return; + const text = source.slice(node.from, node.to); + tokens.push({ text, key: text.startsWith('"') ? text : text.toUpperCase(), from: node.from }); }, }); - return spans; + return { tokens, comments }; +} + +/** Índice del primer comentario con `from >= position`. */ +function firstFrom(spans: Span[], position: number) { + let low = 0; + let high = spans.length; + while (low < high) { + const middle = (low + high) >> 1; + if (spans[middle].from < position) low = middle + 1; + else high = middle; + } + return low; } function commentText(text: string) { @@ -85,7 +108,7 @@ function commentText(text: string) { function attachedComment(source: string, spans: Span[], start: number, end: number) { const above: Span[] = []; let limit = start; - for (let i = spans.length - 1; i >= 0; i -= 1) { + for (let i = firstFrom(spans, start) - 1; i >= 0; i -= 1) { const span = spans[i]; if (span.to > limit) continue; const gap = source.slice(span.to, limit); @@ -94,10 +117,8 @@ function attachedComment(source: string, spans: Span[], start: number, end: numb limit = span.from; } if (above.length) return above.map((span) => commentText(span.text)).join("\n") || null; - const trailing = spans.find( - (span) => span.from >= end && !/\n/.test(source.slice(end, span.from)), - ); - return trailing ? commentText(trailing.text) || null : null; + const trailing = spans[firstFrom(spans, end)]; + return trailing && !/\n/.test(source.slice(end, trailing.from)) ? commentText(trailing.text) || null : null; } class Analyzer { @@ -106,10 +127,11 @@ class Analyzer { private readonly blocks: ReadonlyMap; private readonly comments: Span[]; - constructor(private readonly source: string) { - this.tokens = tokenize(source); + constructor(private readonly source: string, tree?: Tree) { + const { tokens, comments } = scan(source, tree); + this.tokens = tokens; this.blocks = matchingBlocks(this.tokens); - this.comments = commentSpans(source); + this.comments = comments; } run() { @@ -431,9 +453,10 @@ class Analyzer { } /** Símbolos declarados en el texto: unidad principal, bloques anónimos y variables de FOR. */ -export function programSymbols(source: string): ProgramSymbol[] { +/** `tree`: el árbol del editor para este texto, si ya está; evita volver a parsear. */ +export function programSymbols(source: string, tree?: Tree): ProgramSymbol[] { try { - return new Analyzer(source).run(); + return new Analyzer(source, tree).run(); } catch { return []; } diff --git a/app/src/symbolHover.ts b/app/src/symbolHover.ts index 28d4f2f..6a56455 100644 --- a/app/src/symbolHover.ts +++ b/app/src/symbolHover.ts @@ -5,6 +5,8 @@ import { EditorView, hoverTooltip, showTooltip, type Command, type Tooltip } fro import { SymbolCard } from "./components/SymbolCard"; import { editorPath } from "./editorReference"; import { resolveSymbol, type Resolved, type ResolveContext } from "./symbolResolve"; +import type { SourcePart } from "./symbolSources"; +import { ensureSyntaxTree } from "@codemirror/language"; export type ContextFor = (view: EditorView, position: number) => ResolveContext | null; @@ -87,3 +89,9 @@ export const showSymbolCard: Command = (view) => { }); return true; }; + +/** Texto de un editor con su árbol de sintaxis, si está listo en 50 ms. */ +export function editorPart(kind: string, view: EditorView): SourcePart { + const tree = ensureSyntaxTree(view.state, view.state.doc.length, 50); + return tree ? { kind, source: view.state.doc.toString(), tree } : { kind, source: view.state.doc.toString() }; +} diff --git a/app/src/symbolResolve.test.ts b/app/src/symbolResolve.test.ts index 82376b6..50a0db5 100644 --- a/app/src/symbolResolve.test.ts +++ b/app/src/symbolResolve.test.ts @@ -211,3 +211,20 @@ test("la ubicación incluye la columna", async () => { const [found] = await resolveSymbol(at([source], "v :="), path(["V"])); expect(found).toMatchObject({ location: { line: 2, column: 5 } }); }); + +test("un alias en un paquete de 14.000 líneas se resuelve rápido", async () => { + const lookup = fakeLookup({ CLIENTES: info("CLIENTES", "Table") }); + let body = "PACKAGE BODY pkg IS\n"; + for (let i = 0; i < 1600; i += 1) { + body += ` PROCEDURE p${i} IS v NUMBER; BEGIN\n SELECT c.id INTO v FROM clientes c WHERE c.id = ${i};\n` + + " FOR r IN (SELECT id FROM clientes) LOOP v := r.id; END LOOP;\n IF v > 0 THEN v := 1; END IF;\n END;\n"; + } + body += "END;"; + const context = at(["PACKAGE pkg IS END;", body], "c.id INTO", { lookup, nth: 1599 }); + await resolveSymbol(at(["X", "BEGIN NULL; END;"], "NULL"), path(["X"])); + const start = performance.now(); + const found = await resolveSymbol(context, path(["C", "ID"])); + const elapsed = performance.now() - start; + expect(found[0]).toMatchObject({ kind: "column", table: "CLIENTES" }); + expect(elapsed).toBeLessThan(200); +}); diff --git a/app/src/symbolResolve.ts b/app/src/symbolResolve.ts index 9b6df9d..8826b8a 100644 --- a/app/src/symbolResolve.ts +++ b/app/src/symbolResolve.ts @@ -1,7 +1,7 @@ import type { NamePath } from "./editorReference"; import { statementAliases, statementTables } from "./programCompletion"; import { isIdentifier, nameOf, tokenize, type Token } from "./programStructure"; -import { programSymbols, type ProgramSymbol } from "./programSymbols"; +import { programSymbols, type ProgramSymbol, type Tree } from "./programSymbols"; import type { SourcePart, SymbolLookup } from "./symbolSources"; import type { ObjectColumn, ObjectInfo, ObjectType } from "./types"; @@ -34,14 +34,14 @@ const memberKinds = new Set(["field", "parameter"]); const MAX_DEPTH = 6; const cache = new Map(); -function symbolsOf(source: string) { +function symbolsOf(source: string, tree?: Tree) { const hit = cache.get(source); if (hit) { cache.delete(source); cache.set(source, hit); return hit; } - const symbols = programSymbols(source); + const symbols = programSymbols(source, tree); cache.set(source, symbols); if (cache.size > 16) cache.delete(cache.keys().next().value!); return symbols; @@ -69,7 +69,7 @@ type Entity = const homeOf = (parts: SourcePart[], object: ObjectInfo | null): Home => ({ parts, - symbols: parts.map((part) => symbolsOf(part.source)), + symbols: parts.map((part) => symbolsOf(part.source, part.tree)), object, }); @@ -92,6 +92,14 @@ function located(home: Home, part: number, symbol: ProgramSymbol): Resolved { }; } +/** Alias de la sentencia en `position`, tokenizando solo entre los `;` que la rodean. */ +function aliasesAround(source: string, position: number) { + const start = source.lastIndexOf(";", Math.max(0, position - 1)) + 1; + const next = source.indexOf(";", position); + const end = next < 0 ? source.length : next; + return statementAliases(source.slice(start, end), position - start); +} + /** Nombre con puntos, respetando comillas: `hr."Mi Tabla"` → ["HR", "Mi Tabla"]. */ function nameParts(text: string) { return (text.trim().match(/"[^"]+"|[^.\s]+/g) ?? []).map((part) => @@ -215,7 +223,7 @@ class Resolver { item.kind === "symbol" && (valueKinds.has(item.symbol.kind) || item.symbol.kind === "package"))); if (fromSymbol) return fromSymbol; const { current, position } = this.ctx; - const table = statementAliases(this.ctx.parts[current]?.source ?? "", position).get(name); + const table = aliasesAround(this.ctx.parts[current]?.source ?? "", position).get(name); if (table) return { t: "relation", owner: table.owner, name: table.name }; if (!this.ctx.lookup) return null; return this.entityFromObject(await this.object(null, name), name); diff --git a/app/src/symbolSources.ts b/app/src/symbolSources.ts index cf0aaf5..fbc3cb6 100644 --- a/app/src/symbolSources.ts +++ b/app/src/symbolSources.ts @@ -1,10 +1,13 @@ import type { api as appApi } from "./api"; import type { ObjectColumn, ObjectInfo } from "./types"; +import type { Tree } from "./programSymbols"; export interface SourcePart { /** Como `ProgramPart.kind`: "PACKAGE", "PACKAGE BODY", "SQL"… */ kind: string; source: string; + /** Árbol del editor para `source`, si está listo: evita volver a parsear. */ + tree?: Tree; } export interface ObjectKey { From e21a121a5965d5d5a5bee3e9726221bb5eca4f7c Mon Sep 17 00:00:00 2001 From: Walter Aquino Date: Fri, 27 Nov 2026 11:20:20 -0300 Subject: [PATCH 15/24] test(app): WAL-121 rendimiento medido por parseos, no por tiempo Los umbrales en milisegundos fallaban con la suite en paralelo. Co-Authored-By: Claude Opus 5.5 --- app/src/programSymbols.test.ts | 16 +++++++++------- app/src/symbolResolve.test.ts | 11 ++++++----- 2 files changed, 15 insertions(+), 12 deletions(-) diff --git a/app/src/programSymbols.test.ts b/app/src/programSymbols.test.ts index 3a25368..0d971a3 100644 --- a/app/src/programSymbols.test.ts +++ b/app/src/programSymbols.test.ts @@ -1,4 +1,5 @@ -import { expect, test } from "vitest"; +import { expect, test, vi } from "vitest"; +import { oracleDialect } from "./editorReference"; import { programSymbols, type ProgramSymbol } from "./programSymbols"; const find = (symbols: ProgramSymbol[], name: string) => @@ -164,7 +165,7 @@ test("un IF sin cerrar no oculta las rutinas siguientes", () => { expect(one(symbols, "V").scope).not.toBeNull(); }); -test("un paquete de 14.000 líneas se analiza rápido", () => { +test("un paquete grande se parsea una sola vez, o ninguna con el árbol del editor", () => { const routine = (n: number) => ` -- rutina ${n}\n PROCEDURE p${n}(a IN NUMBER, b VARCHAR2 := 'x') IS\n v NUMBER := 1;\n` + " CURSOR c IS SELECT id, nombre FROM clientes WHERE id = a;\n BEGIN\n" + @@ -172,12 +173,13 @@ test("un paquete de 14.000 líneas se analiza rápido", () => { let source = "CREATE OR REPLACE PACKAGE BODY pkg IS\n"; for (let i = 0; i < 1600; i += 1) source += routine(i); source += "END;"; - programSymbols(source.slice(0, 2000)); - const start = performance.now(); + const tree = oracleDialect.language.parser.parse(source); + const parse = vi.spyOn(oracleDialect.language.parser, "parse"); const symbols = programSymbols(source); - const elapsed = performance.now() - start; + expect(parse).toHaveBeenCalledTimes(1); expect(symbols.filter((symbol) => symbol.kind === "procedure")).toHaveLength(1600); expect(symbols.find((symbol) => symbol.name === "P1599")?.comment).toBe("rutina 1599"); - // Holgado para máquinas lentas; antes tardaba más de 300 ms. - expect(elapsed).toBeLessThan(180); + expect(programSymbols(source, tree)).toHaveLength(symbols.length); + expect(parse).toHaveBeenCalledTimes(1); + parse.mockRestore(); }); diff --git a/app/src/symbolResolve.test.ts b/app/src/symbolResolve.test.ts index 50a0db5..7649f00 100644 --- a/app/src/symbolResolve.test.ts +++ b/app/src/symbolResolve.test.ts @@ -1,4 +1,5 @@ import { expect, test, vi } from "vitest"; +import { oracleDialect } from "./editorReference"; import { resolveSymbol, type ResolveContext } from "./symbolResolve"; import type { SourcePart, SymbolLookup } from "./symbolSources"; import type { ObjectColumn, ObjectInfo, ObjectType } from "./types"; @@ -212,7 +213,7 @@ test("la ubicación incluye la columna", async () => { expect(found).toMatchObject({ location: { line: 2, column: 5 } }); }); -test("un alias en un paquete de 14.000 líneas se resuelve rápido", async () => { +test("un alias en un paquete grande no vuelve a parsear todo el paquete", async () => { const lookup = fakeLookup({ CLIENTES: info("CLIENTES", "Table") }); let body = "PACKAGE BODY pkg IS\n"; for (let i = 0; i < 1600; i += 1) { @@ -221,10 +222,10 @@ test("un alias en un paquete de 14.000 líneas se resuelve rápido", async () => } body += "END;"; const context = at(["PACKAGE pkg IS END;", body], "c.id INTO", { lookup, nth: 1599 }); - await resolveSymbol(at(["X", "BEGIN NULL; END;"], "NULL"), path(["X"])); - const start = performance.now(); + context.parts = context.parts.map((part) => ({ ...part, tree: oracleDialect.language.parser.parse(part.source) })); + const parse = vi.spyOn(oracleDialect.language.parser, "parse"); const found = await resolveSymbol(context, path(["C", "ID"])); - const elapsed = performance.now() - start; expect(found[0]).toMatchObject({ kind: "column", table: "CLIENTES" }); - expect(elapsed).toBeLessThan(200); + for (const [input] of parse.mock.calls) expect(String(input).length).toBeLessThan(2000); + parse.mockRestore(); }); From 87126c81cdfe71dd10a65d30ed9194b34c0a7693 Mon Sep 17 00:00:00 2001 From: Walter Aquino Date: Fri, 27 Nov 2026 11:21:51 -0300 Subject: [PATCH 16/24] =?UTF-8?q?fix(app):=20WAL-121=20F12=20no=20navega?= =?UTF-8?q?=20si=20el=20usuario=20sigui=C3=B3=20escribiendo=20o=20cambi?= =?UTF-8?q?=C3=B3=20de=20pesta=C3=B1a?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- app/src/components/ProgramWindow.test.tsx | 44 +++++++++++++++++++++++ app/src/components/ProgramWindow.tsx | 7 +++- app/src/components/SqlWindow.test.tsx | 19 ++++++++++ app/src/components/SqlWindow.tsx | 7 +++- 4 files changed, 75 insertions(+), 2 deletions(-) diff --git a/app/src/components/ProgramWindow.test.tsx b/app/src/components/ProgramWindow.test.tsx index f0e5dee..a1d4990 100644 --- a/app/src/components/ProgramWindow.test.tsx +++ b/app/src/components/ProgramWindow.test.tsx @@ -902,3 +902,47 @@ test("un destino pedido se ubica por línea y columna, aunque esté fuera del te initialTarget={{ partKind: "PACKAGE", line: 99, column: 99 }} />); expect(view.state.selection.main.head).toBe(source.length); }); + +test("F12 no navega si el usuario escribió mientras se resolvía", async () => { + const ref = createRef(); + const onNavigate = vi.fn(); + const other = { owner: "HR", name: "PKG_OTRO", object_type: "Package" as const, status: "Valid" as const, last_ddl_time: "" }; + let answer: (value: typeof other) => void = () => {}; + const symbols = { + object: vi.fn(() => new Promise((resolve) => { answer = resolve; })), + parts: vi.fn(async () => [{ kind: "PACKAGE", source: "PACKAGE pkg_otro AS\n PROCEDURE hacer;\nEND;" }]), + columns: vi.fn(async () => []), + }; + const source = "PACKAGE BODY PKG_A AS\nBEGIN\n pkg_otro.hacer;\nEND;"; + render(); + const view = EditorView.findFromDOM(screen.getByRole("textbox", { name: "Body" }).closest(".cm-editor")!)!; + act(() => view.dispatch({ selection: { anchor: source.indexOf("hacer") + 1 } })); + act(() => ref.current!.goToDefinition!()); + act(() => view.dispatch({ changes: { from: 0, insert: "-- " } })); + await act(async () => { answer(other); }); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(onNavigate).not.toHaveBeenCalled(); +}); + +test("F12 no abre otro objeto si el usuario cambió de pestaña mientras se resolvía", async () => { + const ref = createRef(); + const onNavigate = vi.fn(); + const other = { owner: "HR", name: "PKG_OTRO", object_type: "Package" as const, status: "Valid" as const, last_ddl_time: "" }; + let answer: (value: typeof other) => void = () => {}; + const symbols = { + object: vi.fn(() => new Promise((resolve) => { answer = resolve; })), + parts: vi.fn(async () => [{ kind: "PACKAGE", source: "PACKAGE pkg_otro AS\n PROCEDURE hacer;\nEND;" }]), + columns: vi.fn(async () => []), + }; + const source = "PACKAGE BODY PKG_A AS\nBEGIN\n pkg_otro.hacer;\nEND;"; + const props = { onDirty: vi.fn(), ref, symbols, onNavigate, parts: [{ ...parts[1], source }] }; + const { rerender } = render(); + const view = EditorView.findFromDOM(screen.getByRole("textbox", { name: "Body" }).closest(".cm-editor")!)!; + act(() => view.dispatch({ selection: { anchor: source.indexOf("hacer") + 1 } })); + act(() => ref.current!.goToDefinition!()); + rerender(); + await act(async () => { answer(other); }); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(onNavigate).not.toHaveBeenCalled(); +}); diff --git a/app/src/components/ProgramWindow.tsx b/app/src/components/ProgramWindow.tsx index 72a6e22..399485f 100644 --- a/app/src/components/ProgramWindow.tsx +++ b/app/src/components/ProgramWindow.tsx @@ -161,6 +161,8 @@ export function ProgramWindow({ return view ? editorPart(entry.kind, view) : { kind: entry.kind, source: entry.source }; }), []); useEffect(() => registerRef.current?.(liveSources), [liveSources]); + const activeRef = useRef(active); + activeRef.current = active; const symbolRefs = useRef({ symbols, symbolSelf }); symbolRefs.current = { symbols, symbolSelf }; const symbolContext = useCallback((view, position) => { @@ -321,8 +323,11 @@ export function ProgramWindow({ const view = views.current[index]; if (!view) return; const position = at ?? view.state.selection.main.from; + const { doc } = view.state; + const head = view.state.selection.main.head; const found = await resolveAt(view, position, symbolContext); - if (!found) return; + // Si mientras tanto se escribió o se movió el cursor, el destino ya no corresponde. + if (!found || !activeRef.current || view.state.doc !== doc || view.state.selection.main.head !== head) return; const { name, items } = found; const relation = items.find((item) => item.kind === "relation"); if (relation?.kind === "relation") { diff --git a/app/src/components/SqlWindow.test.tsx b/app/src/components/SqlWindow.test.tsx index 05d0ed0..bac17d3 100644 --- a/app/src/components/SqlWindow.test.tsx +++ b/app/src/components/SqlWindow.test.tsx @@ -857,3 +857,22 @@ describe("ficha y navegación", () => { expect(await screen.findByRole("menuitem", { name: /Ir a la definición/ })).toBeInTheDocument(); }); }); + +test("F12 no salta si el cursor se movió mientras se resolvía", async () => { + const table = { owner: "HR", name: "PKG_X", object_type: "Package" as const, status: "Valid" as const, last_ddl_time: "" }; + let answer: (value: typeof table) => void = () => {}; + const openObject = vi.fn(); + const symbols = { + object: vi.fn(() => new Promise((resolve) => { answer = resolve; })), + parts: vi.fn(async () => [{ kind: "PACKAGE", source: "PACKAGE pkg_x AS\n PROCEDURE f;\nEND;" }]), + columns: vi.fn(async () => []), + }; + const source = "BEGIN pkg_x.f; END;"; + const { ref, view } = setup(source, { symbols, openObject }); + act(() => view.dispatch({ selection: { anchor: source.indexOf("f;") + 1 } })); + act(() => ref.current!.goToDefinition!()); + act(() => view.dispatch({ selection: { anchor: 0 } })); + await act(async () => { answer(table); }); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(openObject).not.toHaveBeenCalled(); +}); diff --git a/app/src/components/SqlWindow.tsx b/app/src/components/SqlWindow.tsx index 51cd9b1..d35af64 100644 --- a/app/src/components/SqlWindow.tsx +++ b/app/src/components/SqlWindow.tsx @@ -800,6 +800,8 @@ export function SqlWindow({ if (view.current) action(view.current); }; + const activeRef = useRef(active); + activeRef.current = active; const symbolsRef = useRef(symbols); symbolsRef.current = symbols; const symbolContext = useCallback((editor, position) => ({ @@ -830,8 +832,11 @@ export function SqlWindow({ const editor = view.current; if (!editor) return; const position = at ?? editor.state.selection.main.from; + const { doc } = editor.state; + const head = editor.state.selection.main.head; const found = await resolveAt(editor, position, symbolContext); - if (!found) return; + // Si mientras tanto se escribió o se movió el cursor, el destino ya no corresponde. + if (!found || !activeRef.current || editor.state.doc !== doc || editor.state.selection.main.head !== head) return; const relation = found.items.find((item) => item.kind === "relation"); if (relation?.kind === "relation") { openObject?.(relation.object); From a28848cc5570aeeaec8497578f3db7950e319bf9 Mon Sep 17 00:00:00 2001 From: Walter Aquino Date: Fri, 27 Nov 2026 11:22:46 -0300 Subject: [PATCH 17/24] fix(app): WAL-121 Alt+clic agrega cursor; Ctrl+clic sin destino ubica el cursor Co-Authored-By: Claude Opus 5.5 --- app/src/components/ProgramWindow.test.tsx | 10 ++++++++++ app/src/components/ProgramWindow.tsx | 9 +++++++-- app/src/components/SqlWindow.tsx | 8 ++++++-- app/src/symbolLink.test.ts | 13 +++++++++++++ app/src/symbolLink.ts | 2 ++ 5 files changed, 38 insertions(+), 4 deletions(-) create mode 100644 app/src/symbolLink.test.ts diff --git a/app/src/components/ProgramWindow.test.tsx b/app/src/components/ProgramWindow.test.tsx index a1d4990..b564c98 100644 --- a/app/src/components/ProgramWindow.test.tsx +++ b/app/src/components/ProgramWindow.test.tsx @@ -946,3 +946,13 @@ test("F12 no abre otro objeto si el usuario cambió de pestaña mientras se reso await new Promise((resolve) => setTimeout(resolve, 20)); expect(onNavigate).not.toHaveBeenCalled(); }); + +test("Ctrl+clic sobre un nombre sin destino deja el cursor donde se hizo clic", async () => { + const source = "PACKAGE BODY PKG_A AS\nBEGIN\n desconocido;\nEND;"; + render(); + const view = EditorView.findFromDOM(screen.getByRole("textbox", { name: "Body" }).closest(".cm-editor")!)!; + const position = source.indexOf("desconocido") + 3; + vi.spyOn(view, "posAtCoords").mockReturnValue(position); + fireEvent.mouseDown(view.contentDOM, { ctrlKey: true, button: 0, clientX: 5, clientY: 5 }); + await waitFor(() => expect(view.state.selection.main.head).toBe(position)); +}); diff --git a/app/src/components/ProgramWindow.tsx b/app/src/components/ProgramWindow.tsx index 399485f..3a547e0 100644 --- a/app/src/components/ProgramWindow.tsx +++ b/app/src/components/ProgramWindow.tsx @@ -318,7 +318,8 @@ export function ProgramWindow({ } /** Definición, declaración o implementación del nombre en `at` (o en el cursor). */ - async function goTo(goal: NavigationGoal, index = selected, at?: number) { + /** `onMiss`: el nombre no lleva a ningún lado (Ctrl+clic lo usa para ubicar el cursor). */ + async function goTo(goal: NavigationGoal, index = selected, at?: number, onMiss?: () => void) { if (comparison) return; const view = views.current[index]; if (!view) return; @@ -345,6 +346,8 @@ export function ProgramWindow({ title: `${NAVIGATION_TITLES[goal]} de ${name}`, x: coords.left, y: coords.bottom, targets, }); + } else { + onMiss?.(); } } @@ -665,7 +668,9 @@ export function ProgramWindow({ closeDeclarationMenu(); setObjectMenu({ reference, x, y, id: ++objectRequestId.current, part: index, position }); } : undefined} - onCtrlClick={(position) => void goTo("definition", index, position)} + onCtrlClick={(position) => void goTo("definition", index, position, () => { + views.current[index]?.dispatch({ selection: { anchor: position } }); + })} onView={(view) => { views.current[index] = view; const base = saved.current[index]; diff --git a/app/src/components/SqlWindow.tsx b/app/src/components/SqlWindow.tsx index d35af64..7790b4f 100644 --- a/app/src/components/SqlWindow.tsx +++ b/app/src/components/SqlWindow.tsx @@ -828,7 +828,7 @@ export function SqlWindow({ } /** Definición, declaración o implementación del nombre en `at` (o en el cursor). */ - async function goTo(goal: NavigationGoal, at?: number) { + async function goTo(goal: NavigationGoal, at?: number, onMiss?: () => void) { const editor = view.current; if (!editor) return; const position = at ?? editor.state.selection.main.from; @@ -850,6 +850,8 @@ export function SqlWindow({ const coords = editor.coordsAtPos(position) ?? editor.contentDOM.getBoundingClientRect(); closeObjectMenu(); setTargetsMenu({ title: `${NAVIGATION_TITLES[goal]} de ${found.name}`, x: coords.left, y: coords.bottom, targets }); + } else { + onMiss?.(); } } @@ -992,7 +994,9 @@ export function SqlWindow({ {}} symbolContext={symbolContext} - onCtrlClick={(position) => void goTo("definition", position)} + onCtrlClick={(position) => void goTo("definition", position, () => { + view.current?.dispatch({ selection: { anchor: position } }); + })} onObjectContext={catalog ? (reference, x, y, position) => { closeTargetsMenu(); setObjectMenu({ reference, x, y, position, id: ++objectMenuId.current }); diff --git a/app/src/symbolLink.test.ts b/app/src/symbolLink.test.ts new file mode 100644 index 0000000..a3ab092 --- /dev/null +++ b/app/src/symbolLink.test.ts @@ -0,0 +1,13 @@ +import { EditorState } from "@codemirror/state"; +import { EditorView } from "@codemirror/view"; +import { expect, test } from "vitest"; +import { symbolLink } from "./symbolLink"; + +const click = (init: Partial) => ({ altKey: false, ctrlKey: false, metaKey: false, shiftKey: false, ...init }) as MouseEvent; + +test("Alt+clic agrega un cursor y Ctrl+clic ya no", () => { + const view = new EditorView({ state: EditorState.create({ doc: "x", extensions: [symbolLink(() => () => {})] }) }); + const adds = view.state.facet(EditorView.clickAddsSelectionRange); + expect(adds.some((check) => check(click({ altKey: true })))).toBe(true); + expect(adds.some((check) => check(click({ ctrlKey: true })))).toBe(false); +}); diff --git a/app/src/symbolLink.ts b/app/src/symbolLink.ts index dea7390..fa59e5c 100644 --- a/app/src/symbolLink.ts +++ b/app/src/symbolLink.ts @@ -35,6 +35,8 @@ export function symbolLink(navigate: () => ((position: number) => void) | null | }; return [ linkField, + // Ctrl+clic navega; agregar un cursor pasa a Alt+clic. + EditorView.clickAddsSelectionRange.of((event) => event.altKey), EditorView.domEventHandlers({ mousemove(event, view) { mouse = { x: event.clientX, y: event.clientY }; From 1f17947b940121bf388999268c69db64ae52778c Mon Sep 17 00:00:00 2001 From: Walter Aquino Date: Fri, 27 Nov 2026 11:23:41 -0300 Subject: [PATCH 18/24] fix(app): WAL-121 fuente envuelta muestra Fuente no disponible Co-Authored-By: Claude Opus 5.5 --- app/src/symbolResolve.test.ts | 20 ++++++++++++++++++++ app/src/symbolResolve.ts | 15 ++++++++++++--- 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/app/src/symbolResolve.test.ts b/app/src/symbolResolve.test.ts index 7649f00..92e0de3 100644 --- a/app/src/symbolResolve.test.ts +++ b/app/src/symbolResolve.test.ts @@ -229,3 +229,23 @@ test("un alias en un paquete grande no vuelve a parsear todo el paquete", async for (const [input] of parse.mock.calls) expect(String(input).length).toBeLessThan(2000); parse.mockRestore(); }); + +test("un paquete envuelto dice que la fuente no está disponible", async () => { + const wrapped = "CREATE OR REPLACE PACKAGE pkg_w wrapped\na000000\n1\nabcd\n"; + const lookup = fakeLookup({ PKG_W: info("PKG_W", "Package") }, { PKG_W: [{ kind: "PACKAGE", source: wrapped }] }); + const note = { kind: "object", object: info("PKG_W", "Package"), note: "Fuente no disponible" }; + expect(await resolveSymbol(at(["BEGIN pkg_w.f; END;"], "f;", { lookup }), path(["PKG_W", "F"]))).toEqual([note]); + expect(await resolveSymbol(at(["BEGIN pkg_w.f; END;"], "pkg_w", { lookup }), path(["PKG_W", "F"], 0))).toEqual([note]); +}); + +test("un cuerpo envuelto deja ver la spec", async () => { + const lookup = fakeLookup({ PKG_W: info("PKG_W", "Package") }, { + PKG_W: [ + { kind: "PACKAGE", source: "PACKAGE pkg_w IS\n PROCEDURE f;\nEND;" }, + { kind: "PACKAGE BODY", source: "PACKAGE BODY pkg_w wrapped\na000000\n" }, + ], + }); + const found = await resolveSymbol(at(["BEGIN pkg_w.f; END;"], "f;", { lookup }), path(["PKG_W", "F"])); + expect(found).toHaveLength(1); + expect(found[0]).toMatchObject({ kind: "symbol", symbol: { name: "F" } }); +}); diff --git a/app/src/symbolResolve.ts b/app/src/symbolResolve.ts index 8826b8a..6a7586e 100644 --- a/app/src/symbolResolve.ts +++ b/app/src/symbolResolve.ts @@ -28,6 +28,10 @@ export interface ResolveContext { lookup: SymbolLookup | null; } +/** Fuente envuelta con `wrap`: no se puede analizar. */ +const wrappedSource = + /^\s*(?:CREATE\s+(?:OR\s+REPLACE\s+)?)?(?:(?:NON)?EDITIONABLE\s+)?(?:PACKAGE|TYPE|FUNCTION|PROCEDURE|TRIGGER)(?:\s+BODY)?\s+(?:"[^"]+"|[\w$#]+)(?:\s*\.\s*(?:"[^"]+"|[\w$#]+))?\s+wrapped\b/i; + const relationTypes = new Set(["Table", "View", "MaterializedView"]); const programTypes = new Set(["Package", "Function", "Procedure", "Type", "Trigger"]); const memberKinds = new Set(["field", "parameter"]); @@ -65,7 +69,8 @@ type Entity = | { t: "record"; home: Home; dataType: string; at?: At } | { t: "query"; home: Home; query: string; label: string } | { t: "relation"; owner: string | null; name: string } - | { t: "schema"; owner: string }; + | { t: "schema"; owner: string } + | { t: "unreadable"; object: ObjectInfo }; const homeOf = (parts: SourcePart[], object: ObjectInfo | null): Home => ({ parts, @@ -166,8 +171,10 @@ class Resolver { return this.safe((lookup) => lookup.columns(realOwner, name), [] as ObjectColumn[]); } + /** Partes legibles del objeto; null si no hay ninguna (sin permiso o todo envuelto). */ private async home(object: ObjectInfo) { - const parts = await this.safe((lookup) => lookup.parts(object), [] as SourcePart[]); + const parts = (await this.safe((lookup) => lookup.parts(object), [] as SourcePart[])) + .filter((part) => !wrappedSource.test(part.source)); return parts.length ? homeOf(parts, object) : null; } @@ -201,7 +208,7 @@ class Resolver { if (relationTypes.has(object.object_type)) return { t: "relation", owner: object.owner, name: object.name }; if (object.object_type !== "Package") return null; const home = await this.home(object); - return home ? { t: "unit", home } : null; + return home ? { t: "unit", home } : { t: "unreadable", object }; } /** Entidad de un símbolo del documento abierto. */ @@ -262,6 +269,8 @@ class Resolver { return this.typeMembers(entity.home, entity.dataType, name, 0, entity.at); case "query": return this.queryColumn(entity.query, name, entity.label); + case "unreadable": + return [{ kind: "object", object: entity.object, note: "Fuente no disponible" }]; } } From 3f752199aa57f94e0bf1ef29805ddb036ec59bd1 Mon Sep 17 00:00:00 2001 From: Walter Aquino Date: Fri, 27 Nov 2026 11:24:30 -0300 Subject: [PATCH 19/24] =?UTF-8?q?fix(app):=20WAL-121=20un=20programa=20que?= =?UTF-8?q?=20recibe=20su=20objeto=20despu=C3=A9s=20registra=20su=20texto?= =?UTF-8?q?=20vivo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- app/src/App.tsx | 3 +++ app/src/components/ProgramWindow.test.tsx | 13 ++++++++++++- app/src/components/ProgramWindow.tsx | 6 ++++-- 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/app/src/App.tsx b/app/src/App.tsx index c88b4c9..fb82517 100644 --- a/app/src/App.tsx +++ b/app/src/App.tsx @@ -1468,6 +1468,9 @@ export default function App() { column: location.column, }); }} + sourceKey={tab.object && tab.connection + ? JSON.stringify([tab.connection.sessionId, tab.object.owner, tab.object.name]) + : undefined} registerSource={tab.object && tab.connection ? (read) => symbolSources.register({ connection: tab.connection!.sessionId, diff --git a/app/src/components/ProgramWindow.test.tsx b/app/src/components/ProgramWindow.test.tsx index b564c98..1bc47b6 100644 --- a/app/src/components/ProgramWindow.test.tsx +++ b/app/src/components/ProgramWindow.test.tsx @@ -774,7 +774,7 @@ test("registra su texto vivo y se da de baja al cerrarse", () => { const release = vi.fn(); const registerSource = vi.fn().mockReturnValue(release); const { unmount } = render( - , + , ); expect(registerSource).toHaveBeenCalledOnce(); const read = registerSource.mock.calls[0][0] as () => { kind: string; source: string }[]; @@ -956,3 +956,14 @@ test("Ctrl+clic sobre un nombre sin destino deja el cursor donde se hizo clic", fireEvent.mouseDown(view.contentDOM, { ctrlKey: true, button: 0, clientX: 5, clientY: 5 }); await waitFor(() => expect(view.state.selection.main.head).toBe(position)); }); + +test("una ventana que recibe su objeto después se registra entonces, una sola vez", () => { + const registerSource = vi.fn().mockReturnValue(vi.fn()); + const props = { parts, readOnly: false, onDirty: vi.fn() }; + const { rerender } = render(); + expect(registerSource).not.toHaveBeenCalled(); + rerender(); + expect(registerSource).toHaveBeenCalledOnce(); + rerender( registerSource(read)} sourceKey="s1|HR|PKG_A" />); + expect(registerSource).toHaveBeenCalledOnce(); +}); diff --git a/app/src/components/ProgramWindow.tsx b/app/src/components/ProgramWindow.tsx index 3a547e0..1e60400 100644 --- a/app/src/components/ProgramWindow.tsx +++ b/app/src/components/ProgramWindow.tsx @@ -68,6 +68,8 @@ interface Props { compile?: ProgramCompiler; /** Registra el texto vivo para la ficha y la navegación de otras ventanas. */ registerSource?: (read: () => SourcePart[]) => () => void; + /** Identifica el objeto registrado; al cambiar (p. ej. tras la primera compilación) se vuelve a registrar. */ + sourceKey?: string; /** Catálogo para la ficha y la navegación; null o ausente: solo lo del documento. */ symbols?: SymbolLookup | null; /** Objeto que muestra la ventana, para ubicar sus propias declaraciones. */ @@ -111,7 +113,7 @@ function storedOutlineWidth() { export function ProgramWindow({ - parts, readOnly, onReadOnlyChange, onDirty, onWorkspaceChange, ref, fileName, catalog, active = true, readCurrentProgram, compilationTarget, compile, onTestRoutine, registerSource, symbols, symbolSelf, + parts, readOnly, onReadOnlyChange, onDirty, onWorkspaceChange, ref, fileName, catalog, active = true, readCurrentProgram, compilationTarget, compile, onTestRoutine, registerSource, sourceKey, symbols, symbolSelf, onNavigate, initialTarget, }: Props) { const [baselines, setBaselines] = useState(() => parts.map(baselineOf)); @@ -160,7 +162,7 @@ export function ProgramWindow({ const view = views.current[index]; return view ? editorPart(entry.kind, view) : { kind: entry.kind, source: entry.source }; }), []); - useEffect(() => registerRef.current?.(liveSources), [liveSources]); + useEffect(() => (sourceKey ? registerRef.current?.(liveSources) : undefined), [liveSources, sourceKey]); const activeRef = useRef(active); activeRef.current = active; const symbolRefs = useRef({ symbols, symbolSelf }); From 3c40ba89c52a6361073c2485cd09e13f9dcb013d Mon Sep 17 00:00:00 2001 From: Walter Aquino Date: Fri, 27 Nov 2026 11:25:01 -0300 Subject: [PATCH 20/24] fix(app): WAL-121 dentro de un SELECT el alias gana a una variable Co-Authored-By: Claude Opus 5.5 --- app/src/symbolResolve.test.ts | 9 +++++++++ app/src/symbolResolve.ts | 7 ++++--- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/app/src/symbolResolve.test.ts b/app/src/symbolResolve.test.ts index 92e0de3..1e77585 100644 --- a/app/src/symbolResolve.test.ts +++ b/app/src/symbolResolve.test.ts @@ -249,3 +249,12 @@ test("un cuerpo envuelto deja ver la spec", async () => { expect(found).toHaveLength(1); expect(found[0]).toMatchObject({ kind: "symbol", symbol: { name: "F" } }); }); + +test("dentro de un SELECT el alias gana a una variable con el mismo nombre", async () => { + const lookup = fakeLookup({ CLIENTES: info("CLIENTES", "Table") }); + const source = "DECLARE c NUMBER; x VARCHAR2(9); BEGIN SELECT c.nombre INTO x FROM clientes c; END;"; + const found = await resolveSymbol(at([source], "nombre", { lookup }), path(["C", "NOMBRE"])); + expect(found).toEqual([ + { kind: "column", table: "CLIENTES", column: { name: "NOMBRE", data_type: "VARCHAR2(100)", nullable: true } }, + ]); +}); diff --git a/app/src/symbolResolve.ts b/app/src/symbolResolve.ts index 6a7586e..3363273 100644 --- a/app/src/symbolResolve.ts +++ b/app/src/symbolResolve.ts @@ -225,13 +225,14 @@ class Resolver { } private async firstEntity(name: string): Promise { + // Dentro de una sentencia SQL, Oracle resuelve primero sus alias y tablas. + const { current, position } = this.ctx; + const table = aliasesAround(this.ctx.parts[current]?.source ?? "", position).get(name); + if (table) return { t: "relation", owner: table.owner, name: table.name }; const visible = this.visible(name); const fromSymbol = this.entityFromSymbol(visible.find((item) => item.kind === "symbol" && (valueKinds.has(item.symbol.kind) || item.symbol.kind === "package"))); if (fromSymbol) return fromSymbol; - const { current, position } = this.ctx; - const table = aliasesAround(this.ctx.parts[current]?.source ?? "", position).get(name); - if (table) return { t: "relation", owner: table.owner, name: table.name }; if (!this.ctx.lookup) return null; return this.entityFromObject(await this.object(null, name), name); } From 3b0cd170d79b27ccef3c98a4e97810eb1fbf4cf4 Mon Sep 17 00:00:00 2001 From: Walter Aquino Date: Fri, 27 Nov 2026 11:27:05 -0300 Subject: [PATCH 21/24] =?UTF-8?q?feat(app):=20WAL-121=20pkg.cursor%ROWTYPE?= =?UTF-8?q?=20y=20atributos=20y=20m=C3=A9todos=20de=20tipos=20objeto?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- app/src/programSymbols.test.ts | 11 +++ app/src/programSymbols.ts | 120 +++++++++++++++++++++++++++++---- app/src/symbolResolve.test.ts | 29 ++++++++ app/src/symbolResolve.ts | 55 ++++++++++----- 4 files changed, 186 insertions(+), 29 deletions(-) diff --git a/app/src/programSymbols.test.ts b/app/src/programSymbols.test.ts index 0d971a3..19946a3 100644 --- a/app/src/programSymbols.test.ts +++ b/app/src/programSymbols.test.ts @@ -183,3 +183,14 @@ test("un paquete grande se parsea una sola vez, o ninguna con el árbol del edit expect(parse).toHaveBeenCalledTimes(1); parse.mockRestore(); }); + +test("tipo objeto: atributos y métodos en spec y body", () => { + const typeSpec = "CREATE OR REPLACE TYPE t_persona AS OBJECT (\n nombre VARCHAR2(50),\n MEMBER FUNCTION saludo RETURN VARCHAR2,\n STATIC PROCEDURE crear(p VARCHAR2)\n);"; + const symbols = programSymbols(typeSpec); + expect(one(symbols, "T_PERSONA")).toMatchObject({ kind: "type", dataType: "OBJECT" }); + expect(one(symbols, "NOMBRE")).toMatchObject({ kind: "field", container: "T_PERSONA", dataType: "VARCHAR2(50)" }); + expect(one(symbols, "SALUDO")).toMatchObject({ kind: "function", container: "T_PERSONA", definition: false }); + expect(one(symbols, "CREAR")).toMatchObject({ kind: "procedure", container: "T_PERSONA" }); + const typeBody = "CREATE OR REPLACE TYPE BODY t_persona AS\n MEMBER FUNCTION saludo RETURN VARCHAR2 IS BEGIN RETURN nombre; END;\nEND;"; + expect(one(programSymbols(typeBody), "SALUDO")).toMatchObject({ kind: "function", container: "T_PERSONA", definition: true }); +}); diff --git a/app/src/programSymbols.ts b/app/src/programSymbols.ts index a8a6ab2..67d9c28 100644 --- a/app/src/programSymbols.ts +++ b/app/src/programSymbols.ts @@ -58,6 +58,8 @@ const tokenEnd = (token: Token) => token.from + token.text.length; const signatureOf = (tokens: Token[]) => format(tokens).replace(/:\s=/g, ":="); const listStops = new Set([";", "IS", "AS"]); const routineStarts = new Set(["PROCEDURE", "FUNCTION"]); +/** Palabras que pueden ir antes de PROCEDURE o FUNCTION en un tipo objeto. */ +const methodPrefixes = new Set(["MEMBER", "STATIC", "CONSTRUCTOR", "MAP", "ORDER", "OVERRIDING", "FINAL", "NOT", "INSTANTIABLE"]); const statementEnd = new Set([";"]); const routineMarkers = new Set([";", "IS", "AS"]); const parameterModes = new Set(["IN", "OUT", "NOCOPY"]); @@ -123,6 +125,8 @@ function attachedComment(source: string, spans: Span[], start: number, end: numb class Analyzer { readonly out: ProgramSymbol[] = []; + /** Tipo objeto cuyo cuerpo se está leyendo: sus métodos lo llevan como `container`. */ + private typeName: string | null = null; private readonly tokens: Token[]; private readonly blocks: ReadonlyMap; private readonly comments: Span[]; @@ -221,6 +225,10 @@ class Analyzer { this.routine(unit, null); return; } + if (kind === "TYPE") { + this.objectType(unit); + return; + } if (kind !== "PACKAGE") return; const isBody = tokens[unit + 1]?.key === "BODY"; const nameIndex = readName(tokens, unit + (isBody ? 2 : 1)); @@ -249,6 +257,10 @@ class Analyzer { while (i < tokens.length) { const { key } = tokens[i]; if (key === "BEGIN" || key === "END" || key === "WRAPPED") return i; + if (this.typeName && methodPrefixes.has(key)) { + i += 1; + continue; + } if (key === "PROCEDURE" || key === "FUNCTION" || key === "CURSOR") { i = this.routine(i, scope); } else if (key === "TYPE" || key === "SUBTYPE") { @@ -341,15 +353,11 @@ class Analyzer { }); } - private routine(start: number, scope: SymbolScope | null) { + /** Firma y clave de una rutina cuyo nombre está en `nameIndex` y su encabezado termina en `end`. */ + private header(start: number, nameIndex: number, items: [number, number][], after: number, end: number) { const { tokens } = this; const kind = tokens[start].key; - const nameIndex = readName(tokens, start + 1); - const name = tokens[nameIndex]; - if (!isIdentifier(name)) return this.statementEnd(start) + 1; - const { items, after } = this.list(nameIndex + 1); - const marker = boundary(tokens, after, routineMarkers); - const returns = tokens[after]?.key === "RETURN" ? tokens.slice(after + 1, marker) : []; + const returns = tokens[after]?.key === "RETURN" ? tokens.slice(after + 1, end) : []; const modifier = returns.findIndex((token) => signatureModifiers.has(token.key)); if (modifier >= 0) returns.length = modifier; const parameters = items.map(([from, to]) => signatureOf(tokens.slice(from, to))); @@ -357,6 +365,95 @@ class Analyzer { `${kind} ${this.text(start + 1, nameIndex + 1)}` + (parameters.length ? `(${parameters.join(", ")})` : "") + (returns.length ? ` RETURN ${format(returns)}` : ""); + const key = JSON.stringify([ + kind, + nameOf(tokens[nameIndex]), + items.map(([from, to]) => normalizedParameter(tokens.slice(from, this.assignment(from, to)?.at ?? to))), + returns.map((token) => token.key), + ]); + return { signature, returns, key }; + } + + /** `TYPE … AS OBJECT (…)` con atributos y métodos, o `TYPE BODY` con sus implementaciones. */ + private objectType(unit: number) { + const { tokens } = this; + const isBody = tokens[unit + 1]?.key === "BODY"; + const nameIndex = readName(tokens, unit + (isBody ? 2 : 1)); + const name = tokens[nameIndex]; + if (!isIdentifier(name)) return; + const typeName = nameOf(name); + const header = boundary(tokens, nameIndex + 1, routineMarkers); + if (tokens[header]?.key !== "IS" && tokens[header]?.key !== "AS") return; + if (isBody) { + this.typeName = typeName; + this.section(header + 1, null); + this.typeName = null; + return; + } + const end = this.statementEnd(header); + const object = tokens[header + 1]?.key === "OBJECT" || tokens[header + 1]?.key === "UNDER"; + this.push({ + kind: "type", + name: typeName, + signature: `TYPE ${this.text(unit + 1, nameIndex + 1)}`, + dataType: object ? "OBJECT" : this.text(header + 1, end) || null, + value: null, + comment: this.comment(unit, nameIndex), + from: name.from, + scope: null, + definition: false, + container: null, + }); + if (!object) return; + const open = boundary(tokens, header + 1, new Set(["("]), end); + for (const [from, to] of this.list(open).items) { + let first = from; + while (first < to && methodPrefixes.has(tokens[first].key)) first += 1; + if (tokens[first]?.key === "PROCEDURE" || tokens[first]?.key === "FUNCTION") { + this.method(first, to, typeName); + } else { + this.member(first, to, "field", typeName, null); + } + } + } + + /** Declaración de un método dentro de `AS OBJECT (…)`, en tokens [start, end). */ + private method(start: number, end: number, typeName: string) { + const { tokens } = this; + const nameIndex = start + 1; + const name = tokens[nameIndex]; + if (!isIdentifier(name)) return; + const { items, after } = this.list(nameIndex + 1); + const { signature, returns, key } = this.header(start, nameIndex, items, after, end); + const methodName = nameOf(name); + this.out.push({ + kind: tokens[start].key === "FUNCTION" ? "function" : "procedure", + name: methodName, + signature, + dataType: returns.length ? format(returns) : null, + value: null, + comment: this.comment(start, end - 1), + from: name.from, + scope: null, + definition: false, + container: typeName, + key, + }); + const own: SymbolScope = { from: tokens[start].from, to: this.endOf(end - 1) }; + for (const [from, to] of items) this.member(from, to, "parameter", methodName, own); + } + + private routine(start: number, scope: SymbolScope | null) { + const { tokens } = this; + const kind = tokens[start].key; + const nameIndex = readName(tokens, start + 1); + const name = tokens[nameIndex]; + if (!isIdentifier(name)) return this.statementEnd(start) + 1; + const { items, after } = this.list(nameIndex + 1); + // RETURN SELF AS RESULT (constructores) lleva un AS que no abre el cuerpo. + const selfResult = tokens[after]?.key === "RETURN" && tokens[after + 1]?.key === "SELF" && tokens[after + 2]?.key === "AS"; + const marker = boundary(tokens, selfResult ? after + 4 : after, routineMarkers); + const { signature, returns, key } = this.header(start, nameIndex, items, after, marker); const opensBody = tokens[marker]?.key === "IS" || tokens[marker]?.key === "AS"; const definition = opensBody && kind !== "CURSOR"; const routineName = nameOf(name); @@ -371,13 +468,8 @@ class Analyzer { from: name.from, scope, definition, - container: null, - key: JSON.stringify([ - kind, - routineName, - items.map(([from, to]) => normalizedParameter(tokens.slice(from, this.assignment(from, to)?.at ?? to))), - returns.map((token) => token.key), - ]), + container: this.typeName, + key, }; this.out.push(symbol); for (const [from, to] of items) this.member(from, to, "parameter", routineName, own); diff --git a/app/src/symbolResolve.test.ts b/app/src/symbolResolve.test.ts index 1e77585..1bb805e 100644 --- a/app/src/symbolResolve.test.ts +++ b/app/src/symbolResolve.test.ts @@ -258,3 +258,32 @@ test("dentro de un SELECT el alias gana a una variable con el mismo nombre", asy { kind: "column", table: "CLIENTES", column: { name: "NOMBRE", data_type: "VARCHAR2(100)", nullable: true } }, ]); }); + +test("campo de un cursor declarado en otro paquete", async () => { + const lookup = fakeLookup( + { PKG_CUR: info("PKG_CUR", "Package"), CLIENTES: info("CLIENTES", "Table") }, + { PKG_CUR: [{ kind: "PACKAGE", source: "PACKAGE pkg_cur IS\n CURSOR c IS SELECT id, nombre FROM clientes;\nEND;" }] }, + ); + const found = await resolveSymbol( + at(["DECLARE v pkg_cur.c%ROWTYPE; BEGIN x := v.nombre; END;"], "nombre;", { lookup }), + path(["V", "NOMBRE"]), + ); + expect(found).toEqual([ + { kind: "column", table: "CLIENTES", column: { name: "NOMBRE", data_type: "VARCHAR2(100)", nullable: true } }, + ]); +}); + +test("atributos y métodos de un tipo objeto", async () => { + const lookup = fakeLookup({ T_PERSONA: info("T_PERSONA", "Type") }, { + T_PERSONA: [ + { kind: "TYPE", source: "CREATE OR REPLACE TYPE t_persona AS OBJECT (\n nombre VARCHAR2(50),\n MEMBER FUNCTION saludo RETURN VARCHAR2\n);" }, + { kind: "TYPE BODY", source: "CREATE OR REPLACE TYPE BODY t_persona AS\n MEMBER FUNCTION saludo RETURN VARCHAR2 IS BEGIN RETURN nombre; END;\nEND;" }, + ], + }); + const source = "DECLARE p t_persona; BEGIN x := p.nombre; y := p.saludo; END;"; + const field = await resolveSymbol(at([source], "nombre;", { lookup }), path(["P", "NOMBRE"])); + expect(field).toHaveLength(1); + expect(field[0]).toMatchObject({ kind: "symbol", symbol: { kind: "field", dataType: "VARCHAR2(50)" }, location: { where: "object", partKind: "TYPE", line: 2 } }); + const method = await resolveSymbol(at([source], "saludo;", { lookup }), path(["P", "SALUDO"])); + expect(method.map((item) => item.kind === "symbol" && item.location.where === "object" && item.location.partKind)).toEqual(["TYPE", "TYPE BODY"]); +}); diff --git a/app/src/symbolResolve.ts b/app/src/symbolResolve.ts index 3363273..31e52a1 100644 --- a/app/src/symbolResolve.ts +++ b/app/src/symbolResolve.ts @@ -286,6 +286,13 @@ class Resolver { const cursor = findSymbol(home, base[0], cursorKinds, at); if (cursor?.symbol.query) return this.queryColumn(cursor.symbol.query, name, cursor.symbol.name); } + if (base.length === 2) { + // pkg.cursor%ROWTYPE + const owner = await this.object(null, base[0]); + const unit = owner?.object_type === "Package" ? await this.home(owner) : null; + const cursor = unit ? findSymbol(unit, base[1], cursorKinds) : null; + if (cursor?.symbol.query) return this.queryColumn(cursor.symbol.query, name, cursor.symbol.name); + } const table = base[base.length - 1]; const column = (await this.columns(base.length > 1 ? base[0] : null, table)).find((item) => item.name === name); return column ? [{ kind: "column", table, column }] : []; @@ -303,25 +310,43 @@ class Resolver { if (collection) return this.typeMembers(home, collection[1], name, depth + 1, at); const base = nameParts(text); - let typeHome: Home | null = home; + if (base.length < 1 || base.length > 2) return []; + let typeHome: Home | null = base.length === 1 ? home : null; let typeAt = at; - if (base.length === 2) { - const object = await this.object(null, base[0]); - typeHome = object?.object_type === "Package" ? await this.home(object) : null; + let type = typeHome ? findSymbol(typeHome, base[0], typeKinds, typeAt) : null; + if (!type) { + // Tipo de otro paquete (pkg.t_rec) o tipo objeto del esquema (t_persona, hr.t_persona). typeAt = undefined; - } else if (base.length !== 1) { - return []; + const owner = base.length === 2 ? await this.object(null, base[0]) : null; + if (owner?.object_type === "Package") { + typeHome = await this.home(owner); + } else { + const object = base.length === 2 ? await this.object(base[0], base[1]) : await this.object(null, base[0]); + typeHome = object?.object_type === "Type" ? await this.home(object) : null; + } + type = typeHome ? findSymbol(typeHome, base[base.length - 1], typeKinds) : null; + } + if (!type || !typeHome) return []; + const found = type; + const typeName = found.symbol.name; + if (found.symbol.dataType === "OBJECT") { + const members: Resolved[] = []; + typeHome.symbols.forEach((symbols, part) => { + for (const symbol of symbols) { + if (symbol.container === typeName && symbol.name === name && symbol.kind !== "parameter") { + members.push(located(typeHome, part, symbol)); + } + } + }); + return members; } - if (!typeHome) return []; - const type = findSymbol(typeHome, base[base.length - 1], typeKinds, typeAt); - if (!type) return []; - if (type.symbol.kind === "type" && /^RECORD\b/i.test(type.symbol.dataType ?? "")) { - return typeHome.symbols[type.part] - .filter((symbol) => symbol.kind === "field" && symbol.container === type.symbol.name && symbol.name === name && - symbol.scope?.from === type.symbol.scope?.from) - .map((symbol) => located(typeHome, type.part, symbol)); + if (found.symbol.kind === "type" && /^RECORD\b/i.test(found.symbol.dataType ?? "")) { + return typeHome.symbols[found.part] + .filter((symbol) => symbol.kind === "field" && symbol.container === typeName && symbol.name === name && + symbol.scope?.from === found.symbol.scope?.from) + .map((symbol) => located(typeHome, found.part, symbol)); } - return type.symbol.dataType ? this.typeMembers(typeHome, type.symbol.dataType, name, depth + 1, typeAt) : []; + return found.symbol.dataType ? this.typeMembers(typeHome, found.symbol.dataType, name, depth + 1, typeAt) : []; } /** Columna `name` de la lista de un SELECT; tipo de la tabla si es una columna simple. */ From f7bbd47e0591fffc69795c625597c61b3d667109 Mon Sep 17 00:00:00 2001 From: Walter Aquino Date: Fri, 27 Nov 2026 11:28:34 -0300 Subject: [PATCH 22/24] =?UTF-8?q?fix(app):=20WAL-118=20buscar=20sin=20vers?= =?UTF-8?q?i=C3=B3n=20nueva=20quita=20el=20=C3=ADcono;=20acento=20al=20pas?= =?UTF-8?q?ar=20el=20mouse?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tests de los casos que quedaban sin cubrir: error al buscar, clic durante la instalación y segundo clic en Nuevo. Documentación de WAL-121. Co-Authored-By: Claude Opus 5.5 --- app/src/App.css | 3 ++ app/src/App.test.tsx | 45 +++++++++++++++++++++++++++++ app/src/App.tsx | 6 +++- docs/ESTADO.md | 3 +- docs/behavior/editor-inteligente.md | 12 ++++++-- 5 files changed, 64 insertions(+), 5 deletions(-) diff --git a/app/src/App.css b/app/src/App.css index af77d49..b3ea30f 100644 --- a/app/src/App.css +++ b/app/src/App.css @@ -169,3 +169,6 @@ 40% { transform: translateY(-4px); } 70% { transform: translateY(1px); } } +.update-badge:hover:not(:disabled) { + color: var(--accent); +} diff --git a/app/src/App.test.tsx b/app/src/App.test.tsx index 1fe2cdf..03c389f 100644 --- a/app/src/App.test.tsx +++ b/app/src/App.test.tsx @@ -1291,3 +1291,48 @@ test("F12 sobre un miembro de otro paquete lo abre en su declaración", async () expect(opened.state.selection.main.head).toBe(other.indexOf("hacer")); }); }); + +test("buscar actualizaciones sin versión nueva quita el ícono que había", async () => { + windowEvents.close.mockResolvedValue(() => {}); + updater.check.mockResolvedValueOnce({ version: "9.9.9", notes: "", install: vi.fn() }).mockResolvedValueOnce(null); + render(); + fireEvent.click(await screen.findByRole("button", { name: "Más tarde" })); + expect(screen.getByRole("button", { name: "Actualización disponible: 9.9.9" })).toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: "Ayuda" })); + fireEvent.click(within(screen.getByRole("menu", { name: "Ayuda" })).getByRole("menuitem", { name: /Buscar actualizaciones/ })); + expect(await screen.findByText("Estás al día")).toBeInTheDocument(); + expect(screen.queryByRole("button", { name: /Actualización disponible/ })).not.toBeInTheDocument(); +}); + +test("un error al buscar actualizaciones deja el ícono", async () => { + windowEvents.close.mockResolvedValue(() => {}); + updater.check.mockResolvedValueOnce({ version: "9.9.9", notes: "", install: vi.fn() }).mockRejectedValueOnce(new Error("red")); + render(); + fireEvent.click(await screen.findByRole("button", { name: "Más tarde" })); + fireEvent.click(screen.getByRole("button", { name: "Ayuda" })); + fireEvent.click(within(screen.getByRole("menu", { name: "Ayuda" })).getByRole("menuitem", { name: /Buscar actualizaciones/ })); + expect(await screen.findByText("No se pudo buscar actualizaciones")).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Actualización disponible: 9.9.9" })).toBeInTheDocument(); +}); + +test("durante la instalación el ícono no abre otro diálogo", async () => { + windowEvents.close.mockResolvedValue(() => {}); + updater.check.mockResolvedValue({ version: "9.9.9", notes: "", install: vi.fn(() => new Promise(() => {})) }); + render(); + fireEvent.click(await screen.findByRole("button", { name: "Actualizar" })); + expect(await screen.findByRole("status", { name: "" })).toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: "Actualización disponible: 9.9.9" })); + expect(screen.getAllByRole("dialog", { name: "OpenPL 9.9.9" })).toHaveLength(1); +}); + +test("un segundo clic en Nuevo lo cierra", async () => { + windowEvents.close.mockResolvedValue(() => {}); + render(); + fireEvent.click(await screen.findByRole("button", { name: "Cancelar" })); + const nuevo = screen.getByRole("button", { name: "Nuevo" }); + fireEvent.click(nuevo); + expect(screen.getByRole("menu", { name: "Nuevo" })).toBeInTheDocument(); + fireEvent.mouseDown(nuevo); + fireEvent.click(nuevo); + expect(screen.queryByRole("menu", { name: "Nuevo" })).not.toBeInTheDocument(); +}); diff --git a/app/src/App.tsx b/app/src/App.tsx index fb82517..0313ee8 100644 --- a/app/src/App.tsx +++ b/app/src/App.tsx @@ -590,7 +590,11 @@ export default function App() { setPendingUpdate(result.update); setUpdateOffer(result.update); } - else if (result.kind === "upToDate" && !silent) showNotice("Estás al día"); + else if (result.kind === "upToDate") { + // La versión anunciada ya no está publicada: el ícono no debe seguir prometiéndola. + setPendingUpdate(null); + if (!silent) showNotice("Estás al día"); + } else if (result.kind === "error") showNotice(result.message, "error"); } const updateChecked = useRef(false); diff --git a/docs/ESTADO.md b/docs/ESTADO.md index 5e53f95..6368d75 100644 --- a/docs/ESTADO.md +++ b/docs/ESTADO.md @@ -4,7 +4,7 @@ ## Resumen -- Editor inteligente (WAL-119, rama `xwhiterr/wal-119-editor-inteligente-ficha-al-pasar-el-mouse`): ficha al pasar el puntero con firma, tipo, valor declarado, comentario, campos de registros y columnas; Ir a la definición (F12, Ctrl+clic), a la declaración (Ctrl+F12) y a la implementación (Ctrl+Shift+F12) en paquetes, ventanas SQL y de prueba. [Comportamiento](behavior/editor-inteligente.md), [diseño](superpowers/specs/2026-11-27-openpl-editor-inteligente-design.md), [plan](superpowers/plans/2026-11-27-openpl-editor-inteligente.md) y [auditoría](../anti-slop/audit-editor-inteligente-2026-11-27.md). Pendiente la prueba en escritorio contra Oracle. +- Editor inteligente (WAL-119, rama `xwhiterr/wal-119-editor-inteligente-ficha-al-pasar-el-mouse`): ficha al pasar el puntero con firma, tipo, valor declarado, comentario, campos de registros y columnas; Ir a la definición (F12, Ctrl+clic), a la declaración (Ctrl+F12) y a la implementación (Ctrl+Shift+F12) en paquetes, ventanas SQL y de prueba. [Comportamiento](behavior/editor-inteligente.md), [diseño](superpowers/specs/2026-11-27-openpl-editor-inteligente-design.md), [plan](superpowers/plans/2026-11-27-openpl-editor-inteligente.md) y [auditoría](../anti-slop/audit-editor-inteligente-2026-11-27.md). Pendientes de la revisión resueltos en WAL-121: análisis sin reparsear (14.000 líneas: unos 25 ms con el árbol del editor), F12 que no salta tarde, Alt+clic para agregar cursor, fuente envuelta, registro tardío, prioridad de alias, `pkg.cursor%ROWTYPE` y tipos objeto. Pendiente la prueba en escritorio contra Oracle. - 1.0.0-beta.8 (WAL-118, WAL-120): con una versión nueva, la barra superior muestra un ícono que da un salto corto y abre el diálogo de actualización. "Más tarde" deja el ícono. Nuevo y los menús de la barra ya no quedan abiertos a la vez. @@ -130,6 +130,7 @@ Rama creada desde `main`, sin merge ni push. Auditoría: | Ir a la declaración (WAL-119) | F12 | Ctrl+F12 | | Ir a la implementación (WAL-119) | (no existía) | Ctrl+Shift+F12 | | Mostrar ficha (WAL-119) | (no existía) | Ctrl+Shift+Espacio | +| Agregar un cursor (WAL-121) | Ctrl+clic | Alt+clic | | Ejecutar | F8 | F8 o Ctrl+Enter | | Buscar siguiente / anterior | sin atajo | F3 / Shift+F3 | | Pestaña siguiente / anterior | sin atajo | Ctrl+Tab / Ctrl+Shift+Tab | diff --git a/docs/behavior/editor-inteligente.md b/docs/behavior/editor-inteligente.md index eec19fa..389167d 100644 --- a/docs/behavior/editor-inteligente.md +++ b/docs/behavior/editor-inteligente.md @@ -16,18 +16,22 @@ tiene ficha. de un cursor, `RECORD` propio, colecciones (`t(i).campo`) y `%TYPE`. En un SELECT, `alias.columna` muestra la columna de la tabla. Una columna de cursor que es una expresión muestra "Expresión". +- **Tipos objeto:** `variable.atributo` y `variable.metodo` muestran el atributo o el método del + tipo (`CREATE TYPE … AS OBJECT`); un método lleva a su implementación en el `TYPE BODY`. +- **Cursores de otro paquete:** `pkg.cursor%ROWTYPE` resuelve las columnas de ese cursor. - **Tablas y vistas:** columnas con tipo y `NOT NULL`, hasta 30. - Cada ficha dice dónde está la declaración (línea, y objeto y parte si es de otro objeto) y el comentario pegado arriba de ella o al final de su línea. - Las sobrecargas muestran una ficha por firma. -- Un objeto con la fuente envuelta o sin permiso de lectura dice "Fuente no disponible". +- Un objeto con la fuente envuelta (`wrapped`) o sin permiso de lectura dice "Fuente no disponible". + Si solo el cuerpo está envuelto, la ficha usa la spec. ## Orden de búsqueda 1. Declaraciones locales visibles en el cursor: la más interna gana sobre una global con el mismo nombre. 2. Declaraciones del paquete abierto, en Spec y Body. -3. Alias y tablas de la sentencia SQL. +3. Dentro de una sentencia SQL, sus alias y tablas van antes que las variables (como en Oracle). 4. Objetos del catálogo, con la conexión principal. Un paquete abierto en otra pestaña se lee del editor, aunque tenga cambios sin guardar. @@ -42,8 +46,10 @@ por conexión y se vuelve a pedir al compilar, refrescar el explorador o reconec | Ir a la declaración | Ctrl+F12 | La declaración en la Spec; si no hay, el cuerpo | | Ir a la implementación | Ctrl+Shift+F12 | El cuerpo; sin cuerpo, la declaración y el aviso "Cuerpo no disponible" | -- Con Ctrl apretado, el nombre bajo el puntero se subraya. +- Con Ctrl apretado, el nombre bajo el puntero se subraya. Ctrl+clic donde no hay destino ubica el + cursor como un clic normal. Agregar un cursor pasa a Alt+clic. - Con varias firmas, un selector lista cada destino. - Un destino en otro objeto abre ese objeto (o activa su pestaña) en la línea de la declaración. +- Si mientras se busca el destino se escribe, se mueve el cursor o se cambia de pestaña, no se navega. - Sobre una tabla o vista, los tres comandos abren su descripción. - El menú contextual de un nombre suma los tres comandos arriba de Describir, Ver fuente y Copiar. From 71a80a0e58f142a41f7c93bd136d8b60db48b2c5 Mon Sep 17 00:00:00 2001 From: Walter Aquino Date: Fri, 27 Nov 2026 11:37:23 -0300 Subject: [PATCH 23/24] =?UTF-8?q?fix(app):=20WAL-121=20correcciones=20de?= =?UTF-8?q?=20la=20segunda=20revisi=C3=B3n?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Los alias solo valen dentro del texto SQL; INTO no es alias; un ; dentro de un texto o comentario no corta la sentencia. - Selección en columna con Alt+Shift+arrastrar; Alt+clic agrega cursor. - Constructor RETURN SELF AS RESULT empareja spec y body; la lista de AS OBJECT no se corta en AS. - Tipos UNDER con atributos propios y heredados. - Lo declarado dentro de un método no se toma como miembro del tipo. - Ctrl+clic sin contexto ubica el cursor. Co-Authored-By: Claude Opus 5.5 --- app/src/components/ProgramEditor.tsx | 2 +- app/src/components/ProgramWindow.test.tsx | 13 +++++ app/src/components/ProgramWindow.tsx | 6 ++- app/src/components/SqlWindow.tsx | 6 ++- app/src/programSymbols.test.ts | 20 ++++++++ app/src/programSymbols.ts | 22 ++++++--- app/src/symbolResolve.test.ts | 40 +++++++++++++++- app/src/symbolResolve.ts | 58 +++++++++++++++++++---- docs/ESTADO.md | 1 + docs/behavior/editor-inteligente.md | 10 ++-- 10 files changed, 154 insertions(+), 24 deletions(-) diff --git a/app/src/components/ProgramEditor.tsx b/app/src/components/ProgramEditor.tsx index 229ca9c..37e0d18 100644 --- a/app/src/components/ProgramEditor.tsx +++ b/app/src/components/ProgramEditor.tsx @@ -165,7 +165,7 @@ export function ProgramEditor(props: Props) { parent: host.current!, doc: latest.current.part.source, extensions: [ - lineNumbers(), programFolding, foldGutter(), drawSelection(), rectangularSelection(), history(), + lineNumbers(), programFolding, foldGutter(), drawSelection(), rectangularSelection({ eventFilter: (event) => event.altKey && event.shiftKey }), history(), highlightActiveLine(), editorSearch(), highlightSelectionMatches(), sql({ dialect: oracleDialect }), syntaxHighlighting(programSyntax), indentUnit.of(INDENT), editing.of(editingExtensions(latest.current.readOnly, label)), diff --git a/app/src/components/ProgramWindow.test.tsx b/app/src/components/ProgramWindow.test.tsx index 1bc47b6..5ac540b 100644 --- a/app/src/components/ProgramWindow.test.tsx +++ b/app/src/components/ProgramWindow.test.tsx @@ -967,3 +967,16 @@ test("una ventana que recibe su objeto después se registra entonces, una sola v rerender( registerSource(read)} sourceKey="s1|HR|PKG_A" />); expect(registerSource).toHaveBeenCalledOnce(); }); + +test("Ctrl+clic sin contexto de símbolos igual ubica el cursor", async () => { + const source = "PACKAGE BODY PKG_A AS\nBEGIN\n pkg_w.f;\nEND;"; + const symbols = { object: vi.fn(async () => null), parts: vi.fn(async () => []), columns: vi.fn(async () => []) }; + render(); + const view = EditorView.findFromDOM(screen.getByRole("textbox", { name: "Body" }).closest(".cm-editor")!)!; + const position = source.indexOf("pkg_w") + 2; + vi.spyOn(view, "posAtCoords").mockReturnValue(position); + const resolveAt = await import("../editorNavigation"); + vi.spyOn(resolveAt, "resolveAt").mockResolvedValue(null); + fireEvent.mouseDown(view.contentDOM, { ctrlKey: true, button: 0, clientX: 5, clientY: 5 }); + await waitFor(() => expect(view.state.selection.main.head).toBe(position)); +}); diff --git a/app/src/components/ProgramWindow.tsx b/app/src/components/ProgramWindow.tsx index 1e60400..1519814 100644 --- a/app/src/components/ProgramWindow.tsx +++ b/app/src/components/ProgramWindow.tsx @@ -330,7 +330,11 @@ export function ProgramWindow({ const head = view.state.selection.main.head; const found = await resolveAt(view, position, symbolContext); // Si mientras tanto se escribió o se movió el cursor, el destino ya no corresponde. - if (!found || !activeRef.current || view.state.doc !== doc || view.state.selection.main.head !== head) return; + if (!activeRef.current || view.state.doc !== doc || view.state.selection.main.head !== head) return; + if (!found) { + onMiss?.(); + return; + } const { name, items } = found; const relation = items.find((item) => item.kind === "relation"); if (relation?.kind === "relation") { diff --git a/app/src/components/SqlWindow.tsx b/app/src/components/SqlWindow.tsx index 7790b4f..8753048 100644 --- a/app/src/components/SqlWindow.tsx +++ b/app/src/components/SqlWindow.tsx @@ -836,7 +836,11 @@ export function SqlWindow({ const head = editor.state.selection.main.head; const found = await resolveAt(editor, position, symbolContext); // Si mientras tanto se escribió o se movió el cursor, el destino ya no corresponde. - if (!found || !activeRef.current || editor.state.doc !== doc || editor.state.selection.main.head !== head) return; + if (!activeRef.current || editor.state.doc !== doc || editor.state.selection.main.head !== head) return; + if (!found) { + onMiss?.(); + return; + } const relation = found.items.find((item) => item.kind === "relation"); if (relation?.kind === "relation") { openObject?.(relation.object); diff --git a/app/src/programSymbols.test.ts b/app/src/programSymbols.test.ts index 19946a3..578e181 100644 --- a/app/src/programSymbols.test.ts +++ b/app/src/programSymbols.test.ts @@ -194,3 +194,23 @@ test("tipo objeto: atributos y métodos en spec y body", () => { const typeBody = "CREATE OR REPLACE TYPE BODY t_persona AS\n MEMBER FUNCTION saludo RETURN VARCHAR2 IS BEGIN RETURN nombre; END;\nEND;"; expect(one(programSymbols(typeBody), "SALUDO")).toMatchObject({ kind: "function", container: "T_PERSONA", definition: true }); }); + +test("el constructor empareja spec y body, y lo que sigue a SELF AS RESULT se lee", () => { + const typeSpec = "CREATE OR REPLACE TYPE t_p AS OBJECT (\n CONSTRUCTOR FUNCTION t_p(n VARCHAR2) RETURN SELF AS RESULT,\n edad NUMBER\n);"; + const typeBody = "CREATE OR REPLACE TYPE BODY t_p AS\n CONSTRUCTOR FUNCTION t_p(n VARCHAR2) RETURN SELF AS RESULT IS BEGIN RETURN; END;\nEND;"; + const declared = programSymbols(typeSpec); + expect(one(declared, "EDAD")).toMatchObject({ kind: "field", container: "T_P" }); + const specKey = declared.find((symbol) => symbol.kind === "function")?.key; + const bodyKey = programSymbols(typeBody).find((symbol) => symbol.kind === "function")?.key; + expect(specKey).toBeDefined(); + expect(specKey).toBe(bodyKey); +}); + +test("las rutinas y variables internas de un método no son del tipo", () => { + const typeBody = + "CREATE OR REPLACE TYPE BODY t_p AS\n MEMBER FUNCTION f RETURN NUMBER IS\n map NUMBER;\n PROCEDURE helper IS BEGIN NULL; END;\n BEGIN RETURN 1; END;\nEND;"; + const symbols = programSymbols(typeBody); + expect(one(symbols, "F")).toMatchObject({ container: "T_P" }); + expect(one(symbols, "HELPER")).toMatchObject({ container: null }); + expect(one(symbols, "MAP")).toMatchObject({ kind: "variable" }); +}); diff --git a/app/src/programSymbols.ts b/app/src/programSymbols.ts index 67d9c28..a2d481f 100644 --- a/app/src/programSymbols.ts +++ b/app/src/programSymbols.ts @@ -195,7 +195,8 @@ class Analyzer { } /** Elementos separados por comas dentro del paréntesis que abre en `open`. */ - private list(open: number) { + /** `stopAtBody`: un paréntesis sin cerrar termina en IS, AS o `;` (no sirve dentro de `AS OBJECT (…)`). */ + private list(open: number, stopAtBody = true) { const items: [number, number][] = []; if (this.tokens[open]?.key !== "(") return { items, after: open }; let depth = 0; @@ -203,7 +204,7 @@ class Analyzer { for (let i = open; i < this.tokens.length; i += 1) { const { key } = this.tokens[i]; // Paréntesis sin cerrar: la lista termina donde empieza el cuerpo o la sentencia. - if (listStops.has(key)) { + if (stopAtBody && listStops.has(key)) { if (i > start) items.push([start, i]); return { items, after: i }; } @@ -382,8 +383,10 @@ class Analyzer { const name = tokens[nameIndex]; if (!isIdentifier(name)) return; const typeName = nameOf(name); - const header = boundary(tokens, nameIndex + 1, routineMarkers); - if (tokens[header]?.key !== "IS" && tokens[header]?.key !== "AS") return; + // `TYPE t UNDER padre (…)` no lleva IS ni AS. + const under = !isBody && tokens[nameIndex + 1]?.key === "UNDER"; + const header = under ? nameIndex : boundary(tokens, nameIndex + 1, routineMarkers); + if (!under && tokens[header]?.key !== "IS" && tokens[header]?.key !== "AS") return; if (isBody) { this.typeName = typeName; this.section(header + 1, null); @@ -391,12 +394,13 @@ class Analyzer { return; } const end = this.statementEnd(header); - const object = tokens[header + 1]?.key === "OBJECT" || tokens[header + 1]?.key === "UNDER"; + const object = under || tokens[header + 1]?.key === "OBJECT"; + const parent = under ? tokens[readName(tokens, nameIndex + 2)] : undefined; this.push({ kind: "type", name: typeName, signature: `TYPE ${this.text(unit + 1, nameIndex + 1)}`, - dataType: object ? "OBJECT" : this.text(header + 1, end) || null, + dataType: parent && isIdentifier(parent) ? `UNDER ${nameOf(parent)}` : object ? "OBJECT" : this.text(header + 1, end) || null, value: null, comment: this.comment(unit, nameIndex), from: name.from, @@ -406,7 +410,7 @@ class Analyzer { }); if (!object) return; const open = boundary(tokens, header + 1, new Set(["("]), end); - for (const [from, to] of this.list(open).items) { + for (const [from, to] of this.list(open, false).items) { let first = from; while (first < to && methodPrefixes.has(tokens[first].key)) first += 1; if (tokens[first]?.key === "PROCEDURE" || tokens[first]?.key === "FUNCTION") { @@ -482,7 +486,11 @@ class Analyzer { } if (!definition) return marker + 1; own.to = this.source.length; + // Lo declarado dentro de un método no pertenece al tipo. + const outerType = this.typeName; + this.typeName = null; const stop = this.section(marker + 1, own); + this.typeName = outerType; const closing = tokens[stop]?.key === "BEGIN" ? this.blocks.get(stop) : tokens[stop]?.key === "END" ? stop : undefined; if (closing === undefined) { // Cuerpo sin END (se está escribiendo): sigue en la próxima rutina que empieza una sentencia. diff --git a/app/src/symbolResolve.test.ts b/app/src/symbolResolve.test.ts index 1bb805e..3b81671 100644 --- a/app/src/symbolResolve.test.ts +++ b/app/src/symbolResolve.test.ts @@ -226,7 +226,9 @@ test("un alias en un paquete grande no vuelve a parsear todo el paquete", async const parse = vi.spyOn(oracleDialect.language.parser, "parse"); const found = await resolveSymbol(context, path(["C", "ID"])); expect(found[0]).toMatchObject({ kind: "column", table: "CLIENTES" }); - for (const [input] of parse.mock.calls) expect(String(input).length).toBeLessThan(2000); + // Solo una ventana acotada alrededor del cursor (unos 8.000 caracteres); el paquete tiene más de 150.000. + expect(body.length).toBeGreaterThan(150_000); + for (const [input] of parse.mock.calls) expect(String(input).length).toBeLessThan(10_000); parse.mockRestore(); }); @@ -287,3 +289,39 @@ test("atributos y métodos de un tipo objeto", async () => { const method = await resolveSymbol(at([source], "saludo;", { lookup }), path(["P", "SALUDO"])); expect(method.map((item) => item.kind === "symbol" && item.location.where === "object" && item.location.partKind)).toEqual(["TYPE", "TYPE BODY"]); }); + +test("después del LOOP de un FOR con consulta, el registro vuelve a ser la variable", async () => { + const lookup = fakeLookup({ CLIENTES: info("CLIENTES", "Table"), OTRA: info("OTRA", "Table") }); + const source = "DECLARE r clientes%ROWTYPE; BEGIN FOR x IN (SELECT * FROM otra r) LOOP v := r.nombre; END LOOP; END;"; + const found = await resolveSymbol(at([source], "nombre;", { lookup }), path(["R", "NOMBRE"])); + expect(found).toMatchObject([{ kind: "column", table: "CLIENTES", column: { name: "NOMBRE" } }]); +}); + +test("el destino de INTO no es un alias", async () => { + const lookup = fakeLookup({ CLIENTES: info("CLIENTES", "Table") }); + const source = "DECLARE r clientes%ROWTYPE; BEGIN SELECT * INTO r FROM clientes c WHERE c.id = r.id; END;"; + const found = await resolveSymbol(at([source], "id;", { lookup }), path(["R", "ID"])); + expect(found).toMatchObject([{ kind: "column", table: "CLIENTES", column: { name: "ID" } }]); +}); + +test("un punto y coma dentro de un texto o un comentario no corta la sentencia", async () => { + const lookup = fakeLookup({ CLIENTES: info("CLIENTES", "Table") }); + const literal = "BEGIN SELECT LISTAGG(c.nombre, ';') WITHIN GROUP (ORDER BY 1) INTO x FROM clientes c; END;"; + expect(await resolveSymbol(at([literal], "nombre", { lookup }), path(["C", "NOMBRE"]))) + .toMatchObject([{ kind: "column", table: "CLIENTES" }]); + const comment = "BEGIN SELECT c.nombre -- fin; ok\n INTO x FROM clientes c; END;"; + expect(await resolveSymbol(at([comment], "nombre", { lookup }), path(["C", "NOMBRE"]))) + .toMatchObject([{ kind: "column", table: "CLIENTES" }]); +}); + +test("atributos de un subtipo UNDER, propios y heredados", async () => { + const lookup = fakeLookup({ T_EMP: info("T_EMP", "Type"), T_PERSONA: info("T_PERSONA", "Type") }, { + T_EMP: [{ kind: "TYPE", source: "CREATE OR REPLACE TYPE t_emp UNDER t_persona (\n sueldo NUMBER\n);" }], + T_PERSONA: [{ kind: "TYPE", source: "CREATE OR REPLACE TYPE t_persona AS OBJECT (\n nombre VARCHAR2(50)\n) NOT FINAL;" }], + }); + const source = "DECLARE e t_emp; BEGIN x := e.sueldo; y := e.nombre; END;"; + expect(await resolveSymbol(at([source], "sueldo;", { lookup }), path(["E", "SUELDO"]))) + .toMatchObject([{ kind: "symbol", symbol: { name: "SUELDO", container: "T_EMP" } }]); + expect(await resolveSymbol(at([source], "nombre;", { lookup }), path(["E", "NOMBRE"]))) + .toMatchObject([{ kind: "symbol", symbol: { name: "NOMBRE", container: "T_PERSONA" } }]); +}); diff --git a/app/src/symbolResolve.ts b/app/src/symbolResolve.ts index 31e52a1..23bb1ac 100644 --- a/app/src/symbolResolve.ts +++ b/app/src/symbolResolve.ts @@ -1,5 +1,5 @@ import type { NamePath } from "./editorReference"; -import { statementAliases, statementTables } from "./programCompletion"; +import { statementTables, type TableReference } from "./programCompletion"; import { isIdentifier, nameOf, tokenize, type Token } from "./programStructure"; import { programSymbols, type ProgramSymbol, type Tree } from "./programSymbols"; import type { SourcePart, SymbolLookup } from "./symbolSources"; @@ -97,12 +97,48 @@ function located(home: Home, part: number, symbol: ProgramSymbol): Resolved { }; } -/** Alias de la sentencia en `position`, tokenizando solo entre los `;` que la rodean. */ -function aliasesAround(source: string, position: number) { - const start = source.lastIndexOf(";", Math.max(0, position - 1)) + 1; - const next = source.indexOf(";", position); - const end = next < 0 ? source.length : next; - return statementAliases(source.slice(start, end), position - start); +const sqlStarts = new Set(["SELECT", "INSERT", "UPDATE", "DELETE", "MERGE", "WITH"]); +const ALIAS_WINDOW = 4000; + +/** + * Tablas y alias visibles en `position`, solo si está dentro del texto de una sentencia SQL + * (no en el PL/SQL que la rodea, p. ej. después del LOOP de un FOR con consulta). Tokeniza una + * ventana acotada, así un `;` dentro de un texto o un comentario no corta la sentencia. + */ +function sqlAliasesAt(source: string, position: number) { + const aliases = new Map(); + const from = source.lastIndexOf("\n", Math.max(0, position - ALIAS_WINDOW)) + 1; + const next = source.indexOf("\n", position + ALIAS_WINDOW); + const text = source.slice(from, next < 0 ? source.length : next); + const at = position - from; + const tokens = tokenize(text); + let first = 0; + let last = tokens.length; + for (let i = 0; i < tokens.length; i += 1) { + if (tokens[i].key !== ";") continue; + if (tokens[i].from < at) first = i + 1; + else { + last = i; + break; + } + } + const inside = tokens.slice(first, last).some((token, offset) => { + if (!sqlStarts.has(token.key) || token.from > at) return false; + // La sentencia termina en el paréntesis que la cierra o al final. + let depth = 0; + for (let j = first + offset + 1; j < last; j += 1) { + const { key } = tokens[j]; + if (key === "(") depth += 1; + else if (key === ")" && depth-- === 0) return at <= tokens[j].from; + } + return true; + }); + if (!inside) return aliases; + for (const { ref, alias } of statementTables(text, at)) { + aliases.set(ref.name, ref); + if (alias) aliases.set(alias, ref); + } + return aliases; } /** Nombre con puntos, respetando comillas: `hr."Mi Tabla"` → ["HR", "Mi Tabla"]. */ @@ -227,7 +263,7 @@ class Resolver { private async firstEntity(name: string): Promise { // Dentro de una sentencia SQL, Oracle resuelve primero sus alias y tablas. const { current, position } = this.ctx; - const table = aliasesAround(this.ctx.parts[current]?.source ?? "", position).get(name); + const table = sqlAliasesAt(this.ctx.parts[current]?.source ?? "", position).get(name); if (table) return { t: "relation", owner: table.owner, name: table.name }; const visible = this.visible(name); const fromSymbol = this.entityFromSymbol(visible.find((item) => @@ -329,7 +365,8 @@ class Resolver { if (!type || !typeHome) return []; const found = type; const typeName = found.symbol.name; - if (found.symbol.dataType === "OBJECT") { + const parent = /^UNDER (.+)$/.exec(found.symbol.dataType ?? "")?.[1]; + if (found.symbol.dataType === "OBJECT" || parent) { const members: Resolved[] = []; typeHome.symbols.forEach((symbols, part) => { for (const symbol of symbols) { @@ -338,7 +375,8 @@ class Resolver { } } }); - return members; + // Lo heredado se busca en el tipo padre. + return members.length || !parent ? members : this.typeMembers(typeHome, parent, name, depth + 1); } if (found.symbol.kind === "type" && /^RECORD\b/i.test(found.symbol.dataType ?? "")) { return typeHome.symbols[found.part] diff --git a/docs/ESTADO.md b/docs/ESTADO.md index 6368d75..ef8a1bc 100644 --- a/docs/ESTADO.md +++ b/docs/ESTADO.md @@ -131,6 +131,7 @@ Rama creada desde `main`, sin merge ni push. Auditoría: | Ir a la implementación (WAL-119) | (no existía) | Ctrl+Shift+F12 | | Mostrar ficha (WAL-119) | (no existía) | Ctrl+Shift+Espacio | | Agregar un cursor (WAL-121) | Ctrl+clic | Alt+clic | +| Selección en columna (WAL-121) | Alt+arrastrar | Alt+Shift+arrastrar | | Ejecutar | F8 | F8 o Ctrl+Enter | | Buscar siguiente / anterior | sin atajo | F3 / Shift+F3 | | Pestaña siguiente / anterior | sin atajo | Ctrl+Tab / Ctrl+Shift+Tab | diff --git a/docs/behavior/editor-inteligente.md b/docs/behavior/editor-inteligente.md index 389167d..9b861d2 100644 --- a/docs/behavior/editor-inteligente.md +++ b/docs/behavior/editor-inteligente.md @@ -17,7 +17,8 @@ tiene ficha. muestra la columna de la tabla. Una columna de cursor que es una expresión muestra "Expresión". - **Tipos objeto:** `variable.atributo` y `variable.metodo` muestran el atributo o el método del - tipo (`CREATE TYPE … AS OBJECT`); un método lleva a su implementación en el `TYPE BODY`. + tipo (`CREATE TYPE … AS OBJECT` o `UNDER padre`, con lo heredado); un método lleva a su + implementación en el `TYPE BODY`. - **Cursores de otro paquete:** `pkg.cursor%ROWTYPE` resuelve las columnas de ese cursor. - **Tablas y vistas:** columnas con tipo y `NOT NULL`, hasta 30. - Cada ficha dice dónde está la declaración (línea, y objeto y parte si es de otro objeto) y el @@ -31,7 +32,9 @@ tiene ficha. 1. Declaraciones locales visibles en el cursor: la más interna gana sobre una global con el mismo nombre. 2. Declaraciones del paquete abierto, en Spec y Body. -3. Dentro de una sentencia SQL, sus alias y tablas van antes que las variables (como en Oracle). +3. Dentro del texto de una sentencia SQL, sus alias y tablas van antes que las variables (como en + Oracle). El destino de `INTO` no cuenta como alias, y después del `LOOP` de un FOR con consulta + vuelven a valer las variables. 4. Objetos del catálogo, con la conexión principal. Un paquete abierto en otra pestaña se lee del editor, aunque tenga cambios sin guardar. @@ -47,7 +50,8 @@ por conexión y se vuelve a pedir al compilar, refrescar el explorador o reconec | Ir a la implementación | Ctrl+Shift+F12 | El cuerpo; sin cuerpo, la declaración y el aviso "Cuerpo no disponible" | - Con Ctrl apretado, el nombre bajo el puntero se subraya. Ctrl+clic donde no hay destino ubica el - cursor como un clic normal. Agregar un cursor pasa a Alt+clic. + cursor como un clic normal. Agregar un cursor pasa a Alt+clic y la selección en columna a + Alt+Shift+arrastrar. - Con varias firmas, un selector lista cada destino. - Un destino en otro objeto abre ese objeto (o activa su pestaña) en la línea de la declaración. - Si mientras se busca el destino se escribe, se mueve el cursor o se cambia de pestaña, no se navega. From 803ecf36889ebad5ba588a0684d898b58e6adc9e Mon Sep 17 00:00:00 2001 From: Walter Aquino Date: Fri, 27 Nov 2026 11:38:14 -0300 Subject: [PATCH 24/24] fix(app): WAL-121 un PRAGMA en AS OBJECT no es atributo Co-Authored-By: Claude Opus 5.5 --- app/src/programSymbols.test.ts | 5 +++++ app/src/programSymbols.ts | 1 + 2 files changed, 6 insertions(+) diff --git a/app/src/programSymbols.test.ts b/app/src/programSymbols.test.ts index 578e181..8fa0fde 100644 --- a/app/src/programSymbols.test.ts +++ b/app/src/programSymbols.test.ts @@ -214,3 +214,8 @@ test("las rutinas y variables internas de un método no son del tipo", () => { expect(one(symbols, "HELPER")).toMatchObject({ container: null }); expect(one(symbols, "MAP")).toMatchObject({ kind: "variable" }); }); + +test("un PRAGMA dentro de AS OBJECT no es un atributo", () => { + const typeSpec = "CREATE TYPE t_p AS OBJECT (\n edad NUMBER,\n MEMBER FUNCTION f RETURN NUMBER,\n PRAGMA RESTRICT_REFERENCES(f, WNDS)\n);"; + expect(find(programSymbols(typeSpec), "PRAGMA")).toHaveLength(0); +}); diff --git a/app/src/programSymbols.ts b/app/src/programSymbols.ts index a2d481f..5aeabe4 100644 --- a/app/src/programSymbols.ts +++ b/app/src/programSymbols.ts @@ -413,6 +413,7 @@ class Analyzer { for (const [from, to] of this.list(open, false).items) { let first = from; while (first < to && methodPrefixes.has(tokens[first].key)) first += 1; + if (tokens[first]?.key === "PRAGMA") continue; if (tokens[first]?.key === "PROCEDURE" || tokens[first]?.key === "FUNCTION") { this.method(first, to, typeName); } else {