opencode-pine2pyne 0.2.1__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: opencode-pine2pyne
3
- Version: 0.2.1
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
- 2,000+ tests over `pine2pyne/` (93% line / 86% branch coverage).
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/ --ignore=tests/test_screener_regression.py -q
93
+ .venv/bin/python -m pytest tests/ -q
94
94
 
95
95
  # with coverage
96
- .venv/bin/python -m pytest tests/ --ignore=tests/test_screener_regression.py \
96
+ .venv/bin/python -m pytest tests/ \
97
97
  --cov=pine2pyne --cov-report=term-missing
98
98
  ```
99
99
 
100
- > `--ignore` is required: `tests/test_screener_regression.py` imports a
101
- > `screener` module from a **sibling repo** that is absent here, and fails at
102
- > collection — which aborts the whole run. Tracked as a P0 card on
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 the USB backup disk, never `rm`
198
- them. An explicit `--run-dir DIR` is used as given (it must be empty).
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,40 +1,40 @@
1
- opencode_pine2pyne-0.2.1.dist-info/licenses/LICENSE,sha256=l6ZEJ0BCsllGRX5Pg-ygs6mQD03fLXJggIyKnSMwC8E,11342
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=1tTwXsSNPWDxqxW4B7FKZ9S1atKXDoy1_ZBLo2KMpVc,2245
5
+ pine2pyne/__init__.py,sha256=ZU5aUIYP_ZiNbvSR0z_61_Bvfuouel6AM0WO27aGKOs,2245
6
6
  pine2pyne/__main__.py,sha256=w6UY1yZijkjI0YRgq03guOunEYTp9S4DjwsAips2GOk,228
7
7
  pine2pyne/ast_nodes.py,sha256=xk0Zrjdip1sZWE6WINKFK4AK3ikxcOnZkirC9RwDl0E,11354
8
8
  pine2pyne/ast_walk.py,sha256=Qt0HUyF7nR3G9kErTB22TuarUJ0g4xQV8QBQ3YeuuIg,4037
9
- pine2pyne/block_value_lowering.py,sha256=kXFeEZH-lmptvTqzPsIxTjR0j49QhnGRWX3imfd0vGw,34496
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=aPbG8dSTqk4iRyrYbIX1GrkjESO6iktnhL52p4SsEKg,36639
13
+ pine2pyne/codegen.py,sha256=-MQfN0OJdrRPPLsTORJk0k4CVPHA-8rn6PWmfyijZxY,37505
14
14
  pine2pyne/conditional_history_calls.py,sha256=T2BIN0MpPxLc17nj1VIynHsM2i4l_jd9dTol4Nb0V-E,4556
15
- pine2pyne/emitted_names.py,sha256=UXyDJpbpQHerT97k-p_-sbuR3Ny8qSO1Z-72V0iWwsk,6101
15
+ pine2pyne/emitted_names.py,sha256=nvs-71JGJsvO0eePSqRl_MBTE3AFRdbZ3IFNPLipTRA,6563
16
16
  pine2pyne/errors.py,sha256=6T2OoC0u2inr1XWMIeC3glI6aplL8dcgET7maA4jDjY,2622
17
17
  pine2pyne/for_loop_end_bound.py,sha256=y3lTjEvL2jZOVXMZ7zHG8X683mz9IQeySouhNw8uAcI,6350
18
18
  pine2pyne/grouped_history_lowering.py,sha256=hxoQcJy0HyvzA7jXQLkcYeJUJ0onDJgKs3Jm5auf5FM,16963
19
- pine2pyne/import_resolver.py,sha256=9zBOyFo1-xCqPsRciHsonzc3Geza1VxJQexdDOTD6O0,19153
19
+ pine2pyne/import_resolver.py,sha256=mWperlEZomLZ44GTFx6Cez9Wz-AexCPioboAwOJfGXE,22272
20
20
  pine2pyne/lexer.py,sha256=wk5O3zEtZnyWLgnr1GwYFcYLWTPA4y-reQLfZq1ew_E,21376
21
21
  pine2pyne/library_collision.py,sha256=0c-t-lgNlAmmhhNO286eCp99rW0FhC9wafcGkIWkXI8,22323
22
22
  pine2pyne/namespace_members.py,sha256=CO-oAesSy6LWthD2qItUrL3cTm8ZZ2Yulg3q_mD69BA,12859
23
23
  pine2pyne/once_lowering.py,sha256=frr0g9nX612MKsPiLyeFEDvyoRcQDQTsBiUZ-qMUiq8,3481
24
24
  pine2pyne/overload_resolution.py,sha256=gPELykcmixn0LQT--nEaS85Uwn8FmrOa_fkuytoC8ag,24904
25
25
  pine2pyne/parse_repair.py,sha256=Uec959EDCvnqeHdVD1ZpSizH150rUAk55BnYF9EbNBM,18882
26
- pine2pyne/parser.py,sha256=n4yxbPUiqLmVkeygW7rGmg42TB0AKLtmKEP4syg-ZHk,75010
26
+ pine2pyne/parser.py,sha256=pMiZJpYn1G-WOzSIrbdo6zzCpNZstpXG2bZoI3DSw7o,75438
27
27
  pine2pyne/pine_builtins.py,sha256=H6DCiG3QuUMo2GAsScdzZzzTLsSB1KucLYGqEXavO38,16181
28
- pine2pyne/pine_semantics.py,sha256=CEZuP7YKxCKMZ-Th6wbQ0Bco_O6ks0nc__-CjqO-k8Q,33267
29
- pine2pyne/scope_renamer.py,sha256=Ctovr75gsmeZR0550cuQVZUD7n0ztVebBlv4OuNwghE,41202
28
+ pine2pyne/pine_semantics.py,sha256=e0CSoUCFp6BYzb2XNIi5_cQVgHfm--lMTKGvaTuraJw,34765
29
+ pine2pyne/scope_renamer.py,sha256=ksyNG4J6xs0SsY3jyCt57pA7K_RhYYFvZYWUlSFe0Kc,43916
30
30
  pine2pyne/strict_boolean.py,sha256=7Z-q2tdVk0rFgu4SecX9GVaWgBof_IFtBKjw1tBolB0,5471
31
31
  pine2pyne/symbol_table.py,sha256=SO40do-faSu-n29-5GOrkKAqEK6Ef9BGtw4sC0w9Jbo,6146
32
32
  pine2pyne/tokens.py,sha256=diG6z5_9DsDCdSN-sapdDAbdIwvklQPuC-05tkhQzDk,3792
33
- pine2pyne/transformer.py,sha256=pVoY8WZ5EvnUk1FRj4aZC9gNwt1_VOqtkPaYbYSTv7s,114239
33
+ pine2pyne/transformer.py,sha256=mwgIMx1GRapzPsZfDWNY16NTxDPVsYVI3Y4svWlud3w,115673
34
34
  pine2pyne/type_inference.py,sha256=UFg7y9Q5Vkd_NnjQ1DD9LrqJ3ywpHSMHv28D_lQlb08,19895
35
35
  pine2pyne/udt_field_defaults.py,sha256=DpOwtiCxKdQjAK5senw2wAzT7JNfgRl3NxCrlLTfk3c,7746
36
- opencode_pine2pyne-0.2.1.dist-info/METADATA,sha256=mbXRxdgNaJwM3VIHdAjzIgt5JxgNFWeRcQREt2MYRWA,14976
37
- opencode_pine2pyne-0.2.1.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
38
- opencode_pine2pyne-0.2.1.dist-info/entry_points.txt,sha256=OQmVtMqXUdYsmXqUEe09w30h54Gmn3JsPjGgVnTO4sA,49
39
- opencode_pine2pyne-0.2.1.dist-info/top_level.txt,sha256=ge_qvuxsfM_9zOv_hIwyLCMe1S8RAr5nUR6n3aBO6J0,10
40
- opencode_pine2pyne-0.2.1.dist-info/RECORD,,
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
@@ -5,7 +5,7 @@ A tool to convert TradingView Pine Script indicators and strategies
5
5
  to PyneCore Python code for local backtesting and analysis.
6
6
  """
7
7
 
8
- __version__ = '0.2.1'
8
+ __version__ = '0.2.2'
9
9
  __author__ = 'Pine2Pyne Transpiler'
10
10
 
11
11
  from .lexer import Lexer, tokenize
@@ -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.strategy decorator."""
252
- name = 'indicator' if isinstance(decl, IndicatorDecl) else 'strategy'
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')
@@ -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
- EMITTED_HELPER_NAMES = frozenset({
31
+ MODULE_HELPER_NAMES = frozenset({
32
32
  'Series', 'Persistent', 'udt', 'method', 'pine_range', 'pine_loop', 'method_call', 'na', 'main', 'script',
33
- }) | frozenset(PYNECORE_LIB_MODULES)
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'),
@@ -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,6 +32,8 @@ 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
34
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)
35
39
  self.pine_loop_name = '' # the name pine_loop is imported under: a v6 for loop re-reads its end (card #82)
@@ -56,6 +60,7 @@ class ImportResolver:
56
60
  def analyze(self, script: Script) -> None:
57
61
  """Analyze script to determine what needs to be imported."""
58
62
  self.bool_is_never_na = bool_is_never_na(script)
63
+ self.library_imports = list(script.imports)
59
64
  # Pre-pass: collect every name the script declares, so a user variable that
60
65
  # shadows a built-in (e.g. hl2) is not mistaken for the built-in below.
61
66
  self._collect_declared_names(script)
@@ -138,6 +143,10 @@ class ImportResolver:
138
143
  if isinstance(node, (IndicatorDecl, StrategyDecl, LibraryDecl)):
139
144
  self.lib_modules.add('script')
140
145
 
146
+ # A library's exported function (card #111)
147
+ if isinstance(node, FuncDecl) and node.is_export:
148
+ self.uses_export = True
149
+
141
150
  # Handle input declarations
142
151
  if isinstance(node, InputDecl):
143
152
  self.lib_modules.add('input')
@@ -292,9 +301,46 @@ class ImportResolver:
292
301
  if module_name in PYNECORE_LIB_MODULES:
293
302
  self.lib_modules.add(module_name)
294
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
+
295
341
  def generate_imports(self) -> List[str]:
296
342
  """Generate import statements in the correct order."""
297
- imports = []
343
+ imports = self.library_import_lines()
298
344
 
299
345
  # 0. Typing imports (if used)
300
346
  if self.uses_any:
@@ -334,6 +380,10 @@ class ImportResolver:
334
380
  method_imports.append('method_call')
335
381
  imports.append(f"from pynecore.core.pine_method import {', '.join(method_imports)}")
336
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
+
337
387
  # 3b. Overload dispatcher for same-name declarations (card #39)
338
388
  if self.uses_overload:
339
389
  imports.append("from pynecore.core.overload import overload")
pine2pyne/parser.py CHANGED
@@ -367,7 +367,7 @@ class Parser:
367
367
 
368
368
  def parse_import(self) -> ImportDecl:
369
369
  """Parse import statement: import user/library/version as alias"""
370
- self.expect(TokenType.IMPORT)
370
+ import_token = self.expect(TokenType.IMPORT)
371
371
 
372
372
  # Parse user/library/version as separate tokens joined by DIV (/)
373
373
  # e.g., doqkhanh/tafirstlib/2 → IDENTIFIER DIV IDENTIFIER DIV INT_LITERAL
@@ -393,7 +393,7 @@ class Parser:
393
393
  self.advance()
394
394
  alias = self.expect(TokenType.IDENTIFIER).value
395
395
 
396
- return ImportDecl(user=user, library=library, version=version, alias=alias)
396
+ return ImportDecl(user=user, library=library, version=version, alias=alias, line=import_token.line)
397
397
 
398
398
  def is_function_declaration(self) -> bool:
399
399
  """Check if current position is a function declaration."""
@@ -1037,13 +1037,17 @@ class Parser:
1037
1037
  """`arr.get(0).v += 1` is valid Pine, but the tree keeps an assignment only to a name (a
1038
1038
  dotted field path included) or, for `=`, a tuple. Any other target used to be dropped
1039
1039
  without a word, leaving a bare expression statement, so it is refused at the operator
1040
- (card #94)."""
1040
+ (card #94). A tuple that is not allowed (`[a, b] := f()`, `[a, b] += ...`) has no receiver
1041
+ and no field, so it gets its own text (card #99)."""
1041
1042
  if isinstance(target, Identifier) or (tuple_allowed and isinstance(target, ArrayLiteral)):
1042
1043
  return
1043
- raise UnsupportedFeatureError(
1044
- f'assignment with {operator_token.value!r} to the result of an expression; '
1045
- f'assign the receiver to a variable first and assign its field',
1046
- operator_token.line, operator_token.column)
1044
+ if isinstance(target, ArrayLiteral):
1045
+ advice = ("to a tuple is not supported; destructure into new names with '=' "
1046
+ "and assign each name with its own ':=' statement")
1047
+ else:
1048
+ advice = 'to the result of an expression; assign the receiver to a variable first and assign its field'
1049
+ raise UnsupportedFeatureError(f'assignment with {operator_token.value!r} {advice}',
1050
+ operator_token.line, operator_token.column)
1047
1051
 
1048
1052
  def parse_block(self) -> List[Statement]:
1049
1053
  """Parse a block of statements (indented)."""
@@ -60,6 +60,10 @@ DISCARD_FROM_VERSION = 5
60
60
  # Pine v6 removed the history of a field of a user-defined type, `t.x[1]` (migration guide to v6, "History of
61
61
  # UDT fields"); v5 accepts it
62
62
  FIELD_HISTORY_REFUSED_FROM_VERSION = 6
63
+ # TradingView's Pine v6 compiler refuses a history read of a `for i = a to b` counter: MEASURED 2026-10-06
64
+ # (VN301! 5m): `Error at 5:31: Variable "i" doesn't have history values (CE10078)`, 5:31 being the counter in
65
+ # `nz(i[1], -1)` (card #99, item 1). Earlier versions and the variables of `for ... in` are not measured
66
+ LOOP_COUNTER_HISTORY_REFUSED_FROM_VERSION = 6
63
67
  # Pine v6's namespaces: the heads of the dotted names of the TradingView v6
64
68
  # reference (pinescript-docs-scraper pine_reference_types.json, 2026-03-12)
65
69
  PINE_NAMESPACES = frozenset({
@@ -99,6 +103,7 @@ RESERVED_ENUM_NAMES = PINE_NAMESPACES
99
103
  BUILTIN_NAMES = (PINE_BUILTIN_VARIABLES | PINE_NAMESPACES | frozenset(SymbolTable().builtin_symbols)
100
104
  | SERIES_VARIABLES | PYNECORE_LIB_MODULES | frozenset(NAMESPACE_MEMBERS))
101
105
  PARAMETER, LOOP_VARIABLE, INPUT, VARIABLE = 'parameter', 'loop variable', 'input', 'variable'
106
+ LOOP_COUNTER = 'loop counter' # the variable of `for i = a to b`: a loop variable that has no history
102
107
  STATEMENT_TYPES = typing.get_args(Statement)
103
108
  SCOPE_KIND_TEXT = {'if': 'an if block', 'for': 'a for loop', 'while': 'a while loop',
104
109
  'switch': 'a switch', 'function': 'a function'}
@@ -263,7 +268,7 @@ class _SemanticCheck:
263
268
  elif INPUT in (earlier, how): # an input is declared only at global scope (parser.py top-level loop)
264
269
  self.report(REFUSE, 'duplicate-input', name, f"'{name}' is already declared in this scope "
265
270
  f'(an input and another declaration cannot share a name)')
266
- elif earlier != LOOP_VARIABLE: # a parameter too: UNPROVEN on TradingView, so a warning
271
+ elif earlier not in (LOOP_VARIABLE, LOOP_COUNTER): # a parameter too: UNPROVEN on TradingView, so a warning
267
272
  self.report(WARN, 'redeclared', name, f"'{name}' is already declared in this scope; "
268
273
  f'TradingView refuses a redeclaration, the later one is used here')
269
274
  scope.names.setdefault(name, how)
@@ -403,7 +408,7 @@ class _SemanticCheck:
403
408
  self.block(node.else_body, stack, 'if')
404
409
  elif isinstance(node, ForLoop):
405
410
  self.expression([node.from_val, node.to_val, node.step], stack)
406
- self.block(node.body, stack, 'for', [node.var])
411
+ self.block(node.body, stack, 'for', [node.var], LOOP_COUNTER)
407
412
  elif isinstance(node, ForInLoop):
408
413
  self.expression(node.iterable, stack)
409
414
  self.block(node.body, stack, 'for', node.vars)
@@ -468,6 +473,9 @@ class _SemanticCheck:
468
473
  elif self.version >= FIELD_HISTORY_REFUSED_FROM_VERSION and self.field_read_rule.is_field_read(
469
474
  node.object, lambda name: self.binding_in_scope(name, stack)):
470
475
  self.report(REFUSE, 'history-on-udt-field', '', self.field_history_message(node), node)
476
+ elif self.version >= LOOP_COUNTER_HISTORY_REFUSED_FROM_VERSION and self.is_loop_counter(node.object, stack):
477
+ self.report(REFUSE, 'loop-counter-history', node.object.name,
478
+ f'Variable "{node.object.name}" doesn\'t have history values', node.object)
471
479
  self.expression([node.object, node.index], stack)
472
480
  elif isinstance(node, FunctionCall):
473
481
  if not isinstance(node.func, str):
@@ -490,6 +498,14 @@ class _SemanticCheck:
490
498
  self.expression([getattr(node, field.name) for field in dataclasses.fields(node)
491
499
  if field.name not in ('line', 'column')], stack)
492
500
 
501
+ def is_loop_counter(self, node, stack: List[_Scope]) -> bool:
502
+ """`node` reads the counter of a `for i = a to b` loop that is open here: the innermost binding of
503
+ its name is the counter, so a name a nested block declares again is that declaration's, not the counter's.
504
+ A name the loop body declares again at the counter's own level keeps the counter's binding (a scope's
505
+ first declaration wins) and is refused: UNMEASURED on TradingView, which refuses the redeclaration itself."""
506
+ depth = self.depth_of(stack, node.name) if isinstance(node, Identifier) else None
507
+ return depth is not None and stack[depth].names[node.name] == LOOP_COUNTER
508
+
493
509
  def binding_in_scope(self, name: str, stack: List[_Scope]) -> Optional[HeadBinding]:
494
510
  """The variable `name` names here, with its declared type: the binding in scope, or a
495
511
  global (declared above or further down, typed as the scope renamer types it, by its
@@ -65,7 +65,7 @@ from .ast_nodes import (
65
65
  )
66
66
  from .ast_walk import walk
67
67
  from .emitted_names import (
68
- EMITTED_HELPER_NAMES, KeywordSpellings, free_spelling, identifier_names,
68
+ EMITTED_HELPER_NAMES, KeywordSpellings, LIBRARY_ALIAS_RENAMED_NAMES, free_spelling, identifier_names,
69
69
  )
70
70
  from .errors import UnsupportedFeatureError
71
71
  from .library_collision import (
@@ -183,6 +183,8 @@ class _ScopeRenamer:
183
183
  # type of `x = mk()` (card #87), `x = array.get(a, 0)` or `x = c ? T.new() : na` (card #91)
184
184
  self.type_evidence = script_type_evidence(script)
185
185
  self.namespace_aliases: Dict[str, str] = {}
186
+ # a library alias the compiled module binds itself -> its emitted name (card #111)
187
+ self.library_alias_spellings: Dict[str, str] = {}
186
188
  # user function named like a library name or a builtin series -> its emitted name (shared by its overloads)
187
189
  self.function_names: Dict[str, str] = {}
188
190
  # function or method name -> {renamed parameter: its emitted name}
@@ -270,8 +272,11 @@ class _ScopeRenamer:
270
272
 
271
273
  def type_hint(self, hint: Optional[str]) -> Optional[str]:
272
274
  """A type-hint string with the keyword-named user types it mentions respelled."""
273
- if hint is None or not self.type_tokens:
275
+ if hint is None or not (self.type_tokens or self.library_alias_spellings):
274
276
  return hint
277
+ # a type a library exports (`lib.T`) is spelled through the alias's emitted name
278
+ hint = re.sub(r'\b([A-Za-z_]\w*)(?=\.)',
279
+ lambda match: self.library_alias_spellings.get(match.group(1), match.group(1)), hint)
275
280
  return re.sub(r'\b[A-Za-z_]\w*\b', lambda match: self.type_tokens.get(match.group(0), match.group(0)), hint)
276
281
 
277
282
  def namespace(self, name: str) -> str:
@@ -560,7 +565,9 @@ class _ScopeRenamer:
560
565
  renamed variable, or a namespace call."""
561
566
  constructs = False
562
567
  if '.' in node.func:
563
- func = self.resolve_dotted(node.func, is_call=True)
568
+ # `array.new<lib.T>`: the call is one token; its type argument is a type hint (card #111)
569
+ callee_path, bracket, type_argument = node.func.partition('<')
570
+ func = self.resolve_dotted(callee_path, is_call=True) + bracket + self.type_hint(type_argument)
564
571
  # `t.m(...)`: only a user method's keywords can name a renamed parameter;
565
572
  # `array.get(a, index = 0)` calls the namespace, whatever user method shares the name
566
573
  member = node.func.rpartition('.')[2]
@@ -629,6 +636,7 @@ class _ScopeRenamer:
629
636
  return self.function(declaration)
630
637
  if isinstance(declaration, (VarDecl, VaripDecl)):
631
638
  return replace(declaration, name=self.resolve(declaration.name),
639
+ type_hint=self.type_hint(declaration.type_hint),
632
640
  value=self.own_value(declaration, [declaration.name]))
633
641
  if isinstance(declaration, InputDecl):
634
642
  return self.input_declaration(declaration)
@@ -684,10 +692,21 @@ class _ScopeRenamer:
684
692
 
685
693
  def type_declaration(self, declaration: TypeDecl) -> TypeDecl:
686
694
  """A UDT's name and fields in their emitted spelling; a field's type may name a keyword-named UDT."""
687
- fields = [(self.spellings.attribute(field[0]), self.type_hint(field[1]), *field[2:])
695
+ fields = [(self.spellings.attribute(field[0]), self.type_hint(field[1]), *self.field_default(field[2:]))
688
696
  for field in declaration.fields]
689
697
  return dataclasses.replace(declaration, name=self.type_spelling(declaration.name), fields=fields)
690
698
 
699
+ def field_default(self, default_part: tuple) -> tuple:
700
+ """A field's default, read as it stands in the module: a dotted constant headed by a renamed library alias
701
+ (`lib.Mode.a`) starts with the alias's emitted name (card #111). Every other default is left as written: a
702
+ built-in series (`close`) stays the built-in, whatever a later global or input of its name does."""
703
+ if default_part and isinstance(default_part[0], Identifier):
704
+ default = default_part[0]
705
+ head, dot, _ = default.name.partition('.')
706
+ if dot and head in self.library_alias_spellings:
707
+ return (dataclasses.replace(default, name=self.resolve_dotted(default.name)), *default_part[1:])
708
+ return default_part
709
+
691
710
  def enum_declaration(self, declaration: EnumDecl) -> EnumDecl:
692
711
  """An enum's name and members in their emitted spelling. A member without a value
693
712
  stands for its own name as a string; it keeps that value when its attribute moves."""
@@ -712,15 +731,32 @@ class _ScopeRenamer:
712
731
  names = [self.resolve(name) for name in statement.target.names]
713
732
  return dataclasses.replace(statement, value=value, target=dataclasses.replace(
714
733
  statement.target, names=names, value=value))
715
- return dataclasses.replace(statement, value=value, target=self.resolve(statement.target))
734
+ return dataclasses.replace(statement, value=value, target=self.resolve(statement.target),
735
+ type_hint=self.type_hint(statement.type_hint))
736
+
737
+ def library_aliases(self, script: Script) -> Dict[str, str]:
738
+ """Bind every `import user/lib/version as alias` whose alias (the library name without one) the compiled
739
+ module binds itself to a fresh name: alias -> its emitted name (card #111). Every use of the alias then
740
+ resolves like any renamed global."""
741
+ for imported in script.imports:
742
+ name = imported.alias or imported.library
743
+ if name in LIBRARY_ALIAS_RENAMED_NAMES and name not in self.library_alias_spellings:
744
+ self.library_alias_spellings[name] = self.fresh_name(name)
745
+ self.scopes[0][name] = Binding(emitted=self.library_alias_spellings[name])
746
+ return self.library_alias_spellings
716
747
 
717
748
  def run(self, script: Script) -> Script:
718
749
  self.scopes = [{}]
750
+ renamed_aliases = self.library_aliases(script)
719
751
  self.global_names(script)
720
752
  declarations = [self.in_source_order(self.global_declaration, declaration)
721
753
  for declaration in script.declarations]
722
754
  body = [self.in_source_order(self.global_statement, statement) for statement in script.body]
723
755
  if not (self.shadowed_names or self.library_names or any(self.parameter_names.values())
724
- or self.spellings.changed or self.moved_bindings or self.moved_inputs or self.function_names):
756
+ or self.spellings.changed or self.moved_bindings or self.moved_inputs or self.function_names
757
+ or renamed_aliases):
725
758
  return script
726
- return dataclasses.replace(script, declarations=declarations, body=body)
759
+ imports = [dataclasses.replace(imported, alias=renamed_aliases[imported.alias or imported.library])
760
+ if (imported.alias or imported.library) in renamed_aliases else imported
761
+ for imported in script.imports]
762
+ return dataclasses.replace(script, declarations=declarations, body=body, imports=imports)
pine2pyne/transformer.py CHANGED
@@ -9,7 +9,7 @@ from .ast_nodes import *
9
9
  from .symbol_table import SymbolTable, Symbol, VariableKind
10
10
  from .type_inference import TypeInference, receiver_path
11
11
  from .ast_walk import walk
12
- from .block_value_lowering import bool_is_never_na, lower_block_values
12
+ from .block_value_lowering import bool_is_never_na, keeps_three_state_bool, lower_block_values
13
13
  from .bool_value_typing import stamp_bool_values
14
14
  from .grouped_history_lowering import lower_grouped_history
15
15
  from .for_loop_end_bound import mark_dynamic_end_bounds
@@ -142,6 +142,7 @@ class Transformer:
142
142
  self.current_function_params: Dict[str, str] = {} # Track current function parameters
143
143
  self.current_function_shadowed_names: set = set() # Untyped parameters that also name a global
144
144
  self.bool_is_never_na = True # Pine v6 and later; set per script by transform()
145
+ self.three_state_bool = False # Pine v4 and v5: the decorator sets na_bool; set per script by transform()
145
146
  self.type_inference.current_scope = lambda: (self.current_function_params, self.current_function_shadowed_names)
146
147
  # Each @method function name -> the Python types of its `this` parameter
147
148
  self.method_functions: Dict[str, set] = {}
@@ -226,6 +227,7 @@ class Transformer:
226
227
  # so every stage below sees one binding per name
227
228
  # Pine v6: an untaken if/switch of bool type is false, not na (card #50)
228
229
  self.bool_is_never_na = bool_is_never_na(script)
230
+ self.three_state_bool = keeps_three_state_bool(script)
229
231
  # A binding named like a pynecore.lib name the script also uses gets its
230
232
  # own name; a namespace under an input or export that keeps it gets an alias (card #9)
231
233
  renamed = rename_shadowing_locals(script)
@@ -765,17 +767,21 @@ class Transformer:
765
767
  # Top-level transformations
766
768
  # ========================================================================
767
769
 
768
- def _transform_script_declaration(self, decl: Union[IndicatorDecl, StrategyDecl]) -> Union[IndicatorDecl, StrategyDecl]:
769
- """Transform indicator/strategy declaration (Rules 2-3, 17, 54)."""
770
+ def _transform_script_declaration(self, decl: Union[IndicatorDecl, StrategyDecl, LibraryDecl]) -> Union[IndicatorDecl, StrategyDecl, LibraryDecl]:
771
+ """Transform indicator/strategy/library declaration (Rules 2-3, 17, 54)."""
770
772
  # Transform kwargs: convert true/false to True/False (Rule 17, 54)
771
773
  transformed_kwargs = {}
772
774
  for key, value in decl.kwargs.items():
773
775
  transformed_kwargs[key] = self._transform_decorator_value(value)
776
+ if self.three_state_bool:
777
+ # Pine v4 and v5: `bool b = na` is a real na (card #99, item 5; the runtime's NA(bool) is False without this)
778
+ transformed_kwargs['na_bool'] = True
774
779
 
775
780
  if isinstance(decl, IndicatorDecl):
776
781
  return IndicatorDecl(title=decl.title, kwargs=transformed_kwargs, line=decl.line)
777
- else:
778
- return StrategyDecl(title=decl.title, kwargs=transformed_kwargs, line=decl.line)
782
+ if isinstance(decl, LibraryDecl):
783
+ return LibraryDecl(title=decl.title, kwargs=transformed_kwargs, line=decl.line)
784
+ return StrategyDecl(title=decl.title, kwargs=transformed_kwargs, line=decl.line)
779
785
 
780
786
  def _transform_decorator_value(self, value: Any) -> Any:
781
787
  """Transform decorator keyword argument values (Rule 17, 54)."""
@@ -1001,7 +1007,7 @@ class Transformer:
1001
1007
  params=transformed_params,
1002
1008
  body=transformed_body,
1003
1009
  is_method=func.is_method,
1004
- is_export=False, # Remove export keyword (Rule 46)
1010
+ is_export=func.is_export, # codegen emits `@export` for it (card #111)
1005
1011
  indexed_params=indexed_params,
1006
1012
  )
1007
1013
 
@@ -1486,12 +1492,16 @@ class Transformer:
1486
1492
  for read, (case, _) in zip(reads, cases)]
