summaryrefslogtreecommitdiff
path: root/lib/sexp/parse.py
blob: a33b79aa2d46a96a8964bb01554e2f568043e2ff (plain)
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210

import re
import base64
import binascii
import re

# Partial implementation of Rivest's proposed S-Expressions standard
# as documented at
#      http://people.csail.mit.edu/rivest/Sexp.txt
#
# It's slightly optimized.
#
# Not implemented:
#    [display hints]
#    {basic transport}

__all__ = [ 'FormatError', 'parse' ]

class FormatError(Exception):
    """Raised when parsing fails."""
    pass

_TOKEN_PAT = r"[a-zA-Z\-\.\/\_\:\*\+\=][a-zA-Z0-9\-\.\/\_\:\*\+\=]*"
# Regular expression to match a single lexeme from an encode s-expression.
_LEXEME_START_RE = re.compile(
    r""" \s* (?: (%s) |     # Grp 0: A token.
                 ([0-9]*(?: [\:\|\#\{]  |   # Grp1 : start of string...
                            \"(?:[^\\\"]+|\\.)*\"))  | # or qstring.
                 ([\(\)])  # Grp 2: a paren of some kind.
              )"""
                              %_TOKEN_PAT,re.X|re.M|re.S)

class _P:
    """Helper class for parenthesis tokens."""
    def __init__(self, val):
        self.val = val
    def __repr__(self):
        return "_P(%r)"%self.val

_OPEN_PAREN = _P("(")
_CLOSE_PAREN = _P(")")
del _P
_SPACE_RE = re.compile(r'\s+')

# Matches all characters in a string that we need to unquote.
_UNQUOTE_CHAR_RE = re.compile(r'''
     \\  (?: [abtnvfr] | \r \n ? | \n \r ? | [xX] [A-Fa-f0-9]{2} | [0-8]{1,3} )
     ''')

# Map from quoted representation to unquoted format.
_UNQUOTE_CHAR_MAP = { 'a': '\a',
                      'b': '\b',
                      't': '\t',
                      'n': '\n',
                      'v': '\v',
                      'f': '\f',
                      'r': '\r' }
def _unquoteChar(ch, _U=_UNQUOTE_CHAR_MAP):
    ch = ch[1:]
    try:
        return _U[ch]
    except KeyError:
        pass
    if ch[0] in "\n\r":
        return ""
    elif ch[0] in 'xX':
        return chr(int(ch[1:], 16))
    else:
        i = int(ch[1:], 8)
        if i >= 256:
            raise FormatError("Octal character format out of range.")
        return chr(i)

def _lexItems(s):
    """Generator that iterates over the lexical items in an encoded
       s-expression.  Yields a string for strings, or the special objects
       _OPEN_PAREN and _CLOSE_PAREN.

       >>> list(_lexItems('(4:a)b   hello) (world 1:a 0: '))
       [_P('('), 'a)b ', 'hello', _P(')'), _P('('), 'world', 'a', '']

       >>> list(_lexItems('a b-c 1#20#2#2061##686877# |aGVsbG8gd29ybGQ|'))
       ['a', 'b-c', ' ', ' a', 'hhw', 'hello world']

       >>> list(_lexItems('#2 0# |aGVs\\nbG8 gd29yb   GQ|  '))
       [' ', 'hello world']

       >>> list(_lexItems('|YWJjZA==| x |YWJjZA| 3|Y   W J  j|'))
       ['abcd', 'x', 'abcd', 'abc']

       >>> list(_lexItems('("1""234""hello world" 3"abc" 4"    " )'))
       [_P('('), '1', '234', 'hello world', 'abc', '    ', _P(')')]

    """
    s = s.strip()
    while s:
        m = _LEXEME_START_RE.match(s)
        if not m:
            raise FormatError("No pattern match at %r"%s[:30])
        g = m.groups()
        if g[2]:
            if g[2] == "(":
                yield _OPEN_PAREN
            else:
                yield _CLOSE_PAREN
            s = s[m.end():]
        elif g[0]:
            # we have a token.  Go with that.
            yield g[0]
            s = s[m.end():]
        else:
            assert g[1]
            lastChar = g[1][-1]
            if lastChar == '"':
                qidx = g[1].index('"')
                quoted = g[1][qidx+1:-1] # All but quotes.
                data = _UNQUOTE_CHAR_RE.sub(_unquoteChar, quoted)
                if qidx != 0:
                    num = int(g[1][:qidx], 10)
                    if num != len(data):
                        raise FormatError("Bad length on quoted string")
                yield data
                s = s[m.end():]
                continue

            num = g[1][:-1]
            if len(num):
                num = int(num, 10)
            else:
                num = None

            if lastChar == ':':
                if num is None:
                    raise FormatError()
                s = s[m.end():]
                if len(s) < num:
                    raise FormatError()
                yield s[:num]
                s = s[num:]
            elif lastChar == '#':
                s = s[m.end():]
                try:
                    nextHash = s.index('#')
                except ValueError:
                    raise FormatError("Unterminated # string")
                dataStr = _SPACE_RE.sub("", s[:nextHash])
                try:
                    data = binascii.a2b_hex(dataStr)
                except TypeError:
                    raise FormatError("Bad hex string")
                if num is not None and len(data) != num:
                    raise FormatError("Bad number on hex string")
                yield data
                s = s[nextHash+1:]
            elif lastChar == '|':
                s = s[m.end():]
                try:
                    nextBar = s.index('|')
                except ValueError:
                    raise FormatError("Unterminated | string")
                dataStr = _SPACE_RE.sub("", s[:nextBar])
                # Re-pad.
                mod = len(dataStr) % 4
                if mod:
                    dataStr += "=" * (4 - mod)
                try:
                    data = binascii.a2b_base64(dataStr)
                except TypeError:
                    raise FormatError("Bad base64 string")
                if num is not None and len(data) != num:
                    raise FormatError("Bad number on base64 string")
                yield data
                s = s[nextBar+1:]
            else:
                assert None

def parse(s):
    """
       >>> parse("()")
       []
       >>> parse("(1:X3:abc1:d)")
       ['X', 'abc', 'd']
       >>> parse("(1:X((3:abc))1:d)")
       ['X', [['abc']], 'd']
       >>> parse("(a b (d\\ne f) (g) #ff00ff# |aGVsbG8gd29ybGQ|)")
       ['a', 'b', ['d', 'e', 'f'], ['g'], '\\xff\\x00\\xff', 'hello world']

    """
    outermost = []
    stack = [ ]
    push = stack.append
    pop = stack.pop
    add = outermost.append

    for item in _lexItems(s):
        if item is _OPEN_PAREN:
            next = []
            add(next)
            push(add)
            add = next.append
        elif item is _CLOSE_PAREN:
            add = pop()
        else:
            # it's a string.
            add(item)

    if len(outermost) != 1:
        raise FormatError("No enclosing parenthesis on list")
    return outermost[0]