(["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 })`: `