1487
1493
 
1488
1494
  def _legacy_bool_cast(self, operand: Expression) -> TernaryOp:
1489
- """Pine v5 `bool(x)`: `False if na(x) else bool(x)`. MEASURED on TradingView
1495
+ """Pine v5 `bool(x)`: `na(bool) if na(x) else bool(x)`. MEASURED on TradingView
1490
1496
  (2026-10-05, v5): `bool(1e-10)`, `bool(-1e-10)` and `bool(1.000001e-10)` are
1491
- true, `bool(0.0)` and `bool(na)` of a float are false, and `f(bool(2))` selects
1492
- a bool overload; v5 has no 1e-10 tolerance, unlike v6's `cast_bool`. Python's
1493
- `bool` is true for nan, hence the `na` test. An operand that is not a name or
1494
- a literal is evaluated once, into a temporary."""
1497
+ true, `bool(0.0)` is false, and `f(bool(2))` selects a bool overload; v5 has no
1498
+ 1e-10 tolerance, unlike v6's `cast_bool`. MEASURED again (2026-10-06, probe6):
1499
+ `bool()` of an na float or an na bool is na, typed or untyped, so the na branch is
1500
+ `na(bool)`, not False (it reads as False wherever a condition reads it); that is
1501
+ Pine v5's three-state bool, which the decorator's `na_bool=True` switches on. The
1502
+ card #79 reading `na=false` for `b_na = bool(naF)` is superseded (its script shape
1503
+ differed; the cause is UNPROVEN). Python's `bool` is true for nan, hence the `na`
1504
+ test. An operand that is not a name or a literal is evaluated once, into a temporary."""
1495
1505
  value = self._transform_expression(operand)
1496
1506
  if isinstance(value, Literal) or (isinstance(value, Identifier) and '.' not in value.name):
1497
1507
  tested, read = value, dataclasses.replace(value)
@@ -1500,7 +1510,7 @@ class Transformer:
1500
1510
  tested, read = NamedExpression(name=temporary, value=value), Identifier(name=temporary)
1501
1511
  self.import_resolver.add_module('na')
1502
1512
  return TernaryOp(condition=FunctionCall(func='na', args=[tested], kwargs={}),
1503
- true_expr=Literal(value=False, literal_type='bool'),
1513
+ true_expr=self._na_initialiser('bool'),
1504
1514
  false_expr=FunctionCall(func='bool', args=[read], kwargs={}))
1505
1515
 
1506
1516
  def _free_spelling(self, preferred: str) -> str:
@@ -1807,7 +1817,8 @@ class Transformer:
1807
1817
 
1808
1818
  first_component = func.split('.')[0]
1809
1819
  if (first_component in KNOWN_MODULES or first_component[0].isupper()
1810
- or first_component in self.import_resolver.aliased_modules.values()):
1820
+ or first_component in self.import_resolver.aliased_modules.values()
1821
+ or first_component in self._library_aliases()):
1811
1822
  return None
1812
1823
 
1813
1824
  obj_path, _, method_name = func.rpartition('.') # "obj.lbl", "set_x"
@@ -1827,7 +1838,13 @@ class Transformer:
1827
1838
  """A pynecore namespace or an imported library alias, not a series variable:
1828
1839
  `close.m()` is a method call on the series, `math.abs(x)` is not."""
1829
1840
  return ((name in KNOWN_MODULES and not is_series_variable(name))
1830
- or name in self.import_resolver.aliased_modules.values())
1841
+ or name in self.import_resolver.aliased_modules.values()
1842
+ or name in self._library_aliases())
1843
+
1844
+ def _library_aliases(self) -> set:
1845
+ """The names the script's `import user/lib/version as alias` lines bind (an unaliased import binds the library name):
1846
+ `lib.max(a, b)` calls the library's `max`, it is not a method call on `lib`."""
1847
+ return {imported.alias or imported.library for imported in self._names_source.imports}
1831
1848
 
1832
1849
  def _transform_member_access_method_call(self, call: FunctionCall, func: MemberAccess) -> Optional[Expression]:
1833
1850
  """Handle MemberAccess-based method calls like obj.lbl.set_x(...).