Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 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
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
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
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
30 changes: 30 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,36 @@ supported as exact pairs; on the 0.x line they are independent. See the

## Unreleased (next release)

- Strategy sizing constants retain their string values in expressions, aliases
and helper calls. Host order and risk settings convert these values to their
numeric representation only at the setting boundary.

- `timeframe.in_seconds` and `timeframe.change` resolve an evaluated empty
string to the chart period, including input, variable, function-return and
named arguments. The argument is evaluated once, and nonempty strings keep
their explicit period. Bare `na` remains accepted; the value returned by
`timeframe.change(na)` is still awaiting verification against TradingView.
Non-string timeframe arguments are refused before C++ emission with the
stable `PF-E2095` type diagnostic and a source location, including input
values, reassignments, indicator results and helper parameters. Equally
specific diagnostic templates distinguish primitive types from qualifiers
using their catalog argument kinds. Dotted builtin signatures retain supplied
arguments, including escaped string literals and VWAP anchors. (#394)
- Script identifiers spelled like integer-to-float conversion temporaries,
including the underscore suffixes of nested conversions, now use the
generator's reserved-name escaping.
- Reference-typed UDT fields keep their type when initialized or reassigned
with `na`, including array defaults. Drawing handles cross user-function
and tuple boundaries by value, and `label(na)` produces a missing label
handle. Polyline locals, arrays, fields and delete methods retain opaque
handles and argument evaluation while rendering remains a visual no-op.
- Generated function variants and persistent local copies avoid authored and
generated member names, including names ending in `_cs1` and composed names
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.

- 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.
The paired engine reports a typed timezone error identifying the failed bar.
Expand Down
6 changes: 6 additions & 0 deletions docs/reference/support-contracts.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@ lowering. Structural mutation, collection reassignment/escape, history and
pair-binder iteration retain PF-E5086 pending TV evidence/provenance support;
declaration tails yielding collections as callable/selection values are refused.
`polyline.all` retains PF-E5085 until the engine has a Polyline handle/arena.
Polyline locals, array elements and UDT fields retain opaque typed handles;
default construction and bare `na` use a missing handle, and copies retain
its identity. `polyline.new` and functional or method-form `delete` keep the
existing visual-only rendering contract, while evaluating their arguments
once in parameter order. Opaque ID allocation joins script reset and rollback
state. This does not supply the live arena required by `polyline.all`.
`var`/`varip` aliases retain PF-E5086 until a TradingView capture establishes
their lifetime semantics. Whether a later creation in the same bar is visible
through the alias is not yet measured against TradingView.
Expand Down
85 changes: 71 additions & 14 deletions pineforge_codegen/analyzer/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
SymbolTable,
TypeSpec,
method_receiver_type_name,
public_type_name,
unify_pine_types,
)
from ..errors import SourceLocation, Diagnostic, CompileError, Level, Phase
Expand Down Expand Up @@ -265,6 +266,7 @@ def __init__(self, ast: Program, filename: str = "<stdin>",
self._block_var_owner: dict[str, int] = {}
self._block_var_renames: dict[int, dict[str, str]] = {}
self._block_var_seq = 0
self._block_var_taken: set[str] | None = None
# Identifier node identity -> the lexical Symbol.scope resolved while
# that node's source scope is live. Codegen uses this narrow
# provenance to distinguish true global aliases from same-named local
Expand Down Expand Up @@ -5018,6 +5020,31 @@ def _record_script_block_binding(self, sym: Symbol, outer: Symbol | None) -> Non
or any(id(body) == outer_owner for body in self._block_node_stack)
)

def _allocate_block_var_member(self, node: VarDecl) -> str:
"""Keep generated lexical storage apart from every syntax spelling."""
if self._block_var_taken is None:
self._block_var_taken = set()
for item, _depth in iter_ast_nodes(self._ast):
if self._budget is not None:
self._budget.check(item.loc, Phase.ANALYZER)
for attr in ("name", "var", "member"):
value = getattr(item, attr, None)
if isinstance(value, str):
self._block_var_taken.add(value)
for attr in ("names", "vars", "params", "members"):
self._block_var_taken.update(
value for value in (getattr(item, attr, None) or ())
if isinstance(value, str)
)
while True:
if self._budget is not None:
self._budget.check(node.loc, Phase.ANALYZER)
self._block_var_seq += 1
member_name = f"{node.name}__blk{self._block_var_seq}"
if member_name not in self._block_var_taken:
self._block_var_taken.add(member_name)
return member_name

def _visit_VarDecl(self, node: VarDecl) -> PineType:
if (not node.is_var and not node.is_varip and node.type_hint is None
and isinstance(node.value, NaLiteral)
Expand Down Expand Up @@ -5276,8 +5303,7 @@ def _visit_VarDecl(self, node: VarDecl) -> PineType:
self._block_var_owner[node.name] = block_id
elif owner != block_id:
# Sibling-scope collision: disambiguate this declaration.
self._block_var_seq += 1
member_name = f"{node.name}__blk{self._block_var_seq}"
member_name = self._allocate_block_var_member(node)
self._block_var_renames.setdefault(block_id, {})[node.name] = member_name
self._var_members.append((member_name, val_type, init_str))
scope_cursor = self._symbols.current_scope
Expand Down Expand Up @@ -7157,15 +7183,6 @@ def _operator_operand_type(
or authored_method
):
result = None
if result is None and isinstance(node, MemberAccess):
if isinstance(node.object, Identifier):
ns = node.object.name
if ns == "syminfo":
ptype = sigs.SYMINFO_VARIABLES.get(f"syminfo.{node.member}")
if ptype is not None:
result = TypeSpec.primitive(ptype.value)
elif ns == "timeframe" and node.member == "period":
result = TypeSpec.primitive("string")
if result is None and isinstance(node, FuncCall):
callee = node.callee
if isinstance(callee, Identifier):
Expand Down Expand Up @@ -7459,6 +7476,46 @@ def _visit_Ternary(self, node: Ternary) -> PineType:
return main_type
return result_type

def _check_timeframe_string_arguments(
self, node: FuncCall,
parameter_types: dict[str, PineType | TypeSpec] | None = None,
) -> None:
"""Check string signature slots using lexical and written-call types."""
if self._pine_version != 6 or self._in_v5_library_definition(node):
return
callee = node.callee
if (not isinstance(callee, MemberAccess)
or not isinstance(callee.object, Identifier)
or callee.object.name != "timeframe"
or self._value_bindings.declaration_bindings.get(id(callee.object)) is not None
or (parameter_types is not None and callee.object.name in parameter_types)):
return
intrinsic = sigs.BUILTIN_FUNCTIONS.get(f"timeframe.{callee.member}")
if intrinsic is None:
return
bound = self._bind_callable_args(node, intrinsic.param_names)
for parameter, value in zip(intrinsic.primary.params, bound):
if value is None or parameter.pine_type != PineType.STRING:
continue
actual = self._operator_operand_type(value, parameter_types)
if actual is None or actual in {
TypeSpec.primitive("string"), TypeSpec.primitive("na"),
}:
# Untyped helper parameters stay open until their written
# call supplies a type. Bare na adopts the string signature.
continue
function_name = intrinsic.name
argument_type = public_type_name(actual) or str(actual)
parameter_type = parameter.pine_type.value
name = parameter.name
from ..pine_spelling import expr_start

self._error(
f"Cannot call '{function_name}' with an argument of type {argument_type} "
f"for {parameter_type} parameter '{name}'.",
expr_start(value).loc or value.loc,
)

def _visit_FuncCall(self, node: FuncCall) -> PineType:
if self._pine_version == 6 and not self._in_v5_library_definition(node):
self._parameter_qualifiers.check_builtin(node)
Expand Down Expand Up @@ -7589,6 +7646,7 @@ def _visit_FuncCall(self, node: FuncCall) -> PineType:
visited_member_arg_types[id(arg)] = self._visit(arg)
for val in node.kwargs.values():
visited_member_arg_types[id(val)] = self._visit(val)
self._check_timeframe_string_arguments(node)
# UDT method call-site typing. Method definitions may contain an
# untyped parameter history read; resolve receiver + args here and
# apply the same deferred map-history gate as regular UDFs before
Expand Down Expand Up @@ -8958,6 +9016,8 @@ def _visit_MemberAccess(self, node: MemberAccess) -> PineType:
if drawing_all_kind(node) not in {None, "polyline"}:
# Collections use TypeSpec for their shape; PineType stays scalar.
return PineType.FLOAT
if self._builtin_sizing_constant(node) is not None:
return PineType.STRING
# Handle specific namespaces
if isinstance(node.object, Identifier):
ns = node.object.name
Expand All @@ -8967,9 +9027,6 @@ def _visit_MemberAccess(self, node: MemberAccess) -> PineType:
# Direction constants
if node.member in ("long", "short"):
return PineType.INT
# Qty type constants
if node.member in ("percent_of_equity", "fixed", "cash"):
return PineType.INT
# Commission type constants
if node.member in ("commission",):
return PineType.VOID # namespace prefix for .percent etc.
Expand Down
51 changes: 50 additions & 1 deletion pineforge_codegen/analyzer/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
from ..errors import Phase
from ..limits import iter_ast_nodes
from ..matrix_overloads import matrix_sum_has_rhs
from ..reference_casts import na_reference_cast_kind
from ..symbols import (
PineType,
TypeSpec,
Expand All @@ -59,7 +60,9 @@
# Drawing-objects-as-data type names (spec §4.1). Defined locally — the
# analyzer must not import from ``codegen`` (codegen imports analyzer, so the
# reverse would be a cycle). Mirrors codegen.tables.DRAWING_TYPE_TO_CPP keys.
_DRAWING_TYPE_NAMES = frozenset({"line", "box", "label", "linefill", "chart.point"})
_DRAWING_TYPE_NAMES = frozenset({
"line", "box", "label", "linefill", "chart.point", "polyline",
})
_DRAWING_NS = frozenset({"line", "box", "label", "linefill"})
_DIRECT_ARRAY_VALUE_PRODUCERS = frozenset({
"from",
Expand Down Expand Up @@ -91,6 +94,26 @@ class TypeHelper:
docstring above.
"""

def _builtin_sizing_constant(self, value):
if not (isinstance(value, MemberAccess)
and isinstance(value.object, Identifier)):
return None
receiver = value.object
constant = sigs.get_sizing_constant(receiver.name, value.member)
if constant is None:
return None
parameters = getattr(self, "_parameter_types", None)
bindings = self._value_bindings.declaration_bindings
if ((self._pine_version == 6 and id(receiver) not in bindings)
or self._value_bindings.binding_of(receiver) is not None
or (self._pine_version != 6
and self._symbols.resolve(receiver.name) is not None)
or (parameters is not None and receiver.name in parameters)
or receiver.name in self._udt_fields
or receiver.name in self._enum_defs):
return None
return constant

def _split_top_level_type_args(self, text: str) -> list[str]:
args: list[str] = []
cur: list[str] = []
Expand Down Expand Up @@ -588,6 +611,10 @@ def direct_user_udt_ctor_name(node: ASTNode) -> str | None:
return typed_receiver_spec
# Drawing-objects-as-data return typing: *.new / *.copy -> handle of
# the self-type; linefill.get_line* -> line; chart.point.* -> point.
if cast_kind := na_reference_cast_kind(value):
return TypeSpec.udt(cast_kind)
if ns == "polyline" and func == "new":
return TypeSpec.udt("polyline")
if ns in _DRAWING_NS:
if func in ("new", "copy"):
return TypeSpec.udt(ns)
Expand Down Expand Up @@ -807,6 +834,8 @@ def direct_user_udt_ctor_name(node: ASTNode) -> str | None:
owner = self._type_spec_from_expr(value.object)
if owner is not None and owner.kind == "udt" and owner.name:
return (self._udt_field_type_specs.get(owner.name) or {}).get(value.member)
if self._builtin_sizing_constant(value) is not None:
return TypeSpec.primitive("string")
return None

@staticmethod
Expand Down Expand Up @@ -1535,6 +1564,9 @@ def _check_node(self, node):
op, operands = node.op, (node.operand,)
elif isinstance(node, Ternary):
op, operands = "?:", (node.condition, node.true_val, node.false_val)
elif isinstance(node, FuncCall):
self._analyzer._check_timeframe_string_arguments(node, self._parameter_types)
return
else:
return
self._analyzer._check_operator_operands(node, op, operands, self._parameter_types)
Expand All @@ -1544,6 +1576,23 @@ def _type_spec_from_expr(self, value, **kwargs):
return self._analyzer._operator_operand_type(
value, self._parameter_types,
)
if (isinstance(value, MemberAccess)
and isinstance(value.object, Identifier)
and self._pine_version == 6
and not self._in_v5_library_definition(value)):
receiver = value.object
bindings = self._value_bindings.declaration_bindings
# Require the receiver's recorded lexical namespace use. A
# missing record is not proof, and even an unresolved parameter
# or local in the written-call environment shadows a namespace.
if (id(receiver) in bindings and bindings[id(receiver)] is None
and (self._parameter_types is None
or receiver.name not in self._parameter_types)
and receiver.name not in self._udt_fields
and receiver.name not in self._enum_defs):
spec = sigs.get_variable_type_spec(receiver.name, value.member)
if spec is not None:
return spec
return super()._type_spec_from_expr(value, **kwargs)

def _visit(self, node):
Expand Down
Loading