Skip to content

FFI functions returning Int64/UInt64 are not properly converted from JavaScript numbers #914

@BIYUEHU

Description

@BIYUEHU

When using FFI to bind JavaScript functions that return numbers, the returned values are not properly converted to MoonBit's Int64/UInt64 types. Instead of performing the necessary conversion to the {hi, lo} object representation, the raw JavaScript number is passed through, causing incorrect behavior in MoonBit code. Reproducing Steps:

  1. Define an FFI function that returns Int64 from a JavaScript function returning a number
  2. Call the function and print the result using MoonBit's println
  3. Compare with the same function returning Int type

Code

  • Target: js
// FFI function returning Int64 - problematic
pub extern "js" fn p(s : String) -> Int64 = "parseInt"

// FFI function returning Int - works correctly  
pub extern "js" fn p1(s : String) -> Int = "parseInt"

fn main {
  // These should print the same values but don't
  println(p1("123"))        // Correctly prints: 123
  println(p("123"))         // Incorrectly prints: 0 (or garbage)
  
  // More examples showing the issue
  println(p1("122222222223"))   // Correctly prints: 122222222223 (if within Int range)
  println(p("122222222223"))    // Incorrectly prints: 0
}

Environment

  • OS: Windows
  • OS distribution and/or version: Windows11
  • CPU Architecture: x86_64
moon 0.1.20250724 (2797252 2025-07-24) D:\Languages\moon\bin\moon.exe
moonc v0.6.22 D:\Languages\moon\bin\moonc.exe
moonrun 0.1.20250724 (2797252 2025-07-24) D:\Languages\moon\bin\moonrun.exe

Error output

The generated JavaScript shows the issue clearly:

// FFI functions - both call parseInt directly
const himeno$kana$45$rhythm$main$$p = (s)=>parseInt(s);   // Should return Int64 {hi, lo}
const himeno$kana$45$rhythm$main$$p1 = (s)=>parseInt(s);  // Returns Int (number)

// Int64 is represented as {hi, lo} object internally
const $0L = { hi: 0, lo: 0 };

// The problem: parseInt returns a JavaScript number, but MoonBit expects {hi, lo}
// No automatic conversion happens, leading to type mismatch

Console output shows incorrect values for Int64 functions while Int functions work correctly. Expected Behavior: FFI functions declared to return Int64/UInt64 should automatically convert JavaScript numbers to the appropriate {hi, lo} object representation, similar to how moonbitlang$core$builtin$$MyInt64$from_int works internally.

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions