All files / src/language diagnostic-engine.ts

100% Statements 93/93
100% Branches 55/55
100% Functions 9/9
100% Lines 91/91

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                16x 16x 16x 16x       16x 16x 16x 16x 16x                                                                 16x         16x 9x 9x 9x 9x   5x 4x                     1x                               16x 17x     17x 17x 17x 3x                     17x   17x   7x 7x 7x                         17x 2x                     17x 1x                   17x           16x 34x 34x 34x   34x 35x     11x 9x 9x 4x 4x                   11x       6x 4x 4x 2x 2x                   6x       9x 9x 5x 5x                 9x     4x 4x 2x 2x                 4x     4x 4x 2x 2x                 4x     1x       34x           16x 5x     5x     5x   2x     2x       3x     3x 2x     3x           16x       7x   7x 7x 7x 7x     7x   7x   4x 3x                 1x                 4x        
import type { SpelNodeImpl } from '../ast/spel-node.js';
import type { SpelReference } from './reference-extractor.js';
import type { ContextSchema } from '../types/context-schema.js';
import { SpelExpressionParser } from '../spel-expression-parser.js';
import { SpelParseException } from '../error/spel-parse-exception.js';
import { SpelReferenceExtractor, SpelReferenceKind } from './reference-extractor.js';
 
/** Severity level for diagnostics */
export enum DiagnosticSeverity {
  ERROR = 'error',
  WARNING = 'warning',
  INFO = 'info',
}
 
/** Source category for diagnostics */
export enum DiagnosticSource {
  SYNTAX = 'syntax',
  SEMANTIC = 'semantic',
  CONTEXT = 'context',
  TYPE = 'type',
}
 
export interface SpelDiagnostic {
  severity: DiagnosticSeverity;
  message: string;
  from: number;
  to: number;
  code: string;
  source: DiagnosticSource;
}
 
export interface ContextValidationResult {
  valid: boolean;
  diagnostics: SpelDiagnostic[];
  missingReferences: SpelReference[];
  typeMismatches: {
    referenceName: string;
    expectedType: string;
    actualUsage: string;
    position: number;
  }[];
}
 
/**
 * Multi-stage diagnostic engine for SpEL expressions.
 *
 * Pipeline:
 *   1. Syntax check — uses the parser for exact error detection
 *   2. Semantic check — detects self-comparisons, double-negation, tautologies
 *   3. Context check — validates references against a ContextSchema
 *   4. Type check — detects operand type mismatches
 */
export namespace SpelDiagnosticEngine {
  /**
   * Check syntax validity of an expression.
   * Returns diagnostics from the SpEL parser.
   */
  export function checkSyntax(expression: string): SpelDiagnostic[] {
    try {
      const parser = new SpelExpressionParser();
      parser.parseExpression(expression);
      return []; // Valid
    } catch (e) {
      if (e instanceof SpelParseException) {
        return [
          {
            severity: DiagnosticSeverity.ERROR,
            message: e.message,
            from: e.position,
            to: expression.length,
            code: 'SYNTAX-' + (String(e.messageCode) || 'UNKNOWN'),
            source: DiagnosticSource.SYNTAX,
          },
        ];
      }
      return [
        {
          severity: DiagnosticSeverity.ERROR,
          message: (e as Error).message,
          from: 0,
          to: expression.length,
          code: 'SYNTAX-UNKNOWN',
          source: DiagnosticSource.SYNTAX,
        },
      ];
    }
  }
 
  /**
   * Check for semantic issues (self-comparison, double negation, tautologies).
   */
  export function checkSemantics(expression: string): SpelDiagnostic[] {
    const diagnostics: SpelDiagnostic[] = [];
 
    // Double negation: !!expr or not not expr
    const doubleNegPattern = /!\s*!|not\s+not/i;
    const dnMatch = doubleNegPattern.exec(expression);
    if (dnMatch) {
      diagnostics.push({
        severity: DiagnosticSeverity.WARNING,
        message: 'Double negation detected — consider simplifying',
        from: dnMatch.index,
        to: dnMatch.index + dnMatch[0].length,
        code: 'SEMANTIC-DOUBLE_NEGATION',
        source: DiagnosticSource.SEMANTIC,
      });
    }
 
    // Self-comparison: detect patterns like #x == #x or #x != #x
    const selfCompPattern = /#(\w+)\s*(==|!=|eq|ne)\s*#\1/g;
    let scMatch: RegExpExecArray | null;
    while ((scMatch = selfCompPattern.exec(expression)) !== null) {
      // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- regex guarantees group 2 exists when matched
      const op = scMatch[2]!;
      const isNeq = op === '!=' || op.toLowerCase() === 'ne';
      diagnostics.push({
        severity: DiagnosticSeverity.WARNING,
        message: isNeq
          ? `Self-comparison '#${scMatch[1]} != #${scMatch[1]}' is always false`
          : `Self-comparison '#${scMatch[1]} == #${scMatch[1]}' is always true`,
        from: scMatch.index,
        to: scMatch.index + scMatch[0].length,
        code: 'SEMANTIC-SELF_COMPARISON',
        source: DiagnosticSource.SEMANTIC,
      });
    }
 
    // Always-true: true or ...
    if (/^true\s+or\b/i.test(expression)) {
      diagnostics.push({
        severity: DiagnosticSeverity.INFO,
        message: 'Expression starts with "true or ..." — left side is always true',
        from: 0,
        to: 8,
        code: 'SEMANTIC-TAUTOLOGY',
        source: DiagnosticSource.SEMANTIC,
      });
    }
 
    // Always-false: false and ...
    if (/^false\s+and\b/i.test(expression)) {
      diagnostics.push({
        severity: DiagnosticSeverity.INFO,
        message: 'Expression starts with "false and ..." — left side is always false',
        from: 0,
        to: 10,
        code: 'SEMANTIC-CONTRADICTION',
        source: DiagnosticSource.SEMANTIC,
      });
    }
 
    return diagnostics;
  }
 
