Skip to content

Commit

Permalink
Fix scoping
Browse files Browse the repository at this point in the history
  • Loading branch information
AnsonYeung authored and LPTK committed Nov 20, 2024
1 parent de16b05 commit ac5e2e0
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 9 deletions.
6 changes: 3 additions & 3 deletions hkmc2/shared/src/main/scala/hkmc2/codegen/js/JSBuilder.scala
Original file line number Diff line number Diff line change
Expand Up @@ -318,9 +318,9 @@ class JSBuilder extends CodeBuilder:
)

def block(t: Block)(using Raise, Scope): Document =
if t.definedVars.isEmpty then returningTerm(t).stripBreaks else
val vars = t.definedVars.toSeq.sortBy(_.uid).iterator.map(l =>
l -> scope.allocateName(l))
val vars = t.definedVars.toSeq.filter(scope.lookup(_).isEmpty).sortBy(_.uid).iterator.map(l =>
l -> scope.allocateName(l))
if vars.isEmpty then returningTerm(t).stripBreaks else
doc"let " :: vars.map: (_, nme) =>
nme
.toList.mkDocument(", ")
Expand Down
29 changes: 29 additions & 0 deletions hkmc2/shared/src/test/mlscript/codegen/Scoping.mls
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
:js

:expect 4
fun f(y) =
let x = 0
class A() with
fun g() =
set x += 1
set y += 1
fun h() =
set x += 1
set y += 1
A().g()
h()
x + y
f(0)
//│ = 4

:expect 0
fun f() =
let x = 0
class A() with
let x = 2
fun g() =
set x += 1
A().g()
x
f()
//│ = 0
16 changes: 10 additions & 6 deletions hkmc2/shared/src/test/mlscript/codegen/While.mls
Original file line number Diff line number Diff line change
Expand Up @@ -197,14 +197,14 @@ fun f(ls) =
else log("Done!")
//│ JS:
//│ function f(ls) {
//│ let ls1, param0, param1, h, tl, tmp;
//│ let param0, param1, h, tl, tmp;
//│ tmp1: while (true) {
//│ if (ls1 instanceof globalThis.Cons.class) {
//│ param0 = ls1.hd;
//│ param1 = ls1.tl;
//│ if (ls instanceof globalThis.Cons.class) {
//│ param0 = ls.hd;
//│ param1 = ls.tl;
//│ h = param0;
//│ tl = param1;
//│ ls1 = tl;
//│ ls = tl;
//│ tmp = globalThis.log(h);
//│ continue tmp1;
//│ } else {
Expand All @@ -220,9 +220,13 @@ f(0)
//│ > Done!

f(Cons(1, 0))
//│ > 1
//│ > Done!

f(Cons(1, Cons(2, Cons(3, 0))))
//│ > 1
//│ > 2
//│ > 3
//│ > Done!


Expand All @@ -239,7 +243,7 @@ while log("Hello World"); false
then 0(0)
else 1
//│ ╔══[PARSE ERROR] Unexpected 'then' keyword here
//│ ║ l.239: then 0(0)
//│ ║ l.243: then 0(0)
//│ ╙── ^^^^
//│ ═══[ERROR] Unrecognized term split (false literal).
//│ ═══[RUNTIME ERROR] Error: match error
Expand Down

0 comments on commit ac5e2e0

Please sign in to comment.