File size: 13,907 Bytes
82cdb59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
// The formula assist module, wave 52 (W52-T05, contract C3, instructions 5 and 7).
//
// PURE functions only. No React, no DOM. That is what makes this module gateable without a
// browser (`verify_formula_engine.py`'s new leg compiles it and drives it under plain `node`), and
// it is what leaves the KEY HANDLING decisions -- what Tab does, what Enter does, when a click
// commits a point-mode proposal -- to the UI layer T06 builds next. This module answers "what is
// the list right now" and "what does this text mean right now"; it never mutates anything and it
// never remembers anything between calls.
//
// Rules implemented here are from `AutoWiki/waves/wave52/proto/excel-behaviour-spec.md`, Part
// A: FA-1..FA-26 (the suggestion dropdown), ST-1..ST-16 (the ScreenTip), CR-1..CR-10 (coloured
// references). Point mode (PM-1..PM-18) is NOT built here -- this ticket ships no UI, and PM's
// rules describe grid interaction (arrow keys, click-drag, scrolling to a proposed cell) that has
// no meaning without one. T06 owns PM.

import { FUNCTIONS, findFunction, type FunctionSpec } from "./functionCatalog";
import { parseRef, type CellRef } from "./a1";

// ── FA-19/FA-18/FA-22: which keys accept a suggestion. Enter is deliberately NOT in this list. ──
//
// β›”β›” THE CRITICAL NEGATIVE RULE (FA-19). Every implementer's instinct from VS Code, IntelliJ and
// every browser autocomplete is that Enter accepts a highlighted item. In Excel it does not: Enter
// commits the LITERAL text typed, and Tab is the only key that accepts (FA-18). Double-click also
// accepts (FA-22), but a mouse click is not a "key" -- the UI layer calls the accept path directly
// on double-click, it never asks this list. `suggest()` itself never decides what a key does; it
// only returns the ranked list. This constant is what the CALLER consults, and it is what the
// gate's negative control mutates to prove a caller that wired Enter here would be caught.
export const ACCEPT_KEYS: readonly string[] = ["Tab"];

/** True only for a key that accepts a highlighted suggestion. FA-18/FA-19/FA-22. */
export function acceptsSuggestion(key: string): boolean {
  return ACCEPT_KEYS.includes(key);
}

// ── Part A section 1: the suggestion dropdown ───────────────────────────────────────────────────

export type SuggestKind = "function";

export interface SuggestItem {
  kind: SuggestKind;
  name: string;
  signature: string;
  summary: string;
}

/** The identifier run a token match is built from. Letters, digits, underscore, dot. */
const IDENT_TAIL = /[A-Za-z_][A-Za-z0-9_.]*$/;

/**
 * FA-1..FA-10: the ranked suggestion list for the token under `caret` in `text`.
 *
 * Returns `[]` (closes the dropdown, per FA-2/FA-24/FA-25) whenever:
 * - `text` does not start with `=` (not a formula at all),
 * - there is no identifier character run immediately before `caret` (bare `=`, right after `(`,
 *   `,`, an operator, or inside a string -- the caller passes the caret position, this function
 *   does not know about quoting, so a caller inside a string literal should not call this at all;
 *   T06 owns that decision),
 * - the token matches nothing in the catalog (prefix, case insensitive -- FA-5/FA-6).
 *
 * Ordering (FA-8): exact case-insensitive match on the whole token first, then every remaining
 * match A-Z ascending, case insensitive. No fuzzy match, no frequency ranking (FA-5, FA-8). The
 * first item in a non-empty result is always the one to preselect (FA-10) -- there is no separate
 * "selected index" concept here because there is nothing to select from an empty list.
 */
export function suggest(text: string, caret: number): SuggestItem[] {
  const src = String(text || "");
  if (!src.startsWith("=")) return [];
  const upto = src.slice(0, Math.max(0, Math.min(caret, src.length)));
  const m = IDENT_TAIL.exec(upto);
  if (!m || m[0].length < 1) return [];
  const token = m[0].toLowerCase();

  const matches = FUNCTIONS.filter((f) => f.name.toLowerCase().startsWith(token));
  const exact = matches.filter((f) => f.name.toLowerCase() === token);
  const exactNames = new Set(exact.map((f) => f.name));
  const rest = matches
    .filter((f) => !exactNames.has(f.name))
    .sort((a, b) => a.name.localeCompare(b.name, "en", { sensitivity: "base" }));

  return [...exact, ...rest].map((f) => toSuggestItem(f));
}

function toSuggestItem(f: FunctionSpec): SuggestItem {
  return { kind: "function", name: f.name, signature: f.signature, summary: f.summary };
}

/**
 * FA-20/FA-21: what accepting a suggestion inserts. A function gets its name (already upper
 * case, FA-7) and the opening parenthesis, caret placed after it. This is pure text -- the caller
 * still owns splicing it into the buffer and moving the real caret.
 */
