Siubaak / sval

A javascript interpreter written in javascript
https://jsbin.com/kehahiqono/edit?js,console
MIT License
379 stars 50 forks source link

Define function toString #98

Open ruifigueira opened 9 months ago

ruifigueira commented 9 months ago

Calling toString on a function would return the source code of the interpreter instead of the actual function body as declared.

It's possible to extract the function code from the node itself, using acorn options like sourceFile.

Siubaak commented 7 months ago

The location and sourceFile options enormously reduce parse efficiency, leading to a low perf of evaluation. I think we should find a more efficient way to generate the string of a function

ruifigueira commented 7 months ago

I understand. I reverted the implicit parsing with locations: true, sourceFile: code. But if the user explicitly includes the source file by provdiing a parser function, a function's .toString will be able to use that source.

Example:


  it('should serialize functions with toString', () => { 
    const parser =  (code) => parse(code, { ecmaVersion: 'latest', locations: true, sourceFile: code });
    const interpreter = new Sval()
    interpreter.import({ expect })
    const parsedCode = interpreter.parse(`
      expect((function x(a, b) { return a + b }).toString()).toEqual('function x(a, b) { return a + b }')
    `, parser);
    interpreter.run(parsedCode)
  })
ruifigueira commented 7 months ago

hi @Siubaak did you have a chance to look into my new proposal?