tsqx 0.1.0__tar.gz

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.
@@ -0,0 +1,65 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: ["*"]
6
+ pull_request:
7
+ branches: ["*"]
8
+ workflow_dispatch:
9
+
10
+ jobs:
11
+ types:
12
+ name: "Typecheck"
13
+ runs-on: ubuntu-latest
14
+
15
+ steps:
16
+ - uses: actions/checkout@v4
17
+ with:
18
+ submodules: recursive
19
+ - name: Setup Python
20
+ uses: actions/setup-python@v5
21
+ with:
22
+ python-version: "3.13"
23
+ - name: Install Hatch
24
+ run: pipx install hatch
25
+ - uses: actions/cache@v4
26
+ with:
27
+ path: ~/.cache/hatch
28
+ key: ${{ runner.os }}-hatch
29
+ restore-keys: ${{ runner.os }}-hatch
30
+ - name: Install dependencies
31
+ run: |
32
+ hatch env create dev
33
+ - name: Run pyright
34
+ run: |
35
+ hatch run dev:pyright
36
+ - name: Ensure Hatch environment is in PATH
37
+ run: echo "$HOME/.cache/hatch/venv/bin" >> $GITHUB_PATH
38
+
39
+ style:
40
+ name: "Style check"
41
+ runs-on: ubuntu-latest
42
+ steps:
43
+ - uses: actions/checkout@v4
44
+ with:
45
+ submodules: recursive
46
+ - name: Setup Python
47
+ uses: actions/setup-python@v5
48
+ with:
49
+ python-version: "3.13"
50
+ - name: Install Hatch
51
+ run: pipx install hatch
52
+ - uses: actions/cache@v4
53
+ with:
54
+ path: ~/.cache/hatch
55
+ key: ${{ runner.os }}-hatch
56
+ restore-keys: ${{ runner.os }}-hatch
57
+ - name: Install dependencies
58
+ run: hatch env create dev
59
+ - name: Run ruff
60
+ run: |
61
+ hatch run dev:ruff check --output-format=github $(git ls-files '*.py')
62
+ hatch run dev:ruff format --diff $(git ls-files '*.py')
63
+ - name: Run spell-check
64
+ run: |
65
+ hatch run dev:codespell $(git ls-files)
@@ -0,0 +1,16 @@
1
+ name: "Conventional commits"
2
+
3
+ on:
4
+ pull_request_target:
5
+ types:
6
+ - opened
7
+ - edited
8
+ - synchronize
9
+ - reopened
10
+
11
+ permissions:
12
+ pull-requests: write
13
+
14
+ jobs:
15
+ main:
16
+ uses: vEnhance/dotfiles/.github/workflows/conv-commit.yml@main
@@ -0,0 +1,35 @@
1
+ name: PyPI Release
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+ workflow_dispatch:
7
+
8
+ jobs:
9
+ pypi-publish:
10
+ name: Upload release to PyPI
11
+ runs-on: ubuntu-latest
12
+ environment:
13
+ name: pypi
14
+ url: https://pypi.org/p/tsqx
15
+ permissions:
16
+ id-token: write
17
+ steps:
18
+ - uses: actions/checkout@v4
19
+ with:
20
+ submodules: recursive
21
+ - name: Setup Python
22
+ uses: actions/setup-python@v5
23
+ with:
24
+ python-version: "3.13"
25
+ - name: Install Hatch
26
+ run: pipx install hatch
27
+ - uses: actions/cache@v4
28
+ with:
29
+ path: ~/.cache/hatch
30
+ key: ${{ runner.os }}-hatch
31
+ restore-keys: ${{ runner.os }}-hatch
32
+ - name: Build package
33
+ run: hatch build
34
+ - name: Publish package distributions to PyPI
35
+ uses: pypa/gh-action-pypi-publish@release/v1
tsqx-0.1.0/.gitignore ADDED
@@ -0,0 +1 @@
1
+ dist/
tsqx-0.1.0/LICENSE.md ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021 Carl Joshua Quines and Evan Chen
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
tsqx-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,64 @@
1
+ Metadata-Version: 2.4
2
+ Name: tsqx
3
+ Version: 0.1.0
4
+ Summary: Asymptote pre-processor for Euclidean geometry diagrams
5
+ Project-URL: repository, https://github.com/vEnhance/tsqx/
6
+ Author-email: Evan Chen <evan@evanchen.cc>, CJ Quines <cj@cjquines.com>
7
+ License: MIT
8
+ License-File: LICENSE.md
9
+ Requires-Python: <4.0,>=3.10
10
+ Description-Content-Type: text/markdown
11
+
12
+ # TSQX
13
+
14
+ [Asymptote](https://asymptote.sourceforge.io/) preprocessor
15
+ for Euclidean geometry diagrams
16
+ descended from the older [TSQ](https://github.com/vEnhance/dotfiles/blob/main/py-scripts/tsq.py).
17
+
18
+ ## Installation
19
+
20
+ `pip install tsqx`
21
+
22
+ ## Documentation
23
+
24
+ See [wiki](https://github.com/cjquines/tsqx/wiki/Documentation).
25
+
26
+ ## Example code
27
+
28
+ ```
29
+ ~triangle A B C
30
+ D ;= foot A B C
31
+ E := midpoint A--B
32
+ F' N = (rotate -30 E)(extension A (foot A B C) C E)
33
+
34
+ circumcircle A B C / 0.2 lightgray /
35
+ A--B--C--cycle
36
+ A--D
37
+ B--F' / dashed blue
38
+ ```
39
+
40
+ Generated code:
41
+
42
+ ```
43
+ pair A = dir(110);
44
+ pair B = dir(210);
45
+ pair C = dir(330);
46
+ pair D = foot(A, B, C);
47
+ pair E = midpoint(A--B);
48
+ pair F_prime = rotate(-30, E)*extension(A, foot(A, B, C), C, E);
49
+
50
+ filldraw(circumcircle(A, B, C), opacity(0.2)+lightgray, defaultpen);
51
+ draw(A--B--C--cycle);
52
+ draw(A--D);
53
+ draw(B--F_prime, dashed+blue);
54
+
55
+ dot("$A$", A, dir(A));
56
+ dot("$B$", B, dir(B));
57
+ dot("$C$", C, dir(C));
58
+ label("$D$", D, dir(D));
59
+ dot("$F'$", F_prime, plain.N);
60
+ ```
61
+
62
+ Which makes the diagram:
63
+
64
+ ![Diagram](sample.png)
tsqx-0.1.0/README.md ADDED
@@ -0,0 +1,53 @@
1
+ # TSQX
2
+
3
+ [Asymptote](https://asymptote.sourceforge.io/) preprocessor
4
+ for Euclidean geometry diagrams
5
+ descended from the older [TSQ](https://github.com/vEnhance/dotfiles/blob/main/py-scripts/tsq.py).
6
+
7
+ ## Installation
8
+
9
+ `pip install tsqx`
10
+
11
+ ## Documentation
12
+
13
+ See [wiki](https://github.com/cjquines/tsqx/wiki/Documentation).
14
+
15
+ ## Example code
16
+
17
+ ```
18
+ ~triangle A B C
19
+ D ;= foot A B C
20
+ E := midpoint A--B
21
+ F' N = (rotate -30 E)(extension A (foot A B C) C E)
22
+
23
+ circumcircle A B C / 0.2 lightgray /
24
+ A--B--C--cycle
25
+ A--D
26
+ B--F' / dashed blue
27
+ ```
28
+
29
+ Generated code:
30
+
31
+ ```
32
+ pair A = dir(110);
33
+ pair B = dir(210);
34
+ pair C = dir(330);
35
+ pair D = foot(A, B, C);
36
+ pair E = midpoint(A--B);
37
+ pair F_prime = rotate(-30, E)*extension(A, foot(A, B, C), C, E);
38
+
39
+ filldraw(circumcircle(A, B, C), opacity(0.2)+lightgray, defaultpen);
40
+ draw(A--B--C--cycle);
41
+ draw(A--D);
42
+ draw(B--F_prime, dashed+blue);
43
+
44
+ dot("$A$", A, dir(A));
45
+ dot("$B$", B, dir(B));
46
+ dot("$C$", C, dir(C));
47
+ label("$D$", D, dir(D));
48
+ dot("$F'$", F_prime, plain.N);
49
+ ```
50
+
51
+ Which makes the diagram:
52
+
53
+ ![Diagram](sample.png)
tsqx-0.1.0/audit.sh ADDED
@@ -0,0 +1,6 @@
1
+ #!/bin/bash
2
+ set -euxo pipefail
3
+
4
+ hatch fmt --check
5
+ hatch run dev:codespell .
6
+ hatch run dev:pyright .
@@ -0,0 +1,112 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "tsqx"
7
+ description = "Asymptote pre-processor for Euclidean geometry diagrams"
8
+ authors = [
9
+ { name = "Evan Chen", email = "evan@evanchen.cc" },
10
+ { name = "CJ Quines", email = "cj@cjquines.com" }
11
+ ]
12
+ license = { text = "MIT" }
13
+ readme = "README.md"
14
+ urls = { repository = "https://github.com/vEnhance/tsqx/" }
15
+ requires-python = ">=3.10,<4.0"
16
+ dependencies = [
17
+ ]
18
+ dynamic = ["version"]
19
+
20
+ [tool.hatch.version]
21
+ path = "tsqx/__about__.py"
22
+
23
+ [tool.hatch.build.targets.wheel]
24
+ packages = ["tsqx"]
25
+
26
+ [tool.hatch.envs.default.scripts]
27
+ tsqx = "python -m tsqx"
28
+
29
+ [project.scripts]
30
+ tsqx = "tsqx.__main__:main"
31
+
32
+ [tool.hatch.envs.dev]
33
+ dependencies = [
34
+ "codespell>=2.4.1",
35
+ "pyright>=1.1.394",
36
+ "toml>=0.10.2",
37
+ "ruff>=0.9.7"
38
+ ]
39
+
40
+ [tool.pyright]
41
+ enableTypeIgnoreComments = true
42
+ exclude = ["**/node_modules", "**/typings", "**/__pycache__", ".git", "venv", ".venv", "**/migrations", "**/tests.py"]
43
+ pythonPlatform = "Linux"
44
+ pythonVersion = "3.10"
45
+ typeCheckingMode = "basic"
46
+ useLibraryCodeForTypes = true
47
+
48
+ reportAssertAlwaysTrue = "error"
49
+ reportCallInDefaultInitializer = "warning"
50
+ reportConstantRedefinition = "none"
51
+ reportDuplicateImport = "error"
52
+ reportFunctionMemberAccess = "none"
53
+ reportGeneralTypeIssues = "error"
54
+ reportImplicitStringConcatenation = "none"
55
+ reportImportCycles = "none"
56
+ reportIncompatibleMethodOverride = "none"
57
+ reportIncompatibleVariableOverride = "none"
58
+ reportIncompleteStub = "none"
59
+ reportInvalidStringEscapeSequence = "error"
60
+ reportInvalidTypeVarUse = "warning"
61
+ reportMissingImports = "error"
62
+ reportMissingModuleSource = "warning"
63
+ reportMissingTypeArgument = false
64
+ reportMissingTypeStubs = false
65
+ reportOptionalCall = "error"
66
+ reportOptionalContextManager = "error"
67
+ reportOptionalIterable = "error"
68
+ reportOptionalMemberAccess = "error"
69
+ reportOptionalOperand = "error"
70
+ reportOptionalSubscript = "error"
71
+ reportOverlappingOverload = "error"
72
+ reportPrivateUsage = "error"
73
+ reportPropertyTypeMismatch = "error"
74
+ reportSelfClsParameterName = "warning"
75
+ reportTypedDictNotRequiredAccess = "warning"
76
+ reportUnboundVariable = "error"
77
+ reportUndefinedVariable = "error"
78
+ reportUnitializedInstanceVariable = "warning"
79
+ reportUnknownArgumentType = "none"
80
+ reportUnknownMemberType = "none"
81
+ reportUnknownParameterType = "warning" # TODO we'll fix this one day
82
+ reportUnknownVariableType = "none"
83
+ reportUnnecessaryCast = "error"
84
+ reportUnnecessaryComparison = "error"
85
+ reportUnnecessaryIsInstance = "error"
86
+ reportUnsupportDunderAll = "warning"
87
+ reportUntypedBaseClass = "none"
88
+ reportUntypedClassDecorator = "none"
89
+ reportUntypedFunctionDecorator = "warning"
90
+ reportUntypedNamedTuple = "error"
91
+ reportUnusedCallResult = "none"
92
+ reportUnusedClass = "error"
93
+ reportUnusedCoroutine = "error"
94
+ reportUnusedFunction = "error"
95
+ reportUnusedImport = "none"
96
+ reportUnusedNamedTuple = "error"
97
+ reportUnusedVariable = "warning"
98
+ reportWildcardImportFromLibrary = "warning"
99
+ strictDictionaryInference = false
100
+ strictListInference = false
101
+ strictParameterNoneValue = false
102
+ strictSetInference = false
103
+
104
+ [tool.ruff]
105
+ line-length = 88
106
+
107
+ [tool.ruff.lint]
108
+ select = ["E4", "E7", "E9", "F", "I"]
109
+
110
+ [tool.codespell]
111
+ count = ""
112
+ quiet-level = 3
tsqx-0.1.0/sample.png ADDED
Binary file
tsqx-0.1.0/sample.txt ADDED
@@ -0,0 +1,9 @@
1
+ ~triangle A B C
2
+ D ;= foot A B C
3
+ E := midpoint A--B
4
+ F' N = (rotate -30 E)(extension A (foot A B C) C E)
5
+
6
+ circumcircle A B C / 0.2 lightgray /
7
+ A--B--C--cycle
8
+ A--D
9
+ B--F' / dashed blue
tsqx-0.1.0/tests.txt ADDED
@@ -0,0 +1,44 @@
1
+ ~triangle A B C
2
+
3
+ P = (1, 2)
4
+ P = foot A B C
5
+ P = foot(A, B, C)
6
+ P = dir(180)
7
+
8
+ # comment
9
+ P := dir(1, 2) # comment
10
+
11
+ P_1 ;= foot A B C
12
+ P_2 := foot A B C
13
+ P_3 dl= foot A B C
14
+ P_4 d= foot A B C
15
+ P_5 l= foot A B C
16
+
17
+ P_6 S = (1, 2)
18
+ P_7 NE = (1, 2)
19
+ P_8 4E2N = (1, 2)
20
+ P_9 1N1SE1N = (1, 2)
21
+
22
+ P := midpoint A--B
23
+ P := midpoint (foot A B C)--B
24
+ P := midpoint B--(foot A B C)
25
+ P := midpoint (foot A B C)--(foot B C A)
26
+
27
+ P := (rotate -30 E)(D)
28
+ P := (rotate -30 E)(foot A B C)
29
+ P := (shift (0, 1))(rotate -30 E)(foot A B C)
30
+ P := (rotate -30 E)(extension A (foot A B C) C E)
31
+
32
+ A--B--C--cycle
33
+ (foot A B C)--D
34
+ D--(foot A B C)
35
+ (foot A B C)--(foot B C A)
36
+ circumcircle A B C
37
+ circumcircle A (extension A B C D) E
38
+
39
+ A--B / blue
40
+ A--B / dashed
41
+ A--B / dashed blue
42
+ A--B--C--cycle / lightgray / blue
43
+ A--B--C--cycle / 0.2 lightgray / dashed blue
44
+ A--B--C--cycle / 0.2 lightgray /
@@ -0,0 +1,3 @@
1
+ __version__ = "0.1.0"
2
+ __author__ = "CJ Quines and Evan Chen"
3
+ __license__ = "MIT"
File without changes
@@ -0,0 +1,452 @@
1
+ import re
2
+ import sys
3
+ from io import TextIOWrapper
4
+ from typing import Any, Generator, TextIO, TypedDict
5
+
6
+
7
+ def generate_points(kind: str, n: int) -> list[str]:
8
+ if kind == "triangle":
9
+ return ["dir(110)", "dir(210)", "dir(330)"]
10
+ elif kind == "regular":
11
+ return [f"dir({(90 + i * 360 / n) % 360})" for i in range(n)]
12
+ raise SyntaxError("Special command not recognized")
13
+
14
+
15
+ T_TOKEN = str | list[str] | list["T_TOKEN"]
16
+
17
+
18
+ class T_OPSTRUCT(TypedDict):
19
+ op: "Op"
20
+ comment: str
21
+
22
+
23
+ GENERIC_PREAMBLE = r"""
24
+ usepackage("amsmath");
25
+ usepackage("amssymb");
26
+ settings.tex="pdflatex";
27
+ settings.outformat="pdf";
28
+ // Replacement for olympiad+cse5 which is not standard
29
+ import geometry;
30
+ // recalibrate fill and filldraw for conics
31
+ void filldraw(picture pic = currentpicture, conic g, pen fillpen=defaultpen, pen drawpen=defaultpen)
32
+ { filldraw(pic, (path) g, fillpen, drawpen); }
33
+ void fill(picture pic = currentpicture, conic g, pen p=defaultpen)
34
+ { filldraw(pic, (path) g, p); }
35
+ // some geometry
36
+ pair foot(pair P, pair A, pair B) { return foot(triangle(A,B,P).VC); }
37
+ pair orthocenter(pair A, pair B, pair C) { return orthocentercenter(A,B,C); }
38
+ pair centroid(pair A, pair B, pair C) { return (A+B+C)/3; }
39
+ // cse5 abbreviations
40
+ path CP(pair P, pair A) { return circle(P, abs(A-P)); }
41
+ path CR(pair P, real r) { return circle(P, r); }
42
+ pair IP(path p, path q) { return intersectionpoints(p,q)[0]; }
43
+ pair OP(path p, path q) { return intersectionpoints(p,q)[1]; }
44
+ path Line(pair A, pair B, real a=0.6, real b=a) { return (a*(A-B)+A)--(b*(B-A)+B); }
45
+ size(%s);
46
+ """.strip()
47
+
48
+ ARITHMETIC_OPERATORS = {"plus": "+", "minus": "-", "mult": "*", "divide": "/"}
49
+
50
+
51
+ class Op:
52
+ exp: T_TOKEN
53
+
54
+ def _join_exp(self, exp: T_TOKEN, join_str: str) -> str:
55
+ return join_str.join(self._emit_exp(e) for e in exp)
56
+
57
+ def _emit_exp(self, exp: T_TOKEN) -> str:
58
+ if not isinstance(exp, list):
59
+ return exp
60
+ if "," in exp:
61
+ return f"({self._join_exp(exp, ' ')})"
62
+ head, *tail = exp
63
+ if not tail:
64
+ return self._emit_exp(head) if isinstance(head, list) else head
65
+ elif tail[0] in ["--", "..", "^^"]:
66
+ return self._join_exp(exp, ", ")
67
+ elif (binop := ARITHMETIC_OPERATORS.get(str(head))) is not None:
68
+ return "(" + self._join_exp(tail, binop) + ")"
69
+ else:
70
+ return f"{head}({self._join_exp(tail, ', ')})"
71
+
72
+ def emit_exp(self) -> str:
73
+ res = self._join_exp(self.exp, "*")
74
+ for j in ["--", "..", "^^"]:
75
+ res = res.replace(f", {j}, ", j)
76
+ return res
77
+
78
+ def emit(self) -> str:
79
+ raise Exception("Operation not recognized")
80
+
81
+ def post_emit(self):
82
+ return None
83
+
84
+
85
+ class Blank(Op):
86
+ def emit(self):
87
+ return ""
88
+
89
+
90
+ class DirectCommand(Op):
91
+ def __init__(self, exp: str):
92
+ self.exp = exp
93
+
94
+ def emit(self):
95
+ return self.exp
96
+
97
+ def post_emit(self):
98
+ return None
99
+
100
+
101
+ class Point(Op):
102
+ def __init__(
103
+ self,
104
+ name: str,
105
+ exp: T_TOKEN,
106
+ dot: bool = True,
107
+ label: bool = True,
108
+ direction: str = "",
109
+ ):
110
+ self.name = name
111
+ self.exp = exp
112
+ self.dot = dot
113
+ self.label = name if label is True else None
114
+ if self.label:
115
+ self.label = self.label.replace("_prime", "'")
116
+ self.label = self.label.replace("_asterisk", r"^{\ast}")
117
+ self.direction = direction or f"dir({name})"
118
+
119
+ def emit(self) -> str:
120
+ return f"pair {self.name} = {self.emit_exp()};"
121
+
122
+ def post_emit(self):
123
+ args = [self.name]
124
+ if self.label:
125
+ args = [f'"${self.label}$"', *args, self.direction]
126
+ if self.dot:
127
+ return f"dot({', '.join(args)});"
128
+ if len(args) > 1:
129
+ return f"label({', '.join(args)});"
130
+ return ""
131
+
132
+
133
+ class Draw(Op):
134
+ def __init__(
135
+ self,
136
+ exp: T_TOKEN,
137
+ fill: str | None = None,
138
+ outline: str | None = None,
139
+ ):
140
+ self.exp = exp
141
+ self.fill = fill
142
+ self.outline = outline
143
+
144
+ def emit(self):
145
+ exp = self.emit_exp()
146
+ if self.fill:
147
+ outline = self.outline or "defaultpen"
148
+ return f"filldraw({exp}, {self.fill}, {outline});"
149
+ elif self.outline:
150
+ return f"draw({exp}, {self.outline});"
151
+ else:
152
+ return f"draw({exp});"
153
+
154
+
155
+ class Parser:
156
+ def __init__(self, soft_label: str | None = None, **_: Any):
157
+ self.soft_label = soft_label
158
+ self.alias_map = {"": "dl", ":": "", ".": "d", ";": "l"}
159
+ if self.soft_label:
160
+ self.alias_map |= {"": "l", ";": "dl"}
161
+ self.aliases = self.alias_map.keys() | self.alias_map.values()
162
+
163
+ def tokenize(self, line: str) -> list[T_TOKEN]:
164
+ line = line.strip() + " "
165
+ for old, new in [
166
+ # ~ and = are separate tokens
167
+ ("~", " ~ "),
168
+ ("=", " = "),
169
+ # for tsqx syntax processing
170
+ ("(", "( "),
171
+ (")", " ) "),
172
+ (",", " , "),
173
+ # spline joiners
174
+ ("--", " -- "),
175
+ ("..", " .. "),
176
+ ("^^", " ^^ "),
177
+ # no spaces around asymptote arithmetic
178
+ (" +", "+"),
179
+ ("+ ", "+"),
180
+ ("- ", "-"),
181
+ (" *", "*"),
182
+ ("* ", "*"),
183
+ # but slashes in draw ops should remain tokens
184
+ (" / ", " / "),
185
+ (" /", "/"),
186
+ ("/ ", "/"),
187
+ # ' not allowed in variable names
188
+ ("'", "_prime"),
189
+ ("&", "_asterisk"),
190
+ ]:
191
+ line = line.replace(old, new)
192
+ return list(filter(None, line.split()))
193
+
194
+ def parse_subexp(
195
+ self,
196
+ tokens: list[T_TOKEN],
197
+ idx: int,
198
+ func_mode=False,
199
+ ) -> tuple[T_TOKEN, int]:
200
+ token = tokens[idx]
201
+ if token[-1] == "(":
202
+ is_func = len(token) > 1
203
+ res: list[T_TOKEN] = []
204
+ idx += 1
205
+ if is_func:
206
+ res.append(token[:-1])
207
+ while tokens[idx] != ")":
208
+ exp, idx = self.parse_subexp(tokens, idx, is_func)
209
+ res.append(exp)
210
+ return res, idx + 1
211
+ if token == "," and func_mode:
212
+ return "", idx + 1
213
+ return token, idx + 1
214
+
215
+ def parse_exp(self, tokens: list[T_TOKEN]):
216
+ if tokens[0][-1] != "(" or tokens[-1] != ")":
217
+ tokens = ["(", *tokens, ")"]
218
+ res: list[T_TOKEN] = []
219
+ idx = 0
220
+ while idx != len(tokens):
221
+ try:
222
+ exp, idx = self.parse_subexp(tokens, idx)
223
+ res.append(list(filter(None, exp)))
224
+ except IndexError:
225
+ raise SyntaxError(f"Unexpected end of line: {tokens}")
226
+ return res
227
+
228
+ def parse_special(
229
+ self,
230
+ tokens: list[T_TOKEN],
231
+ comment: str,
232
+ ) -> Generator[T_OPSTRUCT, None, None]:
233
+ if not tokens:
234
+ raise SyntaxError("Can't parse special command")
235
+ head, *tail = tokens
236
+ if comment != "":
237
+ yield {"op": Blank(), "comment": comment}
238
+ if head in ["triangle", "regular"]:
239
+ for name, exp in zip(tail, generate_points(head, len(tail))):
240
+ assert isinstance(name, str)
241
+ yield {"op": Point(name, [exp]), "comment": f"via ~{head}"}
242
+ return
243
+ else:
244
+ raise SyntaxError(f"Special command {head} not recognized")
245
+
246
+ def parse_name(self, tokens: list[T_TOKEN]) -> tuple[str, dict[str, Any]]:
247
+ if not tokens:
248
+ raise SyntaxError("Can't parse point name")
249
+ name, *rest = tokens
250
+ assert isinstance(name, str)
251
+
252
+ if rest and rest[-1] in self.aliases:
253
+ *rest, opts = rest
254
+ assert isinstance(opts, str)
255
+ else:
256
+ opts = ""
257
+ opts = self.alias_map.get(opts, opts)
258
+ options = {
259
+ "dot": "d" in opts,
260
+ "label": "l" in opts,
261
+ "direction": f"dir({name})", # default direction
262
+ }
263
+
264
+ if rest:
265
+ dirs, *rest = rest
266
+ assert isinstance(dirs, str)
267
+ if m := re.fullmatch(r"([\d\.]+)R([\d\.]+)", dirs):
268
+ options["direction"] = f"{m.groups()[0]}*dir({m.groups()[1]})"
269
+ elif dir_pairs := re.findall(r"(\d+)([A-Z]+)", dirs):
270
+ options["direction"] = "+".join(f"{n}*plain.{w}" for n, w in dir_pairs)
271
+ elif dirs.isdigit():
272
+ options["direction"] = f"dir({dirs})"
273
+ elif re.fullmatch(r"N?S?E?W?", dirs):
274
+ options["direction"] = f"plain.{dirs}"
275
+ else:
276
+ rest.append(dirs)
277
+
278
+ if rest:
279
+ raise SyntaxError("Can't parse point name")
280
+ return name, options
281
+
282
+ def parse_draw(self, tokens: list[T_TOKEN]):
283
+ try:
284
+ idx = tokens.index("/")
285
+ except ValueError:
286
+ fill_: list[T_TOKEN] = []
287
+ outline_ = tokens
288
+ else:
289
+ fill_ = tokens[:idx]
290
+ outline_ = tokens[idx + 1 :]
291
+
292
+ assert all(isinstance(_, str) for _ in outline_)
293
+ outline: list[str] = [
294
+ str(_) for _ in outline_
295
+ ] # this is idiotic, what did i miss?
296
+
297
+ fill: list[str] = []
298
+ for pen in fill_:
299
+ assert isinstance(pen, str)
300
+ if re.fullmatch(r"\d*\.?\d*", pen):
301
+ fill.append(f"opacity({pen})")
302
+ else:
303
+ fill.append(pen)
304
+
305
+ return {"fill": "+".join(fill), "outline": "+".join(outline)}
306
+
307
+ def parse(self, line: str) -> Generator[T_OPSTRUCT, None, None]:
308
+ # escape sequence
309
+ if line.startswith("!"):
310
+ yield {
311
+ "op": DirectCommand(line[1:].strip()),
312
+ "comment": "",
313
+ }
314
+ return
315
+
316
+ if "#" in line:
317
+ line, comment = line.split("#", 1)
318
+ else:
319
+ comment = ""
320
+ tokens = self.tokenize(line)
321
+ if not tokens:
322
+ yield {"op": Blank(), "comment": comment}
323
+ return
324
+ # special
325
+ if tokens[0] == "~":
326
+ yield from self.parse_special(tokens[1:], comment)
327
+ return
328
+ # point
329
+ try:
330
+ idx = tokens.index("=")
331
+ name, options = self.parse_name(tokens[:idx])
332
+ exp = self.parse_exp(tokens[idx + 1 :])
333
+ yield {
334
+ "op": Point(name, exp, **options),
335
+ "comment": comment,
336
+ }
337
+ return
338
+ except ValueError:
339
+ pass
340
+ # draw with options
341
+ try:
342
+ idx = tokens.index("/")
343
+ exp = self.parse_exp(tokens[:idx])
344
+ options = self.parse_draw(tokens[idx + 1 :])
345
+ yield {"op": Draw(exp, **options), "comment": comment}
346
+ return
347
+ except ValueError:
348
+ pass
349
+ # draw without options
350
+ exp = self.parse_exp(tokens)
351
+ yield {"op": Draw(exp), "comment": comment}
352
+ return
353
+
354
+
355
+ class Emitter:
356
+ def __init__(
357
+ self,
358
+ lines: TextIOWrapper | TextIO,
359
+ **args: Any,
360
+ ):
361
+ self.lines = lines
362
+ self.preamble = args.get("preamble", False)
363
+ self.size = args.get("size", "8cm")
364
+ self.parser = Parser(**args)
365
+ self.terse = args.get("terse", False)
366
+
367
+ def emit(self):
368
+ if self.preamble:
369
+ print(GENERIC_PREAMBLE % self.size)
370
+
371
+ original_raw = ""
372
+ op_structs = []
373
+ for line in self.lines:
374
+ original_raw += line
375
+ for op_struct in self.parser.parse(line):
376
+ op_structs.append(op_struct)
377
+
378
+ for op_struct in op_structs:
379
+ print(
380
+ (
381
+ op_struct["op"].emit()
382
+ + (f" // {c}" if (c := op_struct["comment"].rstrip()) else "")
383
+ ).strip()
384
+ )
385
+ print()
386
+
387
+ for op_struct in op_structs:
388
+ if out := op_struct["op"].post_emit():
389
+ print(out)
390
+
391
+ if not self.terse:
392
+ print("")
393
+ print(r"/* --------------------------------+")
394
+ print(r"| TSQX: by CJ Quines and Evan Chen |")
395
+ print(r"| https://github.com/vEnhance/tsqx |")
396
+ print(r"+----------------------------------+")
397
+ print(original_raw.strip())
398
+ print("*/")
399
+
400
+
401
+ def main():
402
+ from argparse import ArgumentParser
403
+
404
+ argparser = ArgumentParser(description="Generate Asymptote code.")
405
+ argparser.add_argument(
406
+ "-p",
407
+ "--pre",
408
+ help="Adds a preamble.",
409
+ action="store_true",
410
+ dest="preamble",
411
+ default=False,
412
+ )
413
+ argparser.add_argument(
414
+ "fname",
415
+ help="Read from file rather than stdin.",
416
+ metavar="filename",
417
+ nargs="?",
418
+ default="",
419
+ )
420
+ argparser.add_argument(
421
+ "-s",
422
+ "--size",
423
+ help="Set image size in preamble.",
424
+ action="store",
425
+ dest="size",
426
+ default="8cm",
427
+ )
428
+ argparser.add_argument(
429
+ "-b",
430
+ "--soft-label",
431
+ help="Don't draw dots on points by default.",
432
+ action="store_true",
433
+ dest="soft_label",
434
+ default=False,
435
+ )
436
+ argparser.add_argument(
437
+ "-t",
438
+ "--terse",
439
+ help="Hide the advertisement and orig source",
440
+ action="store_true",
441
+ dest="terse",
442
+ default=False,
443
+ )
444
+
445
+ args = argparser.parse_args()
446
+ stream = open(args.fname, "r") if args.fname else sys.stdin
447
+ emitter = Emitter(stream, **vars(args))
448
+ emitter.emit()
449
+
450
+
451
+ if __name__ == "__main__":
452
+ main()