repr_v2.nim 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. include system/inclrtl
  2. when defined(nimPreviewSlimSystem):
  3. import std/formatfloat
  4. proc isNamedTuple(T: typedesc): bool {.magic: "TypeTrait".}
  5. ## imported from typetraits
  6. proc distinctBase(T: typedesc, recursive: static bool = true): typedesc {.magic: "TypeTrait".}
  7. ## imported from typetraits
  8. proc rangeBase(T: typedesc): typedesc {.magic: "TypeTrait".}
  9. # skip one level of range; return the base type of a range type
  10. proc repr*(x: NimNode): string {.magic: "Repr", noSideEffect.}
  11. proc repr*(x: int): string =
  12. ## Same as $x
  13. $x
  14. proc repr*(x: int64): string =
  15. ## Same as $x
  16. $x
  17. proc repr*(x: uint64): string {.noSideEffect.} =
  18. ## Same as $x
  19. $x
  20. proc repr*(x: float): string =
  21. ## Same as $x
  22. $x
  23. proc repr*(x: bool): string {.magic: "BoolToStr", noSideEffect.}
  24. ## repr for a boolean argument. Returns `x`
  25. ## converted to the string "false" or "true".
  26. proc repr*(x: char): string {.noSideEffect, raises: [].} =
  27. ## repr for a character argument. Returns `x`
  28. ## converted to an escaped string.
  29. ##
  30. ## .. code-block:: Nim
  31. ## assert repr('c') == "'c'"
  32. result.add '\''
  33. # Elides string creations if not needed
  34. if x in {'\\', '\0'..'\31', '\127'..'\255'}:
  35. result.add '\\'
  36. if x in {'\0'..'\31', '\127'..'\255'}:
  37. result.add $x.uint8
  38. else:
  39. result.add x
  40. result.add '\''
  41. proc repr*(x: string | cstring): string {.noSideEffect, raises: [].} =
  42. ## repr for a string argument. Returns `x`
  43. ## converted to a quoted and escaped string.
  44. result.add '\"'
  45. for i in 0..<x.len:
  46. if x[i] in {'"', '\\', '\0'..'\31', '\127'..'\255'}:
  47. result.add '\\'
  48. case x[i]:
  49. of '\n':
  50. result.add "n\n"
  51. of '\0'..'\9', '\11'..'\31', '\127'..'\255':
  52. result.add $x[i].uint8
  53. else:
  54. result.add x[i]
  55. result.add '\"'
  56. proc repr*[Enum: enum](x: Enum): string {.magic: "EnumToStr", noSideEffect, raises: [].}
  57. ## repr for an enumeration argument. This works for
  58. ## any enumeration type thanks to compiler magic.
  59. ##
  60. ## If a `repr` operator for a concrete enumeration is provided, this is
  61. ## used instead. (In other words: *Overwriting* is possible.)
  62. proc reprDiscriminant*(e: int): string {.compilerproc.} =
  63. # repr and reprjs can use `PNimType` to symbolize `e`; making this work here
  64. # would require a way to pass the set of enum stringified values to cgen.
  65. $e
  66. proc repr*(p: pointer): string =
  67. ## repr of pointer as its hexadecimal value
  68. if p == nil:
  69. result = "nil"
  70. else:
  71. when nimvm:
  72. result = "ptr"
  73. else:
  74. const HexChars = "0123456789ABCDEF"
  75. const len = sizeof(pointer) * 2
  76. var n = cast[uint](p)
  77. result = newString(len)
  78. for j in countdown(len-1, 0):
  79. result[j] = HexChars[n and 0xF]
  80. n = n shr 4
  81. proc repr*(p: proc | iterator {.closure.}): string =
  82. ## repr of a proc as its address
  83. repr(cast[ptr pointer](unsafeAddr p)[])
  84. template repr*[T: distinct|(range and not enum)](x: T): string =
  85. when T is range: # add a branch to handle range
  86. repr(rangeBase(typeof(x))(x))
  87. elif T is distinct:
  88. repr(distinctBase(typeof(x))(x))
  89. else:
  90. {.error: "cannot happen".}
  91. template repr*(t: typedesc): string = $t
  92. proc reprObject[T: tuple|object](res: var string, x: T) {.noSideEffect, raises: [].} =
  93. res.add '('
  94. var firstElement = true
  95. const isNamed = T is object or isNamedTuple(T)
  96. when not isNamed:
  97. var count = 0
  98. for name, value in fieldPairs(x):
  99. if not firstElement: res.add(", ")
  100. when isNamed:
  101. res.add(name)
  102. res.add(": ")
  103. else:
  104. count.inc
  105. res.add repr(value)
  106. firstElement = false
  107. when not isNamed:
  108. if count == 1:
  109. res.add(',') # $(1,) should print as the semantically legal (1,)
  110. res.add(')')
  111. proc repr*[T: tuple|object](x: T): string {.noSideEffect, raises: [].} =
  112. ## Generic `repr` operator for tuples that is lifted from the components
  113. ## of `x`. Example:
  114. ##
  115. ## .. code-block:: Nim
  116. ## $(23, 45) == "(23, 45)"
  117. ## $(a: 23, b: 45) == "(a: 23, b: 45)"
  118. ## $() == "()"
  119. when T is object:
  120. result = $typeof(x)
  121. reprObject(result, x)
  122. proc repr*[T](x: ref T | ptr T): string {.noSideEffect, raises: [].} =
  123. if isNil(x): return "nil"
  124. when T is object:
  125. result = $typeof(x)
  126. reprObject(result, x[])
  127. else:
  128. result = when typeof(x) is ref: "ref " else: "ptr "
  129. result.add repr(x[])
  130. proc collectionToRepr[T](x: T, prefix, separator, suffix: string): string {.noSideEffect, raises: [].} =
  131. result = prefix
  132. var firstElement = true
  133. for value in items(x):
  134. if firstElement:
  135. firstElement = false
  136. else:
  137. result.add(separator)
  138. result.add repr(value)
  139. result.add(suffix)
  140. proc repr*[T](x: set[T]): string =
  141. ## Generic `repr` operator for sets that is lifted from the components
  142. ## of `x`. Example:
  143. ##
  144. ## .. code-block:: Nim
  145. ## ${23, 45} == "{23, 45}"
  146. collectionToRepr(x, "{", ", ", "}")
  147. proc repr*[T](x: seq[T]): string =
  148. ## Generic `repr` operator for seqs that is lifted from the components
  149. ## of `x`. Example:
  150. ##
  151. ## .. code-block:: Nim
  152. ## $(@[23, 45]) == "@[23, 45]"
  153. collectionToRepr(x, "@[", ", ", "]")
  154. proc repr*[T, IDX](x: array[IDX, T]): string =
  155. ## Generic `repr` operator for arrays that is lifted from the components.
  156. collectionToRepr(x, "[", ", ", "]")
  157. proc repr*[T](x: openArray[T]): string =
  158. ## Generic `repr` operator for openarrays that is lifted from the components
  159. ## of `x`. Example:
  160. ##
  161. ## .. code-block:: Nim
  162. ## $(@[23, 45].toOpenArray(0, 1)) == "[23, 45]"
  163. collectionToRepr(x, "[", ", ", "]")
  164. proc repr*[T](x: UncheckedArray[T]): string =
  165. "[...]"