git.s-ol.nu subv / master validate.py
master

Tree @master (Download .tar.gz)

validate.py @masterraw · history · 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
 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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
#!/usr/bin/env python3
""" validate.py
Validates mnemonic labels match the numeric values given for opcodes,
register codes, etc; normalizes argument order and verifies  that there are
no missing arguments.

>>> from io import StringIO
>>> # doctest: +REPORT_NDIFF
... print(subv.join_all(validate(StringIO('''
... == code 0x80000000
... main:
... # load 0x10010000 (UART0) into t0
... 37/lui 5/rd/t0 10010/imm20
... # store 0x48 (H) in UART0+0
... 13/opi 6/rd/t1 0/subop/add 0/rs/x0 48/imm12
... 23/store 2/width/word 5/rs/t0 0/off12 6/rs/t1
... # store 0x65 (e) in UART0+0
... 13/opi 6/rd/t1 0/subop/add 0/rs/x0 65/imm12
... 23/store 2/width/word 5/rs/t0 0/off12 6/rs/t1
... # store 0x6c (l) in UART0+0
... 13/opi 6/rd/t1 0/subop/add 0/rs/x0 6c/imm12
... 23/store 2/width/word 5/rs/t0 0/off12 6/rs/t1
... # store 0x6c (l) in UART0+0
... 13/opi 6/rd/t1 0/subop/add 0/rs/x0 6c/imm12
... 23/store 2/width/word 5/rs/t0 0/off12 6/rs/t1
... # store 0x6f (o) in UART0+0
... 13/opi 6/rd/t1 0/subop/add 0/rs/x0 6f/imm12
... 23/store 2/width/word 5/rs/t0 0/off12 6/rs/t1
... # store 0x0a (\\\\n) in UART0+0
... 13/opi 6/rd/t1 0/subop/add 0/rs/x0 0a/imm12
... 23/store 2/width/word 5/rs/t0 0/off12 6/rs/t1
... # jump back up to the top
... 6f/jal 0/rd/x0 main/off21
... '''[1:-1]))))
== code 0x80000000
main:
# load 0x10010000 (UART0) into t0
37/u 5/rd 10010/imm20
# store 0x48 (H) in UART0+0
13/i 6/rd 0/funct3 0/rs 48/imm12
23/s 2/funct3 5/rs1 0/imm12 6/rs2
# store 0x65 (e) in UART0+0
13/i 6/rd 0/funct3 0/rs 65/imm12
23/s 2/funct3 5/rs1 0/imm12 6/rs2
# store 0x6c (l) in UART0+0
13/i 6/rd 0/funct3 0/rs 6c/imm12
23/s 2/funct3 5/rs1 0/imm12 6/rs2
# store 0x6c (l) in UART0+0
13/i 6/rd 0/funct3 0/rs 6c/imm12
23/s 2/funct3 5/rs1 0/imm12 6/rs2
# store 0x6f (o) in UART0+0
13/i 6/rd 0/funct3 0/rs 6f/imm12
23/s 2/funct3 5/rs1 0/imm12 6/rs2
# store 0x0a (\\n) in UART0+0
13/i 6/rd 0/funct3 0/rs a/imm12
23/s 2/funct3 5/rs1 0/imm12 6/rs2
# jump back up to the top
6f/j 0/rd main/off21
"""

import subv


def pop_part(line, labels, NAME="part"):
    for part in line:
        if part[1] in labels:
            line.remove(part)
            return (part[0], labels[0]) + part[2:]

    raise ValueError("Expected a {} with label {}".format(NAME, "/".join(labels)))


def try_pop_zeroes(line, labels):
    try:
        part = pop_part(line, labels)[:2]
    except ValueError:
        part = (0, labels[0])

    if part[0] != 0:
        raise ValueError("Expected {} value to be zero".format(subv.format_part(part)))

    return part


