Skip to content
This repository was archived by the owner on Nov 23, 2017. It is now read-only.
This repository was archived by the owner on Nov 23, 2017. It is now read-only.

Variable scopes mismatching between Roy and JavaScript #134

@taku0

Description

@taku0

Problem

The variable scopes in JavaScript are whole function; however scopes in Roy are only after the let declaration.
This results in referencing uninitialized variables.

Sample Code

let x = 1
let f = \() ->
  console.log(x)
  let x = true
  x
console.log(f())

Expected

1
true

Actual

undefined
true

Cause

The code is compiled into

var x = 1;
var f = function() {
    console.log((x));
    var x = true;
    return x;
};
console.log(f());

The scope in JavaScript are whole function, thus the code is equivalent to

var x = 1;
var f = function() {
    var x;
    console.log((x));
    x = true;
    return x;
};
console.log(f());

Possible Fix

I guess there are two ways (or more?) but neither is satisfactory.

Option1: Adapting to Roy semantics

Compile the code into

var x = 1;
var f = function() {
    console.log((x));
    return (function() {
      var x = true;
      return x;
    })();
};
console.log(f());

or

var x = 1;
var f = function() {
    console.log((x));
    var x1 = true; // renaming the variable
    return x1;
};
console.log(f());

Both mess compiled code to some extent.

Option 2: Adapting to JavaScript semantics

Raise error if referencing uninitialized variable.

This is inconvenient and not intuitive.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions