refactor system.$ for objects a little; refs #13398

This commit is contained in:
Araq 2020-04-20 10:33:07 +02:00 • committed by Andreas Rumpf
commit 17f222613a

View file

@ -75,17 +75,13 @@ proc `$`*[T: tuple|object](x: T): string =
## $(a: 23, b: 45) == "(a: 23, b: 45)" ## $(a: 23, b: 45) == "(a: 23, b: 45)"
## $() == "()" ## $() == "()"
result = "(" result = "("
# when x is empty, this gives an unused warning
var firstElement {.used.} = true
const isNamed = T is object or isNamedTuple(T) const isNamed = T is object or isNamedTuple(T)
when not isNamed:
var count = 0 var count = 0
for name, value in fieldPairs(x): for name, value in fieldPairs(x):
if not firstElement: result.add(", ") if count > 0: result.add(", ")
when isNamed: when isNamed:
result.add(name) result.add(name)
result.add(": ") result.add(": ")
else:
count.inc count.inc
when compiles($value): when compiles($value):
when value isnot string and value isnot seq and compiles(value.isNil): when value isnot string and value isnot seq and compiles(value.isNil):
@ -93,10 +89,8 @@ proc `$`*[T: tuple|object](x: T): string =
else: result.addQuoted(value) else: result.addQuoted(value)
else: else:
result.addQuoted(value) result.addQuoted(value)
firstElement = false
else: else:
result.add("...") result.add("...")
firstElement = false
when not isNamed: when not isNamed:
if count == 1: if count == 1:
result.add(",") # $(1,) should print as the semantically legal (1,) result.add(",") # $(1,) should print as the semantically legal (1,)