This project has moved and is read-only. For the latest updates, please go here.

Line numbers in stacktraces

Sep 8, 2016 at 9:30 AM

I implemented/ported a module system to run on ClearScript. This requires me to wrap the loaded module code in a function declaration.
This works great but has one small catch: All line numbers in stack traces of exceptions are of by one line. Since this is in the end used to allow my users to write plugins, they do not neccessarily know about the inner implementation of the module system and so the line numbers will be very confusing.
Is there any way to work around this? If not, is it possible to implement a features which makes it possible to specify a line offset when calling Engine.Execute(...) or something similar?
Sep 8, 2016 at 4:48 PM
Hello ZoneRunner,

This requires me to wrap the loaded module code in a function declaration.

Can you say a bit more about (or provide a sample of) how you accomplish this wrapping? Do you take the module's code and splice it into a larger string that you then execute? Do the modules have names (or other identifiers), and if so, how are they related to source code files for which you need to see correct line numbers?

Sep 12, 2016 at 8:27 AM
Well, it works pretty similar to what node.js does, so lets have a look at that:

Starting with line 386 a minimal module system is implemented.
The interesting part is the compile function in line 473. The given source is basically spliced into a function declaration (pretty much as you suggested) to ensure that everything is local to the function end not in the global context. Note how there is no line break after the header. This is done so that line numbers of errors encountered will still be correct after the splicing. However, any errors in the first line of source will be very strange to the user.
The next step is to run the resulting function declaration through the engine. In my case I have defined the runInThisContext function as follows in c#:
private object RunInThisContext( string source, dynamic settings )
    string filename = _GetFileName(settings);

    var moduleLoader = Engine.Evaluate( filename, false, source );
    return moduleLoader;
What I would like to do now is wrap source like this:
'(function (exports, require, module, __filename, __dirname) {\n',
+ source +
And then tell the engine to offset all line positionsi n error messages by -1. Then errors in the first line of source could produce good error messages as well.
Sep 12, 2016 at 4:39 PM
Hi again,

V8 does allow you to specify where a given script begins within its containing file, presumably to accommodate scripts embedded in HTML and other file formats. It also appears to permit negative line and column offsets, enabling exactly the behavior you're looking for.

Unfortunately ClearScript doesn't provide access to this feature, as it only supports script document names. We've added a feature request here.