Skip to content

Commit e3b8fdc

Browse files
authored
Merge pull request #1635 from Alistair-Afton/devel-datamine
devel/datamine: runtime data mining tool
2 parents 813b501 + 599eda7 commit e3b8fdc

3 files changed

Lines changed: 356 additions & 0 deletions

File tree

‎changelog.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ Template for new versions:
3030

3131
- `devel/infinite-sky-probe`: tool for testing whether infinite sky is working correctly
3232
- `gui/export-world-map`: New GUI tool to configure world map exports from the embark selection screen.
33+
- `devel/datamine`: watch live values for changes and diff structure snapshots to aid script development and reverse engineering
3334

3435
## New Features
3536
- `gui/unit-info-viewer`: the unit character sheet now shows the viewed unit's current and long-term mood, color-coded by stress level

‎devel/datamine.lua‎

Lines changed: 313 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,313 @@
1+
-- Runtime data mining: watch live values and diff structure snapshots.
2+
--[====[
3+
4+
devel/datamine
5+
==============
6+
7+
Aids script development and reverse engineering by observing live game state.
8+
Lua expressions are evaluated with the normal script environment, so ``df``,
9+
``dfhack``, and friends are all available.
10+
11+
Usage::
12+
13+
devel/datamine watch [-n name] [-i frames] <lua expression>
14+
devel/datamine unwatch <name>|all
15+
devel/datamine watches
16+
devel/datamine snap <name> <lua expression>
17+
devel/datamine diff <name>
18+
devel/datamine find <lua expression> <substring>
19+
20+
``watch`` polls the expression every ``frames`` frames (default 1) and prints a
21+
line to the DFHack console whenever its value changes. Watches are cleared when
22+
the world is unloaded; use ``unwatch`` to stop earlier.
23+
24+
``snap`` records the current value of every field reachable from the
25+
expression's result (bounded depth and vector length), and ``diff`` prints the
26+
paths whose values changed since the snapshot -- e.g. "perform action X, then
27+
see which fields changed". ``find`` prints the paths of all fields whose name
28+
or value contains the given substring.
29+
30+
Examples::
31+
32+
devel/datamine watch -n cursor df.global.cursor.x
33+
devel/datamine snap site df.global.world.world_data.active_site[0]
34+
devel/datamine diff site
35+
devel/datamine find df.global.world.units.all[0] stress
36+
37+
]====]
38+
39+
local repeat_util = require('repeat-util')
40+
41+
local TIMER_NAME = 'devel/datamine'
42+
local MAX_CONTAINER_ELEMS = 200
43+
local MAX_DEPTH = 5
44+
local MAX_LEAVES = 20000
45+
local MAX_OUTPUT_LINES = 200
46+
47+
-- script environments persist across invocations
48+
watches = watches or {}
49+
snapshots = snapshots or {}
50+
51+
dfhack.onStateChange.devel_datamine = function(sc)
52+
if sc == SC_WORLD_UNLOADED then
53+
for k in pairs(watches) do watches[k] = nil end
54+
for k in pairs(snapshots) do snapshots[k] = nil end
55+
end
56+
end
57+
58+
local function eval_expr(expr)
59+
local fn, err = load('return ' .. expr, 'datamine:' .. expr, 't', _ENV)
60+
if not fn then
61+
fn, err = load(expr, 'datamine:' .. expr, 't', _ENV)
62+
end
63+
if not fn then
64+
return nil, err
65+
end
66+
local ok, ret = pcall(fn)
67+
if not ok then
68+
return nil, ret
69+
end
70+
return ret
71+
end
72+
73+
local function safe_get(obj, key)
74+
local ok, v = pcall(function() return obj[key] end)
75+
if ok then return v end
76+
end
77+
78+
-- short printable representation of a leaf value
79+
local function repr(v)
80+
return tostring(v)
81+
end
82+
83+
local function is_compound(v)
84+
if type(v) == 'table' then return true end
85+
if type(v) ~= 'userdata' then return false end
86+
local kind = safe_get(v, '_kind')
87+
return kind == 'struct' or kind == 'bitfield' or kind == 'container'
88+
end
89+
90+
-- walk obj, calling cb(path, v) for every leaf value; leaves beyond the cap
91+
-- are counted but not walked, so a truncated walk finishes promptly
92+
local function walk(obj, path, depth, visited, leaf_count, cb)
93+
if leaf_count[1] > MAX_LEAVES then return end
94+
if not is_compound(obj) then
95+
leaf_count[1] = leaf_count[1] + 1
96+
cb(path, obj)
97+
return
98+
end
99+
if depth > MAX_DEPTH then return end
100+
-- userdata wrappers are not identity-stable across field accesses, but
101+
-- tostring() includes the object address; tables use identity directly
102+
local vkey = type(obj) == 'userdata' and tostring(obj) or obj
103+
if visited[vkey] then return end
104+
visited[vkey] = true
105+
local container = type(obj) == 'userdata' and
106+
safe_get(obj, '_kind') == 'container'
107+
local count = 0
108+
local truncated = false
109+
local ok = pcall(function()
110+
for k, v in pairs(obj) do
111+
count = count + 1
112+
if container and count > MAX_CONTAINER_ELEMS then break end
113+
local sub = type(k) == 'number' and
114+
(path .. '[' .. k .. ']') or (path .. '.' .. tostring(k))
115+
walk(v, sub, depth + 1, visited, leaf_count, cb)
116+
end
117+
end)
118+
truncated = not ok or (container and count > MAX_CONTAINER_ELEMS)
119+
if truncated then
120+
cb(path, '<uniterable or truncated>')
121+
end
122+
end
123+
124+
local function snapshot(root)
125+
local map = {}
126+
walk(root, '', 0, {}, {0}, function(path, v)
127+
map[path] = repr(v)
128+
end)
129+
return map
130+
end
131+
132+
local function sorted_keys(map)
133+
local keys = {}
134+
for k in pairs(map) do keys[#keys + 1] = k end
135+
table.sort(keys)
136+
return keys
137+
end
138+
139+
local function print_lines(lines)
140+
for i = 1, math.min(#lines, MAX_OUTPUT_LINES) do
141+
dfhack.print(lines[i] .. '\n')
142+
end
143+
if #lines > MAX_OUTPUT_LINES then
144+
dfhack.print(('... and %d more\n'):format(#lines - MAX_OUTPUT_LINES))
145+
end
146+
end
147+
148+
local function poll_watches()
149+
for name, w in pairs(watches) do
150+
w.countdown = w.countdown - 1
151+
if w.countdown <= 0 then
152+
w.countdown = w.interval
153+
local val, err = eval_expr(w.expr)
154+
if err then
155+
if w.last_err ~= err then
156+
w.last_err = err
157+
dfhack.printerr(('datamine[%s]: %s'):format(name, err))
158+
end
159+
else
160+
w.last_err = nil
161+
local r = repr(val)
162+
if r ~= w.last then
163+
dfhack.print(('datamine[%s]: %s -> %s\n'):format(
164+
name, w.last or 'nil', r))
165+
w.last = r
166+
end
167+
end
168+
end
169+
end
170+
end
171+
172+
local function ensure_timer()
173+
if next(watches) then
174+
repeat_util.scheduleUnlessAlreadyScheduled(
175+
TIMER_NAME, 1, 'frames', poll_watches)
176+
else
177+
repeat_util.cancel(TIMER_NAME)
178+
end
179+
end
180+
181+
local function cmd_watch(args)
182+
local name, interval, i = nil, 1, 1
183+
while i <= #args do
184+
if args[i] == '-n' then
185+
name = args[i + 1]; i = i + 2
186+
elseif args[i] == '-i' then
187+
interval = tonumber(args[i + 1]) or 1; i = i + 2
188+
else
189+
break
190+
end
191+
end
192+
local expr = table.concat(args, ' ', i)
193+
if expr == '' then qerror('missing lua expression') end
194+
name = name or expr
195+
local val, err = eval_expr(expr)
196+
if err then qerror(('cannot evaluate: %s'):format(err)) end
197+
watches[name] = {expr = expr, interval = math.max(1, interval),
198+
countdown = 0, last = repr(val)}
199+
dfhack.print(('watching %s = %s\n'):format(name, watches[name].last))
200+
ensure_timer()
201+
end
202+
203+
local function cmd_unwatch(name)
204+
if name == 'all' then
205+
watches = {}
206+
repeat_util.cancel(TIMER_NAME)
207+
dfhack.print('all watches removed\n')
208+
return
209+
end
210+
if not name or not watches[name] then
211+
qerror(('no watch named %q'):format(tostring(name)))
212+
end
213+
watches[name] = nil
214+
ensure_timer()
215+
dfhack.print(('stopped watching %s\n'):format(name))
216+
end
217+
218+
local function cmd_watches()
219+
if not next(watches) then
220+
dfhack.print('no active watches\n')
221+
return
222+
end
223+
for name, w in pairs(watches) do
224+
dfhack.print(('%s = %s [%s]\n'):format(name, w.last or 'nil', w.expr))
225+
end
226+
end
227+
228+
local function cmd_snap(args)
229+
local name = args[1]
230+
local expr = table.concat(args, ' ', 2)
231+
if not name or expr == '' then
232+
qerror('usage: snap <name> <lua expression>')
233+
end
234+
local val, err = eval_expr(expr)
235+
if err then qerror(('cannot evaluate: %s'):format(err)) end
236+
snapshots[name] = {expr = expr, map = snapshot(val)}
237+
local n = 0
238+
for _ in pairs(snapshots[name].map) do n = n + 1 end
239+
dfhack.print(('snapshot %q: %d fields recorded\n'):format(name, n))
240+
end
241+
242+
local function cmd_diff(name)
243+
if not name then qerror('usage: diff <name>') end
244+
local snap = snapshots[name]
245+
if not snap then qerror(('no snapshot named %q'):format(name)) end
246+
local val, err = eval_expr(snap.expr)
247+
if err then qerror(('cannot evaluate: %s'):format(err)) end
248+
local now = snapshot(val)
249+
local lines = {}
250+
local seen = {}
251+
for _, path in ipairs(sorted_keys(snap.map)) do
252+
seen[path] = true
253+
if now[path] == nil then
254+
lines[#lines + 1] = ('%s: %s -> <gone>'):format(path, snap.map[path])
255+
elseif now[path] ~= snap.map[path] then
256+
lines[#lines + 1] = ('%s: %s -> %s'):format(
257+
path, snap.map[path], now[path])
258+
end
259+
end
260+
for _, path in ipairs(sorted_keys(now)) do
261+
if not seen[path] then
262+
lines[#lines + 1] = ('%s: <new> -> %s'):format(path, now[path])
263+
end
264+
end
265+
if #lines == 0 then
266+
dfhack.print('no changes\n')
267+
else
268+
print_lines(lines)
269+
end
270+
end
271+
272+
local function cmd_find(args)
273+
if #args < 2 then
274+
qerror('usage: find <lua expression> <substring>')
275+
end
276+
local pat = args[#args]:lower()
277+
local expr = table.concat(args, ' ', 1, #args - 1)
278+
local val, err = eval_expr(expr)
279+
if err then qerror(('cannot evaluate: %s'):format(err)) end
280+
local lines = {}
281+
walk(val, '', 0, {}, {0}, function(path, v)
282+
local r = repr(v)
283+
if path:lower():find(pat, 1, true) or r:lower():find(pat, 1, true) then
284+
lines[#lines + 1] = ('%s = %s'):format(path, r)
285+
end
286+
end)
287+
if #lines == 0 then
288+
dfhack.print('no matching fields\n')
289+
else
290+
print_lines(lines)
291+
end
292+
end
293+
294+
local args = {...}
295+
local cmd = table.remove(args, 1)
296+
297+
if not cmd or cmd == 'help' then
298+
print(dfhack.script_help())
299+
elseif cmd == 'watch' then
300+
cmd_watch(args)
301+
elseif cmd == 'unwatch' or cmd == 'stop' then
302+
cmd_unwatch(args[1])
303+
elseif cmd == 'watches' or cmd == 'list' then
304+
cmd_watches()
305+
elseif cmd == 'snap' then
306+
cmd_snap(args)
307+
elseif cmd == 'diff' then
308+
cmd_diff(args[1])
309+
elseif cmd == 'find' then
310+
cmd_find(args)
311+
else
312+
qerror(('unknown command: %s'):format(cmd))
313+
end

‎docs/devel/datamine.rst‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
devel/datamine
2+
==============
3+
4+
.. dfhack-tool::
5+
:summary: Watch live values and diff structure snapshots.
6+
:tags: dev
7+
8+
Aids script development and reverse engineering by observing live game state.
9+
Lua expressions are evaluated with the normal script environment, so ``df``,
10+
``dfhack``, and friends are all available.
11+
12+
Usage
13+
-----
14+
15+
::
16+
17+
devel/datamine watch [-n name] [-i frames] <lua expression>
18+
devel/datamine unwatch <name>|all
19+
devel/datamine watches
20+
devel/datamine snap <name> <lua expression>
21+
devel/datamine diff <name>
22+
devel/datamine find <lua expression> <substring>
23+
24+
``watch`` polls the expression every ``frames`` frames (default 1) and prints a
25+
line to the DFHack console whenever its value changes. Watches are cleared when
26+
the world is unloaded; use ``unwatch`` to stop earlier.
27+
28+
``snap`` records the current value of every field reachable from the
29+
expression's result (bounded depth and vector length), and ``diff`` prints the
30+
paths whose values changed since the snapshot -- e.g. "perform action X, then
31+
see which fields changed". ``find`` prints the paths of all fields whose name
32+
or value contains the given substring.
33+
34+
Examples
35+
--------
36+
37+
::
38+
39+
devel/datamine watch -n cursor df.global.cursor.x
40+
devel/datamine snap site df.global.world.world_data.active_site[0]
41+
devel/datamine diff site
42+
devel/datamine find df.global.world.units.all[0] stress

0 commit comments

Comments
 (0)