aboutsummaryrefslogtreecommitdiff
path: root/tools/sexpr.py
blob: ded88cb153d165c8d198a207a07714e0de43866a (plain) (blame)
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
"""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