aboutsummaryrefslogtreecommitdiffstats
path: root/subv.py
blob: 43bfa35b0aa4913c814db8a80eaf717ed3e92084 (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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
import re
white = re.compile(r'[ \t\.\n]+')
hex = re.compile(r'^\-?(0x)?[0-9a-f]+$')
slice_re = re.compile(r'^([^\[]+)(?:\[(\d+):(\d+)\])?$')
field_re = re.compile(r'^(imm|off)(\d+)$')

# parsing
def parse_part(part):
    """ parse a literal with attached metadata.

    >>> parse_part('0')
    (0,)
    >>> parse_part('00')
    (0,)
    >>> parse_part('0x00')
    (0,)

    >>> parse_part('12')
    (18,)
    >>> parse_part('0x12')
    (18,)

    >>> parse_part('-12')
    (-18,)
    >>> parse_part('-0x12')
    (-18,)

    >>> parse_part('00/with/tag')
    (0, 'with', 'tag')
    >>> parse_part('-12/and/tag')
    (-18, 'and', 'tag')

    >>> parse_part('label/tag*')
    ('label', 'tag*')
    >>> parse_part('$label/tag*')
    ('$label', 'tag*')
    >>> parse_part('label:suff/tag*')
    ('label:suff', 'tag*')
    >>> parse_part('$label:suff/tag*')
    ('$label:suff', 'tag*')
    >>> parse_part('label[3:1]/tag*')
    ('label[3:1]', 'tag*')
    >>> parse_part('$label:suff[11:0]/tag*')
    ('$label:suff[11:0]', 'tag*')
    """
    part = part.split('/')
    if hex.match(part[0]):
        part[0] = int(part[0], 16)
    return tuple(part)

def parse_instr(line):
    """ parse an instruction-line.

    >>> parse_instr('ff/op 0/subop/add 1/rd/x1 label[11:0]/imm12')
    [(255, 'op'), (0, 'subop', 'add'), (1, 'rd', 'x1'), ('label[11:0]', 'imm12')]
    """
    parts = white.split(line)
    parts = [parse_part(part) for part in parts if part != '']
    return parts

def parse_segment(line):
    """ parse a segment-line.

    >>> parse_segment('== code 0x8000')
    ('code', 32768)
    >>> parse_segment('== text')
    ('text',)
    """
    parts = white.split(line)
    if len(parts) == 3:
      return (parts[1], int(parts[2], 16))
    elif len(parts) == 2:
      return (parts[1],)
    else:
      raise ValueError("invalid segment line")

def parse_label(line):
    """ parse a label-line.

    >>> parse_label('some_label:')
    'some_label'
    >>> parse_label('$some:label:')
    '$some:label'
    """
    return line[:-1]

def parse_reference(part):
    """ parse a sliced-label part.

    >>> parse_reference(('lbl', 'imm32'))
    {'label': 'lbl', 'mode': 'imm', 'size': 32, 'meta': ()}

    >>> parse_reference(('x[11:0]', 'off12'))
    {'label': 'x', 'mode': 'off', 'size': 12, 'meta': (), 'hi': 11, 'lo': 0}
    """
    ref = part[0]
    field = part[1]

    label, hi, lo = slice_re.match(ref).groups()
    mode, size = field_re.match(field).groups()
    
    ref = {
        'label': label,
        'mode': mode,
        'size': int(size),
        'meta': part[2:],
    }

    if hi is not None:
        ref['hi'] = int(hi)
        ref['lo'] = int(lo)

    return ref

def classify(line):
    """ classify cleaned lines.

    >>> classify('')
    'empty'
    >>> classify('== code')
    'segment'
    >>> classify('== text 0x1000')
    'segment'
    >>> classify('some_label:')
    'label'
    >>> classify('$some:label:')
    'label'
    >>> classify('ff/op 0/subop/add 1/rd/x1 label[11:0]/imm12')
    'instr'
    """
    if line == '':
        return 'empty'
    elif line.startswith('=='): # segment
        return 'segment'
    elif line.endswith(':'): # label
        return 'label'
    else:
        return 'instr'

def parse(line):
    """ clean, classify and parse lines.
    """
    raw = line.strip()
    split = raw.split('#', 1)
    if len(split) == 1:
        clean = raw
        comment = None
    else:
        clean, comment = split

    type = classify(clean)

    if type == 'segment':
        parsed = parse_segment(clean)
    elif type == 'label':
        parsed = parse_label(clean)
    elif type == 'instr':
        parsed = parse_instr(clean)
    else:
        parsed = None

    return {
        'type': type,
        'raw': raw,
        'line': clean,
        'comment': comment,
        type: parsed,
    }

def is_reference(part):
    """ check whether a part is a label reference.

    >>> is_reference(('hello',))
    True
    >>> is_reference(('hello:world',))
    True
    >>> is_reference(('$label',))
    True
    >>> is_reference(('$label:extra',))
    True
    >>> is_reference(('$label:extra', 'off20'))
    True
    >>> is_reference(('plain', 'off20'))
    True

    >>> is_reference((0,))
    False
    >>> is_reference((1,))
    False
    >>> is_reference((1, 'disp20'))
    False
    >>> is_reference((0x13f, 'imm12'))
    False
    """
    return isinstance(part[0], str)

def untag(part, expect=None):
    """ returns the value of a part and optionally verifies the first tag.

    >>> untag((2, 'num'))
    2
    >>> untag(('$label', 'imm20'))
    '$label'
    >>> untag((2, 'hello', 'things'))
    2

    >>> untag((2, 'num'), expect='num')
    2
    >>> untag(('$label', 'imm20'), expect='imm20')
    '$label'

    >>> untag((2, 'imm12'), expect='imm20')
    Traceback (most recent call last):
        ...
    ValueError: expected (2, 'imm12') to be labelled imm20
    >>> untag(('$label', 'imm20'), expect='off12')
    Traceback (most recent call last):
        ...
    ValueError: expected ('$label', 'imm20') to be labelled off12
    """
    if expect and part[1] != expect:
        raise ValueError("expected {} to be labelled {}".format(part, expect))
    return part[0]

def format_part(part):
    """ opposite of parse_part.

    >>> format_part((0,))
    '00'
    >>> format_part((0x00,))
    '00'
    >>> format_part((16,))
    '10'
    >>> format_part((0x10,))
    '10'

    >>> format_part(('label', 'tag*'))
    'label/tag*'
    >>> format_part(('$label', 'tag*'))
    '$label/tag*'
    >>> format_part(('label:suff', 'tag'))
    'label:suff/tag'
    >>> format_part(('$label:suff', 'tag'))
    '$label:suff/tag'
    """
    if not is_reference(part):
        first = '{:02x}'.format(part[0])
        part = (first, *part[1:])
    return '/'.join([str(p) for p in part])

def format(line):
    """ opposite of parse.

    >>> format({
    ...     'type': 'instr',
    ...     'instr': [(255, 'op'), (0, 'subop', 'add'), (1, 'rd', 'x1'), ('label[11:0]', 'imm12')],
    ...     'comment': "this does things."
    ... })
    'ff/op 00/subop/add 01/rd/x1 label[11:0]/imm12 # this does things.'
    """
    if line['type'] == 'instr':
      packed = ' '.join(format_part(part) for part in line['instr'])
      if line['comment']:
          packed = packed + ' # ' + line['comment']
      return packed
    else:
      raise NotImplementedError()

def dump(line):
    """ debug-friendly string representation of parsed lines.

    >>> dump({
    ...     'type': 'instr',
    ...     'instr': [(255, 'op'), (0, 'subop', 'add'), (1, 'rd', 'x1'), ('label[11:0]', 'imm12')],
    ...     'comment': "this does things."
    ... })
    "instr[(255, 'op'), (0, 'subop', 'add'), (1, 'rd', 'x1'), ('label[11:0]', 'imm12')]"
    """

    return '{}{}'.format(line['type'], line[line['type']])

def join_all(gen):
    res = '\n'.join(gen)
    return res