All files / src/syntax-validation syntax-validation.service.ts

61.03% Statements 47/77
25% Branches 4/16
77.77% Functions 7/9
60.81% Lines 45/74

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 21411x 11x 11x 11x       11x 20x     20x     20x                                 20x   20x 20x         20x 20x 20x                                             26x   26x 16x     16x     10x 10x 10x 10x 10x                                                             10x       10x 10x       10x 10x   10x 10x 10x               10x       10x                                                                                                         3x   3x 1x     2x 2x   2x 3x 3x 3x     2x             16x 16x      
import { Injectable, Logger } from '@nestjs/common';
import * as path from 'path';
import { existsSync } from 'fs';
import { Parser, Language } from 'web-tree-sitter';
import { SyntaxValidationError, SyntaxError } from './dto/syntax-error.dto';
 
@Injectable()
export class SyntaxValidationService {
  private readonly logger = new Logger(SyntaxValidationService.name);
 
  // Cache parsers by file extension to avoid re-initializing
  private parserCache = new Map<string, Parser>();
 
  // Mapping file extensions to their Tree-sitter grammar WASM files.
  private readonly grammarMap: Record<string, string> = {
    '.js': 'tree-sitter-javascript.wasm',
    '.jsx': 'tree-sitter-javascript.wasm',
    '.ts': 'tree-sitter-typescript.wasm',
    '.tsx': 'tree-sitter-tsx.wasm',
    '.json': 'tree-sitter-json.wasm',
    '.html': 'tree-sitter-html.wasm',
    '.css': 'tree-sitter-css.wasm',
    '.py': 'tree-sitter-python.wasm',
    '.rs': 'tree-sitter-rust.wasm',
    '.toml': 'tree-sitter-toml.wasm',
    '.yaml': 'tree-sitter-yaml.wasm',
    '.yml': 'tree-sitter-yaml.wasm',
    '.sh': 'tree-sitter-bash.wasm',
  };
 
  // Resolve grammar directory path (same logic as PatchHandler)
  private readonly grammarDir = (() => {
    // Path for production build (dist folder)
    const prodPath = path.resolve(__dirname, '../../bin/grammar/');
    Iif (existsSync(prodPath)) {
      return prodPath;
    }
 
    // Fallback path for development (src folder)
    const devPath = path.resolve(__dirname, '../bin/grammar/');
    if (existsSync(devPath)) {
      return devPath;
    }
 
    // If neither is found, log a warning and default to prod path.
    // Logger is not available here, so using console.
    console.warn(
      `[SyntaxValidationService] Grammar directory not found. Looked for ${prodPath} and ${devPath}. Syntax validation may not function correctly.`,
    );
    return prodPath;
  })();
 
  /**
   * Validates the syntax of file content.
   * Returns null if syntax is valid, or a SyntaxValidationError if errors are found.
   *
   * @param filePath - The file path (for error reporting)
   * @param content - The file content to validate
   * @returns SyntaxValidationError | null
   */
  async validate(
    filePath: string,
    content: string,
  ): Promise<SyntaxValidationError | null> {
    const ext = path.extname(filePath).toLowerCase();
 
    if (!this.grammarMap[ext]) {
      this.logger.debug(
        `No grammar available for extension "${ext}". Skipping syntax validation.`,
      );
      return null;
    }
 
    try {
      const parser = await this.getParser(ext);
      if (!parser) {
        this.logger.warn(`Could not load parser for extension "${ext}".`);
        return null;
      }
 
      // Parse the content
      const tree = parser.parse(content);
 
      // Check for syntax errors in the parse tree
      Iif (tree.rootNode.hasError) {
        const errors = this.collectSyntaxErrors(tree, content);
        return {
          filePath,
          errors,
        };
      }
 
      // No syntax errors found
      return null;
    } catch (error) {
      this.logger.error(
        `Error during syntax validation for ${filePath}: ${error.message}`,
        error.stack,
      );
      // Don't block edits if validation fails; just log the error
      return null;
    }
  }
 
  /**
   * Gets or creates a cached parser for the given file extension.
   */
  private async getParser(extension: string): Promise<Parser | null> {
    Iif (this.parserCache.has(extension)) {
      return this.parserCache.get(extension)!;
    }
 
    const grammarFile = this.grammarMap[extension];
    Iif (!grammarFile) {
      return null;
    }
 
    try {
      const grammarPath = path.join(this.grammarDir, grammarFile);
 
      await Parser.init();
      const parser = new Parser();
      const language = await Language.load(grammarPath);
      parser.setLanguage(language);
 
      this.parserCache.set(extension, parser);
      this.logger.log(`Loaded Tree-sitter parser for "${extension}"`);
 
      return parser;
    } catch (error) {
      this.logger.error(
        `Failed to load grammar for "${extension}": ${error.message}`,
        error.stack,
      );
      return null;
    }
  }
 
  /**
   * Collects syntax errors from a Tree-sitter parse tree.
   * Traverses the tree and collects all nodes that have errors.
   */
  private collectSyntaxErrors(
    tree: ReturnType<Parser['parse']>,
    content: string,
  ): SyntaxError[] {
    const errors: SyntaxError[] = [];
    const lines = content.split('\n');
 
    /**
     * Recursively traverse the tree to find error nodes.
     */
    function findErrorNodes(node: any) {
      // Check if this node has an error
      Iif (node.isError || node.isMissing) {
        const line = node.startPosition.row;
        const col = node.startPosition.column;
        const codeLine = lines[line] || '';
 
        errors.push({
          line: line + 1, // Convert to 1-based for display
          column: col + 1, // Convert to 1-based for display
          message: node.isError
            ? 'Syntax error detected at this location.'
            : 'Missing syntax element at this location.',
          codeSnippet: codeLine.trim(),
        });
      }
 
      // Recursively check all children
      for (let i = 0; i < node.childCount; i++) {
        const child = node.child(i);
        Iif (child) {
          findErrorNodes(child);
        }
      }
    }
 
    findErrorNodes(tree.rootNode);
    return errors;
  }
 
  /**
   * Formats syntax errors for display to the AI.
   * Returns formatted error details without correction hints (tool-specific corrections are added by handlers).
   */
  formatErrors(validationError: SyntaxValidationError): string {
    const { filePath, errors } = validationError;
 
    if (errors.length === 0) {
      return '';
    }
 
    let message = `Syntax corruption detected in "${filePath}":\n\n`;
    message += `Found ${errors.length} syntax error(s):\n\n`;
 
    errors.forEach((err, index) => {
      message += `${index + 1}. Line ${err.line}, Column ${err.column}\n`;
      message += `   Code: ${err.codeSnippet}\n`;
      message += `   Issue: ${err.message}\n\n`;
    });
 
    return message;
  }
 
  /**
   * Clears the parser cache. Useful for testing or when grammars are updated.
   */
  clearCache(): void {
    this.parserCache.clear();
    this.logger.log('Syntax validation parser cache cleared.');
  }
}