Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

repr_v2 improvements #14992

Merged
merged 3 commits into from
Jul 15, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 28 additions & 10 deletions lib/system/repr_v2.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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 & '\''

proc repr*(x: cstring): string {.noSideEffect.} =
## repr for a CString argument. Returns `x`
## converted to a quoted string.
'"' & $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: 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
Expand All @@ -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))

Expand Down
6 changes: 6 additions & 0 deletions tests/arc/trepr.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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