def validate_part(line, labels, MAP, NAME="part"):
    part = pop_part(line, labels, NAME)

    MNEMONICS = "\nvalid mnemonics are: " + ", ".join(
        subv.format_part((MAP[name], labels[0], name)) for name in MAP
    )

    if len(part) != 3:
        raise ValueError(
            "{} part {} needs a value mnemonic".format(NAME, subv.format_part(part))
            + MNEMONICS
        )

    value, _, name = part

    if name not in MAP:
        raise ValueError("Unknown {} mnemonic '{}'".format(NAME, name) + MNEMONICS)

    if value != MAP[name]:
        raise ValueError(
            "{} code doesn't match mnemonic (got {}, expected {})".format(
                NAME,
                subv.format_part(part),
                subv.format_part((MAP[name],) + part[1:]),
            )
        )

    return part


def pop_immediate(line, sizes, modes=["imm"]):
    if isinstance(sizes, int):
        sizes = [sizes]

    for part in line:
        imm = subv.parse_immediate(part[1])
        if imm and imm["size"] in sizes:
            line.remove(part)

            if imm["mode"] not in modes:
                raise ValueError(
                    "Expected immediate {} to use mode {}".format(
                        subv.format_part(part), "/".join(modes)
                    )
                )

            if not isinstance(part[0], str):
                imm["mode"] = modes[0]

            return (part[0], subv.format_immediate(imm))

    raise ValueError(
        "Expected an immediate with size {}".format("/".join(str(s) for s in sizes))
    )


def validate_empty(inputs):
    if len(inputs) != 0:
        raise ValueError("Extra arguments: {}".format(inputs))


REG_NAMES = "zero,ra,sp,gp,tp,t0,t1,t2,s0,s1,a0,a1,a2,a3,a4,a5,a6,a7,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11,t3,t4,t5,t6"
REG_NAMES = {name: i for i, name in enumerate(REG_NAMES.split(","))}
REG_NAMES.update({"x{}".format(i): i for i in range(32)})


def validate_reg(line, labels):
    """pop a register and validate its mnemonic.

    >>> validate_reg([(5, 'rd', 't0')], ['rd', 'dest'])
    (5, 'rd')
    >>> validate_reg([(5, 'rd', 'x5')], ['rd', 'dest'])
    (5, 'rd')
    >>> validate_reg([(5, 'dest', 'x5')], ['rd', 'dest'])
    (5, 'rd')

    >>> validate_reg([(5, 'rd')], ['rd']) # doctest: +ELLIPSIS
    Traceback (most recent call last):
        ...
    ValueError: register part 5/rd needs a value mnemonic
    valid mnemonics are: 0/rd/zero, 1/rd/ra, 2/rd/sp, ...
    >>> validate_reg([(5, 'rd', 'xxx')], ['rd']) # doctest: +ELLIPSIS
    Traceback (most recent call last):
        ...
    ValueError: Unknown register mnemonic 'xxx'
    valid mnemonics are: 0/rd/zero, 1/rd/ra, 2/rd/sp, ...
    >>> validate_reg([(3, 'rd', 't0')], ['rd'])
    Traceback (most recent call last):
        ...
    ValueError: register code doesn't match mnemonic (got 3/rd/t0, expected 5/rd/t0)
    >>> validate_reg([(5, 'rd')], ['rs'])
    Traceback (most recent call last):
        ...
    ValueError: Expected a register with label rs
    >>> validate_reg([], ['rd', 'dest'])
    Traceback (most recent call last):
        ...
    ValueError: Expected a register with label rd/dest
    """

    return validate_part(line, labels, REG_NAMES, "register")[:2]


COMP_OP_NAMES = {
    "add": 0,
    "sub": 0,
    "xor": 4,
    "or": 6,
    "and": 7,
    "sll": 1,
    "slt": 2,
    "sltu": 3,
    "srl": 5,
    "sra": 5,
}

STORE_WIDTHS = {
    # ISA names
    # byte
    "b": 0,
    "byte": 0,
    # halfword
    "h": 1,
    "half": 1,
    # word
    "w": 2,
    "word": 2,
}

