Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· openaiHugging Face Suzhen/CodeChat

i want to use ts-morph to traverse two sourcefiles, get the AST and compare each node to…

  1. User

    i want to use ts-morph to traverse two sourcefiles, get the AST and compare each node to see if the node name and node text are same with each other. can you give me the nodejs script?

  2. Assistant

    Sure! Here is a basic Node.js script to traverse two TypeScript source files using ts-morph, get the AST, and compare each node:

    const { Project } = require("ts-morph");
    
    // Create a new project instance
    const project = new Project();
    
    // Load the two source files into the project
    const sourceFile1 = project.addSourceFileAtPath("path/to/file1.ts");
    const sourceFile2 = project.addSourceFileAtPath("path/to/file2.ts");
    
    // Traverse the AST of both source files
    sourceFile1.forEachDescendant((node1, traversal) => {
      // Find the equivalent node in the second source file
      const node2 = sourceFile2.getDescendantAtStartWithWidth(node1.getStart(), node1.getWidth());
      
      // Compare the nodes
      if (node1.getKind() === node2.getKind() && node1.getText() === node2.getText()) {
        console.log(`Node ${node1.getKindName()} with text "${node1.getText()}" is the same in both files.`);
      }
    });
    
    

    This script loads two TypeScript files (file1.ts and file2.ts) into a Project instance and traverses their ASTs using forEachDescendant(). It compares each node in file1.ts to its equivalent node in file2.ts using getDescendantAtStartWithWidth(), and checks if their node kind and text are the same using getKind() and getText(). If they are the same, a message is printed to the console. You can customize this script to suit your specific needs.

  3. User

    as the order of definitions in two source files can not be guaranteed, can you modify your script to meet the requirement?

  4. Assistant

    Sure! Here is a modified version of the script that compares every node in one source file with every node in the other source file, regardless of their order of definition:

    const { Project } = require("ts-morph");
    
    // Create a new project instance
    const project = new Project();
    
    // Load the two source files into the project
    const sourceFile1 = project.addSourceFileAtPath("path/to/file1.ts");
    const sourceFile2 = project.addSourceFileAtPath("path/to/file2.ts");
    
    // Array to hold nodes from file 2
    const nodes2 = sourceFile2.getDescendants();
    
    // Traverse the AST of file 1
    sourceFile1.forEachDescendant((node1, traversal) => {
      // Compare the node to every node in file 2
      for (const node2 of nodes2) {
        if (node1.getKind() === node2.getKind() && node1.getText() === node2.getText()) {
          console.log(`Node ${node1.getKindName()} with text "${node1.getText()}" is the same in both files.`);
        }
      }
    });
    

    This script compares every node in one source file (file1.ts) with every node in the other source file (file2.ts) regardless of their order of definition. It first retrieves all the descendants of file2.ts using getDescendants() and stores them in an array. It then traverses the AST of file1.ts using forEachDescendant() and compares each node to every node in file2.ts using a for loop. If they are the same, a message is printed to the console.

    Please note that comparing every node in this way can be computationally expensive, especially for large files, so you may want to consider optimizing the script for performance based on your specific needs.

  5. User

    ok, let's assume that we have two projects with corresponding source files. can you write a script by using ts-morph, traverse from the entry file and compare each node to see if two project's ATS are the same? the order of definitions in each files is not guaranteed.

  6. Assistant

    Sure! Here is a script that uses ts-morph to traverse both projects from their entry files, compares each node, and returns a boolean indicating whether the two ASTs are the same:

    const { Project } = require("ts-morph");
    
    // Create a new project instance for each project
    const project1 = new Project();
    const project2 = new Project();
    
    // Load the entry files for both projects
    const entryFile1 = project1.addSourceFileAtPath("path/to/project1/entryFile.ts");
    const entryFile2 = project2.addSourceFileAtPath("path/to/project2/entryFile.ts");
    
    // Traverse the ASTs of both projects starting from their entry files
    const areEqual = areNodesEqual(entryFile1, entryFile2);
    
    console.log(`The two projects are ${areEqual ? "" : "not "}equal`);
    
    /**
     * Helper function to compare nodes in two files recursively
     */
    function areNodesEqual(node1, node2) {
      // Compare the node
      if (node1.getKind() !== node2.getKind() || node1.getText() !== node2.getText()) {
        return false;
      }
    
      // Recursively compare child nodes
      const children1 = node1.getChildren();
      const children2 = node2.getChildren();
      if (children1.length !== children2.length) {
        return false;
      }
      for (let i = 0; i < children1.length; i++) {
        if (!areNodesEqual(children1[i], children2[i])) {
          return false;
        }
      }
    
      return true;
    }
    

    This script creates separate Project instances for both projects, loads their corresponding entry files (entryFile.ts), and traverses their ASTs starting from the entry files using a helper function areNodesEqual(). This function recursively compares each node starting from the entry file and returns false if any of the nodes are not equal or if the number of child nodes differ. If all nodes are equal, the function returns true. Finally, the script compares the ASTs of both projects by calling areNodesEqual() on their respective entry files and logs the result to the console.

    Please note that comparing two entire projects like this can be computationally expensive, especially for large projects or when comparing multiple pairs of files, so you may want to consider optimizing the script for performance based on your specific needs.