nim-lang / Nim

Nim is a statically typed compiled systems programming language. It combines successful concepts from mature languages like Python, Ada and Modula. Its design focuses on efficiency, expressiveness, and elegance (in that order of priority).
https://nim-lang.org
Other
16.64k stars 1.47k forks source link

repr doesn't handle control chars correctly, eg `repr("abc\ndef")` #17747

Open timotheecour opened 3 years ago

timotheecour commented 3 years ago

Example

when true:
  let a = "abc\ndef"
  echo a.repr

Current Output

--gc:refc 0x10b0de060"abc\10" "def"

--gc:arc

"abc\n def"

Expected Output

"abc\ndef"

(with or without hex prefix, that's a separate issue, see https://github.com/nim-lang/Nim/issues/16052)

which is what this gives:

when true:
  import std/sugar
  let a = "abc\ndef"
  echo "".dup(addQuoted(a))

Possible Solution

reuse addQuoted

Additional Information

1.5.1 957478ce264d0496f9a0c33de4af77ad0846b42d originally reported in https://forum.nim-lang.org/t/7799#49565

ringabout commented 3 years ago

It seems to be an intended behaviour:

proc reprStrAux(result: var string, s: cstring; len: int) =
  if cast[pointer](s) == nil:
    add result, "nil"
    return
  if len > 0:
    add result, reprPointer(cast[pointer](s))
  add result, "\""
  for i in 0 .. pred(len):
    let c = s[i]
    case c
    of '"': add result, "\\\""
    of '\\': add result, "\\\\" # BUGFIX: forgotten
    of '\10': add result, "\\10\"\n\"" # " \n " # better readability
    of '\127' .. '\255', '\0'..'\9', '\11'..'\31':
      add result, "\\" & reprInt(ord(c))
    else:
      result.add(c)
  add result, "\""
timotheecour commented 3 years ago

even if it was intentional, it doesn't make much sense and is surprising; it should just behave like addQuoted.

Clyybber commented 3 years ago

IMO the behaviour with arc is a good one and improves readability.

timotheecour commented 3 years ago

0x10b0de060"abc\10" "def" => 0x10b0de060"abc\n def"