unitracker-grammar 0.3.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.
- unitracker_grammar/__init__.py +15 -0
- unitracker_grammar/canonical.lark +178 -0
- unitracker_grammar/canonical.py +28 -0
- unitracker_grammar/expr.py +292 -0
- unitracker_grammar/notes.py +25 -0
- unitracker_grammar-0.3.0.dist-info/METADATA +271 -0
- unitracker_grammar-0.3.0.dist-info/RECORD +10 -0
- unitracker_grammar-0.3.0.dist-info/WHEEL +5 -0
- unitracker_grammar-0.3.0.dist-info/licenses/LICENSE +201 -0
- unitracker_grammar-0.3.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""The canonical unitracker document as a Lark grammar, with its note table."""
|
|
2
|
+
|
|
3
|
+
from unitracker_grammar.canonical import GRAMMAR, CanonicalError, parse, parser
|
|
4
|
+
from unitracker_grammar.notes import NTSC_HZ, PAL_HZ, frequency, table
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"GRAMMAR",
|
|
8
|
+
"NTSC_HZ",
|
|
9
|
+
"PAL_HZ",
|
|
10
|
+
"CanonicalError",
|
|
11
|
+
"frequency",
|
|
12
|
+
"parse",
|
|
13
|
+
"parser",
|
|
14
|
+
"table",
|
|
15
|
+
]
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
// The canonical unitracker document: format 1.20 with the init row (anarkiwi/unitracker#165),
|
|
2
|
+
// value-or-expression command arguments (anarkiwi/unitracker#172) and no fixed record types
|
|
3
|
+
// (anarkiwi/unitracker#126, anarkiwi/unitracker#165). A document names no player: everything it
|
|
4
|
+
// plays is in it, and its only constants are the note table F(k) (notes.py) at its clock.
|
|
5
|
+
// Whitespace is exact, but a space inside a flow collection or a block scalar may be a line
|
|
6
|
+
// wrap (a newline and the continuation indentation); a flow expression that contains a comma
|
|
7
|
+
// is written in single quotes. Every block line ends with its newline.
|
|
8
|
+
|
|
9
|
+
start: "unitracker: " VERSION _NL meta _NL (clock _NL)? (voices _NL)? (tempo _NL)? tables? (init _NL)? "song:" _NL row+ ending
|
|
10
|
+
|
|
11
|
+
// ---- header: clock, voices and tempo only where they differ from PAL, 3 and 6 ---------------
|
|
12
|
+
|
|
13
|
+
meta: "meta: " _LC meta_item (_SEP meta_item)* "}"
|
|
14
|
+
meta_item: META_KEY ": " text
|
|
15
|
+
text: TEXT | SQUOTED | DQUOTED
|
|
16
|
+
|
|
17
|
+
clock: "clock: {cycles_per_tick: " INT ", clock_hz: " INT "}"
|
|
18
|
+
voices: "voices: " INT
|
|
19
|
+
tempo: "tempo: " (INT | "[" INT ", " INT "]")
|
|
20
|
+
|
|
21
|
+
// the tables expressions index as T[k]: 0 outside the list
|
|
22
|
+
tables: "tables:" _NL (" " XTABLE ": " intlist _NL)+
|
|
23
|
+
intlist: _LB INT (_SEP INT)* "]"
|
|
24
|
+
|
|
25
|
+
// one event per voice: the state after init, a step of no duration before the first tick
|
|
26
|
+
init: "init: " _LB event (_SEP event)* "]"
|
|
27
|
+
|
|
28
|
+
// ---- timeline ---------------------------------------------------------------------------
|
|
29
|
+
|
|
30
|
+
row: " - def:" _NL section+ " play: " plays _NL
|
|
31
|
+
| " - play: " plays _NL
|
|
32
|
+
ending: " - end" _NL | " - {loop: " INT "}" _NL
|
|
33
|
+
plays: _LB play (_SEP play)* "]"
|
|
34
|
+
play: PHRASE SIGNED? | CONT | END
|
|
35
|
+
|
|
36
|
+
// ---- definitions: each record type once per row, names in first-use order --------------
|
|
37
|
+
|
|
38
|
+
section: " restart:" _NL (" " RESTART ": " program _NL)+
|
|
39
|
+
| " ins:" _NL (" " INS ": " instrument _NL)+
|
|
40
|
+
| " ctrl:" _NL (" " CTRL ": " program _NL)+
|
|
41
|
+
| " pw:" _NL (" " PW ": " modulation _NL)+
|
|
42
|
+
| " filter:" _NL (" " FILTER ": " modulation _NL)+
|
|
43
|
+
| " x:" _NL (" " X ": " expr _NL)+
|
|
44
|
+
| " phrase:" _NL (" " PHRASE ": " phrase _NL)+
|
|
45
|
+
|
|
46
|
+
instrument: _LC ins_ad "}"
|
|
47
|
+
ins_ad: "ad: " (INT) (_SEP ins_sr)? | ins_sr
|
|
48
|
+
ins_sr: "sr: " (INT) (_SEP ins_ctrl)? | ins_ctrl
|
|
49
|
+
ins_ctrl: "ctrl: " (CTRL | program) (_SEP ins_pw)? | ins_pw
|
|
50
|
+
ins_pw: "pw: " (PW | modulation) (_SEP ins_filter)? | ins_filter
|
|
51
|
+
ins_filter: "filter: " (FILTER | modulation) (_SEP ins_freq)? | ins_freq
|
|
52
|
+
ins_freq: "freq: " (fexpr) (_SEP ins_fn)? | ins_fn
|
|
53
|
+
ins_fn: "mod: " NAME (_WB param_bag)? (_SEP ins_restart)? | ins_restart
|
|
54
|
+
param_bag: "{" pname_val (_SEP pname_val)* "}"
|
|
55
|
+
pname_val: NAME _BSC (SIGNED | INT | NAME | pname_list)
|
|
56
|
+
pname_list: "[" (SIGNED | INT) (_SEP (SIGNED | INT))* "]"
|
|
57
|
+
_WB: /(?: |\n +)/ // a flow space that may be a line wrap
|
|
58
|
+
_BSC: /:(?: |\n +)/ // a bag's colon, a space or a line wrap before its value
|
|
59
|
+
ins_restart: "restart: " (RESTART | program)
|
|
60
|
+
|
|
61
|
+
// a program: its rows in the order they run, then its end or its loop
|
|
62
|
+
program: _LB (row_ _SEP)* (END | _LC LOOP INT "}") "]"
|
|
63
|
+
// a pulse or filter program that is one expression (a constant is one) is written as that
|
|
64
|
+
modulation: program | fexpr
|
|
65
|
+
|
|
66
|
+
row_: _LC "}" | _LC row_wait "}"
|
|
67
|
+
row_wait: "wait: " (INT) (_SEP row_hold)? | row_hold
|
|
68
|
+
row_hold: "hold: " (INT) (_SEP row_ctrl)? | row_ctrl
|
|
69
|
+
row_ctrl: "ctrl: " (ctrl_value) (_SEP row_gate)? | row_gate
|
|
70
|
+
row_gate: "gate: " (INT) (_SEP row_note)? | row_note
|
|
71
|
+
row_note: "note: " (note_value) (_SEP row_ad)? | row_ad
|
|
72
|
+
row_ad: "ad: " (INT) (_SEP row_sr)? | row_sr
|
|
73
|
+
row_sr: "sr: " (INT) (_SEP row_pw)? | row_pw
|
|
74
|
+
row_pw: "pw: " (pw_value) (_SEP row_cut)? | row_cut
|
|
75
|
+
row_cut: "cut: " (fexpr) (_SEP row_res)? | row_res
|
|
76
|
+
row_res: "res: " (INT) (_SEP row_route)? | row_route
|
|
77
|
+
row_route: "route: " (route_value) (_SEP row_mode)? | row_mode
|
|
78
|
+
row_mode: "mode: " (INT) (_SEP row_freq)? | row_freq
|
|
79
|
+
row_freq: "freq: " (fexpr) (_SEP row_run)? | row_run
|
|
80
|
+
row_run: "run: " (program_name) (_SEP row_filter)? | row_filter
|
|
81
|
+
row_filter: "filter: " (NONE) (_SEP row_vol)? | row_vol
|
|
82
|
+
row_vol: "vol: " (INT)
|
|
83
|
+
|
|
84
|
+
ctrl_value: INT | CTRLMASK
|
|
85
|
+
note_value: SIGNED | NOTE
|
|
86
|
+
pw_value: fexpr | NONE
|
|
87
|
+
route_value: INT | ROUTE_ADD | ROUTE_ADD_MASK INT | ROUTE_REMOVE | ROUTE_REMOVE_MASK INT "'"
|
|
88
|
+
program_name: CTRL | PW | FILTER
|
|
89
|
+
|
|
90
|
+
// ---- events -----------------------------------------------------------------------------
|
|
91
|
+
|
|
92
|
+
phrase: _LB event (_SEP event)* "]"
|
|
93
|
+
event: NOTE_ATOM ("." INS)? cmd_run keep_pw keep_filter ("*" INT)?
|
|
94
|
+
cmd_run: "!run:" (program_name | NONE) cmd_pw | cmd_pw
|
|
95
|
+
cmd_pw: "!pw:" (INT | X | NONE) cmd_filter | cmd_filter
|
|
96
|
+
cmd_filter: FILTER_NONE cmd_ad | cmd_ad
|
|
97
|
+
cmd_ad: "!ad:" INT cmd_sr | cmd_sr
|
|
98
|
+
cmd_sr: "!sr:" INT cmd_ctrl | cmd_ctrl
|
|
99
|
+
cmd_ctrl: "!ctrl:" INT cmd_resfilt | cmd_resfilt
|
|
100
|
+
cmd_resfilt: "!resfilt:" INT "/" INT cmd_mode | cmd_mode
|
|
101
|
+
cmd_mode: "!mode:" INT cmd_vol | cmd_vol
|
|
102
|
+
cmd_vol: "!vol:" INT cmd_cut | cmd_cut
|
|
103
|
+
cmd_cut: "!cut:" (INT | X) cmd_tempo | cmd_tempo
|
|
104
|
+
cmd_tempo: "!tempo:" INT ("/" INT)? cmd_vtempo | cmd_vtempo
|
|
105
|
+
cmd_vtempo: "!vtempo:" INT ("/" INT)? cmd_freq | cmd_freq
|
|
106
|
+
cmd_freq: "!freq:" (X | NONE | SIGNED | INT) cmd_set | cmd_set
|
|
107
|
+
cmd_set: ("!set " NAME " " (SIGNED | INT))+ cmd_legato | cmd_legato
|
|
108
|
+
cmd_legato: LEGATO |
|
|
109
|
+
keep_pw: KEEP_PW |
|
|
110
|
+
keep_filter: KEEP_FILTER |
|
|
111
|
+
|
|
112
|
+
// ---- expressions (docs/modulation/expressions.md) ---------------------------------------
|
|
113
|
+
|
|
114
|
+
// plain in a block mapping; in a flow collection plain, or in quotes when it contains a comma
|
|
115
|
+
fexpr: expr | "'" expr "'"
|
|
116
|
+
expr: term (ADD term)*
|
|
117
|
+
term: factor (MUL factor | FLOORDIV factor | MOD factor)*
|
|
118
|
+
factor: INT | SIGNED | V | PHI | N
|
|
119
|
+
| F expr ")" | XTABLE "[" expr "]"
|
|
120
|
+
| ABS expr ")" | MIN expr _SEP expr ")" | MAX expr _SEP expr ")"
|
|
121
|
+
| "(" expr ")" | "(" expr CMP expr ")"
|
|
122
|
+
| NEG factor
|
|
123
|
+
|
|
124
|
+
// ---- terminals --------------------------------------------------------------------------
|
|
125
|
+
|
|
126
|
+
VERSION: /\d+\.\d+/
|
|
127
|
+
META_KEY: "title" | "author" | "released"
|
|
128
|
+
XTABLE: /[A-EG-MO-Z][A-Za-z]*/
|
|
129
|
+
INT: /\d+/
|
|
130
|
+
SIGNED: /[+-]\d+/
|
|
131
|
+
CTRLMASK: /\d*\^\d+/
|
|
132
|
+
NOTE: /[A-G]#?-?\d+/
|
|
133
|
+
NOTE_ATOM: /[A-G]#?-?\d+|-|off|on/
|
|
134
|
+
INS: /i\d+/
|
|
135
|
+
CTRL: /c\d+/
|
|
136
|
+
PW: /pw\d+/
|
|
137
|
+
FILTER: /f\d+/
|
|
138
|
+
RESTART: /r\d+/
|
|
139
|
+
X: /x\d+/
|
|
140
|
+
PHRASE: /p\d+/
|
|
141
|
+
TEXT: /[^\s,\[\]{}'"#&*!|>%@`][^,\[\]{}]*/
|
|
142
|
+
SQUOTED: /'(?:[^']|'')*'/
|
|
143
|
+
DQUOTED: /"(?:[^"\\]|\\.)*"/
|
|
144
|
+
NAME: /[a-z][a-z0-9_]*/
|
|
145
|
+
|
|
146
|
+
CONT: "~"
|
|
147
|
+
END: "end"
|
|
148
|
+
LOOP: "loop: "
|
|
149
|
+
NONE: "none"
|
|
150
|
+
ROUTE_ADD: "+"
|
|
151
|
+
ROUTE_ADD_MASK: "+ "
|
|
152
|
+
ROUTE_REMOVE: "'-'"
|
|
153
|
+
ROUTE_REMOVE_MASK: "'- "
|
|
154
|
+
FILTER_NONE: "!filter:none"
|
|
155
|
+
LEGATO: "!legato"
|
|
156
|
+
KEEP_PW: "!pw"
|
|
157
|
+
KEEP_FILTER: "!filter"
|
|
158
|
+
OSC_MOD: "symmetric" | "ramp" | "approach"
|
|
159
|
+
V: "v"
|
|
160
|
+
PHI: "φ"
|
|
161
|
+
N: "N"
|
|
162
|
+
F: "F("
|
|
163
|
+
ABS: "abs("
|
|
164
|
+
MIN: "min("
|
|
165
|
+
MAX: "max("
|
|
166
|
+
NEG: "-"
|
|
167
|
+
MUL: "*"
|
|
168
|
+
|
|
169
|
+
_NL: "\n"
|
|
170
|
+
// a flow collection may wrap after its opening bracket
|
|
171
|
+
_LB: /\[(?:\n +)?/
|
|
172
|
+
_LC: /\{(?:\n +)?/
|
|
173
|
+
_SEP: /,(?: |\n +)/
|
|
174
|
+
|
|
175
|
+
ADD: /(?: |\n +)[+-](?: |\n +)/
|
|
176
|
+
FLOORDIV: /(?: |\n +)\/\/(?: |\n +)/
|
|
177
|
+
MOD: /(?: |\n +)%(?: |\n +)/
|
|
178
|
+
CMP: /(?: |\n +)(?:==|!=|<=|>=|<|>)(?: |\n +)/
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""The canonical document grammar, ``canonical.lark``, and a parser for it."""
|
|
2
|
+
|
|
3
|
+
import functools
|
|
4
|
+
from importlib import resources
|
|
5
|
+
|
|
6
|
+
from lark import Lark, Tree, exceptions
|
|
7
|
+
|
|
8
|
+
GRAMMAR = resources.files("unitracker_grammar") / "canonical.lark"
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class CanonicalError(ValueError):
|
|
12
|
+
"""A text that is not a canonical document."""
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@functools.lru_cache(maxsize=1)
|
|
16
|
+
def parser() -> Lark:
|
|
17
|
+
"""The LALR parser of the canonical grammar."""
|
|
18
|
+
return Lark(GRAMMAR.read_text(encoding="utf-8"), parser="lalr", lexer="contextual")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def parse(text: str) -> Tree:
|
|
22
|
+
"""The parse tree of canonical document ``text``."""
|
|
23
|
+
try:
|
|
24
|
+
return parser().parse(text)
|
|
25
|
+
except exceptions.UnexpectedInput as exc:
|
|
26
|
+
raise CanonicalError(
|
|
27
|
+
f"line {exc.line} column {exc.column}: {str(exc).splitlines()[0]}"
|
|
28
|
+
) from exc
|
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
"""Modulator expressions: checked, printed in their one text and compiled to Python.
|
|
2
|
+
|
|
3
|
+
Integer literals, ``+ - *``, ``//`` (floor division), ``%`` (floor modulo), ``abs``, ``min``,
|
|
4
|
+
``max``, a comparison ``(a op b)`` as 1 or 0 (op one of ``== != < <= > >=``), ``v``, ``φ``,
|
|
5
|
+
``N``, ``F(k)`` (the frequency of note k) and ``T[k]`` for a named table ``T``. An expression is
|
|
6
|
+
a stdlib :mod:`ast` node, read from a text by :func:`tree` or from a canonical parse tree by
|
|
7
|
+
:class:`Nodes`.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import ast
|
|
11
|
+
import functools
|
|
12
|
+
|
|
13
|
+
from lark import Token, Transformer
|
|
14
|
+
|
|
15
|
+
PHI = "φ"
|
|
16
|
+
NAMES = {"v": "v", PHI: "phi", "N": "N"}
|
|
17
|
+
CALLS = {"abs": 1, "min": 2, "max": 2, "F": 1}
|
|
18
|
+
_CALLED = {"F": "_F"}
|
|
19
|
+
_BINARY = {ast.Add: "+", ast.Sub: "-", ast.Mult: "*", ast.FloorDiv: "//", ast.Mod: "%"}
|
|
20
|
+
_COMPARE = {ast.Eq: "==", ast.NotEq: "!=", ast.Lt: "<", ast.LtE: "<=", ast.Gt: ">", ast.GtE: ">="}
|
|
21
|
+
_OPERATOR = {text: op for op, text in (_BINARY | _COMPARE).items()}
|
|
22
|
+
_GUARDED = {"//": "_div", "%": "_mod"}
|
|
23
|
+
_ATOMS = {"V": "v", "PHI": PHI, "N": "N"}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class ExpressionError(ValueError):
|
|
27
|
+
"""A text is not an expression of the modulator grammar."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def written(text: str):
|
|
31
|
+
"""The written value of an expression text: an integer literal as an int."""
|
|
32
|
+
try:
|
|
33
|
+
return int(text)
|
|
34
|
+
except ValueError:
|
|
35
|
+
return text
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _python(node, tables, zero: bool) -> str:
|
|
39
|
+
"""Python source of a parsed expression reading ``tables`` (see :func:`source`)."""
|
|
40
|
+
# pylint: disable=too-many-return-statements
|
|
41
|
+
if (
|
|
42
|
+
isinstance(node, ast.Constant)
|
|
43
|
+
and isinstance(node.value, int)
|
|
44
|
+
and not isinstance(node.value, bool)
|
|
45
|
+
):
|
|
46
|
+
return str(node.value)
|
|
47
|
+
if isinstance(node, ast.Name) and node.id in NAMES:
|
|
48
|
+
return NAMES[node.id]
|
|
49
|
+
if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.USub):
|
|
50
|
+
return f"(-{_python(node.operand, tables, zero)})"
|
|
51
|
+
if isinstance(node, ast.BinOp) and type(node.op) in _BINARY:
|
|
52
|
+
op = _BINARY[type(node.op)]
|
|
53
|
+
left, right = _python(node.left, tables, zero), _python(node.right, tables, zero)
|
|
54
|
+
if (
|
|
55
|
+
zero
|
|
56
|
+
and op in _GUARDED
|
|
57
|
+
and not (isinstance(node.right, ast.Constant) and node.right.value)
|
|
58
|
+
):
|
|
59
|
+
return f"{_GUARDED[op]}({left}, {right})"
|
|
60
|
+
return f"({left} {op} {right})"
|
|
61
|
+
if isinstance(node, ast.Compare):
|
|
62
|
+
return _comparison(node, tables, zero)
|
|
63
|
+
if isinstance(node, ast.List):
|
|
64
|
+
raise ExpressionError(
|
|
65
|
+
f"{ast.unparse(node)!r} is outside the grammar: a comparison is written (a op b)"
|
|
66
|
+
)
|
|
67
|
+
if isinstance(node, ast.Call):
|
|
68
|
+
name = node.func.id if isinstance(node.func, ast.Name) else None
|
|
69
|
+
if node.keywords or name not in CALLS:
|
|
70
|
+
raise ExpressionError(f"{ast.unparse(node)!r} calls no grammar function")
|
|
71
|
+
if len(node.args) != CALLS[name]:
|
|
72
|
+
raise ExpressionError(f"{name} takes {CALLS[name]} argument(s)")
|
|
73
|
+
args = ", ".join(_python(a, tables, zero) for a in node.args)
|
|
74
|
+
return f"{_CALLED.get(name, name)}({args})"
|
|
75
|
+
if isinstance(node, ast.Subscript) and isinstance(node.value, ast.Name):
|
|
76
|
+
name = node.value.id
|
|
77
|
+
if name not in tables:
|
|
78
|
+
raise ExpressionError(f"unknown table {name!r}")
|
|
79
|
+
return f"_T[{name!r}]({_python(node.slice, tables, zero)})"
|
|
80
|
+
raise ExpressionError(f"{ast.unparse(node)!r} is outside the grammar")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _comparison(node, tables, zero: bool) -> str:
|
|
84
|
+
"""One comparison, 1 when it holds, else 0."""
|
|
85
|
+
if len(node.ops) != 1:
|
|
86
|
+
raise ExpressionError(f"({ast.unparse(node)}) is not one comparison")
|
|
87
|
+
op = _COMPARE.get(type(node.ops[0]))
|
|
88
|
+
if op is None:
|
|
89
|
+
raise ExpressionError(f"({ast.unparse(node)}) compares with no grammar operator")
|
|
90
|
+
left, right = _python(node.left, tables, zero), _python(node.comparators[0], tables, zero)
|
|
91
|
+
return f"(1 if {left} {op} {right} else 0)"
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def tree(text: str) -> ast.expr:
|
|
95
|
+
"""The node of an expression text, unchecked."""
|
|
96
|
+
try:
|
|
97
|
+
return ast.parse(text.strip(), mode="eval").body
|
|
98
|
+
except SyntaxError as exc:
|
|
99
|
+
raise ExpressionError(f"bad expression {text!r}: {exc.msg}") from exc
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def source(expr: str | ast.expr, tables=(), zero: bool = False) -> str:
|
|
103
|
+
"""Python source over ``v``, ``phi``, ``N``, ``_F`` and ``_T`` of an expression text or node;
|
|
104
|
+
``zero``: ``//`` and ``%`` by a divisor that is no nonzero literal call ``_div`` and ``_mod``,
|
|
105
|
+
0 by a divisor of 0, else they raise ZeroDivisionError."""
|
|
106
|
+
return _python(tree(expr) if isinstance(expr, str) else expr, set(tables), zero)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def canonical(text: str) -> str:
|
|
110
|
+
"""The one text of expression ``text`` (see :func:`printed`)."""
|
|
111
|
+
return printed(tree(text))
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def printed(node) -> str:
|
|
115
|
+
"""The one text of expression node ``node``: sums and products as linear forms (constant
|
|
116
|
+
terms and factors folded, like terms merged), terms in one order, parentheses only where the
|
|
117
|
+
grammar needs them, and decimal literals."""
|
|
118
|
+
return _sum(*_linear(node))
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _linear(node) -> tuple[int, dict]:
|
|
122
|
+
"""``(constant, {factors: coefficient})`` of ``node`` as a sum of products."""
|
|
123
|
+
if isinstance(node, ast.Constant):
|
|
124
|
+
return int(node.value), {}
|
|
125
|
+
if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.USub):
|
|
126
|
+
const, terms = _linear(node.operand)
|
|
127
|
+
return -const, {f: -c for f, c in terms.items()}
|
|
128
|
+
if isinstance(node, ast.BinOp) and isinstance(node.op, (ast.Add, ast.Sub)):
|
|
129
|
+
sign = 1 if isinstance(node.op, ast.Add) else -1
|
|
130
|
+
(a, at), (b, bt) = _linear(node.left), _linear(node.right)
|
|
131
|
+
terms = dict(at)
|
|
132
|
+
for f, c in bt.items():
|
|
133
|
+
terms[f] = terms.get(f, 0) + sign * c
|
|
134
|
+
return a + sign * b, {f: c for f, c in terms.items() if c}
|
|
135
|
+
if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mult):
|
|
136
|
+
return _product(_linear(node.left), _linear(node.right))
|
|
137
|
+
return 0, {(_factor(node),): 1}
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _product(left: tuple, right: tuple) -> tuple[int, dict]:
|
|
141
|
+
(a, at), (b, bt) = left, right
|
|
142
|
+
if not at or not bt:
|
|
143
|
+
const, terms, k = (b, bt, a) if not at else (a, at, b)
|
|
144
|
+
return const * k, {f: c * k for f, c in terms.items() if c * k}
|
|
145
|
+
factors = []
|
|
146
|
+
coef = 1
|
|
147
|
+
for const, terms in (left, right):
|
|
148
|
+
if not const and len(terms) == 1:
|
|
149
|
+
((f, c),) = terms.items()
|
|
150
|
+
factors += f
|
|
151
|
+
coef *= c
|
|
152
|
+
else:
|
|
153
|
+
factors.append(f"({_sum(const, terms)})")
|
|
154
|
+
return 0, {tuple(sorted(factors, key=_order)): coef}
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _factor(node) -> str:
|
|
158
|
+
"""The text of a node that is no sum or product, as a factor."""
|
|
159
|
+
# pylint: disable=too-many-return-statements
|
|
160
|
+
if isinstance(node, ast.Name):
|
|
161
|
+
return node.id
|
|
162
|
+
if isinstance(node, ast.Compare):
|
|
163
|
+
op = _COMPARE[type(node.ops[0])]
|
|
164
|
+
return f"({printed(node.left)} {op} {printed(node.comparators[0])})"
|
|
165
|
+
if isinstance(node, ast.Call):
|
|
166
|
+
args = [printed(a) for a in node.args]
|
|
167
|
+
if node.func.id in ("min", "max"):
|
|
168
|
+
args.sort(key=_order)
|
|
169
|
+
return f"{node.func.id}({', '.join(args)})"
|
|
170
|
+
if isinstance(node, ast.Subscript):
|
|
171
|
+
return f"{node.value.id}[{printed(node.slice)}]"
|
|
172
|
+
if isinstance(node, ast.BinOp):
|
|
173
|
+
left, right = _linear(node.left), _linear(node.right)
|
|
174
|
+
return f"{_operand(*left, True)} {_BINARY[type(node.op)]} {_operand(*right)}"
|
|
175
|
+
raise ExpressionError(f"{ast.unparse(node)!r} is outside the grammar")
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _operand(const: int, terms: dict, left: bool = False) -> str:
|
|
179
|
+
"""An operand of ``%`` or ``//``: a term on the left, a factor on the right."""
|
|
180
|
+
text = _sum(const, terms)
|
|
181
|
+
if not terms or (len(terms) == 1 and not const and (left or _atomic(terms))):
|
|
182
|
+
return text
|
|
183
|
+
return f"({text})"
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _sum(const: int, terms: dict) -> str:
|
|
187
|
+
out = []
|
|
188
|
+
for factors, coef in sorted(terms.items(), key=lambda t: _order("*".join(t[0]))):
|
|
189
|
+
body = "*".join(
|
|
190
|
+
f"({f})" if _divides(f) and (len(factors) > 1 or abs(coef) != 1) else f for f in factors
|
|
191
|
+
)
|
|
192
|
+
if abs(coef) != 1:
|
|
193
|
+
body = f"{abs(coef)}*{body}"
|
|
194
|
+
if not out:
|
|
195
|
+
lead = "-" if coef < 0 else ""
|
|
196
|
+
if coef == -1 and len(factors) == 1 and _divides(factors[0]):
|
|
197
|
+
body = f"({body})"
|
|
198
|
+
out.append(lead + body)
|
|
199
|
+
else:
|
|
200
|
+
out.append((" - " if coef < 0 else " + ") + body)
|
|
201
|
+
if const or not out:
|
|
202
|
+
out.append(str(const) if not out else (" - " if const < 0 else " + ") + str(abs(const)))
|
|
203
|
+
return "".join(out)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _divides(factor: str) -> bool:
|
|
207
|
+
"""Whether a factor's text is a ``%`` or ``//`` at its top level."""
|
|
208
|
+
depth = 0
|
|
209
|
+
for k, ch in enumerate(factor):
|
|
210
|
+
depth += {"(": 1, "[": 1, ")": -1, "]": -1}.get(ch, 0)
|
|
211
|
+
if not depth and factor[k : k + 3] in (" % ", " //"):
|
|
212
|
+
return True
|
|
213
|
+
return False
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _atomic(terms: dict) -> bool:
|
|
217
|
+
((factors, coef),) = terms.items()
|
|
218
|
+
return coef == 1 and len(factors) == 1 and not _divides(factors[0])
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _order(text: str) -> tuple:
|
|
222
|
+
"""The order of terms and factors: integers, names, then the rest, each by its text."""
|
|
223
|
+
return (0 if text.lstrip("-").isdigit() else 1 if text in NAMES else 2, text)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _div(a: int, b: int) -> int:
|
|
227
|
+
return a // b if b else 0
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _mod(a: int, b: int) -> int:
|
|
231
|
+
return a % b if b else 0
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def compile_expr(expr: str | ast.expr, namespace: dict, zero: bool = False):
|
|
235
|
+
"""A function ``(v, phi, N) -> int`` of an expression text or node (``zero`` as in
|
|
236
|
+
:func:`source`).
|
|
237
|
+
|
|
238
|
+
``namespace``, the function's globals, holds ``_F(k)``, the frequency of format note k, and
|
|
239
|
+
``_T``, each named table's function of its index.
|
|
240
|
+
"""
|
|
241
|
+
body = source(expr, namespace["_T"], zero)
|
|
242
|
+
if zero:
|
|
243
|
+
# pylint: disable-next=eval-used
|
|
244
|
+
return eval(f"lambda _div, _mod: lambda v, phi, N: {body}", namespace)(_div, _mod)
|
|
245
|
+
return eval(f"lambda v, phi, N: {body}", namespace) # pylint: disable=eval-used
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _at(values: tuple, k: int) -> int:
|
|
249
|
+
return values[k] if 0 <= k < len(values) else 0
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def indexed(values) -> functools.partial:
|
|
253
|
+
"""A table's function of its index: ``values[k]``, 0 outside them."""
|
|
254
|
+
return functools.partial(_at, tuple(values))
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
class Nodes(Transformer):
|
|
258
|
+
"""The expressions of a canonical parse tree (rules ``fexpr``, ``expr``, ``term`` and
|
|
259
|
+
``factor``) as nodes; ``-`` before a literal is a negative literal."""
|
|
260
|
+
|
|
261
|
+
# pylint: disable=missing-function-docstring
|
|
262
|
+
|
|
263
|
+
def fexpr(self, children):
|
|
264
|
+
return children[0]
|
|
265
|
+
|
|
266
|
+
def expr(self, children):
|
|
267
|
+
out = children[0]
|
|
268
|
+
for op, operand in zip(children[1::2], children[2::2]):
|
|
269
|
+
out = ast.BinOp(out, _OPERATOR[op.strip()](), operand)
|
|
270
|
+
return out
|
|
271
|
+
|
|
272
|
+
term = expr
|
|
273
|
+
|
|
274
|
+
def factor(self, children):
|
|
275
|
+
# pylint: disable=too-many-return-statements
|
|
276
|
+
head, *rest = children
|
|
277
|
+
if not isinstance(head, Token):
|
|
278
|
+
if not rest:
|
|
279
|
+
return head
|
|
280
|
+
return ast.Compare(head, [_OPERATOR[rest[0].strip()]()], [rest[1]])
|
|
281
|
+
if head.type in ("INT", "SIGNED"):
|
|
282
|
+
return ast.Constant(int(head))
|
|
283
|
+
if head.type in _ATOMS:
|
|
284
|
+
return ast.Name(_ATOMS[head.type])
|
|
285
|
+
if head.type == "XTABLE":
|
|
286
|
+
return ast.Subscript(ast.Name(str(head)), rest[0])
|
|
287
|
+
if head.type == "NEG":
|
|
288
|
+
(inner,) = rest
|
|
289
|
+
if isinstance(inner, ast.Constant):
|
|
290
|
+
return ast.Constant(-inner.value)
|
|
291
|
+
return ast.UnaryOp(ast.USub(), inner)
|
|
292
|
+
return ast.Call(ast.Name(head[:-1]), rest, [])
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""The note table: ``F(k)``, the SID frequency word of format note ``k`` at a clock."""
|
|
2
|
+
|
|
3
|
+
PAL_HZ = 985248
|
|
4
|
+
NTSC_HZ = 1022727
|
|
5
|
+
A4 = 57
|
|
6
|
+
A4_HZ = 440
|
|
7
|
+
WORD = 1 << 16
|
|
8
|
+
PHASE = 1 << 24
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def frequency(note: int, clock_hz: int = PAL_HZ) -> int:
|
|
12
|
+
"""``F(k)``: the frequency word of format note ``k`` (C2 is 24) in equal temperament from
|
|
13
|
+
A4 at 440 Hz, rounded to the nearest word; 0 below C0 and where the word overflows."""
|
|
14
|
+
if note < 0:
|
|
15
|
+
return 0
|
|
16
|
+
word = round(A4_HZ * 2 ** ((note - A4) / 12) * PHASE / clock_hz)
|
|
17
|
+
return word if word < WORD else 0
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def table(clock_hz: int = PAL_HZ) -> list[int]:
|
|
21
|
+
"""``F(k)`` for every note whose word fits, from C0."""
|
|
22
|
+
out = []
|
|
23
|
+
while (word := frequency(len(out), clock_hz)) > 0:
|
|
24
|
+
out.append(word)
|
|
25
|
+
return out
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: unitracker-grammar
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: The canonical unitracker document as a Lark grammar, with its note table and modulator expression language
|
|
5
|
+
Author: Josh Bailey
|
|
6
|
+
License: Apache License
|
|
7
|
+
Version 2.0, January 2004
|
|
8
|
+
http://www.apache.org/licenses/
|
|
9
|
+
|
|
10
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
11
|
+
|
|
12
|
+
1. Definitions.
|
|
13
|
+
|
|
14
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
15
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
16
|
+
|
|
17
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
18
|
+
the copyright owner that is granting the License.
|
|
19
|
+
|
|
20
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
21
|
+
other entities that control, are controlled by, or are under common
|
|
22
|
+
control with that entity. For the purposes of this definition,
|
|
23
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
24
|
+
direction or management of such entity, whether by contract or
|
|
25
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
26
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
27
|
+
|
|
28
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
29
|
+
exercising permissions granted by this License.
|
|
30
|
+
|
|
31
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
32
|
+
including but not limited to software source code, documentation
|
|
33
|
+
source, and configuration files.
|
|
34
|
+
|
|
35
|
+
"Object" form shall mean any form resulting from mechanical
|
|
36
|
+
transformation or translation of a Source form, including but
|
|
37
|
+
not limited to compiled object code, generated documentation,
|
|
38
|
+
and conversions to other media types.
|
|
39
|
+
|
|
40
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
41
|
+
Object form, made available under the License, as indicated by a
|
|
42
|
+
copyright notice that is included in or attached to the work
|
|
43
|
+
(an example is provided in the Appendix below).
|
|
44
|
+
|
|
45
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
46
|
+
form, that is based on (or derived from) the Work and for which the
|
|
47
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
48
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
49
|
+
of this License, Derivative Works shall not include works that remain
|
|
50
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
51
|
+
the Work and Derivative Works thereof.
|
|
52
|
+
|
|
53
|
+
"Contribution" shall mean any work of authorship, including
|
|
54
|
+
the original version of the Work and any modifications or additions
|
|
55
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
56
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
57
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
58
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
59
|
+
means any form of electronic, verbal, or written communication sent
|
|
60
|
+
to the Licensor or its representatives, including but not limited to
|
|
61
|
+
communication on electronic mailing lists, source code control systems,
|
|
62
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
63
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
64
|
+
excluding communication that is conspicuously marked or otherwise
|
|
65
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
66
|
+
|
|
67
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
68
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
69
|
+
subsequently incorporated within the Work.
|
|
70
|
+
|
|
71
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
72
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
73
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
74
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
75
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
76
|
+
Work and such Derivative Works in Source or Object form.
|
|
77
|
+
|
|
78
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
79
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
80
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
81
|
+
(except as stated in this section) patent license to make, have made,
|
|
82
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
83
|
+
where such license applies only to those patent claims licensable
|
|
84
|
+
by such Contributor that are necessarily infringed by their
|
|
85
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
86
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
87
|
+
institute patent litigation against any entity (including a
|
|
88
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
89
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
90
|
+
or contributory patent infringement, then any patent licenses
|
|
91
|
+
granted to You under this License for that Work shall terminate
|
|
92
|
+
as of the date such litigation is filed.
|
|
93
|
+
|
|
94
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
95
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
96
|
+
modifications, and in Source or Object form, provided that You
|
|
97
|
+
meet the following conditions:
|
|
98
|
+
|
|
99
|
+
(a) You must give any other recipients of the Work or
|
|
100
|
+
Derivative Works a copy of this License; and
|
|
101
|
+
|
|
102
|
+
(b) You must cause any modified files to carry prominent notices
|
|
103
|
+
stating that You changed the files; and
|
|
104
|
+
|
|
105
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
106
|
+
that You distribute, all copyright, patent, trademark, and
|
|
107
|
+
attribution notices from the Source form of the Work,
|
|
108
|
+
excluding those notices that do not pertain to any part of
|
|
109
|
+
the Derivative Works; and
|
|
110
|
+
|
|
111
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
112
|
+
distribution, then any Derivative Works that You distribute must
|
|
113
|
+
include a readable copy of the attribution notices contained
|
|
114
|
+
within such NOTICE file, excluding those notices that do not
|
|
115
|
+
pertain to any part of the Derivative Works, in at least one
|
|
116
|
+
of the following places: within a NOTICE text file distributed
|
|
117
|
+
as part of the Derivative Works; within the Source form or
|
|
118
|
+
documentation, if provided along with the Derivative Works; or,
|
|
119
|
+
within a display generated by the Derivative Works, if and
|
|
120
|
+
wherever such third-party notices normally appear. The contents
|
|
121
|
+
of the NOTICE file are for informational purposes only and
|
|
122
|
+
do not modify the License. You may add Your own attribution
|
|
123
|
+
notices within Derivative Works that You distribute, alongside
|
|
124
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
125
|
+
that such additional attribution notices cannot be construed
|
|
126
|
+
as modifying the License.
|
|
127
|
+
|
|
128
|
+
You may add Your own copyright statement to Your modifications and
|
|
129
|
+
may provide additional or different license terms and conditions
|
|
130
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
131
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
132
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
133
|
+
the conditions stated in this License.
|
|
134
|
+
|
|
135
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
136
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
137
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
138
|
+
this License, without any additional terms or conditions.
|
|
139
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
140
|
+
the terms of any separate license agreement you may have executed
|
|
141
|
+
with Licensor regarding such Contributions.
|
|
142
|
+
|
|
143
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
144
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
145
|
+
except as required for reasonable and customary use in describing the
|
|
146
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
147
|
+
|
|
148
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
149
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
150
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
151
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
152
|
+
implied, including, without limitation, any warranties or conditions
|
|
153
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
154
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
155
|
+
appropriateness of using or redistributing the Work and assume any
|
|
156
|
+
risks associated with Your exercise of permissions under this License.
|
|
157
|
+
|
|
158
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
159
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
160
|
+
unless required by applicable law (such as deliberate and grossly
|
|
161
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
162
|
+
liable to You for damages, including any direct, indirect, special,
|
|
163
|
+
incidental, or consequential damages of any character arising as a
|
|
164
|
+
result of this License or out of the use or inability to use the
|
|
165
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
166
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
167
|
+
other commercial damages or losses), even if such Contributor
|
|
168
|
+
has been advised of the possibility of such damages.
|
|
169
|
+
|
|
170
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
171
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
172
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
173
|
+
or other liability obligations and/or rights consistent with this
|
|
174
|
+
License. However, in accepting such obligations, You may act only
|
|
175
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
176
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
177
|
+
defend, and hold each Contributor harmless for any liability
|
|
178
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
179
|
+
of your accepting any such warranty or additional liability.
|
|
180
|
+
|
|
181
|
+
END OF TERMS AND CONDITIONS
|
|
182
|
+
|
|
183
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
184
|
+
|
|
185
|
+
To apply the Apache License to your work, attach the following
|
|
186
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
187
|
+
replaced with your own identifying information. (Don't include
|
|
188
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
189
|
+
comment syntax for the file format. We also recommend that a
|
|
190
|
+
file or class name and description of purpose be included on the
|
|
191
|
+
same "printed page" as the copyright notice for easier
|
|
192
|
+
identification within third-party archives.
|
|
193
|
+
|
|
194
|
+
Copyright [yyyy] [name of copyright owner]
|
|
195
|
+
|
|
196
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
197
|
+
you may not use this file except in compliance with the License.
|
|
198
|
+
You may obtain a copy of the License at
|
|
199
|
+
|
|
200
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
201
|
+
|
|
202
|
+
Unless required by applicable law or agreed to in writing, software
|
|
203
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
204
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
205
|
+
See the License for the specific language governing permissions and
|
|
206
|
+
limitations under the License.
|
|
207
|
+
|
|
208
|
+
Project-URL: Homepage, https://github.com/anarkiwi/unitracker-grammar
|
|
209
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
210
|
+
Classifier: Programming Language :: Python :: 3
|
|
211
|
+
Requires-Python: >=3.12
|
|
212
|
+
Description-Content-Type: text/markdown
|
|
213
|
+
License-File: LICENSE
|
|
214
|
+
Requires-Dist: lark>=1.2
|
|
215
|
+
Provides-Extra: dev
|
|
216
|
+
Requires-Dist: black>=24; extra == "dev"
|
|
217
|
+
Requires-Dist: pylint>=3; extra == "dev"
|
|
218
|
+
Requires-Dist: pytest>=7; extra == "dev"
|
|
219
|
+
Requires-Dist: pytest-cov>=4; extra == "dev"
|
|
220
|
+
Dynamic: license-file
|
|
221
|
+
|
|
222
|
+
# unitracker-grammar
|
|
223
|
+
|
|
224
|
+
The canonical [unitracker](https://github.com/anarkiwi/unitracker) document as a
|
|
225
|
+
[Lark](https://github.com/lark-parser/lark) grammar, with an LALR parser for it and the note
|
|
226
|
+
table its expressions read as `F(k)`, and the modulator expression language: checked, printed
|
|
227
|
+
in its one text and compiled to Python.
|
|
228
|
+
|
|
229
|
+
A document names no player. It holds everything it plays: instruments, programs, expressions,
|
|
230
|
+
phrases and the tables its expressions index. Its only constants are the note table at its clock
|
|
231
|
+
and the header defaults (PAL clock, 3 voices, tempo 6).
|
|
232
|
+
|
|
233
|
+
## Install
|
|
234
|
+
|
|
235
|
+
```sh
|
|
236
|
+
pip install "unitracker-grammar @ git+https://github.com/anarkiwi/unitracker-grammar"
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
## Use
|
|
240
|
+
|
|
241
|
+
```python
|
|
242
|
+
from unitracker_grammar import parse, CanonicalError, frequency, table
|
|
243
|
+
tree = parse(text) # a lark.Tree, or CanonicalError naming the line and column
|
|
244
|
+
frequency(57) # F(57): A4 at the PAL clock
|
|
245
|
+
table(clock_hz=1022727) # F(k) for every note whose word fits, from C0, at NTSC
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
`parser()` is the cached `lark.Lark` parser and `GRAMMAR` the grammar file resource.
|
|
249
|
+
|
|
250
|
+
## Expressions
|
|
251
|
+
|
|
252
|
+
`unitracker_grammar.expr` owns the modulator expression language. An expression is a stdlib
|
|
253
|
+
`ast` node, read from a text by `tree` or from a parse tree's `expr` and `fexpr` rules by the
|
|
254
|
+
`Nodes` transformer.
|
|
255
|
+
|
|
256
|
+
```python
|
|
257
|
+
from unitracker_grammar import expr, frequency
|
|
258
|
+
expr.canonical("1024 + 16*min(3, φ)") # '16*min(3, φ) + 1024', its one text
|
|
259
|
+
fn = expr.compile_expr("v + W[φ]", {"_F": frequency, "_T": {"W": expr.indexed([1, 2])}})
|
|
260
|
+
fn(10, 1, 48) # (v, φ, N) -> 12
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
`source` is the Python source of an expression (`ExpressionError` outside the grammar),
|
|
264
|
+
`printed` the one text of a node and `written` an integer literal as an int. `//` and `%` raise
|
|
265
|
+
`ZeroDivisionError` on a divisor of 0; with `zero=True` they are 0.
|
|
266
|
+
|
|
267
|
+
## Grammar
|
|
268
|
+
|
|
269
|
+
[`src/unitracker_grammar/canonical.lark`](src/unitracker_grammar/canonical.lark); the document
|
|
270
|
+
format and the meaning of each construct are described in unitracker's
|
|
271
|
+
[docs/format](https://github.com/anarkiwi/unitracker/blob/main/docs/format/document.md).
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
unitracker_grammar/__init__.py,sha256=MBnQeRCM5uvzkKB6KgU18QdxnhXih5sCeNUG0t0C2Io,370
|
|
2
|
+
unitracker_grammar/canonical.lark,sha256=1gJgRhXB8qqk4qzs8a8WKDut6DHYDB7TSHzmpTXHEl4,6947
|
|
3
|
+
unitracker_grammar/canonical.py,sha256=EEvyyA6d2-HhNFN8K0zVjGBPk4xyc8qiKtq-QKIc_xY,829
|
|
4
|
+
unitracker_grammar/expr.py,sha256=iZQMttmy2zS-g60gqES6diDLW_m_EMnPuWyNwL6Dej0,11541
|
|
5
|
+
unitracker_grammar/notes.py,sha256=utJEOzxWHr5xUOYBmjXloCgqnYCocr5kuheBPNc4iQE,777
|
|
6
|
+
unitracker_grammar-0.3.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
|
7
|
+
unitracker_grammar-0.3.0.dist-info/METADATA,sha256=uf6xCZhyhpJvUFPG-qBWrsAeLHS5NkN92hvRaH5WCDY,15794
|
|
8
|
+
unitracker_grammar-0.3.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
9
|
+
unitracker_grammar-0.3.0.dist-info/top_level.txt,sha256=c4ag8vMWGjSRQ-YkRoGfcKkFJshnXm0pXm4fgTZ1wRo,19
|
|
10
|
+
unitracker_grammar-0.3.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
unitracker_grammar
|