on master help sign in
javascript: abstracted tailcalls
commit468f0d593635ba42047ae56a5d7516e58f859725 authorraichoo <raichoo@googlemail.com> dateFri 11 Jan 2013, 21:37 (14 years ago) parent58b10e1
1 file changed+20−19
src/IRTS/CodegenJavaScript.hs+20−19
src/IRTS/CodegenJavaScript.hs+20−19
@@ -33,7 +33,7 @@ codegenJavaScript definitions filename outputType =
3333
3434 mainLoop :: String
3535 mainLoop = intercalate "\n" [ "\nfunction main() {"
36− , createTrampoline "__IDR__.runMain0()" ++ ";"
36+ , createTailcall "__IDR__.runMain0()"
3737 , "}\n\nmain();\n"
3838 ]
3939
@@ -49,7 +49,22 @@ idrRuntime =
4949 [ "__IDR__.IntType = { type: 'IntType' };"
5050 , "__IDR__.Tailcall = function(f) { this.f = f };"
5151 , "__IDR__.Con = function(i,name,vars)"
52− , "{this.i = i;this.name = name;this.vars = vars;};"
52+ , "{this.i = i;this.name = name;this.vars = vars;};\n"
53+ , "__IDR__.tailcall = function(f){\n"
54+ ++ "var __f = f;\n"
55+ ++ "while (__f) {\ntry {\n"
56+ ++ "var f = __f;\n"
57+ ++ "__f = null;\n"
58+ ++ "return f();"
59+ ++ "\n} catch(ex) {\n"
60+ ++ "if (ex instanceof __IDR__.Tailcall) {\n"
61+ ++ "__f = ex.f;"
62+ ++ "\n} else {\n"
63+ ++ "throw ex;"
64+ ++ "\n}"
65+ ++ "\n}"
66+ ++ "\n}"
67+ ++ "\n}"
5368 ]
5469
5570createModule :: Maybe String -> NamespaceName -> String -> String
@@ -179,7 +194,7 @@ translateExpression _ (SV var) =
179194 translateVariableName var
180195
181196translateExpression modname (SApp False name vars) =
182− createTrampoline $ translateFunctionCall name vars
197+ createTailcall $ translateFunctionCall name vars
183198
184199translateExpression modname (SApp True name vars) =
185200 "(function(){\n"
@@ -337,22 +352,8 @@ createIfBlock cond e =
337352 ++ "return " ++ e
338353 ++ ";\n}"
339354
340−createTrampoline call =
341− "(function(){\n"
342− ++ "var __f = function(){return " ++ call ++ "};\n"
343− ++ "while (__f) {\ntry {\n"
344− ++ "var f = __f;\n"
345− ++ "__f = null;\n"
346− ++ "return f();"
347− ++ "\n} catch(ex) {\n"
348− ++ "if (ex instanceof __IDR__.Tailcall) {\n"
349− ++ "__f = ex.f;"
350− ++ "\n} else {\n"
351− ++ "throw ex;"
352− ++ "\n}"
353− ++ "\n}"
354− ++ "\n}"
355− ++ "\n})()"
355+createTailcall call =
356+ "__IDR__.tailcall(function(){return " ++ call ++ "})"
356357
357358translateFunctionCall name vars =
358359 concat (intersperse "." $ translateNamespace name)