hitherto 0.2.0__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.
hitherto/__init__.py ADDED
@@ -0,0 +1,39 @@
1
+ """Hitherto: a typed language for time-series feature pipelines.
2
+
3
+ This package is the compiler in Python. It reads a Hitherto program,
4
+ refuses any feature that reads the future, and gives back Python with
5
+ pandas for the rest. It needs no OCaml.
6
+
7
+ import hitherto
8
+
9
+ program = hitherto.compile('''
10
+ input mid : Stream[event, lag 0ms]
11
+ let mid_1s = bar(mid, 1s, last)
12
+ feature ret = mid_1s / shift(mid_1s, 1s) - 1
13
+ ''')
14
+ out = program.run(mid=a_pandas_series)
15
+ out["features"]["ret"]
16
+
17
+ A program that is refused raises `hitherto.CompileError`, whose text is
18
+ the message the command line prints: where, what, the cause and a hint.
19
+ """
20
+
21
+ from .api import ( # noqa: A004
22
+ CompileError,
23
+ Finding,
24
+ Program,
25
+ check,
26
+ compile,
27
+ compile_file,
28
+ format_json,
29
+ format_sarif,
30
+ lint,
31
+ lint_file,
32
+ lint_path,
33
+ )
34
+ from .version import VERSION as __version__
35
+
36
+ __all__ = [
37
+ "CompileError", "Finding", "Program", "check", "compile", "compile_file",
38
+ "format_json", "format_sarif", "lint", "lint_file", "lint_path", "__version__",
39
+ ]
hitherto/__main__.py ADDED
@@ -0,0 +1,96 @@
1
+ """The command line of the Python compiler. It takes what `htoc` takes
2
+ and prints what `htoc` prints."""
3
+
4
+ import os
5
+ import sys
6
+
7
+ from . import checker, emit, lexer, linter, parser
8
+ from .version import VERSION
9
+
10
+ USAGE = """usage: hitherto <file.hto> compile to Python and print it
11
+ hitherto <file.hto> -o <out.py> compile to Python and write it to a file
12
+ hitherto --tokens <file.hto> print the tokens
13
+ hitherto --parse <file.hto> parse and print the program back
14
+ hitherto --ast <file.hto> the same, with source spans
15
+ hitherto --check <file.hto> type check and print each declaration's type
16
+ hitherto --version
17
+ """
18
+
19
+
20
+ def main(arguments=None):
21
+ """Returns the exit code: 0, or 1 for a program that is refused, or 2
22
+ for a command that makes no sense."""
23
+ arguments = sys.argv[1:] if arguments is None else arguments
24
+ if arguments == ["--version"]:
25
+ print(VERSION)
26
+ return 0
27
+ modes = {
28
+ "--tokens": lexer.run,
29
+ "--parse": lambda path: parser.run(path, "parse"),
30
+ "--ast": lambda path: parser.run(path, "ast"),
31
+ "--check": checker.run,
32
+ "--lint": linter.run,
33
+ }
34
+ out_path = None
35
+ if arguments and arguments[0] == "--lint":
36
+ ignore_labels = False
37
+ fmt = "text"
38
+ paths = []
39
+ i = 1
40
+ while i < len(arguments):
41
+ arg = arguments[i]
42
+ if arg == "--ignore-labels":
43
+ ignore_labels = True
44
+ elif arg == "--format":
45
+ if i + 1 >= len(arguments) or arguments[i + 1] not in ("text", "json", "sarif"):
46
+ sys.stderr.write(USAGE)
47
+ return 2
48
+ fmt = arguments[i + 1]
49
+ i += 1
50
+ elif arg.startswith("--format="):
51
+ fmt = arg.split("=", 1)[1]
52
+ if fmt not in ("text", "json", "sarif"):
53
+ sys.stderr.write(USAGE)
54
+ return 2
55
+ elif arg.startswith("-"):
56
+ sys.stderr.write(USAGE)
57
+ return 2
58
+ else:
59
+ paths.append(arg)
60
+ i += 1
61
+ if not paths:
62
+ sys.stderr.write(USAGE)
63
+ return 2
64
+ for p in paths:
65
+ if not os.path.exists(p):
66
+ sys.stderr.write("hitherto: no such file: %s\n" % p)
67
+ return 2
68
+ stdout_text, stderr_text, code = linter.run(paths, ignore_labels=ignore_labels, fmt=fmt)
69
+ sys.stderr.buffer.write(stderr_text.encode("utf-8"))
70
+ sys.stdout.buffer.write(stdout_text.encode("utf-8"))
71
+ return code
72
+ if len(arguments) == 2 and arguments[0] in modes:
73
+ action, path = modes[arguments[0]], arguments[1]
74
+ elif len(arguments) == 1:
75
+ action, path = emit.run, arguments[0]
76
+ elif len(arguments) == 3 and arguments[1] == "-o":
77
+ action, path, out_path = emit.run, arguments[0], arguments[2]
78
+ else:
79
+ sys.stderr.write(USAGE)
80
+ return 2
81
+ if not os.path.exists(path):
82
+ sys.stderr.write("hitherto: no such file: %s\n" % path)
83
+ return 2
84
+ stdout_text, stderr_text, code = action(path)
85
+ # Programs are read and written a byte at a time, as `htoc` does.
86
+ sys.stderr.buffer.write(stderr_text.encode("latin-1"))
87
+ if code == 0 and out_path is not None:
88
+ with open(out_path, "wb") as f:
89
+ f.write(stdout_text.encode("latin-1"))
90
+ else:
91
+ sys.stdout.buffer.write(stdout_text.encode("latin-1"))
92
+ return code
93
+
94
+
95
+ if __name__ == "__main__":
96
+ sys.exit(main())
hitherto/api.py ADDED
@@ -0,0 +1,144 @@
1
+ """What a program that uses the compiler calls: `compile`, `check` and
2
+ the `Program` that `compile` returns."""
3
+
4
+ import builtins
5
+ import os
6
+ import sys
7
+
8
+ from . import checker as _check
9
+ from . import emit as _emit
10
+ from . import lexer as _lexer
11
+ from . import linter as _lint
12
+ from . import parser as _parser
13
+
14
+ Finding = _lint.Finding
15
+ format_json = _lint.format_json
16
+ format_sarif = _lint.format_sarif
17
+ lint = _lint.lint
18
+ lint_file = _lint.lint_file
19
+ lint_path = _lint.lint_path
20
+
21
+
22
+ class CompileError(Exception):
23
+ """A program the compiler refuses. Its text is what the command line
24
+ prints: `name:line:col: error: message`, with the cause and the hint
25
+ on the lines after it when there are any.
26
+
27
+ `line` and `col` count from one, as the command line's do."""
28
+
29
+ def __init__(self, name, line, col, message):
30
+ super().__init__("%s:%d:%d: error: %s" % (name, line, col, message))
31
+ self.name = name
32
+ self.line = line
33
+ self.col = col
34
+ self.message = message
35
+
36
+
37
+ def _as_bytes_seen(source):
38
+ """The program as the compiler reads it: one character for each byte.
39
+ The OCaml compiler reads a file as bytes, and positions in its
40
+ messages count bytes. Text is taken as UTF-8."""
41
+ if isinstance(source, bytes):
42
+ return source.decode("latin-1")
43
+ if isinstance(source, str):
44
+ return source.encode("utf-8").decode("latin-1")
45
+ raise TypeError("a program is text or bytes, and this is a %s" % type(source).__name__)
46
+
47
+
48
+ def _checked(source, name):
49
+ try:
50
+ return _check.checked_program(_parser.Parser(_as_bytes_seen(source)).program())
51
+ except (_lexer.LexError, _parser.SyntaxProblem, _check.CheckProblem) as problem:
52
+ raise CompileError(name, problem.line, problem.col, problem.message) from None
53
+
54
+
55
+ def check(source, name="<program>"):
56
+ """Type check a program without generating anything. Returns one
57
+ (keyword, name, type) for each declaration, the type as text, such as
58
+ ("feature", "ret", "Stream[bar 1s, lag 0ms]"). Raises CompileError
59
+ for a program that is refused."""
60
+ return [(decl["word"], decl["name"], _check.type_text(value)) for decl, value in _checked(source, name)]
61
+
62
+
63
+ def compile(source, name="<program>"): # noqa: A001
64
+ """Compile a program given as text. Returns a `Program`. Raises
65
+ CompileError for a program that is refused, and then nothing has been
66
+ generated. `name` is what messages and the generated code call the
67
+ program."""
68
+ checked = _checked(source, name)
69
+ return Program(name, checked, _emit.program(os.path.basename(name), checked))
70
+
71
+
72
+ def compile_file(path):
73
+ """Compile the program in a file."""
74
+ with open(path, "rb") as f:
75
+ return compile(f.read(), name=str(path))
76
+
77
+
78
+ def _find_the_runtime():
79
+ """The generated code imports `hto_rt`. Installed with pip it is on
80
+ the path already. Run from a copy of the repository it is in the
81
+ folder `runtime` beside this package, and that folder is added."""
82
+ try:
83
+ import hto_rt # noqa: F401
84
+ except ModuleNotFoundError as missing:
85
+ if missing.name != "hto_rt":
86
+ raise # hto_rt was found, and something it needs was not: pandas, most likely
87
+ beside = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "runtime")
88
+ if not os.path.exists(os.path.join(beside, "hto_rt.py")):
89
+ raise
90
+ sys.path.insert(0, beside)
91
+
92
+
93
+ class Program:
94
+ """A compiled program.
95
+
96
+ python the generated module, as text
97
+ inputs the names of its inputs, in the order they were declared
98
+ features the names of its features, in order
99
+ labels the names of its labels, in order
100
+ types the checked type of every name, as text
101
+
102
+ `run` runs it on pandas data and needs pandas. Everything else,
103
+ compiling included, does not."""
104
+
105
+ def __init__(self, name, checked, python):
106
+ self.name = name
107
+ self.python = python
108
+ self.inputs = [decl["name"] for decl, _ in checked if decl["word"] == "input"]
109
+ self.features = [decl["name"] for decl, _ in checked if decl["word"] == "feature"]
110
+ self.labels = [decl["name"] for decl, _ in checked if decl["word"] == "label"]
111
+ self.types = {decl["name"]: _check.type_text(value) for decl, value in checked}
112
+ self._function = None
113
+
114
+ def __repr__(self):
115
+ return "<hitherto.Program %s: %d inputs, %d features, %d labels>" % (
116
+ self.name, len(self.inputs), len(self.features), len(self.labels))
117
+
118
+ def run(self, *positional, **named):
119
+ """Run the program. Inputs are given by position, in the order
120
+ they were declared, or by the names they have in the program. A
121
+ stream is a pandas Series indexed by timestamps, a panel a dict
122
+ from symbol to such a Series, and a universe a dict from symbol
123
+ to a DatetimeIndex. Returns {"features": {...}, "labels": {...}}."""
124
+ if len(positional) > len(self.inputs):
125
+ raise TypeError("%s takes %d inputs (%s) and was given %d"
126
+ % (self.name, len(self.inputs), ", ".join(self.inputs), len(positional)))
127
+ given = dict(zip(self.inputs, positional))
128
+ for name, value in named.items():
129
+ if name not in self.inputs:
130
+ raise TypeError("%s has no input called `%s`. Its inputs are: %s"
131
+ % (self.name, name, ", ".join(self.inputs) or "none"))
132
+ if name in given:
133
+ raise TypeError("the input `%s` was given twice" % name)
134
+ given[name] = value
135
+ missing = [name for name in self.inputs if name not in given]
136
+ if missing:
137
+ raise TypeError("%s was not given its input%s %s"
138
+ % (self.name, "" if len(missing) == 1 else "s", ", ".join("`%s`" % m for m in missing)))
139
+ if self._function is None:
140
+ _find_the_runtime()
141
+ namespace = {}
142
+ exec(builtins.compile(self.python, "<hitherto: %s>" % self.name, "exec"), namespace)
143
+ self._function = namespace["run"]
144
+ return self._function(*[given[name] for name in self.inputs])