-
Notifications
You must be signed in to change notification settings - Fork 490
Expand file tree
/
Copy pathgen_config.py
More file actions
executable file
·1508 lines (1242 loc) · 45.6 KB
/
gen_config.py
File metadata and controls
executable file
·1508 lines (1242 loc) · 45.6 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
# Copyright © 2019-2023
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
gen_config.py
Generates configuration macros for:
- Verilog header (-f verilog)
- C/C++ header (-f cpp)
- compiler flags (-f cflags)
Key features:
- Reads defaults from TOML (ordered, sectioned).
- Applies overrides from --cflags and trailing -D... args.
- Supports [[enum]] blocks in TOML to declare enum-typed parameters.
- Supports [[builtin]] blocks in TOML to declare environment-sourced variables used only in expr evaluation.
- Supports [[param]] blocks in TOML to declare parameter variables used only in expr evaluation / unresolved RHS.
- builtin/param variables are NOT emitted to outputs.
- Supports "expr:" values in TOML, with $NAME references.
- supports local/private variables as lowercase definitions to use with expressions.
- Unresolved header mode (default for cpp/verilog): emits preprocessor-friendly
definitions that can be overridden from -D flags.
- Resolved mode (-r/--resolved): fully evaluates expressions and emits
resolved constants (always enabled for cflags).
"""
from __future__ import annotations
import argparse
import ast
import copy
import os
import re
import shlex
import sys
from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Set, Tuple
# -----------------------------
# Tiny TOML Parser
# -----------------------------
class TinyTOML:
def parse(self, content: str) -> Dict[str, Any]:
root: Dict[str, Any] = {}
cursor: Dict[str, Any] = root
for raw in content.splitlines():
# Strip comments (works for your configs; none have '#' inside strings)
line = raw.split("#", 1)[0].strip()
if not line:
continue
if line.startswith("[[") and line.endswith("]]"):
key = line[2:-2].strip()
arr = root.get(key)
if arr is None:
arr = []
root[key] = arr
if not isinstance(arr, list):
raise ValueError(f"TOML key {key!r} used as both table and array-of-tables")
tbl: Dict[str, Any] = {}
arr.append(tbl)
cursor = tbl
continue
if line.startswith("[") and line.endswith("]"):
key = line[1:-1].strip()
tbl = root.get(key)
if tbl is None:
tbl = {}
root[key] = tbl
if not isinstance(tbl, dict):
raise ValueError(f"TOML key {key!r} used as both scalar and table")
cursor = tbl
continue
if "=" in line:
k, v = line.split("=", 1)
key = k.strip()
val = v.strip()
cursor[key] = self._parse_value(val)
continue
raise ValueError(f"Unrecognized TOML line: {raw!r}")
return root
def _parse_value(self, val: str) -> Any:
if val == "true": return True
if val == "false": return False
try:
return ast.literal_eval(val)
except (ValueError, SyntaxError):
return val
def _load_toml(path: str) -> Dict[str, Any]:
with open(path, "r", encoding="utf-8") as f:
return TinyTOML().parse(f.read())
# -----------------------------
# Basics
# -----------------------------
_PUBLIC_SCOPE_RE = re.compile(r"^[A-Z0-9_]+$")
_DOLLAR_IDENT_RE = re.compile(r"\$([A-Za-z_][A-Za-z0-9_]*)")
_DOLLAR_BRACE_RE = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}")
_BACKTICK_EXPR_RE = re.compile(r"^`(.+)`$")
_INT_RE = re.compile(r"^[+-]?\d+$")
_HEX_TOKEN_RE = re.compile(r"^\s*0[xX]([0-9A-Fa-f_]+)\s*$")
_HEX_ASSIGN_RE = re.compile(r"^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(0[xX][0-9A-Fa-f_]+)\s*(?:#.*)?$")
def _has_public_scope(name: str) -> bool:
return _PUBLIC_SCOPE_RE.fullmatch(name) is not None
def _preprocess_expr(expr: str) -> str:
expr = _DOLLAR_BRACE_RE.sub(r"\1", expr)
expr = _DOLLAR_IDENT_RE.sub(r"\1", expr)
return expr
def _is_expr_string(v: Any) -> bool:
if not isinstance(v, str):
return False
s = v.strip()
return s.startswith("expr:") or (_BACKTICK_EXPR_RE.fullmatch(s) is not None)
def _extract_expr(v: str) -> Optional[str]:
s = v.strip()
if s.startswith("expr:"):
return s[len("expr:"):].strip()
m = _BACKTICK_EXPR_RE.fullmatch(s)
if m:
return m.group(1).strip()
return None
def _scalar(s: str) -> Any:
ss = s.strip()
if ss.lower() in ("true", "false"):
return (ss.lower() == "true")
if _INT_RE.fullmatch(ss):
return int(ss, 10)
if (ss.startswith('"') and ss.endswith('"')) or (ss.startswith("'") and ss.endswith("'")):
return ss[1:-1]
return ss
def _truthy(v: Any) -> bool:
if isinstance(v, bool):
return v
if isinstance(v, int):
return v != 0
if isinstance(v, str):
s = v.strip().lower()
if s in ("0", "false", "no", "off", ""):
return False
if s in ("1", "true", "yes", "on"):
return True
return True
return bool(v)
def _cpp_quote(s: str) -> str:
return '"' + s.replace("\\", "\\\\").replace('"', '\\"') + '"'
# -----------------------------
# Hex metadata (TOML source scan)
# -----------------------------
@dataclass(frozen=True)
class HexMeta:
digits: str
width: int # exact nibble width in bits = 4 * len(digits)
def _scan_hex_literals(toml_path: str) -> Dict[str, HexMeta]:
out: Dict[str, HexMeta] = {}
in_enum = False
in_builtin = False
in_param = False
with open(toml_path, "r", encoding="utf-8") as f:
for raw_line in f:
line = raw_line.rstrip("\n")
s = line.strip()
if not s:
continue
if s.startswith("[[") and s.endswith("]]"):
in_enum = (s == "[[enum]]")
in_builtin = (s == "[[builtin]]")
in_param = (s == "[[param]]")
continue
if s.startswith("[") and s.endswith("]"):
in_enum = False
in_builtin = False
in_param = False
continue
if in_enum or in_builtin or in_param:
continue
if "=" in line:
rhs = line.split("=", 1)[1].lstrip()
if rhs.startswith('"') or rhs.startswith("'"):
continue
m = _HEX_ASSIGN_RE.match(line)
if not m:
continue
key = m.group(1)
lit = m.group(2)
digits = lit[2:].replace("_", "")
width = 4 * len(digits)
out[key] = HexMeta(digits=digits.upper(), width=width)
return out
def _format_int_literal(dkind: str, key: str, value: int, hex_meta: Dict[str, HexMeta]) -> str:
hm = hex_meta.get(key)
if hm is None:
# A bare decimal literal is implicitly 32-bit in Verilog; a value
# outside the signed-32-bit range is silently truncated by strict
# tools (e.g. Vivado synthesis). Emit a sized hex literal instead so
# the full value survives — address/size constants can exceed 2**31.
if dkind == "sv" and value >= 2**31:
digits = f"{value:X}"
return f"{4 * len(digits)}'h{digits}"
return str(value)
if dkind == "sv": # verilog-style literal
return f"{hm.width}'h{hm.digits}"
return "0x" + hm.digits
def _format_int_from_expr_source(dkind: str, value_node: ast.AST, value: int, expr_src: str) -> str:
seg = ast.get_source_segment(expr_src, value_node) or ""
m = _HEX_TOKEN_RE.match(seg)
if not m:
return str(value)
digits = m.group(1).replace("_", "").upper()
width = 4 * len(digits)
if dkind == "sv":
return f"{width}'h{digits}"
return "0x" + digits
# -----------------------------
# TOML layout (ordered + sections)
# -----------------------------
@dataclass
class Layout:
sections: List[Tuple[Optional[str], List[str]]]
ordered_keys: List[str]
key_to_section: Dict[str, Optional[str]]
def _flatten_with_layout(toml_data: Dict[str, Any]) -> Tuple[Dict[str, Any], Layout]:
flat: Dict[str, Any] = {}
sections: List[Tuple[Optional[str], List[str]]] = []
ordered: List[str] = []
k2s: Dict[str, Optional[str]] = {}
root_keys: List[str] = []
for top_k, top_v in toml_data.items():
if top_k in ("enum", "builtin", "param"):
continue
if isinstance(top_v, dict):
sec_keys: List[str] = []
for k, v in top_v.items():
flat[k] = v
sec_keys.append(k)
ordered.append(k)
k2s[k] = top_k
sections.append((top_k, sec_keys))
else:
flat[top_k] = top_v
root_keys.append(top_k)
ordered.append(top_k)
k2s[top_k] = None
if root_keys:
sections.insert(0, (None, root_keys))
return flat, Layout(sections=sections, ordered_keys=ordered, key_to_section=k2s)
# -----------------------------
# Enums (declared in TOML with [[enum]])
# -----------------------------
@dataclass(frozen=True)
class EnumSpec:
values: List[Any]
def _load_enums(toml_data: Dict[str, Any]) -> Dict[str, EnumSpec]:
enums = toml_data.get("enum", None)
if enums is None:
return {}
if not isinstance(enums, list):
raise ValueError("TOML 'enum' must be an array of tables (use [[enum]])")
out: Dict[str, EnumSpec] = {}
for i, item in enumerate(enums):
if not isinstance(item, dict) or len(item) == 0:
raise ValueError(f"enum[{i}] must be a non-empty table like: [[enum]] XLEN=[32,64]")
for name, values in item.items():
if not isinstance(values, list) or len(values) == 0:
raise ValueError(f"enum[{i}].{name} must be a non-empty list")
if name in out:
raise ValueError(f"Duplicate enum name: {name}")
norm: List[Any] = []
for v in values:
if isinstance(v, str):
norm.append(_scalar(v))
else:
norm.append(v)
out[name] = EnumSpec(values=norm)
return out
# -----------------------------
# Builtins / Params (declared in TOML with [[builtin]] / [[param]])
# -----------------------------
@dataclass(frozen=True)
class VarSpec:
typ: str # "bool" | "int" | "string"
def _load_var_table(toml_data: Dict[str, Any], key: str) -> Dict[str, VarSpec]:
arr = toml_data.get(key, None)
if arr is None:
return {}
if not isinstance(arr, list):
raise ValueError(f"TOML '{key}' must be an array of tables (use [[{key}]])")
out: Dict[str, VarSpec] = {}
for i, item in enumerate(arr):
if not isinstance(item, dict) or len(item) == 0:
raise ValueError(f"Each [[{key}]] must be a non-empty table, e.g. [[{key}]] FOO=\"bool\"")
for name, typ in item.items():
if not isinstance(name, str) or not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", name):
raise ValueError(f"Invalid {key} name: {name!r}")
if name in out:
raise ValueError(f"Duplicate {key} name: {name}")
if not isinstance(typ, str):
raise ValueError(
f"{key} type for {name} must be a string (TOML requires quotes), e.g. {name}=\"int\""
)
t = typ.strip().lower()
if t not in ("bool", "int", "string"):
raise ValueError(f"Unsupported {key} type for {name}: {typ!r} (use \"bool\"|\"int\"|\"string\")")
out[name] = VarSpec(typ=t)
return out
def _var_default(spec: VarSpec) -> Any:
if spec.typ == "bool":
return False
if spec.typ == "int":
return 0
return ""
def _coerce_env(raw: str, spec: VarSpec) -> Any:
"""Cast an environment-variable string to a [[builtin]]'s declared type."""
if spec.typ == "bool":
return _truthy(raw)
if spec.typ == "int":
try:
return int(raw.strip(), 0)
except ValueError:
return _var_default(spec)
return raw
# -----------------------------
# -D parsing + overrides
# -----------------------------
@dataclass
class Define:
name: str
value: Optional[str]
def _parse_defines(tokens: List[str]) -> List[Define]:
out: List[Define] = []
for tok in tokens:
if not tok.startswith("-D"):
continue
item = tok[2:]
if not item:
continue
if "=" in item:
n, v = item.split("=", 1)
out.append(Define(name=n.strip(), value=v.strip()))
else:
out.append(Define(name=item.strip(), value=None))
return out
def _parse_defines_from_cflags(cflags: str) -> List[Define]:
if not cflags:
return []
return _parse_defines(shlex.split(cflags))
def _apply_overrides(defs: List[Define], enums: Dict[str, EnumSpec]) -> Tuple[Dict[str, Any], Set[str]]:
overrides: Dict[str, Any] = {}
explicit: Set[str] = set()
def set_enum(name: str, val: Any) -> None:
spec = enums[name]
if val not in spec.values:
raise ValueError(f"Invalid value for {name}: {val} (allowed: {spec.values})")
overrides[name] = val
explicit.add(name)
for d in defs:
if d.name.endswith("_DISABLE"):
base = d.name[:-8]
en = f"{base}_ENABLE"
dis = True if d.value is None else _truthy(_scalar(d.value))
if dis:
overrides[en] = False
explicit.add(en)
continue
if d.name in enums:
if d.value is None:
raise ValueError(f"Enum override requires value: -D{d.name}=<value> or -D{d.name}_<value>")
set_enum(d.name, _scalar(d.value))
continue
if "_" in d.name and d.value is None:
base, suffix = d.name.rsplit("_", 1)
if base in enums:
set_enum(base, _scalar(suffix))
overrides[d.name] = True
explicit.add(d.name)
continue
if d.value is None:
overrides[d.name] = True
explicit.add(d.name)
else:
overrides[d.name] = _scalar(d.value)
explicit.add(d.name)
return overrides, explicit
# -----------------------------
# Dialect helpers
# -----------------------------
@dataclass(frozen=True)
class Dialect:
kind: str # "c" or "sv"
def ifndef(self) -> str:
return "#ifndef" if self.kind == "c" else "`ifndef"
def ifdef(self) -> str:
return "#ifdef" if self.kind == "c" else "`ifdef"
def else_(self) -> str:
return "#else" if self.kind == "c" else "`else"
def endif(self) -> str:
return "#endif" if self.kind == "c" else "`endif"
def define(self) -> str:
return "#define" if self.kind == "c" else "`define"
def undef(self) -> str:
return "#undef" if self.kind == "c" else "`undef"
def ref(self, name: str) -> str:
return name if self.kind == "c" else f"`{name}"
def _make_guard_macro(output_path: Optional[str], fallback: str) -> str:
if not output_path:
return fallback
base = os.path.basename(output_path)
base = re.sub(r"[^A-Za-z0-9]", "_", base).upper()
if not base:
return fallback
if base[0].isdigit():
base = "_" + base
return base
# -----------------------------
# Builtin helpers in unresolved mode
# -----------------------------
class HelperSpec:
fn: str
macro: str
def emit(self, d: Dialect) -> List[str]:
raise NotImplementedError
def translate_call(self, d: Dialect, args: List[str]) -> str:
raise NotImplementedError
def _guarded_macro(d: Dialect, name: str, body: str) -> List[str]:
return [
f"{d.ifndef()} {name}",
f"{d.define()} {name}{body}",
f"{d.endif()}",
"",
]
def _fold_binary(macro_call: str, args: List[str]) -> str:
if len(args) == 0:
return "0"
if len(args) == 1:
return args[0]
s = f"{macro_call}({args[0]}, {args[1]})"
for x in args[2:]:
s = f"{macro_call}({s}, {x})"
return s
class MinHelper(HelperSpec):
fn = "min"
macro = "__MIN"
def emit(self, d: Dialect) -> List[str]:
return _guarded_macro(d, self.macro, "(a,b) (((a) < (b)) ? (a) : (b))")
def translate_call(self, d: Dialect, args: List[str]) -> str:
return _fold_binary(d.ref(self.macro), args)
class MaxHelper(HelperSpec):
fn = "max"
macro = "__MAX"
def emit(self, d: Dialect) -> List[str]:
return _guarded_macro(d, self.macro, "(a,b) (((a) > (b)) ? (a) : (b))")
def translate_call(self, d: Dialect, args: List[str]) -> str:
return _fold_binary(d.ref(self.macro), args)
class UpHelper(HelperSpec):
fn = "up"
macro = "__UP"
def emit(self, d: Dialect) -> List[str]:
return _guarded_macro(d, self.macro, "(x) (((x) != 0) ? (x) : 1)")
def translate_call(self, d: Dialect, args: List[str]) -> str:
if len(args) != 1:
return "0"
return f"{d.ref(self.macro)}({args[0]})"
class ClampHelper(HelperSpec):
fn = "clamp"
macro = "__CLAMP"
def emit(self, d: Dialect) -> List[str]:
return _guarded_macro(
d,
self.macro,
"(x,lo,hi) (((x) > (hi)) ? (hi) : (((x) < (lo)) ? (lo) : (x)))",
)
def translate_call(self, d: Dialect, args: List[str]) -> str:
if len(args) != 3:
return "0"
return f"{d.ref(self.macro)}({args[0]}, {args[1]}, {args[2]})"
class PowHelper(HelperSpec):
fn = "pow"
macro = "__POW"
def emit(self, d: Dialect) -> List[str]:
if d.kind == "sv":
return _guarded_macro(d, self.macro, "(x,y) ((x) ** (y))")
# constexpr-compatible recursive inline function — usable in constexpr contexts.
return [
f"{d.ifndef()} {self.macro}",
f"{d.define()} {self.macro}(x, y) __vx_cfg_pow((x), (y))",
"static inline constexpr long long __vx_cfg_pow(long long b, long long e) {",
" return (e <= 0) ? 1 : b * __vx_cfg_pow(b, e - 1);",
"}",
f"{d.endif()}",
"",
]
def translate_call(self, d: Dialect, args: List[str]) -> str:
if len(args) != 2:
return "0"
return f"{d.ref(self.macro)}({args[0]}, {args[1]})"
class Clog2Helper(HelperSpec):
fn = "clog2"
macro = "__CLOG2"
def emit(self, d: Dialect) -> List[str]:
if d.kind == "sv":
return _guarded_macro(d, self.macro, "(x) ($clog2(x))")
# constexpr-compatible recursive inline function — usable in constexpr contexts.
return [
f"{d.ifndef()} {self.macro}",
f"{d.define()} {self.macro}(x) __vx_cfg_clog2((long long)(x))",
"static inline constexpr int __vx_cfg_clog2_impl(long long v, int acc) {",
" return (v <= 1) ? acc : __vx_cfg_clog2_impl((v + 1) / 2, acc + 1);",
"}",
"static inline constexpr int __vx_cfg_clog2(long long x) {",
" return (x <= 1) ? 0 : __vx_cfg_clog2_impl(x, 0);",
"}",
f"{d.endif()}",
"",
]
def translate_call(self, d: Dialect, args: List[str]) -> str:
if len(args) != 1:
return "0"
return f"{d.ref(self.macro)}({args[0]})"
HELPERS: Dict[str, HelperSpec] = {
"min": MinHelper(),
"max": MaxHelper(),
"up": UpHelper(),
"clamp": ClampHelper(),
"pow": PowHelper(),
"clog2": Clog2Helper(),
}
def _helpers_used(expr: str) -> Set[str]:
expr2 = _preprocess_expr(expr)
tree = ast.parse(expr2, mode="eval")
used: Set[str] = set()
for n in ast.walk(tree):
if isinstance(n, ast.Call) and isinstance(n.func, ast.Name):
if n.func.id in HELPERS:
used.add(n.func.id)
return used
# -----------------------------
# Lowercase-local inlining
# -----------------------------
# Lowercase keys (failing _has_public_scope) are private symbols used only at
# expression-evaluation time. They are never emitted as macros, so any reference
# to one in unresolved output must be substituted with the local's expression.
def _stamp_locations(subtree: ast.AST, src: ast.AST) -> ast.AST:
ln = getattr(src, "lineno", 1)
co = getattr(src, "col_offset", 0)
end_ln = getattr(src, "end_lineno", None)
end_co = getattr(src, "end_col_offset", None)
for n in ast.walk(subtree):
n.lineno = ln
n.col_offset = co
if end_ln is not None:
n.end_lineno = end_ln
n.end_col_offset = end_co
return subtree
def _build_local_asts(toml_defs: Dict[str, Any]) -> Dict[str, ast.AST]:
raw_locals: Dict[str, Any] = {k: v for k, v in toml_defs.items() if not _has_public_scope(k)}
cache: Dict[str, ast.AST] = {}
visiting: Set[str] = set()
def parse_raw(raw: Any) -> ast.AST:
if _is_expr_string(raw):
expr = _extract_expr(str(raw))
if expr is None:
raise ValueError(f"Bad expr syntax in local: {raw}")
expr2 = _preprocess_expr(expr)
return ast.parse(expr2, mode="eval").body
v = _scalar(raw) if isinstance(raw, str) else raw
return ast.parse(repr(v), mode="eval").body
def resolve(key: str) -> ast.AST:
if key in cache:
return cache[key]
if key in visiting:
raise ValueError(f"Cycle in lowercase-local references involving '{key}'")
visiting.add(key)
class T(ast.NodeTransformer):
def visit_Name(self, n: ast.Name) -> ast.AST:
if n.id in raw_locals:
return _stamp_locations(copy.deepcopy(resolve(n.id)), n)
return n
node = T().visit(parse_raw(raw_locals[key]))
cache[key] = node
visiting.remove(key)
return node
for k in raw_locals:
resolve(k)
return cache
def _inline_locals_into(node: ast.AST, locals_ast: Dict[str, ast.AST]) -> ast.AST:
if not locals_ast:
return node
class T(ast.NodeTransformer):
def visit_Name(self, n: ast.Name) -> ast.AST:
if n.id in locals_ast:
return _stamp_locations(copy.deepcopy(locals_ast[n.id]), n)
return n
return T().visit(node)
# -----------------------------
# Unresolved macro expression translator
# -----------------------------
class MacroExprTranslator:
def __init__(self, d: Dialect, params: Set[str], expr_src: Optional[str] = None) -> None:
self.d = d
self.params = params
self.expr_src = expr_src
def translate(self, expr: str, current_key: Optional[str], enums: Dict[str, EnumSpec]) -> str:
expr2 = _preprocess_expr(expr)
tree = ast.parse(expr2, mode="eval")
self.expr_src = expr2
return self._emit(tree.body, current_key=current_key, enums=enums)
def _name_ref(self, name: str) -> str:
if self.d.kind == "sv" and name in self.params:
# [[param]] symbols are RTL-provided localparams. The SV side uses the
# short, un-prefixed name (VX_gpu_pkg localparam convention); the
# C side keeps VX_CFG_* (no package scoping there).
return name[len("VX_CFG_"):] if name.startswith("VX_CFG_") else name
return self.d.ref(name)
def _emit(self, node: ast.AST, current_key: Optional[str], enums: Dict[str, EnumSpec]) -> str:
if isinstance(node, ast.Constant):
if isinstance(node.value, bool):
return "1" if node.value else "0"
if node.value is None:
return "0"
if isinstance(node.value, int):
if self.expr_src is not None:
return _format_int_from_expr_source(self.d.kind, node, node.value, self.expr_src)
return str(node.value)
if isinstance(node.value, str):
if current_key is not None and current_key in enums:
if re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", node.value):
return node.value
return _cpp_quote(node.value)
return str(node.value)
if isinstance(node, ast.Name):
return self._name_ref(node.id)
if isinstance(node, ast.BoolOp):
join = " && " if isinstance(node.op, ast.And) else " || "
parts = [self._emit(v, current_key, enums) for v in node.values]
return "(" + join.join(f"({p})" for p in parts) + ")"
if isinstance(node, ast.UnaryOp):
if isinstance(node.op, ast.USub):
return f"(-({self._emit(node.operand, current_key, enums)}))"
if isinstance(node.op, ast.Not):
return f"(!({self._emit(node.operand, current_key, enums)}))"
return f"({self._emit(node.operand, current_key, enums)})"
if isinstance(node, ast.BinOp):
a = self._emit(node.left, current_key, enums)
b = self._emit(node.right, current_key, enums)
op = node.op
if isinstance(op, (ast.Div, ast.FloorDiv)):
return f"(({a}) / ({b}))"
if isinstance(op, ast.Mult):
return f"(({a}) * ({b}))"
if isinstance(op, ast.Add):
return f"(({a}) + ({b}))"
if isinstance(op, ast.Sub):
return f"(({a}) - ({b}))"
if isinstance(op, ast.LShift):
return f"(({a}) << ({b}))"
if isinstance(op, ast.RShift):
return f"(({a}) >> ({b}))"
if isinstance(op, ast.BitOr):
return f"(({a}) | ({b}))"
if isinstance(op, ast.BitAnd):
return f"(({a}) & ({b}))"
if isinstance(op, ast.BitXor):
return f"(({a}) ^ ({b}))"
if isinstance(op, ast.Mod):
return f"(({a}) % ({b}))"
raise ValueError(f"Unsupported BinOp: {type(op).__name__}")
if isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
fn = node.func.id
args = [self._emit(a, current_key, enums) for a in node.args]
h = HELPERS.get(fn)
if h is not None:
return h.translate_call(self.d, args)
if fn == "int" and len(args) == 1:
return f"({args[0]})"
if fn == "bool" and len(args) == 1:
return f"(({args[0]}) ? 1 : 0)"
raise ValueError(f"Unsupported function '{fn}' in unresolved macro expr")
if isinstance(node, ast.IfExp):
raise ValueError("Conditional expressions must be emitted via `ifdef trees, not as RHS")
raise ValueError(f"Unsupported AST node in unresolved macro expr: {type(node).__name__}")
# -----------------------------
# Unresolved conditional emission
# -----------------------------
def _emit_test_tree(lines: List[str], d: Dialect, test: ast.AST, emit_true, emit_false) -> None:
if isinstance(test, ast.Name):
lines.append(f"{d.ifdef()} {test.id}")
emit_true()
lines.append(d.else_())
emit_false()
lines.append(d.endif())
return
if isinstance(test, ast.UnaryOp) and isinstance(test.op, ast.Not) and isinstance(test.operand, ast.Name):
lines.append(f"{d.ifndef()} {test.operand.id}")
emit_true()
lines.append(d.else_())
emit_false()
lines.append(d.endif())
return
if isinstance(test, ast.BoolOp) and isinstance(test.op, ast.And):
vals = list(test.values)
def emit_and(idx: int) -> None:
if idx >= len(vals):
emit_true()
return
t = vals[idx]
def t_true():
emit_and(idx + 1)
def t_false():
emit_false()
_emit_test_tree(lines, d, t, t_true, t_false)
emit_and(0)
return
if isinstance(test, ast.BoolOp) and isinstance(test.op, ast.Or):
vals = list(test.values)
def emit_or(idx: int) -> None:
if idx >= len(vals):
emit_false()
return
t = vals[idx]
def t_true():
emit_true()
def t_false():
emit_or(idx + 1)
_emit_test_tree(lines, d, t, t_true, t_false)
emit_or(0)
return
raise ValueError("Unresolved boolean/conditional test must use only $FLAG / not $FLAG / ($A and $B) / ($A or $B)")
def _is_pure_flag_test(node: ast.AST) -> bool:
if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not) and isinstance(node.operand, ast.Name):
return True
if isinstance(node, ast.BoolOp) and isinstance(node.op, (ast.And, ast.Or)):
def _leaf_ok(n: ast.AST) -> bool:
if isinstance(n, ast.Name):
return True
if isinstance(n, ast.UnaryOp) and isinstance(n.op, ast.Not) and isinstance(n.operand, ast.Name):
return True
if isinstance(n, ast.BoolOp) and isinstance(n.op, (ast.And, ast.Or)):
return all(_leaf_ok(v) for v in n.values)
return False
return _leaf_ok(node)
return False
def _emit_unresolved_define_value(lines: List[str], d: Dialect, key: str, value_node: ast.AST,
enums: Dict[str, EnumSpec], expr_src: str, params: Set[str]) -> None:
if key in enums:
if isinstance(value_node, ast.Constant) and isinstance(value_node.value, str):
v = value_node.value
if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", v):
raise ValueError(f"Enum {key} value must be identifier-like, got: {v!r}")
lines.append(f"{d.define()} {key} {v}")
lines.append(f"{d.define()} {key}_{v}")
return
if isinstance(value_node, ast.Constant) and isinstance(value_node.value, int):
v = value_node.value
lines.append(f"{d.define()} {key} {v}")
lines.append(f"{d.define()} {key}_{v}")
return
raise ValueError(f"Enum {key} unresolved branch must yield a string/int literal")
if isinstance(value_node, ast.Constant) and isinstance(value_node.value, int):
rhs = _format_int_from_expr_source(d.kind, value_node, value_node.value, expr_src)
lines.append(f"{d.define()} {key} {rhs}".rstrip())
return
tr = MacroExprTranslator(d, params=params, expr_src=expr_src)
rhs = tr._emit(value_node, current_key=None, enums=enums)
lines.append(f"{d.define()} {key} {rhs}".rstrip())
def _emit_unresolved_conditional(lines: List[str], d: Dialect, key: str, node: ast.IfExp,
enums: Dict[str, EnumSpec], expr_src: str, params: Set[str]) -> None:
def emit_true():
if isinstance(node.body, ast.IfExp):
_emit_unresolved_conditional(lines, d, key, node.body, enums, expr_src, params)
else:
_emit_unresolved_define_value(lines, d, key, node.body, enums, expr_src, params)
def emit_false():
if isinstance(node.orelse, ast.IfExp):
_emit_unresolved_conditional(lines, d, key, node.orelse, enums, expr_src, params)
else:
_emit_unresolved_define_value(lines, d, key, node.orelse, enums, expr_src, params)
_emit_test_tree(lines, d, node.test, emit_true, emit_false)
def _emit_unresolved_boolean_define(lines: List[str], d: Dialect, key: str, test: ast.AST, add_blank: bool = True) -> None:
lines.append(f"{d.ifndef()} {key}")
def t_true():
lines.append(f"{d.define()} {key}")
def t_false():
return
_emit_test_tree(lines, d, test, t_true, t_false)
lines.append(d.endif())
if add_blank:
lines.append("")
def _emit_unresolved_key(lines: List[str], d: Dialect, key: str, raw: Any,
enums: Dict[str, EnumSpec], hex_meta: Dict[str, HexMeta],
params: Set[str], locals_ast: Dict[str, ast.AST]) -> None:
if not _has_public_scope(key):
return
# enum handling unchanged...
if key in enums:
for v in enums[key].values:
flag = f"{key}_{v}"
lines.append(f"{d.ifdef()} {flag}")
lines.append(f"{d.undef()} {key}")
lines.append(f"{d.define()} {key} {v}")
lines.append(d.endif())
lines.append("")
for v in enums[key].values:
lines.append(f"{d.ifndef()} {key}_{v}")
lines.append(f"{d.ifndef()} {key}")
if _is_expr_string(raw):
expr = _extract_expr(str(raw))
if expr is None:
raise ValueError(f"Bad expr syntax for {key}: {raw}")