Jint: Regression: Using 'const' inside a nested function gives JavaScriptException: *variable* has not been initialized

Created on 3 Aug 2020  路  5Comments  路  Source: sebastienros/jint

The following code will report "testVariable has not been initialized" on tip of dev branch.

Maybe let/const support has not yet been finalized? This used to work fine with an older version of Jint, so curious as to whether or not recent changes to make let/const scoping work has made this regress.

Any ideas what to do to make this work again?

using System;

public static class Program
{

    public static void Main(string[] args)
    {
        Jint.Engine engine = new Jint.Engine();
        engine.SetValue("log", new Action<object>(Console.WriteLine));
        engine.Execute(@"
(function(){

const testVariable = ""test"";

function render() {
    log(testVariable);
}
render();

})();
        ");

    }

}
bug

All 5 comments

Confirming via bifurcate that this regressed in #722.
I understand let/const before that commit wasn't correctly scoped but at least the above code would run. After the changes in #722 it appears the above case has not been tested.
The issue occurs with both let and const, but not with var.

The previous code base was just assuming const as var. which is why the result for this example was valid.
But this seems like a legit bug now. Suprising that that it didn't get caught in the current unit tests as there are lots of them.

I debugged a bit and I now understand the problem. Jint models script function instance using BlockStatement as body, which itself tracks introduced variables.

In this case it re-declares the testVariable with bad outcome. I think I can create a fix which utilizes statement list for script function instance body instead of lexical-aware block - script body hoisting is handled inside script initialization already.

THANK YOU! That was an incredibly fast fix - confirmed that it also works here in our real-world code.

Glad to hear it's now working as expected, quite unfortunate little bug that was. As bonus the function evaluation is now slightly faster as we don't do virtual dispatch for common case and don't hoist it twice...

Was this page helpful?
0 / 5 - 0 ratings

Related issues

smadurange picture smadurange  路  3Comments

hnafar picture hnafar  路  3Comments

mikeswanson picture mikeswanson  路  3Comments

Jugolo picture Jugolo  路  13Comments

christianrondeau picture christianrondeau  路  10Comments