Last active
April 7, 2021 14:55
-
-
Save Araq/46988d814ed3a142eac7c55f092eb2f6 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
proc generateAccessors(name, hidden, typ, fieldTyp: NimNode): NimNode = | |
template helper(name, hidden, typ, fieldTyp) {.dirty.} = | |
proc name*(self: typ): auto = self.hidden | |
proc `name=`*(self: var typ; val: fieldTyp) = | |
self.hidden = val | |
result = getAst(helper(name, hidden, typ, fieldTyp)) | |
proc transform(n: NimNode; stmts, obj: NimNode): NimNode = | |
if n.kind == nnkIdentDefs and obj.kind == nnkIdent: | |
for i in 0..n.len-3: | |
let hidden = newIdentNode($n[i] & "000") | |
stmts.add generateAccessors(n[i], hidden, obj, n[n.len-2]) | |
n[i] = hidden | |
result = n | |
else: | |
var objB = if n.kind == nnkTypeDef: n[0] else: obj | |
result = copyNimNode(n) | |
for i in 0..<n.len: | |
result.add transform(n[i], stmts, objB) | |
macro wrapObject(n: untyped): untyped = | |
var a = newStmtList() | |
a.add newEmptyNode() | |
let t = transform(n, a, newEmptyNode()) | |
a[0] = t | |
result = a | |
echo repr result | |
wrapObject: | |
type | |
MyObject = object | |
x, y: int | |
s: string |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment