Njs: Show the exact line where exception happened.

Created on 18 Apr 2019  路  3Comments  路  Source: nginx/njs

Currently only function level stack trace is available.

trace.js

function f() {
    var a
    var b

    return ({}).a.a;
} 

f();
njs test.js
TypeError: cannot get property "a" of undefined
    at f (trace.js:2)
    at main (native)

correct line is: 5

feature help wanted in-progress

All 3 comments

@drsm, @hongzhidao Welcome to test https://gist.github.com/bca1263094b3b0b48e8f20236fc079c1

$ cat t2.js 
for (var i = 0; 
        i < a; 
        i++) { }

$ ./build/njs -d t2.js
t2.js:main
    2 | 00000 MOVE              0011 62500000CC60
    2 | 00024 JUMP              48
    4 | 00040 POST INC          0021 0011 0011
    3 | 00072 GLOBAL GET        0021 0001 62500000CC70
    3 | 00104 REFERENCE ERROR
    3 | 00152 LESS              0021 0011 0021
    3 | 00184 JUMP IF TRUE      0021 -144
    6 | 00208 STOP              62500000CCA0
Thrown:
ReferenceError: "a" is not defined in t2.js:3
    at main (t2.js:3)

@xeioex

Works well. And the implementation is very concise.
BTW, I will be affected a litter by Map, and you introduced the thing line number.

  1. rename njs_generate_map as njs_generate_code_map.
    Since njs_generate_map may be introduced in the future for Map object.

  2. go further
    I think line number is an important thing as you've done, I'd like to see it in someplace.

typedef struct {
    uint32_t                 offset;
    uint32_t                 line;
} njs_vm_line_num_t;


typedef struct {
    u_char                   *start;
    u_char                   *end;
    njs_str_t                file;
    njs_str_t                name;
    njs_arr_t                *lines;  /* of njs_vm_line_num_t */
} njs_vm_code_t;

@xeioex

template literal may cause wrong line numbers:

$ cat -n lines.js 
     1
     2  var lines1 = `
     3  var a = 1;
     4  var b = 2;
     5  `;
     6
     7  throw new Error('x');
drsm@L7480:~/work/njs$ node lines.js 
/home/drsm/work/njs/lines.js:7
throw new Error('x');
^

Error: x
    at Object.<anonymous> (/home/drsm/work/njs/lines.js:7:7)
    at Module._compile (internal/modules/cjs/loader.js:1138:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
    at Module.load (internal/modules/cjs/loader.js:986:32)
    at Function.Module._load (internal/modules/cjs/loader.js:879:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47
drsm@L7480:~/work/njs$ build/njs lines.js 
Thrown:
Error: x
    at main (lines.js:5)
Was this page helpful?
0 / 5 - 0 ratings