aboutsummaryrefslogtreecommitdiff
path: root/tools/sexpr.py
diff options
context:
space:
mode:
authorLouis <louis@dnge.de>2026-11-11 10:08:41 +0100
committerLouis <louis@dnge.de>2026-11-11 10:08:41 +0100
commit2e433fcd0d1afadd8ab786dd30d7d4546bdee43d (patch)
treef2a5603703d56b08c1eaa672eaf529ec4b2cc3fa /tools/sexpr.py
downloadhw-toolchain-2e433fcd0d1afadd8ab786dd30d7d4546bdee43d.tar.gz
hw-toolchain: placer, routers and KiCad helpers for agent-driven hardware work
Rust placer (simulated annealing) and negotiated-congestion router for 2-layer KiCad boards, pnr.sh to place, route, DRC-check and install candidates, Python KiCad helpers, repo conventions (AGENTS.md) and the tool documentation under knowledge/. Konnect (KiCad MCP, AGPL) as a submodule. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'tools/sexpr.py')
-rw-r--r--tools/sexpr.py61
1 files changed, 61 insertions, 0 deletions
diff --git a/tools/sexpr.py b/tools/sexpr.py
new file mode 100644
index 0000000..ded88cb
--- /dev/null
+++ b/tools/sexpr.py
@@ -0,0 +1,61 @@
+"""Minimal S-expression reader/writer for KiCad files."""
+import re
+
+class Q(str):
+ """Quoted string atom."""
+
+_tok = re.compile(r'\s*(?:(\()|(\))|"((?:[^"\\]|\\.)*)"|([^\s()"]+))', re.S)
+
+def parse(text):
+ stack = [[]]
+ pos = 0
+ n = len(text)
+ while pos < n:
+ m = _tok.match(text, pos)
+ if not m:
+ if text[pos:].strip() == "":
+ break
+ raise ValueError("bad sexpr at %d" % pos)
+ pos = m.end()
+ if m.group(1):
+ stack.append([])
+ elif m.group(2):
+ top = stack.pop()
+ stack[-1].append(top)
+ elif m.group(3) is not None:
+ stack[-1].append(Q(m.group(3).replace('\\"', '"').replace("\\\\", "\\")))
+ else:
+ stack[-1].append(m.group(4))
+ return stack[0][0]
+
+def _atom(a):
+ if isinstance(a, Q):
+ return '"' + a.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n") + '"'
+ if isinstance(a, float):
+ s = ("%.4f" % a).rstrip("0").rstrip(".")
+ return "0" if s in ("-0", "") else s
+ return str(a)
+
+def dump(e, ind=0):
+ if not isinstance(e, list):
+ return _atom(e)
+ if all(not isinstance(x, list) for x in e):
+ return "(" + " ".join(_atom(x) for x in e) + ")"
+ out = "(" + " ".join(_atom(x) for x in e if not isinstance(x, list))
+ # keep leading atoms on first line, children on new lines
+ parts = []
+ lead = True
+ for x in e:
+ if isinstance(x, list):
+ lead = False
+ parts.append("\n" + "\t" * (ind + 1) + dump(x, ind + 1))
+ elif not lead:
+ parts.append(" " + _atom(x))
+ return out + "".join(parts) + "\n" + "\t" * ind + ")"
+
+def find(e, key):
+ return [x for x in e if isinstance(x, list) and x and x[0] == key]
+
+def first(e, key):
+ r = find(e, key)
+ return r[0] if r else None