jsonnet icon indicating copy to clipboard operation
jsonnet copied to clipboard

max stack frame exceeded when foldl with object/array as accumulated value

Open bigdrum opened this issue 3 years ago • 1 comments

The following code would fail (i know this is not meaningful, but just act as a reduced example)

std.foldl(function(p, c) [p[0]+1, c], std.range(0, 2000), [0, 0])

Output:

Error: RUNTIME ERROR: max stack frames exceeded.

I thought this was due to lack of tail recursion optimization, but that's not the case if the accumulated value is a string. Hence the following code is fine by writing a new foldl wrapper (workaround, so accumulated value is a string instead)

local foldl(f, arr, init) =
  std.parseJson(std.foldl(function(p, curr)
    std.manifestJson(f(std.parseJson(p), curr))
                          , arr, std.manifestJson(init)));

foldl(function(p, c) [p[0]+1, c], std.range(0, 2000), [0, 0])

Output:

[
  2001,
  2000
]

I found this problem as I was trying to using jsonnet to solve advent of code (https://gist.github.com/bigdrum/1980304abc6561d01f12dad50aa73538). But I would not be surprised if this happens in real world usage.

bigdrum avatar Dec 02 '21 14:12 bigdrum

Yeah, this is a major issue. You can increase the stack trace size manually, but foldl and foldr should just work...

sbarzowski avatar Dec 12 '21 17:12 sbarzowski