From 9d575733ab4ff4525a293a81854d641a3e0d214e Mon Sep 17 00:00:00 2001 From: Kristian Sons Date: Fri, 4 Sep 2015 13:15:44 +0200 Subject: [PATCH] Added options that skips non-explicit execption edges in CFG Includes test that fails before changes. --- README.md | 6 +++++- lib/index.js | 6 ++++-- test/test.js | 12 ++++++++++++ 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 50f066d..6d3049e 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,11 @@ To create a png file showing the CFG of a js file: ```js var esgraph = require('esgraph'); -var cfg = esgraph(esprima.parse(source, {range: true})); +var cfg = esgraph(esprima.parse(source, {range: true}), { + // do not create edges for non-explicit exceptions (default: false) + omitExceptions: false + } +); // cfg[0] is the start node // cfg[1] is the end node // cfg[2] is an array of all nodes for easier iteration diff --git a/lib/index.js b/lib/index.js index 8aa46e6..ca169af 100644 --- a/lib/index.js +++ b/lib/index.js @@ -17,10 +17,12 @@ module.exports.dot = require('./dot'); /** * Returns [entry, exit] `FlowNode`s for the passed in AST */ -function ControlFlowGraph(astNode) { +function ControlFlowGraph(astNode, options) { + options = options || {}; var parentStack = []; var exitNode = new FlowNode(undefined, undefined, 'exit'); var catchStack = [exitNode]; + var omitExceptions = !!options.omitExceptions; createNodes(astNode); linkSiblings(astNode); @@ -167,7 +169,7 @@ function ControlFlowGraph(astNode) { } function mayThrow(node) { - if (expressionThrows(node)) + if (!omitExceptions && expressionThrows(node)) node.cfg.connect(getExceptionTarget(node), 'exception'); } function expressionThrows(astNode) { diff --git a/test/test.js b/test/test.js index 78e1542..2ebf5f3 100644 --- a/test/test.js +++ b/test/test.js @@ -35,6 +35,18 @@ describe('esgraph', function () { var cfg = esgraph(ast); esgraph.dot(cfg); }); + + it('should omit implicit exception edges when omitExceptions option is set', function () { + var contents = fs.readFileSync(dir + "basicblocks.js", 'utf8'); + var ast = espree.parse(contents, {comment: true, range: true}); + delete ast.comments; + + var cfg = esgraph(ast); + cfg[1].prev.length.should.equal(2); + + cfg = esgraph(ast, {omitExceptions: true}); + cfg[1].prev.length.should.equal(1); + }); }); describe('esgraph.dot', function () {