export function acceptedText(item: SuggestItem): string {
  return `${item.name}(`;
}

// ── Part A section 2: the ScreenTip (signature tooltip) ─────────────────────────────────────────

export interface ActiveArg {
  functionName: string;
  /** 0-based count of top-level commas before `caret`, inside that function's own parens. ST-5. */
  argIndex: number;
  /** The argument name to render bold, or null when there is nothing to bold (ST-6). */
  boldArgName: string | null;
}

/**
 * ST-1..ST-8: which function's signature to show, and which argument is bold, for the caret
 * position in `text`. Returns `null` when the caret is not inside any open call's parentheses
 * (ST-15 -- that is the caller's cue to hide the tooltip).
 *
 * ST-5, the exact rule: count TOP-LEVEL commas between the innermost enclosing function's own `(`
 * and the caret. A comma inside a nested call's parens, inside a quoted string, or inside a
 * bracketed `[...]` table specifier does not count -- each of those is tracked separately so a
 * nested call's commas are attributed to ITS OWN frame, never to the frame around it.
 *
 * ST-6: once the caret passes the last named argument, a signature ending in `...` keeps its
 * repeating argument bold; one that does not keeps NO argument bold (the tooltip itself stays up,
 * per ST-6 -- this function still returns a result, just with `boldArgName: null`).
 */
export function activeArg(text: string, caret: number): ActiveArg | null {
  const src = String(text || "");
  if (!src.startsWith("=")) return null;
  const end = Math.max(0, Math.min(caret, src.length));

  interface Frame {
    fnName: string;
    commaCount: number;
  }
  const stack: Frame[] = [];
  let quote: string | null = null;
  let bracketDepth = 0;
  let i = 0;

  while (i < end) {
    const c = src[i];
    if (quote) {
      if (c === quote) quote = null;
      i += 1;
      continue;
    }
    if (c === '"' || c === "'") {
      quote = c;
      i += 1;
      continue;
    }
    if (c === "[") {
      bracketDepth += 1;
      i += 1;
      continue;
    }
    if (c === "]") {
      bracketDepth = Math.max(0, bracketDepth - 1);
      i += 1;
      continue;
    }
    if (c === "(") {
      const preceding = IDENT_TAIL.exec(src.slice(0, i));
      stack.push({ fnName: preceding ? preceding[0].toUpperCase() : "", commaCount: 0 });
      i += 1;
      continue;
    }
    if (c === ")") {
      stack.pop();
      i += 1;
      continue;
    }
    if (c === "," && bracketDepth === 0 && stack.length > 0) {
      stack[stack.length - 1].commaCount += 1;
      i += 1;
      continue;
    }
    i += 1;
  }

  if (stack.length === 0) return null;
  const top = stack[stack.length - 1];
  const spec = findFunction(top.fnName);
  const boldArgName = spec ? boldArgumentName(spec, top.commaCount) : null;
  return { functionName: top.fnName, argIndex: top.commaCount, boldArgName };
}

/** ST-6's capping rule, isolated so it is one small pure function instead of inline branching. */
function boldArgumentName(spec: FunctionSpec, argIndex: number): string | null {
  const names = spec.argNames;
  if (names.length === 0) return null;
  if (argIndex < names.length) return names[argIndex];
  const repeats = spec.signature.trimEnd().endsWith("...)");
  return repeats ? names[names.length - 1] : null;
}

// ── Part A section 4: coloured references ───────────────────────────────────────────────────────

export interface CellReference {
  /** The reference exactly as it appears in the formula text, e.g. "A1" or "B2:B4". */
  text: string;
  isRange: boolean;
  start: CellRef;
  end: CellRef;
  /** 0-5, a slot into the fixed six colour rotation in refColors.ts (CR-4). */
  colorIndex: number;
  /** W57-T01: a whole column or row. Endpoints carry only its axis position; a painter
   * must bound the other axis against the sheet it is painting on. */
  band?: "column" | "row";
}

/** One reference candidate, matched but not yet range-joined. */
const REF_TOKEN =
  "(?:(?:'([^']{1,64})'|([A-Za-z_][A-Za-z0-9_]{0,63}))!)?(\\$?)([A-Za-z]{1,3})(\\$?)([1-9][0-9]{0,6})";

// W57-T01: only identical axes form a band; matchBandAt checks equality after matching.
// The trailing boundary prevents A:A1 or 1:10 from being accepted as a shorter band.
const BAND_TOKEN =
  "(?:(?:'([^']{1,64})'|([A-Za-z_][A-Za-z0-9_]{0,63}))!)?(\\$?)"
  + "([A-Za-z]{1,3}|[1-9][0-9]{0,6}):(\\$?)([A-Za-z]{1,3}|[1-9][0-9]{0,6})"
  + "(?![A-Za-z0-9_$!])";

