miscdollars.nim 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. when defined(nimHasIsNamedTuple):
  15. proc isNamedTuple(T: typedesc): bool {.magic: "TypeTrait".}
  16. else:
  17. # for bootstrap; remove after release 1.2
  18. proc isNamedTuple(T: typedesc): bool =
  19. # Taken from typetraits.
  20. when T isnot tuple: result = false
  21. else:
  22. var t: T
  23. for name, _ in t.fieldPairs:
  24. when name == "Field0":
  25. return compiles(t.Field0)
  26. else:
  27. return true
  28. return false
  29. template tupleObjectDollar*[T: tuple | object](result: var string, x: T) =
  30. result = "("
  31. const isNamed = T is object or isNamedTuple(typeof(T))
  32. var count {.used.} = 0
  33. for name, value in fieldPairs(x):
  34. if count > 0: result.add(", ")
  35. when isNamed:
  36. result.add(name)
  37. result.add(": ")
  38. count.inc
  39. when compiles($value):
  40. when value isnot string and value isnot seq and compiles(value.isNil):
  41. if value.isNil: result.add "nil"
  42. else: result.addQuoted(value)
  43. else:
  44. result.addQuoted(value)
  45. else:
  46. result.add("...")
  47. when not isNamed:
  48. if count == 1:
  49. result.add(",") # $(1,) should print as the semantically legal (1,)
  50. result.add(")")