Skip to content
This repository was archived by the owner on Apr 9, 2022. It is now read-only.

JavaScript CodeGen

Seyedamirhossein Hesamian edited this page Dec 27, 2021 · 4 revisions

There is a "glue code" JavaScript file called basic.js which bridges the gap between autogenerated code and Toy.

Given this Toy Fibonacci code:

/**
 * This is an example of multiline comment
 */
class Driver() extends IO() {
  // This is an example of single line comment
  def fibonacci(n: Int): Int = if (n <= 1)
    n
  else
    fibonacci(n - 1) + fibonacci(n - 2);

  def assertEquals(expected: Any, actual: Any, msg: String): IO = if (expected != actual)
    out(
      "["
        .concat(msg)
        .concat("]")
        .concat("expected: ")
        .concat(expected.toString())
        .concat(" but received: ")
        .concat(actual.toString())
    )
  else
    out("passed!");

  { assertEquals(34, fibonacci(9), "fibonacci") }
}

class Driver() extends IO() {
    match new Foo() with {
        case x:IO => {},
        case null => out_any("it is null?")
    }
}

It generates:

class Driver extends IO {
  constructor() {
    super();
    (() => {
      return this.assertEquals(34, this.fibonacci(9), "fibonacci");
    }).bind(this)();
  }
  fibonacci(n) {
    return n <= 1 ? n : this.fibonacci(n - 1) + this.fibonacci(n - 2);
  }
  assertEquals(expected, actual, msg) {
    return expected !== actual
      ? this.out(
          "["
            .concat(msg)
            .concat("]")
            .concat("expected: ")
            .concat(expected.toString())
            .concat(" but received: ")
            .concat(actual.toString())
        )
      : this.out("passed!");
  }
}
class Driver extends IO {
  constructor() {
    super();
    ((rndVar100) => {
      var x;
      return rndVar100 instanceof IO && (x = rndVar100)
        ? new Unit()
        : rndVar100 === null
        ? this.out_any("it is null?")
        : new Error("pattern matching failed.");
    }).bind(this)(new Foo());
  }
}
new Driver();

The generated JavaScript code is not properly formatted but it is "correct" meaning that it semantically is equivalent to the original Toy code.

Clone this wiki locally