LOAD_WIDTHS = STORE_WIDTHS | {
    # unsigned byte
    "bu": 4,
    "ubyte": 4,
    # unsigned halfword
    "hu": 5,
    "uhalf": 5,
}

BRANCH_NAMES = {
    # equal
    "beq": 0,
    "eq": 0,
    "==": 0,
    # not equal
    "bne": 1,
    "ne": 1,
    "!=": 1,
    # lower than
    "blt": 4,
    "lt": 4,
    "<": 4,
    # greater/equal than
    "bge": 5,
    "ge": 5,
    ">=": 5,
    # unsigned lower than
    "bltu": 6,
    "ltu": 6,
    "<u": 6,
    # unsigned greater/equal than
    "bgeu": 7,
    "geu": 7,
    ">=u": 7,
}

SYSTEM_OP_NAMES = {
    "priv": 0,  # fence, ecall, ebreak
    "csrrw": 1,  # CSR read/write
    "csrrs": 2,  # CSR read/set,
    "csrrc": 3,  # CSR read/clear,
    "csrrwi": 5,  # CSR read/write immediate
    "csrrsi": 6,  # CSR read/set, immediate
    "csrrci": 7,  # CSR read/clear, immediate
}


def validate_opr(inputs):
    """
    validate integer register-register operations.

    >>> validate_opr(subv.parse('33/opr 0/mode/norm 0/subop/add 5/rd/t0 a/rs/a0 b/rs/a1')['instr'])
    [(51, 'r'), (5, 'rd'), (0, 'funct3'), (10, 'rs1'), (11, 'rs2'), (0, 'funct7')]
    >>> validate_opr(subv.parse('33/opr 20/mode/alt 0/subop/sub 5/rd/t0 a/rs/a0 b/rs/a1')['instr'])
    [(51, 'r'), (5, 'rd'), (0, 'funct3'), (10, 'rs1'), (11, 'rs2'), (32, 'funct7')]
    >>> validate_opr(subv.parse('33/opr 20/mode/alt 5/subop/sra 5/rd/t0 a/rs/a0 b/rs/a1')['instr'])
    [(51, 'r'), (5, 'rd'), (5, 'funct3'), (10, 'rs1'), (11, 'rs2'), (32, 'funct7')]

    >>> validate_opr(subv.parse('33/opr 20/mode/alt 0/subop/add 5/rd/t0 a/rs/a0 b/rs/a1')['instr'])
    Traceback (most recent call last):
        ...
    ValueError: comp-op 0/funct3/add needs to go with comp-mode 0/funct7/norm
    >>> validate_opr(subv.parse('33/opr 0/mode/norm 0/subop/sub 5/rd/t0 a/rs/a0 b/rs/a1')['instr'])
    Traceback (most recent call last):
        ...
    ValueError: comp-op 0/funct3/sub needs to go with comp-mode 20/funct7/alt
    >>> validate_opr(subv.parse('33/opr 0/mode/norm 5/subop/sra 5/rd/t0 a/rs/a0 b/rs/a1')['instr'])
    Traceback (most recent call last):
        ...
    ValueError: comp-op 5/funct3/sra needs to go with comp-mode 20/funct7/alt
    """
    op = inputs.pop(0)

    dest = validate_reg(inputs, ["rd", "dest"])
    rs1 = validate_reg(inputs, ["rs1", "rs", "src1", "src"])
    rs2 = validate_reg(inputs, ["rs2", "rs", "src2", "src"])

    funct3 = validate_part(
        inputs, ["funct3", "funct", "subop"], COMP_OP_NAMES, NAME="comp-op"
    )
    funct7 = validate_part(
        inputs, ["funct7", "mode"], {"norm": 0, "alt": 32}, NAME="comp-mode"
    )

    expect_mode = "alt" if funct3[2] in ["sub", "sra"] else "norm"
    expect_val = 32 if expect_mode == "alt" else 0

    if funct7[2] != expect_mode:
        raise ValueError(
            "comp-op {} needs to go with comp-mode {}".format(
                subv.format_part(funct3),
                subv.format_part((expect_val, "funct7", expect_mode)),
            )
        )

    validate_empty(inputs)

    return [
        (op[0], "r"),
        dest,
        funct3[:2],
        rs1,
        rs2,
        funct7[:2],
    ]


