BindingIdentifier.IsEquivalentTo and Lookup.IsEquivalentTo

Jan 29, 2014 at 2:50 PM

I have a couple of questions regarding the IsEquivalentTo methods on BindingIdentifier and Lookup.
  1. Say, you have two variables, BI and LU (that is a BindingIdentifier and a Lookup). Intuitively, it should be the same to do BI.IsEquivalentTo(LU) and LU.IsEquivalentTo(BI). But currently it isn't. My question is: Is this by design, or a bug?
  2. BindingIdentifier.IsEquivalentTo(Lookup) compares the VariableFields by reference. Isn't it supposed to use JSVariableField.IsSameField?
The latter question comes from a real project... See this snippet:
JSParser parser = new JSParser { 
   Settings = new CodeSettings { PreprocessOnly = true }
var block = parser.Parse(
  function a() {
    var i = 1;
    return function() {

// bi is the 'i' in: var i = 1
var bi = (((((block.First() as FunctionObject).Body as Block).ElementAt(0) as Var).First() as VariableDeclaration).Binding as BindingIdentifier);

// lu is the 'i' in: console.log(i)
var lu = ((((((((block.First() as FunctionObject).Body as Block).ElementAt(1) as ReturnNode).Operand as FunctionObject).Body as Block).ElementAt(0) as CallNode).Arguments as AstNodeList)[0] as Lookup);

var equal1 = bi.IsEquivalentTo(lu);
var equal2 = bi.VariableField.IsSameField(lu.VariableField);
Here equal1 is false and equal2 is true.

Since both 'i's are referring to the same variable, it would make more sense to me if equal1 was true.
Jan 29, 2014 at 6:58 PM
If I remember correctly, we use the IsEquivalentTo to figure out if we can get rid of variables with only a single reference and a constant initializer value. For instance,
function foo(bar)
    var x = "prefix";
    return x + bar;
would get minified to:
function foo(bar){return"prefix"+bar}
But in your general example, I can't safely make that replacement every time because the variable is defined in one scope but referenced in another. I mean, yes: in this specific example I could get rid of the var i = 1 and just have the function just return 1, but that isn't always true. So the IsEquivalentTo method won't say a variable is equivalent to the definition if they are in different scopes. Yes, they point to the same field, so IsSameField returns true, but they aren't "equivalent" within the definition of also being in the same scope.
Marked as answer by F2 on 1/29/2014 at 2:35 PM
Jan 29, 2014 at 8:11 PM
Okay, thanks a lot!
I misunderstood the intention of "IsEquivalentTo".