Skip to content

[fork-ffi] integers: fromNumberImpl — fromNumber must return Nothing when the Number is not an integer or… #85

@Unisay

Description

@Unisay

Package: purescript-lua-integers
File: src/Data/Int.lua
Function: fromNumberImpl
Class: semantics Severity: high

fromNumber must return Nothing when the Number is not an integer or falls outside the Int32 range. The upstream JS is return (n | 0) === n ? just(n) : nothing; — it truncates to Int32 and only returns Just when the value is unchanged. The Lua version computes math.modf(n) (which discards the fractional part) and ALWAYS returns just(i), so it never returns Nothing. This breaks the package's own tests: fromNumber 0.9 == Nothing and fromNumber (-0.9) == Nothing (Test/Data/Int.purs lines 22-23) — the Lua returns Just 0. Out-of-range inputs (e.g. 2147483648.0) also wrongly yield Just instead of Nothing.

Current (Lua):

fromNumberImpl = (function(just)
  return function(nothing)
    return function(n)
      local i = math.modf(n)
      return just(i)
    end
  end
end),

Expected: Nothing for any non-integral Number (fromNumber 0.9 == Nothing) and for any value outside [-2147483648, 2147483647]; Just n only when n is an integer within Int32 range.

Proposed fix:

return function(n)
  local i = math.modf(n)
  if i == n and n >= -2147483648 and n <= 2147483647 then
    return just(n)
  end
  return nothing
end

Found by the FFI audit; reproduced under Lua 5.1.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions