formatoptimizer.nim 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. ## This is the example that optimizes a modified "hello world"
  2. import macros
  3. proc invalidFormatString() =
  4. echo "invalidFormatString"
  5. template formatImpl(handleChar: untyped) =
  6. var i = 0
  7. while i < f.len:
  8. if f[i] == '$':
  9. case f[i+1]
  10. of '1'..'9':
  11. var j = 0
  12. i += 1
  13. while f[i] in {'0'..'9'}:
  14. j = j * 10 + ord(f[i]) - ord('0')
  15. i += 1
  16. result.add(a[j-1])
  17. else:
  18. invalidFormatString()
  19. else:
  20. result.add(handleChar(f[i]))
  21. i += 1
  22. proc `%`*(f: string, a: openArray[string]): string =
  23. template identity(x: untyped): untyped = x
  24. result = ""
  25. formatImpl(identity)
  26. macro optFormat{`%`(f, a)}(f: string{lit}, a: openArray[string]): untyped =
  27. result = newNimNode(nnkBracket)
  28. #newCall("&")
  29. let f = f.strVal
  30. formatImpl(newLit)
  31. result = nestList(newIdentNode("&"), result)
  32. template optAdd1{x = y; add(x, z)}(x, y, z: string) =
  33. x = y & z
  34. #template optAdd2{x.add(y); x.add(z)}(x, y, z: string) =
  35. # x.add(y & z)
  36. proc `/&` [T: object](x: T): string =
  37. result = "("
  38. for name, value in fieldPairs(x):
  39. result.add("$1: $2\n" % [name, $value])
  40. result.add(")")
  41. type
  42. MyObject = object
  43. a, b: int
  44. s: string
  45. let obj = MyObject(a: 3, b: 4, s: "abc")
  46. echo(/&obj)