pythontutor-dev / pythontutor

10 stars 4 forks source link

JavaScript: duplicate block variables in loops #51

Open pgbovine opened 5 years ago

pgbovine commented 5 years ago

http://pythontutor.com/visualize.html#code=const%20x%20%3D%20%5B'hello',%20'world',%20'goodbye'%5D%3B%20%20%20%20%0Afor%20%28const%20e%20of%20x%29%20%7B%20%20%20%20%0A%20%20console.log%28'ELEMENT%3A%20'%20%2B%20e%29%3B%0A%7D&cumulative=false&curInstr=4&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=js&rawInputLstJSON=%5B%5D&textReferences=false

pgbovine commented 4 years ago

in general there's no easy way to fix this without resorting to unreliable heuristics, since the node debugger spits out 2 duplicate variables in successive blocks whenever there's a for-loop. there's no easy way to tell the difference between these duplicates being created by a for-loop and simply two let variables with the same names being defined in nested scopes. you could imagine a heuristic that looks for a definition on the line of the for loop, but that may be flaky.

pgbovine commented 4 years ago

here are two contrasting examples to show how you can't generally tell whether there should legitimately be two i's, or just one (without resorting to unreliable heuristics):

There should be only one i here since it's a loop variable: http://pythontutor.com/visualize.html#code=for%20%28let%20i%20%3D%200%3B%20i%20%3C%201%3B%20i%2B%2B%29%20%7B%0A%20%20let%20nestedVar%20%3D%2042%3B%0A%20%20console.log%28nestedVar%29%3B%0A%7D&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=js&rawInputLstJSON=%5B%5D&textReferences=false

There should legitimately be two i's here since they're both defined as let vars in nested scopes: http://pythontutor.com/visualize.html#code=if%20%28true%29%20%7B%0A%20%20let%20i%20%3D%200%3B%0A%20%20if%20%28true%29%20%7B%0A%20%20%20%20let%20i%20%3D%201%3B%0A%20%20%20%20if%20%28true%29%20%7B%0A%20%20%20%20%20%20let%20nestedVar%20%3D%2042%3B%0A%20%20%20%20%20%20console.log%28nestedVar%29%3B%0A%20%20%20%20%7D%0A%20%20%7D%0A%7D&cumulative=false&curInstr=6&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=js&rawInputLstJSON=%5B%5D&textReferences=false