diff --git a/moonscript/transform/statements.lua b/moonscript/transform/statements.lua index afad5c4..f71aede 100644 --- a/moonscript/transform/statements.lua +++ b/moonscript/transform/statements.lua @@ -44,7 +44,32 @@ last_stm = function(stms) end return stms[last_exp_id], last_exp_id, stms end +local transform_last_stm +transform_last_stm = function(stms, fn) + local _, last_idx, _stms = last_stm(stms) + if _stms ~= stms then + error("cannot transform last node in group") + end + return (function() + local _accum_0 = { } + local _len_0 = 1 + for i, stm in ipairs(stms) do + if i == last_idx then + _accum_0[_len_0] = { + "transform", + stm, + fn + } + else + _accum_0[_len_0] = stm + end + _len_0 = _len_0 + 1 + end + return _accum_0 + end)() +end return { + Run = Run, last_stm = last_stm, - Run = Run + transform_last_stm = transform_last_stm } diff --git a/moonscript/transform/statements.moon b/moonscript/transform/statements.moon index bf214a6..0e3baeb 100644 --- a/moonscript/transform/statements.moon +++ b/moonscript/transform/statements.moon @@ -26,5 +26,20 @@ last_stm = (stms) -> stms[last_exp_id], last_exp_id, stms -{:last_stm, :Run} +-- transform the last stm is a list of stms +-- will puke on group +transform_last_stm = (stms, fn) -> + _, last_idx, _stms = last_stm stms + + if _stms != stms + error "cannot transform last node in group" + + return for i, stm in ipairs stms + if i == last_idx + {"transform", stm, fn} + else + stm + + +{:Run, :last_stm, :transform_last_stm} diff --git a/spec/transform_spec.moon b/spec/transform_spec.moon index 807175f..682561d 100644 --- a/spec/transform_spec.moon +++ b/spec/transform_spec.moon @@ -45,4 +45,43 @@ describe "moonscript.transform.statements", -> assert.same 2, idx assert t == stms[2][2], "should get correct table" + describe "transform_last_stm", -> + import transform_last_stm, Run from require "moonscript.transform.statements" + + it "transforms empty stms", -> + before = {} + after = transform_last_stm before, (n) -> {"wrapped", n} + + assert.same before, after + assert before != after + + it "transforms stms", -> + before = { + {"ref", "butt_world"} + {"ref", "hello_world"} + } + + transformer = (n) -> n + after = transform_last_stm before, transformer + + assert.same { + {"ref", "butt_world"} + {"transform", {"ref", "hello_world"}, transformer} + }, after + + it "transforms empty stms ignoring runs", -> + before = { + {"ref", "butt_world"} + {"ref", "hello_world"} + Run => print "hi" + } + + transformer = (n) -> n + after = transform_last_stm before, transformer + + assert.same { + {"ref", "butt_world"} + {"transform", {"ref", "hello_world"}, transformer} + before[3] + }, after