File size: 5,840 Bytes
1b2c3dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
#!/usr/bin/env python3
"""把 KiCad 官方符号库解析成「一颗料一行」的引脚表。

输入:data/kicad-symbols/(git 克隆,版本号由调用方记录)
输出:data/parts.jsonl —— {lib, name, footprint, datasheet, description, pins:[{num,name,etype}], base}

只做事实抽取,不做任何归一化或判断;归一化在出题那一步,规则写在预注册里。
派生料(extends)继承基础符号的引脚,字段用自己的。
"""
import json
import pathlib
import sys


def tokenize(text):
    i, n = 0, len(text)
    while i < n:
        c = text[i]
        if c in " \t\r\n":
            i += 1
        elif c in "()":
            yield c
            i += 1
        elif c == '"':
            j = i + 1
            buf = []
            while j < n and text[j] != '"':
                if text[j] == "\\" and j + 1 < n:
                    buf.append(text[j + 1])
                    j += 2
                else:
                    buf.append(text[j])
                    j += 1
            yield ("s", "".join(buf))
            i = j + 1
        else:
            j = i
            while j < n and text[j] not in " \t\r\n()":
                j += 1
            yield text[i:j]
            i = j


def parse(text):
    stack, cur = [], []
    for tok in tokenize(text):
        if tok == "(":
            stack.append(cur)
            cur = []
        elif tok == ")":
            done = cur
            cur = stack.pop()
            cur.append(done)
        else:
            cur.append(tok[1] if isinstance(tok, tuple) else tok)
    return cur


def walk_symbols(node):
    """库文件顶层的 (symbol "NAME" ...);嵌套的 unit 符号不在这里返回。"""
    for item in node:
        if isinstance(item, list) and item and item[0] == "kicad_symbol_lib":
            for sub in item[1:]:
                if isinstance(sub, list) and sub and sub[0] == "symbol":
                    yield sub


def collect_pins(sym):
    pins = []
    for sub in sym[2:]:
        if not isinstance(sub, list) or not sub:
            continue
        if sub[0] == "symbol":  # unit / body style
            pins.extend(collect_pins(sub))
        elif sub[0] == "pin":
            etype = sub[1] if len(sub) > 1 and isinstance(sub[1], str) else ""
            name = num = ""
            hidden = False
            for f in sub[2:]:
                if isinstance(f, list) and f:
                    if f[0] == "name" and len(f) > 1:
                        name = f[1]
                    elif f[0] == "number" and len(f) > 1:
                        num = f[1]
                    elif f[0] == "hide" and (len(f) == 1 or f[1] == "yes"):
                        hidden = True
                elif f == "hide":
                    hidden = True
            pins.append({"num": num, "name": name, "etype": etype, "hidden": hidden})
    return pins


def props(sym):
    out = {}
    for sub in sym[2:]:
        if isinstance(sub, list) and len(sub) >= 3 and sub[0] == "property":
            out[sub[1]] = sub[2]
    return out


def extends_of(sym):
    for sub in sym[2:]:
        if isinstance(sub, list) and len(sub) >= 2 and sub[0] == "extends":
            return sub[1]
    return None


def main(root, out_path):
    root = pathlib.Path(root)
    n_parts = n_files = n_err = n_base_err = 0
    with open(out_path, "w") as out:
        for libdir in sorted(root.glob("*.kicad_symdir")):
            lib = libdir.name.removesuffix(".kicad_symdir")
            raw = {}
            for f in sorted(libdir.glob("*.kicad_sym")):
                n_files += 1
                try:
                    tree = parse(f.read_text(encoding="utf-8"))
                except Exception as e:  # 解析不了的原样报出来,不吞
                    n_err += 1
                    print(f"解析失败 {f}: {e}", file=sys.stderr)
                    continue
                for sym in walk_symbols(tree):
                    raw[sym[1]] = sym
            for name, sym in raw.items():
                # 沿 extends 走到头:base 记最终祖先。父符号找不到、或者绕成圈,记 base_error,出题时整颗不收。
                base, base_error, seen, cur = None, None, {name}, sym
                while True:
                    ext = extends_of(cur)
                    if not ext:
                        break
                    if ext not in raw:
                        base_error = f"父符号 {ext} 不在库里"
                        break
                    if ext in seen:
                        base_error = f"extends 绕成圈:{ext}"
                        break
                    seen.add(ext)
                    base = ext
                    cur = raw[ext]
                n_base_err += bool(base_error)
                pins = collect_pins(cur)
                # 同一个脚号在多个 unit / 画法里重复出现时只留一份
                uniq = {}
                for p in pins:
                    uniq.setdefault((p["num"], p["name"], p["etype"]), p)
                p_own = props(sym)
                out.write(json.dumps({
                    "lib": lib, "name": name, "base": base, "base_error": base_error,
                    "footprint": p_own.get("Footprint", ""),
                    "datasheet": p_own.get("Datasheet", ""),
                    "description": p_own.get("Description", ""),
                    "keywords": p_own.get("ki_keywords", ""),
                    "pins": sorted(uniq.values(), key=lambda p: (len(p["num"]), p["num"])),
                }, ensure_ascii=False) + "\n")
                n_parts += 1
    print(f"库 {len(list(root.glob('*.kicad_symdir')))} 个 · 文件 {n_files} · 料 {n_parts} · 解析失败 {n_err} · 继承链异常 {n_base_err}")


if __name__ == "__main__":
    main(sys.argv[1], sys.argv[2])