def validate_opi(inputs):
    """
    validate integer register-immediate operations.

    >>> validate_opi(subv.parse('13/opi 5/rd/t0 0/subop/add a/rs/a0 42/imm12')['instr'])
    [(19, 'i'), (5, 'rd'), (0, 'funct3'), (10, 'rs'), (66, 'imm12')]
    >>> validate_opi(subv.parse('13/opi 5/rd/t0 3/subop/sltu 5/rs/t0 8/imm12')['instr'])
    [(19, 'i'), (5, 'rd'), (3, 'funct3'), (5, 'rs'), (8, 'imm12')]
    >>> validate_opi(subv.parse('13/opi 5/rd/t0 1/subop/sll 0/imm7 5/rs/t0 8/imm5')['instr'])
    [(19, 'i'), (5, 'rd'), (1, 'funct3'), (5, 'rs'), (8, 'imm12')]
    >>> validate_opi(subv.parse('13/opi 5/rd/t0 1/subop/sll 5/rs/t0 8/imm12')['instr'])
    [(19, 'i'), (5, 'rd'), (1, 'funct3'), (5, 'rs'), (8, 'imm12')]
    >>> validate_opi(subv.parse('13/opi 5/rd/t0 5/subop/sra 20/imm7 5/rs/t0 8/imm5')['instr'])
    [(19, 'i'), (5, 'rd'), (5, 'funct3'), (5, 'rs'), (1032, 'imm12')]
    >>> validate_opi(subv.parse('13/opi 5/rd/t0 5/subop/sra 5/rs/t0 408/imm12')['instr'])
    [(19, 'i'), (5, 'rd'), (5, 'funct3'), (5, 'rs'), (1032, 'imm12')]

    >>> validate_opi(subv.parse('13/opi 5/rd/t0 1/subop/sll 12/imm7 5/rs/t0 8/imm5')['instr'])
    Traceback (most recent call last):
        ...
    ValueError: comp-op 1/funct3/sll needs to go with comp-mode 0/imm7/norm
    >>> validate_opi(subv.parse('13/opi 5/rd/t0 1/subop/sll 5/rs/t0 108/imm12')['instr'])
    Traceback (most recent call last):
        ...
    ValueError: comp-op 1/funct3/sll needs to go with comp-mode 0/imm7/norm
    >>> validate_opi(subv.parse('13/opi 5/rd/t0 5/subop/sra 10/imm7 5/rs/t0 8/imm5')['instr'])
    Traceback (most recent call last):
        ...
    ValueError: comp-op 5/funct3/sra needs to go with comp-mode 20/imm7/alt
    >>> validate_opi(subv.parse('13/opi 5/rd/t0 5/subop/sra 5/rs/t0 208/imm12')['instr'])
    Traceback (most recent call last):
        ...
    ValueError: comp-op 5/funct3/sra needs to go with comp-mode 20/imm7/alt
    """
    op = inputs.pop(0)

    dest = validate_reg(inputs, ["rd", "dest"])
    funct = validate_part(
        inputs, ["funct3", "funct", "subop"], COMP_OP_NAMES, NAME="comp-op"
    )
    src = validate_reg(inputs, ["rs", "rs1"])

    if funct[2] in ["sll", "srl", "sra"]:
        try:
            shamt = pop_immediate(inputs, 5)
            mode = validate_part(
                inputs, ["funct7", "mode"], {"norm": 0, "alt": 32}, NAME="comp-mode"
            )
        except ValueError:
            imm = pop_immediate(inputs, 12)
            shamt = ((imm[0] & 0b11111), 'imm5')
            mode = (imm[0] >> 5, 'imm7')

        expect_mode = "alt" if funct[2] == "sra" else "norm"
        expect_val = 32 if expect_mode == "alt" else 0

        if mode[0] != expect_val:
            raise ValueError(
                "comp-op {} needs to go with comp-mode {}".format(
                    subv.format_part(funct),
                    subv.format_part((expect_val, "imm7", expect_mode)),
                )
            )

        imm = ((mode[0] << 5) | shamt[0], 'imm12')
    else:
        imm = pop_immediate(inputs, 12)

    validate_empty(inputs)

    return [
        (op[0], "i"),
        dest,
        funct[:2],
        src,
        imm,
    ]


