-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcocotb_ref_model.py
More file actions
1616 lines (1456 loc) · 59.1 KB
/
Copy pathcocotb_ref_model.py
File metadata and controls
1616 lines (1456 loc) · 59.1 KB
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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Cocotb-ready reference-model cross-check for t27 -> Icarus Verilog.
Usage (standalone):
python3 scripts/cocotb_ref_model.py \
--ast-json ast.json \
--verilog DUT.v \
--top-module MODULE_TB
The script can also be imported as a cocotb test module; when cocotb is
present it will use the runner API, otherwise it falls back to running
``iverilog`` + ``vvp`` directly.
The reference model evaluates the expected expression of every ``assert_eq``
inside ``test`` / ``invariant`` blocks and verifies that the generated Verilog
simulation log reports ``[TEST] <name> : PASSED``. It also reads the VCD probe
value captured for the actual expression and compares it against the
independently evaluated expected value using the declared bit width and
signedness.
"""
from __future__ import annotations
import argparse
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
HAVE_COCOTB = False
try:
import cocotb
from cocotb.triggers import Timer
HAVE_COCOTB = True
except Exception: # cocotb is optional; standalone mode works without it
pass
# ---------------------------------------------------------------------------
# Bit-vector value representation
# ---------------------------------------------------------------------------
class Bv:
"""A width-aware bit-vector value."""
__slots__ = ("value", "width", "signed")
def __init__(self, value: int, width: int, signed: bool) -> None:
self.width = width
self.signed = signed
self.value = self._mask(value)
def _mask(self, v: int) -> int:
return int(v) & ((1 << self.width) - 1)
def as_int(self) -> int:
"""Return the value as a Python int with correct sign."""
v = self.value
if self.signed and v >= (1 << (self.width - 1)):
v -= 1 << self.width
return v
def as_unsigned(self) -> int:
return self.value
def __repr__(self) -> str:
return f"Bv({self.as_int()}, w={self.width}, signed={self.signed})"
# ---------------------------------------------------------------------------
# Type/width helpers
# ---------------------------------------------------------------------------
_TYPE_WIDTH: Dict[str, int] = {
"bool": 1,
"u8": 8,
"i8": 8,
"u16": 16,
"i16": 16,
"u32": 32,
"i32": 32,
"u64": 64,
"i64": 64,
"u128": 128,
"i128": 128,
"usize": 32,
"int": 32,
"nat": 32,
}
_TYPE_SIGNED: set = {"i8", "i16", "i32", "i64", "i128", "int"}
def _parse_array_type(ty: str) -> Optional[Tuple[List[int], str]]:
"""Parse '[2][3]i16' into ([2, 3], 'i16') or None."""
rest = ty.strip()
dims: List[int] = []
while rest.startswith("["):
close = rest.find("]")
if close == -1:
return None
try:
dims.append(int(rest[1:close].strip()))
except ValueError:
return None
rest = rest[close + 1 :].strip()
if not dims or not rest:
return None
return (dims, rest)
def _base_type_name(ty: str) -> str:
parsed = _parse_array_type(ty)
return parsed[1] if parsed else ty.strip()
def _type_width_signed(ty: str) -> Optional[Tuple[int, bool]]:
"""Return (width, signed) for a scalar t27 type, or None."""
parsed = _parse_array_type(ty)
elem_type = parsed[1] if parsed else ty.strip()
width = _TYPE_WIDTH.get(elem_type)
if width is None:
return None
signed = elem_type in _TYPE_SIGNED
if parsed:
# A whole array is not scalar, but callers decide whether they want the
# element width.
return (width, signed)
return (width, signed)
def _scalar_array_info(ty: str) -> Optional[Tuple[int, int, bool]]:
"""For '[N]i16' return (count, element_width, signed)."""
parsed = _parse_array_type(ty)
if not parsed:
return None
dims, elem = parsed
if len(dims) != 1:
return None
width = _TYPE_WIDTH.get(elem)
if width is None:
return None
return (dims[0], width, elem in _TYPE_SIGNED)
def _primitive_array_info(ty: str) -> Optional[Tuple[List[int], str, int, bool]]:
"""For '[2][3]i16' return (dims, elem, total_width, signed)."""
parsed = _parse_array_type(ty)
if not parsed:
return None
dims, elem = parsed
elem_width = _TYPE_WIDTH.get(elem)
if elem_width is None:
return None
total = elem_width
for d in dims:
total *= d
return (dims, elem, total, elem in _TYPE_SIGNED)
def _is_primitive_scalar_type(ty: str) -> bool:
"""True for 'u32', 'i16', etc. and '[N]u32' one-dimensional scalar arrays."""
parsed = _parse_array_type(ty)
elem = parsed[1] if parsed else ty.strip()
return elem in _TYPE_WIDTH and (parsed is None or len(parsed[0]) == 1)
def _packed_type_width_signed(
ctx: EvalContext, ty: str
) -> Optional[Tuple[int, bool]]:
"""Return (width, signed) for a lowerable packed scalar struct or array."""
parsed = _parse_array_type(ty)
if parsed:
dims, elem = parsed
# W564: arrays of lowerable packed scalar structs fold the struct width
# across all dimensions into a single unsigned packed vector.
if _is_lowerable_scalar_struct_type(ctx, elem):
base_ws = _packed_type_width_signed(ctx, elem)
if base_ws is None:
return None
total = base_ws[0]
for d in dims:
total *= d
return (total, False)
# Fixed-size primitive scalar array (1-D or multi-D).
info = _primitive_array_info(ty)
if info is not None:
return (info[2], info[3])
return None
# Lowerable packed scalar struct.
if not _is_lowerable_scalar_struct_type(ctx, ty):
return None
decl = ctx.decls.get(f"struct:{ty.strip()}")
if decl is None:
return None
total = 0
for field in _children(decl):
ftype = field.get("extra_type", "")
finfo = _scalar_array_info(ftype)
if finfo is not None:
total += finfo[0] * finfo[1]
continue
fws = _type_width_signed(ftype)
if fws is None:
return None
total += fws[0]
return (total, False)
def _is_lowerable_scalar_struct_type(ctx: EvalContext, ty: str) -> bool:
"""Mirror the compiler's notion of a lowerable packed scalar struct."""
decl = ctx.decls.get(f"struct:{ty.strip()}")
if decl is None:
return False
for field in _children(decl):
ftype = field.get("extra_type", "")
if _scalar_array_info(ftype) is not None:
continue
if _type_width_signed(ftype) is not None:
continue
return False
return True
def _contains_kind(node: Dict[str, Any], kind: str) -> bool:
"""Recursively check whether `node` or any descendant has the given kind."""
if node.get("kind") == kind:
return True
return any(_contains_kind(child, kind) for child in _children(node))
# ---------------------------------------------------------------------------
# AST helpers
# ---------------------------------------------------------------------------
def _children(node: Dict[str, Any]) -> List[Dict[str, Any]]:
return node.get("children", []) or []
def _literal_value(node: Dict[str, Any]) -> Optional[Any]:
"""Return integer/bool/string value for a literal node, or None."""
if node.get("kind") != "ExprLiteral":
return None
value = node.get("value", "")
if value in ("true", "false"):
return value == "true"
for prefix, base in (("0x", 16), ("0b", 2), ("0o", 8)):
if value.lower().startswith(prefix):
try:
return int(value[len(prefix) :], base)
except ValueError:
return None
try:
return int(value, 10)
except ValueError:
try:
return float(value)
except ValueError:
return value
def _literal_bv(node: Dict[str, Any]) -> Optional[Bv]:
"""Return a width-aware bit-vector for a literal, or None."""
if node.get("kind") != "ExprLiteral":
return None
value = node.get("value", "")
if value == "true":
return Bv(1, 1, False)
if value == "false":
return Bv(0, 1, False)
extra = node.get("extra_type", "")
if extra:
ws = _type_width_signed(extra)
if ws is None:
return None
width, signed = ws
else:
width, signed = 32, True
# Parse numeric literal.
for prefix, base in (("0x", 16), ("0b", 2), ("0o", 8)):
if value.lower().startswith(prefix):
try:
return Bv(int(value[len(prefix) :], base), width, signed)
except ValueError:
return None
try:
return Bv(int(value, 10), width, signed)
except ValueError:
return None
def _eval_simple_const(node: Dict[str, Any]) -> Optional[Any]:
"""Evaluate a tiny subset of constant expressions used in asserts."""
kind = node.get("kind")
if kind == "ExprLiteral":
return _literal_value(node)
if kind == "ExprBinary" and len(_children(node)) == 2:
op = node.get("extra_op", "")
left = _eval_simple_const(_children(node)[0])
right = _eval_simple_const(_children(node)[1])
if left is None or right is None:
return None
try:
if op == "+":
return left + right
if op == "-":
return left - right
if op == "*":
return left * right
if op == "/":
return left // right if isinstance(left, int) and isinstance(right, int) else left / right
if op == "%":
return left % right
if op == "==":
return left == right
if op == "!=":
return left != right
if op == "<":
return left < right
if op == "<=":
return left <= right
if op == ">":
return left > right
if op == ">=":
return left >= right
except Exception:
return None
if kind == "ExprUnary" and len(_children(node)) == 1:
op = node.get("extra_op", "")
child = _eval_simple_const(_children(node)[0])
if child is None:
return None
if op == "-":
return -child
if op == "!":
return not child
if kind == "ExprCast" and len(_children(node)) == 1:
return _eval_simple_const(_children(node)[0])
return None
def _sanitize_probe_name(name: str) -> str:
return re.sub(r"[^A-Za-z0-9_]", "_", name)
def _probe_name(block_name: str, idx: int) -> str:
return f"_t27_probe_{_sanitize_probe_name(block_name)}_{idx}"
def _collect_top_level_decls(root: Dict[str, Any]) -> Dict[str, Dict[str, Any]]:
"""Collect top-level declarations by name for type/function lookup."""
out: Dict[str, Dict[str, Any]] = {}
for decl in _children(root):
kind = decl.get("kind")
name = decl.get("name", "")
if not name:
continue
if kind == "StructDecl":
out[f"struct:{name}"] = decl
elif kind == "FnDecl":
out[f"fn:{name}"] = decl
elif kind == "ConstDecl":
out[f"const:{name}"] = decl
elif kind == "EnumDecl":
out[f"enum:{name}"] = decl
return out
def _struct_field_type(structs: Dict[str, Dict[str, Any]], struct_name: str, field_name: str) -> Optional[str]:
decl = structs.get(f"struct:{struct_name}")
if not decl:
return None
for field in _children(decl):
if field.get("name") == field_name:
return field.get("extra_type", "")
return None
def _find_function_body(fn: Dict[str, Any]) -> Optional[Dict[str, Any]]:
"""Return the first StmtReturn or bare return expression in a function."""
for stmt in _children(fn):
kind = stmt.get("kind")
if kind == "ExprReturn" and _children(stmt):
return _children(stmt)[0]
if kind == "StmtReturn" and _children(stmt):
child = _children(stmt)[0]
if child.get("kind") == "ExprReturn" and _children(child):
return _children(child)[0]
return child
return None
# ---------------------------------------------------------------------------
# Expression evaluator with typed width/signedness
# ---------------------------------------------------------------------------
class EvalContext:
"""Holds variable bindings and top-level declarations for expression eval."""
def __init__(self, root: Dict[str, Any], bind_module_initializers: bool = True) -> None:
self.root = root
self.decls = _collect_top_level_decls(root)
self.vars: Dict[str, Bv] = {}
# Cache function parameter/return types and local variable types.
self.fn_param_types: Dict[str, List[Tuple[str, str]]] = {}
self.fn_return_types: Dict[str, str] = {}
self.fn_local_types: Dict[str, Dict[str, str]] = {}
# Track which function we are evaluating so parameter/local declared
# types can be resolved even when the identifier is bound in vars.
self.current_fn: Optional[str] = None
# W547: track test-block local variable types and the current test block
# so that assertions referencing function-local packed arrays can infer
# the correct element width/signedness for the VCD cross-check.
self.test_local_types: Dict[str, Dict[str, str]] = {}
self.current_block: Optional[str] = None
for decl in _children(root):
if decl.get("kind") != "FnDecl":
continue
name = decl.get("name", "")
params = decl.get("params", []) or []
if name:
self.fn_param_types[name] = params
self.fn_return_types[name] = decl.get("extra_return_type", "")
locals_map: Dict[str, str] = {}
# Function parameters are not emitted as StmtLocal nodes, but they
# carry a type annotation in the FnDecl params list. Record them so
# field/index access on parameter identifiers resolves correctly.
for pname, ptype in params:
if pname and ptype:
locals_map[pname] = ptype
for stmt in _children(decl):
if stmt.get("kind") == "StmtLocal":
vname = stmt.get("name", "")
vtype = stmt.get("extra_type", "")
if vname and vtype:
locals_map[vname] = vtype
self.fn_local_types[name] = locals_map
# W541/W543: bind module-level const/var initializers of lowerable packed
# scalar struct (or fixed-size scalar array) type so that assertions on
# whole packed values can be independently evaluated. Track which ones
# are mutable so whole-struct assignments inside test blocks update the
# reference model state.
self.mutable_module_names: set = set()
if bind_module_initializers:
for decl in _children(root):
kind = decl.get("kind")
if kind not in ("ConstDecl",):
continue
name = decl.get("name", "")
vtype = decl.get("extra_type", "")
if not name or not vtype:
continue
if not _is_lowerable_scalar_struct_type(self, vtype) and _scalar_array_info(vtype) is None:
continue
if decl.get("extra_mutable", False):
self.mutable_module_names.add(name)
kids = _children(decl)
if not kids:
continue
init_node = kids[0]
init = _eval_expr_bv(self, init_node)
if init is None:
continue
self.vars[name] = init
def bind(self, name: str, value: Bv) -> None:
self.vars[name] = value
def resolve_var_type(self, name: str) -> Optional[str]:
if name in self.vars:
return None # runtime binding; type is carried by the Bv
# module-level const/var are both represented as ConstDecl in the AST.
c = self.decls.get(f"const:{name}")
if c is not None:
return c.get("extra_type", "")
return None
def _type_of_expr(ctx: EvalContext, node: Dict[str, Any]) -> Optional[Tuple[int, bool]]:
"""Infer the scalar width and signedness of an expression node."""
kind = node.get("kind")
if kind == "ExprLiteral":
bv = _literal_bv(node)
return (bv.width, bv.signed) if bv else None
if kind == "ExprIdentifier":
name = node.get("name", "")
if name in ctx.vars:
v = ctx.vars[name]
return (v.width, v.signed)
ty = ctx.resolve_var_type(name)
if ty:
return _packed_type_width_signed(ctx, ty) or _type_width_signed(ty)
return None
if kind == "ExprCall":
ret_ty = ctx.fn_return_types.get(node.get("name", ""), "")
return _packed_type_width_signed(ctx, ret_ty) or _type_width_signed(ret_ty)
if kind == "ExprArrayLiteral":
elem_type = node.get("extra_type", "")
size_str = node.get("extra_size", "")
full_ty = f"[{size_str}]{elem_type}" if size_str and elem_type else ""
# W564: use the packed-vector width for primitive scalar arrays and for
# arrays of lowerable packed scalar structs.
packed = _packed_type_width_signed(ctx, full_ty)
if packed is not None:
return packed
info = _primitive_array_info(full_ty)
if info is not None:
return (info[2], info[3])
ws = _type_width_signed(elem_type)
if ws is None:
return None
try:
count = int(size_str.split("][")[-1])
except ValueError:
return None
return (count * ws[0], ws[1])
if kind == "ExprStructLit":
struct_name = node.get("extra_type", "") or node.get("name", "")
return _packed_type_width_signed(ctx, struct_name)
if kind == "ExprFieldAccess" and _children(node):
base = _children(node)[0]
base_name = _base_name(base)
if base_name is None:
return None
base_type = _resolve_base_type(ctx, base_name)
if base_type is None:
return None
ftype = _struct_field_type(ctx.decls, base_type, node.get("name", ""))
if ftype is None:
return None
info = _scalar_array_info(ftype)
if info:
return (info[0] * info[1], info[2])
return _type_width_signed(ftype)
if kind == "ExprIndex" and len(_children(node)) >= 2:
base = _children(node)[0]
base_name = _base_name(base)
if base_name is None:
return None
# W547: use the full declared type (including array dimensions) so that
# primitive scalar arrays like [3]i8 resolve to the correct element
# width/signedness. _resolve_base_type strips dimensions for struct-name
# lookups; that is the wrong granularity here.
full_type = _resolve_full_type(ctx, base_name)
if full_type is None:
return None
# Primitive scalar array element.
parsed = _parse_array_type(full_type)
if parsed:
_, elem = parsed
ws = _type_width_signed(elem)
if ws:
return ws
# Scalar-struct array field element access: base is a field access
# whose field is a fixed-size scalar array. For this path the base type
# is the struct name without array dimensions.
base_type = _resolve_base_type(ctx, base_name)
if base_type is not None and base.get("kind") == "ExprFieldAccess":
ftype = _struct_field_type(ctx.decls, base_type, base.get("name", ""))
if ftype:
info = _scalar_array_info(ftype)
if info:
return (info[1], info[2])
return None
if kind == "ExprCast":
target = node.get("extra_type", "")
base = target.split("[")[0].strip()
return _type_width_signed(base)
if kind == "ExprBinary":
op = node.get("extra_op", "")
if op in ("&&", "||", "and", "or", "==", "!=", "<", "<=", ">", ">="):
return (1, False)
left = _type_of_expr(ctx, _children(node)[0])
right = _type_of_expr(ctx, _children(node)[1])
if left is None or right is None:
return None
if op in ("<<", ">>"):
return left
return (max(left[0], right[0]), left[1] or right[1])
if kind == "ExprUnary":
op = node.get("extra_op", "")
child = _type_of_expr(ctx, _children(node)[0])
if child is None:
return None
if op in ("!", "not"):
return (1, False)
return child
return None
def _base_name(node: Dict[str, Any]) -> Optional[str]:
kind = node.get("kind")
if kind == "ExprIdentifier":
return node.get("name", "") or None
if kind == "ExprIndex" and _children(node):
return _base_name(_children(node)[0])
return None
def _collect_index_chain(
node: Dict[str, Any]
) -> Tuple[Optional[Dict[str, Any]], List[Dict[str, Any]]]:
"""Walk an ExprIndex chain and return (root, [indices in source order]).
For ``m[i][j]`` the chain is ``ExprIndex(ExprIndex(m, i), j)``; this
function descends to ``m`` and returns the indices ``[i, j]`` in the order
they appear in the source.
"""
indices: List[Dict[str, Any]] = []
while node.get("kind") == "ExprIndex" and _children(node):
kids = _children(node)
if len(kids) >= 2:
indices.append(kids[1])
node = kids[0]
return node, indices
def _resolve_full_type(ctx: EvalContext, name: str) -> Optional[str]:
"""Return the declared type of `name` including array dimensions."""
if ctx.current_fn:
local_ty = ctx.fn_local_types.get(ctx.current_fn, {}).get(name)
if local_ty:
return local_ty
if ctx.current_block:
local_ty = ctx.test_local_types.get(ctx.current_block, {}).get(name)
if local_ty:
return local_ty
c = ctx.decls.get(f"const:{name}")
if c is not None:
ty = c.get("extra_type", "")
if ty:
return ty
return ctx.resolve_var_type(name)
def _resolve_base_type(ctx: EvalContext, name: str) -> Optional[str]:
# W542: function parameters are bound in vars but are not StmtLocal nodes,
# so resolve their declared type from the current function's local map
# first. They shadow module-level names inside the function body.
if ctx.current_fn:
local_ty = ctx.fn_local_types.get(ctx.current_fn, {}).get(name)
if local_ty:
return _base_type_name(local_ty)
# W547: test-block local variables (e.g. `let a : [3]i8 = seq();`) carry a
# type annotation in the StmtLocal node. Resolve them when evaluating
# assertions inside the same test block.
if ctx.current_block:
local_ty = ctx.test_local_types.get(ctx.current_block, {}).get(name)
if local_ty:
return _base_type_name(local_ty)
# W541: module-level const/var are now bound in ctx.vars, but we still need
# their declared type for field/index type inference. Top-level decls
# always carry the type annotation.
c = ctx.decls.get(f"const:{name}")
if c is not None:
ty = c.get("extra_type", "")
if ty:
return _base_type_name(ty)
# Fallback for unbound identifiers.
ty = ctx.resolve_var_type(name)
if ty:
return _base_type_name(ty)
return None
def _eval_expr_bv(ctx: EvalContext, node: Dict[str, Any]) -> Optional[Bv]:
"""Evaluate an expression and return a width-aware Bv value."""
kind = node.get("kind")
if kind == "ExprLiteral":
return _literal_bv(node)
if kind == "ExprIdentifier":
name = node.get("name", "")
if name in ctx.vars:
return ctx.vars[name]
return None
if kind == "ExprCall":
return _eval_call_bv(ctx, node)
if kind == "ExprFieldAccess":
return _eval_field_bv(ctx, node)
if kind == "ExprIndex":
return _eval_index_bv(ctx, node)
if kind == "ExprCast":
return _eval_cast_bv(ctx, node)
if kind == "ExprBinary":
return _eval_binary_bv(ctx, node)
if kind == "ExprUnary":
return _eval_unary_bv(ctx, node)
if kind == "ExprSwitch":
return _eval_switch_bv(ctx, node)
if kind == "ExprIf":
return _eval_ternary_bv(ctx, node)
if kind == "ExprStructLit":
return _eval_struct_lit_bv(ctx, node)
if kind == "ExprArrayLiteral":
return _eval_array_lit_bv(ctx, node)
return None
def _eval_array_lit_bv(ctx: EvalContext, node: Dict[str, Any]) -> Optional[Bv]:
"""Pack a scalar array literal into a bit-vector (element 0 at LSB).
W548: handle multi-dimensional literals such as
``[2][3]u8{ row0, row1 }`` by concatenating inner packed arrays. For a
one-dimensional scalar array each child is masked to the element width
before packing, matching the compiler's packed-vector layout.
"""
children = _children(node)
if not children:
return None
elem_type = node.get("extra_type", "")
size_str = node.get("extra_size", "")
full_ty = f"[{size_str}]{elem_type}" if size_str and elem_type else ""
parsed = _parse_array_type(full_ty) if full_ty else None
if parsed:
dims, elem = parsed
elem_ws = _type_width_signed(elem)
if elem_ws and len(dims) >= 1:
count = dims[0]
total_width = elem_ws[0]
for d in dims:
total_width *= d
inner_width = total_width // count
raw = 0
off = 0
for child in children:
val = _eval_expr_bv(ctx, child)
if val is None:
return None
mask = (1 << inner_width) - 1
raw |= (val.value & mask) << off
off += inner_width
return Bv(raw, total_width, elem_ws[1])
# Fallback: recursively concatenate children at their natural widths.
raw = 0
width = 0
signed: Optional[bool] = None
for child in children:
val = _eval_expr_bv(ctx, child)
if val is None:
return None
mask = (1 << val.width) - 1
raw |= (val.value & mask) << width
width += val.width
if signed is None:
signed = val.signed
if signed is None:
return None
return Bv(raw, width, signed)
def _eval_struct_lit_bv(ctx: EvalContext, node: Dict[str, Any]) -> Optional[Bv]:
"""Pack a scalar-struct literal into a bit-vector (LSB-first field order)."""
struct_name = node.get("name", "")
decl = ctx.decls.get(f"struct:{struct_name}")
if decl is None:
return None
fields = [(f.get("name", ""), f.get("extra_type", "")) for f in _children(decl)]
# Collect explicitly provided field values.
assigned: Dict[str, Bv] = {}
for child in _children(node):
if child.get("kind") != "ExprFieldAccess":
continue
fname = child.get("name", "")
kids = _children(child)
if not kids:
continue
val = _eval_expr_bv(ctx, kids[0])
if val is None:
return None
assigned[fname] = val
raw = 0
offset = 0
total_width = 0
for fname, ftype in fields:
info = _scalar_array_info(ftype)
if info is not None:
fw = info[0] * info[1]
signed = info[2]
else:
ws = _type_width_signed(ftype)
if ws is None:
return None
fw, signed = ws
val = assigned.get(fname)
if val is None:
val = Bv(0, fw, signed)
# Pack each field at its declared width, masking values that were
# evaluated at a wider natural width (e.g. integer literals).
mask = (1 << fw) - 1
raw |= (val.value & mask) << offset
offset += fw
total_width += fw
return Bv(raw, total_width, False)
def _eval_call_bv(ctx: EvalContext, node: Dict[str, Any]) -> Optional[Bv]:
name = node.get("name", "")
args = _children(node)
fn = ctx.decls.get(f"fn:{name}")
if fn is None:
return None
params = ctx.fn_param_types.get(name, [])
if len(args) != len(params):
return None
# W543: create a call-only context so that evaluating the callee body does
# not re-enter the module-initializer binding loop. The callee still sees
# all module-level bindings already established in the outer context.
call_ctx = EvalContext(ctx.root, bind_module_initializers=False)
call_ctx.vars.update(ctx.vars)
call_ctx.current_fn = name
for (pname, ptype), arg in zip(params, args):
arg_bv = _eval_expr_bv(ctx, arg)
if arg_bv is None:
arg_ws = _type_width_signed(ptype)
if arg_ws is None:
return None
arg_bv = Bv(0, *arg_ws)
call_ctx.bind(pname, arg_bv)
# Add local type info for function-local vars.
call_ctx.fn_local_types = ctx.fn_local_types
body = _find_function_body(fn)
if body is None:
return None
return _eval_expr_bv(call_ctx, body)
def _eval_field_bv(ctx: EvalContext, node: Dict[str, Any]) -> Optional[Bv]:
if not _children(node):
return None
base = _children(node)[0]
base_name = _base_name(base)
if base_name is None:
return None
base_type = _resolve_base_type(ctx, base_name)
if base_type is None:
return None
field_name = node.get("name", "")
ftype = _struct_field_type(ctx.decls, base_type, field_name)
if ftype is None:
return None
whole = _eval_expr_bv(ctx, base)
if whole is None:
return None
# Compute offset and width within the packed vector (reverse field order).
struct_decl = ctx.decls.get(f"struct:{base_type}")
if struct_decl is None:
return None
fields = [(f.get("name", ""), f.get("extra_type", "")) for f in _children(struct_decl)]
# Fields are stored LSB-first in the packed vector, so the offset of a field
# is the sum of widths of fields declared before it.
offset = 0
field_width = 1
for fname, fty in fields:
info = _scalar_array_info(fty)
fw = info[0] * info[1] if info else (_TYPE_WIDTH.get(fty) or 1)
if fname == field_name:
field_width = fw
break
offset += fw
# Extract the field bits.
raw = (whole.value >> offset) & ((1 << field_width) - 1)
signed = False
if ftype:
info = _scalar_array_info(ftype)
if info:
signed = info[2]
else:
signed = ftype.strip() in _TYPE_SIGNED
return Bv(raw, field_width, signed)
def _eval_index_bv(ctx: EvalContext, node: Dict[str, Any]) -> Optional[Bv]:
root, indices = _collect_index_chain(node)
if root is None or not indices:
return None
idx_values = [_eval_expr_bv(ctx, idx) for idx in indices]
if any(v is None for v in idx_values):
return None
idxs = [v.as_int() for v in idx_values]
if root.get("kind") == "ExprIdentifier":
base_name = root.get("name", "")
if not base_name:
return None
# W547/W548: use the full declared type (including all array dimensions)
# so that primitive scalar arrays like ``[2][3]i8`` resolve correctly.
full_type = _resolve_full_type(ctx, base_name)
if full_type is not None:
parsed = _parse_array_type(full_type)
if parsed:
dims, elem = parsed
elem_ws = _type_width_signed(elem)
if elem_ws and len(dims) == len(idxs):
# W548: compute row-major flat element index from the full
# index chain. Element ``[i][j]`` of ``[2][3]u8`` is at
# flat index ``i * 3 + j``.
flat = 0
for dim, idx in zip(dims, idxs):
if idx < 0 or idx >= dim:
return None
flat = flat * dim + idx
whole_bv = ctx.vars.get(base_name)
if whole_bv is None:
return None
raw = (whole_bv.value >> (flat * elem_ws[0])) & (
(1 << elem_ws[0]) - 1
)
return Bv(raw, *elem_ws)
return None
if root.get("kind") == "ExprFieldAccess":
# Scalar-struct array field element access: ``aos[i].field[j]``.
# Field arrays are currently one-dimensional.
if len(idxs) != 1:
return None
idx = idxs[0]
base_name = _base_name(root)
if base_name is None:
return None
base_type = _resolve_base_type(ctx, base_name)
if base_type is None:
return None
field_bv = _eval_field_bv(ctx, root)
if field_bv is None:
return None
ftype = _struct_field_type(ctx.decls, base_type, root.get("name", ""))
if ftype is None:
return None
info = _scalar_array_info(ftype)
if info is None:
return None
count, elem_w, signed = info
if idx < 0 or idx >= count:
return None
raw = (field_bv.value >> (idx * elem_w)) & ((1 << elem_w) - 1)
return Bv(raw, elem_w, signed)
return None
def _eval_cast_bv(ctx: EvalContext, node: Dict[str, Any]) -> Optional[Bv]:
if not _children(node):
return None
target = node.get("extra_type", "")
base = target.split("[")[0].strip()
ws = _type_width_signed(base)
if ws is None:
return None
src = _eval_expr_bv(ctx, _children(node)[0])
if src is None:
return None
width, signed = ws
raw = src.value
if width > src.width:
# Sign-extend signed sources, zero-extend unsigned sources.
if src.signed and (raw & (1 << (src.width - 1))):
raw |= ((1 << (width - src.width)) - 1) << src.width
# Bv.__init__ masks/truncates to the target width.
return Bv(raw, width, signed)
def _eval_binary_bv(ctx: EvalContext, node: Dict[str, Any]) -> Optional[Bv]:
if len(_children(node)) < 2:
return None
op = node.get("extra_op", "")
left = _eval_expr_bv(ctx, _children(node)[0])
right = _eval_expr_bv(ctx, _children(node)[1])
if left is None or right is None:
return None
if op in ("&&", "||", "and", "or"):
return Bv(1 if (left.as_int() and right.as_int()) else 0, 1, False)
if op in ("==", "!=", "<", "<=", ">", ">="):
result = _compare_bv(left, op, right)
return Bv(1 if result else 0, 1, False)
res_type = _type_of_expr(ctx, node) or (max(left.width, right.width), left.signed or right.signed)
width, signed = res_type
a = left.as_int()
b = right.as_int()
if op == "+":
return Bv(a + b, width, signed)
if op == "-":
return Bv(a - b, width, signed)
if op == "*":
return Bv(a * b, width, signed)
if op == "/":
if b == 0:
return None
if signed:
return Bv(_signed_div(a, b), width, signed)
return Bv(a // b, width, signed)
if op == "%":
if b == 0:
return None