nodecanvas-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,332 @@
1
+ """Checks for reflection task bindings (``method`` + ``parameters``) with ready-to-apply fixes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import copy
6
+ from typing import Any, Dict, Iterable, List, Optional, Tuple
7
+
8
+ from .model import Graph
9
+ from .schema import generic_args, short_generic, simple_name
10
+
11
+ PRIMITIVES = {
12
+ "System.Boolean",
13
+ "System.Single",
14
+ "System.Double",
15
+ "System.Int32",
16
+ "System.Int64",
17
+ "System.String",
18
+ "System.Byte",
19
+ "System.Char",
20
+ "System.UInt32",
21
+ "System.Int16",
22
+ }
23
+
24
+
25
+ def _strip(t: str) -> str:
26
+ return t.split(",")[0].strip() if "[[" not in t else t
27
+
28
+
29
+ def var_type(var: dict) -> Optional[str]:
30
+ t = var.get("$type", "")
31
+ if "MissingVariableType" in t:
32
+ t = var.get("_missingType", "")
33
+ args = generic_args(t)
34
+ return _strip(args[0]) if args else None
35
+
36
+
37
+ def is_reference_type(schema, type_name: str) -> bool:
38
+ """Classes and Unity objects (null is a meaningful value); not primitives, strings, structs or enums."""
39
+ t = _strip(type_name)
40
+ if t in PRIMITIVES or t.startswith("System.Nullable") or "[[" in t:
41
+ return False
42
+ if t.startswith("UnityEngine."):
43
+ return t.split(".")[-1] not in UNITY_VALUE_TYPES
44
+ decl = schema.find(t)
45
+ return decl is not None and decl.kind in ("class", "interface", "record")
46
+
47
+
48
+ UNITY_VALUE_TYPES = {
49
+ "Vector2",
50
+ "Vector3",
51
+ "Vector4",
52
+ "Quaternion",
53
+ "Color",
54
+ "Color32",
55
+ "Rect",
56
+ "Bounds",
57
+ "LayerMask",
58
+ "Vector2Int",
59
+ "Vector3Int",
60
+ "Ray",
61
+ "RaycastHit",
62
+ }
63
+
64
+
65
+ def _known(schema, t: str) -> bool:
66
+ """Types whose assignability can be decided offline (sources, primitives, Unity value types)."""
67
+ t = _strip(t)
68
+ if t.startswith("UnityEngine."):
69
+ return t.split(".")[-1] in UNITY_VALUE_TYPES
70
+ return t in PRIMITIVES or schema.find(t) is not None
71
+
72
+
73
+ def assignable(schema, var_t: Optional[str], target: str) -> bool:
74
+ """Can a variable of ``var_t`` be passed where ``target`` is expected (same type or a source subclass)?"""
75
+ if not var_t:
76
+ return False
77
+ if _strip(var_t) == _strip(target):
78
+ return True
79
+ decl = schema.find(_strip(var_t))
80
+ if decl is None:
81
+ return False
82
+ want = simple_name(target)
83
+ return any(
84
+ c.name == want or any(b.split("<")[0].split(".")[-1] == want for b in c.bases) for c in schema.chain(decl)
85
+ )
86
+
87
+
88
+ def _path_str(path: Tuple) -> str:
89
+ return ".".join(str(p) for p in path)
90
+
91
+
92
+ def _target(g: Graph, owner: dict) -> Dict[str, Any]:
93
+ if "_sourceNode" in owner:
94
+ return {"from": owner["_sourceNode"]["$ref"], "to": owner["_targetNode"]["$ref"]}
95
+ return {"node": g.nid(owner)}
96
+
97
+
98
+ def check_task(ws, g: Graph, owner: dict, path: Tuple, task: dict) -> Iterable[Tuple[str, str, str, Optional[dict]]]:
99
+ """Yield ``(severity, code, message, fix_op)`` for one reflection task."""
100
+ method = task.get("method")
101
+ params = task.get("parameters")
102
+ if not isinstance(method, dict) or not isinstance(params, list):
103
+ return
104
+ base = (method.get("_baseInfo") or "").split("|")
105
+ if len(base) < 2:
106
+ return
107
+ type_name, member = base[0], base[1]
108
+ sig = [s for s in (method.get("_paramsInfo") or "").split("|") if s] if method.get("_paramsInfo") else []
109
+ label = f"{simple_name(type_name)}.{member}"
110
+ schema = ws.schema
111
+
112
+ # stored argument types that differ from the bound overload
113
+ mismatch = [
114
+ k
115
+ for k, p in enumerate(params)
116
+ if isinstance(p, dict) and p.get("_type") and k < len(sig) and _strip(p["_type"]) != _strip(sig[k])
117
+ ]
118
+ if mismatch:
119
+ k = mismatch[0]
120
+ msg = (
121
+ f"argument {k + 1} of {label} is stored as {short_generic(params[k]['_type'])} "
122
+ f"but the bound overload takes {short_generic(sig[k])}"
123
+ )
124
+ fix = None
125
+ better = _fitting_overload(ws, g, type_name, member, params, sig)
126
+ if better is not None:
127
+ msg += f"; overload {member}({', '.join(simple_name(p) for p in better)}) fits the arguments"
128
+ fix = _retarget_fix(ws, g, owner, path, task, better)
129
+ yield "warning", "arg-type-mismatch", msg, fix
130
+
131
+ # variable bound to a parameter of an incompatible type (both types known)
132
+ for k, p in enumerate(params):
133
+ if not isinstance(p, dict) or not p.get("_targetVariableID") or k >= len(sig) or k in mismatch:
134
+ continue
135
+ var = g.var_by_id(p["_targetVariableID"])
136
+ vt = var_type(var) if var is not None else None
137
+ pt = _strip(sig[k])
138
+ if not vt or _strip(vt) == pt or not _known(schema, vt) or not _known(schema, pt):
139
+ continue
140
+ if not assignable(schema, vt, pt):
141
+ msg = (
142
+ f"argument {k + 1} of {label} is ${var.get('_name')} ({short_generic(vt)}) "
143
+ f"but the parameter takes {short_generic(pt)}"
144
+ )
145
+ better = _fitting_overload(ws, g, type_name, member, params, sig)
146
+ fix = None
147
+ if better is not None:
148
+ msg += f"; overload {member}({', '.join(simple_name(x) for x in better)}) fits the arguments"
149
+ fix = _retarget_fix(ws, g, owner, path, task, better)
150
+ yield "warning", "arg-type-mismatch", msg, fix
151
+
152
+ # empty object arguments
153
+ for k, p in enumerate(params):
154
+ if not isinstance(p, dict) or p.get("_name") or p.get("_targetVariableID") or "_value" in p:
155
+ continue
156
+ t = p.get("_type") or (sig[k] if k < len(sig) else None)
157
+ if not t or not is_reference_type(schema, t):
158
+ continue
159
+ cands = _scoped_candidates(g, owner, [v for v in g.variables.values() if assignable(schema, var_type(v), t)])
160
+ where = f"argument {k + 1} of {label}"
161
+ if cands:
162
+ best = cands[0]
163
+ names = ", ".join("$" + v.get("_name", "?") for v in cands[:3])
164
+ fix = dict(
165
+ _target(g, owner),
166
+ op="set",
167
+ path=_path_str(path + ("parameters", k)),
168
+ raw=True,
169
+ value={"_type": p.get("_type") or _strip(t), "_name": best["_name"], "_targetVariableID": best["_id"]},
170
+ )
171
+ yield (
172
+ "info",
173
+ "null-arg",
174
+ f"{where} ({short_generic(t)}) is empty (null is passed); if unintended, did you mean {names}?",
175
+ fix,
176
+ )
177
+ else:
178
+ yield ("info", "null-arg", f"{where} ({short_generic(t)}) is empty (null is passed)", None)
179
+
180
+ agent = task.get("overrideAgent")
181
+ if (
182
+ isinstance(agent, dict)
183
+ and agent.get("_type")
184
+ and not (agent.get("_name") or agent.get("_targetVariableID") or "_value" in agent)
185
+ ):
186
+ cands = [v for v in g.variables.values() if assignable(schema, var_type(v), agent["_type"])]
187
+ hint = f"; did you mean {', '.join('$' + v.get('_name', '?') for v in cands[:3])}?" if cands else ""
188
+ yield ("warning", "null-agent", f"{label} overrides the agent with an empty variable{hint}", None)
189
+
190
+
191
+ def _scoped_candidates(g: Graph, owner: dict, cands: List[dict]) -> List[dict]:
192
+ """Order fitting variables by scope: the ``current`` of the nearest enclosing Iterate first, then
193
+ variables written earlier on the way from the root (nearest first), then the rest."""
194
+ if "_sourceNode" in owner or not cands:
195
+ return cands
196
+ from .assets import used_variables
197
+
198
+ ranked: List[str] = []
199
+ child, cur = owner, (g.parents(owner) or [None])[0]
200
+ while cur is not None:
201
+ cv = cur.get("current") if simple_name(cur.get("$type", "")) == "Iterator" else None
202
+ if isinstance(cv, dict) and cv.get("_targetVariableID"):
203
+ ranked.append(cv["_targetVariableID"])
204
+ kids = g.children(cur)
205
+ earlier = kids[: kids.index(child)] if child in kids else []
206
+ for sib in reversed(earlier):
207
+ from .layout import Layouter
208
+
209
+ sub = Layouter(g, None).subtree(sib)
210
+ ranked += [vid for vid, mode in used_variables(g, sub).items() if "w" in mode]
211
+ child, cur = cur, (g.parents(cur) or [None])[0]
212
+ order = {vid: i for i, vid in reversed(list(enumerate(ranked)))}
213
+ return sorted(cands, key=lambda v: order.get(v.get("_id"), len(ranked)))
214
+
215
+
216
+ def call_args(g: Graph) -> Dict[Tuple, Tuple[str, List[Optional[str]]]]:
217
+ """``(id(owner), path) -> (Type.Member, [variable name or None per argument])`` for every reflection call."""
218
+ from .model import walk
219
+
220
+ out = {}
221
+ for owner in list(g.nodes) + list(g.connections):
222
+ for path, d in walk(owner):
223
+ m, params = d.get("method"), d.get("parameters")
224
+ if isinstance(m, dict) and isinstance(params, list) and "|" in (m.get("_baseInfo") or ""):
225
+ t, member = m["_baseInfo"].split("|")[:2]
226
+ args = []
227
+ for p in params:
228
+ var = (
229
+ g.var_by_id(p.get("_targetVariableID"))
230
+ if isinstance(p, dict) and p.get("_targetVariableID")
231
+ else None
232
+ )
233
+ bound = (
234
+ "$" + var["_name"]
235
+ if var
236
+ else ("$" + p["_name"] if isinstance(p, dict) and p.get("_name") else None)
237
+ )
238
+ empty = isinstance(p, dict) and not bound and "_value" not in p
239
+ args.append(bound if bound else (None if empty else "literal"))
240
+ out[(id(owner), path)] = (f"{simple_name(t)}.{member}", args)
241
+ return out
242
+
243
+
244
+ def lost_bindings_by_identity(before: Dict, g: Graph) -> List[str]:
245
+ """Arguments that were bound to a variable before an edit and are empty after it (same node object)."""
246
+ after = call_args(g)
247
+ lines = []
248
+ for key, (member, args) in after.items():
249
+ old = before.get(key)
250
+ if old is None or old[0] != member:
251
+ continue
252
+ for k, (a, b) in enumerate(zip(old[1], args)):
253
+ if a and a.startswith("$") and b is None:
254
+ owner = next((o for o in list(g.nodes) + list(g.connections) if id(o) == key[0]), None)
255
+ where = g.owner_label(owner) if owner is not None else "?"
256
+ lines.append(f"{where} {member} argument {k + 1}: {a} -> empty")
257
+ return lines
258
+
259
+
260
+ def lost_bindings_by_member(old_g: Graph, new_g: Graph) -> List[str]:
261
+ """Per member and argument position: more empty arguments and fewer bound ones than before."""
262
+
263
+ def tally(g):
264
+ t: Dict[Tuple[str, int], List[int]] = {}
265
+ names: Dict[Tuple[str, int], set] = {}
266
+ for member, args in call_args(g).values():
267
+ for k, a in enumerate(args):
268
+ c = t.setdefault((member, k), [0, 0])
269
+ if a is None:
270
+ c[1] += 1
271
+ elif a.startswith("$"):
272
+ c[0] += 1
273
+ names.setdefault((member, k), set()).add(a)
274
+ return t, names
275
+
276
+ (old, old_names), (new, _) = tally(old_g), tally(new_g)
277
+ lines = []
278
+ for key, (bound, empty) in new.items():
279
+ ob, oe = old.get(key, [0, 0])
280
+ if empty > oe and bound < ob:
281
+ was = ", ".join(sorted(old_names.get(key, [])))
282
+ lines.append(f"{key[0]} argument {key[1] + 1}: {empty - oe} call(s) lost their variable (was {was})")
283
+ return lines
284
+
285
+
286
+ def _fitting_overload(
287
+ ws, g: Graph, type_name: str, member: str, params: List[dict], sig: List[str]
288
+ ) -> Optional[List[str]]:
289
+ schema = ws.schema
290
+ actual = []
291
+ for k, p in enumerate(params):
292
+ var = g.var_by_id(p.get("_targetVariableID")) if isinstance(p, dict) and p.get("_targetVariableID") else None
293
+ actual.append(var_type(var) if var is not None else (p.get("_type") if isinstance(p, dict) else None))
294
+ fits = []
295
+ for o in schema.overloads(type_name, member, len(params)):
296
+ decl = schema.find(type_name)
297
+ full = [ws_full(ws, t, decl) for t in o["params"]]
298
+ if [_strip(f) for f in full] == [_strip(s) for s in sig]:
299
+ continue
300
+ if all(a is None or assignable(schema, a, f) for a, f in zip(actual, full)):
301
+ fits.append(o["params"])
302
+ return fits[0] if len(fits) == 1 else None
303
+
304
+
305
+ def ws_full(ws, type_text: str, ctx) -> str:
306
+ from .typenames import TypeNames
307
+
308
+ if not hasattr(ws, "_typenames"):
309
+ ws._typenames = TypeNames(ws)
310
+ return ws._typenames.full(type_text, ctx)
311
+
312
+
313
+ def _retarget_fix(ws, g: Graph, owner: dict, path: Tuple, task: dict, overload: List[str]) -> Optional[dict]:
314
+ from .spec import Speccer
315
+
316
+ sp = Speccer(ws, g)
317
+ kind = {"ExecuteFunction_Multiplatform": "call", "CheckFunction_Multiplatform": "check"}.get(
318
+ simple_name(task.get("$type", ""))
319
+ )
320
+ if kind is None:
321
+ return None
322
+ try:
323
+ spec = sp.reflection(copy.deepcopy(task), kind)
324
+ except (KeyError, ValueError, IndexError):
325
+ return None
326
+ args = []
327
+ for p in task.get("parameters") or []:
328
+ ref = sp.var_ref(p) if isinstance(p, dict) and (p.get("_name") or p.get("_targetVariableID")) else None
329
+ args.append(ref if isinstance(ref, str) else sp.param(p, p.get("_type"), None))
330
+ spec["args"] = args
331
+ spec["overload"] = [simple_name(t) for t in overload]
332
+ return dict(_target(g, owner), op="set", path=_path_str(path), value=spec)