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.54k stars 1.47k forks source link

Incorrect int64 overflow with JS backend #6752

Closed GULPF closed 1 year ago

GULPF commented 6 years ago

Test case:

proc foo() =
    let x = 711127'i64
    let y = x * 86400'i64 # Overflow with js backend, but not with other backends
foo()
Araq commented 6 years ago

Seems correct to me, on JS int is 32bits and 61_441_372_800 doesn't fit in 32 bits.

GULPF commented 6 years ago

You're correct, but there still seems to be an issue somewhere.

This works (but shouldn't?):

import typetraits
let x = 711127
let y = x * 86400
doAssert type(y).name == "int"
doAssert y > high(int)

This works (and should?):

import typetraits
let x = 711127'i64
doAssert type(x * 86400'i64).name == "int64"
let y = x * 86400'i64

This doesn't work (but should?):

import typetraits
proc foo() =
    let x = 711127'i64
    doAssert type(x * 86400'i64).name == "int64"
    let y = x * 86400'i64 # Overflow
foo()
skilchen commented 6 years ago

As @Araq told us in another context JS has only float64 numbers. Unless you are using bitwise operations. Then the float64 numbers are indeed handled as int32. So as long as you don't use bitwise operations, i think it is safe to turn of this overflow check off, if you keep in mind that you have only 53 bits of precision available to represent integers exactly in float64 numbers. You can have something like int53 in JS but not really int64.

littleli commented 5 years ago

I think this specification should be mentioned here for completeness along with other references.

  1. BigInt proposal
  2. BigInt: arbitrary-precision integers in JavaScript
  3. BigInt availability in browsers

I'm aware this is arbitrary precision land. This likely means less performant arithmetics, but modern javascript runtimes don't fear of change runtime representation of numbers for sake of performance.

BigInts are supported in Chrome from version 67, Nodejs with recent v8 and I know that Nodejs implementation in Graalvm distribution also supports BigInts.

stale[bot] commented 4 years ago

This issue has been automatically marked as stale because it has not had recent activity. If you think it is still a valid issue, write a comment below; otherwise it will be closed. Thank you for your contributions.