summary refs log tree commit diff stats
path: root/lib/system
diff options
context:
space:
mode:
authorClyybber <darkmine956@gmail.com>2020-07-15 22:04:15 +0200
committerGitHub <noreply@github.com>2020-07-15 22:04:15 +0200
commit813dd1b670b953b0ac8348b04079faadace46c29 (patch)
tree2198193cf11c1f8fb4bc379c6cd8ceaa2b79b268 /lib/system
parente057b1d8395f4d639e195bc8f6a7e6922c149201 (diff)
downloadNim-813dd1b670b953b0ac8348b04079faadace46c29.tar.gz
repr_v2 improvements (#14992)
* Support proc in arc repr

* Typo

* Improve repr for strings and chars
Diffstat (limited to 'lib/system')
-rw-r--r--lib/system/repr_v2.nim38
1 files changed, 28 insertions, 10 deletions
diff --git a/lib/system/repr_v2.nim b/lib/system/repr_v2.nim
index fcc187a42..d456f4454 100644
--- a/lib/system/repr_v2.nim
+++ b/lib/system/repr_v2.nim
@@ -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
@@ -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))