  /**
   * Validate expression references against a ContextSchema.
   */
  export function checkContext(expression: string, contextSchema: ContextSchema): SpelDiagnostic[] {
    const refs = SpelReferenceExtractor.extract(expression);
    const diagnostics: SpelDiagnostic[] = [];
    const missingRefs: SpelReference[] = [];
 
    for (const ref of refs) {
      switch (ref.kind) {
        case SpelReferenceKind.VARIABLE: {
          // Check if variable exists in schema
          if (ref.name !== 'root' && ref.name !== 'this') {
            const hasVariable = ref.name in contextSchema.variables;
            if (!hasVariable) {
              missingRefs.push(ref);
              diagnostics.push({
                severity: DiagnosticSeverity.WARNING,
                message: `Variable '#${ref.name}' is not defined in context`,
                from: ref.startPos,
                to: ref.endPos,
                code: 'CONTEXT-UNDEFINED_VARIABLE',
                source: DiagnosticSource.CONTEXT,
              });
            }
          }
          break;
        }
        case SpelReferenceKind.ROOT_PROPERTY: {
          // Check if property exists on root object
          if (contextSchema.root) {
            const hasField = ref.name in contextSchema.root.fields;
            if (!hasField) {
              missingRefs.push(ref);
              diagnostics.push({
                severity: DiagnosticSeverity.WARNING,
                message: `Property '${ref.name}' not found on root object '${contextSchema.root.name}'`,
                from: ref.startPos,
                to: ref.endPos,
                code: 'CONTEXT-UNKNOWN_PROPERTY',
                source: DiagnosticSource.CONTEXT,
              });
            }
          }
          break;
        }
        case SpelReferenceKind.BEAN:
        case SpelReferenceKind.BEAN_FACTORY: {
          const hasBean = ref.name in contextSchema.beans;
          if (!hasBean) {
            missingRefs.push(ref);
            diagnostics.push({
              severity: DiagnosticSeverity.WARNING,
              message: `Bean '@${ref.name}' is not registered in context`,
              from: ref.startPos,
              to: ref.endPos,
              code: 'CONTEXT-UNDEFINED_BEAN',
              source: DiagnosticSource.CONTEXT,
            });
          }
          break;
        }
        case SpelReferenceKind.TYPE: {
          const hasType = ref.name in contextSchema.types;
          if (!hasType) {
            missingRefs.push(ref);
            diagnostics.push({
              severity: DiagnosticSeverity.WARNING,
              message: `Type 'T(${ref.name})' is not registered in context`,
              from: ref.startPos,
              to: ref.endPos,
              code: 'CONTEXT-UNDEFINED_TYPE',
              source: DiagnosticSource.CONTEXT,
            });
          }
          break;
        }
        case SpelReferenceKind.FUNCTION: {
          const hasFunc = ref.name in contextSchema.functions;
          if (!hasFunc) {
            missingRefs.push(ref);
            diagnostics.push({
              severity: DiagnosticSeverity.WARNING,
              message: `Function '#${ref.name}' is not registered in context`,
              from: ref.startPos,
              to: ref.endPos,
              code: 'CONTEXT-UNDEFINED_FUNCTION',
              source: DiagnosticSource.CONTEXT,
            });
          }
          break;
        }
        default:
          break;
      }
    }
 
    return diagnostics;
  }
 
  /**
   * Run all validation stages.
   */
  export function validate(expression: string, contextSchema?: ContextSchema): SpelDiagnostic[] {
    const diagnostics: SpelDiagnostic[] = [];
 
    // Stage 1: Syntax
    diagnostics.push(...checkSyntax(expression));
 
    // If syntax errors exist, skip further stages (expression can't be parsed)
    if (
      diagnostics.some(
        (d) => d.source === DiagnosticSource.SYNTAX && d.severity === DiagnosticSeverity.ERROR,
      )
    ) {
      return diagnostics;
    }
 
    // Stage 2: Semantic
    diagnostics.push(...checkSemantics(expression));
 
    // Stage 3: Context (only if schema provided)
    if (contextSchema) {
      diagnostics.push(...checkContext(expression, contextSchema));
    }
 
    return diagnostics;
  }
 
  /**
   * Parse an expression and return both AST and diagnostics.
   */
  export function parseWithDiagnostics(expression: string): {
    ast: SpelNodeImpl | null;
    diagnostics: SpelDiagnostic[];
  } {
    const diagnostics: SpelDiagnostic[] = [];
 
    try {
      const parser = new SpelExpressionParser();
      const expr = parser.parseExpression(expression);
      const ast = (expr as { getAST?: () => SpelNodeImpl }).getAST?.() ?? null;
 
      // Run semantic checks on valid expression
      diagnostics.push(...checkSemantics(expression));
 
      return { ast, diagnostics };
    } catch (e) {
      if (e instanceof SpelParseException) {
        diagnostics.push({
          severity: DiagnosticSeverity.ERROR,
          message: e.message,
          from: e.position,
          to: expression.length,
          code: 'SYNTAX-' + (String(e.messageCode) || 'UNKNOWN'),
          source: DiagnosticSource.SYNTAX,
        });
      } else {
        diagnostics.push({
          severity: DiagnosticSeverity.ERROR,
          message: (e as Error).message,
          from: 0,
          to: expression.length,
          code: 'SYNTAX-UNKNOWN',
          source: DiagnosticSource.SYNTAX,
        });
      }
      return { ast: null, diagnostics };
    }
  }
}