Skip to content

[fork-ffi] arrays: traverse1Impl — Faulty JS->Lua translation of the new ConsCell(...) / `new… #73

@Unisay

Description

@Unisay

Package: purescript-lua-arrays
File: src/Data/Array/NonEmpty/Internal.lua
Function: traverse1Impl
Class: semantics Severity: high

Faulty JS->Lua translation of the new ConsCell(...) / new Cont(...) constructor pattern. In JS these are invoked with new, so each returns a freshly-allocated object. The Lua port rewrote them as functions taking an explicit this first parameter (Cont(this, fn), ConsCell(this, head, tail)) that mutate this and return nil, but the call sites still call them with the data arguments only -- e.g. finalCell(head) calls ConsCell(head, emptyList), so this = the head element and this.head = ... errors. consList(x)(xs) calls ConsCell(x, xs) and go returns Cont(function() ... end), all likewise broken. The function errors on its very first real invocation. Confirmed under Lua 5.1: attempt to index local 'this' (a number value) at the this.head = head line. This breaks traverse1/sequence1 for NonEmptyArray entirely.

Current (Lua):

local function Cont(this, fn) this.fn = fn end
local function ConsCell(this, head, tail)
  this.head = head
  this.tail = tail
end
local function finalCell(head) return ConsCell(head, emptyList) end
local function consList(x) return function(xs) return ConsCell(x, xs) end end
...
return Cont(function() return go(buildFrom(last, acc), currentLen - 1, xs) end)

Expected: JS uses new, so the constructors allocate and return objects: finalCell(h) => {head=h, tail=emptyList}; consList(x)(xs) => {head=x, tail=xs}; go returns a Cont wrapper {fn=...}. traverse1Impl(apply,map,f)(array) must thread these cells through and produce the reversed-then-listToArray result. With Identity-style apply/map and f=(*10), traverse1Impl(...)({1,2,3}) must yield {10,20,30}.

Proposed fix:

Make the constructors return tables instead of mutating a phantom `this`:
  local function Cont(fn) return {fn = fn} end
  local function ConsCell(head, tail) return {head = head, tail = tail} end
The existing call sites (finalCell, consList, the `Cont(function() ... end)` in `go`) then work unchanged. Verified under Lua 5.1: yields {10,20,30}.

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