UNPKG

agentsqripts

Version:

Comprehensive static code analysis toolkit for identifying technical debt, security vulnerabilities, performance issues, and code quality problems

91 lines (85 loc) 2.58 kB
/** * @file AST helper utilities index * @description Single responsibility: Export all AST manipulation utilities */ const parseCode = require('./parseCode'); const acornWalk = require('acorn-walk'); /** * Find nodes in AST matching a predicate * @param {Object} ast - AST to search * @param {Function} predicate - Function to test nodes * @returns {Array} Matching nodes */ function findNodes(ast, predicate) { const nodes = []; acornWalk.simple(ast, { Program: (node) => { if (predicate(node)) nodes.push(node); }, FunctionDeclaration: (node) => { if (predicate(node)) nodes.push(node); }, VariableDeclaration: (node) => { if (predicate(node)) nodes.push(node); }, Identifier: (node) => { if (predicate(node)) nodes.push(node); }, Literal: (node) => { if (predicate(node)) nodes.push(node); }, ExpressionStatement: (node) => { if (predicate(node)) nodes.push(node); }, ReturnStatement: (node) => { if (predicate(node)) nodes.push(node); }, BlockStatement: (node) => { if (predicate(node)) nodes.push(node); }, CallExpression: (node) => { if (predicate(node)) nodes.push(node); }, BinaryExpression: (node) => { if (predicate(node)) nodes.push(node); }, }); return nodes; } /** * Get context information for a node * @param {Object} node - AST node * @param {string} code - Original source code * @returns {Object} Context information */ function getNodeContext(node, code) { return { type: node.type, start: node.start, end: node.end, line: code.substring(0, node.start).split('\n').length, text: code.substring(node.start, node.end) }; } /** * Get scope variables from AST * @param {Object} ast - AST to analyze * @returns {Array} Variable declarations */ function getScopeVariables(ast) { const variables = []; acornWalk.simple(ast, { VariableDeclarator: (node) => { if (node.id.name) { variables.push(node.id.name); } } }); return variables; } /** * Walk through AST with callback * @param {Object} ast - AST to walk * @param {Function} callback - Callback for each node */ function walkAST(ast, callback) { acornWalk.simple(ast, { Program: callback, FunctionDeclaration: callback, VariableDeclaration: callback, Identifier: callback, Literal: callback, ExpressionStatement: callback, ReturnStatement: callback, BlockStatement: callback, CallExpression: callback, BinaryExpression: callback, }); } module.exports = { parseCode, findNodes, getNodeContext, getScopeVariables, walkAST };