All files / src/language completion-engine.ts

100% Statements 67/67
91.48% Branches 43/47
100% Functions 8/8
100% Lines 64/64

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394          16x 16x 16x 16x 16x 16x 16x 16x 16x 16x                             16x                                                                                                                                                                                                                                                                                                                                                                             16x                 16x         20x 20x     20x 480x 269x         20x 13x       20x 926x 586x     20x           16x 1x           16x           23x     23x 15x 15x 12x                     23x 5x 4x 4x                     5x 3x 3x                       23x 3x 3x 3x                     23x 10x 10x 5x                     23x 5x 5x 5x                   23x           16x                         20x 20x 12x     20x 20x 5x 15x 1x   20x             520x 231x      
import type { ContextSchema } from '../types/context-schema.js';
 
/**
 * Category of a completion suggestion.
 */
export enum CompletionKind {
  KEYWORD = 'keyword',
  OPERATOR = 'operator',
  VARIABLE = 'variable',
  PROPERTY = 'property',
  METHOD = 'method',
  FUNCTION = 'function',
  BEAN = 'bean',
  TYPE = 'type',
  SNIPPET = 'snippet',
}
 
export interface CompletionItem {
  label: string;
  kind: CompletionKind;
  detail?: string;
  documentation?: string;
  insertText: string;
  sortPriority: number;
}
 
/**
 * Static completions that are always available regardless of context.
 */
const STATIC_COMPLETIONS: CompletionItem[] = [
  // Keywords
  {
    label: 'null',
    kind: CompletionKind.KEYWORD,
    detail: 'Null literal',
    insertText: 'null',
    sortPriority: 50,
  },
  {
    label: 'true',
    kind: CompletionKind.KEYWORD,
    detail: 'Boolean true',
    insertText: 'true',
    sortPriority: 50,
  },
  {
    label: 'false',
    kind: CompletionKind.KEYWORD,
    detail: 'Boolean false',
    insertText: 'false',
    sortPriority: 50,
  },
  {
    label: 'new',
    kind: CompletionKind.KEYWORD,
    detail: 'Constructor call',
    insertText: 'new ',
    sortPriority: 50,
  },
  {
    label: 'T()',
    kind: CompletionKind.KEYWORD,
    detail: 'Type reference',
    insertText: 'T($1)',
    sortPriority: 50,
  },
 
  // Operators
  {
    label: 'and (&&)',
    kind: CompletionKind.OPERATOR,
    detail: 'Logical AND',
    insertText: 'and ',
    sortPriority: 40,
  },
  {
    label: 'or (||)',
    kind: CompletionKind.OPERATOR,
    detail: 'Logical OR',
    insertText: 'or ',
    sortPriority: 40,
  },
  {
    label: 'not (!)',
    kind: CompletionKind.OPERATOR,
    detail: 'Logical NOT',
    insertText: 'not ',
    sortPriority: 40,
  },
  {
    label: '==',
    kind: CompletionKind.OPERATOR,
    detail: 'Equal to',
    insertText: '== ',
    sortPriority: 40,
  },
  {
    label: '!=',
    kind: CompletionKind.OPERATOR,
    detail: 'Not equal to',
    insertText: '!= ',
    sortPriority: 40,
  },
  {
    label: '>',
    kind: CompletionKind.OPERATOR,
    detail: 'Greater than',
    insertText: '> ',
    sortPriority: 40,
  },
  {
    label: '<',
    kind: CompletionKind.OPERATOR,
    detail: 'Less than',
    insertText: '< ',
    sortPriority: 40,
  },
  {
    label: '>=',
    kind: CompletionKind.OPERATOR,
    detail: 'Greater than or equal',
    insertText: '>= ',
    sortPriority: 40,
  },
  {
    label: '<=',
    kind: CompletionKind.OPERATOR,
    detail: 'Less than or equal',
    insertText: '<= ',
    sortPriority: 40,
  },
  {
    label: 'matches',
    kind: CompletionKind.OPERATOR,
    detail: 'Regex match',
    insertText: "matches '$1'",
    sortPriority: 40,
  },
  {
    label: 'between',
    kind: CompletionKind.OPERATOR,
    detail: 'Range check',
    insertText: 'between {$1, $2}',
    sortPriority: 40,
  },
  {
    label: 'instanceof',
    kind: CompletionKind.OPERATOR,
    detail: 'Type check',
    insertText: 'instanceof ',
    sortPriority: 40,
  },
  {
    label: '?:',
    kind: CompletionKind.OPERATOR,
    detail: 'Elvis (null-safe default)',
    insertText: '?: $1',
    sortPriority: 40,
  },
 
  // Snippets
  {
    label: '?: ternary',
    kind: CompletionKind.SNIPPET,
    detail: 'Ternary conditional',
    insertText: '$1 ? $2 : $3',
    sortPriority: 20,
  },
  {
    label: '.?[]',
    kind: CompletionKind.SNIPPET,
    detail: 'Collection selection (all)',
    insertText: '.?[$1]',
    sortPriority: 20,
  },
  {
    label: '.![]',
    kind: CompletionKind.SNIPPET,
    detail: 'Collection projection',
    insertText: '.![$1]',
    sortPriority: 20,
  },
  {
    label: '.^[]',
    kind: CompletionKind.SNIPPET,
    detail: 'Collection selection (first)',
    insertText: '.^[$1]',
    sortPriority: 20,
  },
  {
    label: '.*[]',
    kind: CompletionKind.SNIPPET,
    detail: 'Collection selection (last)',
    insertText: '.*[$1]',
    sortPriority: 20,
  },
  {
    label: '#this',
    kind: CompletionKind.SNIPPET,
    detail: 'Current element reference',
    insertText: '#this',
    sortPriority: 30,
  },
];
 
