All files / src/services/parsing treeSitterManager.js

0% Statements 0/83
0% Branches 0/24
0% Functions 0/8
0% Lines 0/83

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
/**
 * TreeSitterManager - Loads and manages tree-sitter language grammars
 *
 * This module is responsible for loading the specified tree-sitter language
 * grammars (JavaScript, Python, TypeScript) from their NPM package locations
 * and providing access to initialized parsers for these languages.
 */
 
import pkg from "tree-sitter";
const { Parser } = pkg;
import path from "path";
import fs from "fs";
import logger from "../../utils/logger.js";
 
/**
 * TreeSitterManager class
 * Responsible for loading and managing tree-sitter language grammars
 */
export class TreeSitterManager {
  /**
   * Creates a new TreeSitterManager instance
   */
  constructor() {
    this.loadedGrammars = new Map();
    this.initialized = false;
  }
 
  /**
   * Initialize tree-sitter language grammars
   * @param {string[]} configuredLanguages - Array of language names to load (e.g., ['javascript', 'python', 'typescript'])
   * @returns {Promise<boolean>} - True if all configured languages were loaded successfully
   */
  async initializeGrammars(configuredLanguages) {
    if (this.initialized) {
      logger.warn(
        "TreeSitterManager.initializeGrammars called, but grammars are already initialized"
      );
      return true;
    }
 
    logger.info(
      `Initializing Tree-sitter grammars for: ${configuredLanguages.join(", ")}`
    );
 
    let allSuccessful = true;
 
    // Process each configured language
    for (const language of configuredLanguages) {
      try {
        // Handle special cases for languages with native bindings
        if (language === "typescript") {
          await this.loadTypescriptGrammar();
          continue;
        } else if (language === "python") {
          await this.loadPythonGrammar();
          continue;
        } else if (language === "javascript") {
          await this.loadJavaScriptGrammar();
          continue;
        }
 
        // If we get here, we don't have a specific loader for this language
        logger.warn(`No specific loader available for language: ${language}`);
        allSuccessful = false;
      } catch (error) {
        logger.error(
          `Failed to load grammar for ${language}: ${error.message}`,
          {
            error: error.stack,
          }
        );
        allSuccessful = false;
      }
    }
 
    // Set initialized flag
    this.initialized = this.loadedGrammars.size > 0;
 
    if (!this.initialized) {
      logger.error("Failed to initialize any Tree-sitter grammars");
      return false;
    }
 
    logger.info(
      `Successfully initialized ${this.loadedGrammars.size} Tree-sitter grammars`
    );
    return allSuccessful;
  }
 
  /**
   * Load the JavaScript grammar using WASM
   * @private
   */
  async loadJavaScriptGrammar() {
    try {
      logger.info("Loading JavaScript grammar using require");
 
      // Use CommonJS require for loading the JavaScript grammar
      const { createRequire } = await import("module");
      const require = createRequire(import.meta.url);
 
      // Load the JavaScript grammar
      const jsLanguage = require("tree-sitter-javascript");
 
      if (!jsLanguage) {
        throw new Error("Failed to load JavaScript grammar module");
      }
 
      this.loadedGrammars.set("javascript", jsLanguage);
      logger.info("Successfully loaded grammar for javascript");
    } catch (error) {
      logger.error(`Failed to load JavaScript grammar: ${error.message}`, {
        error: error.stack,
      });
      throw error;
    }
  }
 
  /**
   * Load the TypeScript grammar using Node.js bindings
   * @private
   */
  async loadTypescriptGrammar() {
    try {
      logger.info("Loading TypeScript grammars using Node.js bindings");
 
      // Use Node.js require for native modules
      // Since we're in ESM context, we need to use createRequire
      const { createRequire } = await import("module");
      const require = createRequire(import.meta.url);
 
      // Load TypeScript module
      const tsModule = require("tree-sitter-typescript");
 
      if (!tsModule) {
        throw new Error("Failed to load TypeScript grammar module");
      }
 
      // TypeScript grammar
      if (tsModule.typescript) {
        this.loadedGrammars.set("typescript", tsModule.typescript);
        logger.info("Successfully loaded grammar for typescript");
      } else {
        logger.error("TypeScript grammar not found in the module");
      }
 
      // TSX grammar
      if (tsModule.tsx) {
        this.loadedGrammars.set("tsx", tsModule.tsx);
        logger.info("Successfully loaded grammar for tsx");
      } else {
        logger.error("TSX grammar not found in the module");
      }
    } catch (error) {
      logger.error(`Failed to load TypeScript grammars: ${error.message}`, {
        error: error.stack,
      });
      throw error;
    }
  }
 
  /**
   * Load the Python grammar using Node.js bindings
   * @private
   */
  async loadPythonGrammar() {
    try {
      logger.info("Loading Python grammar using Node.js bindings");
 
      // Use Node.js require for native modules
      // Since we're in ESM context, we need to use createRequire
      const { createRequire } = await import("module");
      const require = createRequire(import.meta.url);
 
      // Load Python module
      const pythonModule = require("tree-sitter-python");
 
      if (!pythonModule) {
        throw new Error("Failed to load Python grammar module");
      }
 
      this.loadedGrammars.set("python", pythonModule);
      logger.info("Successfully loaded grammar for python");
    } catch (error) {
      logger.error(`Failed to load Python grammar: ${error.message}`, {
        error: error.stack,
      });
      throw error;
    }
  }
 
  /**
   * Get a parser for the specified language
   * @param {string} languageName - Name of the language (e.g., 'javascript', 'python', 'typescript', 'tsx')
   * @returns {Parser|null} - Initialized parser for the language or null if not available
   */
  getParserForLanguage(languageName) {
    if (!this.initialized) {
      logger.warn(
        "TreeSitterManager.getParserForLanguage called before initialization"
      );
      return null;
    }
 
    const grammar = this.loadedGrammars.get(languageName);
 
    if (!grammar) {
      logger.warn(`No grammar loaded for language: ${languageName}`);
      return null;
    }
 
    try {
      // Create a new parser instance
      const parser = new pkg();
 
      // Set the language for the parser
      parser.setLanguage(grammar);
 
      return parser;
    } catch (error) {
      logger.error(
        `Failed to create parser for ${languageName}: ${error.message}`,
        {
          error: error.stack,
        }
      );
      return null;
    }
  }
 
  /**
   * Check if a language grammar is loaded
   * @param {string} languageName - Name of the language
   * @returns {boolean} - True if the language grammar is loaded
   */
  hasLanguage(languageName) {
    return this.loadedGrammars.has(languageName);
  }
 
  /**
   * Get list of loaded language grammars
   * @returns {string[]} - Array of language names that are loaded
   */
  getLoadedLanguages() {
    return Array.from(this.loadedGrammars.keys());
  }
}
 
export default TreeSitterManager;