def validate_jalr(inputs):
    """
    validate jalr operations.

    >>> validate_jalr(subv.parse('67/jalr 0/rd/x0 0/subop 1/rs/ra 0/off12')['instr'])
    [(103, 'i'), (0, 'rd'), (0, 'funct3'), (1, 'rs'), (0, 'imm12')]
    >>> validate_jalr(subv.parse('67/jalr 0/rd/x0 1/rs/ra 0/off12')['instr'])
    [(103, 'i'), (0, 'rd'), (0, 'funct3'), (1, 'rs'), (0, 'imm12')]

    >>> validate_jalr(subv.parse('67/jalr 0/rd/x0 4/subop 1/rs/ra 0/off12')['instr'])
    Traceback (most recent call last):
        ...
    ValueError: Expected 4/funct3 value to be zero
    """
    op = inputs.pop(0)

    dest = validate_reg(inputs, ["rd", "dest"])
    funct = try_pop_zeroes(inputs, ["funct3", "funct", "subop"])
    src = validate_reg(inputs, ["rs", "rs1", "base"])
    offset = pop_immediate(inputs, 12, ["imm", "off"])

    if funct[0] != 0:
        raise ValueError("Expected 0/funct3, got {}".format(subv.format_part(funct)))

    validate_empty(inputs)

    return [
        (op[0], "i"),
        dest,
        funct[:2],
        src,
        offset,
    ]


def validate_system(inputs):
    """
    validate system operations.

    >>> validate_system(subv.parse('73/system 0/dest/x0 1/subop/csrrw 5/rs/t0 afe/csr')['instr'])
    [(115, 'i'), (0, 'rd'), (1, 'funct3'), (5, 'rs'), (2814, 'imm12')]
    >>> validate_system(subv.parse('73/system 0/dest/x0 5/subop/csrrwi 7/imm5 afe/csr')['instr'])
    [(115, 'i'), (0, 'rd'), (5, 'funct3'), (7, 'imm5'), (2814, 'imm12')]

    >>> validate_system(subv.parse('73/system 0/subop/priv 0/funct12/ecall')['instr'])
    [(115, 'i'), (0, 'rd'), (0, 'funct3'), (0, 'rs'), (0, 'imm12')]
    >>> validate_system(subv.parse('73/system 0/subop/priv 1/funct12/ebreak')['instr'])
    [(115, 'i'), (0, 'rd'), (0, 'funct3'), (0, 'rs'), (1, 'imm12')]

    >>> validate_system(subv.parse('73/system 0/dest/x0 1/subop/csrrw 7/imm5 afe/csr')['instr'])
    Traceback (most recent call last):
        ...
    ValueError: Expected a register with label rs/rs1/src
    >>> validate_system(subv.parse('73/system 0/dest/x0 5/subop/csrrwi 5/rs/t0 afe/csr')['instr'])
    Traceback (most recent call last):
        ...
    ValueError: Expected an immediate with size 5
    >>> validate_system(subv.parse('73/system 1/dest/x1 0/subop/priv 1/funct12/ebreak')['instr'])
    Traceback (most recent call last):
        ...
    ValueError: Expected 1/rd value to be zero
    """
    op = inputs.pop(0)

    funct = validate_part(
        inputs, ["funct3", "funct", "subop"], SYSTEM_OP_NAMES, "system-op"
    )

    if funct[0] == 0:
        # ecall/ebreak
        imm = validate_part(
            inputs, ["imm12", "funct12"], {"ecall": 0, "ebreak": 1}, "system-priv-op"
        )[:2]

        dest = try_pop_zeroes(inputs, ["rd", "dest"])
        src = try_pop_zeroes(inputs, ["rs", "rs1", "src"])
    else:
        dest = validate_reg(inputs, ["rd", "dest"])
        imm = pop_part(inputs, ["imm12", "csr"], "CSR-specifier")

        if funct[2][-1] == "i":
            src = pop_immediate(inputs, 5)
        else:
            src = validate_reg(inputs, ["rs", "rs1", "src"])

    validate_empty(inputs)

    return [
        (op[0], "i"),
        dest,
        funct[:2],
        src,
        imm,
    ]