/**
 * Completion engine for SpEL expressions.
 *
 * Provides context-aware auto-completion suggestions for editors.
 * When a ContextSchema is available, suggestions include variable names,
 * property names, method names, bean names, and type names.
 */
export namespace SpelCompletionEngine {
  /**
   * Get completion suggestions at a given cursor position.
   *
   * @param expression The current expression text
   * @param position Cursor position (character offset)
   * @param contextSchema Optional context schema for context-aware completions
   * @returns Sorted list of completion items
   */
  export function getCompletions(
    expression: string,
    position: number,
    contextSchema?: ContextSchema,
  ): CompletionItem[] {
    const prefix = getPrefixAt(expression, position);
    const items: CompletionItem[] = [];
 
    // Always include static completions filtered by prefix
    for (const item of STATIC_COMPLETIONS) {
      if (matchesPrefix(item.label, prefix)) {
        items.push(item);
      }
    }
 
    // Add context-aware completions if schema is available
    if (contextSchema) {
      items.push(...getContextCompletions(expression, position, contextSchema, prefix));
    }
 
    // Sort by priority (descending) then alphabetically
    items.sort((a, b) => {
      if (b.sortPriority !== a.sortPriority) return b.sortPriority - a.sortPriority;
      return a.label.localeCompare(b.label);
    });
 
    return items;
  }
 
  /**
   * Get static keyword and operator completions (no context needed).
   */
  export function getStaticCompletions(): CompletionItem[] {
    return [...STATIC_COMPLETIONS];
  }
 
  /**
   * Get context-aware completions based on a ContextSchema.
   */
  export function getContextCompletions(
    _expression: string,
    _position: number,
    contextSchema: ContextSchema,
    prefix = '',
  ): CompletionItem[] {
    const items: CompletionItem[] = [];
 
    // Variables from context schema
    for (const [name, schema] of Object.entries(contextSchema.variables)) {
      const label = '#' + name;
      if (matchesPrefix(label, prefix)) {
        items.push({
          label,
          kind: CompletionKind.VARIABLE,
          detail: schema.type ? `Variable (${schema.type})` : 'Variable',
          insertText: '#' + name,
          sortPriority: 100,
        });
      }
    }
 
    // Root object fields
    if (contextSchema.root) {
      for (const [name, schema] of Object.entries(contextSchema.root.fields)) {
        Eif (matchesPrefix(name, prefix)) {
          items.push({
            label: name,
            kind: CompletionKind.PROPERTY,
            detail: `Field (${schema.type})`,
            insertText: name,
            sortPriority: 90,
          });
        }
      }
 
      // Root object methods
      for (const [name, schema] of Object.entries(contextSchema.root.methods)) {
        Eif (matchesPrefix(name, prefix)) {
          items.push({
            label: name + '()',
            kind: CompletionKind.METHOD,
            detail: schema.returnType ? `→ ${schema.returnType}` : 'Method',
            insertText: name + '($1)',
            sortPriority: 85,
          });
        }
      }
    }
 
    // Registered functions
    for (const [name, schema] of Object.entries(contextSchema.functions)) {
      const label = '#' + name;
      Eif (matchesPrefix(label, prefix)) {
        items.push({
          label: label + '()',
          kind: CompletionKind.FUNCTION,
          detail: schema.returnType ? `→ ${schema.returnType}` : 'Function',
          insertText: '#' + name + '($1)',
          sortPriority: 95,
        });
      }
    }
 
    // Registered beans
    for (const [name, schema] of Object.entries(contextSchema.beans)) {
      const label = '@' + name;
      if (matchesPrefix(label, prefix)) {
        items.push({
          label,
          kind: CompletionKind.BEAN,
          detail: schema.type ? `Bean (${schema.type})` : 'Bean',
          insertText: '@' + name,
          sortPriority: 90,
        });
      }
    }
 
    // Registered types
    for (const [name, schema] of Object.entries(contextSchema.types)) {
      const label = 'T(' + name + ')';
      Eif (matchesPrefix(label, prefix)) {
        items.push({
          label,
          kind: CompletionKind.TYPE,
          detail: schema.className ? `Class: ${schema.className}` : 'Type',
          insertText: 'T(' + name + ')',
          sortPriority: 85,
        });
      }
    }
 
    return items;
  }
 
  // ===== Private helpers =====
 
  /** The characters a completable prefix is made of: `\w` plus the `.` of a property path. */
  const NAME_CHARACTER = /[\w.]/;
 
  /**
   * Extract the word at the cursor position as the completion prefix.
   *
   * Scanned backwards rather than matched with `/(#|@|T\()?[\w.]*$/`. That pattern is quadratic
   * when the text before the cursor ends in a long run of name characters that the end anchor
   * then rejects: the engine retries the quantified class from every offset, which measured
   * 615 ms for 32 000 characters, and this receives everything the caller passes as the
   * expression. Boundary is equivalent — the anchor makes the leftmost match the longest run
   * ending at the cursor — and the loop visits each character once.
   */
  function getPrefixAt(expression: string, position: number): string {
    let start = position;
    while (start > 0 && NAME_CHARACTER.test(expression.charAt(start - 1))) {
      start--;
    }
    // `#name`, `@bean` and `T(Type` all carry their introducer inside the prefix.
    const introducer = expression.charAt(start - 1);
    if (introducer === '#' || introducer === '@') {
      start--;
    } else if (introducer === '(' && expression.charAt(start - 2) === 'T') {
      start -= 2;
    }
    return expression.slice(start, position);
  }
 
  /**
   * Check if a label matches the current prefix (case-insensitive).
   */
  function matchesPrefix(label: string, prefix: string): boolean {
    if (!prefix) return true;
    return label.toLowerCase().startsWith(prefix.toLowerCase());
  }
}