miscdollars.nim 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. from std/private/digitsutils import addInt
  2. template toLocation*(result: var string, file: string | cstring, line: int, col: int) =
  3. ## avoids spurious allocations
  4. # Hopefully this can be re-used everywhere so that if a user needs to customize,
  5. # it can be done in a single place.
  6. result.add file
  7. if line > 0:
  8. result.add "("
  9. addInt(result, line)
  10. if col > 0:
  11. result.add ", "
  12. addInt(result, col)
  13. result.add ")"
  14. proc isNamedTuple(T: typedesc): bool {.magic: "TypeTrait".}
  15. template tupleObjectDollar*[T: tuple | object](result: var string, x: T) =
  16. result = "("
  17. const isNamed = T is object or isNamedTuple(typeof(T))
  18. var count {.used.} = 0
  19. for name, value in fieldPairs(x):
  20. if count > 0: result.add(", ")
  21. when isNamed:
  22. result.add(name)
  23. result.add(": ")
  24. count.inc
  25. when compiles($value):
  26. when value isnot string and value isnot seq and compiles(value.isNil):
  27. if value.isNil: result.add "nil"
  28. else: result.addQuoted(value)
  29. else:
  30. result.addQuoted(value)
  31. else:
  32. result.add("...")
  33. when not isNamed:
  34. if count == 1:
  35. result.add(",") # $(1,) should print as the semantically legal (1,)
  36. result.add(")")