def validate_load(inputs):
    op = inputs.pop(0)

    dest = validate_reg(inputs, ["rd", "dest"])
    width = validate_part(inputs, ["funct3", "funct", "width"], LOAD_WIDTHS, "width")
    base = validate_reg(inputs, ["rs", "base"])
    offset = pop_immediate(inputs, 12, ["imm", "off"])

    validate_empty(inputs)

    return [
        (op[0], "i"),
        dest,
        width[:2],
        base,
        offset,
    ]


def validate_store(inputs):
    op = inputs.pop(0)
    width = validate_part(inputs, ["funct3", "funct", "width"], STORE_WIDTHS, "width")
    base = validate_reg(inputs, ["rs1", "rs", "base"])
    offset = pop_immediate(inputs, 12, ["imm", "off"])
    src = validate_reg(inputs, ["rs2", "rs", "src"])

    validate_empty(inputs)

    return [
        (op[0], "s"),
        width[:2],
        base,
        offset,
        src,
    ]


def validate_branch(inputs):
    op = inputs.pop(0)

    funct = validate_part(
        inputs, ["funct3", "funct", "subop"], BRANCH_NAMES, "branch-op"
    )
    rs1 = validate_reg(inputs, ["rs1", "rs", "src1", "src"])
    rs2 = validate_reg(inputs, ["rs2", "rs", "src2", "src"])
    offset = pop_immediate(inputs, [12, 13], ["imm", "off"])

    validate_empty(inputs)

    return [
        (op[0], "b"),
        funct[:2],
        rs1,
        rs2,
        offset,
    ]


def validate_u(inputs):
    op = inputs.pop(0)
    rd = validate_reg(inputs, ["rd", "dest"])
    imm = pop_immediate(inputs, 20, ["imm", "off"])

    validate_empty(inputs)

    return [
        (op[0], "u"),
        rd,
        imm,
    ]


def validate_j(inputs):
    op = inputs.pop(0)

    dest = validate_reg(inputs, ["rd", "dest"])
    offset = pop_immediate(inputs, [21, 20], ["imm", "off"])

    validate_empty(inputs)

    return [
        (op[0], "j"),
        dest,
        offset,
    ]


instr_map = {
    "opr": (validate_opr, 0x33),
    "opi": (validate_opi, 0x13),
    "jalr": (validate_jalr, 0x67),
    "system": (validate_system, 0x73),
    "load": (validate_load, 0x03),
    "store": (validate_store, 0x23),
    "branch": (validate_branch, 0x63),
    "lui": (validate_u, 0x37),
    "auipc": (validate_u, 0x17),
    "jal": (validate_j, 0x6F),
}


@subv.with_parsed_lines
def validate(iter):
    for segment, line in iter:
        if line["type"] == "instr" and segment == "code":
            op = line["instr"][0]
            assert len(op) == 2, "instruction without op label: {}".format(op)

            (op, label) = op
            if label not in instr_map:
                raise ValueError("unknown op label: {}".format(label))
            (validator, expected) = instr_map[label]
            if op != expected:
                raise ValueError(
                    "opcode {:02x} doesn't match label {} (expected {:02x})".format(
                        op, label, expected
                    )
                )

            line["instr"] = validator(line["instr"][:])
            line = yield subv.format(line)
        else:
            line = yield line["raw"]


if __name__ == "__main__":
    import sys

    for line in validate(sys.stdin):
        print(line)