vmconv.nim 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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 seq:
  29. result = newNode(nkBracket)
  30. for ai in a:
  31. result.add toLit(ai)
  32. elif T is object:
  33. result = newTree(nkObjConstr)
  34. result.add(newNode(nkEmpty))
  35. for k, ai in fieldPairs(a):
  36. let reti = newNode(nkExprColonExpr)
  37. reti.add k.toLit
  38. reti.add ai.toLit
  39. result.add reti
  40. else:
  41. static: doAssert false, "not yet supported: " & $T # add as needed