Repository navigation
Expand file tree
/
Copy path_codegen_core.py
More file actions
487 lines (398 loc) · 18.4 KB
/
Copy path_codegen_core.py
File metadata and controls
487 lines (398 loc) · 18.4 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
# Copyright (c) 2026 Jonathan Embley-Riches. All rights reserved.
"""URLab codegen — core shared data + helpers.
Dependency root. Owns:
- ``DiagBuffer`` — the diagnostics buffer the orchestrator + checks
share.
- ``_UE_TYPE_INFO`` — single source of truth for every UE type
codegen can emit; ``_UE_TYPE_FAMILY`` and
``_UE_TYPES_ACCEPTING_UNITS_META`` are derived views.
- Naming helpers, schema readers, canon-iteration helpers.
- The 5-strategy ``_resolve_mjs_field`` chain — the bridge between
MJCF attr names and the C struct field names MuJoCo picks.
- ``_resolve_value_map`` — the xml_enum value-map reader.
- ``FileWrite`` — the data class every emitter produces.
Read-only against rules / schema / snapshot. No file writes, no
UPROPERTY emission, no .cpp injection. ``generate_ue_components``
and ``_codegen_checks`` both import from here.
"""
from __future__ import annotations
import re
import sys
from dataclasses import dataclass
from typing import Any, Dict, Iterable, Iterator, List, Optional, Sequence, Set, Tuple
# ---------------------------------------------------------------------------
# Diagnostics
# ---------------------------------------------------------------------------
@dataclass
class Diagnostic:
"""A non-fatal codegen warning. Collected by ``_diag_add`` during a
run and flushed once at the end via ``_diag_flush``."""
message: str
source: str = "" # short tag for grouping (e.g. "schema_drift")
class DiagBuffer:
"""Collects codegen diagnostics during a run. ``pending`` is the
queue of unflushed entries; ``fired_count`` survives the flush so
``main()`` can check whether ``--strict`` should exit non-zero."""
def __init__(self) -> None:
self.pending: List[Diagnostic] = []
self.fired_count: int = 0
def add(self, message: str, *, source: str = "") -> None:
self.pending.append(Diagnostic(message=message, source=source))
def flush(self) -> None:
"""Print collected diagnostics to stderr, advance ``fired_count``
by the number flushed, and clear the pending list."""
if not self.pending:
return
print(f"\n--- codegen diagnostics ({len(self.pending)}) ---",
file=sys.stderr)
for d in self.pending:
print(d.message, file=sys.stderr)
print(
"(diagnostics are non-fatal; the codegen has emitted what it "
"can — fix the rules to silence them.)",
file=sys.stderr,
)
self.fired_count += len(self.pending)
self.pending.clear()
def reset(self) -> None:
self.pending.clear()
self.fired_count = 0
_DIAGS_BUFFER = DiagBuffer()
def _diag_add(message: str, *, source: str = "") -> None:
_DIAGS_BUFFER.add(message, source=source)
def _diag_flush() -> None:
_DIAGS_BUFFER.flush()
def _reset_diags() -> None:
"""Reset the diag buffer between runs so back-to-back invocations
in the same Python process (test runners, integration shells)
don't carry stale state."""
_DIAGS_BUFFER.reset()
# ---------------------------------------------------------------------------
# UE type registry
# ---------------------------------------------------------------------------
@dataclass(frozen=True)
class _UEType:
"""Single source of truth for a UE type codegen can emit. Every per-
type dispatch (default initializer, drift-check shape, UHT Units-meta
gate) reads this row instead of redeclaring the type universe."""
default_init: str # C++ initializer (e.g. ``"0.0f"``)
shape: Tuple[str, Any] # drift-check shape (see _classify_c_type)
accepts_units_meta: bool # UHT allows Units="..." on this type
# Every UE type codegen can target. ``_attr_default_value``,
# ``_UE_TYPE_FAMILY``, and ``_UE_TYPES_ACCEPTING_UNITS_META`` below are
# thin views over this dict.
_UE_TYPE_INFO: Dict[str, _UEType] = {
"float": _UEType("0.0f", ("scalar", "num"), True),
"double": _UEType("0.0", ("scalar", "num"), True),
"int32": _UEType("0", ("scalar", "int"), True),
"uint8": _UEType("0", ("scalar", "int"), True), # synth-mirror only
"bool": _UEType("false", ("scalar", "bool"), False),
"FString": _UEType('TEXT("")', ("scalar", "string"), False),
"FVector": _UEType("FVector::ZeroVector", ("vec", 3), True),
"FQuat": _UEType("FQuat::Identity", ("vec", 4), False),
"FLinearColor": _UEType("FLinearColor::White", ("vec", 4), False),
"TArray<float>": _UEType("{}", ("array", None), False),
"TArray<int32>": _UEType("{}", ("array", None), False),
}
def _attr_default_value(ue_type: str) -> str:
info = _UE_TYPE_INFO.get(ue_type)
if info is not None:
return info.default_init
# Unknown types fall through to the default-construct literal — same
# for novel TArray<...> entries (e.g. TArray<UObject*>) the registry
# doesn't enumerate.
return "{}"
# UE type → shape for ``_check_type_shape_drift``. Derived from
# ``_UE_TYPE_INFO`` so the type universe is declared once.
_UE_TYPE_FAMILY = {k: v.shape for k, v in _UE_TYPE_INFO.items()}
_UE_TYPES_ACCEPTING_UNITS_META = {
k for k, v in _UE_TYPE_INFO.items() if v.accepts_units_meta
}
def _ue_type_accepts_units_meta(ue_type: str) -> bool:
"""UHT enforces 'Units' meta only on numeric scalars + numeric
structs. Returns False for TArray<...>, FString, FLinearColor,
FQuat — codegen silently drops the Units meta for those types so
the build succeeds."""
info = _UE_TYPE_INFO.get(ue_type)
return bool(info and info.accepts_units_meta)
_DYNAMIC_VEC_TYPES = {
"mjFloatVec", "mjDoubleVec", "mjIntVec", "mjStringVec",
"mjFloatVecVec", "mjDoubleVecVec", "mjIntVecVec",
}
_KNOWN_UE_UNITS = {
# UE5 numeric units the editor knows how to render + (optionally)
# convert via Display Units preferences.
"m", "cm", "mm", "km",
"rad", "deg",
}
@dataclass
class FileWrite:
"""One file write the codegen would perform. Collected during the
phase walk; ``apply_writes`` either flushes them to disk, prints
diffs, or returns the count under ``--check``."""
path: str
content: str
def override_toggle_name(prop_name: str) -> str:
"""``bOverride_<X>`` is the codegen-emitted toggle field that
gates whether the corresponding UPROPERTY's value gets written
back to the mjs struct."""
return f"bOverride_{prop_name}"
# ---------------------------------------------------------------------------
# Rule-iteration helpers
# ---------------------------------------------------------------------------
def iter_canon_absorbed(elem_canons: Iterable[str],
canonicalizations: Dict[str, Any]) -> Iterator[str]:
"""Yield every attr absorbed by any canonicalisation in
``elem_canons``. Skips unknown canon keys silently — diagnostics
for those live in the rule-validity drift checks."""
if not canonicalizations:
return
for c in elem_canons:
cd = canonicalizations.get(c)
if cd:
yield from cd.get("absorbs_attrs", ())
def compute_canon_absorbed(elem_canons: Iterable[str],
canonicalizations: Dict[str, Any]) -> Set[str]:
return set(iter_canon_absorbed(elem_canons, canonicalizations))
def iter_category_attrs(attrs: Iterable[str], *,
global_excl: Set[str],
elem_excl: Set[str],
canon_absorbed: Set[str],
extra_excl: Optional[Set[str]] = None) -> Iterator[str]:
"""Yield attrs that pass the standard codegen exclusion gates plus
any site-specific ``extra_excl`` set the caller assembles
(xml_enum_attrs, target-collation-absorbed, etc — these vary per
emission stage)."""
for attr in attrs:
if attr in global_excl or attr in elem_excl or attr in canon_absorbed:
continue
if extra_excl is not None and attr in extra_excl:
continue
yield attr
# ---------------------------------------------------------------------------
# Schema readers
# ---------------------------------------------------------------------------
def schema_attrs(schema: Dict[str, Any], path: str) -> List[str]:
"""Read an attribute list at a dotted path, e.g.
``actuator_common.attrs``. Returns [] if missing."""
cur: Any = schema
for piece in path.split("."):
if isinstance(cur, dict) and piece in cur:
cur = cur[piece]
else:
return []
if isinstance(cur, list):
if cur and isinstance(cur[0], str):
return list(cur)
attrs: List[str] = []
for entry in cur:
if isinstance(entry, dict):
if "attrs" in entry and isinstance(entry["attrs"], list):
attrs.extend([str(x) for x in entry["attrs"]])
else:
for v in entry.values():
if isinstance(v, list):
attrs.extend([str(x) for x in v])
seen = set()
out = []
for a in attrs:
if a not in seen:
seen.add(a)
out.append(a)
return out
if isinstance(cur, dict):
attrs2: List[str] = []
for v in cur.values():
if isinstance(v, list):
attrs2.extend([str(x) for x in v if isinstance(x, str)])
return attrs2
return []
def schema_subtype_attrs(schema: Dict[str, Any], category: str,
subtype_key: str) -> List[str]:
"""Look up per-subtype attrs from schema['actuator_types'][key] /
schema['sensor_types'] (list-of-dict). Returns [] if not found."""
if category == "actuator":
block = schema.get("actuator_types", {})
if isinstance(block, dict):
entry = block.get(subtype_key)
if isinstance(entry, list):
return [str(x) for x in entry]
if isinstance(entry, dict) and "attrs" in entry:
return [str(x) for x in entry["attrs"]]
return []
if category == "sensor":
block = schema.get("sensor_types", [])
if isinstance(block, list):
for entry in block:
if isinstance(entry, dict) and entry.get("name") == subtype_key:
attrs = entry.get("attrs", [])
return [str(x) for x in attrs] if isinstance(attrs, list) else []
if isinstance(entry, str) and entry == subtype_key:
return []
return []
return []
# ---------------------------------------------------------------------------
# C-type classifier (drift-check inputs)
# ---------------------------------------------------------------------------
def _classify_c_type(c_type: str, array_dim) -> Optional[tuple]:
"""Reduce an introspect c_type + array_dim down to a comparable
(shape, dim_or_family) tuple. Shapes:
``("scalar", fam)`` — single value, fam ∈ {num,int,bool,string}
``("vec", N)`` — fixed-size C array of length N
``("array", None)`` — dynamic-length C vec (mjFloatVec, etc.)
``("opaque", _)`` — mjsElement* and other spec-internal
pointers URLab never exposes; returning a
distinct tag lets the check skip them
without silently accepting "scalar"
matches.
Returns None for genuinely unknown bases so the check stays quiet
on novel types instead of producing noise.
"""
ct = c_type.strip()
base_no_arr = re.sub(r"\s*\[[^\]]*\]\s*", "", ct).strip()
base_no_ptr = base_no_arr.rstrip(" *").strip()
if base_no_ptr in _DYNAMIC_VEC_TYPES:
return ("array", None)
if base_no_ptr.startswith("mjsElement") or base_no_ptr.endswith("Element"):
return ("opaque", None)
if "*" in ct or "mjString" in ct or "std::string" in ct:
return ("scalar", "string")
is_array = array_dim is not None and array_dim != 1
base = base_no_arr
fam: Optional[str] = None
if base in ("mjtNum", "float", "double"):
fam = "num"
elif base in ("int", "mjtByte", "unsigned char", "uint8_t", "uchar"):
fam = "int"
elif base in ("bool", "_Bool", "mjtBool"):
fam = "bool"
else:
return None
if is_array:
if array_dim in (3, 4):
return ("vec", array_dim)
return ("array", None)
return ("scalar", fam)
def _shapes_compatible(ue_shape: tuple, c_shape: tuple) -> bool:
"""True when ``ue_shape`` can legitimately back ``c_shape``.
A ``TArray<X>`` (array) is shape-compatible with a fixed-size C
array (vec) because the codegen writes ``prop.Num()`` elements
into the C array.
Vec-to-vec requires the dim to match exactly.
Scalar↔array always mismatches. Opaque C shapes are skipped."""
if c_shape[0] == "opaque":
return True
if ue_shape[0] == c_shape[0]:
if ue_shape[0] == "vec":
return ue_shape[1] == c_shape[1]
return True
if ue_shape[0] == "array" and c_shape[0] == "vec":
return True
return False
# ---------------------------------------------------------------------------
# Vec3 convert format table
# ---------------------------------------------------------------------------
#
# Maps the per-field ``apply_to_spec_mode`` rule values for FVector
# UPROPERTYs to the per-element write template the synth-struct emitter
# uses. Each entry is a Python format string with two slots: ``{c}``
# (the destination C-array expression) and ``{ue}`` (the source UE
# FVector expression).
_VEC3_CONVERT_FMT = {
"pos": "{c}[0] = {ue}.X / 100.0; {c}[1] = -{ue}.Y / 100.0; {c}[2] = {ue}.Z / 100.0;",
"vec3_cm": "{c}[0] = {ue}.X / 100.0; {c}[1] = -{ue}.Y / 100.0; {c}[2] = {ue}.Z / 100.0;",
"vec3_y_flip": "{c}[0] = {ue}.X; {c}[1] = -{ue}.Y; {c}[2] = {ue}.Z;",
"passthrough": "{c}[0] = {ue}.X; {c}[1] = {ue}.Y; {c}[2] = {ue}.Z;",
}
# ---------------------------------------------------------------------------
# mjs-field resolver chain (the 5-strategy bridge)
# ---------------------------------------------------------------------------
def _resolve_direct(attr: str, mjs_fields: Set[str]) -> Optional[str]:
"""``attr`` matches a struct field verbatim (condim -> condim)."""
return attr if attr in mjs_fields else None
def _resolve_name_suffix(attr: str, mjs_fields: Set[str]) -> Optional[str]:
"""``attr + "name"`` matches (mesh -> meshname). MuJoCo's name-
ref fields uniformly append ``name`` to the schema attr."""
cand = attr + "name"
return cand if cand in mjs_fields else None
def _resolve_root_name_digits(attr: str, mjs_fields: Set[str]) -> Optional[str]:
"""``<root><digits>`` -> ``<root>name<digits>`` (body1 ->
bodyname1)."""
m = re.match(r"^(.*?)(\d+)$", attr)
if not m:
return None
root, digits = m.group(1), m.group(2)
for candidate in (f"{root}name{digits}", f"{root}_name{digits}"):
if candidate in mjs_fields:
return candidate
return None
def _resolve_underscore_norm(attr: str, mjs_fields: Set[str]) -> Optional[str]:
"""Strip all underscores and look for matching letters
(solreflimit -> solref_limit). Lossy — only used when nothing
cleaner fits."""
norm = attr.replace("_", "")
for f in mjs_fields:
if f.replace("_", "") == norm:
return f
return None
def _resolve_actuator_prefix(attr: str, mjs_fields: Set[str]) -> Optional[str]:
"""Schema ``actuator*`` -> mjs ``act*`` (actuatorfrclimited ->
actfrclimited). MuJoCo abbreviates the prefix on its struct
fields even though the XML attr spells it out."""
if not attr.startswith("actuator"):
return None
cand = "act" + attr[len("actuator"):]
if cand in mjs_fields:
return cand
cand_norm = cand.replace("_", "")
for f in mjs_fields:
if f.replace("_", "") == cand_norm:
return f
return None
_MJS_FIELD_RESOLVERS = (
_resolve_direct,
_resolve_name_suffix,
_resolve_root_name_digits,
_resolve_underscore_norm,
_resolve_actuator_prefix,
)
def _resolve_mjs_field(attr: str, mjs_fields: set,
attr_to_mjs_field: Optional[Dict[str, str]] = None) -> str:
"""Pick the correct C field name on a category's mjs struct for a
given schema attribute. Per-element ``attr_to_mjs_field``
overrides apply first; otherwise the ``_MJS_FIELD_RESOLVERS``
chain captures MuJoCo's own naming conventions in priority order.
Falls back to ``attr`` if nothing matches — the build then
surfaces the mismatch loudly when the export line tries to access
``Element->attr``."""
if attr_to_mjs_field and attr in attr_to_mjs_field:
return attr_to_mjs_field[attr]
if not mjs_fields:
return attr
for resolver in _MJS_FIELD_RESOLVERS:
hit = resolver(attr, mjs_fields)
if hit is not None:
return hit
return attr
# ---------------------------------------------------------------------------
# xml_enum value-map resolver
# ---------------------------------------------------------------------------
def _resolve_value_map(attr: str, enum_def: Dict[str, Any]) -> Dict[str, Sequence[str]]:
"""Return the ``{xml_val -> [UE_enum_member, mj_const]}`` table for
an xml_enum attr. The rule must carry an explicit ``value_map``."""
if "value_map" in enum_def:
return enum_def["value_map"]
raise RuntimeError(f"xml_enum {attr}: rule is missing value_map")
def _value_map_pair(mapping: Any) -> Optional[Tuple[str, str]]:
"""Unpack a ``value_map`` entry into ``(ue_member, mj_const)`` or
return None when the shape is malformed. The 4 check sites that
used to inline ``isinstance(mapping, (list, tuple)) and len(mapping)
>= 2`` route through here so one shape contract covers all of
them. The corresponding emit-side path raises (see
``_emit_xml_enum_export``) — the rule shape contract test
(test_rule_shape_contract.py::test_xml_enum_attr_value_maps_have_
correct_shape) is the canonical gate; this helper is the
runtime fallback for the drift checks."""
if not isinstance(mapping, (list, tuple)) or len(mapping) < 2:
return None
return mapping[0], mapping[1]