repr_v2 improvements (#14992)

* Support proc in arc repr

* Typo

* Improve repr for strings and chars
This commit is contained in:
Clyybber
2020-07-15 22:04:15 +02:00
committed by GitHub
parent e057b1d839
commit 813dd1b670
2 changed files with 34 additions and 10 deletions

View File

@@ -29,21 +29,35 @@ proc repr*(x: bool): string {.magic: "BoolToStr", noSideEffect.}
proc repr*(x: char): string {.noSideEffect.} =
## repr for a character argument. Returns `x`
## converted to a string.
## converted to an escaped string.
##
## .. code-block:: Nim
## assert repr('c') == "'c'"
'\'' & $x & '\''
result.add '\''
# Elides string creations if not needed
if x in {'\\', '\0'..'\31', '\127'..'\255'}:
result.add '\\'
if x in {'\0'..'\31', '\127'..'\255'}:
result.add $x.uint8
else:
result.add x
result.add '\''
proc repr*(x: cstring): string {.noSideEffect.} =
## repr for a CString argument. Returns `x`
## converted to a quoted string.
'"' & $x & '"'
proc repr*(x: string): string {.noSideEffect.} =
proc repr*(x: string | cstring): string {.noSideEffect.} =
## repr for a string argument. Returns `x`
## but quoted.
'"' & x & '"'
## converted to a quoted and escaped string.
result.add '\"'
for i in 0..<x.len:
if x[i] in {'"', '\\', '\0'..'\31', '\127'..'\255'}:
result.add '\\'
case x[i]:
of '\n':
result.add "n\n"
of '\0'..'\9', '\11'..'\31', '\127'..'\255':
result.add $x[i].uint8
else:
result.add x[i]
result.add '\"'
proc repr*[Enum: enum](x: Enum): string {.magic: "EnumToStr", noSideEffect.}
## repr for an enumeration argument. This works for
@@ -68,6 +82,10 @@ proc repr*(p: pointer): string =
result[j] = HexChars[n and 0xF]
n = n shr 4
proc repr*(p: proc): string =
## repr of a proc as its address
repr(cast[pointer](p))
template repr*(x: distinct): string =
repr(distinctBase(typeof(x))(x))

View File

@@ -62,3 +62,9 @@ var c2 = new tuple[member: ref seq[string]]
c2.member = new seq[string]
c2.member[] = @["hello"]
echo c2.repr
proc p2 =
echo "hey"
discard repr p2