standard init template; macros.recordFields

This commit is contained in:
Zahary Karadjov 2018-12-18 17:39:39 +02:00
commit 8e1fa61e91
3 changed files with 99 additions and 0 deletions

11
std_shims.nimble Normal file
View File

@ -0,0 +1,11 @@
mode = ScriptMode.Verbose
packageName = "std_shims"
version = "0.1.0"
author = "Status Research & Development GmbH"
description = "APIs available in the latests version of Nim, backported to older stable releases"
license = "Apache License 2.0"
skipDirs = @["tests"]
requires "nim >= 0.19.0"

84
std_shims/macros_shim.nim Normal file
View File

@ -0,0 +1,84 @@
import
macros
export
macros
type
FieldDescription* = object
name*: NimNode
isPublic*: bool
typ*: NimNode
pragmas*: NimNode
iterator recordFields*(typeImpl: NimNode): FieldDescription =
# TODO: This doesn't support inheritance yet
let
objectType = typeImpl[2]
recList = objectType[2]
if recList.len > 0:
var traversalStack = @[(recList, 0)]
while true:
assert traversalStack.len > 0
let (recList, idx) = traversalStack[^1]
let n = recList[idx]
inc traversalStack[^1][1]
if idx == recList.len - 1:
discard traversalStack.pop
case n.kind
of nnkRecWhen:
for i in countdown(n.len - 1, 0):
let branch = n[i]
case branch.kind:
of nnkElifBranch:
traversalStack.add (branch[1], 0)
of nnkElse:
traversalStack.add (branch[0], 0)
else:
assert false
continue
of nnkRecCase:
assert n.len > 0
for i in countdown(n.len - 1, 1):
let branch = n[i]
case branch.kind
of nnkOfBranch:
traversalStack.add (branch[^1], 0)
of nnkElse:
traversalStack.add (branch[0], 0)
else:
assert false
traversalStack.add (newTree(nnkRecCase, n[0]), 0)
continue
of nnkIdentDefs:
let fieldType = n[^2]
for i in 0 ..< n.len - 2:
var field: FieldDescription
field.name = n[i]
if field.name.kind == nnkPostfix:
field.isPublic = true
field.name = field.name[1]
if field.name.kind == nnkPragmaExpr:
field.pragmas = field.name[1]
field.name = field.name[0]
yield field
of nnkNilLit, nnkDiscardStmt, nnkCommentStmt, nnkEmpty:
discard
else:
assert false
if traversalStack.len == 0: break

4
std_shims/objects.nim Normal file
View File

@ -0,0 +1,4 @@
template init*(lvalue: var auto, args: varargs[typed]) =
mixin init
lvalue = init(type(lvalue), args)