opencode-pine2pyne 0.2.3__py3-none-any.whl → 0.2.5__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.3
3
+ Version: 0.2.5
4
4
  Summary: Pine Script v6 to PyneCore Python transpiler
5
5
  Author: rubycell
6
6
  License-Expression: Apache-2.0
@@ -35,9 +35,10 @@ Backlog and known bugs: [Projects board #10](https://github.com/users/rubycell/p
35
35
  of the PyneCore runtime (repo `/home/mike/workspace/github/pynecore`).
36
36
  - Where it runs: a command-line tool and a Python library. It has no service, no port and no host of its own.
37
37
  Development happens on mike-PC. Full test suites run on Minh_pc (see section 7).
38
- - Package: `opencode-pine2pyne` on PyPI, version `0.2.3` in `pine2pyne/__init__.py` and `CHANGELOG.md`.
39
- Live PyPI state is UNVERIFIED: 0.2.3 is prepared (commit and local tag `v0.2.3`), not uploaded.
40
- `CHANGELOG.md` lists #115 to #118 under 0.2.3; the tag `v0.2.2` is the release before them.
38
+ - Package: `opencode-pine2pyne` on PyPI, version `0.2.5` in `pine2pyne/__init__.py` and `CHANGELOG.md`.
39
+ Live PyPI state is UNVERIFIED: 0.2.5 is prepared (commit and branch `worker/Worker1ForPine2Pyne/release-0-2-5-rebased`), not
40
+ uploaded and not tagged. 0.2.4 is on PyPI (the simple index lists 0.1.0 to 0.2.4; tag `v0.2.4` is pushed).
41
+ `CHANGELOG.md` lists the changes since 0.2.4 under 0.2.5; the tag `v0.2.4` is the release before them.
41
42
  - The transpiler imports only the standard library (`pyproject.toml`: `dependencies = []`).
42
43
  The generated script needs the runtime `opencode-pyneruntime` (`runtime` extra, `>=6.9.1`).
43
44
  - License: Apache-2.0 (`pyproject.toml`, `LICENSE`).
@@ -211,7 +212,7 @@ There are three test systems. A green run of one says nothing about the others.
211
212
  Reports go to `test_results{,_pds}.{json,txt}` at the repo root (git-ignored), or into `--run-dir`.
212
213
  - Latest local reports, 2026-10-02 08:45 (`test_results.json`, `test_results_pds.json`; local files, not tracked):
213
214
  - `sample/pinescript`: 411 run, 2 skipped, 411 transpiled, 393 passed, 18 failed
214
- (11 `pynecore_api`, 5 `missing_security_data`, 2 `type_error`).
215
+ (11 `pynecore_api`, 7 `missing_security_data`).
215
216
  - `sample_pds`: 328 run, 3 skipped, 319 transpiled, 322 passed, 6 failed (all `missing_security_data`).
216
217
  Of the 322 passes, 304 ran clean and 18 are expected-error samples (`expect_error` in
217
218
  `tools/sample_expectations.toml`): 9 `pine_refusal` (transpile refused, so not in the 319),
@@ -1,8 +1,8 @@
1
- opencode_pine2pyne-0.2.3.dist-info/licenses/LICENSE,sha256=l6ZEJ0BCsllGRX5Pg-ygs6mQD03fLXJggIyKnSMwC8E,11342
1
+ opencode_pine2pyne-0.2.5.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=BV4O9H7xipptM5ZmeW0wBotZosKe50QrdXUaILQNuj8,2436
5
+ pine2pyne/__init__.py,sha256=4cvBbiYJdqWhv9CEiYpkhIqnO-t8X1xUoHXTFNhD3l0,2436
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
@@ -10,33 +10,34 @@ pine2pyne/block_value_lowering.py,sha256=gAtc0tX0tBfpqrMwIRhbXOUP5q8F60WHR-5Xjj0
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=-MQfN0OJdrRPPLsTORJk0k4CVPHA-8rn6PWmfyijZxY,37505
13
+ pine2pyne/codegen.py,sha256=h4WVahx8ldPXdgLM9AOLTeTGPPw0lxBkS4ur1cYObzY,37428
14
14
  pine2pyne/conditional_history_calls.py,sha256=T2BIN0MpPxLc17nj1VIynHsM2i4l_jd9dTol4Nb0V-E,4556
15
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=mWperlEZomLZ44GTFx6Cez9Wz-AexCPioboAwOJfGXE,22272
20
- pine2pyne/legacy_function_names.py,sha256=zdIF4fa40A-fkFiwECa3GeGmMT7lZjvVHACs1FbjQ6g,3499
21
- pine2pyne/lexer.py,sha256=wT-F7dptRTqaWXVduVP8xHVjZH8KfUH9pplZvR9RdE0,22810
22
- pine2pyne/library_collision.py,sha256=0c-t-lgNlAmmhhNO286eCp99rW0FhC9wafcGkIWkXI8,22323
19
+ pine2pyne/import_resolver.py,sha256=TgSLAcByc314hKpSOkG4JPLC60keM8F4zx9Wcn_LbTY,24429
20
+ pine2pyne/legacy_function_names.py,sha256=Gz4oNt1_R6y1CEW-6Dwe4V0qTPHS9yq2Tlm8wZWIgLA,4079
21
+ pine2pyne/lexer.py,sha256=HNlY9hgjP4yPndC_LNeBZ19tfikzmesk7eMQDuFmdgw,23478
22
+ pine2pyne/library_collision.py,sha256=5tRGGmlCK3D8U8BZOm36Y0vr7MGJ6ri8EB0qY7DM3Dc,23156
23
+ pine2pyne/merged_namespace_heads.py,sha256=MtNcjNdrObCyfayoGLLc9e8sOeYmXsJD62ZOgyGtshI,1929
23
24
  pine2pyne/namespace_members.py,sha256=CO-oAesSy6LWthD2qItUrL3cTm8ZZ2Yulg3q_mD69BA,12859
24
25
  pine2pyne/once_lowering.py,sha256=frr0g9nX612MKsPiLyeFEDvyoRcQDQTsBiUZ-qMUiq8,3481
25
26
  pine2pyne/overload_resolution.py,sha256=gPELykcmixn0LQT--nEaS85Uwn8FmrOa_fkuytoC8ag,24904
26
- pine2pyne/parse_repair.py,sha256=Uec959EDCvnqeHdVD1ZpSizH150rUAk55BnYF9EbNBM,18882
27
- pine2pyne/parser.py,sha256=c-JQu6LEls_EacpeSGfOHZJSJo_k25wJ9CnojZI3CqE,77634
28
- pine2pyne/pine_builtins.py,sha256=XRds4zd7t2Twdgi7dK06iEvpw73glo863CaSz0wKG5s,16733
27
+ pine2pyne/parse_repair.py,sha256=AAnctVViKJwyE3W1nSGM3Hs9pQZB3yYWFYD_iiRvAYc,19525
28
+ pine2pyne/parser.py,sha256=Jm71A-5B8CoJMO6yeahd7yYfehyL7T6y5yL2YmQiZQY,78885
29
+ pine2pyne/pine_builtins.py,sha256=y7tm98xP3zDsFiUDG6Jv3B8G60WOf8FvfyJt7Gb539k,17475
29
30
  pine2pyne/pine_semantics.py,sha256=e0CSoUCFp6BYzb2XNIi5_cQVgHfm--lMTKGvaTuraJw,34765
30
- pine2pyne/scope_renamer.py,sha256=uM935RXVdQb6QRHd3-mTZN02343EnZE8pFibqr30H5c,44446
31
+ pine2pyne/scope_renamer.py,sha256=akdsjh4qNZi75elazkanxXYuEJ8pe9tax2lQJEH3gqQ,48823
31
32
  pine2pyne/strategy_when_lowering.py,sha256=bN5rAEKGy6bkp3Rm093GnAfpwtswExYsBbBGOdMeMbo,5334
32
33
  pine2pyne/strict_boolean.py,sha256=7Z-q2tdVk0rFgu4SecX9GVaWgBof_IFtBKjw1tBolB0,5471
33
34
  pine2pyne/symbol_table.py,sha256=SO40do-faSu-n29-5GOrkKAqEK6Ef9BGtw4sC0w9Jbo,6146
34
35
  pine2pyne/tokens.py,sha256=diG6z5_9DsDCdSN-sapdDAbdIwvklQPuC-05tkhQzDk,3792
35
- pine2pyne/transformer.py,sha256=mwgIMx1GRapzPsZfDWNY16NTxDPVsYVI3Y4svWlud3w,115673
36
+ pine2pyne/transformer.py,sha256=t3MOFIrajj0fZ8147xlvBAO5FTaEnYdJHs0YTvW3FtY,120975
36
37
  pine2pyne/type_inference.py,sha256=UFg7y9Q5Vkd_NnjQ1DD9LrqJ3ywpHSMHv28D_lQlb08,19895
37
38
  pine2pyne/udt_field_defaults.py,sha256=DpOwtiCxKdQjAK5senw2wAzT7JNfgRl3NxCrlLTfk3c,7746
38
- opencode_pine2pyne-0.2.3.dist-info/METADATA,sha256=PFEJPwfv86uUgLoSrrUQ2Iw6hB87d1b0haOCVzZqNoI,24337
39
- opencode_pine2pyne-0.2.3.dist-info/WHEEL,sha256=a-udL2m4V_6Yn8b-uKzWb12RjRxwwMo6ohYFM24tpaY,91
40
- opencode_pine2pyne-0.2.3.dist-info/entry_points.txt,sha256=OQmVtMqXUdYsmXqUEe09w30h54Gmn3JsPjGgVnTO4sA,49
41
- opencode_pine2pyne-0.2.3.dist-info/top_level.txt,sha256=ge_qvuxsfM_9zOv_hIwyLCMe1S8RAr5nUR6n3aBO6J0,10
42
- opencode_pine2pyne-0.2.3.dist-info/RECORD,,
39
+ opencode_pine2pyne-0.2.5.dist-info/METADATA,sha256=LH1H42cUT3h6R8F9lAVM_H1vj48bDMUoW6rhv2PE2a0,24470
40
+ opencode_pine2pyne-0.2.5.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
41
+ opencode_pine2pyne-0.2.5.dist-info/entry_points.txt,sha256=OQmVtMqXUdYsmXqUEe09w30h54Gmn3JsPjGgVnTO4sA,49
42
+ opencode_pine2pyne-0.2.5.dist-info/top_level.txt,sha256=ge_qvuxsfM_9zOv_hIwyLCMe1S8RAr5nUR6n3aBO6J0,10
43
+ opencode_pine2pyne-0.2.5.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (84.2.0)
2
+ Generator: setuptools (84.2.1)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
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.3'
8
+ __version__ = '0.2.5'
9
9
  __author__ = 'Pine2Pyne Transpiler'
10
10
 
11
11
  from .lexer import Lexer, tokenize
pine2pyne/codegen.py CHANGED
@@ -498,10 +498,6 @@ class CodeGenerator:
498
498
  # Regular assignment
499
499
  value = self.generate_expression(stmt.value)
500
500
 
501
- # Wrap string literals assigned to Color type as Color('...')
502
- if stmt.type_hint == 'Color' and value.startswith("'") and value.endswith("'"):
503
- value = f'Color({value})'
504
-
505
501
  # Add type hint if present
506
502
  if stmt.type_hint:
507
503
  self.emit(f'{target}: {stmt.type_hint} = {value}')
@@ -850,10 +846,11 @@ class CodeGenerator:
850
846
  elif expr.literal_type == 'bool':
851
847
  return 'True' if expr.value else 'False'
852
848
  elif expr.literal_type == 'color':
849
+ # A color is a Color object: pynecore reads .value, .r, .t and compares two colors through it
853
850
  if expr.is_double_quoted:
854
- return f'"{self._escape_string(expr.value, chr(34))}"'
851
+ return f'Color("{self._escape_string(expr.value, chr(34))}")'
855
852
  else:
856
- return f"'{self._escape_string(expr.value, chr(39))}'"
853
+ return f"Color('{self._escape_string(expr.value, chr(39))}')"
857
854
  else:
858
855
  return str(expr.value)
859
856
 
@@ -10,6 +10,7 @@ from .errors import UnsupportedFeatureError
10
10
  from .ast_walk import walk
11
11
  from .block_value_lowering import bool_is_never_na
12
12
  from .udt_field_defaults import FIELD_FACTORY_IMPORT, emitted_default_requires_na, is_series_default
13
+ from .namespace_members import NAMESPACE_MEMBERS
13
14
  from .pine_builtins import (
14
15
  PYNECORE_LIB_MODULES, DRAWING_TYPES, CHART_TYPES,
15
16
  SERIES_VARIABLES, is_series_variable, needs_plot_style_remap
@@ -56,6 +57,9 @@ class ImportResolver:
56
57
  # A namespace spelled by an alias because an input or export keeps its name
57
58
  # (scope_renamer, card #9): module name -> alias ('size' -> '_size_module')
58
59
  self.aliased_modules: dict[str, str] = {}
60
+ # A library imported under the name of a namespace the script reads: namespace -> (the name its module is
61
+ # imported by, the name of the library merged over the built-in namespace) (job transpileerrors2)
62
+ self.shadowed_namespaces: dict[str, tuple[str, str]] = {}
59
63
 
60
64
  def analyze(self, script: Script) -> None:
61
65
  """Analyze script to determine what needs to be imported."""
@@ -127,6 +131,10 @@ class ImportResolver:
127
131
  if isinstance(node, NaLiteral):
128
132
  self.uses_na = True
129
133
 
134
+ # A color literal is emitted as Color('#...') (job colorliteral)
135
+ if isinstance(node, Literal) and node.literal_type == 'color':
136
+ self.drawing_types.add('Color')
137
+
130
138
  # Handle function calls
131
139
  if isinstance(node, FunctionCall):
132
140
  self._process_function_call(node)
@@ -407,6 +415,7 @@ class ImportResolver:
407
415
  self.lib_modules.add('NA')
408
416
 
409
417
  all_lib_imports = []
418
+ self.lib_modules.update('string' if namespace == 'str' else namespace for namespace in self.shadowed_namespaces)
410
419
  if self.lib_modules:
411
420
  all_lib_imports.extend(sorted(self.lib_modules))
412
421
  if self.builtin_variables:
@@ -450,4 +459,21 @@ class ImportResolver:
450
459
  types = sorted(self.chart_types)
451
460
  imports.append(f"from pynecore.types.chart import {', '.join(types)}")
452
461
 
462
+ # 11. A library imported under a namespace name: the name is the library merged over the built-in. The
463
+ # library's exports win and every other member is the built-in's (TradingView, measured; pynecore's
464
+ # `shadowed_namespace`)
465
+ # pynecore imports the submodule `pynecore.lib.<namespace>` for an `import pynecore.lib.<namespace>` statement,
466
+ # not for the bare read the merge line makes, and `pynecore.lib` itself imports only some of them: a fresh
467
+ # `pyne run` failed with "module 'pynecore.lib' has no attribute 'ta'" (job namespaceimport). A name that
468
+ # pynecore.lib defines as a function (`nz`, `fixnan`, `timestamp`, ...) has no submodule, and importing it is a
469
+ # ModuleNotFoundError: NAMESPACE_MEMBERS, generated from the runtime, holds exactly the names that have one
470
+ if self.shadowed_namespaces:
471
+ python_names = {namespace: 'string' if namespace == 'str' else namespace
472
+ for namespace in self.shadowed_namespaces}
473
+ imports.append("from pynecore.core.pine_import import shadowed_namespace")
474
+ imports.extend(f"import pynecore.lib.{python_name}" for python_name in sorted(set(python_names.values()))
475
+ if python_name in NAMESPACE_MEMBERS)
476
+ for namespace, (library_name, merged_name) in sorted(self.shadowed_namespaces.items()):
477
+ imports.append(f"{merged_name} = shadowed_namespace({library_name}, {python_names[namespace]})")
478
+
453
479
  return imports
@@ -12,6 +12,9 @@ name from the table is renamed, and only when the script declares no FUNCTION of
12
12
  scope at the call, so the builtin is the callee. A source with no //@version line, or one at v5 or later, is not
13
13
  touched.
14
14
 
15
+ `iff(cond, then, else)` is a function of those versions too (v5 removed it for `?:`), and it is not a renamed call: the
16
+ transformer emits it (`iff_is_the_function` tells it when the name is the builtin; job iffunction).
17
+
15
18
  Left out on purpose (card #116 follow-ups): names a Python builtin of the same spelling already answers
16
19
  (`abs`, `max`, `min`, `round`, `pow`, `range`), which run today with Python semantics; and the legacy names
17
20
  that are series, not calls (a bare `tr`, `vwap`, `obv`, `tickerid`, ...).
@@ -64,3 +67,9 @@ def qualify_legacy_function_names(script: Script) -> Script:
64
67
  if isinstance(node, FunctionCall) and isinstance(node.func, str) and node.func in renames:
65
68
  node.func = renames[node.func]
66
69
  return script
70
+
71
+
72
+ def iff_is_the_function(script: Script) -> bool:
73
+ """True when a call `iff(...)` of this script is the Pine v1-v4 function: the script declares //@version 1-4
74
+ and no function named `iff` of its own (a user's own `iff` wins, as for every name above)."""
75
+ return 1 <= _declared_version(script) <= 4 and 'iff' not in _declared_function_names(script)
pine2pyne/lexer.py CHANGED
@@ -10,6 +10,10 @@ from .errors import LexerError
10
10
  from .tokens import Token, TokenType, KEYWORDS, TYPE_KEYWORDS
11
11
 
12
12
 
13
+ # A git merge conflict marker: seven `<`, `=` or `>` at the start of a line, then the end of the line or a space
14
+ MERGE_CONFLICT_MARKER = re.compile(r'^(?:<{7}|={7}|>{7})(?=[ \t\r]|$)', re.MULTILINE)
15
+
16
+
13
17
  class Lexer:
14
18
  """Tokenizes Pine Script v6 source code."""
15
19
 
@@ -359,6 +363,12 @@ class Lexer:
359
363
 
360
364
  def tokenize(self) -> List[Token]:
361
365
  """Tokenize the entire source code."""
366
+ marker = MERGE_CONFLICT_MARKER.search(self.source)
367
+ if marker:
368
+ # `<<<<<<<` would lex as `<<` tokens and be refused as an unexpected token, which reads like a
369
+ # transpiler bug; a file saved with an unresolved conflict is not Pine
370
+ raise LexerError(f'unresolved merge conflict marker {marker.group()!r}: resolve the conflict in the file',
371
+ self.source.count('\n', 0, marker.start()) + 1, 1)
362
372
  self.tokens = []
363
373
  at_line_start = True
364
374
 
@@ -44,6 +44,21 @@ def colliding_names(script: Script) -> FrozenSet[str]:
44
44
  return frozenset(bound & used & PYNECORE_LIB_MODULES)
45
45
 
46
46
 
47
+ def namespace_heads_read(script: Script) -> FrozenSet[str]:
48
+ """pynecore.lib namespaces the script writes as a dotted head (`ta.sma(...)`, `math.pi`) and never calls bare.
49
+ A library imported under such a name is merged over the namespace (job transpileerrors2)."""
50
+ dotted: Set[str] = set()
51
+ called: Set[str] = set()
52
+ for node in walk(script):
53
+ if isinstance(node, FunctionCall) and isinstance(node.func, str):
54
+ (dotted if '.' in node.func else called).add(node.func.split('.')[0])
55
+ elif isinstance(node, Identifier) and '.' in node.name:
56
+ dotted.add(node.name.split('.')[0])
57
+ elif isinstance(node, MemberAccess) and isinstance(node.object, str):
58
+ dotted.add(node.object.split('.')[0])
59
+ return frozenset((dotted - called) & (PYNECORE_LIB_MODULES | {'str'}))
60
+
61
+
47
62
  def _names_bound_by(node):
48
63
  if isinstance(node, (VarDecl, VaripDecl, InputDecl, Parameter)):
49
64
  return (node.name,)
@@ -0,0 +1,35 @@
1
+ """The reads of a namespace that a library alias spells, renamed to the merged namespace (job transpileerrors2).
2
+
3
+ `import TradingView/ta/9` makes `ta` the library merged over the built-in `ta` (member by member, as TradingView
4
+ resolves it). The compiled module binds the merged namespace to a name of its own, because pynecore reads every
5
+ imported name as its library object: a rebound `ta` would lose the library's exports. The transformer keeps its
6
+ knowledge of the built-in calls under the name `ta`, so the reads are renamed after it has run: this pass turns each
7
+ dotted read headed by the namespace (`ta.sma`, `ta.atr`, a library export `ta.doubled`) into one headed by the
8
+ merged name.
9
+ """
10
+ import dataclasses
11
+ from typing import Dict
12
+
13
+ from .ast_nodes import FunctionCall, Identifier, MemberAccess
14
+ from .ast_walk import child_field_names, map_children
15
+
16
+
17
+ def rename_namespace_heads(tree, merged_names: Dict[str, str]):
18
+ """A copy of `tree` (nodes, lists, tuples, dicts) in which every dotted function call, identifier and member access
19
+ headed by a key of `merged_names` is headed by its value instead."""
20
+ def rebuild(node):
21
+ changes = {name: map_children(getattr(node, name), rebuild) for name in child_field_names(type(node))}
22
+ if isinstance(node, FunctionCall) and isinstance(node.func, str):
23
+ changes['func'] = _renamed(node.func, merged_names)
24
+ elif isinstance(node, Identifier):
25
+ changes['name'] = _renamed(node.name, merged_names)
26
+ elif isinstance(node, MemberAccess) and isinstance(node.object, str):
27
+ changes['object'] = _renamed(node.object, merged_names)
28
+ return dataclasses.replace(node, **changes)
29
+
30
+ return map_children(tree, rebuild)
31
+
32
+
33
+ def _renamed(dotted: str, merged_names: Dict[str, str]) -> str:
34
+ head, dot, rest = dotted.partition('.')
35
+ return merged_names[head] + dot + rest if dot and head in merged_names else dotted
pine2pyne/parse_repair.py CHANGED
@@ -6,7 +6,8 @@ the spellings of valid Pine below, it is rewritten into the spelling the grammar
6
6
  already accepts, and the source is parsed again. A source that parses today
7
7
  never reaches a repair, so its output cannot change.
8
8
 
9
- row 1 `\\xa0` used as whitespace -> a space (outside strings and comments)
9
+ row 1 a Unicode space separator (Zs) used as whitespace -> a space (outside strings and comments):
10
+ U+00A0, U+2000-U+200A, U+202F, U+205F, U+3000. U+200B (Cf) and U+FEFF stay refused
10
11
  CRLF `\\r\\n` / `\\r` line ends in a str -> `\\n`, as reading the file in text mode does
11
12
  row 2 unary `+x` -> `x`
12
13
  row 3 `.99` -> `0.99`
@@ -25,8 +26,9 @@ Each parse costs one pass of the file's budget; when a chain dead-ends or the
25
26
  budget runs out, the FIRST error is raised, with the message and line:col the
26
27
  unrepaired source gave, and the error the chain ended on as its __cause__.
27
28
 
28
- UNPROVEN on TradingView, pinned by tests/test_parse_repair_card55.py: `\\xa0` as
29
- whitespace; comma statements; `var p = 0, q = 0` makes only `p` a var here; a
29
+ UNPROVEN on TradingView, pinned by tests/test_parse_repair_card55.py: `\\xa0` and the
30
+ Zs spaces other than U+200A as whitespace (U+200A is proven: a script published on
31
+ TradingView has it in its import lines; U+200B is refused by TradingView, measured); comma statements; `var p = 0, q = 0` makes only `p` a var here; a
30
32
  statement led by `+` on the indent grid stays refused; unary `+` on a non-number
31
33
  (`+"a"`) is accepted; an operator-led wrap indented by a multiple of 4 is joined, as
32
34
  the lexer already joins a trailing-operator wrap on any indent.
@@ -40,7 +42,8 @@ from .parser import Parser
40
42
  from .tokens import Token, TokenType
41
43
 
42
44
  MINIMUM_REPAIR_PASSES = 200
43
- NO_BREAK_SPACE = '\xa0'
45
+ # Unicode category Zs, but U+0020 (the lexer reads it already)
46
+ SPACE_SEPARATORS = ('\xa0', *map(chr, range(0x2000, 0x200b)), '\u202f', '\u205f', '\u3000')
44
47
  CARRIAGE_RETURN = '\r'
45
48
 
46
49
  OPERAND_END_TYPES = {
@@ -123,12 +126,12 @@ def _budget_refusal(first_error: ParserError, budget: int) -> ParserError:
123
126
 
124
127
 
125
128
  def _tokenize(source: str, repairs: List[str]) -> Tuple[List[Token], Optional[LexerError]]:
126
- """Lex `source`; on a no-break space or a carriage return, rewrite it once and lex again.
129
+ """Lex `source`; on a space separator or a carriage return, rewrite it once and lex again.
127
130
 
128
131
  Returns the tokens and the first lexer error a rewrite got past (None if none did).
129
132
  """
130
- rewrites = {NO_BREAK_SPACE: ('no_break_space', _no_break_space_outside_strings),
131
- CARRIAGE_RETURN: ('carriage_return', _universal_newlines)}
133
+ rewrites = {character: ('space_separator', _space_separators_outside_strings) for character in SPACE_SEPARATORS}
134
+ rewrites[CARRIAGE_RETURN] = ('carriage_return', _universal_newlines)
132
135
  first_error = None
133
136
  while True:
134
137
  try:
@@ -139,13 +142,15 @@ def _tokenize(source: str, repairs: List[str]) -> Tuple[List[Token], Optional[Le
139
142
  if character not in rewrites:
140
143
  raise first_error from (None if error is first_error else error)
141
144
  kind, rewrite = rewrites.pop(character)
145
+ if kind == 'space_separator': # one rewrite handles every separator
146
+ rewrites = {key: value for key, value in rewrites.items() if value[0] != kind}
142
147
  repairs.append(f'{kind}@{error.line}:{error.column}')
143
148
  source = rewrite(source)
144
149
 
145
150
 
146
151
  def _rejected_character(error: LexerError) -> Optional[str]:
147
152
  """The character of an `Unexpected character: <repr>` lexer error, else None."""
148
- for character in (NO_BREAK_SPACE, CARRIAGE_RETURN):
153
+ for character in (*SPACE_SEPARATORS, CARRIAGE_RETURN):
149
154
  if error.message == f'Unexpected character: {character!r}':
150
155
  return character
151
156
  return None
@@ -156,8 +161,8 @@ def _universal_newlines(source: str) -> str:
156
161
  return source.replace('\r\n', '\n').replace('\r', '\n')
157
162
 
158
163
 
159
- def _no_break_space_outside_strings(source: str) -> str:
160
- """Every `\\xa0` outside a string literal or a `//` comment becomes a space."""
164
+ def _space_separators_outside_strings(source: str) -> str:
165
+ """Every Unicode space separator outside a string literal or a `//` comment becomes a space."""
161
166
  characters, quote, index = list(source), None, 0
162
167
  while index < len(characters):
163
168
  character = characters[index]
@@ -172,7 +177,7 @@ def _no_break_space_outside_strings(source: str) -> str:
172
177
  index = source.find('\n', index)
173
178
  index = len(source) if index < 0 else index
174
179
  continue
175
- elif character == NO_BREAK_SPACE:
180
+ elif character in SPACE_SEPARATORS:
176
181
  characters[index] = ' '
177
182
  index += 1
178
183
  return ''.join(characters)
pine2pyne/parser.py CHANGED
@@ -523,13 +523,16 @@ class Parser:
523
523
  """Parse single-line function body with optional comma-separated statements.
524
524
  Pine Script allows: fn(x) => stmt1, stmt2, return_expr
525
525
  Each comma-separated item can be an assignment or expression.
526
- Returns a single expression (no commas) or a list of statements (commas present).
526
+ Returns a single expression (no commas) or a list of statements (commas present, or
527
+ one declaration: its value is the function's value, as in the multi-line form).
527
528
  """
528
529
  # Parse first item — could be var declaration, assignment, or expression
529
530
  first = self._parse_positioned_single_line_item()
530
531
 
531
532
  # Check for comma (multiple statements)
532
533
  if not self.match(TokenType.COMMA):
534
+ if isinstance(first, (Assignment, VarDecl, VaripDecl)):
535
+ return [first] # A body is an expression or a list of statements, never one declaration
533
536
  return first # Single expression, return as-is
534
537
 
535
538
  # Multiple comma-separated statements
@@ -545,8 +548,8 @@ class Parser:
545
548
  """Parse a single item in a comma-separated single-line function body.
546
549
  Can be: var type name = expr, name = expr, or just expr.
547
550
  """
548
- # Handle 'var' declarations: var type name = expr
549
- if self.match(TokenType.VAR):
551
+ # Handle 'var' and 'varip' declarations: var type name = expr
552
+ if self.match(TokenType.VAR, TokenType.VARIP):
550
553
  return self.parse_statement()
551
554
 
552
555
  # Try assignment: name = expr (look ahead for IDENTIFIER followed by ASSIGN)
@@ -792,35 +795,26 @@ class Parser:
792
795
  result = (self.match(TokenType.ASSIGN) and
793
796
  ((self.peek_token().type == TokenType.IDENTIFIER and
794
797
  self.peek_token().value.startswith('input.')) or
795
- self._legacy_typed_input_call_ahead()))
798
+ self._input_call_ahead()))
796
799
 
797
800
  self.pos = saved_pos
798
801
  return result
799
802
 
800
- def _legacy_typed_input_call_ahead(self) -> bool:
801
- """At `= input(` ... `type=<kind>` ... `)` with a kind parse_function_call rewrites to an input.* call
802
- (card #115): such a call is an input declaration, as its v5 spelling is."""
803
- from .pine_builtins import LEGACY_INPUT_TYPE_ARGUMENT_FUNCTIONS
803
+ def _input_call_ahead(self) -> bool:
804
+ """At `= input(` ...: true when the whole right side is a call parse_function_call rewrote to an
805
+ input.<type> call (a `type=` keyword, card #115, or a default that shows the type), so the statement
806
+ is an input declaration as its input.<type> spelling is. `input(10) * 2` is not: it is an expression."""
804
807
  if self.peek_token().value != 'input' or self.peek_token(2).type != TokenType.LPAREN:
805
808
  return False
806
- depth, offset = 0, 2
807
- while True:
808
- token = self.peek_token(offset)
809
- if token.type == TokenType.EOF:
810
- return False
811
- if token.type in (TokenType.LPAREN, TokenType.LBRACKET):
812
- depth += 1
813
- elif token.type in (TokenType.RPAREN, TokenType.RBRACKET):
814
- depth -= 1
815
- if depth == 0:
816
- return False
817
- elif (depth == 1 and token.type == TokenType.IDENTIFIER and token.value == 'type'
818
- and self.peek_token(offset + 1).type == TokenType.ASSIGN):
819
- kind = self.peek_token(offset + 2)
820
- # a bare `float`/`bool`/`string`/`color` lexes as TYPE_IDENTIFIER; parse_function_call rewrites it too
821
- return (kind.type in (TokenType.IDENTIFIER, TokenType.TYPE_IDENTIFIER)
822
- and kind.value.removeprefix('input.') in LEGACY_INPUT_TYPE_ARGUMENT_FUNCTIONS)
823
- offset += 1
809
+ saved_pos = self.pos
810
+ self.pos += 1 # past the `=`
811
+ try:
812
+ call = self.parse_expression()
813
+ except ParserError:
814
+ return False
815
+ finally:
816
+ self.pos = saved_pos
817
+ return isinstance(call, FunctionCall) and isinstance(call.func, str) and call.func.startswith('input.')
824
818
 
825
819
  def parse_input_declaration(self) -> InputDecl:
826
820
  """Parse input declaration. Handles: name = input.*() and type name = input.*()"""
@@ -1554,10 +1548,10 @@ class Parser:
1554
1548
  else:
1555
1549
  func_name = func
1556
1550
 
1557
- # Pine v2-v4 `input(defval, title, type=input.float)` is the v5 `input.float(defval, title)` (card #115)
1558
- if func_name == 'input' and isinstance(kwargs.get('type'), Identifier):
1559
- from .pine_builtins import LEGACY_INPUT_TYPE_ARGUMENT_FUNCTIONS
1560
- typed_function = LEGACY_INPUT_TYPE_ARGUMENT_FUNCTIONS.get(kwargs['type'].name.removeprefix('input.'))
1551
+ # Pine v2-v4 `input(defval, title, type=input.float)` is the v5 `input.float(defval, title)` (card #115);
1552
+ # a plain `input(20)` is the input.<type> call its default value shows
1553
+ if func_name == 'input':
1554
+ typed_function = self._plain_input_function(args, kwargs)
1561
1555
  if typed_function is not None:
1562
1556
  func_name = typed_function
1563
1557
  kwargs = {key: value for key, value in kwargs.items() if key != 'type'}
@@ -1566,6 +1560,35 @@ class Parser:
1566
1560
  return FunctionCall(func=func_name, args=args, kwargs=kwargs,
1567
1561
  line=getattr(func, 'line', 0), column=getattr(func, 'column', 0))
1568
1562
 
1563
+ @staticmethod
1564
+ def _plain_input_function(args: list, kwargs: dict) -> Optional[str]:
1565
+ """The input.<type> function a plain `input(...)` call stands for, else None (the call stays as it is).
1566
+
1567
+ The `type=` keyword names it (card #115). Else the default value does, as on TradingView: a literal by
1568
+ its type, a negative number by its operand, a builtin source series by its name, `color.<name>` as a
1569
+ color. A call with three or more positional arguments is not decided here: after `title` the order
1570
+ differs by version and by input type.
1571
+ """
1572
+ from .pine_builtins import (LEGACY_INPUT_TYPE_ARGUMENT_FUNCTIONS, PLAIN_INPUT_LITERAL_FUNCTIONS,
1573
+ PLAIN_INPUT_SOURCE_NAMES)
1574
+ if isinstance(kwargs.get('type'), Identifier):
1575
+ return LEGACY_INPUT_TYPE_ARGUMENT_FUNCTIONS.get(kwargs['type'].name.removeprefix('input.'))
1576
+ if len(args) > 2 or (args and 'defval' in kwargs):
1577
+ return None
1578
+ default = args[0] if args else kwargs.get('defval')
1579
+ if isinstance(default, UnaryOp) and default.op == '-' and isinstance(default.operand, Literal):
1580
+ default = default.operand
1581
+ if default.literal_type not in ('int', 'float'):
1582
+ return None
1583
+ if isinstance(default, Literal):
1584
+ return PLAIN_INPUT_LITERAL_FUNCTIONS.get(default.literal_type)
1585
+ if isinstance(default, Identifier):
1586
+ if default.name in PLAIN_INPUT_SOURCE_NAMES:
1587
+ return 'input.source'
1588
+ if default.name.startswith('color.'):
1589
+ return 'input.color'
1590
+ return None
1591
+
1569
1592
  def parse_method_call(self, obj: Expression, method: str) -> MethodCall:
1570
1593
  """Parse method call arguments."""
1571
1594
  self.expect(TokenType.LPAREN)
@@ -268,6 +268,18 @@ LEGACY_INPUT_TYPE_ARGUMENT_FUNCTIONS: Dict[str, str] = {
268
268
  'session': 'input.session', 'time': 'input.time', 'color': 'input.color', 'price': 'input.price',
269
269
  }
270
270
 
271
+ # Plain `input(defval, ...)` (no namespace, v4 and v5) takes its type from the default value, as the input.<type>
272
+ # function of that type does (measured on TradingView: metainfo.inputs of one script). `defval`'s node decides:
273
+ # a literal by its type, a negative number literal by its operand, a builtin source series by its name,
274
+ # a `color.<name>` constant as a color.
275
+ PLAIN_INPUT_LITERAL_FUNCTIONS: Dict[str, str] = {
276
+ 'int': 'input.int', 'float': 'input.float', 'bool': 'input.bool', 'string': 'input.string',
277
+ 'color': 'input.color',
278
+ }
279
+ # The series TradingView lists as a source input's options
280
+ PLAIN_INPUT_SOURCE_NAMES: FrozenSet[str] = frozenset({
281
+ 'open', 'high', 'low', 'close', 'hl2', 'hlc3', 'hlcc4', 'ohlc4', 'volume',
282
+ })
271
283
  # input.int/input.float have a second positional form after `title` (v6 reference): the options form,
272
284
  # selected by a list third argument (pynecore's _bind_numeric_tail, _NUMERIC_OPTIONS_TAIL; card #95).
273
285
  NUMERIC_INPUT_FUNCTIONS: FrozenSet[str] = frozenset({'input.int', 'input.float'})
@@ -22,6 +22,9 @@ not the binding's own member (see library_collision.MemberRule). Two kinds of
22
22
  binding keep their name: an input (its name is the key of the script's input
23
23
  settings) and an `export` declaration (its name is the library's API); a
24
24
  namespace use under such a binding reads an alias of the namespace instead.
25
+ An `export` with a parameter named like a function or method of the script is split into a private `f_body<N>`
26
+ (the same body, its parameters renamed like any function's) and the public export, which keeps the parameter names
27
+ and calls it (card #119).
25
28
 
26
29
  A local named like a builtin series variable (`close`, `time`, `hour`) gets its own name
27
30
  wherever it is declared below the top level: in a function, as a loop variable (card #84) or
@@ -69,7 +72,8 @@ from .emitted_names import (
69
72
  )
70
73
  from .errors import UnsupportedFeatureError
71
74
  from .library_collision import (
72
- MemberRule, binding_type, colliding_names, global_declarations, input_type, script_type_evidence,
75
+ MemberRule, binding_type, colliding_names, global_declarations, input_type, namespace_heads_read,
76
+ script_type_evidence,
73
77
  )
74
78
  from .pine_builtins import (
75
79
  CALLABLE_SERIES_VARIABLES, PYNECORE_LIB_MODULES, PYTHON_RESERVED_WORDS, SERIES_VARIABLES,
@@ -90,6 +94,9 @@ class RenamedScript(NamedTuple):
90
94
  namespace_aliases: Dict[str, str]
91
95
  # function or method name -> {Pine parameter name: its emitted name}
92
96
  parameter_names: Dict[str, Dict[str, str]]
97
+ # namespace -> (the name its library module is imported by, the name of the merged namespace), when a
98
+ # library alias spells a namespace the script reads
99
+ shadowed_namespaces: Dict[str, Tuple[str, str]]
93
100
 
94
101
 
95
102
  @dataclasses.dataclass(frozen=True)
@@ -103,9 +110,38 @@ class Binding:
103
110
  def rename_shadowing_locals(script: Script) -> RenamedScript:
104
111
  """Return a copy of `script` with shadowing locals and library-named
105
112
  bindings renamed. The input script is not modified."""
113
+ script = split_exports_with_shadowed_callees(script)
106
114
  renamer = _ScopeRenamer(script)
107
115
  return RenamedScript(renamer.run(script), renamer.namespace_aliases,
108
- {name: renames for name, renames in renamer.parameter_names.items() if renames})
116
+ {name: renames for name, renames in renamer.parameter_names.items() if renames},
117
+ renamer.shadowed_namespaces)
118
+
119
+
120
+ def split_exports_with_shadowed_callees(script: Script) -> Script:
121
+ """An `export` function keeps its parameter names (its public signature), so a parameter named like a
122
+ function or method of the script hides that function from the exported body. Such an export becomes a
123
+ private function with the same body, whose parameters the renamer then renames like any function's, and an
124
+ export of the same signature that calls it (card #119 follow-up)."""
125
+ function_names = {declaration.name for declaration in script.declarations if isinstance(declaration, FuncDecl)}
126
+ used_names = collect_names(script)
127
+ declarations = []
128
+ split_any = False
129
+ for declaration in script.declarations:
130
+ if not (isinstance(declaration, FuncDecl) and declaration.is_export
131
+ and any(parameter.name in function_names for parameter in declaration.params)):
132
+ declarations.append(declaration)
133
+ continue
134
+ split_any = True
135
+ private_name = fresh_name(f'{declaration.name}_body', used_names)
136
+ declarations.append(dataclasses.replace(
137
+ declaration, name=private_name, is_export=False, is_overload=False,
138
+ params=[dataclasses.replace(parameter, default=None) for parameter in declaration.params]))
139
+ declarations.append(dataclasses.replace(
140
+ declaration, indexed_params=set(),
141
+ body=FunctionCall(func=private_name, args=[Identifier(name=parameter.name)
142
+ for parameter in declaration.params],
143
+ line=declaration.line, column=declaration.column)))
144
+ return dataclasses.replace(script, declarations=declarations) if split_any else script
109
145
 
110
146
 
111
147
  def collect_names(tree) -> Set[str]:
@@ -185,6 +221,9 @@ class _ScopeRenamer:
185
221
  self.namespace_aliases: Dict[str, str] = {}
186
222
  # a library alias the compiled module binds itself -> its emitted name (card #111)
187
223
  self.library_alias_spellings: Dict[str, str] = {}
224
+ # a library alias that spells a namespace the script reads -> (the name the library module is imported by,
225
+ # the name of the library merged over the built-in namespace); merged_namespace_heads renames the reads
226
+ self.shadowed_namespaces: Dict[str, Tuple[str, str]] = {}
188
227
  # user function named like a library name or a builtin series -> its emitted name (shared by its overloads)
189
228
  self.function_names: Dict[str, str] = {}
190
229
  # function or method name -> {renamed parameter: its emitted name}
@@ -205,8 +244,11 @@ class _ScopeRenamer:
205
244
  # sanitized spellings of keyword-named inputs and exports: the settings id and the
206
245
  # library API keep them, so another binding of that spelling moves
207
246
  self.external_spellings: Set[str] = set()
208
- # keyword-named input whose spelling another input holds -> its new name
247
+ # keyword-named input whose spelling another input holds, or input named like a function or method of
248
+ # the script -> its new name
209
249
  self.moved_inputs: Dict[str, str] = {}
250
+ # the inputs named like a function or method of the script: they keep their Pine label (card #119)
251
+ self.inputs_named_like_a_function: Set[str] = set()
210
252
  self.moved_bindings = False
211
253
  # global named like a builtin series -> its first declaration: an input (card #86), a
212
254
  # var, an assignment or a tuple target (card #89)
@@ -479,6 +521,9 @@ class _ScopeRenamer:
479
521
  renames = self.parameter_names.setdefault(name, {})
480
522
  renamed_names = self.library_names if name in exported else self.library_names | global_names
481
523
  renamed_names = renamed_names | self.external_spellings
524
+ if name not in exported:
525
+ # a parameter named like a function or method of the script hides it from the body (card #119)
526
+ renamed_names = renamed_names | self.user_function_names | self.method_names
482
527
  for parameter in declaration.params:
483
528
  if parameter.name in renamed_names and parameter.name not in renames:
484
529
  renames[parameter.name] = self.fresh_name(parameter.name)
@@ -511,6 +556,12 @@ class _ScopeRenamer:
511
556
  self.moved_inputs[name] = free_spelling(spelling, self.spellings.occupied)
512
557
  else:
513
558
  self.external_spellings.add(spelling)
559
+ # an input named like a function or method of the script: the input is a parameter of main() and the
560
+ # script's functions are defined inside main(), so the function overwrites the parameter (card #119)
561
+ self.inputs_named_like_a_function = {name for name in input_names
562
+ if name in self.user_function_names or name in self.method_names}
563
+ for name in sorted(self.inputs_named_like_a_function - self.moved_inputs.keys()):
564
+ self.moved_inputs[name] = self.fresh_name(name)
514
565
  exported = {node.name for node in script.declarations
515
566
  if isinstance(node, FuncDecl) and node.is_export}
516
567
  for name in sorted(exported & PYTHON_RESERVED_WORDS):
@@ -662,8 +713,11 @@ class _ScopeRenamer:
662
713
  [declaration.args, declaration.kwargs])
663
714
  arguments = self.expression(declaration.args), self.expression(declaration.kwargs)
664
715
  self.scopes[0].update(saved)
665
- return dataclasses.replace(declaration, name=self.moved_inputs.get(name, name),
666
- args=arguments[0], kwargs=arguments[1])
716
+ args, kwargs = arguments
717
+ if name in self.inputs_named_like_a_function and len(args) < 2 and 'title' not in kwargs:
718
+ # Pine shows the variable name when the call gives no title: the rename must not change the label
719
+ kwargs = {**kwargs, 'title': Literal(value=name, literal_type='string', is_double_quoted=True)}
720
+ return dataclasses.replace(declaration, name=self.moved_inputs.get(name, name), args=args, kwargs=kwargs)
667
721
 
668
722
  def read_builtin_by_alias(self, names: Set[str], tree) -> Dict[str, Binding]:
669
723
  """Until the caller restores the returned bindings, each input of `names` that `tree`
@@ -749,7 +803,12 @@ class _ScopeRenamer:
749
803
  if name in LIBRARY_ALIAS_RENAMED_NAMES and name not in self.library_alias_spellings:
750
804
  self.library_alias_spellings[name] = self.fresh_name(name)
751
805
  self.scopes[0][name] = Binding(emitted=self.library_alias_spellings[name])
752
- return self.library_alias_spellings
806
+ heads = namespace_heads_read(script)
807
+ for imported in script.imports:
808
+ name = imported.alias or imported.library
809
+ if name in heads and name not in self.library_alias_spellings and name not in self.shadowed_namespaces:
810
+ self.shadowed_namespaces[name] = (self.fresh_name(name), self.fresh_name(name))
811
+ return {**self.library_alias_spellings, **{name: names[0] for name, names in self.shadowed_namespaces.items()}}
753
812
 
754
813
  def run(self, script: Script) -> Script:
755
814
  self.scopes = [{}]
pine2pyne/transformer.py CHANGED
@@ -12,8 +12,10 @@ from .ast_walk import walk
12
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
+ from .legacy_function_names import iff_is_the_function
15
16
  from .for_loop_end_bound import mark_dynamic_end_bounds
16
17
  from .emitted_names import EMITTED_HELPER_NAMES, free_spelling, identifier_names
18
+ from .merged_namespace_heads import rename_namespace_heads
17
19
  from .scope_renamer import collect_names, fresh_name, rename_shadowing_locals
18
20
  from .strict_boolean import evaluates_and_or_strictly
19
21
  from .overload_resolution import OverloadArgumentCoercion, mark_overloaded_declarations
@@ -48,6 +50,8 @@ RANGE_HELPER = 'pine_range' # the runtime's fixed-bound loop helper (card #94)
48
50
  MAP_TYPE_PREFIXES = ('dict',)
49
51
  # The type hints of every collection a for-in can iterate: array, matrix, map
50
52
  COLLECTION_TYPE_PREFIXES = ('list', 'Matrix') + MAP_TYPE_PREFIXES
53
+ # Pine v6 function forms of a syminfo variable; TradingView refuses every other `syminfo.<name>(symbol)`
54
+ SYMBOL_PART_FUNCTIONS = ('syminfo.prefix', 'syminfo.ticker')
51
55
 
52
56
  # pynecore's runtime method dispatcher: `method_call('m', receiver, ...)` runs the
53
57
  # namespace function of the receiver's class (card #8)
@@ -148,6 +152,7 @@ class Transformer:
148
152
  self.method_functions: Dict[str, set] = {}
149
153
  self._renamed_functions: Dict[str, str] = {} # Pine name -> sanitized Python name
150
154
  self._pine_keywords: Dict[str, Dict[str, str]] = {} # set by transform()
155
+ self._iff_is_function = False # set by transform(): a call `iff(...)` is the Pine v1-v4 function
151
156
  # A switch-subject temporary avoids every Pine name of the script; the
152
157
  # names are collected on first need (card #43)
153
158
  self._names_source: Optional[Script] = None
@@ -220,6 +225,7 @@ class Transformer:
220
225
  'for the next script (pine2pyne.transpile() does)')
221
226
  self._transform_started = True # before any work, so a failed transform consumes the instance too
222
227
  output = PyneTransformedScript()
228
+ self._iff_is_function = iff_is_the_function(script)
223
229
  output.strict_boolean_operators = evaluates_and_or_strictly(script)
224
230
  output.bool_is_never_na = bool_is_never_na(script)
225
231
 
@@ -233,6 +239,10 @@ class Transformer:
233
239
  renamed = rename_shadowing_locals(script)
234
240
  script = renamed.script
235
241
  self.import_resolver.aliased_modules = dict(renamed.namespace_aliases)
242
+ self.import_resolver.shadowed_namespaces = dict(renamed.shadowed_namespaces)
243
+ # the transformer has spelled Pine's `str` as the module `string` by the time the reads are renamed
244
+ self._merged_namespace_names = {'string' if name == 'str' else name: merged
245
+ for name, (_, merged) in renamed.shadowed_namespaces.items()}
236
246
  # user function or method name -> {emitted parameter name: its Pine name}:
237
247
  # a builtin method of the same name is called with the Pine keyword (card #17)
238
248
  self._pine_keywords = {name: {emitted: pine for pine, emitted in renames.items()}
@@ -374,6 +384,11 @@ class Transformer:
374
384
  output.main_body, {decl.name for decl in output.enum_declarations},
375
385
  self.type_inference.declared_type_name)
376
386
 
387
+ # The reads of a namespace that a library alias spells go to the merged namespace (job transpileerrors2)
388
+ if self._merged_namespace_names:
389
+ output.main_body = rename_namespace_heads(output.main_body, self._merged_namespace_names)
390
+ output.module_constants = rename_namespace_heads(output.module_constants, self._merged_namespace_names)
391
+
377
392
  # Analyze transformed AST for type names in type hints (Matrix, Line, etc.)
378
393
  self._analyze_transformed_types(output)
379
394
 
@@ -1893,6 +1908,16 @@ class Transformer:
1893
1908
  kwargs={},
1894
1909
  )
1895
1910
 
1911
+ # SPECIAL CASE: the Pine v1-v4 function iff(cond, then, else)
1912
+ if func == 'iff' and self._iff_is_function and len(call.args) == 3 and not call.kwargs:
1913
+ return self._iff_call(call)
1914
+
1915
+ # SPECIAL CASE: syminfo.prefix(symbol) / syminfo.ticker(symbol), the function forms
1916
+ if func in SYMBOL_PART_FUNCTIONS:
1917
+ symbol = self._symbol_argument(call)
1918
+ if symbol is not None:
1919
+ return self._symbol_part(func == 'syminfo.prefix', symbol)
1920
+
1896
1921
  # SPECIAL CASE: array.max(a, nth) / array.min(a, nth) with 2 args
1897
1922
  if func in ('array.max', 'array.min') and len(call.args) == 2:
1898
1923
  self.import_resolver.add_module('order')
@@ -1970,6 +1995,54 @@ class Transformer:
1970
1995
  pine_call, pine_name, call.args, transformed_args, call.kwargs, transformed_kwargs)
1971
1996
  return FunctionCall(func=func, args=transformed_args, kwargs=transformed_kwargs)
1972
1997
 
1998
+ @staticmethod
1999
+ def _symbol_argument(call: FunctionCall) -> Optional[Expression]:
2000
+ """The symbol of `syminfo.ticker(symbol)`, as one positional or `symbol=` argument, else None."""
2001
+ if len(call.args) == 1 and not call.kwargs:
2002
+ return call.args[0]
2003
+ if not call.args and set(call.kwargs) == {'symbol'}:
2004
+ return call.kwargs['symbol']
2005
+ return None
2006
+
2007
+ def _symbol_part(self, is_prefix: bool, symbol: Expression) -> Expression:
2008
+ """`syminfo.prefix(symbol)` (before the FIRST colon) or `syminfo.ticker(symbol)` (after it).
2009
+
2010
+ Measured on TradingView: for "A:B:C" the prefix is "A" and the ticker is "B:C"; a symbol with
2011
+ no colon gives "" for both. PyneCore has only the variables, so the rule is emitted here.
2012
+ A string literal is folded; any other symbol is split once at run time with `string.split`
2013
+ (na for an na symbol, which is passed through), and a lambda binds the pieces so the symbol
2014
+ expression is evaluated once.
2015
+ """
2016
+ if isinstance(symbol, Literal) and symbol.literal_type == 'string':
2017
+ prefix, colon, ticker = symbol.value.partition(':')
2018
+ # No colon: partition() gives the whole symbol as `prefix`, but TradingView's prefix is ""
2019
+ return Literal(value=(prefix if colon else '') if is_prefix else ticker, literal_type='string')
2020
+ self.import_resolver.add_module('string')
2021
+ self.import_resolver.add_module('na')
2022
+ split = FunctionCall(func='string.split',
2023
+ args=[self._transform_expression(symbol), Literal(value=':', literal_type='string')],
2024
+ kwargs={})
2025
+ # The parameter is a name no Pine name of the script holds: pynecore's series pass has no lambda scope,
2026
+ # so a script series of the same name would be read in its place. string.split gives na for an na symbol,
2027
+ # and TradingView gives the string na for both functions then (measured), so the na is passed through
2028
+ # (a "" is the string na only in newer pynecore runtimes).
2029
+ pieces = self._fresh_temporary_name('symbol_pieces')
2030
+ rule = (f'(lambda {pieces}: {pieces} if na({pieces}) else {pieces}[0] if len({pieces}) > 1 else "")' if is_prefix
2031
+ else f'(lambda {pieces}: {pieces} if na({pieces}) else ":".join({pieces}[1:]))')
2032
+ return FunctionCall(func=rule, args=[split], kwargs={})
2033
+
2034
+ def _iff_call(self, call: FunctionCall) -> FunctionCall:
2035
+ """Pine v1-v4 `iff(cond, then, else)`: a function of its three values, so each of them is evaluated on every
2036
+ bar, as the arguments of a call are. A `?:` evaluates only the value it takes, and a call with state (`ta.sma`,
2037
+ a function with a `var`) in the other one would keep a history that skips bars. The three values are passed
2038
+ to a lambda, which Python calls with all of them evaluated. The parameters are names no Pine name of the
2039
+ script holds: pynecore's series pass has no lambda scope, so a script series of the same name would be read in
2040
+ their place (the `syminfo.ticker(symbol)` form binds its pieces the same way)."""
2041
+ condition, then_value, else_value = (self._fresh_temporary_name(stem)
2042
+ for stem in ('iff_condition', 'iff_then', 'iff_else'))
2043
+ rule = f'(lambda {condition}, {then_value}, {else_value}: {then_value} if {condition} else {else_value})'
2044
+ return FunctionCall(func=rule, args=[self._transform_expression(arg) for arg in call.args], kwargs={})
2045
+
1973
2046
  def _transform_method_call(self, call: MethodCall) -> Union[MethodCall, FunctionCall, TernaryOp]:
1974
2047
  """Transform method call (Rule 48)."""
1975
2048
  if '.' in call.method: # zs.get(0).bx.delete() parses as method 'bx.delete' (#36)