From e8786f49ffc5f95ebe2229763bf5505e809e7cf2 Mon Sep 17 00:00:00 2001 From: yann300 Date: Wed, 10 Aug 2016 15:10:01 +0200 Subject: [PATCH] astcrawler --- src/index.js | 4 +++- src/util/astWalker.js | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 src/util/astWalker.js diff --git a/src/index.js b/src/index.js index 2325fe9d97..77da64ba23 100644 --- a/src/index.js +++ b/src/index.js @@ -5,6 +5,7 @@ var BasicPanel = require('./ui/BasicPanel') var TraceManager = require('./trace/traceManager') var CodeManager = require('./code/codeManager') var SourceMappingDecoder = require('./util/sourceMappingDecoder') +var AstWalker = require('./util/astWalker') if (typeof (module) !== 'undefined' && typeof (module.exports) !== 'undefined') { module.exports = modules() @@ -24,7 +25,8 @@ function modules () { BasicPanel: BasicPanel }, util: { - SourceMappingDecoder: SourceMappingDecoder + SourceMappingDecoder: SourceMappingDecoder, + AstWalker: AstWalker } } } diff --git a/src/util/astWalker.js b/src/util/astWalker.js new file mode 100644 index 0000000000..7e38011d94 --- /dev/null +++ b/src/util/astWalker.js @@ -0,0 +1,40 @@ +'use strict' +/* + Crawl the given AST through the function walk(ast, callback) +*/ +function AstWalker () { +} +/* + * visit all the AST nodes + * + * @param {Object} ast - AST node + * @param {Object or Function} callback - if (Function) the function will be called for every node. + * - if (Object) callback[] will be called for every node of type . callback["*"] will be called fo all other nodes. + * in each case, if the callback returns false it does not descend into children. If no callback for the current type, children are visited. +*/ +AstWalker.prototype.walk = function (ast, callback) { + crawlNode(ast, callback) +} + +function crawlNode (node, callback) { + if (manageCallBack(node, callback) && node.children && node.children.length > 0) { + for (var k in node.children) { + var child = node.children[k] + crawlNode(child, callback) + } + } +} + +function manageCallBack (node, callback) { + if (callback instanceof Function) { + return callback(null, node) + } else if (callback instanceof Object) { + if (callback[node.name] instanceof 'Function') { + return callback[node.name](null, node) + } else if (callback['*'] instanceof 'Function') { + return callback['*'](null, node) + } else { + return true + } + } +}