-
-
Save planetis-m/15968fb7e5ae0b414857360ac930c4e8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import macros, sets | |
macro lcSet(body): untyped = | |
# analyse the body, find the deepest expression 'it' and replace it via | |
# 'result.add it' | |
let res = genSym(nskVar, "lcResult") | |
proc t(n, res: NimNode): NimNode = | |
# Looks for the last statement of the last statement, etc... | |
case n.kind | |
of nnkStmtList, nnkStmtListExpr, nnkBlockStmt, nnkBlockExpr, | |
nnkWhileStmt, | |
nnkForStmt, nnkIfExpr, nnkIfStmt, nnkTryStmt, nnkCaseStmt, | |
nnkElifBranch, nnkElse, nnkElifExpr: | |
result = copyNimTree(n) | |
if n.len >= 1: | |
result[^1] = t(n[^1], res) | |
else: | |
# add checks for {k: v}, {k} here | |
template adder(res, n) = | |
res.incl n | |
result = getAst adder(res, n) | |
let v = newTree(nnkVarSection, | |
newTree(nnkIdentDefs, res, newEmptyNode(), newTree(nnkCall, newTree(nnkBracketExpr, bindSym"initSet", | |
newCall(bindSym"typeof", body))))) | |
result = newTree(nnkStmtListExpr, v, t(body, res), res) | |
echo repr result | |
import tables, sets | |
var data = {2: "bird", 5: "word"}.toTable | |
let x = lcSet: | |
for k, v in data: | |
if k mod 2 == 0: | |
k | |
echo x |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment