UNPKG

estree-toolkit

Version:

Traverser, scope tracker, and more tools for working with ESTree AST

49 lines (48 loc) 1.96 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.isReference = exports.getCommonAncestor = exports.hasBinding = exports.evaluateTruthy = exports.evaluate = void 0; var evaluate_1 = require("./evaluate"); Object.defineProperty(exports, "evaluate", { enumerable: true, get: function () { return evaluate_1.evaluate; } }); Object.defineProperty(exports, "evaluateTruthy", { enumerable: true, get: function () { return evaluate_1.evaluateTruthy; } }); var hasBinding_1 = require("./hasBinding"); Object.defineProperty(exports, "hasBinding", { enumerable: true, get: function () { return hasBinding_1.hasBinding; } }); const getCommonAncestor = (paths) => { const ancestorsArr = []; for (let i = 0; i < paths.length; i++) { const ancestors = []; let parent = paths[i].parentPath; while (parent != null) { ancestors.push(parent); parent = parent.parentPath; } ancestorsArr.push(ancestors.reverse()); } let common = null; let currAncestor; for (let i = 0;; i++) { currAncestor = ancestorsArr[0][i]; for (let j = 0; j < paths.length; j++) { if (currAncestor !== ancestorsArr[j][i]) return common; } common = currAncestor; } }; exports.getCommonAncestor = getCommonAncestor; const isReference = (path, includeGlobals = true) => { if (!path.scope) { throw new Error("Can't use isReference() when `scope` is not enabled"); } const binding = path.scope.getBinding(path.node.name); if (binding != null) { return path === binding.identifierPath || binding.references.includes(path); } if (!includeGlobals) return false; const globalBinding = path.scope.getGlobalBinding(path.node.name); if (globalBinding != null) { return globalBinding.references.includes(path); } return false; }; exports.isReference = isReference;