repr_v2.nim 5.4 KB

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