﻿import re
def parse(text):
    toks = re.findall(r'\(|\)|"(?:\\.|[^"\\])*"|[^\s()"]+', text)
    stack=[[]]
    for t in toks:
        if t=='(':
            stack.append([])
        elif t==')':
            x=stack.pop(); stack[-1].append(x)
        else:
            stack[-1].append(t)
    return stack[0][0]
def unq(s): return s[1:-1].replace('\\"','"') if s.startswith('"') else s
def find(node, key):
    return [c for c in node if isinstance(c,list) and c and c[0]==key]
def dump(n, ind=0):
    if not isinstance(n, list): return n
    if all(not isinstance(c,list) for c in n):
        return '(' + ' '.join(n) + ')'
    s = '(' + ' '.join(c for c in n if not isinstance(c,list))
    for c in n:
        if isinstance(c,list): s += '\n' + '\t'*(ind+1) + dump(c, ind+1)
    return s + '\n' + '\t'*ind + ')'
def lib_symbol(path, name, embedded=False):
    tree = parse(open(path, encoding='utf-8').read())
    root = tree
    if embedded:
        root = find(tree,'lib_symbols')[0]
    for c in find(root,'symbol'):
        if unq(c[1])==name: return c
    raise KeyError(name)
def pins(sym):
    out=[]
    def walk(n):
        for c in n:
            if isinstance(c,list):
                if c and c[0]=='pin':
                    at=find(c,'at')[0]; nm=unq(find(c,'name')[0][1]); num=unq(find(c,'number')[0][1])
                    out.append((num,nm,c[1],float(at[1]),float(at[2]),int(float(at[3])) if len(at)>3 else 0))
                else: walk(c)
    walk(sym); return out
def prop(sym, key):
    for p in find(sym,'property'):
        if unq(p[1])==key: return unq(p[2])
