2

Is there a way to inspect which variables (and lines of code) contribute to a value in Javascript? For example if I would inspect the parameter input in this code

let x=5;
let y=x+3;

function a(input) {
  // analyzing input in this scope/context,
  // i would like to see that it is a combination of
  // x from line 1 and a constant '3' from line 2.
  inspectDataFlow(input);
}

a(y);

I would like to get as output a data structure that would be something like this:

input (line 8)
  y (line 2)
    x (line 1)
    "3" (line 2)

Purpose and goal

My goal for this would be to have a tool where you could see/change the value of a Javascript variable and it would automatically adjust the variables that the value originates from.

For example, you could have a function to draw shapes. And when you adjust visually the shapes that were drawn, the original variables for color, shape positions etc would update accordingly.

Something a bit like this but for editing arbitrary code, even after a user has modified the code lines:

http://yining1023.github.io/p5PlayGround/

Another idea I was thinking was to visualize how a variable has been composed: which lines it is a combination of and how they affect the result.

Potential approach

One approach for this I'm thinking about is to add instrumentation to the code with Esprima/Acorn that is then called on runtime. The instrumentation would keep track on which variables have been called on which lines (and scopes) and how they relate to each other, a bit like this:

http://alltom.com/pages/instrumenting-javascript/

I wonder if this would work and if there is a framework one could use for this? Or if one would have to do the instrumentation from scratch?

Related themes

This could be related to data flow analysis or use-define chains, but I'm not sure, since I don't know much about compilers.

https://en.wikipedia.org/wiki/Use-define_chain

My first idea was that this could be done using static analysis with something like Esprima/Acorn, but I'm not sure if that is the right way, or if this could be done with some custom Javascript interpreter instead.

http://tobyho.com/2013/12/02/fun-with-esprima/

Janne Aukia
  • 1,003
  • 6
  • 7
  • 1
    Not an answer per se, as the question's a bit old, but see https://stackoverflow.com/questions/5388618/are-there-any-static-call-graph-and-or-control-flow-graph-api-for-javascript –  Dec 27 '17 at 02:35
  • Thanks! That is interesting and definitely related. However, that is mostly about making a graph of calls, I'm interested in inspecting the variable definitions, too. And a run-time tool would be fine, since it would probably be much easier than static analysis. – Janne Aukia Jan 17 '18 at 11:24

0 Answers0