tdont_mutate.nim 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. discard """
  2. cmd: "nim check --hints:off $file"
  3. """
  4. import tables
  5. {.experimental: "views".}
  6. const
  7. Whitespace = {' ', '\t', '\n', '\r'}
  8. proc split*(s: string, seps: set[char] = Whitespace, maxsplit: int = -1): Table[int, openArray[char]] #[tt.Error
  9. ^ 'result' borrows from the immutable location 's' and attempts to mutate it
  10. ]# =
  11. var last = 0
  12. var splits = maxsplit
  13. result = initTable[int, openArray[char]]()
  14. while last <= len(s):
  15. var first = last
  16. while last < len(s) and s[last] notin seps:
  17. inc(last)
  18. if splits == 0: last = len(s)
  19. result[first] = toOpenArray(s, first, last-1)
  20. result[first][0] = 'c'
  21. if splits == 0: break
  22. dec(splits)
  23. inc(last)
  24. proc `$`(x: openArray[char]): string =
  25. result = newString(x.len)
  26. for i in 0..<x.len: result[i] = x[i]
  27. proc otherTest(x: int) =
  28. var y: var int = x #[tt.Error
  29. ^ 'y' borrows from the immutable location 'x' and attempts to mutate it
  30. ]#
  31. y = 3
  32. proc main() =
  33. let words = split("asdf 231")
  34. for i, x in words:
  35. echo i, ": ", x
  36. main()
  37. # This has to continue to work:
  38. type
  39. PNode = ref object
  40. TSrcGen = object
  41. comStack: seq[PNode]
  42. proc pushCom(g: var TSrcGen, n: PNode) =
  43. setLen(g.comStack, g.comStack.len + 1)
  44. g.comStack[^1] = n