/**
 * CR-1..CR-5, CR-9: every distinct cell or range reference in `text`, in order of FIRST
 * appearance, each carrying a colour slot from the fixed six colour rotation (CR-4) -- the same
 * slot for every later occurrence of an identical reference (CR-3), cycling after the sixth.
 *
 * A range (`B2:B4`) is ONE reference distinct from either endpoint alone (CR-3). Quoted text is
 * never scanned (`="A1 is nice"` yields no references) and a token immediately followed by `(` is
 * a function name, not a reference (the same collision `a1.ts::rewriteRefs` guards, e.g. `LOG10(`).
 *
 * β›” THIS DOES NOT REUSE `a1.ts::rewriteRefs`'s scanner because that scanner's job is different:
 * it REWRITES text byte for byte and treats `B4:B8` as two independent references either side of a
 * literal `:`. This function instead needs to RECOGNISE a range as one unit for colouring (CR-3),
 * so it does its own scan -- but it reuses `a1.ts::parseRef` to turn a matched substring into a
 * `CellRef` rather than re-deriving the `$`/sheet-name grammar a second time.
 */
export function refsIn(text: string): CellReference[] {
  const src = String(text || "");
  const scan = new RegExp(REF_TOKEN, "gy");
  const bandScan = new RegExp(BAND_TOKEN, "gy");
  const out: CellReference[] = [];
  const slotByKey = new Map<string, number>();
  let nextSlot = 0;
  let quote: string | null = null;
  let i = 0;

  const matchAt = (pos: number): { token: string; ref: CellRef } | null => {
    scan.lastIndex = pos;
    const m = scan.exec(src);
    if (!m || m.index !== pos) return null;
    const after = src.slice(pos + m[0].length);
    if (/^\s*\(/.test(after)) return null; // a function name, e.g. LOG10(
    const ref = parseRef(m[0]);
    if (!ref) return null;
    return { token: m[0], ref };
  };

  const matchBandAt = (pos: number): {
    token: string; ref: CellRef; end: CellRef; band: "column" | "row";
  } | null => {
    bandScan.lastIndex = pos;
    const m = bandScan.exec(src);
    if (!m || m.index !== pos) return null;
    if (m[4].toUpperCase() !== m[6].toUpperCase()) return null;
    const after = src.slice(pos + m[0].length);
    if (/^\s*\(/.test(after)) return null;
    const isColumn = /^[A-Za-z]/.test(m[4]);
    // parseRef stays cell-only: widening it would also change fill and structural rewrites.
    const ref: CellRef = {
      sheet: m[1] || m[2] || "",
      colAbs: isColumn && m[3] === "$",
      col: isColumn ? m[4].toUpperCase() : "A",
      rowAbs: !isColumn && m[3] === "$",
      row: isColumn ? 1 : Number(m[4]),
    };
    return {
      token: m[0],
      ref,
      end: {
        ...ref,
        colAbs: isColumn && m[5] === "$",
        rowAbs: !isColumn && m[5] === "$",
      },
      band: isColumn ? "column" : "row",
    };
  };

  while (i < src.length) {
    const c = src[i];
    if (quote) {
      if (c === quote) quote = null;
      i += 1;
      continue;
    }
    if (c === '"') {
      quote = c;
      i += 1;
      continue;
    }
    if (c === "'") {
      const close = src.indexOf("'", i + 1);
      const isSheetName = close > i && src[close + 1] === "!";
      if (!isSheetName) {
        quote = c;
        i += 1;
        continue;
      }
    }
    const prev = i ? src[i - 1] : "";
    const boundary = !/[A-Za-z0-9_$]/.test(prev);
    if (boundary && /[A-Za-z0-9$']/.test(c)) {
      const band = matchBandAt(i);
      const first = matchAt(i) ?? band;
      if (first) {
        let fullText = first.token;
        let end = band?.end ?? first.ref;
        let cursor = i + first.token.length;
        if (!band && src[cursor] === ":") {
          const second = matchAt(cursor + 1);
          if (second) {
            fullText = `${first.token}:${second.token}`;
            end = second.ref;
            cursor = cursor + 1 + second.token.length;
          }
        }
        const key = fullText.toUpperCase();
        let slot = slotByKey.get(key);
        if (slot === undefined) {
          slot = nextSlot % 6;
          nextSlot += 1;
          slotByKey.set(key, slot);
        }
        out.push({
          text: fullText,
          isRange: fullText.includes(":"),
          start: first.ref,
          end,
          colorIndex: slot,
          ...(band ? { band: band.band } : {}),
        });
        i = cursor;
        continue;
      }
    }
    i += 1;
  }
  return out;
}