toverflw.nim 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. discard """
  2. output: "ok"
  3. cmd: "nim $target --overflowChecks:off $options $file"
  4. """
  5. # Tests nim's ability to detect overflows
  6. {.push overflowChecks: on.}
  7. var
  8. a = high(int)
  9. b = -2
  10. overflowDetected = false
  11. try:
  12. writeLine(stdout, b - a)
  13. except OverflowDefect:
  14. overflowDetected = true
  15. {.pop.} # overflow check
  16. doAssert(overflowDetected)
  17. block: # Overflow checks in a proc
  18. var
  19. a = high(int)
  20. b = -2
  21. overflowDetected = false
  22. {.push overflowChecks: on.}
  23. proc foo() =
  24. let c = b - a
  25. {.pop.}
  26. try:
  27. foo()
  28. except OverflowDefect:
  29. overflowDetected = true
  30. doAssert(overflowDetected)
  31. block: # Overflow checks in a forward declared proc
  32. var
  33. a = high(int)
  34. b = -2
  35. overflowDetected = false
  36. proc foo()
  37. {.push overflowChecks: on.}
  38. proc foo() =
  39. let c = b - a
  40. {.pop.}
  41. try:
  42. foo()
  43. except OverflowDefect:
  44. overflowDetected = true
  45. doAssert(overflowDetected)
  46. block: # Overflow checks doesn't affect fwd declaration
  47. var
  48. a = high(int)
  49. b = -2
  50. overflowDetected = false
  51. {.push overflowChecks: on.}
  52. proc foo()
  53. {.pop.}
  54. proc foo() =
  55. let c = b - a
  56. try:
  57. foo()
  58. except OverflowDefect:
  59. overflowDetected = true
  60. doAssert(not overflowDetected)
  61. echo "ok"