diff --git a/Cargo.lock b/Cargo.lock index 5fe699d..f510ed9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2939,7 +2939,7 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" [[package]] name = "openpl-app" -version = "1.0.0-beta.7" +version = "1.0.0-beta.8" dependencies = [ "dirs 6.0.0", "openpl-core", @@ -2959,7 +2959,7 @@ dependencies = [ [[package]] name = "openpl-core" -version = "1.0.0-beta.7" +version = "1.0.0-beta.8" dependencies = [ "dirs 6.0.0", "keyring", @@ -2975,7 +2975,7 @@ dependencies = [ [[package]] name = "openpl-oracle" -version = "1.0.0-beta.7" +version = "1.0.0-beta.8" dependencies = [ "oracle", "serde", diff --git a/Cargo.toml b/Cargo.toml index 5334bf8..87b59d7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "2" members = ["crates/openpl-oracle", "crates/openpl-core", "app/src-tauri"] [workspace.package] -version = "1.0.0-beta.7" +version = "1.0.0-beta.8" edition = "2021" license = "Apache-2.0 OR MIT" 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/app/package-lock.json b/app/package-lock.json index 49e1d0f..e4f7b65 100644 --- a/app/package-lock.json +++ b/app/package-lock.json @@ -1,12 +1,12 @@ { "name": "openpl", - "version": "1.0.0-beta.7", + "version": "1.0.0-beta.8", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "openpl", - "version": "1.0.0-beta.7", + "version": "1.0.0-beta.8", "license": "Apache-2.0 OR MIT", "dependencies": { "@codemirror/autocomplete": "^6.20.4", diff --git a/app/package.json b/app/package.json index ea8bab9..3228c24 100644 --- a/app/package.json +++ b/app/package.json @@ -1,7 +1,7 @@ { "name": "openpl", "private": true, - "version": "1.0.0-beta.7", + "version": "1.0.0-beta.8", "type": "module", "scripts": { "dev": "vite", diff --git a/app/src-tauri/tauri.conf.json b/app/src-tauri/tauri.conf.json index 9b5c4bb..927150c 100644 --- a/app/src-tauri/tauri.conf.json +++ b/app/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "OpenPL", - "version": "1.0.0-beta.7", + "version": "1.0.0-beta.8", "identifier": "org.openpl.app", "build": { "beforeDevCommand": "npm run dev", diff --git a/app/src/App.css b/app/src/App.css index 3b32f25..b3ea30f 100644 --- a/app/src/App.css +++ b/app/src/App.css @@ -155,3 +155,20 @@ justify-content: flex-end; gap: 8px; } + +.update-badge { + color: var(--accent); +} +@media (prefers-reduced-motion: no-preference) { + .update-badge { + animation: update-bounce 600ms ease-out 3; + } +} +@keyframes update-bounce { + 0%, 100% { transform: translateY(0); } + 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 8babf52..03c389f 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(), @@ -1210,3 +1212,127 @@ 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(); +}); + +test("una actualización encontrada deja el ícono tras Más tarde", async () => { + windowEvents.close.mockResolvedValue(() => {}); + updater.check.mockResolvedValue({ version: "9.9.9", notes: "", install: vi.fn() }); + render(); + fireEvent.click(await screen.findByRole("button", { name: "Más tarde" })); + expect(screen.queryByRole("dialog", { name: "OpenPL 9.9.9" })).not.toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: "Actualización disponible: 9.9.9" })); + expect(screen.getByRole("dialog", { name: "OpenPL 9.9.9" })).toBeInTheDocument(); +}); + +test("sin actualización no hay ícono", async () => { + windowEvents.close.mockResolvedValue(() => {}); + render(); + 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")); + }); +}); + +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 553dec9..0313ee8 100644 --- a/app/src/App.tsx +++ b/app/src/App.tsx @@ -4,6 +4,7 @@ import { useCallback, useEffect, useLayoutEffect, + useMemo, useRef, useState, } from "react"; @@ -41,6 +42,8 @@ import { parseTestFile, type TestSettings } from "./testFile"; 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"; @@ -81,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", @@ -120,6 +127,8 @@ interface ProgramTab { fileName?: string; workspaceProfileId?: string; load?: symbol; + /** Posición pedida por "Ir a la definición" desde otra ventana. */ + target?: { partKind: string; line: number; column: number }; /** Ventana SQL: sesión propia, texto inicial y estado de su transacción. */ sql?: { sessionId: string; @@ -182,12 +191,14 @@ 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(); }; 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); @@ -217,6 +228,7 @@ export default function App() { latestWorkspace.current = { programs, connections }; const saveBeforeClose = useRef<() => boolean>(() => false); const [updateOffer, setUpdateOffer] = useState(null); + const [pendingUpdate, setPendingUpdate] = useState(null); const [updateProgress, setUpdateProgress] = useState(undefined); // Un catálogo estable por sesión de ventana SQL: completado contra su propia sesión. const sqlCatalogs = useRef(new Map()); @@ -268,7 +280,10 @@ export default function App() { "spec", "body", "sideBySide", + "goToDefinition", "goToDeclaration", + "goToImplementation", + "showSymbolCard", "foldBlock", "unfoldBlock", "objectActions", @@ -307,7 +322,10 @@ export default function App() { !program.readOnly || [ "save", + "goToDefinition", "goToDeclaration", + "goToImplementation", + "showSymbolCard", "foldBlock", "unfoldBlock", "goToLine", @@ -336,7 +354,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), @@ -454,6 +475,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; @@ -564,8 +586,15 @@ export default function App() { async function checkUpdates(silent: boolean) { const result = await runCheck(tauriUpdater, silent); - if (result.kind === "available") setUpdateOffer(result.update); - else if (result.kind === "upToDate" && !silent) showNotice("Estás al día"); + if (result.kind === "available") { + setPendingUpdate(result.update); + setUpdateOffer(result.update); + } + 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); @@ -930,6 +959,7 @@ export default function App() { object: ObjectInfo, mode: "view" | "edit" = "view", connection = active, + at?: { partKind: string; line: number; column: number }, ) { if (!connection) return; if (!supportsProgram.has(object.object_type)) { @@ -955,6 +985,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 }); @@ -967,6 +998,7 @@ export default function App() { readOnly: mode === "view", dirty: false, load, + target: at, }); } try { @@ -1023,6 +1055,7 @@ export default function App() { try { return await api.sqlExecute(id, sql, []); } finally { + symbolSources.invalidate(sessionId); compileSession.current = null; try { await api.sqlClose(id); @@ -1126,12 +1159,12 @@ export default function App() {
- + + {pendingUpdate && ( + { if (updateProgress === undefined) setUpdateOffer(pendingUpdate); }} + /> + )} {newMenu && ( 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} @@ -1411,6 +1458,30 @@ export default function App() { Cargando editor…

}> { + const { location } = target; + if (location.where !== "object" || !editorConnection) return; + void onOpenObject(location.object, "view", editorConnection, { + partKind: location.partKind, + line: location.line, + 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, + 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/ContextMenu.tsx b/app/src/components/ContextMenu.tsx index 09e70d0..aca199b 100644 --- a/app/src/components/ContextMenu.tsx +++ b/app/src/components/ContextMenu.tsx @@ -21,11 +21,15 @@ interface Props { onClose: () => void; width?: number; className?: string; + /** Botón que abre el menú: un clic sobre él no cuenta como clic fuera. */ + anchor?: { readonly current: HTMLElement | null }; } /** Menú de clic derecho en la posición del puntero. Se cierra con Escape, clic fuera o al elegir. */ -export function ContextMenu({ x, y, label, items, onClose, width = 260, className = "" }: Props) { +export function ContextMenu({ x, y, label, items, onClose, width = 260, className = "", anchor }: Props) { const ref = useRef(null); + const anchorRef = useRef(anchor); + anchorRef.current = anchor; const hasAction = items.some((item) => item !== "sep" && item.run); const onCloseRef = useRef(onClose); onCloseRef.current = onClose; @@ -42,6 +46,7 @@ export function ContextMenu({ x, y, label, items, onClose, width = 260, classNam useEffect(() => { const out = (e: MouseEvent) => { if (ref.current?.contains(e.target as Node)) return; + if (anchorRef.current?.current?.contains(e.target as Node)) return; const focusInside = ref.current?.contains(document.activeElement); const hitsControl = e.target instanceof Element && 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/MenuBar.tsx b/app/src/components/MenuBar.tsx index ad01fb7..78ced39 100644 --- a/app/src/components/MenuBar.tsx +++ b/app/src/components/MenuBar.tsx @@ -23,7 +23,8 @@ function disabledReason(item: MenuItemDef): string { return "No disponible en el contexto actual"; } -export function MenuBar({ menus }: { menus: MenuDef[] }) { +/** `onOpen` avisa al abrir un menú, para cerrar los menús desplegables de afuera. */ +export function MenuBar({ menus, onOpen }: { menus: MenuDef[]; onOpen?: () => void }) { const [open, setOpen] = useState(null); const ref = useRef(null); const trigger = useRef(null); @@ -31,6 +32,8 @@ export function MenuBar({ menus }: { menus: MenuDef[] }) { menusRef.current = menus; const openRef = useRef(open); openRef.current = open; + const onOpenRef = useRef(onOpen); + onOpenRef.current = onOpen; useEffect(() => { let altPending = false; @@ -78,6 +81,7 @@ export function MenuBar({ menus }: { menus: MenuDef[] }) { useEffect(() => { if (!open) return; + onOpenRef.current?.(); const close = (e: MouseEvent) => { if (!ref.current?.contains(e.target as Node)) setOpen(null); }; diff --git a/app/src/components/ProgramEditor.tsx b/app/src/components/ProgramEditor.tsx index ec3f76d..37e0d18 100644 --- a/app/src/components/ProgramEditor.tsx +++ b/app/src/components/ProgramEditor.tsx @@ -16,6 +16,8 @@ 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 { symbolLink } from "../symbolLink"; import { programFolding } from "../programFolding"; import { catalogCompletion, keywordCompletion, type CompletionCatalog } from "../programCompletion"; import { editorSearch } from "./EditorSearch"; @@ -81,6 +83,10 @@ 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; + /** Ctrl+clic sobre un nombre: ir a su definición. */ + onCtrlClick?: (position: number) => void; } function markerDiagnostics(markers: EditorMarker[], length: number): Diagnostic[] { @@ -159,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)), @@ -173,6 +179,8 @@ export function ProgramEditor(props: Props) { to: "a", "folded code": "Código plegado", unfold: "Desplegar", }), 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 960f8b0..5ac540b 100644 --- a/app/src/components/ProgramWindow.test.tsx +++ b/app/src/components/ProgramWindow.test.tsx @@ -769,3 +769,214 @@ 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" } })); + 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(); +}); + +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(); +}); + +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(); + }); +}); + +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); +}); + +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(); +}); + +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)); +}); + +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(); +}); + +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 d9d6c8e..1519814 100644 --- a/app/src/components/ProgramWindow.tsx +++ b/app/src/components/ProgramWindow.tsx @@ -11,6 +11,11 @@ import { api } from "../api"; import { commands, formatKeys, type CommandId } from "../keymap"; import { describeError, type ObjectInfo, type ProgramPart } from "../types"; 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"; import { ProgramComparison, type ComparisonResult } from "./ProgramComparison"; @@ -18,6 +23,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, SymbolLookup } from "../symbolSources"; +import { editorPart, showSymbolCard, type ContextFor } from "../symbolHover"; export type ProgramActions = Partial void>> & { hasPending?: () => boolean }; @@ -59,6 +66,18 @@ 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; + /** 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. */ + 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; line: number; column: number }; } const caption = (kind: string) => { @@ -92,13 +111,10 @@ function storedOutlineWidth() { } } -interface DeclarationTarget { - index: number; - entry: ProgramDeclaration; -} 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, sourceKey, symbols, symbolSelf, + onNavigate, initialTarget, }: Props) { const [baselines, setBaselines] = useState(() => parts.map(baselineOf)); const [compiling, setCompiling] = useState(false); @@ -109,8 +125,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); @@ -138,6 +154,30 @@ 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; + 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(() => (sourceKey ? registerRef.current?.(liveSources) : undefined), [liveSources, sourceKey]); + const activeRef = useRef(active); + activeRef.current = active; + 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); @@ -268,35 +308,63 @@ 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). */ + /** `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[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 }); + 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); + // Si mientras tanto se escribió o se movió el cursor, el destino ya no corresponde. + if (!activeRef.current || view.state.doc !== doc || view.state.selection.main.head !== head) return; + if (!found) { + onMiss?.(); + return; } - if (canSplit && selected === 1) { - for (const entry of first) { - if (entry.name === reference.name) bySignature.set(entry.key, { index: 0, entry }); - } + 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 }); + 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 ${name}`, + x: coords.left, y: coords.bottom, targets, + }); + } else { + onMiss?.(); } } + useEffect(() => { + if (!initialTarget) return; + const index = parts.findIndex((part) => part.kind === initialTarget.partKind); + 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]); + async function save() { if (saving) return; const index = selected; @@ -448,7 +516,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, @@ -467,9 +537,10 @@ 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), goToLine: runInEditor(gotoLine), find: runInEditor(openFind), findNext: runInEditor(findNextMatch), @@ -586,6 +657,7 @@ export function ProgramWindow({ {split && {caption(entry.kind)}} void goTo("definition", index, position, () => { + views.current[index]?.dispatch({ selection: { anchor: position } }); + })} onView={(view) => { views.current[index] = view; const base = saved.current[index]; @@ -637,6 +712,7 @@ export function ProgramWindow({ {active && catalog && objectMenu && ( void goTo(goal, objectMenu.part, objectMenu.position))} onMessage={setMessage} onDescribe={(object) => setDescription({ object, sessionId: catalog.sessionId, id: objectMenu.id })} /> )} @@ -646,10 +722,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/SqlWindow.test.tsx b/app/src/components/SqlWindow.test.tsx index 327afe9..bac17d3 100644 --- a/app/src/components/SqlWindow.test.tsx +++ b/app/src/components/SqlWindow.test.tsx @@ -811,3 +811,68 @@ 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(); + }); +}); + +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 b2bcd3e..8753048 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 { editorPart, 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; line: number; column: 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,65 @@ 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) => ({ + parts: [editorPart("SQL", editor)], + 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, line: location.line, column: location.column }); + } 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, onMiss?: () => void) { + 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); + // Si mientras tanto se escribió o se movió el cursor, el destino ya no corresponde. + 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); + 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 }); + } else { + onMiss?.(); + } + } + const busy = running || fetching || applying; useEffect(() => { onBusy?.(busy); }, [busy, onBusy]); const actions: ProgramActions = { @@ -805,6 +879,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 +997,14 @@ export function SqlWindow({
{}} + symbolContext={symbolContext} + 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 }); + } : undefined} onView={onView} onSelection={setCursor} onChange={(doc) => { @@ -1136,6 +1222,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/components/SymbolCard.css b/app/src/components/SymbolCard.css new file mode 100644 index 0000000..77c9986 --- /dev/null +++ b/app/src/components/SymbolCard.css @@ -0,0 +1,64 @@ +.cm-tooltip.cm-symbol-tooltip { + border: 1px solid var(--line2); + border-radius: 4px; + background: var(--s1); + color: var(--text); + box-shadow: 0 4px 16px rgb(0 0 0 / 0.25); +} +.symbol-card { + max-width: 560px; + max-height: 320px; + overflow: auto; + padding: 6px 10px; + font-size: 12px; +} +.symbol-card-item + .symbol-card-item { + margin-top: 6px; + padding-top: 6px; + border-top: 1px solid var(--line); +} +.symbol-card code, +.symbol-card pre, +.symbol-card-columns { + font-family: var(--font-code); +} +.symbol-card-head { + display: flex; + align-items: baseline; + gap: 8px; +} +.symbol-card-head code { + white-space: pre-wrap; + word-break: break-word; +} +.symbol-card-head span, +.symbol-card-place, +.symbol-card-note, +.symbol-card-query { + color: var(--muted); +} +.symbol-card-type { + display: block; + margin-top: 2px; +} +.symbol-card p, +.symbol-card pre { + margin: 4px 0 0; +} +.symbol-card-comment, +.symbol-card-query { + white-space: pre-wrap; +} +.symbol-card-columns { + margin-top: 4px; + border-collapse: collapse; +} +.symbol-card-columns td { + 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/components/SymbolCard.test.tsx b/app/src/components/SymbolCard.test.tsx new file mode 100644 index 0000000..a15110b --- /dev/null +++ b/app/src/components/SymbolCard.test.tsx @@ -0,0 +1,61 @@ +import { render, screen } from "@testing-library/react"; +import { expect, test } from "vitest"; +import { SymbolCard } from "./SymbolCard"; +import type { Resolved } from "../symbolResolve"; +import type { ProgramSymbol } from "../programSymbols"; +import type { ObjectInfo } from "../types"; + +const pkg: ObjectInfo = { owner: "HR", name: "PKG_VENTAS", object_type: "Package", status: "Valid", last_ddl_time: "" }; + +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, column: 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, column: 1 }, + }]; + 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/components/UpdateBadge.test.tsx b/app/src/components/UpdateBadge.test.tsx new file mode 100644 index 0000000..b7227a2 --- /dev/null +++ b/app/src/components/UpdateBadge.test.tsx @@ -0,0 +1,10 @@ +import { fireEvent, render, screen } from "@testing-library/react"; +import { expect, test, vi } from "vitest"; +import { UpdateBadge } from "./UpdateBadge"; + +test("muestra la versión en su nombre y abre al hacer clic", () => { + 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/app/src/editorNavigation.test.ts b/app/src/editorNavigation.test.ts new file mode 100644 index 0000000..5999a78 --- /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, column: 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, column: 6 }, + }; + 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..aa945d8 --- /dev/null +++ b/app/src/editorNavigation.ts @@ -0,0 +1,79 @@ +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"; + +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.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 }; +} + +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) }; +} 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, + }; +} 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 eba0bc6..19a35ab 100644 --- a/app/src/keymap.ts +++ b/app/src/keymap.ts @@ -27,7 +27,10 @@ export type CommandId = | "spec" | "body" | "sideBySide" + | "goToDefinition" | "goToDeclaration" + | "goToImplementation" + | "showSymbolCard" | "foldBlock" | "unfoldBlock" | "objectActions" @@ -100,7 +103,10 @@ 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" }, { id: "objectActions", label: "Acciones del objeto", keys: "Alt+Enter" }, diff --git a/app/src/programStructure.ts b/app/src/programStructure.ts index 94f2d97..5730a97 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; @@ -118,7 +118,7 @@ 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( @@ -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..8fa0fde --- /dev/null +++ b/app/src/programSymbols.test.ts @@ -0,0 +1,221 @@ +import { expect, test, vi } from "vitest"; +import { oracleDialect } from "./editorReference"; +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); +}); + +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(); +}); + +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" + + " 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;"; + const tree = oracleDialect.language.parser.parse(source); + const parse = vi.spyOn(oracleDialect.language.parser, "parse"); + const symbols = programSymbols(source); + expect(parse).toHaveBeenCalledTimes(1); + expect(symbols.filter((symbol) => symbol.kind === "procedure")).toHaveLength(1600); + expect(symbols.find((symbol) => symbol.name === "P1599")?.comment).toBe("rutina 1599"); + expect(programSymbols(source, tree)).toHaveLength(symbols.length); + 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 }); +}); + +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" }); +}); + +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 new file mode 100644 index 0000000..5aeabe4 --- /dev/null +++ b/app/src/programSymbols.ts @@ -0,0 +1,564 @@ +import { oracleDialect } from "./editorReference"; +import { + boundary, + findCreatedUnit, + format, + normalizedParameter, + isIdentifier, + matchingBlocks, + nameOf, + readName, + signatureModifiers, + storedUnits, + 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" + | "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; + /** Rutinas: identifica la misma rutina en spec y body aunque cambien IN o los valores por omisión. */ + key?: string; +} + +interface Span { + from: number; + to: number; + text: string; +} + +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"]); +/** 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"]); + +/** 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.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 { 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) { + 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 = firstFrom(spans, start) - 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[firstFrom(spans, end)]; + return trailing && !/\n/.test(source.slice(end, trailing.from)) ? commentText(trailing.text) || null : null; +} + +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[]; + + constructor(private readonly source: string, tree?: Tree) { + const { tokens, comments } = scan(source, tree); + this.tokens = tokens; + this.blocks = matchingBlocks(this.tokens); + this.comments = comments; + } + + 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`. */ + /** `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; + 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 (stopAtBody && 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) { + 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 === "TYPE") { + this.objectType(unit); + 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 (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") { + 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: signatureOf(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: 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, + scope, + definition: false, + container, + }); + } + + /** 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 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))); + const signature = + `${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); + // `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); + this.typeName = null; + return; + } + const end = this.statementEnd(header); + 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: parent && isIdentifier(parent) ? `UNDER ${nameOf(parent)}` : 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, 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 { + 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); + 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: this.typeName, + key, + }; + 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; + // 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. + 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; + } + + 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. */ +/** `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, tree).run(); + } catch { + return []; + } +} 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..6a56455 --- /dev/null +++ b/app/src/symbolHover.ts @@ -0,0 +1,97 @@ +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"; +import type { SourcePart } from "./symbolSources"; +import { ensureSyntaxTree } from "@codemirror/language"; + +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; +}; + +/** 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/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 new file mode 100644 index 0000000..fa59e5c --- /dev/null +++ b/app/src/symbolLink.ts @@ -0,0 +1,71 @@ +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, + // 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 }; + 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; + }, + }), + ]; +} diff --git a/app/src/symbolResolve.test.ts b/app/src/symbolResolve.test.ts new file mode 100644 index 0000000..3b81671 --- /dev/null +++ b/app/src/symbolResolve.test.ts @@ -0,0 +1,327 @@ +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"; + +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, column: 12 }, + { where: "here", part: 1, from: body.indexOf("calcular"), line: 2, column: 12 }, + ]); +}); + +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" }]); +}); + +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" } }); +}); + +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 } }); +}); + +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) { + 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 }); + 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"])); + expect(found[0]).toMatchObject({ kind: "column", table: "CLIENTES" }); + // 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(); +}); + +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" } }); +}); + +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 } }, + ]); +}); + +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"]); +}); + +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 new file mode 100644 index 0000000..23bb1ac --- /dev/null +++ b/app/src/symbolResolve.ts @@ -0,0 +1,461 @@ +import type { NamePath } from "./editorReference"; +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"; +import type { ObjectColumn, ObjectInfo, ObjectType } from "./types"; + +export type SymbolLocation = + | { 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 } + | { 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. Sus declaraciones se ubican como "here". */ + self: Pick | null; + /** null sin conexión. */ + 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"]); +const MAX_DEPTH = 6; + +const cache = new Map(); +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, tree); + 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; +} + +/** 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; at?: At } + | { t: "query"; home: Home; query: string; label: string } + | { t: "relation"; owner: string | null; name: string } + | { t: "schema"; owner: string } + | { t: "unreadable"; object: ObjectInfo }; + +const homeOf = (parts: SourcePart[], object: ObjectInfo | null): Home => ({ + parts, + symbols: parts.map((part) => symbolsOf(part.source, part.tree)), + 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 { 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, column } + : { where: "here", part, from: symbol.from, line, column }, + }; +} + +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"]. */ +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; +} + +/** 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 found.find(({ symbol }) => !symbol.scope) ?? found[0] ?? 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, null); + } + + 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[]); + } + + /** 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[])) + .filter((part) => !wrappedSource.test(part.source)); + 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 } : { t: "unreadable", object }; + } + + /** 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 }; + } + 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 { + // Dentro de una sentencia SQL, Oracle resuelve primero sus alias y tablas. + const { current, position } = this.ctx; + 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) => + item.kind === "symbol" && (valueKinds.has(item.symbol.kind) || item.symbol.kind === "package"))); + if (fromSymbol) return fromSymbol; + 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, entity.at); + return found?.kind === "symbol" && found.symbol.dataType + ? { t: "record", home: entity.home, dataType: found.symbol.dataType, at: entity.at } + : 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, entity.at); + case "query": + return this.queryColumn(entity.query, name, entity.label); + case "unreadable": + return [{ kind: "object", object: entity.object, note: "Fuente no disponible" }]; + } + } + + /** Campo `name` de un valor de tipo `dataType` declarado en `home`. */ + 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, 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 }] : []; + } + const anchored = /^(.+)%TYPE$/i.exec(text); + if (anchored) { + const base = nameParts(anchored[1]); + 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, 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, at); + + const base = nameParts(text); + if (base.length < 1 || base.length > 2) return []; + let typeHome: Home | null = base.length === 1 ? home : null; + let typeAt = at; + 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; + 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; + 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) { + if (symbol.container === typeName && symbol.name === name && symbol.kind !== "parameter") { + members.push(located(typeHome, part, symbol)); + } + } + }); + // 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] + .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 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. */ + 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 []; + } +} 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..fbc3cb6 --- /dev/null +++ b/app/src/symbolSources.ts @@ -0,0 +1,87 @@ +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 { + 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); + } + }, + }; +} diff --git a/docs/ESTADO.md b/docs/ESTADO.md index a23a243..ef8a1bc 100644 --- a/docs/ESTADO.md +++ b/docs/ESTADO.md @@ -1,9 +1,13 @@ # 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 +- 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. + - 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). @@ -122,6 +126,12 @@ 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 | +| 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 new file mode 100644 index 0000000..9b861d2 --- /dev/null +++ b/docs/behavior/editor-inteligente.md @@ -0,0 +1,59 @@ +# 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". +- **Tipos objeto:** `variable.atributo` y `variable.metodo` muestran el atributo o el método del + 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 + 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 (`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. 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. + +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. Ctrl+clic donde no hay destino ubica el + 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. +- 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. diff --git a/docs/superpowers/plans/2026-11-27-openpl-aviso-actualizacion.md b/docs/superpowers/plans/2026-11-27-openpl-aviso-actualizacion.md new file mode 100644 index 0000000..7a3b776 --- /dev/null +++ b/docs/superpowers/plans/2026-11-27-openpl-aviso-actualizacion.md @@ -0,0 +1,58 @@ +# Aviso de actualización en la barra superior. Plan de implementación + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Un ícono en la barra superior que aparece con un salto cuando hay versión nueva y abre el diálogo de actualización. + +**Architecture:** `App.tsx` guarda la actualización encontrada en `pendingUpdate`, separada de `updateOffer` (diálogo abierto). Un componente `UpdateBadge` la muestra en `titlebar`. Sale en la rama `xwhiterr/menu-nuevo-se-cierra` (ya tiene el arreglo del menú Nuevo) como 1.0.0-beta.8. + +**Tech Stack:** React 19, TypeScript, Vitest + Testing Library, Phosphor. + +**Spec:** `docs/superpowers/specs/2026-11-27-openpl-editor-inteligente-design.md`, Parte 1. + +## Global Constraints + +- Textos cortos en español. Íconos Phosphor. Color con tokens del tema: el ícono usa `var(--accent)`, que ya tiene contraste ≥ 3 contra `--s0` medido en `themes.ts` (no hace falta token nuevo). +- Con `prefers-reduced-motion: reduce` no hay animación. +- TDD: test que falla primero (AGENTS.md regla 5). +- Sin chequeo periódico: solo al abrir y desde Ayuda > Buscar actualizaciones. + +## Review Focus + +- "Más tarde" debe cerrar el diálogo y dejar el ícono: hoy `onLater` hace `setUpdateOffer(null)` y no hay otro rastro. +- Buscar actualizaciones desde Ayuda sin versión nueva no debe borrar un ícono ya visible por un chequeo anterior que sí encontró una. +- Durante la instalación el ícono no abre un segundo diálogo. +- El ícono es un botón alcanzable con Tab y con nombre accesible que incluye la versión. +- La animación corre una sola vez al aparecer, no en cada render. + +--- + +### Task 1: Ícono de actualización + +**Files:** +- Create: `app/src/components/UpdateBadge.tsx` +- Modify: `app/src/App.tsx` (estado de actualización ~219, `checkUpdates` ~565, `titlebar` ~1127, `UpdateDialog` ~1544) +- Modify: `app/src/App.css` (clase `.update-badge` y `@keyframes update-bounce`) +- Test: `app/src/components/UpdateBadge.test.tsx`, `app/src/App.test.tsx` + +**Interfaces:** +- Produces: `UpdateBadge({ version: string; onOpen: () => void })`: `