From 1ee056eedf773ac6166247755439092e0e0a9bca Mon Sep 17 00:00:00 2001 From: Li Jin Date: Wed, 11 Mar 2020 00:21:33 +0800 Subject: add macro functions. --- spec/inputs/macro.moon | 69 +++++++++++++++++++++++++++++++++++++++++++ spec/inputs/macro_export.moon | 29 ++++++++++++++++++ 2 files changed, 98 insertions(+) create mode 100644 spec/inputs/macro.moon create mode 100644 spec/inputs/macro_export.moon (limited to 'spec/inputs') diff --git a/spec/inputs/macro.moon b/spec/inputs/macro.moon new file mode 100644 index 0000000..eb1e224 --- /dev/null +++ b/spec/inputs/macro.moon @@ -0,0 +1,69 @@ +macro block init = -> + with require "moonp" + package.moonpath = "?.moon;./spec/inputs/?.moon" + "" + +$init! + +import "macro_export" as {$myconfig:$config, :$showMacro, :$asserts, :$assert} + +$asserts item == nil + +$myconfig false + +v = $assert item == nil + +macro expr and = (...)-> + values = [value for value in *{...}] + $showMacro "and", "#{ table.concat values, " and " }" + +if $and f1 + print "OK" + +if $and f1,f2,f3 + print "OK" + +macro expr map = (items,action)-> + $showMacro "map", "[#{action} for _ in *#{items}]" + +macro expr filter = (items,action)-> + $showMacro "filter", "[_ for _ in *#{items} when #{action}]" + +macro expr reduce = (items,def,action)-> + $showMacro "reduce", "if ##{items} == 0 + #{def} +else + _1 = #{def} + for _2 in *#{items} + _1 = #{action} + _1" + +macro block foreach = (items,action)-> + $showMacro "foreach", "for _ in *#{items} + #{action}" + +macro expr pipe = (...)-> + switch select "#",... + when 0 then return "" + when 1 then return ... + ops = {...} + last = ops[1] + stmts = for i = 2,#ops + stmt = "\tlocal _#{i} = #{last} |> #{ops[i]}" + last = "_#{i}" + stmt + res = "do +#{table.concat stmts,"\n"} + #{last}" + $showMacro "pipe", res + +{1,2,3} |> $map(_ * 2) |> $filter(_ > 4) |> $foreach print _ + +$foreach $filter($map({1,2,3}, _ * 2), _ > 4), print _ + +print $pipe( + {1, 2, 3} + $map(_ * 2) + $filter(_ > 4) + $reduce(0, _1 + _2) +) diff --git a/spec/inputs/macro_export.moon b/spec/inputs/macro_export.moon new file mode 100644 index 0000000..369b83b --- /dev/null +++ b/spec/inputs/macro_export.moon @@ -0,0 +1,29 @@ +export macro block config = (debugging = true)-> + global debugMode = debugging == "true" + global debugMacro = true + "" + +export macro expr showMacro = (name,res)-> + if debugMacro + "do + txt = #{res} + print '['..#{name}..']' + print txt + txt" + else + "#{res}" + +export macro block asserts = (cond)-> + if debugMode + $showMacro "assert", "assert #{cond}" + else + "" + +export macro expr assert = (cond)-> + if debugMode + $showMacro "assert", "assert #{cond}" + else + "#{cond}" + +$config! + -- cgit v1.2.3-55-g6feb