Skip to content

A user function's return type, an untyped parameter or an untyped local that holds an array, a matrix, a UDT or a string is typed double: ten valid v6 forms whose C++ does not compile #391

Closed

Description

@letiep97

Summary

In Pine v6 a user function's result takes the type of its last expression, and a function parameter, or a local declared with =, takes its type from what it receives. In the ten forms below Codegen 1.12.0 types the C++ return value, parameter or local as double although it holds an array, a matrix, a UDT or a string, and the generated C++ does not compile. Each has a control that differs in one place and builds.

# Group Form Generated signature or declaration C++ error
1 A the function's last statement is an if … else block whose branches end with an array<float> double firstN(std::vector<double>& src, int n) assigning to 'double' from incompatible type 'std::vector<double>' on _func_ret = out;
2 A the same with a UDT in both branches double _func_ret = 0.0; in calc assigning to 'double' from incompatible type 'Stats'
3 A the body is a ternary of two array<float> parameters: k == 0 ? a : b double pickArr(int k, std::vector<double>& a, std::vector<double>& b) no viable conversion from returned value of type 'std::vector<double>' to function return type 'double'
4 A the function returns a typed array<float> local, and reads a global series with [shift] from its parameter, so it is generated once per call site double features_cs0(int shift), double features_cs1(int shift) the same error in the per-call-site copies
5 A untyped parameter s, body parts.size() > 1 ? parts.get(1) : s, called with a string variable double tail(std::string s) no viable conversion from returned value of type 'std::string' to function return type 'double'
6 B an array passed through two untyped parameters: avgOf(arr) => sumOf(arr) / arr.size() double avgOf(std::vector<double>& arr) but double sumOf(double arr) member reference base type 'double' is not a structure or union
7 B arrays taken from a tuple ([ups, dns] = make()) passed to an untyped parameter double lastOf(double x, double y, bool useX) invalid range expression of type 'double'
8 B one untyped parameter called with an array<int> and with an array<float> only double trim(std::vector<int>& arr, int maxSize) non-const lvalue reference to type 'vector<int>' cannot bind to a value of unrelated type 'vector<double>'
9 B a string passed through two untyped parameters double sessionStart(std::string startStr) but std::tuple<int, int> hm(double txt) no viable conversion from 'std::string' to 'double'
10 B an untyped local tmp = matrix.copy(state), later reassigned with tmp := step(tmp) where step returns a matrix double tmp = 0.0; assigning to 'double' from incompatible type 'NumericMatrix'

