Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
85b9100
Resolve empty timeframe arguments to the chart period
luisleo526 Nov 14, 2026
6e90b5a
Integrate empty timeframe handling with current main
luisleo526 Nov 14, 2026
6453949
Preserve timeframe arguments and generated-name safety
luisleo526 Nov 14, 2026
cd3b13f
Update anchor test expectations for conditional timeframe calls
luisleo526 Nov 14, 2026
909baaf
Preserve reference types across fields and calls
luisleo526 Nov 14, 2026
9120d20
Combine reference-type support with current main
luisleo526 Nov 14, 2026
cb93e2d
Handle emitters without function metadata
luisleo526 Nov 14, 2026
96297f9
Retain structured value types across user function calls
luisleo526 Nov 14, 2026
9237e1b
Check compound values through native execution
luisleo526 Nov 14, 2026
2a8071d
Combine structured type support with current main
luisleo526 Nov 14, 2026
e004cbf
Bound type inference within expression queries
luisleo526 Nov 14, 2026
8802058
Validate timeframe argument types
luisleo526 Nov 14, 2026
7a28a29
Register the timeframe argument diagnostic
luisleo526 Nov 15, 2026
209b3dc
Refresh test reporting and timestamp controls
luisleo526 Nov 15, 2026
31f2d50
Refresh test reporting and timestamp controls
luisleo526 Nov 15, 2026
49cab86
Refresh test reporting and timestamp controls
luisleo526 Nov 15, 2026
c04553d
Disambiguate diagnostic templates by argument kinds
luisleo526 Nov 15, 2026
f2f6ec8
Validate timeframe arguments using semantic types
luisleo526 Nov 15, 2026
b2db977
fix(codegen): allocate function clone names against authored members
luisleo526 Nov 15, 2026
c9bb034
Use the generated timeframe type diagnostic presentation
luisleo526 Nov 15, 2026
5beedda
Locate helper argument expectations inside the builtin call
luisleo526 Nov 15, 2026
bd8a3c6
Resolve registered argument types and report their source starts
luisleo526 Nov 15, 2026
4da8042
fix(codegen): separate composed helper and lexical storage names
luisleo526 Nov 15, 2026
95e5924
Preserve sizing string values across expressions and host settings
luisleo526 Nov 15, 2026
149cb9b
Exercise v5 receiver shadowing through an imported library
luisleo526 Nov 15, 2026
95b26d8
Preserve integer risk type boundary codes
luisleo526 Nov 15, 2026
6e9d119
Strengthen sizing regression and reserve generated name
luisleo526 Nov 15, 2026
d9a643e
Lower computed risk type arms at numeric boundary
luisleo526 Nov 15, 2026
57d0db6
Convert sizing selection arms at host boundaries
luisleo526 Nov 15, 2026
6c1ff4f
fix(codegen): preserve established typed method names
luisleo526 Nov 15, 2026
a0afaa8
Assert the risk type conversion for reassigned sizing variables (#394)
luisleo526 Nov 15, 2026
db8b39a
Combine the empty timeframe and reference type fixes
luisleo526 Nov 15, 2026
ed1eb67
Combine with the generated name collision fix
luisleo526 Nov 15, 2026
45b8662
Preserve unresolved script selection history
luisleo526 Nov 15, 2026
43ec287
Combine corrected timeframe and compound type inference
luisleo526 Nov 15, 2026
40a9877
Combine the compound value type fix with the stacked fixes (#391)
luisleo526 Nov 15, 2026
cbe9f2b
fix(codegen): compile qualified declarations and request helper forms
luisleo526 Nov 15, 2026
6fa5d2b
Merge main into the compound value type fix (#391)
luisleo526 Nov 15, 2026
c2569a2
Combine the qualified declaration and request helper fix (#372) with …
luisleo526 Nov 15, 2026
057eb62
fix(codegen): preserve allocated callable and tuple history identities
luisleo526 Nov 15, 2026
986b52a
fix(codegen): preserve tuple history payload boundaries
luisleo526 Nov 15, 2026
8f2365b
Merge current main into the qualified declaration and request helper fix
luisleo526 Nov 15, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,19 @@ supported as exact pairs; on the 0.x line they are independent. See the
that overlap collection-history or requested-context storage. Persistent
declarations in sibling blocks also retain distinct storage when a script
uses their generated spelling. Declarations, calls and history storage use
the same allocated identities. Regenerate C++ and relink affected strategies.
the same allocated identities, including when selecting reachable variants
for emission. Regenerate C++ and relink affected strategies.
- Persistent declarations accept a type qualifier after `var` or `varip`.
Lower-timeframe requests return independently typed arrays for inline and
helper-returned tuple payloads.
- Complete nested indentation levels can combine tabs and spaces. Requested
`na`/`nz` helper parameters retain their bindings beside time operations;
global tuple declarations and their member histories share one requested
sample. Uncalled forwarding helpers no longer allocate unresolved TA buffers
for their unreachable call variants (#372). Bare tuple-element history
payloads retain their located refusal. Tuple histories rendered through the
expression visitor, including reads through globals, retain their chart
series and warning.

- A zone name the engine rejects now makes calendar-form `timestamp()` stop the
run at its first evaluation, instead of silently calculating a UTC value.
Expand Down
24 changes: 24 additions & 0 deletions docs/reference/support-contracts.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,29 @@
## Support contracts

Persistent typed declarations parse their storage prefix separately from their
qualifier: `var const float`, `varip const int`, and the corresponding `simple`
and `series` forms retain both annotations and their existing initialization.

`request.security_lower_tf` tuple payloads, written inline or returned by a
helper, produce one array per element. Each intrabar evaluates the tuple once
before distributing values to the independently typed arrays; clearing the
request clears every array together. Tuple-bound arrays retain collection
metadata in global and callable scopes.

A global tuple declaration read by `request.security` is sampled once in the
requested evaluator, in declaration order. Scalar and history reads share that
sample, including stateful helper results. Member history commits on completed
requested bars even when a lazy payload does not read the member on that bar.
Helper parameter bindings remain active through `na`/`nz` builtin emission in
both evaluator modes. These rules supersede the older tuple refusal limitations
described in the historical helper row below.

Complete mixed tab/space nested block prefixes use four columns per tab plus
the spaces. Previously accepted incomplete mixed prefixes, skipped first-body
widths and pending logical-line continuations retain their earlier handling
pending additional TradingView observations; they are not newly refused as part
of the nested-block correction.

Builtin `array.slice` on a resolved typed array in the script, a function or
method parameter, or a callable-local array opens the view gate and lowers the
script's array storage to typed handles:
Expand Down
12 changes: 11 additions & 1 deletion pineforge_codegen/analyzer/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -5627,6 +5627,9 @@ def _selection_tuple_shape(

def _visit_TupleAssign(self, node: TupleAssign) -> PineType:
val_type = self._visit(node.value)
lower_types = (node.value.annotations or {}).get(
"lower_tf_tuple_element_types", (),
)
loc = node.loc or SourceLocation(file=self._filename, line=1, col=1, end_col=1)
is_program_global = (
self._global_scope and self._symbols.current_scope.name == "global"
Expand Down Expand Up @@ -5741,7 +5744,14 @@ def _visit_TupleAssign(self, node: TupleAssign) -> PineType:
self._record_script_block_binding(sym, outer_symbol)
self._note_member_writer(sym, name, node)

if (self._collection_scope_stack
if idx < len(lower_types):
inner = lower_types[idx]
spec = TypeSpec.array(
TypeSpec.primitive("int64") if inner == PineType.INT
else self._pine_type_to_spec(inner)
)
self._record_collection_type(name, spec)
elif (self._collection_scope_stack
and self._block_node_stack
and self._symbols.current_scope.name != "global"):
owner_id = id(self._block_node_stack[-1])
Expand Down
48 changes: 33 additions & 15 deletions pineforge_codegen/analyzer/call_handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -1001,9 +1001,8 @@ def _handle_request_security_lower_tf(self, node: FuncCall) -> PineType:
the codegen knows to emit a ``std::vector<T>`` accumulator that
gets cleared on sub-bar 0 and pushed-to per sub-bar.

UDT / color / string element types are deliberately rejected here
with a precise diagnostic; the runtime path only knows how to
accumulate ``double`` / ``int`` / ``bool``."""
Scalar calls retain their existing numeric/bool arrays. Tuple calls
carry each primitive element's type to its own array accumulator."""
param_names = ["symbol", "timeframe", "expression",
"ignore_invalid_symbol", "currency",
"ignore_invalid_timeframe", "calc_bars_count"]
Expand Down Expand Up @@ -1033,13 +1032,6 @@ def _handle_request_security_lower_tf(self, node: FuncCall) -> PineType:
node.loc,
)

if isinstance(expr_node, TupleLiteral):
self._error(
"request.security_lower_tf does not support tuple expressions yet. "
"Issue separate request.security_lower_tf calls for each series.",
node.loc,
)

for arg in node.args:
if arg is not None and arg is not expr_node:
self._visit(arg)
Expand All @@ -1054,20 +1046,45 @@ def _handle_request_security_lower_tf(self, node: FuncCall) -> PineType:
ta_end = len(self._ta_call_sites)
security_ta_range = (ta_start, ta_end) if ta_end > ta_start else None

tuple_types = self._tuple_element_types_by_node.get(id(expr_node), ())
if (isinstance(expr_node, FuncCall)
and isinstance(expr_node.callee, Identifier)
and self._func_returns_tuple.get(expr_node.callee.name, False)):
tuple_types = self._func_tuple_element_types.get(expr_node.callee.name, ())
if PineType.UNKNOWN in tuple_types:
tuple_types = self._security_callsite_tuple_types(
expr_node.callee.name, expr_node, tuple_types,
)
elif (isinstance(expr_node, FuncCall)
and isinstance(expr_node.callee, MemberAccess)
and isinstance(expr_node.callee.object, Identifier)
and expr_node.callee.object.name == "ta"):
count = TA_TUPLE_ELEMENT_COUNTS.get(expr_node.callee.member, 0)
if count:
tuple_types = tuple_types or (PineType.FLOAT,) * count

# Cache the resolved element type on the call node so the
# ``_type_spec_from_expr`` pass can map ``request.security_lower_tf``
# to ``array<T>`` without re-visiting the expression (which would
# double-allocate TA call sites for expressions like ``ta.ema``).
cached_anns = getattr(node, "annotations", None) or {}
cached_anns["lower_tf_element_pine_type"] = expr_pine_type
if tuple_types:
cached_anns["lower_tf_tuple_element_types"] = tuple_types
self._security_tuple_shapes[id(node)] = len(tuple_types)
node.annotations = cached_anns

if expr_pine_type not in (PineType.FLOAT, PineType.INT, PineType.BOOL,
PineType.NA, PineType.UNKNOWN):
element_types = tuple_types or (expr_pine_type,)
supported = {PineType.FLOAT, PineType.INT, PineType.BOOL,
PineType.NA, PineType.UNKNOWN}
if tuple_types:
supported |= {PineType.STRING, PineType.COLOR}
unsupported = next((item for item in element_types if item not in supported), None)
if unsupported is not None:
element_label = {
PineType.STRING: "string",
PineType.COLOR: "color",
}.get(expr_pine_type, str(expr_pine_type))
}.get(unsupported, str(unsupported))
self._error(
"request.security_lower_tf element type '" + element_label
+ "' is not yet supported. Supported element types: float, int, bool. "
Expand All @@ -1085,8 +1102,9 @@ def _handle_request_security_lower_tf(self, node: FuncCall) -> PineType:
sec_id=sec_id,
timeframe=context["timeframe"] if context is not None else tf_node,
expression=expr_node,
returns_tuple=False,
tuple_size=0,
returns_tuple=bool(tuple_types),
tuple_size=len(tuple_types),
tuple_element_types=tuple(tuple_types),
gaps=None,
lookahead=None,
ta_range=security_ta_range,
Expand Down
99 changes: 97 additions & 2 deletions pineforge_codegen/codegen/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -806,6 +806,7 @@ def func_var_storage(owner: str, raw_name: str) -> str:
# authority for nested stateful-helper dispatch (see visit_call).
self._current_instance_name: str | None = None
self._instance_dispatch: dict[tuple[str | None, int], str] = {}
self._live_func_instances: set[str] | None = None
self._fresh_instances: list[dict] = []
self._fresh_var_members: list[tuple[str, str, str]] = []
# Fresh fixnan members for context-sensitive helper instances (nested
Expand Down Expand Up @@ -2075,6 +2076,7 @@ def natural_name(fname: str, cs_idx: int) -> str:
interned: dict[tuple, dict] = {}
worklist: list[dict] = []
seen_walk: set[str] = set()
instances: dict[str, dict] = {}
fresh_counter = 0

# Seed with the natural clones the flat emission loop produces.
Expand Down Expand Up @@ -2107,6 +2109,7 @@ def natural_name(fname: str, cs_idx: int) -> str:
if inst["name"] in seen_walk:
continue
seen_walk.add(inst["name"])
instances[inst["name"]] = inst
body = func_bodies.get(inst["fname"])
if not body:
continue
Expand Down Expand Up @@ -2267,6 +2270,84 @@ def natural_name(fname: str, cs_idx: int) -> str:
worklist.append(ginst)
self._instance_dispatch[(inst["name"], id(callnode))] = ginst["name"]

# Definition-time calls reserve variants too. Only paths rooted in
# executable statements instantiate their chart-context TA buffers.
# Preserve all semantic analysis; select emission after composing the
# same natural/fresh dispatch graph that the call visitor uses.
for fi in ctx.func_infos:
instances.setdefault(self._func_cpp_base_name(fi.name), {
"fname": fi.name, "name": self._func_cpp_base_name(fi.name),
"call_site_idx": None, "ta_remap": {},
})
methods: dict[int, set[str]] = {}
for call_id, key in ctx.method_call_bindings:
methods.setdefault(call_id, set()).add(key)

def targets(call, parent):
dispatch = self._instance_dispatch.get(
(parent["name"] if parent is not None else None, id(call)),
)
if dispatch is not None:
return [dispatch]
bound = ctx.func_call_cs_map.get(id(call))
if bound is not None:
names = [bound[0]]
elif id(call) in inherited_names:
names = [inherited_names[id(call)]]
elif isinstance(call.callee, Identifier) and call.callee.name in func_bodies:
names = [call.callee.name]
else:
names = sorted(methods.get(id(call), ()))
result = []
for name in names:
if name in stateful and ctx.func_call_site_counts.get(name, 0) > 0:
index = (
bound[1] if bound is not None
else (parent.get("call_site_idx") or 0) if parent is not None
else 0
)
result.append(natural_name(name, index))
else:
result.append(self._func_cpp_base_name(name))
return result

roots = [
stmt for stmt in ctx.ast.body
if not isinstance(stmt, (FuncDef, MethodDef))
]
pending = [
target
for call in self._iter_func_calls(roots)
for target in targets(call, None)
]
live: set[str] = set()
live_owners: set[str] = set()
used_ta: set[str] = set()
while pending:
if self._budget is not None:
self._budget.check(phase=Phase.CODEGEN)
name = pending.pop()
if name in live:
continue
live.add(name)
instance = instances.get(name)
if instance is None:
continue
owner = instance["fname"]
live_owners.add(owner)
used_ta.update(instance.get("ta_remap", {}).values())
for call in self._iter_func_calls(func_bodies.get(owner, ())):
pending.extend(targets(call, instance))
self._live_func_instances = live
self._dead_func_names.update(stateful - live_owners)
self._dead_ta_indices = {
index for index, site in enumerate(ctx.ta_call_sites)
if site.owner_func in stateful and site.member_name not in used_ta
}
self._fresh_instances[:] = [
instance for instance in self._fresh_instances if instance["name"] in live
]

def _callable_var_collection_spec(
self, name: str, owner_func: str | None = None) -> TypeSpec | None:
"""Exact TypeSpec for a function-scoped persistent collection member.
Expand Down Expand Up @@ -5657,17 +5738,27 @@ def _generate_cpp(self) -> str:
# emits ``std::vector<T>`` and the eval method pushes the
# per-sub-bar value. Element type is inferred from the
# expression — analyzer constrained it to int / float / bool.
tuple_types = item.get("tuple_element_types", ())
ctype = self._infer_cpp_type_for_security_elem(expr_node)
if ctype not in ("double", "int", "bool"):
if tuple_types:
accumulators = ", ".join(
f"std::vector<{part}>"
for part in self._lower_tf_tuple_cpp_types(tuple_types)
)
result_type = f"std::tuple<{accumulators}>"
elif ctype not in ("double", "int", "bool"):
# Defensive fallback — analyzer should already have
# rejected unsupported types, but keep the codegen
# well-defined if a future path slips through.
ctype = "double"
result_type = f"std::vector<{ctype}>"
else:
result_type = f"std::vector<{ctype}>"
self._security_ohlc_hist_fields_by_sec[sec_id] = (
self._collect_security_ohlc_hist_fields(state_expr)
)
lines.append(
f" std::vector<{ctype}> _req_sec_lower_tf_{sec_id}{{}};"
f" {result_type} _req_sec_lower_tf_{sec_id}{{}};"
)
for field in sorted(
self._security_ohlc_hist_fields_by_sec.get(sec_id, ())
Expand Down Expand Up @@ -6344,6 +6435,10 @@ def allocate_legacy_flag(base: str) -> str:
if (has_ta or has_series or needs_security_clone) and total_cs > 0:
# Emit one variant per call site
for cs_idx in range(total_cs):
if (self._live_func_instances is not None
and self._func_variant_name(fi.name, cs_idx)
not in self._live_func_instances):
continue
self._emit_func_def(fi, lines, call_site_idx=cs_idx)
lines.append("")
else:
Expand Down
Loading
Loading