vmconv.nim 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import ast
  2. template elementType*(T: typedesc): typedesc =
  3. typeof(block:
  4. var a: T
  5. for ai in a: ai)
  6. proc fromLit*(a: PNode, T: typedesc): auto =
  7. ## generic PNode => type
  8. ## see also reverse operation `toLit`
  9. when T is set:
  10. result = default(T)
  11. type Ti = elementType(T)
  12. for ai in a:
  13. result.incl Ti(ai.intVal)
  14. else:
  15. static: doAssert false, "not yet supported: " & $T # add as needed
  16. proc toLit*[T](a: T): PNode =
  17. ## generic type => PNode
  18. ## see also reverse operation `fromLit`
  19. when T is string: newStrNode(nkStrLit, a)
  20. elif T is Ordinal: newIntNode(nkIntLit, a.ord)
  21. elif T is (proc): newNode(nkNilLit)
  22. elif T is ref:
  23. if a == nil: newNode(nkNilLit)
  24. else: toLit(a[])
  25. elif T is tuple:
  26. result = newTree(nkTupleConstr)
  27. for ai in fields(a): result.add toLit(ai)
  28. elif T is object:
  29. result = newTree(nkObjConstr)
  30. result.add(newNode(nkEmpty))
  31. for k, ai in fieldPairs(a):
  32. let reti = newNode(nkExprColonExpr)
  33. reti.add k.toLit
  34. reti.add ai.toLit
  35. result.add reti
  36. else:
  37. static: doAssert false, "not yet supported: " & $T # add as needed