A. The return type of a user function (cases 1 to 5). In case 4 the control, which does not read history through the parameter, is generated once as std::vector<double> features(int shift). In case 5 the parameter itself is typed std::string; only the return type is wrong, and the same call with a string literal builds. The ternary of strings with na fixed in 1.10.0 (#281 case 2) builds too.

B. An untyped parameter or local (cases 6 to 10). In cases 6 and 9 the outer function is typed from its call site; the inner function, called with the outer function's parameter, is not. In case 7 the tuple elements themselves are declared std::vector<double>; only the parameter that receives them is double. In case 8 the parameter gets one type for both calls. Case 10 builds when the local is not reassigned.

Related, not the same: #372 case 1 covered an untyped parameter read with [] whose argument comes from the caller's untyped parameter. That one was refused at analysis and is fixed in 1.12.0; these translate and fail in C++.

Versions

pineforge-codegen 1.12.0 with pineforge-engine v1.12.0 (6e27d0f2). Apple clang 17.0.0, macOS 15.8 arm64. BTCUSDT 1h bars from 2024-01-01 to 2024-03-01 (1,441 bars), initial capital 10000, no commission or slippage.

TradingView: BINANCE:BTCUSDT, 1h, Deep Backtesting over the same dates, measured on 2026-11-14: the ten scripts and their controls save without error and give the same 26 trades (the last one still open at the end of the range), net profit 29.93, as the controls on PineForge.

Reproduction

Every control builds and runs on PineForge with 26 trades and net profit 29.93.

1. if … else returning an array

//@version=6
strategy("array returned from an if-else", overlay = true, initial_capital = 10000)
fast = ta.ema(close, 10)
slow = ta.ema(close, 30)
firstN(array<float> src, int n) =>
    array<float> out = array.new<float>()
    if src.size() == 0
        out
    else
        for i = 0 to math.min(n, src.size()) - 1
            out.push(src.get(i))
        out
var vals = array.new<float>()
vals.unshift(close)
if vals.size() > 20
    vals.pop()
array<float> top = firstN(vals, 3)
plot(top.size() > 0 ? top.get(0) : na)
if ta.crossover(fast, slow)
    strategy.entry("Long", strategy.long, qty = 0.01)
if ta.crossunder(fast, slow)
    strategy.close("Long")
error: assigning to 'double' from incompatible type 'std::vector<double>'
    _func_ret = out;

Control: the block is if src.size() > 0 (no else) followed by out as the last line.

2. if … else returning a UDT

//@version=6
strategy("UDT returned from an if-else", overlay = true, initial_capital = 10000)
fast = ta.ema(close, 10)
slow = ta.ema(close, 30)
type Stats
    float lo = na
    float hi = na
calc(int len) =>
    Stats s = Stats.new()
    if bar_index < len
        s
    else
        s.lo := ta.lowest(low, len)
        s.hi := ta.highest(high, len)
        s
Stats st = calc(20)
plot(st.hi)
if ta.crossover(fast, slow)
    strategy.entry("Long", strategy.long, qty = 0.01)
if ta.crossunder(fast, slow)
    strategy.close("Long")
error: assigning to 'double' from incompatible type 'Stats'

Control: if bar_index >= len with the two assignments, then s as the last line.

3. Ternary of two arrays

//@version=6
strategy("array returned from a ternary", overlay = true, initial_capital = 10000)
fast = ta.ema(close, 10)
slow = ta.ema(close, 30)
pickArr(int k, array<float> a, array<float> b) =>
    k == 0 ? a : b
var ups = array.new<float>()
var dns = array.new<float>()
ups.push(high)
dns.push(low)
array<float> sel = pickArr(close > open ? 0 : 1, ups, dns)
plot(sel.get(sel.size() - 1))
if ta.crossover(fast, slow)
    strategy.entry("Long", strategy.long, qty = 0.01)
if ta.crossunder(fast, slow)
    strategy.close("Long")
error: no viable conversion from returned value of type 'std::vector<double>' to function return type 'double'

Control, one change: array<float> r = k == 0 ? a : b then r.

4. Array returned by a function that reads history with its parameter

//@version=6
strategy("array returned by a function reading history", overlay = true, initial_capital = 10000)
fast = ta.ema(close, 10)
slow = ta.ema(close, 30)
r = ta.rsi(close, 14)
e = ta.ema(close, 20)
features(int shift) =>
    array<float> f = array.new<float>()
    f.push(r[shift])
    f.push(e[shift])
    f
array<float> cur = features(0)
array<float> prev = features(1)
plot(cur.get(0) - prev.get(0))
if ta.crossover(fast, slow)
    strategy.entry("Long", strategy.long, qty = 0.01)
if ta.crossunder(fast, slow)
    strategy.close("Long")

The same error as case 3, in features_cs0 and in features_cs1.

Control, one change: f.push(r) and f.push(e) (no [shift]).

5. String returned through an untyped parameter

//@version=6
strategy("string returned through an untyped parameter", overlay = true, initial_capital = 10000)
fast = ta.ema(close, 10)
slow = ta.ema(close, 30)
tail(s) =>
    parts = str.split(s, ":")
    parts.size() > 1 ? parts.get(1) : s
var names = array.from("A:B", "C")
if barstate.islast
    for i = 0 to names.size() - 1
        nm = names.get(i)
        log.info(tail(nm))
if ta.crossover(fast, slow)
    strategy.entry("Long", strategy.long, qty = 0.01)
if ta.crossunder(fast, slow)
    strategy.close("Long")
error: no viable conversion from returned value of type 'std::string' to function return type 'double'

Control, one change: tail(string s). log.info(tail("A:B")) also builds.

6. Array through two untyped parameters

//@version=6
strategy("array through two untyped parameters", overlay = true, initial_capital = 10000)
fast = ta.ema(close, 10)
slow = ta.ema(close, 30)
sumOf(arr) =>
    float s = 0.0
    for i = 0 to arr.size() - 1
        s += arr.get(i)
    s
avgOf(arr) =>
    sumOf(arr) / arr.size()
var vals = array.new<float>()
vals.push(close)
if vals.size() > 20
    vals.shift()
plot(avgOf(vals))
if ta.crossover(fast, slow)
    strategy.entry("Long", strategy.long, qty = 0.01)
if ta.crossunder(fast, slow)
    strategy.close("Long")
error: member reference base type 'double' is not a structure or union

Control, one change: avgOf(array<float> arr) (sumOf stays untyped).

7. Arrays from a tuple to an untyped parameter

//@version=6
strategy("arrays from a tuple to an untyped parameter", overlay = true, initial_capital = 10000)
fast = ta.ema(close, 10)
slow = ta.ema(close, 30)
make() =>
    var a = array.new<float>()
    var b = array.new<float>()
    a.push(high)
    b.push(low)
    [a, b]
lastOf(x, y, bool useX) =>
    pick = useX ? x : y
    float v = na
    for e in pick
        v := e
    v
[ups, dns] = make()
plot(lastOf(ups, dns, close > open))
if ta.crossover(fast, slow)
    strategy.entry("Long", strategy.long, qty = 0.01)
if ta.crossunder(fast, slow)
    strategy.close("Long")
error: invalid range expression of type 'double'

Control, one change: lastOf(array<float> x, array<float> y, bool useX). The untyped lastOf also builds when it is called with two var arrays declared at the top level instead of the tuple elements.

8. One untyped parameter, two element types

//@version=6
strategy("untyped parameter given int and float arrays", overlay = true, initial_capital = 10000)
fast = ta.ema(close, 10)
slow = ta.ema(close, 30)
trim(arr, int maxSize) =>
    if arr.size() > maxSize
        arr.shift()
var ints = array.new<int>()
var floats = array.new<float>()
ints.push(bar_index)
floats.push(close)
trim(ints, 50)
trim(floats, 50)
if ta.crossover(fast, slow)
    strategy.entry("Long", strategy.long, qty = 0.01)
if ta.crossunder(fast, slow)
    strategy.close("Long")
error: non-const lvalue reference to type 'vector<int>' cannot bind to a value of unrelated type 'vector<double>'

Control, one change: without the trim(ints, 50) call.

9. String through two untyped parameters

//@version=6
strategy("string through two untyped parameters", overlay = true, initial_capital = 10000)
fast = ta.ema(close, 10)
slow = ta.ema(close, 30)
startIn = input.string("09:30", "Start")
hm(txt) =>
    [int(str.tonumber(str.substring(txt, 0, 2))), int(str.tonumber(str.substring(txt, 3, 5)))]
sessionStart(startStr) =>
    [h, m] = hm(startStr)
    timestamp("GMT+0", year, month, dayofmonth, h, m)
plot(sessionStart(startIn))
if ta.crossover(fast, slow)
    strategy.entry("Long", strategy.long, qty = 0.01)
if ta.crossunder(fast, slow)
    strategy.close("Long")
error: no viable conversion from 'std::string' to 'double'

Control, one change: sessionStart(string startStr) (hm stays untyped).

10. Untyped matrix local, reassigned

//@version=6
strategy("untyped matrix local reassigned", overlay = true, initial_capital = 10000)
fast = ta.ema(close, 10)
slow = ta.ema(close, 30)
step(matrix<float> prev) =>
    nxt = matrix.new<float>(2, 1, 0.0)
    nxt.set(0, 0, prev.get(0, 0) * 0.5)
    nxt
var matrix<float> state = matrix.new<float>(2, 1, 0.0)
state.set(0, 0, close)
if barstate.islast
    tmp = matrix.copy(state)
    for k = 1 to 3
        tmp := step(tmp)
    log.info(str.tostring(tmp.get(0, 0)))
if ta.crossover(fast, slow)
    strategy.entry("Long", strategy.long, qty = 0.01)
if ta.crossunder(fast, slow)
    strategy.close("Long")
error: assigning to 'double' from incompatible type 'NumericMatrix'

Control, one change: matrix<float> tmp = matrix.copy(state).

Expected

All ten build and run as their controls:

  • A: the function's C++ return type follows the type of its last expression, through an if … else block, a ternary, per-call-site copies and an untyped parameter.
  • B: an untyped parameter takes the type of each argument it receives, including when the argument is another function's untyped parameter or a tuple element; a function called with two element types gets one instance per type; and an untyped local keeps the type of its initialiser.

Workaround

  • A: end the function with a typed local (array<float> r = … then r), avoid an else branch as the last statement, and declare the parameter type when the function returns a string built from it.
  • B: declare the parameter type (array<float> arr, string s) on every function in the chain, give two element types two functions, and declare the type of a matrix local.

Activity

  1. luisleo526 commented on Nov 14, 2026

    @luisleo526
    Contributor

    Thank you for the detailed report and the controls; they make each case easy to reproduce.

    We will reproduce the ten forms in your table on Codegen 1.12.0 and on current main, find where the translation goes wrong, and post the findings here by 2026-11-15, with a fix target.

    🤖 Generated with Claude Code

  2. luisleo526 commented on Nov 15, 2026

    @luisleo526
    Contributor

    Findings 2026-11-15 (UTC+8), as promised.

    • All ten forms reproduce on Codegen 1.12.0 and on current main: the generated C++ does not compile.
    • Cause: when a user function's return type, an untyped parameter or an untyped local is not written out, the translator falls back to double, even when the value is an array, a matrix, a UDT or a string.
    • Fix: the type is now inferred from what the value actually is. Our full test run caught a problem in the first version of the fix: deeply nested calls became much slower (a nesting test went from 0.03 s to 0.64 s at depth 16). That is fixed; the same test now takes about 0.03 s at every depth, and the depth-40 test passes.

    Fix target: we cannot give one honestly yet, because the final native verification on your scripts has not run (it is scheduled on a cloud machine today), and the fix is not in today's batch. We will post the date here as soon as that run has finished, and the merge commit when it lands.

  3. luisleo526 commented on Nov 15, 2026

    @luisleo526
    Contributor

    Fixed on main in b7379dd (#406). An array, matrix, UDT or string returned from a user function, passed to an untyped parameter or kept in a reassigned local is no longer inferred as double, so these scripts now generate C++ that compiles. Compound types are inferred through branch returns, nested calls, tuple arguments and local assignments, and calls with different array element types get separate callable variants. The reproduction tests in tests/test_callable_compound_type_flow.py fail on the previous main and pass now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions