opencode-pine2pyne 0.2.0__py3-none-any.whl → 0.2.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {opencode_pine2pyne-0.2.0.dist-info → opencode_pine2pyne-0.2.2.dist-info}/METADATA +10 -10
- {opencode_pine2pyne-0.2.0.dist-info → opencode_pine2pyne-0.2.2.dist-info}/RECORD +19 -18
- pine2pyne/__init__.py +1 -1
- pine2pyne/ast_nodes.py +1 -0
- pine2pyne/block_value_lowering.py +11 -0
- pine2pyne/codegen.py +20 -5
- pine2pyne/conditional_history_calls.py +96 -0
- pine2pyne/emitted_names.py +8 -2
- pine2pyne/errors.py +2 -1
- pine2pyne/import_resolver.py +55 -2
- pine2pyne/parser.py +113 -31
- pine2pyne/pine_builtins.py +31 -2
- pine2pyne/pine_semantics.py +36 -13
- pine2pyne/scope_renamer.py +54 -12
- pine2pyne/transformer.py +54 -35
- {opencode_pine2pyne-0.2.0.dist-info → opencode_pine2pyne-0.2.2.dist-info}/WHEEL +0 -0
- {opencode_pine2pyne-0.2.0.dist-info → opencode_pine2pyne-0.2.2.dist-info}/entry_points.txt +0 -0
- {opencode_pine2pyne-0.2.0.dist-info → opencode_pine2pyne-0.2.2.dist-info}/licenses/LICENSE +0 -0
- {opencode_pine2pyne-0.2.0.dist-info → opencode_pine2pyne-0.2.2.dist-info}/top_level.txt +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: opencode-pine2pyne
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.2
|
|
4
4
|
Summary: Pine Script v6 to PyneCore Python transpiler
|
|
5
5
|
Author: rubycell
|
|
6
6
|
License-Expression: Apache-2.0
|
|
@@ -87,20 +87,19 @@ so a green run of one says nothing about the others.
|
|
|
87
87
|
|
|
88
88
|
### 1. Unit tests — pytest
|
|
89
89
|
|
|
90
|
-
|
|
90
|
+
6,870 tests over `pine2pyne/` (6,848 passed, 1 skipped, 21 xfailed at a16621b; 93% line / 86% branch coverage).
|
|
91
91
|
|
|
92
92
|
```bash
|
|
93
|
-
.venv/bin/python -m pytest tests/
|
|
93
|
+
.venv/bin/python -m pytest tests/ -q
|
|
94
94
|
|
|
95
95
|
# with coverage
|
|
96
|
-
.venv/bin/python -m pytest tests/
|
|
96
|
+
.venv/bin/python -m pytest tests/ \
|
|
97
97
|
--cov=pine2pyne --cov-report=term-missing
|
|
98
98
|
```
|
|
99
99
|
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
> [board #10](https://github.com/users/rubycell/projects/10).
|
|
100
|
+
A bare `pytest tests/` needs no `--ignore`: `tests/test_screener_regression.py`, which
|
|
101
|
+
imported a `screener` module from a sibling repo that is absent here and aborted the
|
|
102
|
+
whole run at collection, was retired from the repo.
|
|
104
103
|
|
|
105
104
|
Some tests are `@pytest.mark.xfail(strict=True)` and pin **confirmed unfixed
|
|
106
105
|
bugs**, each with a card on [board #10](https://github.com/users/rubycell/projects/10).
|
|
@@ -194,8 +193,9 @@ changes by design.
|
|
|
194
193
|
`backup/deleteable/ground_truth_runs/<tool>-<time>/`, next to the other disposable output, and each run leaves
|
|
195
194
|
one tree of roughly 0.9 GB there (script, settings and three CSVs per sample). A generate run also copies the
|
|
196
195
|
collected files into `ground_truth/<suite>/` (gitignored). Nothing here is deleted by a tool: when you want the
|
|
197
|
-
space back, move old run roots (and the `gt_compare_<time>/` scratch copies) to
|
|
198
|
-
them. An explicit `--run-dir DIR` is
|
|
196
|
+
space back, move old run roots (and the `gt_compare_<time>/` scratch copies) to
|
|
197
|
+
`/mnt/data970/Backup/mike-PC-deleteable/<date>-pine2pyne/`, never `rm` them. An explicit `--run-dir DIR` is
|
|
198
|
+
used as given (it must be empty).
|
|
199
199
|
- **A `REGRESSION` line** names the sample and file whose digest changed. To see
|
|
200
200
|
*what* changed, diff that sample's CSV in the run root's `<suite>/<sample>/<data file>/`
|
|
201
201
|
against a baseline copy. That copy is in `ground_truth/<suite>/<sample>/` if you
|
|
@@ -1,39 +1,40 @@
|
|
|
1
|
-
opencode_pine2pyne-0.2.
|
|
1
|
+
opencode_pine2pyne-0.2.2.dist-info/licenses/LICENSE,sha256=l6ZEJ0BCsllGRX5Pg-ygs6mQD03fLXJggIyKnSMwC8E,11342
|
|
2
2
|
pine2pyne/README.md,sha256=7O2y_Jn9EQ6yNXZio7qAvEqdfVnuiJE_C6zyTdWkUgM,6021
|
|
3
3
|
pine2pyne/TRANSPILER_BEST_PRACTICES.md,sha256=I9UQYI-KlObGGODfItU0kIt-Bo6MVh9XgPfXPRvjh_4,18197
|
|
4
4
|
pine2pyne/TRANSPILER_USAGE.md,sha256=7iT-dnig8t-gMxozVYHgKoxr7W--SITLoyJk41PYlrs,5569
|
|
5
|
-
pine2pyne/__init__.py,sha256=
|
|
5
|
+
pine2pyne/__init__.py,sha256=ZU5aUIYP_ZiNbvSR0z_61_Bvfuouel6AM0WO27aGKOs,2245
|
|
6
6
|
pine2pyne/__main__.py,sha256=w6UY1yZijkjI0YRgq03guOunEYTp9S4DjwsAips2GOk,228
|
|
7
|
-
pine2pyne/ast_nodes.py,sha256=
|
|
7
|
+
pine2pyne/ast_nodes.py,sha256=xk0Zrjdip1sZWE6WINKFK4AK3ikxcOnZkirC9RwDl0E,11354
|
|
8
8
|
pine2pyne/ast_walk.py,sha256=Qt0HUyF7nR3G9kErTB22TuarUJ0g4xQV8QBQ3YeuuIg,4037
|
|
9
|
-
pine2pyne/block_value_lowering.py,sha256=
|
|
9
|
+
pine2pyne/block_value_lowering.py,sha256=gAtc0tX0tBfpqrMwIRhbXOUP5q8F60WHR-5Xjj0SjUE,35086
|
|
10
10
|
pine2pyne/bool_builtins.py,sha256=VSJqSKn06bPNBHm00LDcurzr24ff7lyGr3SrFbGR0XA,1921
|
|
11
11
|
pine2pyne/bool_value_typing.py,sha256=ggy14DtkeQz8JNfAu4rYS3h3Xu6CsEYmI6NqclsGiw8,23265
|
|
12
12
|
pine2pyne/cli.py,sha256=FgL-C0W3DHrgeM-m9hx0PaMOPI0XxN9MNSsPPsf1UP0,7925
|
|
13
|
-
pine2pyne/codegen.py,sha256
|
|
14
|
-
pine2pyne/
|
|
15
|
-
pine2pyne/
|
|
13
|
+
pine2pyne/codegen.py,sha256=-MQfN0OJdrRPPLsTORJk0k4CVPHA-8rn6PWmfyijZxY,37505
|
|
14
|
+
pine2pyne/conditional_history_calls.py,sha256=T2BIN0MpPxLc17nj1VIynHsM2i4l_jd9dTol4Nb0V-E,4556
|
|
15
|
+
pine2pyne/emitted_names.py,sha256=nvs-71JGJsvO0eePSqRl_MBTE3AFRdbZ3IFNPLipTRA,6563
|
|
16
|
+
pine2pyne/errors.py,sha256=6T2OoC0u2inr1XWMIeC3glI6aplL8dcgET7maA4jDjY,2622
|
|
16
17
|
pine2pyne/for_loop_end_bound.py,sha256=y3lTjEvL2jZOVXMZ7zHG8X683mz9IQeySouhNw8uAcI,6350
|
|
17
18
|
pine2pyne/grouped_history_lowering.py,sha256=hxoQcJy0HyvzA7jXQLkcYeJUJ0onDJgKs3Jm5auf5FM,16963
|
|
18
|
-
pine2pyne/import_resolver.py,sha256=
|
|
19
|
+
pine2pyne/import_resolver.py,sha256=mWperlEZomLZ44GTFx6Cez9Wz-AexCPioboAwOJfGXE,22272
|
|
19
20
|
pine2pyne/lexer.py,sha256=wk5O3zEtZnyWLgnr1GwYFcYLWTPA4y-reQLfZq1ew_E,21376
|
|
20
21
|
pine2pyne/library_collision.py,sha256=0c-t-lgNlAmmhhNO286eCp99rW0FhC9wafcGkIWkXI8,22323
|
|
21
22
|
pine2pyne/namespace_members.py,sha256=CO-oAesSy6LWthD2qItUrL3cTm8ZZ2Yulg3q_mD69BA,12859
|
|
22
23
|
pine2pyne/once_lowering.py,sha256=frr0g9nX612MKsPiLyeFEDvyoRcQDQTsBiUZ-qMUiq8,3481
|
|
23
24
|
pine2pyne/overload_resolution.py,sha256=gPELykcmixn0LQT--nEaS85Uwn8FmrOa_fkuytoC8ag,24904
|
|
24
25
|
pine2pyne/parse_repair.py,sha256=Uec959EDCvnqeHdVD1ZpSizH150rUAk55BnYF9EbNBM,18882
|
|
25
|
-
pine2pyne/parser.py,sha256=
|
|
26
|
-
pine2pyne/pine_builtins.py,sha256=
|
|
27
|
-
pine2pyne/pine_semantics.py,sha256=
|
|
28
|
-
pine2pyne/scope_renamer.py,sha256=
|
|
26
|
+
pine2pyne/parser.py,sha256=pMiZJpYn1G-WOzSIrbdo6zzCpNZstpXG2bZoI3DSw7o,75438
|
|
27
|
+
pine2pyne/pine_builtins.py,sha256=H6DCiG3QuUMo2GAsScdzZzzTLsSB1KucLYGqEXavO38,16181
|
|
28
|
+
pine2pyne/pine_semantics.py,sha256=e0CSoUCFp6BYzb2XNIi5_cQVgHfm--lMTKGvaTuraJw,34765
|
|
29
|
+
pine2pyne/scope_renamer.py,sha256=ksyNG4J6xs0SsY3jyCt57pA7K_RhYYFvZYWUlSFe0Kc,43916
|
|
29
30
|
pine2pyne/strict_boolean.py,sha256=7Z-q2tdVk0rFgu4SecX9GVaWgBof_IFtBKjw1tBolB0,5471
|
|
30
31
|
pine2pyne/symbol_table.py,sha256=SO40do-faSu-n29-5GOrkKAqEK6Ef9BGtw4sC0w9Jbo,6146
|
|
31
32
|
pine2pyne/tokens.py,sha256=diG6z5_9DsDCdSN-sapdDAbdIwvklQPuC-05tkhQzDk,3792
|
|
32
|
-
pine2pyne/transformer.py,sha256=
|
|
33
|
+
pine2pyne/transformer.py,sha256=mwgIMx1GRapzPsZfDWNY16NTxDPVsYVI3Y4svWlud3w,115673
|
|
33
34
|
pine2pyne/type_inference.py,sha256=UFg7y9Q5Vkd_NnjQ1DD9LrqJ3ywpHSMHv28D_lQlb08,19895
|
|
34
35
|
pine2pyne/udt_field_defaults.py,sha256=DpOwtiCxKdQjAK5senw2wAzT7JNfgRl3NxCrlLTfk3c,7746
|
|
35
|
-
opencode_pine2pyne-0.2.
|
|
36
|
-
opencode_pine2pyne-0.2.
|
|
37
|
-
opencode_pine2pyne-0.2.
|
|
38
|
-
opencode_pine2pyne-0.2.
|
|
39
|
-
opencode_pine2pyne-0.2.
|
|
36
|
+
opencode_pine2pyne-0.2.2.dist-info/METADATA,sha256=wyP2thJ4q3QjWxhpnUOH5e5iksKYRY09YuxBHkM-B5k,14921
|
|
37
|
+
opencode_pine2pyne-0.2.2.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
|
|
38
|
+
opencode_pine2pyne-0.2.2.dist-info/entry_points.txt,sha256=OQmVtMqXUdYsmXqUEe09w30h54Gmn3JsPjGgVnTO4sA,49
|
|
39
|
+
opencode_pine2pyne-0.2.2.dist-info/top_level.txt,sha256=ge_qvuxsfM_9zOv_hIwyLCMe1S8RAr5nUR6n3aBO6J0,10
|
|
40
|
+
opencode_pine2pyne-0.2.2.dist-info/RECORD,,
|
pine2pyne/__init__.py
CHANGED
pine2pyne/ast_nodes.py
CHANGED
|
@@ -302,6 +302,7 @@ class ForLoop(Statement):
|
|
|
302
302
|
# counter (`pine_loop`) that re-reads it; empty for a fixed `pine_range` (card #82)
|
|
303
303
|
counter_name: str = ""
|
|
304
304
|
counter_helper: str = "" # the name `pine_loop` is imported under (an alias when the script uses the name)
|
|
305
|
+
range_helper: str = "" # the name `pine_range` is imported under for a fixed loop; empty is `pine_range` (card #94)
|
|
305
306
|
|
|
306
307
|
|
|
307
308
|
@dataclass
|
|
@@ -274,6 +274,17 @@ def bool_is_never_na(script: Script) -> bool:
|
|
|
274
274
|
return not version.isdigit() or int(version) >= 6
|
|
275
275
|
|
|
276
276
|
|
|
277
|
+
# Pine v4 and v5 keep a third bool state, na; the runtime names exactly these two versions (`na_bool`)
|
|
278
|
+
THREE_STATE_BOOL_VERSIONS = ('4', '5')
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def keeps_three_state_bool(script: Script) -> bool:
|
|
282
|
+
"""True for a Pine v4 or v5 script: its bool may be na (`bool b = na`, a bool history before
|
|
283
|
+
warm-up), so its decorator sets the runtime's `na_bool` switch (card #99, item 5; MEASURED on
|
|
284
|
+
TradingView 2026-10-06, probe6). A script with no version annotation is v6, as in `bool_is_never_na`."""
|
|
285
|
+
return bool(script.version) and script.version.version in THREE_STATE_BOOL_VERSIONS
|
|
286
|
+
|
|
287
|
+
|
|
277
288
|
def _tuple_width(value, functions: '_UserFunctions') -> Optional[int]:
|
|
278
289
|
"""The width of the tuples `value` yields, from an arm that ends in `[x, y]`,
|
|
279
290
|
in a tuple destructure, or in a call of a user function of known width."""
|
pine2pyne/codegen.py
CHANGED
|
@@ -135,6 +135,17 @@ class CodeGenerator:
|
|
|
135
135
|
self.generate_type_declaration(type_decl)
|
|
136
136
|
self.emit('')
|
|
137
137
|
|
|
138
|
+
# A library's export surface: one Exported proxy per exported name, published in __all__ (card #111).
|
|
139
|
+
# pynecore's `@export` resolves the proxy by name in this module's globals
|
|
140
|
+
exported_names = list(dict.fromkeys(
|
|
141
|
+
statement.name for statement in script.main_body if isinstance(statement, FuncDecl) and statement.is_export))
|
|
142
|
+
if exported_names:
|
|
143
|
+
for exported_name in exported_names:
|
|
144
|
+
self.emit(f'{self._esc(exported_name)} = Exported()')
|
|
145
|
+
self.emit('')
|
|
146
|
+
self.emit('__all__ = [' + ', '.join(f"'{self._esc(name)}'" for name in exported_names) + ']')
|
|
147
|
+
self.emit('')
|
|
148
|
+
|
|
138
149
|
# 4. Main function with decorator (helper functions now inside main)
|
|
139
150
|
if script.main_decorator:
|
|
140
151
|
self.top_level_line = script.main_decorator.line
|
|
@@ -247,9 +258,9 @@ class CodeGenerator:
|
|
|
247
258
|
# Top-level code generation
|
|
248
259
|
# ========================================================================
|
|
249
260
|
|
|
250
|
-
def generate_decorator(self, decl: Union[IndicatorDecl, StrategyDecl]) -> str:
|
|
251
|
-
"""Generate @script.indicator or @script.
|
|
252
|
-
name = 'indicator'
|
|
261
|
+
def generate_decorator(self, decl: Union[IndicatorDecl, StrategyDecl, LibraryDecl]) -> str:
|
|
262
|
+
"""Generate @script.indicator, @script.strategy or @script.library decorator."""
|
|
263
|
+
name = {IndicatorDecl: 'indicator', LibraryDecl: 'library'}.get(type(decl), 'strategy')
|
|
253
264
|
# A None title is an expression, emitted as the 'title' keyword (card #55)
|
|
254
265
|
arguments = [] if decl.title is None else [f"'{self._escape_string(decl.title, chr(39))}'"]
|
|
255
266
|
arguments += [f'{key}={self.generate_decorator_value(value)}' for key, value in decl.kwargs.items()]
|
|
@@ -358,6 +369,9 @@ class CodeGenerator:
|
|
|
358
369
|
# Emit @method decorator if this is a method
|
|
359
370
|
if hasattr(func, 'is_method') and func.is_method:
|
|
360
371
|
self.emit('@method')
|
|
372
|
+
# A library's exported function (card #111); pynecore's @export goes above @overload
|
|
373
|
+
if func.is_export:
|
|
374
|
+
self.emit('@export')
|
|
361
375
|
# Same-name declarations share one pynecore @overload dispatcher (card #39)
|
|
362
376
|
if func.is_overload:
|
|
363
377
|
self.emit('@overload')
|
|
@@ -542,11 +556,12 @@ class CodeGenerator:
|
|
|
542
556
|
self.generate_statement(s)
|
|
543
557
|
self.indent_level -= 1
|
|
544
558
|
return
|
|
559
|
+
range_helper = stmt.range_helper or 'pine_range'
|
|
545
560
|
if stmt.step:
|
|
546
561
|
step = self.generate_expression(stmt.step)
|
|
547
|
-
self.emit(f'for {var} in
|
|
562
|
+
self.emit(f'for {var} in {range_helper}({from_val}, {to_val}, {step}):')
|
|
548
563
|
else:
|
|
549
|
-
self.emit(f'for {var} in
|
|
564
|
+
self.emit(f'for {var} in {range_helper}({from_val}, {to_val}):')
|
|
550
565
|
|
|
551
566
|
self.indent_level += 1
|
|
552
567
|
for s in stmt.body:
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""A `ta.*` call that runs on only some bars (card #96).
|
|
2
|
+
|
|
3
|
+
Pine keeps a call site's series history by running the call on every bar. A `ta.*` call
|
|
4
|
+
reached only when a condition holds keeps a history that skips the other bars, so its value
|
|
5
|
+
differs from the same call made on every bar (card #60 measured this: the transpiled output
|
|
6
|
+
matches Pine's call-site semantics in every construct, and a hoisted call gives another value).
|
|
7
|
+
The Pine User Manual (Execution model) says to run such functions in the global scope for
|
|
8
|
+
consistent results. The transpiler never hoists: it keeps the call where the script has it and
|
|
9
|
+
reports the site, as TradingView does, so the author decides.
|
|
10
|
+
|
|
11
|
+
A call is conditional when it sits in:
|
|
12
|
+
- the body of an `if`, `else if` or `else`, or an `else if` condition (it is read only when the
|
|
13
|
+
earlier ones failed), as a statement or as a value;
|
|
14
|
+
- a branch of `?:`;
|
|
15
|
+
- a `switch` arm or its default, or a case after the first (the first case is always read);
|
|
16
|
+
- the right operand of `and` / `or` in Pine v6, which evaluates them lazily. Pine v5 and earlier
|
|
17
|
+
evaluate both operands (card #65), so the right operand there is not conditional.
|
|
18
|
+
|
|
19
|
+
A function body starts unconditional again: whether the function is called conditionally is not
|
|
20
|
+
decided here. A loop body is not conditional. `ta.vwap` and the other argument-free `ta.`
|
|
21
|
+
variables are not calls and are hoisted by the transpiler already.
|
|
22
|
+
"""
|
|
23
|
+
from typing import List
|
|
24
|
+
|
|
25
|
+
from .ast_nodes import (
|
|
26
|
+
BinaryOp, FuncDecl, FunctionCall, IfExpression, IfStatement, Script, SwitchExpression, SwitchStatement,
|
|
27
|
+
TernaryOp,
|
|
28
|
+
)
|
|
29
|
+
from .ast_walk import child_field_names, is_node
|
|
30
|
+
from .strict_boolean import BOOLEAN_OPERATORS, evaluates_and_or_strictly
|
|
31
|
+
|
|
32
|
+
HISTORY_CALL_PREFIX = 'ta.'
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def conditional_history_calls(script: Script) -> List[FunctionCall]:
|
|
36
|
+
"""Every `ta.*` call of `script` that runs on only some bars, in source order."""
|
|
37
|
+
finder = _ConditionalCallFinder(evaluates_and_or_strictly(script))
|
|
38
|
+
finder.visit(script, False)
|
|
39
|
+
return sorted(finder.calls, key=lambda call: (call.line, call.column))
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class _ConditionalCallFinder:
|
|
43
|
+
def __init__(self, right_operand_always_runs: bool):
|
|
44
|
+
self.right_operand_always_runs = right_operand_always_runs
|
|
45
|
+
self.calls: List[FunctionCall] = []
|
|
46
|
+
|
|
47
|
+
def visit(self, value, conditional: bool) -> None:
|
|
48
|
+
if isinstance(value, (list, tuple)):
|
|
49
|
+
for item in value:
|
|
50
|
+
self.visit(item, conditional)
|
|
51
|
+
elif isinstance(value, dict):
|
|
52
|
+
for item in value.values():
|
|
53
|
+
self.visit(item, conditional)
|
|
54
|
+
elif is_node(value):
|
|
55
|
+
self.visit_node(value, conditional)
|
|
56
|
+
|
|
57
|
+
def visit_node(self, node, conditional: bool) -> None:
|
|
58
|
+
if isinstance(node, (IfStatement, IfExpression, TernaryOp)):
|
|
59
|
+
self.visit_branches(node, conditional)
|
|
60
|
+
elif isinstance(node, (SwitchStatement, SwitchExpression)):
|
|
61
|
+
self.visit_switch(node, conditional)
|
|
62
|
+
elif isinstance(node, BinaryOp) and node.op in BOOLEAN_OPERATORS:
|
|
63
|
+
self.visit(node.left, conditional)
|
|
64
|
+
self.visit(node.right, conditional or not self.right_operand_always_runs)
|
|
65
|
+
elif isinstance(node, FuncDecl):
|
|
66
|
+
self.visit(node.params, False)
|
|
67
|
+
self.visit(node.body, False)
|
|
68
|
+
else:
|
|
69
|
+
if conditional and isinstance(node, FunctionCall) and _is_history_call(node):
|
|
70
|
+
self.calls.append(node)
|
|
71
|
+
for name in child_field_names(type(node)):
|
|
72
|
+
self.visit(getattr(node, name), conditional)
|
|
73
|
+
|
|
74
|
+
def visit_branches(self, node, conditional: bool) -> None:
|
|
75
|
+
"""The condition always runs; each branch and every `else if` condition only after it."""
|
|
76
|
+
self.visit(node.condition, conditional)
|
|
77
|
+
if isinstance(node, IfStatement):
|
|
78
|
+
self.visit(node.body, True)
|
|
79
|
+
for condition, body in node.elseifs:
|
|
80
|
+
self.visit(condition, True)
|
|
81
|
+
self.visit(body, True)
|
|
82
|
+
self.visit(node.else_body, True)
|
|
83
|
+
else:
|
|
84
|
+
self.visit(node.true_expr, True)
|
|
85
|
+
self.visit(node.false_expr, True)
|
|
86
|
+
|
|
87
|
+
def visit_switch(self, node, conditional: bool) -> None:
|
|
88
|
+
self.visit(node.expr, conditional)
|
|
89
|
+
for index, (case, body) in enumerate(node.cases):
|
|
90
|
+
self.visit(case, conditional if index == 0 else True)
|
|
91
|
+
self.visit(body, True)
|
|
92
|
+
self.visit(node.default, True)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _is_history_call(call: FunctionCall) -> bool:
|
|
96
|
+
return isinstance(call.func, str) and call.func.startswith(HISTORY_CALL_PREFIX)
|
pine2pyne/emitted_names.py
CHANGED
|
@@ -28,9 +28,15 @@ from typing import Dict, Set
|
|
|
28
28
|
from .pine_builtins import PYNECORE_LIB_MODULES, PYTHON_RESERVED_WORDS, sanitize_identifier
|
|
29
29
|
|
|
30
30
|
# Names the generated module imports or defines itself; no generated spelling may equal one
|
|
31
|
-
|
|
31
|
+
MODULE_HELPER_NAMES = frozenset({
|
|
32
32
|
'Series', 'Persistent', 'udt', 'method', 'pine_range', 'pine_loop', 'method_call', 'na', 'main', 'script',
|
|
33
|
-
})
|
|
33
|
+
})
|
|
34
|
+
EMITTED_HELPER_NAMES = MODULE_HELPER_NAMES | frozenset(PYNECORE_LIB_MODULES)
|
|
35
|
+
|
|
36
|
+
# A library alias spelled like one of these is renamed (scope_renamer): `lib` is the pynecore library object pynecore's
|
|
37
|
+
# own transformers read in a compiled module, the rest are the helpers the module imports. A namespace or series name
|
|
38
|
+
# is not here: `import x as ta` is pynecore's shadowed_namespace, which a rename would drop (import_resolver refuses it)
|
|
39
|
+
LIBRARY_ALIAS_RENAMED_NAMES = MODULE_HELPER_NAMES | {'lib'}
|
|
34
40
|
|
|
35
41
|
# Fields that hold text, not names: a title or a literal is not an identifier
|
|
36
42
|
_TEXT_FIELDS = {('IndicatorDecl', 'title'), ('StrategyDecl', 'title'), ('LibraryDecl', 'title'),
|
pine2pyne/errors.py
CHANGED
|
@@ -53,7 +53,8 @@ class SemanticError(Pine2PyneError):
|
|
|
53
53
|
class SemanticWarning(UserWarning):
|
|
54
54
|
"""A program TradingView refuses that is still transpiled, output unchanged
|
|
55
55
|
(operator decision 2026-09-24, card #28): a same-scope redeclaration, a read
|
|
56
|
-
before the declaration
|
|
56
|
+
before the declaration; and, though TradingView compiles it, a `ta.*` call
|
|
57
|
+
that runs on only some bars (card #96). Carries the rule's `code` and the Pine position;
|
|
57
58
|
under `-W error` it propagates as an exception like a refusal."""
|
|
58
59
|
def __init__(self, code: str, message: str, line: int = 0, column: int = 0):
|
|
59
60
|
super().__init__(f'{line}:{column}: {message} [{code}]')
|
pine2pyne/import_resolver.py
CHANGED
|
@@ -3,8 +3,10 @@ Import resolver for PyneCore transpiled code.
|
|
|
3
3
|
|
|
4
4
|
Collects all used symbols and generates appropriate import statements.
|
|
5
5
|
"""
|
|
6
|
+
import keyword
|
|
6
7
|
from typing import Set, List
|
|
7
8
|
from .ast_nodes import *
|
|
9
|
+
from .errors import UnsupportedFeatureError
|
|
8
10
|
from .ast_walk import walk
|
|
9
11
|
from .block_value_lowering import bool_is_never_na
|
|
10
12
|
from .udt_field_defaults import FIELD_FACTORY_IMPORT, emitted_default_requires_na, is_series_default
|
|
@@ -30,7 +32,10 @@ class ImportResolver:
|
|
|
30
32
|
self.uses_method = False # User-defined methods
|
|
31
33
|
self.uses_method_call = False # method_call for explicit method calling
|
|
32
34
|
self.uses_overload = False # pynecore @overload for same-name declarations
|
|
35
|
+
self.uses_export = False # a library's `export` functions: the Exported proxy and the @export decorator (card #111)
|
|
36
|
+
self.library_imports: List[ImportDecl] = [] # `import user/lib/version as alias`, one Python import each (card #111)
|
|
33
37
|
self.uses_pine_range = False # pine_range for loops
|
|
38
|
+
self.pine_range_name = 'pine_range' # the name pine_range is imported under; the transformer sets an alias when the script uses the name (card #94)
|
|
34
39
|
self.pine_loop_name = '' # the name pine_loop is imported under: a v6 for loop re-reads its end (card #82)
|
|
35
40
|
self.uses_cast_int = False # cast_int for type casting
|
|
36
41
|
self.uses_cast_float = False # cast_float for type casting
|
|
@@ -55,6 +60,7 @@ class ImportResolver:
|
|
|
55
60
|
def analyze(self, script: Script) -> None:
|
|
56
61
|
"""Analyze script to determine what needs to be imported."""
|
|
57
62
|
self.bool_is_never_na = bool_is_never_na(script)
|
|
63
|
+
self.library_imports = list(script.imports)
|
|
58
64
|
# Pre-pass: collect every name the script declares, so a user variable that
|
|
59
65
|
# shadows a built-in (e.g. hl2) is not mistaken for the built-in below.
|
|
60
66
|
self._collect_declared_names(script)
|
|
@@ -137,6 +143,10 @@ class ImportResolver:
|
|
|
137
143
|
if isinstance(node, (IndicatorDecl, StrategyDecl, LibraryDecl)):
|
|
138
144
|
self.lib_modules.add('script')
|
|
139
145
|
|
|
146
|
+
# A library's exported function (card #111)
|
|
147
|
+
if isinstance(node, FuncDecl) and node.is_export:
|
|
148
|
+
self.uses_export = True
|
|
149
|
+
|
|
140
150
|
# Handle input declarations
|
|
141
151
|
if isinstance(node, InputDecl):
|
|
142
152
|
self.lib_modules.add('input')
|
|
@@ -291,9 +301,46 @@ class ImportResolver:
|
|
|
291
301
|
if module_name in PYNECORE_LIB_MODULES:
|
|
292
302
|
self.lib_modules.add(module_name)
|
|
293
303
|
|
|
304
|
+
def library_import_lines(self) -> List[str]:
|
|
305
|
+
"""`import user/lib/version as alias` is the Python import of the module `lib` under `alias` (card #111).
|
|
306
|
+
|
|
307
|
+
pynecore loads a library as a module (`<lib>.py`, on `sys.path`); the user and the version are not part of
|
|
308
|
+
the module name, so one library name stands for one library: two imports of it that differ in user or
|
|
309
|
+
version are refused, as is a name Python cannot import (a keyword) or an alias (the library name when none is
|
|
310
|
+
given) that would shadow a pynecore.lib name the script reads. (An alias spelled like `lib` or a helper is
|
|
311
|
+
renamed before this point, by the scope renamer.)"""
|
|
312
|
+
lines: List[str] = []
|
|
313
|
+
libraries: dict = {}
|
|
314
|
+
for imported in self.library_imports:
|
|
315
|
+
module = imported.library
|
|
316
|
+
if keyword.iskeyword(module) or not module.isidentifier():
|
|
317
|
+
raise UnsupportedFeatureError(
|
|
318
|
+
f'import {imported.user}/{module}/{imported.version}: "{module}" is not a Python module name',
|
|
319
|
+
imported.line)
|
|
320
|
+
identity = (imported.user, imported.version)
|
|
321
|
+
if libraries.setdefault(module, identity) != identity:
|
|
322
|
+
raise UnsupportedFeatureError(
|
|
323
|
+
f'two imports of the library "{module}" differ in user or version: the module is the library '
|
|
324
|
+
f'name, so one name stands for one library', imported.line)
|
|
325
|
+
alias = imported.alias or module
|
|
326
|
+
if keyword.iskeyword(alias):
|
|
327
|
+
raise UnsupportedFeatureError(
|
|
328
|
+
f'import {imported.user}/{module}/{imported.version} as {alias}: "{alias}" is a Python keyword',
|
|
329
|
+
imported.line)
|
|
330
|
+
if alias in self.lib_modules | self.builtin_variables:
|
|
331
|
+
raise UnsupportedFeatureError(
|
|
332
|
+
f'import {imported.user}/{module}/{imported.version} as {alias}: "{alias}" would shadow a name '
|
|
333
|
+
f'the compiled module binds (a built-in the script reads: pynecore resolves `{alias}.name` '
|
|
334
|
+
f'against the library first and the built-in after, which the transpiler does not emit)',
|
|
335
|
+
imported.line)
|
|
336
|
+
line = f'import {module}' if alias == module else f'import {module} as {alias}'
|
|
337
|
+
if line not in lines:
|
|
338
|
+
lines.append(line)
|
|
339
|
+
return lines
|
|
340
|
+
|
|
294
341
|
def generate_imports(self) -> List[str]:
|
|
295
342
|
"""Generate import statements in the correct order."""
|
|
296
|
-
imports =
|
|
343
|
+
imports = self.library_import_lines()
|
|
297
344
|
|
|
298
345
|
# 0. Typing imports (if used)
|
|
299
346
|
if self.uses_any:
|
|
@@ -308,8 +355,10 @@ class ImportResolver:
|
|
|
308
355
|
imports.append("from pynecore import pine_loop")
|
|
309
356
|
elif self.pine_loop_name:
|
|
310
357
|
imports.append(f"from pynecore import pine_loop as {self.pine_loop_name}")
|
|
311
|
-
if self.uses_pine_range:
|
|
358
|
+
if self.uses_pine_range and self.pine_range_name == 'pine_range':
|
|
312
359
|
imports.append("from pynecore import pine_range")
|
|
360
|
+
elif self.uses_pine_range:
|
|
361
|
+
imports.append(f"from pynecore import pine_range as {self.pine_range_name}")
|
|
313
362
|
|
|
314
363
|
# 2. Pine cast (if used)
|
|
315
364
|
if self.uses_cast_int or self.uses_cast_float or self.uses_cast_bool:
|
|
@@ -331,6 +380,10 @@ class ImportResolver:
|
|
|
331
380
|
method_imports.append('method_call')
|
|
332
381
|
imports.append(f"from pynecore.core.pine_method import {', '.join(method_imports)}")
|
|
333
382
|
|
|
383
|
+
# 3a. A library's export surface (card #111)
|
|
384
|
+
if self.uses_export:
|
|
385
|
+
imports.append("from pynecore.core.pine_export import Exported, export")
|
|
386
|
+
|
|
334
387
|
# 3b. Overload dispatcher for same-name declarations (card #39)
|
|
335
388
|
if self.uses_overload:
|
|
336
389
|
imports.append("from pynecore.core.overload import overload")
|