feat(spatial): 第一个真实 provider——KiCad 网表到 Observation,零依赖
This commit is contained in:
1 parent
29491cae82
commit
f907d57b6a
5 files changed
+352
-2
No files matched your search
@@ -0,0 +1,80 @@
|
||||
"""s-表达式:KiCad 的网表、工程文件、封装库都是这个形状。
|
||||
|
||||
只做一件小事——把 ``(a (b "c") d)`` 变成嵌套列表 ``["a", ["b", "c"], "d"]``。
|
||||
不做 schema 校验,不做单位换算,也不试图理解语义:上层自己按路径取值。
|
||||
|
||||
写它的理由不是"不想用第三方库",而是这里必须零依赖:provider 要能在只有
|
||||
Python 的机器上跑,否则每换一台机器就要先把环境装一遍,而装环境这件事
|
||||
正在 M2 的验收路径上(服务器连不上时整条链路就断了)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def parse(text: str) -> list:
|
||||
"""Parse one s-expression into nested lists of strings."""
|
||||
out, stack, i, n = [], [], 0, len(text)
|
||||
token = []
|
||||
while i < n:
|
||||
ch = text[i]
|
||||
if ch == '"':
|
||||
i += 1
|
||||
buf = []
|
||||
while i < n and text[i] != '"':
|
||||
if text[i] == "\\" and i + 1 < n:
|
||||
i += 1
|
||||
buf.append({"n": "\n", "t": "\t", '"': '"', "\\": "\\"}.get(text[i], text[i]))
|
||||
else:
|
||||
buf.append(text[i])
|
||||
i += 1
|
||||
token.append("".join(buf))
|
||||
i += 1
|
||||
continue
|
||||
if ch == "(":
|
||||
stack.append([])
|
||||
token = []
|
||||
elif ch == ")":
|
||||
if token:
|
||||
stack[-1].append("".join(token))
|
||||
token = []
|
||||
if not stack:
|
||||
raise ValueError(f"unbalanced ')' at {i}")
|
||||
done = stack.pop()
|
||||
(stack[-1] if stack else out).append(done)
|
||||
elif ch in " \t\r\n":
|
||||
if token:
|
||||
stack[-1].append("".join(token))
|
||||
token = []
|
||||
else:
|
||||
token.append(ch)
|
||||
i += 1
|
||||
if token:
|
||||
out.append("".join(token))
|
||||
if stack:
|
||||
raise ValueError("unbalanced '('")
|
||||
return out
|
||||
|
||||
|
||||
def find(node, name: str):
|
||||
"""First child list whose head is ``name``, or None."""
|
||||
if isinstance(node, list):
|
||||
for child in node:
|
||||
if isinstance(child, list) and child and child[0] == name:
|
||||
return child
|
||||
return None
|
||||
|
||||
|
||||
def find_all(node, name: str) -> list:
|
||||
if not isinstance(node, list):
|
||||
return []
|
||||
return [c for c in node if isinstance(c, list) and c and c[0] == name]
|
||||
|
||||
|
||||
def value(node, name: str, default=None):
|
||||
"""The first atom of ``(name atom)``, or ``default``."""
|
||||
child = find(node, name)
|
||||
if child is None:
|
||||
return default
|
||||
for item in child[1:]:
|
||||
if not isinstance(item, list):
|
||||
return item
|
||||
return default
|
||||
Reference in new issue
Block a user