ballercat / walt

:zap: Walt is a JavaScript-like syntax for WebAssembly text format :zap:
https://ballercat.github.io/walt/
MIT License
4.64k stars 122 forks source link

Unexpected TypeError when experimenting with arrays #168

Closed WalasPrime closed 6 years ago

WalasPrime commented 6 years ago

Bug Report

Overview

An unexpected error occurs when running a particular piece of code. No proper error description is given so there is no way of telling what is wrong.

Expected

A proper error message should be shown.

Actual

S:\GIT\walt-tests\node_modules\walt-compiler\dist\walt.js:5213
    body.push(index_9, kind.code, `${kind.text}  ${debug ? debug : ''}`);
                            ^

TypeError: Cannot read property 'code' of undefined
    at code.forEach (S:\GIT\walt-tests\node_modules\walt-compiler\dist\walt.js:5213:29)
    at Array.forEach (<anonymous>)
    at emitFunctionBody (S:\GIT\walt-tests\node_modules\walt-compiler\dist\walt.js:5211:8)
    at functions.forEach.func (S:\GIT\walt-tests\node_modules\walt-compiler\dist\walt.js:5273:29)
    at Array.forEach (<anonymous>)
    at emit$7 (S:\GIT\walt-tests\node_modules\walt-compiler\dist\walt.js:5273:13)
    at Object.ast [as code] (S:\GIT\walt-tests\node_modules\walt-compiler\dist\walt.js:5442:19)
    at emit (S:\GIT\walt-tests\node_modules\walt-compiler\dist\walt.js:5483:350)
    at compile (S:\GIT\walt-tests\node_modules\walt-compiler\dist\walt.js:5824:16)
    at Object.<anonymous> (S:\GIT\walt-tests\mat.js:3:16)

Example

This snippet fails (required npm install walt-compiler)

const { compile } = require('walt-compiler');

const buffer = compile(`
const memory: Memory<{initial: 1}>;

type ResultFnType = (i32) => void;

export function func(a: i32, l: i32, f: ResultFnType): i32 {
    let v: i32 = 0;
    let i: i32 = 0;
    for(i; i < l; i+=1)
        v += a[i];
    f(v);
}
`).buffer();

WebAssembly.instantiate(buffer).then(result => {
    let sum;
    result.instance.exports.func([1, 2, 1], 3, (r) => sum = r);
    console.log(sum);
});

Offtop

It would be nice if there was an example on how to work with array arguments/array results in Walt (or if it's even possible at the moment).

ballercat commented 6 years ago

Thank you for reporting this. There is a fix in a PR for improved messaging in flight #165

To help debug any other potential issues, could you provide the result of require('walt-compiler').VERSION.

A couple of notes on your code above though.

ballercat commented 6 years ago

Had a chance to validate your code snippet. Turns out that you had a subscript on a non array type, which when generated created an undefined opcode. This caused a hard fatal as you already brought up.

You want to change this line

export function func(a: i32, l: i32, f: ResultFnType): i32 {

to

export function func(a: i32[], l: i32, f: ResultFnType): i32 {

then you should be able to access a like an array via a[i]

Thanks for reporting this, the code snippet was very helpful!