0

I want to use the UglifyJS parser to check if any identifiers in a piece of code are used when they are not guaranteed to be defined.

Example:

// Should raise an error since myfunc and myvar have not been defined, but works
var ast = jsp.parse('myfunc(myvar);');

I realise that myfunc and myvar are not necessarily undefined (since they could exist in scope) but I want to know when they possibly might be undefined.

echo "myfunc(myvar);" | uglifyjs happily returns myfunc(myvar); and I can't find any option to check for undefined variables.

If I run JSLint and turn assume browser, window, node.js, etc all off, then this is the result I'm after. I want to do a similar thing with UglifyJS, assuming nothing about the environment (no window, console, alert, etc).

Flash
  • 15,945
  • 13
  • 70
  • 98

2 Answers2

0

You've got a pretty tall order, since you're expecting to determine if certain contents of string literals constitute valid code. A string literal can be almost literally (hehe) anything. It is of course possible (which is a quite distinct concept from "easy") to specify the exact circumstances under which a string literal is expected to be valid according to some specification, but if you want help doing that, you'll need to show that you've already got an algorithm that can identify such literals.

You need to, first, identify such circumstances and, second, state a set of rules (a formal grammar would be a good way to do this) that such literal contents have to follow (note that under some, but not all, circumstances, it might be possible to express such a grammar in terms of regexes).

ebohlman
  • 14,795
  • 5
  • 33
  • 35
  • UglifyJS is already capable of determining if a string is valid code (it's a parser so that's what it's for). My question is specifically how to extend its parsing capabilities to flag undefined identifiers. – Flash Sep 20 '12 at 09:57
0

You could use the "Scope Chain". The Variable Scope is described in this article http://tore.darell.no/pages/scope_in_javascript.

Using the Scope chain might be easy, or not...

Here is a good examle from the artcile

//global
function foo () {
  //global.foo
  function bar () {
    //global.foo.bar
    function baz () {
      //global.foo.bar.baz
    }
  }
}

You could check if your function and/ or variable is defined in this scope chain or up to a specific level in your scope chain. (e.g. everything in global.foo.bar is okay).

Maybe this is how you could solve your problem.

SvenFinke
  • 1,254
  • 3
  • 15
  • 30