Last active
May 27, 2018 20:46
-
-
Save Vindaar/b9cef31428cfb2f26fbb5e70d9ba394c 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, times, strutils, tables | |
type | |
Data* = object | |
value*: int | |
fvalue*: float | |
tvalue*: Time | |
Container* = object | |
desc*: string | |
tab*: Table[string, int] | |
ivalue*: int | |
fvalue*: float | |
tvalue*: Time | |
seqVal*: seq[float] | |
proc parseBracketExpr(b: NimNode): NimNode = | |
## iterates over a nnkBracketExpr and parses it correctly | |
## we create a string containing the type and finally generate | |
## a new symbol from it | |
# create a string in which we store the string describing the type | |
var strRes = "" | |
# get the typeKind for the type of bracketExpr. If it's a sequence | |
# we manually add 'seq' | |
case b.typeKind | |
of ntySequence: | |
strRes.add "seq" | |
of ntyGenericInst: | |
# in case of a GenericInst we just take the first element, e.g. in case | |
# of a Table[string, int] this is just `Table` | |
strRes.add b[0].getType.strVal | |
else: | |
echo "Type ", b.treeRepr, " not supported!" | |
# add the bracket and then iterate over all members | |
strRes.add "[" | |
for i in 1 ..< b.len: | |
# add the string value of the type | |
strRes.add b[i].getType.strVal | |
if i != b.len - 1: | |
# add comma and space for all but the last type | |
strRes.add ", " | |
strRes.add "]" | |
# given this string generate a new symbol for it | |
result = genSym(ident = strRes) | |
iterator objFields(t: NimNode): (NimNode, NimNode) = | |
let reclist = t.getType[2] | |
for i in 0 ..< reclist.len: | |
echo "reclist[i].getType.treeRepr ", reclist[i].getTypeInst.treeRepr | |
case reclist[i].getTypeInst.kind | |
of nnkBracketExpr: | |
let brSym = parseBracketExpr(reclist[i].getTypeInst) | |
yield (reclist[i], brSym) | |
else: | |
yield (reclist[i], reclist[i].getTypeInst) | |
macro echoFields(data: typed): typed = | |
result = newStmtList() | |
for n, t in data.getType.objFields: | |
let i = $n | |
let i2 = $t.treeRepr | |
let s = quote do: | |
echo `i`, ", ", `i2` | |
result.add(s) | |
var d: Data | |
var c: Container | |
echoFields(d) | |
echo "Now another type:" | |
echoFields(c) | |
# value, Sym "int" | |
# fvalue, Sym "float" | |
# tvalue, Sym "Time" | |
# Now another type: | |
# desc, Sym "string" | |
# tab, Sym "Table[string, int]" | |
# ivalue, Sym "int" | |
# fvalue, Sym "float" | |
# tvalue, Sym "Time" | |
# seqVal, Sym "seq[float]" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment