pymetrix-eviews 0.1.0a1__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.
- pymetrix_eviews/__init__.py +83 -0
- pymetrix_eviews/_version.py +1 -0
- pymetrix_eviews/app.py +374 -0
- pymetrix_eviews/bundle-1.schema.json +104 -0
- pymetrix_eviews/bundle.py +889 -0
- pymetrix_eviews/dates.py +196 -0
- pymetrix_eviews/export/pymetrix_export.prg +476 -0
- pymetrix_eviews/panel.py +326 -0
- pymetrix_eviews/program/__init__.py +292 -0
- pymetrix_eviews/program/control.py +1368 -0
- pymetrix_eviews/program/data.py +1479 -0
- pymetrix_eviews/program/estimation.py +1133 -0
- pymetrix_eviews/program/ir.py +395 -0
- pymetrix_eviews/program/left.py +89 -0
- pymetrix_eviews/program/models.py +462 -0
- pymetrix_eviews/program/parse.py +124 -0
- pymetrix_eviews/program/report.py +155 -0
- pymetrix_eviews/program/script.py +258 -0
- pymetrix_eviews/program/steps.py +234 -0
- pymetrix_eviews-0.1.0a1.dist-info/METADATA +248 -0
- pymetrix_eviews-0.1.0a1.dist-info/RECORD +24 -0
- pymetrix_eviews-0.1.0a1.dist-info/WHEEL +4 -0
- pymetrix_eviews-0.1.0a1.dist-info/entry_points.txt +8 -0
- pymetrix_eviews-0.1.0a1.dist-info/licenses/LICENSE +28 -0
|
@@ -0,0 +1,1368 @@
|
|
|
1
|
+
"""Phase 3: control flow. Loops, ``if`` blocks, subroutines, included programs, ``exitloop``, ``return`` and ``stop``,
|
|
2
|
+
the program's arguments (``%0``, ``%1``), names made from the program's variables (``y_{%s}``) and the program's own
|
|
3
|
+
values: conditions, loop bounds, and the strings and numbers made with EViews's programming-language functions
|
|
4
|
+
(``@word``, ``@wcount``, ``@wlookup``, ``@isobject``, a group's ``@count`` and ``@seriesname``, an equation's ``@r2``).
|
|
5
|
+
|
|
6
|
+
EViews's date functions (``@dateval``, ``@datestr``, ``@dateadd``, ``@datediff``, ``@dtoo``, ``@otod``) are program
|
|
7
|
+
values too: they act on ``%`` strings and ``!`` numbers, never on series, so they are not pymetrix expressions but
|
|
8
|
+
Python, with ``pymetrix_eviews.dates`` (``eviews_dates`` in the script), worked out at translation time when the
|
|
9
|
+
program's values are known, else when the script runs (a subroutine's parameters, as in FRB/US's ``dateshift``).
|
|
10
|
+
|
|
11
|
+
The program is read into blocks (``build``); the walker (``Flow``) translates them in order with the translator of
|
|
12
|
+
phases 1 and 2. A block becomes the same block in the script (``for i in range(1, n + 1):``, ``if r2 > 0.5:``, a
|
|
13
|
+
subroutine a function), and the same block in steps mode, which runs it in Python and makes each statement inside
|
|
14
|
+
it a recorded step: the History stays flat, as if each step had been made in a dialog. A condition is decided when
|
|
15
|
+
it is reached, so it can use a result made just before (``if eq.@r2 > 0.5``).
|
|
16
|
+
|
|
17
|
+
A block's body is translated once, as the program text is. What a body assigns is a value known only when the
|
|
18
|
+
program runs: lines after it use it by name, never a value guessed before. A name made from such a value
|
|
19
|
+
(``series y_{%s} = log(x_{%s})``) is an f-string in the script (``f"y_{s}"``) and the name made when the step runs;
|
|
20
|
+
which series a page has is no longer checked after it.
|
|
21
|
+
|
|
22
|
+
A subroutine's body is translated at its first ``call`` (on the page then selected), or after the program when
|
|
23
|
+
nothing calls it. EViews passes arguments by reference: a subroutine that assigns a parameter returns it, and the
|
|
24
|
+
call gives the value back to the caller's variable (``simend = dateshift(simstart, simend, 23)``). A subroutine
|
|
25
|
+
that is not ``local`` shares the program's variables (``global`` in the script); a local one shares nothing, and
|
|
26
|
+
the objects it would make are deleted when it returns in EViews, so its data and estimation lines are left out.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import re
|
|
32
|
+
from dataclasses import dataclass, field
|
|
33
|
+
from pathlib import Path
|
|
34
|
+
from typing import Any
|
|
35
|
+
|
|
36
|
+
from .ir import Code, Def, For, If, Invoke, Jump, Text, Var, While, name_code, quote
|
|
37
|
+
from .parse import Program, Statement, parse_program
|
|
38
|
+
from .report import ERROR, LEFT, NOTE, TRANSLATED
|
|
39
|
+
|
|
40
|
+
__all__ = ["Flow", "Node", "PLACEHOLDER", "ProgramValues", "WHILE_CAP", "build", "dynamic_ops", "render_code"]
|
|
41
|
+
|
|
42
|
+
WHILE_CAP = 10_000 # passes of a while loop in steps mode before it stops with an error (ProgramTranslation.run)
|
|
43
|
+
|
|
44
|
+
PLACEHOLDER = re.compile(r"pmxrt(\d+)z") # a program variable's value in a name, while a statement is translated
|
|
45
|
+
|
|
46
|
+
_OPENERS = {"for": "next", "while": "wend", "if": "endif", "subroutine": "endsub"}
|
|
47
|
+
_CLOSERS = {"next": "for", "wend": "while", "endif": "if", "endsub": "subroutine"}
|
|
48
|
+
_WORDS = {"for": "for loop", "while": "while loop", "if": "if block", "subroutine": "subroutine"}
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
# -- blocks ----------------------------------------------------------------------------------------------------------
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass
|
|
55
|
+
class Node:
|
|
56
|
+
"""A statement, or a block with its body: ``kind`` is ``plain``, ``for``, ``while``, ``if``, ``subroutine``,
|
|
57
|
+
``include`` (``included``: the included program's nodes) or ``stray`` (a block's end with no start). ``file`` is
|
|
58
|
+
the program the statement is in ('' for the main one)."""
|
|
59
|
+
|
|
60
|
+
st: Statement
|
|
61
|
+
kind: str
|
|
62
|
+
file: str = ""
|
|
63
|
+
body: list[Node] = field(default_factory=list)
|
|
64
|
+
orelse: list[Node] = field(default_factory=list)
|
|
65
|
+
else_st: Statement | None = None
|
|
66
|
+
close: Statement | None = None
|
|
67
|
+
included: list[Node] = field(default_factory=list)
|
|
68
|
+
program: Program | None = None # an included program, read
|
|
69
|
+
error: str = ""
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _blocks(program: Program, file: str) -> list[Node]:
|
|
73
|
+
top: list[Node] = []
|
|
74
|
+
stack: list[tuple[Node, list[Node]]] = [] # an open block and the body being filled
|
|
75
|
+
for st in program.statements:
|
|
76
|
+
word = st.word if st.kind == "command" else ""
|
|
77
|
+
into = stack[-1][1] if stack else top
|
|
78
|
+
if word in _OPENERS:
|
|
79
|
+
node = Node(st, word, file)
|
|
80
|
+
into.append(node)
|
|
81
|
+
stack.append((node, node.body))
|
|
82
|
+
elif word == "else" and stack and stack[-1][0].kind == "if" and stack[-1][0].else_st is None:
|
|
83
|
+
node = stack[-1][0]
|
|
84
|
+
node.else_st = st
|
|
85
|
+
stack[-1] = (node, node.orelse)
|
|
86
|
+
elif word in _CLOSERS and stack and stack[-1][0].kind == _CLOSERS[word]:
|
|
87
|
+
stack.pop()[0].close = st
|
|
88
|
+
elif word in _CLOSERS or word == "else":
|
|
89
|
+
what = f"{word} without its {_CLOSERS.get(word, 'if')}" + (f" (the {_WORDS[stack[-1][0].kind]} open at line "
|
|
90
|
+
f"{stack[-1][0].st.line} ends with "
|
|
91
|
+
f"{_OPENERS[stack[-1][0].kind]})" if stack else "")
|
|
92
|
+
into.append(Node(st, "stray", file, error=what))
|
|
93
|
+
else:
|
|
94
|
+
into.append(Node(st, "include" if word == "include" else "plain", file))
|
|
95
|
+
for node, _ in stack:
|
|
96
|
+
node.error = f"the {_WORDS[node.kind]} has no {_OPENERS[node.kind]}"
|
|
97
|
+
return top
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def build(program: Program, file: str = "", folder: Path | None = None, seen: tuple[str, ...] = ()) -> list[Node]:
|
|
101
|
+
"""The program's blocks, with each included program read (relative to ``folder``) and its blocks inside the
|
|
102
|
+
``include`` node."""
|
|
103
|
+
nodes = _blocks(program, file)
|
|
104
|
+
|
|
105
|
+
def walk(ns: list[Node]) -> None:
|
|
106
|
+
for n in ns:
|
|
107
|
+
if n.kind == "include":
|
|
108
|
+
_include(n, folder, seen)
|
|
109
|
+
walk(n.body)
|
|
110
|
+
walk(n.orelse)
|
|
111
|
+
|
|
112
|
+
walk(nodes)
|
|
113
|
+
return nodes
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _include(node: Node, folder: Path | None, seen: tuple[str, ...]) -> None:
|
|
117
|
+
words = re.findall(r'"[^"]*"|\S+', node.st.rest)
|
|
118
|
+
if len(words) != 1:
|
|
119
|
+
node.error = "include names one program: include lib.prg"
|
|
120
|
+
return
|
|
121
|
+
name = words[0].strip('"').replace("\\", "/")
|
|
122
|
+
path = Path(name if name.lower().endswith(".prg") else name + ".prg")
|
|
123
|
+
if not path.is_absolute():
|
|
124
|
+
path = (folder or Path.cwd()) / path
|
|
125
|
+
shown = name if name.lower().endswith(".prg") else name + ".prg"
|
|
126
|
+
if not path.is_file():
|
|
127
|
+
node.error = f"the included program {shown} is not found (looked for {path})"
|
|
128
|
+
return
|
|
129
|
+
key = str(path.resolve()).lower()
|
|
130
|
+
if key in seen:
|
|
131
|
+
node.error = f"{shown} includes itself (through {' -> '.join(Path(s).name for s in seen)})"
|
|
132
|
+
return
|
|
133
|
+
raw = path.read_bytes()
|
|
134
|
+
try:
|
|
135
|
+
text = raw.decode("utf-8-sig")
|
|
136
|
+
except UnicodeDecodeError:
|
|
137
|
+
text = raw.decode("cp1252")
|
|
138
|
+
node.program = parse_program(text)
|
|
139
|
+
node.included = build(node.program, shown, path.parent, (*seen, key))
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _assigned(nodes: list[Node], subs: dict[str, Any], seen: set[str] | None = None) -> set[str]:
|
|
143
|
+
"""The program variables (``!x``, ``%s``, scalars and strings) that statements in ``nodes`` may assign, through
|
|
144
|
+
the subroutines they call too."""
|
|
145
|
+
seen = set() if seen is None else seen
|
|
146
|
+
out: set[str] = set()
|
|
147
|
+
for n in nodes:
|
|
148
|
+
st = n.st
|
|
149
|
+
if st.kind == "assign" and st.lhs[:1] in "!%":
|
|
150
|
+
out.add(st.lhs.lower())
|
|
151
|
+
elif st.kind == "assign" and not st.lhs[:1] in "{(":
|
|
152
|
+
out.add(st.lhs.lower())
|
|
153
|
+
elif st.kind == "command" and st.word in ("scalar", "string"):
|
|
154
|
+
m = re.match(r"\s*([A-Za-z_]\w*)", st.rest)
|
|
155
|
+
if m:
|
|
156
|
+
out.add(m.group(1).lower())
|
|
157
|
+
elif st.kind == "command" and st.word == "for":
|
|
158
|
+
m = re.match(r"\s*([!%]\w+)", st.rest)
|
|
159
|
+
if m:
|
|
160
|
+
out.add(m.group(1).lower())
|
|
161
|
+
elif st.kind == "command" and st.word == "call":
|
|
162
|
+
m = re.match(r"\s*(\w+)\s*(?:\((.*)\))?\s*$", st.rest, re.S)
|
|
163
|
+
if m:
|
|
164
|
+
for a in _split_args(m.group(2) or ""):
|
|
165
|
+
if re.fullmatch(r"\s*[!%]\w+\s*", a):
|
|
166
|
+
out.add(a.strip().lower())
|
|
167
|
+
sub = subs.get(m.group(1).lower())
|
|
168
|
+
if sub is not None and not sub.local and sub.name not in seen:
|
|
169
|
+
seen.add(sub.name)
|
|
170
|
+
out |= _assigned(sub.node.body, subs, seen)
|
|
171
|
+
out |= _assigned(n.body, subs, seen) | _assigned(n.orelse, subs, seen) | _assigned(n.included, subs, seen)
|
|
172
|
+
return out
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _split_args(text: str) -> list[str]:
|
|
176
|
+
"""Arguments separated by commas outside brackets and quotes."""
|
|
177
|
+
out, depth, start, quoted = [], 0, 0, False
|
|
178
|
+
for i, ch in enumerate(text):
|
|
179
|
+
if ch == '"':
|
|
180
|
+
quoted = not quoted
|
|
181
|
+
elif not quoted and ch == "(":
|
|
182
|
+
depth += 1
|
|
183
|
+
elif not quoted and ch == ")":
|
|
184
|
+
depth -= 1
|
|
185
|
+
elif not quoted and ch == "," and depth == 0:
|
|
186
|
+
out.append(text[start:i])
|
|
187
|
+
start = i + 1
|
|
188
|
+
if text.strip():
|
|
189
|
+
out.append(text[start:])
|
|
190
|
+
return out
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
# -- names made as the program runs ---------------------------------------------------------------------------------
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _to_text(s: str, registry: dict[int, str]) -> Any:
|
|
197
|
+
if not PLACEHOLDER.search(s):
|
|
198
|
+
return s
|
|
199
|
+
parts: list[Any] = []
|
|
200
|
+
pos = 0
|
|
201
|
+
for m in PLACEHOLDER.finditer(s):
|
|
202
|
+
if m.start() > pos:
|
|
203
|
+
parts.append(s[pos:m.start()])
|
|
204
|
+
parts.append(Var(registry[int(m.group(1))]))
|
|
205
|
+
pos = m.end()
|
|
206
|
+
if pos < len(s):
|
|
207
|
+
parts.append(s[pos:])
|
|
208
|
+
return Text(tuple(parts))
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _fstring(literal: str, registry: dict[int, str]) -> str:
|
|
212
|
+
"""A string literal of the script with the placeholders as an f-string's fields."""
|
|
213
|
+
prefix = ""
|
|
214
|
+
if literal[:1] in "fF":
|
|
215
|
+
prefix, literal = "f", literal[1:]
|
|
216
|
+
quote_ch = literal[0]
|
|
217
|
+
body = literal[1:-1]
|
|
218
|
+
if not prefix:
|
|
219
|
+
body = body.replace("{", "{{").replace("}", "}}")
|
|
220
|
+
body = PLACEHOLDER.sub(lambda m: "{" + registry[int(m.group(1))] + "}", body)
|
|
221
|
+
return f"f{quote_ch}{body}{quote_ch}"
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def render_code(code: str, registry: dict[int, str]) -> str:
|
|
225
|
+
"""Python with placeholders made into what runs: in a string, an f-string's field (``f"log(x_{s})"``); in a
|
|
226
|
+
name, the object of that name (``globals()[f"eq_{c}"]``)."""
|
|
227
|
+
if not PLACEHOLDER.search(code):
|
|
228
|
+
return code
|
|
229
|
+
out: list[str] = []
|
|
230
|
+
pos = 0
|
|
231
|
+
|
|
232
|
+
def names(text: str) -> str:
|
|
233
|
+
def one(m: re.Match[str]) -> str:
|
|
234
|
+
if not PLACEHOLDER.search(m.group(0)) or (m.start() > 0 and text[m.start() - 1] == "."):
|
|
235
|
+
return m.group(0)
|
|
236
|
+
return f"globals()[{_fstring(quote(m.group(0)), registry)}]"
|
|
237
|
+
|
|
238
|
+
return re.sub(r"[A-Za-z_]\w*", one, text)
|
|
239
|
+
|
|
240
|
+
for m in re.finditer(r'[fF]?"(?:[^"\\]|\\.)*"|[fF]?\'(?:[^\'\\]|\\.)*\'', code):
|
|
241
|
+
out.append(names(code[pos:m.start()]))
|
|
242
|
+
out.append(_fstring(m.group(0), registry) if PLACEHOLDER.search(m.group(0)) else m.group(0))
|
|
243
|
+
pos = m.end()
|
|
244
|
+
out.append(names(code[pos:]))
|
|
245
|
+
return "".join(out)
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _dyn(value: Any, registry: dict[int, str]) -> Any:
|
|
249
|
+
import dataclasses
|
|
250
|
+
|
|
251
|
+
from .ir import Arg, Attr, New, RefTo, SampleSpec
|
|
252
|
+
|
|
253
|
+
if isinstance(value, str):
|
|
254
|
+
return _to_text(value, registry)
|
|
255
|
+
if isinstance(value, Text):
|
|
256
|
+
parts: list[Any] = []
|
|
257
|
+
for p in value.parts:
|
|
258
|
+
t = _to_text(p, registry) if isinstance(p, str) else p
|
|
259
|
+
parts.extend(t.parts if isinstance(t, Text) else [t])
|
|
260
|
+
return Text(tuple(parts))
|
|
261
|
+
if isinstance(value, SampleSpec):
|
|
262
|
+
return dataclasses.replace(value, start=_dyn(value.start, registry), end=_dyn(value.end, registry),
|
|
263
|
+
where=_dyn(value.where, registry))
|
|
264
|
+
if isinstance(value, New):
|
|
265
|
+
return dataclasses.replace(value, args=tuple(_dyn(a, registry) for a in value.args))
|
|
266
|
+
if isinstance(value, Arg):
|
|
267
|
+
return dataclasses.replace(value, value=_dyn(value.value, registry))
|
|
268
|
+
if isinstance(value, RefTo) and isinstance(value.name, str):
|
|
269
|
+
return RefTo(_to_text(value.name, registry))
|
|
270
|
+
if isinstance(value, Attr):
|
|
271
|
+
return value if not PLACEHOLDER.search(value.base) else value # an attribute of a page: pages are never made so
|
|
272
|
+
if isinstance(value, dict):
|
|
273
|
+
return {_dyn(k, registry): _dyn(v, registry) for k, v in value.items()}
|
|
274
|
+
if isinstance(value, list):
|
|
275
|
+
return [_dyn(v, registry) for v in value]
|
|
276
|
+
if isinstance(value, tuple):
|
|
277
|
+
return tuple(_dyn(v, registry) for v in value)
|
|
278
|
+
return value
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def dynamic_ops(ops: list[Any], registry: dict[int, str]) -> list[Any]:
|
|
282
|
+
"""A statement's ops with the placeholders of the program's values made into names made as the program runs."""
|
|
283
|
+
import dataclasses
|
|
284
|
+
|
|
285
|
+
from .ir import Cmd, Step
|
|
286
|
+
|
|
287
|
+
out: list[Any] = []
|
|
288
|
+
for op in ops:
|
|
289
|
+
if isinstance(op, Step):
|
|
290
|
+
out.append(dataclasses.replace(
|
|
291
|
+
op, receiver=_to_text(op.receiver, registry) if isinstance(op.receiver, str) else _dyn(op.receiver, registry),
|
|
292
|
+
output=_to_text(op.output, registry), callee=render_code(op.callee, registry),
|
|
293
|
+
args=tuple(_dyn(a, registry) for a in op.args)))
|
|
294
|
+
elif isinstance(op, Code):
|
|
295
|
+
out.append(Code(render_code(op.code, registry), tuple(_to_text(n, registry) for n in op.names)))
|
|
296
|
+
elif isinstance(op, Cmd):
|
|
297
|
+
fields = {f.name: _to_text(getattr(op.command, f.name), registry) for f in dataclasses.fields(op.command)
|
|
298
|
+
if isinstance(getattr(op.command, f.name), str) and PLACEHOLDER.search(getattr(op.command, f.name))}
|
|
299
|
+
if fields:
|
|
300
|
+
out.append(dataclasses.replace(op, fields=fields, script=render_code(op.command.to_code(), registry)))
|
|
301
|
+
else:
|
|
302
|
+
out.append(op)
|
|
303
|
+
else:
|
|
304
|
+
out.append(op)
|
|
305
|
+
return out
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
# -- the program's values ---------------------------------------------------------------------------------------------
|
|
309
|
+
|
|
310
|
+
_TOKEN = re.compile(r"""\s*(?:
|
|
311
|
+
(?P<num>(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?)
|
|
312
|
+
| (?P<str>"[^"]*")
|
|
313
|
+
| (?P<member>[A-Za-z_]\w*\.@\w+)
|
|
314
|
+
| (?P<name>[!%]\w+|@?[A-Za-z_]\w*)
|
|
315
|
+
| (?P<op><>|<=|>=|[-+*/^=<>(),])
|
|
316
|
+
)""", re.X)
|
|
317
|
+
|
|
318
|
+
# EViews's string and word functions: Python for the arguments' code (each a (code, kind) pair)
|
|
319
|
+
_STRING_FUNCTIONS = {
|
|
320
|
+
"@lower": (1, lambda a: f"{_m(a[0])}.lower()", "str"), "@upper": (1, lambda a: f"{_m(a[0])}.upper()", "str"),
|
|
321
|
+
"@trim": (1, lambda a: f"{_m(a[0])}.strip()", "str"), "@ltrim": (1, lambda a: f"{_m(a[0])}.lstrip()", "str"),
|
|
322
|
+
"@rtrim": (1, lambda a: f"{_m(a[0])}.rstrip()", "str"), "@len": (1, lambda a: f"len({a[0][0]})", "num"),
|
|
323
|
+
"@length": (1, lambda a: f"len({a[0][0]})", "num"),
|
|
324
|
+
"@replace": (3, lambda a: f"{_m(a[0])}.replace({a[1][0]}, {a[2][0]})", "str"),
|
|
325
|
+
"@left": (2, lambda a: f"{_m(a[0])}[:{_int(a[1])}]", "str"), "@right": (2, lambda a: f"{_m(a[0])}[-{_int(a[1], True)}:]", "str"),
|
|
326
|
+
"@mid": ((2, 3), lambda a: f"{_m(a[0])}[{_int(a[1])} - 1:{_int(a[1])} - 1 + {_int(a[2])}]" if len(a) == 3
|
|
327
|
+
else f"{_m(a[0])}[{_int(a[1])} - 1:]", "str"),
|
|
328
|
+
"@instr": (2, lambda a: f"({_m(a[0])}.find({a[1][0]}) + 1)", "num"),
|
|
329
|
+
"@str": (1, lambda a: f"str({a[0][0]})", "str"), "@val": (1, lambda a: f"float({a[0][0]})", "num"),
|
|
330
|
+
"@wcount": (1, lambda a: f"len({_m(a[0])}.split())", "num"),
|
|
331
|
+
"@word": (2, lambda a: f"{_m(a[0])}.split()[{_int(a[1])} - 1]", "str"),
|
|
332
|
+
"@wfind": (2, lambda a: f"({_m(a[0])}.split().index({a[1][0]}) + 1 if {a[1][0]} in {_m(a[0])}.split() else 0)", "num"),
|
|
333
|
+
"@wfindnc": (2, lambda a: f"({_m(a[0])}.lower().split().index({_m(a[1])}.lower()) + 1 "
|
|
334
|
+
f"if {_m(a[1])}.lower() in {_m(a[0])}.lower().split() else 0)", "num"),
|
|
335
|
+
"@abs": (1, lambda a: f"abs({a[0][0]})", "num"), "@sqrt": (1, lambda a: f"{a[0][0]} ** 0.5", "num"),
|
|
336
|
+
"@floor": (1, lambda a: f"float(int({a[0][0]} // 1))", "num"),
|
|
337
|
+
"@ceiling": (1, lambda a: f"float(-int(-({a[0][0]}) // 1))", "num"),
|
|
338
|
+
}
|
|
339
|
+
_NOTES = {"@str": "@str gives Python's text for the number, which may differ from EViews's in the digits shown (verify)",
|
|
340
|
+
"@word": "@word past the last word is an error in Python, an empty string in EViews",
|
|
341
|
+
"@val": "@val of a text that is not a number is an error in Python, NA in EViews"}
|
|
342
|
+
# EViews's date functions (pymetrix_eviews.dates): the arguments taken, the report's note, and what they give
|
|
343
|
+
_DATE_NOTE = "EViews's date numbers (days since 1 January A.D. 1, that day 0), worked out by pymetrix_eviews.dates"
|
|
344
|
+
_DATES = {"@dateval": (1, 2, _DATE_NOTE, "num"), "@datestr": (1, 2, _DATE_NOTE, "str"), "@dateadd": (3, 3, _DATE_NOTE, "num"),
|
|
345
|
+
"@datediff": (3, 3, _DATE_NOTE, "num"),
|
|
346
|
+
"@dtoo": (1, 1, "@dtoo: the date's observation number among the page's periods, when the line runs", "num"),
|
|
347
|
+
"@otod": (1, 1, "@otod: the observation's period as pandas writes it (2001Q3), when the line runs", "str")}
|
|
348
|
+
_STATISTICS = {"@mean": "mean", "@sum": "sum", "@min": "min", "@max": "max", "@stdev": "std", "@median": "median",
|
|
349
|
+
"@obs": "count"}
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def _m(arg: tuple[str, str, int]) -> str:
|
|
353
|
+
"""An argument as the receiver of a method: bracketed unless it is a name or a literal."""
|
|
354
|
+
code = arg[0]
|
|
355
|
+
return code if re.fullmatch(r"[A-Za-z_][\w.]*|\"[^\"]*\"|globals\(\)\[[^\]]*\]", code) else f"({code})"
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def _int(arg: tuple[str, str, int], parens: bool = False) -> str:
|
|
359
|
+
code = arg[0]
|
|
360
|
+
if re.fullmatch(r"\d+", code):
|
|
361
|
+
return code
|
|
362
|
+
return f"int({code})"
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
class _Values:
|
|
366
|
+
"""A recursive-descent reader of an EViews program expression into Python: (code, kind, precedence), with
|
|
367
|
+
``static`` false once it uses something known only when the program runs (an object, the data)."""
|
|
368
|
+
|
|
369
|
+
def __init__(self, tr: Any, text: str, at: int) -> None:
|
|
370
|
+
self.tr, self.text, self.at = tr, text, at
|
|
371
|
+
self.tokens: list[tuple[str, str]] = []
|
|
372
|
+
pos = 0
|
|
373
|
+
while pos < len(text):
|
|
374
|
+
if not text[pos:].strip():
|
|
375
|
+
break
|
|
376
|
+
m = _TOKEN.match(text, pos)
|
|
377
|
+
if m is None or m.end() == pos:
|
|
378
|
+
raise _error(f"{text[pos:].strip()[:20]!r} does not read here")
|
|
379
|
+
kind = m.lastgroup or "op"
|
|
380
|
+
self.tokens.append((kind, m.group(kind)))
|
|
381
|
+
pos = m.end()
|
|
382
|
+
self.i = 0
|
|
383
|
+
self.notes: list[str] = []
|
|
384
|
+
self.static = True
|
|
385
|
+
|
|
386
|
+
def peek(self) -> tuple[str, str]:
|
|
387
|
+
return self.tokens[self.i] if self.i < len(self.tokens) else ("end", "")
|
|
388
|
+
|
|
389
|
+
def take(self) -> tuple[str, str]:
|
|
390
|
+
tok = self.peek()
|
|
391
|
+
self.i += 1
|
|
392
|
+
return tok
|
|
393
|
+
|
|
394
|
+
def expect(self, op: str) -> None:
|
|
395
|
+
kind, value = self.take()
|
|
396
|
+
if value != op:
|
|
397
|
+
raise _error(f"expected {op!r}" + (f", not {value!r}" if value else " at the end"))
|
|
398
|
+
|
|
399
|
+
def word(self, w: str) -> bool:
|
|
400
|
+
kind, value = self.peek()
|
|
401
|
+
return kind == "name" and value.lower() == w
|
|
402
|
+
|
|
403
|
+
def read(self) -> tuple[str, str, int]:
|
|
404
|
+
out = self.or_()
|
|
405
|
+
if self.peek()[0] != "end":
|
|
406
|
+
raise _error(f"{self.peek()[1]!r} does not read here")
|
|
407
|
+
return out
|
|
408
|
+
|
|
409
|
+
@staticmethod
|
|
410
|
+
def wrap(part: tuple[str, str, int], prec: int) -> str:
|
|
411
|
+
return part[0] if part[2] >= prec else f"({part[0]})"
|
|
412
|
+
|
|
413
|
+
def or_(self) -> tuple[str, str, int]:
|
|
414
|
+
left = self.and_()
|
|
415
|
+
while self.word("or"):
|
|
416
|
+
self.take()
|
|
417
|
+
right = self.and_()
|
|
418
|
+
left = (f"{self.wrap(left, 1)} or {self.wrap(right, 1)}", "bool", 1)
|
|
419
|
+
return left
|
|
420
|
+
|
|
421
|
+
def and_(self) -> tuple[str, str, int]:
|
|
422
|
+
left = self.not_()
|
|
423
|
+
while self.word("and"):
|
|
424
|
+
self.take()
|
|
425
|
+
right = self.not_()
|
|
426
|
+
left = (f"{self.wrap(left, 2)} and {self.wrap(right, 2)}", "bool", 2)
|
|
427
|
+
return left
|
|
428
|
+
|
|
429
|
+
def not_(self) -> tuple[str, str, int]:
|
|
430
|
+
if self.word("not"):
|
|
431
|
+
self.take()
|
|
432
|
+
inner = self.not_()
|
|
433
|
+
return (f"not {self.wrap(inner, 3)}", "bool", 3)
|
|
434
|
+
return self.cmp()
|
|
435
|
+
|
|
436
|
+
def cmp(self) -> tuple[str, str, int]:
|
|
437
|
+
left = self.add()
|
|
438
|
+
kind, value = self.peek()
|
|
439
|
+
if value in ("=", "<>", "<", ">", "<=", ">="):
|
|
440
|
+
self.take()
|
|
441
|
+
right = self.add()
|
|
442
|
+
op = {"=": "==", "<>": "!="}.get(value, value)
|
|
443
|
+
if left[1] == "str" and right[1] == "str" and op not in ("==", "!="):
|
|
444
|
+
raise _left("ordering strings (<, >) is not translated: = and <> are")
|
|
445
|
+
return (f"{self.wrap(left, 5)} {op} {self.wrap(right, 5)}", "bool", 4)
|
|
446
|
+
return left
|
|
447
|
+
|
|
448
|
+
def add(self) -> tuple[str, str, int]:
|
|
449
|
+
left = self.mul()
|
|
450
|
+
while self.peek()[1] in ("+", "-"):
|
|
451
|
+
op = self.take()[1]
|
|
452
|
+
right = self.mul()
|
|
453
|
+
kind = "str" if left[1] == "str" or right[1] == "str" else "num"
|
|
454
|
+
if kind == "str" and op == "-":
|
|
455
|
+
raise _error("a string minus a string")
|
|
456
|
+
left = (f"{self.wrap(left, 5)} {op} {self.wrap(right, 6)}", kind, 5)
|
|
457
|
+
return left
|
|
458
|
+
|
|
459
|
+
def mul(self) -> tuple[str, str, int]:
|
|
460
|
+
left = self.neg()
|
|
461
|
+
while self.peek()[1] in ("*", "/"):
|
|
462
|
+
op = self.take()[1]
|
|
463
|
+
right = self.neg()
|
|
464
|
+
left = (f"{self.wrap(left, 6)} {op} {self.wrap(right, 7)}", "num", 6)
|
|
465
|
+
return left
|
|
466
|
+
|
|
467
|
+
def neg(self) -> tuple[str, str, int]:
|
|
468
|
+
if self.peek()[1] == "-":
|
|
469
|
+
self.take()
|
|
470
|
+
inner = self.neg()
|
|
471
|
+
return (f"-{self.wrap(inner, 7)}", "num", 7)
|
|
472
|
+
if self.peek()[1] == "+":
|
|
473
|
+
self.take()
|
|
474
|
+
return self.neg()
|
|
475
|
+
return self.pow_()
|
|
476
|
+
|
|
477
|
+
def pow_(self) -> tuple[str, str, int]:
|
|
478
|
+
base = self.atom()
|
|
479
|
+
if self.peek()[1] == "^":
|
|
480
|
+
self.take()
|
|
481
|
+
exp = self.neg()
|
|
482
|
+
return (f"{self.wrap(base, 9)} ** {self.wrap(exp, 7)}", "num", 8)
|
|
483
|
+
return base
|
|
484
|
+
|
|
485
|
+
def args(self) -> list[tuple[str, str, int]]:
|
|
486
|
+
out: list[tuple[str, str, int]] = []
|
|
487
|
+
self.expect("(")
|
|
488
|
+
if self.peek()[1] == ")":
|
|
489
|
+
self.take()
|
|
490
|
+
return out
|
|
491
|
+
while True:
|
|
492
|
+
out.append(self.or_())
|
|
493
|
+
if self.peek()[1] == ",":
|
|
494
|
+
self.take()
|
|
495
|
+
continue
|
|
496
|
+
self.expect(")")
|
|
497
|
+
return out
|
|
498
|
+
|
|
499
|
+
def raw_args(self) -> str:
|
|
500
|
+
"""The text of a call's brackets, as written (a series expression for a statistic)."""
|
|
501
|
+
depth = 0
|
|
502
|
+
start = None
|
|
503
|
+
while True:
|
|
504
|
+
kind, value = self.take()
|
|
505
|
+
if kind == "end":
|
|
506
|
+
raise _error("a bracket is not closed")
|
|
507
|
+
if value == "(":
|
|
508
|
+
depth += 1
|
|
509
|
+
if depth == 1:
|
|
510
|
+
start = self.i
|
|
511
|
+
continue
|
|
512
|
+
elif value == ")":
|
|
513
|
+
depth -= 1
|
|
514
|
+
if depth == 0:
|
|
515
|
+
return " ".join(v for _, v in self.tokens[start:self.i - 1])
|
|
516
|
+
|
|
517
|
+
def atom(self) -> tuple[str, str, int]:
|
|
518
|
+
kind, value = self.take()
|
|
519
|
+
if kind == "num":
|
|
520
|
+
text = "0" + value if value.startswith(".") else value
|
|
521
|
+
return (text, "num", 9)
|
|
522
|
+
if kind == "str":
|
|
523
|
+
return (quote(value[1:-1]), "str", 9)
|
|
524
|
+
if value == "(":
|
|
525
|
+
inner = self.or_()
|
|
526
|
+
self.expect(")")
|
|
527
|
+
return (inner[0], inner[1], 9) if inner[2] >= 9 else (f"({inner[0]})", inner[1], 9)
|
|
528
|
+
if kind == "member":
|
|
529
|
+
obj, _, member = value.partition(".")
|
|
530
|
+
index = self.args() if self.peek()[1] == "(" else []
|
|
531
|
+
self.static = False
|
|
532
|
+
code, out_kind, note = self.tr.value_member(obj, member.lower(), index)
|
|
533
|
+
if note and note not in self.notes:
|
|
534
|
+
self.notes.append(note)
|
|
535
|
+
return (code, out_kind, 9)
|
|
536
|
+
if kind == "name":
|
|
537
|
+
low = value.lower()
|
|
538
|
+
if low.startswith("@"):
|
|
539
|
+
return self.function(low)
|
|
540
|
+
if self.peek()[1] == "(" and not low.startswith(("!", "%")):
|
|
541
|
+
if low == "c" or low in self.tr._vectors():
|
|
542
|
+
index = self.args()
|
|
543
|
+
self.static = False
|
|
544
|
+
code, note = self.tr.coefficient_code(low, index)
|
|
545
|
+
if note and note not in self.notes:
|
|
546
|
+
self.notes.append(note)
|
|
547
|
+
return (code, "num", 9)
|
|
548
|
+
raise _left(f"{value}(...) is not translated in a program's value: a function EViews's programs use is "
|
|
549
|
+
"written with @")
|
|
550
|
+
if low in ("na",):
|
|
551
|
+
return ('float("nan")', "num", 9)
|
|
552
|
+
if PLACEHOLDER.fullmatch(low):
|
|
553
|
+
raise _left("an object named by a variable ({%x}) as a value: use one of its data members ({%x}.@count)")
|
|
554
|
+
code, out_kind, known = self.tr.value_name(value)
|
|
555
|
+
if not known:
|
|
556
|
+
self.static = False
|
|
557
|
+
return (code, out_kind, 9)
|
|
558
|
+
if kind == "end":
|
|
559
|
+
raise _error("the expression ends too soon")
|
|
560
|
+
raise _error(f"{value!r} does not read here")
|
|
561
|
+
|
|
562
|
+
def date_function(self, name: str) -> tuple[str, str, int]:
|
|
563
|
+
"""EViews's date functions, as Python with ``pymetrix_eviews.dates`` (``eviews_dates`` in the script): worked
|
|
564
|
+
out now when the program's values are known, else when the script runs (see that module)."""
|
|
565
|
+
args = self.args()
|
|
566
|
+
low, high = _DATES[name][:2]
|
|
567
|
+
if not low <= len(args) <= high:
|
|
568
|
+
shown = str(low) if low == high else f"{low} or {high}"
|
|
569
|
+
raise _error(f"{name} takes {shown} arguments, not {len(args)}")
|
|
570
|
+
if name == "@datestr" and len(args) == 1:
|
|
571
|
+
raise _left("@datestr without a format writes the date in EViews's default format, which depends on its "
|
|
572
|
+
"settings: give the format (@datestr(d, \"yyyy[q]q\"))")
|
|
573
|
+
if name == "@dateadd" or name == "@datediff":
|
|
574
|
+
unit = args[-1][0]
|
|
575
|
+
if re.fullmatch(r'"[^"]*"', unit) and unit[1:-1].strip().lower() not in ("a", "y", "s", "q", "m", "w", "d"):
|
|
576
|
+
raise _left(f"{name} with the unit {unit}: the units a (or y), s, q, m, w and d are translated")
|
|
577
|
+
codes = [a[0] for a in args]
|
|
578
|
+
if name in ("@dtoo", "@otod"):
|
|
579
|
+
page = self.tr._page()
|
|
580
|
+
self.static = False
|
|
581
|
+
codes = [page.var, *codes]
|
|
582
|
+
note = _DATES[name][2]
|
|
583
|
+
if note not in self.notes:
|
|
584
|
+
self.notes.append(note)
|
|
585
|
+
return (f"eviews_dates.{name[1:]}({', '.join(codes)})", _DATES[name][3], 9)
|
|
586
|
+
|
|
587
|
+
def function(self, name: str) -> tuple[str, str, int]:
|
|
588
|
+
if name == "@obssmpl":
|
|
589
|
+
page = self.tr._page()
|
|
590
|
+
self.static = False
|
|
591
|
+
return (f"int({page.var}.sample_mask().sum())", "num", 9)
|
|
592
|
+
if name in _STATISTICS:
|
|
593
|
+
text = self.raw_args()
|
|
594
|
+
page = self.tr._page()
|
|
595
|
+
inner = self.tr.expression(text, self.at, page)
|
|
596
|
+
self.static = False
|
|
597
|
+
fn = _STATISTICS[name]
|
|
598
|
+
note = f"{name} over the page's sample when the line runs, missing values skipped"
|
|
599
|
+
if note not in self.notes:
|
|
600
|
+
self.notes.append(note)
|
|
601
|
+
return (f"float({page.var}.eval({inner.code()})[{page.var}.sample_mask()].{fn}())", "num", 9)
|
|
602
|
+
if name == "@isobject":
|
|
603
|
+
args = self.args()
|
|
604
|
+
if len(args) != 1:
|
|
605
|
+
raise _error("@isobject takes one name")
|
|
606
|
+
page = self.tr._page()
|
|
607
|
+
self.static = False
|
|
608
|
+
arg = _m(args[0])
|
|
609
|
+
return (f"({arg}.lower() in {page.var}.names or {arg}.lower() in globals())", "bool", 9)
|
|
610
|
+
if name == "@wlookup":
|
|
611
|
+
args = self.args()
|
|
612
|
+
if not 1 <= len(args) <= 2:
|
|
613
|
+
raise _error("@wlookup takes a pattern, and a type")
|
|
614
|
+
if len(args) == 2 and args[1][0].lower() not in ('"series"',):
|
|
615
|
+
raise _left("@wlookup with a type other than series is not translated: the page's series are")
|
|
616
|
+
page = self.tr._page()
|
|
617
|
+
self.static = False
|
|
618
|
+
note = "@wlookup looks among the page's series (Dataset.series with the pattern)"
|
|
619
|
+
if note not in self.notes:
|
|
620
|
+
self.notes.append(note)
|
|
621
|
+
return (f'" ".join({page.var}.series({_m(args[0])}.lower()).names)', "str", 9)
|
|
622
|
+
if name in _STRING_FUNCTIONS:
|
|
623
|
+
n, make, out_kind = _STRING_FUNCTIONS[name]
|
|
624
|
+
args = self.args()
|
|
625
|
+
allowed = n if isinstance(n, tuple) else (n,)
|
|
626
|
+
if len(args) not in allowed:
|
|
627
|
+
shown = " or ".join(map(str, allowed))
|
|
628
|
+
raise _error(f"{name} takes {shown} argument{'s' if max(allowed) > 1 else ''}, not {len(args)}")
|
|
629
|
+
if name in _NOTES and _NOTES[name] not in self.notes:
|
|
630
|
+
self.notes.append(_NOTES[name])
|
|
631
|
+
return (make(args), out_kind, 9)
|
|
632
|
+
if name in ("@log", "@exp"):
|
|
633
|
+
args = self.args()
|
|
634
|
+
if len(args) != 1:
|
|
635
|
+
raise _error(f"{name} takes one number")
|
|
636
|
+
raise _left(f"{name} of a value known when the program runs: pymetrix's scripts import only pymetrix (use "
|
|
637
|
+
"a series' log, or work the number out first)")
|
|
638
|
+
from .left import GAP_FUNCTIONS, PROGRAM_FUNCTIONS
|
|
639
|
+
|
|
640
|
+
if name in _DATES:
|
|
641
|
+
return self.date_function(name)
|
|
642
|
+
if name == "@strdate":
|
|
643
|
+
raise _left("@strdate is a series of each observation's date as text (an alpha series): not translated; "
|
|
644
|
+
"@datestr of a date number is")
|
|
645
|
+
if name == "@date":
|
|
646
|
+
raise _left("@date is a series (each observation's date number), not a program's value: @dateval of a date "
|
|
647
|
+
"string is translated")
|
|
648
|
+
if name in ("@uiprompt", "@uidialog", "@uiedit", "@uilist", "@uiradio"):
|
|
649
|
+
raise _left("interactive prompts; in pymetrix: the dialog asks for the program's arguments")
|
|
650
|
+
if name in PROGRAM_FUNCTIONS or name in GAP_FUNCTIONS:
|
|
651
|
+
raise _left(f"{name} is not translated in a program's values (a gap, docs/known-gaps.md): @word, @wcount, "
|
|
652
|
+
"@wfind, @wlookup, @isobject, @lower, @upper, @replace, @trim, @left, @right, @mid, @instr, "
|
|
653
|
+
"@len, @str, @val, @floor, @ceiling, @dateval, @datestr, @dateadd, @datediff, @dtoo, @otod and the "
|
|
654
|
+
"sample's statistics are")
|
|
655
|
+
from pymetrix.models.eviews import FUNCTIONS as SERIES_FUNCTIONS
|
|
656
|
+
|
|
657
|
+
if name in SERIES_FUNCTIONS:
|
|
658
|
+
raise _left(f"{name} is translated in a series' formula, not in a program's values (a number or a string): "
|
|
659
|
+
"@word, @wcount, @floor, @ceiling, the date functions and the sample's statistics are")
|
|
660
|
+
raise _left(f"{name} is not an EViews function this translator knows")
|
|
661
|
+
|
|
662
|
+
|
|
663
|
+
def _error(reason: str) -> Exception:
|
|
664
|
+
from .data import _error as e
|
|
665
|
+
|
|
666
|
+
return e(reason)
|
|
667
|
+
|
|
668
|
+
|
|
669
|
+
def _left(reason: str) -> Exception:
|
|
670
|
+
from .data import _left as e
|
|
671
|
+
|
|
672
|
+
return e(reason)
|
|
673
|
+
|
|
674
|
+
|
|
675
|
+
_SAFE = {"len": len, "float": float, "int": int, "str": str, "abs": abs}
|
|
676
|
+
|
|
677
|
+
|
|
678
|
+
def _dates_module() -> Any:
|
|
679
|
+
"""``pymetrix_eviews.dates``, as the script names it (``eviews_dates``)."""
|
|
680
|
+
from .. import dates
|
|
681
|
+
|
|
682
|
+
return dates
|
|
683
|
+
|
|
684
|
+
|
|
685
|
+
class ProgramValues:
|
|
686
|
+
"""The translator's handling of the program's own values (mixed into ``Translator``)."""
|
|
687
|
+
|
|
688
|
+
def program_value(self, text: str, at: int = 0) -> tuple[str, Any, str, list[str]]:
|
|
689
|
+
"""An EViews program expression as Python: its code, its value where known before the program runs (else
|
|
690
|
+
``_UNKNOWN``), its kind (``num``, ``str`` or ``bool``) and notes."""
|
|
691
|
+
from .data import _UNKNOWN
|
|
692
|
+
|
|
693
|
+
text, _ = self._braces(text)
|
|
694
|
+
reader = _Values(self, text, at)
|
|
695
|
+
code, kind, _ = reader.read()
|
|
696
|
+
value: Any = _UNKNOWN
|
|
697
|
+
if reader.static:
|
|
698
|
+
known = {v.name: v.value for v in self.py.values() if v.value is not _UNKNOWN and v.kind in ("scalar", "control", "string")}
|
|
699
|
+
try:
|
|
700
|
+
value = eval(code, {"__builtins__": _SAFE, "eviews_dates": _dates_module()}, known) # noqa: S307 - Python made here from the program's own values
|
|
701
|
+
except Exception: # noqa: BLE001 - a name with no value yet, an index past the end: worked out when it runs
|
|
702
|
+
value = _UNKNOWN
|
|
703
|
+
if isinstance(value, bool):
|
|
704
|
+
value = float(value)
|
|
705
|
+
return code, value, kind, reader.notes
|
|
706
|
+
|
|
707
|
+
def value_name(self, name: str) -> tuple[str, str, bool]:
|
|
708
|
+
"""A name in a program expression: a scalar, a string or a control variable (``!i``, ``%s``)."""
|
|
709
|
+
from .data import _UNKNOWN
|
|
710
|
+
|
|
711
|
+
key = name.lower()
|
|
712
|
+
v = self.py.get(key)
|
|
713
|
+
if v is None and key[:1] in "!%":
|
|
714
|
+
v = self.runtime_variable(key)
|
|
715
|
+
if v is None:
|
|
716
|
+
if key in self.unset or self.lost:
|
|
717
|
+
raise self._missing(name)
|
|
718
|
+
page = self.current
|
|
719
|
+
if page is not None and page.series is not None and key in page.series:
|
|
720
|
+
raise _left(f"{name} is a series: a program's value takes a number (scalar m = @mean({name}) first)")
|
|
721
|
+
raise _error(f"{name} is not a scalar, a string or a variable of the program")
|
|
722
|
+
if v.kind in ("scalar", "control"):
|
|
723
|
+
return v.name, "num", v.value is not _UNKNOWN
|
|
724
|
+
if v.kind == "string":
|
|
725
|
+
return v.name, "str", v.value is not _UNKNOWN
|
|
726
|
+
raise _left(f"{name} is a {v.kind}: as a program's value, use one of its data members ({name}.@count)")
|
|
727
|
+
|
|
728
|
+
def value_member(self, obj: str, member: str, index: list[tuple[str, str, int]]) -> tuple[str, str, str]:
|
|
729
|
+
"""``obj.@member(index)``: a group's ``@count``, ``@seriesname(i)`` and ``@members``; an equation's values
|
|
730
|
+
(``@r2``, ``@coefs(i)``) through phase 2; for an object named by a variable, by what the member says it is."""
|
|
731
|
+
key = obj.lower()
|
|
732
|
+
dynamic = PLACEHOLDER.search(key) is not None
|
|
733
|
+
v = self.py.get(key)
|
|
734
|
+
if v is not None and v.kind == "group" or dynamic and member in ("@count", "@seriesname", "@members"):
|
|
735
|
+
ref = name_code(_to_text(key, self.dynamic)) if dynamic else v.name
|
|
736
|
+
note = f"{obj} is taken to be a group, as {member} is a group's" if dynamic else ""
|
|
737
|
+
if member == "@count":
|
|
738
|
+
return f"len({ref}.names)", "num", note
|
|
739
|
+
if member == "@members":
|
|
740
|
+
return f'" ".join({ref}.names)', "str", note
|
|
741
|
+
if member == "@seriesname":
|
|
742
|
+
if len(index) != 1:
|
|
743
|
+
raise _error("@seriesname takes the series' position")
|
|
744
|
+
return f"{ref}.names[{_int(index[0])} - 1]", "str", note
|
|
745
|
+
raise _left(f"{obj}.{member} is not translated: a group's @count, @seriesname and @members are")
|
|
746
|
+
if dynamic:
|
|
747
|
+
fit = self.fits.get(key)
|
|
748
|
+
if fit is None:
|
|
749
|
+
raise _left(f"{obj}.{member}: an object named by a variable that no line translated so far estimates")
|
|
750
|
+
if index and len(index) != 1:
|
|
751
|
+
raise _error(f"{member} takes one index")
|
|
752
|
+
i: int | None = None
|
|
753
|
+
if index:
|
|
754
|
+
try:
|
|
755
|
+
i = int(index[0][0])
|
|
756
|
+
except ValueError:
|
|
757
|
+
raise _left(f"{obj}.{member} with an index known when the program runs is not translated: a number is") from None
|
|
758
|
+
code, note = self.member_code(obj, member, i)
|
|
759
|
+
if dynamic:
|
|
760
|
+
code = render_code(code, self.dynamic)
|
|
761
|
+
return code, "num", note
|
|
762
|
+
|
|
763
|
+
def coefficient_code(self, vector: str, index: list[tuple[str, str, int]]) -> tuple[str, str]:
|
|
764
|
+
if len(index) != 1 or not re.fullmatch(r"\d+", index[0][0]):
|
|
765
|
+
raise _left(f"{vector}(...) with an index known when the program runs is not translated: a number is")
|
|
766
|
+
_, codes, notes = self.members_in(f"{vector}({index[0][0]})")
|
|
767
|
+
return next(iter(codes.values())), "; ".join(notes)
|
|
768
|
+
|
|
769
|
+
def runtime_variable(self, key: str) -> Any:
|
|
770
|
+
"""Inside a block or a subroutine: a program variable (``!x``, ``%s``) no line before has set, taken as set
|
|
771
|
+
when the program runs (by the caller, or an earlier pass of a loop)."""
|
|
772
|
+
from .data import _UNKNOWN, _Py
|
|
773
|
+
|
|
774
|
+
if not self.runtime or key[:1] not in "!%":
|
|
775
|
+
return None
|
|
776
|
+
name, _ = self._name(key, f"{'control' if key[0] == '!' else 'string'} {key}")
|
|
777
|
+
v = _Py(name, "control" if key[0] == "!" else "string", _UNKNOWN)
|
|
778
|
+
self.py[key] = v
|
|
779
|
+
return v
|
|
780
|
+
|
|
781
|
+
def placeholder(self, key: str) -> str:
|
|
782
|
+
"""The placeholder of a program variable's value in a name, while a statement is translated."""
|
|
783
|
+
name = self.py[key].name
|
|
784
|
+
for i, n in self.dynamic.items():
|
|
785
|
+
if n == name:
|
|
786
|
+
return f"pmxrt{i}z"
|
|
787
|
+
i = len(self.dynamic)
|
|
788
|
+
self.dynamic[i] = name
|
|
789
|
+
return f"pmxrt{i}z"
|
|
790
|
+
|
|
791
|
+
|
|
792
|
+
# -- the walker ------------------------------------------------------------------------------------------------------
|
|
793
|
+
|
|
794
|
+
|
|
795
|
+
@dataclass
|
|
796
|
+
class _Sub:
|
|
797
|
+
name: str # lower case
|
|
798
|
+
node: Node
|
|
799
|
+
params: list[tuple[str, str, str]] = field(default_factory=list) # (type, EViews name, key in py)
|
|
800
|
+
local: bool = False
|
|
801
|
+
var: str = "" # the function's Python name
|
|
802
|
+
pnames: list[str] = field(default_factory=list) # the parameters' Python names
|
|
803
|
+
returns: list[int] = field(default_factory=list) # positions of the parameters the body assigns
|
|
804
|
+
done: bool = False
|
|
805
|
+
translating: bool = False
|
|
806
|
+
error: str = ""
|
|
807
|
+
outcome: Any = None
|
|
808
|
+
|
|
809
|
+
|
|
810
|
+
_DOLLAR = ("a name with $ in it (_$_x) is not translated: pymetrix's names are Python names; rename the object in the "
|
|
811
|
+
"program (a gap, docs/known-gaps.md)")
|
|
812
|
+
|
|
813
|
+
_PARAM_TYPES = ("string", "scalar", "series", "group", "equation", "vector", "matrix", "sym", "coef", "model", "sample",
|
|
814
|
+
"table", "graph", "svector", "rowvector", "var", "system", "alpha", "text", "spool", "pool", "valmap",
|
|
815
|
+
"frml", "link", "logl", "sspace")
|
|
816
|
+
|
|
817
|
+
|
|
818
|
+
class Flow:
|
|
819
|
+
"""Translates the program's blocks in order (see the module's docstring)."""
|
|
820
|
+
|
|
821
|
+
def __init__(self, tr: Any, nodes: list[Node]) -> None:
|
|
822
|
+
self.tr = tr
|
|
823
|
+
self.nodes = nodes
|
|
824
|
+
self.subs: dict[str, _Sub] = {}
|
|
825
|
+
self.loops = 0 # loops around the statement being translated
|
|
826
|
+
self.sub: _Sub | None = None # the subroutine being translated
|
|
827
|
+
self._collect(nodes)
|
|
828
|
+
|
|
829
|
+
def _collect(self, nodes: list[Node]) -> None:
|
|
830
|
+
from .data import Outcome
|
|
831
|
+
|
|
832
|
+
for n in nodes:
|
|
833
|
+
if n.kind == "subroutine" and not n.error:
|
|
834
|
+
sub = self._signature(n)
|
|
835
|
+
sub.outcome = Outcome(n.st, TRANSLATED, "", file=n.file, kind="subroutine")
|
|
836
|
+
if sub.name in self.subs:
|
|
837
|
+
sub.error = f"a second subroutine {sub.name} (the first is at line {self.subs[sub.name].node.st.line}" + \
|
|
838
|
+
(f" of {self.subs[sub.name].node.file}" if self.subs[sub.name].node.file else "") + ")"
|
|
839
|
+
else:
|
|
840
|
+
self.subs[sub.name] = sub
|
|
841
|
+
continue
|
|
842
|
+
self.subs.setdefault(f"{sub.name}#{n.st.line}{n.file}", sub)
|
|
843
|
+
self._collect(n.included)
|
|
844
|
+
|
|
845
|
+
def _signature(self, n: Node) -> _Sub:
|
|
846
|
+
m = re.fullmatch(r"\s*(local\s+)?([A-Za-z_]\w*)\s*(?:\((.*)\))?\s*", n.st.rest, re.S | re.I)
|
|
847
|
+
if m is None:
|
|
848
|
+
sub = _Sub("?", n, error="subroutine names the subroutine: subroutine f(string %a, scalar !b)")
|
|
849
|
+
return sub
|
|
850
|
+
sub = _Sub(m.group(2).lower(), n, local=bool(m.group(1)))
|
|
851
|
+
for part in _split_args(m.group(3) or ""):
|
|
852
|
+
words = part.split()
|
|
853
|
+
if len(words) != 2 or words[0].lower() not in _PARAM_TYPES:
|
|
854
|
+
sub.error = f"the parameter {part.strip()!r} does not read: a type and a name (string %a, scalar !b)"
|
|
855
|
+
break
|
|
856
|
+
kind, pname = words[0].lower(), words[1]
|
|
857
|
+
if kind not in ("string", "scalar"):
|
|
858
|
+
sub.error = (f"a parameter of type {kind} ({pname}): object arguments are not translated (a gap, "
|
|
859
|
+
"docs/known-gaps.md); string and scalar parameters are")
|
|
860
|
+
break
|
|
861
|
+
sub.params.append((kind, pname, pname.lower()))
|
|
862
|
+
return sub
|
|
863
|
+
|
|
864
|
+
# -- walking --------------------------------------------------------------------------------------------------
|
|
865
|
+
|
|
866
|
+
def walk(self, nodes: list[Node]) -> list[Any]:
|
|
867
|
+
out = []
|
|
868
|
+
for n in nodes:
|
|
869
|
+
out.extend(self.node(n))
|
|
870
|
+
return out
|
|
871
|
+
|
|
872
|
+
def node(self, n: Node) -> list[Any]:
|
|
873
|
+
from .data import Outcome
|
|
874
|
+
|
|
875
|
+
tr = self.tr
|
|
876
|
+
if n.error:
|
|
877
|
+
tr.forget()
|
|
878
|
+
return [self._outcome(n.st, ERROR, n.error, n.file), *self._inside(n, ERROR, f"inside a block that does not read (line {n.st.line})")]
|
|
879
|
+
if n.kind == "plain":
|
|
880
|
+
return [self.plain(n)]
|
|
881
|
+
if n.kind == "include":
|
|
882
|
+
shown = self._shown(n)
|
|
883
|
+
count = sum(1 for line in n.program.lines if line.strip()) if n.program is not None else 0
|
|
884
|
+
o = Outcome(n.st, TRANSLATED, f"the {count} lines of {shown} follow, under its name; its subroutines are "
|
|
885
|
+
"functions of the script", file=n.file, kind="include")
|
|
886
|
+
o.program, o.included_file = n.program, shown
|
|
887
|
+
o.children = self.walk(n.included)
|
|
888
|
+
return [o]
|
|
889
|
+
if n.kind == "subroutine":
|
|
890
|
+
sub = self._sub_of(n)
|
|
891
|
+
if sub.outcome is None:
|
|
892
|
+
sub.outcome = Outcome(n.st, TRANSLATED, "", file=n.file, kind="subroutine")
|
|
893
|
+
o = sub.outcome
|
|
894
|
+
if sub.error:
|
|
895
|
+
o.status, o.reason = ERROR if "does not read" in sub.error or "a second" in sub.error else LEFT, sub.error
|
|
896
|
+
o.children = self._inside_list(n.body, LEFT, f"inside the subroutine {sub.name} (line {n.st.line}), which is "
|
|
897
|
+
"left out")
|
|
898
|
+
o.closer = self._outcome(n.close, LEFT, f"the end of the subroutine {sub.name}, which is left out", n.file)
|
|
899
|
+
return [o]
|
|
900
|
+
return [self.block(n)]
|
|
901
|
+
|
|
902
|
+
@staticmethod
|
|
903
|
+
def _shown(n: Node) -> str:
|
|
904
|
+
words = re.findall(r'"[^"]*"|\S+', n.st.rest)
|
|
905
|
+
name = words[0].strip('"') if words else "?"
|
|
906
|
+
return name if name.lower().endswith(".prg") else name + ".prg"
|
|
907
|
+
|
|
908
|
+
def _sub_of(self, n: Node) -> _Sub:
|
|
909
|
+
for sub in self.subs.values():
|
|
910
|
+
if sub.node is n:
|
|
911
|
+
return sub
|
|
912
|
+
return self._signature(n)
|
|
913
|
+
|
|
914
|
+
def _outcome(self, st: Statement | None, status: str, reason: str, file: str) -> Any:
|
|
915
|
+
from .data import Outcome
|
|
916
|
+
|
|
917
|
+
if st is None:
|
|
918
|
+
return None
|
|
919
|
+
return Outcome(st, status, reason, file=file)
|
|
920
|
+
|
|
921
|
+
def _inside_list(self, nodes: list[Node], status: str, reason: str) -> list[Any]:
|
|
922
|
+
out = []
|
|
923
|
+
for c in nodes:
|
|
924
|
+
o = self._outcome(c.st, status if c.kind != "plain" or status != ERROR else LEFT, reason, c.file)
|
|
925
|
+
self.tr.inside_block(c.st)
|
|
926
|
+
o.children = self._inside_list(c.body, status, reason)
|
|
927
|
+
o.orelse = self._inside_list(c.orelse, status, reason)
|
|
928
|
+
o.else_outcome = self._outcome(c.else_st, LEFT, reason, c.file)
|
|
929
|
+
o.closer = self._outcome(c.close, LEFT, reason, c.file)
|
|
930
|
+
if c.kind == "include":
|
|
931
|
+
o.children = self._inside_list(c.included, status, reason)
|
|
932
|
+
out.append(o)
|
|
933
|
+
return out
|
|
934
|
+
|
|
935
|
+
def _inside(self, n: Node, status: str, reason: str) -> list[Any]:
|
|
936
|
+
"""The statements of a block that is left out (or does not read), each saying so."""
|
|
937
|
+
out = self._inside_list(n.body, LEFT, reason)
|
|
938
|
+
if n.else_st is not None:
|
|
939
|
+
out.append(self._outcome(n.else_st, LEFT, reason, n.file))
|
|
940
|
+
out += self._inside_list(n.orelse, LEFT, reason)
|
|
941
|
+
if n.close is not None:
|
|
942
|
+
out.append(self._outcome(n.close, LEFT, reason, n.file))
|
|
943
|
+
return out
|
|
944
|
+
|
|
945
|
+
def _runtime(self) -> Any:
|
|
946
|
+
tr = self.tr
|
|
947
|
+
|
|
948
|
+
class _Ctx:
|
|
949
|
+
def __enter__(self_inner) -> None:
|
|
950
|
+
tr.runtime += 1
|
|
951
|
+
|
|
952
|
+
def __exit__(self_inner, *exc: Any) -> None:
|
|
953
|
+
tr.runtime -= 1
|
|
954
|
+
|
|
955
|
+
return _Ctx()
|
|
956
|
+
|
|
957
|
+
def _unknown(self, keys: set[str]) -> None:
|
|
958
|
+
"""Program variables a block assigns: their values are known only when the program runs."""
|
|
959
|
+
from .data import _UNKNOWN
|
|
960
|
+
|
|
961
|
+
for k in keys:
|
|
962
|
+
v = self.tr.py.get(k)
|
|
963
|
+
if v is not None and v.kind in ("scalar", "control", "string"):
|
|
964
|
+
v.value = _UNKNOWN
|
|
965
|
+
|
|
966
|
+
# -- statements -------------------------------------------------------------------------------------------------
|
|
967
|
+
|
|
968
|
+
_NOT_IN_BLOCKS = {"wfopen": "opening the workfile", "wfcreate": "making a page", "pagecreate": "making a page",
|
|
969
|
+
"pageselect": "selecting a page", "model": "making a model", "system": "making a system",
|
|
970
|
+
"sspace": "a state-space object"}
|
|
971
|
+
|
|
972
|
+
def plain(self, n: Node) -> Any:
|
|
973
|
+
from .data import Outcome
|
|
974
|
+
|
|
975
|
+
tr = self.tr
|
|
976
|
+
st = n.st
|
|
977
|
+
word = st.word if st.kind == "command" else ""
|
|
978
|
+
if word in ("exitloop", "return", "stop"):
|
|
979
|
+
return self.jump(n)
|
|
980
|
+
if word == "call":
|
|
981
|
+
return self.call(n)
|
|
982
|
+
if tr.runtime and (word in self._NOT_IN_BLOCKS or st.kind == "method" and st.obj.lower() in tr.models and st.word in ("append", "merge")):
|
|
983
|
+
what = self._NOT_IN_BLOCKS.get(word, "building a model")
|
|
984
|
+
o = Outcome(st, LEFT, f"{what} inside a loop, an if block or a subroutine is not translated: pages and models are "
|
|
985
|
+
"followed as the program's text runs, so make them before its control flow", file=n.file)
|
|
986
|
+
tr.inside_block(st)
|
|
987
|
+
tr.forget()
|
|
988
|
+
return o
|
|
989
|
+
if self.sub is not None and self.sub.local and word not in ("scalar", "string") and st.kind != "assign" \
|
|
990
|
+
and not (st.kind == "assign" and st.lhs[:1] in "!%"):
|
|
991
|
+
o = Outcome(st, LEFT, f"inside the local subroutine {self.sub.name}: the objects a local subroutine makes are "
|
|
992
|
+
"deleted when it returns in EViews, so its data and estimation lines are not translated (its "
|
|
993
|
+
"strings, numbers and control flow are)", file=n.file)
|
|
994
|
+
tr.inside_block(st)
|
|
995
|
+
return o
|
|
996
|
+
if self.sub is not None and self.sub.local and st.kind == "assign" and st.lhs[:1] not in "!%" \
|
|
997
|
+
and st.lhs.lower() not in tr.py:
|
|
998
|
+
o = Outcome(st, LEFT, f"inside the local subroutine {self.sub.name}: a series it makes is deleted when it returns in "
|
|
999
|
+
"EViews; not translated", file=n.file)
|
|
1000
|
+
tr.inside_block(st)
|
|
1001
|
+
return o
|
|
1002
|
+
try:
|
|
1003
|
+
o = tr.statement(st)
|
|
1004
|
+
except Exception as exc: # noqa: BLE001 - a line the translator cannot take is an error row, not a lost translation
|
|
1005
|
+
tr.forget()
|
|
1006
|
+
o = Outcome(st, ERROR, f"the translator failed on this line ({type(exc).__name__}: {exc}); please report it")
|
|
1007
|
+
o.file = n.file
|
|
1008
|
+
return o
|
|
1009
|
+
|
|
1010
|
+
def jump(self, n: Node) -> Any:
|
|
1011
|
+
from .data import Outcome
|
|
1012
|
+
|
|
1013
|
+
word = n.st.word
|
|
1014
|
+
if n.st.rest.strip():
|
|
1015
|
+
return Outcome(n.st, ERROR, f"{word} takes nothing after it", file=n.file)
|
|
1016
|
+
if word == "exitloop":
|
|
1017
|
+
if not self.loops:
|
|
1018
|
+
return Outcome(n.st, ERROR, "exitloop outside a loop", file=n.file)
|
|
1019
|
+
o = Outcome(n.st, TRANSLATED, "", [Jump("break")], file=n.file)
|
|
1020
|
+
return o
|
|
1021
|
+
if word == "return":
|
|
1022
|
+
if self.sub is None:
|
|
1023
|
+
o = Outcome(n.st, NOTE, "return outside a subroutine ends the program, as stop does", [Jump("stop")], file=n.file)
|
|
1024
|
+
return o
|
|
1025
|
+
return Outcome(n.st, TRANSLATED, "", [Jump("return")], file=n.file)
|
|
1026
|
+
return Outcome(n.st, TRANSLATED, "", [Jump("stop")], file=n.file)
|
|
1027
|
+
|
|
1028
|
+
def call(self, n: Node) -> Any:
|
|
1029
|
+
from .data import Outcome, _Out
|
|
1030
|
+
|
|
1031
|
+
tr = self.tr
|
|
1032
|
+
st = n.st
|
|
1033
|
+
m = re.fullmatch(r"\s*([A-Za-z_]\w*)\s*(?:\((.*)\))?\s*", st.rest, re.S)
|
|
1034
|
+
if m is None:
|
|
1035
|
+
return Outcome(st, ERROR, "call names the subroutine: call f(%a, 1)", file=n.file)
|
|
1036
|
+
name = m.group(1).lower()
|
|
1037
|
+
sub = self.subs.get(name)
|
|
1038
|
+
if "$" in re.sub(r'"[^"]*"', "", st.text):
|
|
1039
|
+
tr._unset(st)
|
|
1040
|
+
if sub is not None:
|
|
1041
|
+
self._unknown(_assigned([sub.node], self.subs))
|
|
1042
|
+
tr.forget()
|
|
1043
|
+
return Outcome(st, LEFT, _DOLLAR, file=n.file)
|
|
1044
|
+
if sub is None:
|
|
1045
|
+
status = ERROR if not tr.lost else LEFT
|
|
1046
|
+
tr.forget()
|
|
1047
|
+
return Outcome(st, status, f"no subroutine {m.group(1)} in the program or the programs it includes", file=n.file)
|
|
1048
|
+
if sub.error:
|
|
1049
|
+
self._unknown(_assigned([sub.node], self.subs))
|
|
1050
|
+
tr.forget()
|
|
1051
|
+
return Outcome(st, LEFT, f"the subroutine {sub.name} is left out: {sub.error}", file=n.file)
|
|
1052
|
+
args = _split_args(m.group(2) or "")
|
|
1053
|
+
if len(args) != len(sub.params):
|
|
1054
|
+
return Outcome(st, ERROR, f"{sub.name} takes {len(sub.params)} argument{'s' if len(sub.params) != 1 else ''}, "
|
|
1055
|
+
f"not {len(args)}", file=n.file)
|
|
1056
|
+
codes: list[str] = []
|
|
1057
|
+
notes: list[str] = []
|
|
1058
|
+
targets: list[str | None] = []
|
|
1059
|
+
try:
|
|
1060
|
+
for (kind, pname, _), arg in zip(sub.params, args):
|
|
1061
|
+
text = arg.strip()
|
|
1062
|
+
plain_var = re.fullmatch(r"[!%]\w+", text) is not None
|
|
1063
|
+
if plain_var and text.lower() not in tr.py and text.lower() not in tr.unset and not tr.lost and not tr.runtime:
|
|
1064
|
+
# an argument the subroutine sets (EViews makes the variable): it starts empty
|
|
1065
|
+
var, _ = tr._name(text.lower(), f"{'string' if text[0] == '%' else 'control'} {text.lower()}")
|
|
1066
|
+
from .data import _UNKNOWN, _Py
|
|
1067
|
+
|
|
1068
|
+
tr.py[text.lower()] = _Py(var, "string" if text[0] == "%" else "control", _UNKNOWN)
|
|
1069
|
+
codes.append('""' if text[0] == "%" else 'float("nan")')
|
|
1070
|
+
notes.append(f"{text} is set by {sub.name}")
|
|
1071
|
+
else:
|
|
1072
|
+
code, _, vkind, vnotes = tr.program_value(text, st.rest_at)
|
|
1073
|
+
if kind == "string" and vkind != "str":
|
|
1074
|
+
raise _left(f"{pname} is a string parameter: {text} is not a string")
|
|
1075
|
+
if kind == "scalar" and vkind == "str":
|
|
1076
|
+
raise _left(f"{pname} is a scalar parameter: {text} is a string")
|
|
1077
|
+
codes.append(code)
|
|
1078
|
+
notes += [x for x in vnotes if x not in notes]
|
|
1079
|
+
targets.append(tr.py[text.lower()].name if plain_var and text.lower() in tr.py else None)
|
|
1080
|
+
except _Out as out:
|
|
1081
|
+
tr._unset(st)
|
|
1082
|
+
self._unknown(_assigned([sub.node], self.subs))
|
|
1083
|
+
tr.forget()
|
|
1084
|
+
return Outcome(st, out.status, out.reason, file=n.file)
|
|
1085
|
+
self.translate_sub(sub)
|
|
1086
|
+
if sub.error:
|
|
1087
|
+
self._unknown(_assigned([sub.node], self.subs))
|
|
1088
|
+
tr.forget()
|
|
1089
|
+
return Outcome(st, LEFT, f"the subroutine {sub.name} is left out: {sub.error}", file=n.file)
|
|
1090
|
+
back = tuple(targets[i] for i in sub.returns)
|
|
1091
|
+
# what the subroutine assigns, through its parameters and (not local) the program's variables
|
|
1092
|
+
changed = {a.strip().lower() for a, i in zip(args, range(len(args))) if i in sub.returns}
|
|
1093
|
+
if not sub.local:
|
|
1094
|
+
changed |= _assigned(sub.node.body, self.subs)
|
|
1095
|
+
self._unknown(changed)
|
|
1096
|
+
if any(t is None for t in back):
|
|
1097
|
+
notes.append("an argument that is not a variable does not take back the value the subroutine gives its "
|
|
1098
|
+
"parameter, as in EViews")
|
|
1099
|
+
return Outcome(st, NOTE if notes else TRANSLATED, "; ".join(notes), [Invoke(sub.var, tuple(codes), back)], file=n.file)
|
|
1100
|
+
|
|
1101
|
+
def translate_sub(self, sub: _Sub) -> None:
|
|
1102
|
+
"""The subroutine's body, translated once: at its first call, or after the program."""
|
|
1103
|
+
from .data import _UNKNOWN, _Py
|
|
1104
|
+
|
|
1105
|
+
if sub.done or sub.translating:
|
|
1106
|
+
return
|
|
1107
|
+
tr = self.tr
|
|
1108
|
+
sub.translating = True
|
|
1109
|
+
if not sub.var:
|
|
1110
|
+
sub.var, _ = tr._name(sub.name, f"subroutine {sub.name}")
|
|
1111
|
+
saved_py = dict(tr.py) if sub.local else {k: v for k, v in tr.py.items()}
|
|
1112
|
+
saved = (self.sub, self.loops)
|
|
1113
|
+
self.sub, self.loops = sub, 0
|
|
1114
|
+
params: list[str] = []
|
|
1115
|
+
for kind, pname, key in sub.params:
|
|
1116
|
+
var, _ = tr._name(pname, f"parameter {sub.name}.{key}")
|
|
1117
|
+
params.append(var)
|
|
1118
|
+
tr.py[key] = _Py(var, "string" if kind == "string" else "control" if pname.startswith("!") else "scalar", _UNKNOWN)
|
|
1119
|
+
if sub.local: # a local subroutine sees only its parameters
|
|
1120
|
+
for k in list(tr.py):
|
|
1121
|
+
if k not in {key for _, _, key in sub.params}:
|
|
1122
|
+
del tr.py[k]
|
|
1123
|
+
sub.pnames = params
|
|
1124
|
+
assigned = _assigned(sub.node.body, self.subs)
|
|
1125
|
+
sub.returns = [i for i, (_, _, key) in enumerate(sub.params) if key in assigned]
|
|
1126
|
+
self._unknown(assigned)
|
|
1127
|
+
with self._runtime():
|
|
1128
|
+
sub.outcome.children = self.walk(sub.node.body)
|
|
1129
|
+
sub.outcome.closer = self._outcome(sub.node.close, TRANSLATED, f"the end of the subroutine {sub.name}", sub.node.file)
|
|
1130
|
+
names = ", ".join(params)
|
|
1131
|
+
sub.outcome.reason = "; ".join(x for x in (
|
|
1132
|
+
f"a function: def {sub.var}({names})" + (" (local: it shares none of the program's variables)" if sub.local else ""),
|
|
1133
|
+
f"it returns {', '.join(params[i] for i in sub.returns)}, which EViews passes back to the caller's variables"
|
|
1134
|
+
if sub.returns else "") if x)
|
|
1135
|
+
sub.outcome.status = NOTE
|
|
1136
|
+
sub.outcome.ops = [Def(sub.var, tuple(params), local=sub.local)] # the report's Python: the function's first line
|
|
1137
|
+
# the parameters are the function's own: the program's variables of those names come back
|
|
1138
|
+
for _, _, key in sub.params:
|
|
1139
|
+
if key in saved_py:
|
|
1140
|
+
tr.py[key] = saved_py[key]
|
|
1141
|
+
else:
|
|
1142
|
+
tr.py.pop(key, None)
|
|
1143
|
+
if sub.local:
|
|
1144
|
+
tr.py.clear()
|
|
1145
|
+
tr.py.update(saved_py)
|
|
1146
|
+
self.sub, self.loops = saved
|
|
1147
|
+
sub.translating = False
|
|
1148
|
+
sub.done = True
|
|
1149
|
+
|
|
1150
|
+
def finish(self) -> None:
|
|
1151
|
+
"""The subroutines nothing calls: translated after the program, as it stands at its end."""
|
|
1152
|
+
for sub in list(self.subs.values()):
|
|
1153
|
+
if not sub.done and not sub.error and sub.outcome is not None:
|
|
1154
|
+
self.translate_sub(sub)
|
|
1155
|
+
sub.outcome.reason += "; nothing calls it: translated after the program"
|
|
1156
|
+
|
|
1157
|
+
# -- blocks ---------------------------------------------------------------------------------------------------
|
|
1158
|
+
|
|
1159
|
+
def _left_block(self, n: Node, status: str, reason: str) -> list[Any]:
|
|
1160
|
+
from .data import Outcome
|
|
1161
|
+
|
|
1162
|
+
self.tr.forget()
|
|
1163
|
+
self._unknown(_assigned([n], self.subs))
|
|
1164
|
+
o = Outcome(n.st, status, reason, file=n.file)
|
|
1165
|
+
o.children = self._inside(n, LEFT, f"inside the {_WORDS[n.kind]} at line {n.st.line}, which is left out")
|
|
1166
|
+
return [o]
|
|
1167
|
+
|
|
1168
|
+
def block(self, n: Node) -> Any:
|
|
1169
|
+
from .data import _Out
|
|
1170
|
+
|
|
1171
|
+
tr = self.tr
|
|
1172
|
+
try:
|
|
1173
|
+
if "$" in re.sub(r'"[^"]*"', "", n.st.text):
|
|
1174
|
+
raise _left(_DOLLAR)
|
|
1175
|
+
if n.kind == "for":
|
|
1176
|
+
header, note = self.for_header(n.st)
|
|
1177
|
+
elif n.kind == "while":
|
|
1178
|
+
code, _, kind, notes = tr.program_value(n.st.rest, n.st.rest_at)
|
|
1179
|
+
header, note = While(code), "; ".join(notes)
|
|
1180
|
+
else:
|
|
1181
|
+
text = re.sub(r"(?i)\s+then\s*$", "", n.st.rest)
|
|
1182
|
+
if text == n.st.rest:
|
|
1183
|
+
raise _error("if ... then: then ends the condition")
|
|
1184
|
+
code, _, kind, notes = tr.program_value(text, n.st.rest_at)
|
|
1185
|
+
header, note = If(code), "; ".join(notes)
|
|
1186
|
+
except _Out as out:
|
|
1187
|
+
return self._left_block(n, out.status, out.reason)[0]
|
|
1188
|
+
return self._body(n, header, note)
|
|
1189
|
+
|
|
1190
|
+
def _body(self, n: Node, header: Any, note: str) -> Any:
|
|
1191
|
+
from .data import Outcome
|
|
1192
|
+
|
|
1193
|
+
tr = self.tr
|
|
1194
|
+
assigned = _assigned([n], self.subs)
|
|
1195
|
+
self._unknown(assigned)
|
|
1196
|
+
o = Outcome(n.st, NOTE if note else TRANSLATED, note, [header], file=n.file, kind=n.kind)
|
|
1197
|
+
loop = n.kind in ("for", "while")
|
|
1198
|
+
self.loops += loop
|
|
1199
|
+
with self._runtime():
|
|
1200
|
+
if n.kind == "if":
|
|
1201
|
+
before = {k: (set(p.series) if p.series is not None else None, p.sample) for k, p in tr.pages.items()}
|
|
1202
|
+
o.children = self.walk(n.body)
|
|
1203
|
+
after = {k: (set(p.series) if p.series is not None else None, p.sample) for k, p in tr.pages.items()}
|
|
1204
|
+
for k, p in tr.pages.items():
|
|
1205
|
+
if k in before:
|
|
1206
|
+
p.series = set(before[k][0]) if before[k][0] is not None else None
|
|
1207
|
+
p.sample = before[k][1]
|
|
1208
|
+
o.else_outcome = self._outcome(n.else_st, TRANSLATED, f"the else branch of the if block at line {n.st.line}", n.file)
|
|
1209
|
+
o.orelse = self.walk(n.orelse)
|
|
1210
|
+
for k, p in tr.pages.items():
|
|
1211
|
+
if k not in after:
|
|
1212
|
+
continue
|
|
1213
|
+
one, sample = after[k]
|
|
1214
|
+
p.series = None if one is None or p.series is None else p.series | one
|
|
1215
|
+
if sample != p.sample:
|
|
1216
|
+
p.sample = None
|
|
1217
|
+
tr.sample_unknown.add(p.var)
|
|
1218
|
+
else:
|
|
1219
|
+
o.children = self.walk(n.body)
|
|
1220
|
+
self.loops -= loop
|
|
1221
|
+
self._unknown(assigned)
|
|
1222
|
+
o.closer = self._outcome(n.close, TRANSLATED, f"the end of the {_WORDS[n.kind]} at line {n.st.line}", n.file)
|
|
1223
|
+
if n.kind == "while":
|
|
1224
|
+
o.reason = "; ".join(x for x in (o.reason, f"steps mode stops after {WHILE_CAP:,} passes (run(while_cap=...))") if x)
|
|
1225
|
+
o.status = NOTE
|
|
1226
|
+
return o
|
|
1227
|
+
|
|
1228
|
+
def for_header(self, st: Statement) -> tuple[Any, str]:
|
|
1229
|
+
from .data import _UNKNOWN, _Py
|
|
1230
|
+
|
|
1231
|
+
tr = self.tr
|
|
1232
|
+
text = st.rest
|
|
1233
|
+
m = re.fullmatch(r"\s*(![A-Za-z_]\w*)\s*=\s*(.+?)\s+to\s+(.+?)(?:\s+step\s+(.+?))?\s*", text, re.I | re.S)
|
|
1234
|
+
notes: list[str] = []
|
|
1235
|
+
if m:
|
|
1236
|
+
key = m.group(1).lower()
|
|
1237
|
+
bounds = []
|
|
1238
|
+
for part in (m.group(2), m.group(3), m.group(4)):
|
|
1239
|
+
if part is None:
|
|
1240
|
+
bounds.append(None)
|
|
1241
|
+
continue
|
|
1242
|
+
code, value, kind, ns = tr.program_value(part, st.rest_at)
|
|
1243
|
+
if kind == "str":
|
|
1244
|
+
raise _error(f"{part.strip()} is a string, not a number")
|
|
1245
|
+
notes += [x for x in ns if x not in notes]
|
|
1246
|
+
bounds.append((code, value))
|
|
1247
|
+
v = tr.py.get(key)
|
|
1248
|
+
if v is None:
|
|
1249
|
+
var, _ = tr._name(key, f"control {key}")
|
|
1250
|
+
tr.py[key] = _Py(var, "control", _UNKNOWN)
|
|
1251
|
+
elif v.kind not in ("control", "scalar"):
|
|
1252
|
+
raise _error(f"{m.group(1)} is a {v.kind}, not a number")
|
|
1253
|
+
var = tr.py[key].name
|
|
1254
|
+
start, end, step = bounds
|
|
1255
|
+
|
|
1256
|
+
def as_int(b: tuple[str, Any]) -> str:
|
|
1257
|
+
code, value = b
|
|
1258
|
+
if re.fullmatch(r"-?\d+", code):
|
|
1259
|
+
return code
|
|
1260
|
+
if value is not _UNKNOWN and isinstance(value, (int, float)) and float(value).is_integer():
|
|
1261
|
+
return f"int({code})" if not re.fullmatch(r"len\(.*\)", code) else code
|
|
1262
|
+
return code if re.fullmatch(r"len\(.*\)", code) else f"int({code})"
|
|
1263
|
+
|
|
1264
|
+
s, e = as_int(start), as_int(end)
|
|
1265
|
+
if step is None:
|
|
1266
|
+
stop = str(int(e) + 1) if re.fullmatch(r"-?\d+", e) else f"{e} + 1"
|
|
1267
|
+
return For(var, f"range({s}, {stop})"), "; ".join(notes)
|
|
1268
|
+
k = as_int(step)
|
|
1269
|
+
if re.fullmatch(r"-?\d+", k):
|
|
1270
|
+
if int(k) == 0:
|
|
1271
|
+
raise _error("a for loop's step is 0")
|
|
1272
|
+
d = 1 if int(k) > 0 else -1
|
|
1273
|
+
stop = str(int(e) + d) if re.fullmatch(r"-?\d+", e) else f"{e} {'+' if d > 0 else '-'} 1"
|
|
1274
|
+
return For(var, f"range({s}, {stop}, {k})"), "; ".join(notes)
|
|
1275
|
+
return For(var, f"range({s}, {e} + (1 if {k} > 0 else -1), {k})"), "; ".join(notes)
|
|
1276
|
+
m = re.fullmatch(r"\s*(%[A-Za-z_]\w*)\s+(.*)", text, re.S)
|
|
1277
|
+
if m:
|
|
1278
|
+
key = m.group(1).lower()
|
|
1279
|
+
words = re.findall(r'"[^"]*"|\S+', m.group(2))
|
|
1280
|
+
if words and re.fullmatch(r"%\w+", words[0]) and len(words) > 1 and all(re.fullmatch(r"%\w+", w) for w in words[:2]) \
|
|
1281
|
+
and words[1].lower() not in tr.py:
|
|
1282
|
+
raise _left("a for loop over several string variables at once (for %a %b ...) is not translated")
|
|
1283
|
+
items: list[str] = []
|
|
1284
|
+
for w in words:
|
|
1285
|
+
inner = re.fullmatch(r"\{?(%\w+)\}?", w)
|
|
1286
|
+
if inner and (w.startswith("{") == w.endswith("}")):
|
|
1287
|
+
vkey = inner.group(1).lower()
|
|
1288
|
+
v = tr.py.get(vkey) or tr.runtime_variable(vkey)
|
|
1289
|
+
if v is None:
|
|
1290
|
+
raise tr._missing(inner.group(1))
|
|
1291
|
+
if v.kind != "string":
|
|
1292
|
+
raise _error(f"{inner.group(1)} is a {v.kind}, not a string")
|
|
1293
|
+
if v.value is not _UNKNOWN and not tr.runtime:
|
|
1294
|
+
items += [quote(x) for x in str(v.value).split()]
|
|
1295
|
+
else:
|
|
1296
|
+
items.append(f"*{v.name}.split()")
|
|
1297
|
+
elif "{" in w or "!" in w or "%" in w:
|
|
1298
|
+
raise _left(f"{w}: a for loop's item made from a variable is not translated; a string variable of names "
|
|
1299
|
+
"({%names}) is")
|
|
1300
|
+
else:
|
|
1301
|
+
items.append(quote(w.strip('"')))
|
|
1302
|
+
if not items:
|
|
1303
|
+
raise _error("a for loop over strings names them: for %s a b c")
|
|
1304
|
+
v = tr.py.get(key)
|
|
1305
|
+
if v is None:
|
|
1306
|
+
var, _ = tr._name(key, f"string {key}")
|
|
1307
|
+
tr.py[key] = _Py(var, "string", _UNKNOWN)
|
|
1308
|
+
elif v.kind != "string":
|
|
1309
|
+
raise _error(f"{m.group(1)} is a {v.kind}, not a string")
|
|
1310
|
+
var = tr.py[key].name
|
|
1311
|
+
if len(items) == 1 and items[0].startswith("*"):
|
|
1312
|
+
return For(var, items[0][1:]), "; ".join(notes)
|
|
1313
|
+
return For(var, "[" + ", ".join(items) + "]"), "; ".join(notes)
|
|
1314
|
+
raise _error("a for loop reads: for !i = 1 to n [step k], or for %s a b c")
|
|
1315
|
+
|
|
1316
|
+
|
|
1317
|
+
def ops_of(outcomes: list[Any], file_of: Any = None) -> tuple[Any, ...]:
|
|
1318
|
+
"""The steps of translated outcomes, blocks with their bodies: (line, op, file) entries."""
|
|
1319
|
+
import dataclasses
|
|
1320
|
+
|
|
1321
|
+
out: list[Any] = []
|
|
1322
|
+
for o in outcomes:
|
|
1323
|
+
if o is None:
|
|
1324
|
+
continue
|
|
1325
|
+
if getattr(o, "kind", "") == "include":
|
|
1326
|
+
out.extend(ops_of(o.children))
|
|
1327
|
+
continue
|
|
1328
|
+
if getattr(o, "kind", "") == "subroutine":
|
|
1329
|
+
continue # functions are collected apart (functions_of)
|
|
1330
|
+
if o.status not in (TRANSLATED, NOTE):
|
|
1331
|
+
continue
|
|
1332
|
+
for op in o.ops:
|
|
1333
|
+
if isinstance(op, (For, While)):
|
|
1334
|
+
op = dataclasses.replace(op, body=ops_of(o.children))
|
|
1335
|
+
elif isinstance(op, If):
|
|
1336
|
+
op = dataclasses.replace(op, body=ops_of(o.children), orelse=ops_of(o.orelse))
|
|
1337
|
+
out.append((o.statement.line, op, o.file))
|
|
1338
|
+
return tuple(out)
|
|
1339
|
+
|
|
1340
|
+
|
|
1341
|
+
def functions_of(flow: Flow) -> list[tuple[int, Def, str]]:
|
|
1342
|
+
"""The subroutines translated, as functions: (line, Def, file), in the order they are defined."""
|
|
1343
|
+
out = []
|
|
1344
|
+
seen = set()
|
|
1345
|
+
for sub in flow.subs.values():
|
|
1346
|
+
if id(sub) in seen or sub.error or not sub.done or sub.outcome is None:
|
|
1347
|
+
continue
|
|
1348
|
+
seen.add(id(sub))
|
|
1349
|
+
body = ops_of(sub.outcome.children)
|
|
1350
|
+
shared = _shared(body, sub) if not sub.local else ()
|
|
1351
|
+
out.append((sub.node.st.line, Def(sub.var, tuple(sub.pnames), tuple(sub.pnames[i] for i in sub.returns), shared,
|
|
1352
|
+
sub.local, body), sub.node.file))
|
|
1353
|
+
return out
|
|
1354
|
+
|
|
1355
|
+
|
|
1356
|
+
def _shared(body: tuple[Any, ...], sub: _Sub) -> tuple[str, ...]:
|
|
1357
|
+
"""The names a (not local) subroutine's body assigns other than its parameters: the program's (``global``)."""
|
|
1358
|
+
from .script import body_lines
|
|
1359
|
+
|
|
1360
|
+
names: list[str] = []
|
|
1361
|
+
for line in body_lines(body, 0):
|
|
1362
|
+
m = re.match(r"\s*(?:for\s+([A-Za-z_]\w*)\s+in\b|((?:[A-Za-z_]\w*\s*,\s*)*[A-Za-z_]\w*)\s*=(?!=))", line)
|
|
1363
|
+
if m:
|
|
1364
|
+
for n in re.split(r"\s*,\s*", (m.group(1) or m.group(2)).strip()):
|
|
1365
|
+
if n and n not in sub.pnames and n not in names and n != "_":
|
|
1366
|
+
names.append(n)
|
|
1367
|
+
return tuple(names)
|
|
1368
|
+
|