summaryrefslogtreecommitdiff
path: root/anim/src/nodes.zig
blob: e6ba663a83816827b0b2b01efa633a87be0c8767 (plain) (blame)
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
//! `nodes`, a lens (design/README.md, "3. Panels"): the structs the
//! program's pointers reach from a root variable (`objects.reach`: the
//! recording's types say which fields are pointers and which is the
//! value), drawn as boxes of a value and a pointer with arrows between
//! them, in the band's left half; and in its right half the `hexdump` of
//! the bytes they are drawn from. A node's place is its allocation's, so
//! nodes stay where they are while pointers change: a list reversing is
//! its arrows turning round. Above each node its address, the same digits
//! as its row in the dump; under it its `pin`: the registers, and the
//! scene's variables, that hold its address. This is the idea drawn from
//! memory: it reacts when the step's projection arrives from its bytes.
//! Reads `Moment.variables`, `Moment.read`, `Moment.allocation`.
const std = @import("std");
const sk = @import("sketch");
const anim = @import("anim");
const zt = @import("ztrace");
const ui = @import("ui.zig");
const rows = @import("rows.zig");
const context = @import("context.zig");
const cursors = @import("cursor.zig");
const Recording = @import("Recording.zig");
const objects = @import("objects.zig");
const hexdump = @import("hexdump.zig");
const ties = @import("ties.zig");
const Stage = @import("stage.zig").Stage;
const theme = ui.theme;
const time = theme.time;
const Rect = ui.Rect;
const t = theme.color.text;
const m = theme.metric.context;

pub const Nodes = struct {
    cursor: cursors.Cursor,
    stage: *const Stage,
    title: []const u8 = "the list",
    /// The variable the structure hangs from.
    root: []const u8,
    /// The scene's variables that point at nodes, named in their pins with the registers.
    track: []const []const u8 = &.{},
    /// No registers in the pins: an instrumented program's registers say nothing of it.
    quiet: bool = false,
    focus: bool = true,

    pub fn draw(g: *const Nodes, f: *sk.Frame, placed: anim.Placed) void {
        const box = g.stage.box(placed, .band);
        if (box.h < m.tag + m.row) return;
        const u = context.at(f, placed, box);
        const now = g.cursor.now(placed);
        const rec = g.cursor.rec;
        const heap = theme.color.region.heap;
        const legend = [_]ui.Legend{
            .{ .text = "value", .ink = ui.rgb(t.primary) },
            .{ .text = "next", .ink = ui.rgb(heap) },
            .{ .text = "malloc's", .ink = ui.rgb(t.dim) },
            .{ .text = "never read", .ink = ui.rgb(t.faint) },
        };
        _ = u.panel(box.w, box.h, g.title, .{ .focus = g.focus, .legend = &legend });
        const half = theme.layout.state.x - theme.layout.program.x;
        const moment = now.shown(.idea);
        const things = objects.reach(f.scratch, rec, moment, null);
        const before = objects.reach(f.scratch, rec, now.before(), null);

        // The dump: the heap the nodes are in, from the first one's chunk to the last's.
        var lo: u64 = std.math.maxInt(u64);
        var hi: u64 = 0;
        for (rec.allocations) |a| if (things.len > 0 and a.size == things[0].type.record.size) {
            lo = @min(lo, (a.ptr - 16) & ~@as(u64, 15));
            hi = @max(hi, (a.ptr + a.size + 15) & ~@as(u64, 15));
        };
        const count = theme.layout.rowsIn(box.h);
        if (lo < hi) {
            const first = hexdump.window(now, lo, hi, count);
            const shown = @min(count, (hi - first) / 16);
            const base = theme.size.sans.tag;
            u.text(.sans_medium, base, half + 12, m.tag - 6, "its bytes", t.primary);
            u.text(.sans, theme.size.sans.micro, half + 12 + u.width(.sans_medium, base, "its bytes") + 12, m.tag - 6, u.print("the heap, {x} to {x}", .{ first, first + 16 * shown - 1 }), t.faint);
            hexdump.draw(u, now, half, m.tag + m.pad, first, shown, .{ .things = things });
        }
        if (things.len == 0) {
            const root = rec.variable(f.scratch, moment, g.root);
            const empty = root != null and (Recording.word(moment, root.?.addr, 8) catch null) == 0;
            u.text(.sans, theme.size.sans.micro, 24, m.tag + 40, if (empty) u.print("empty: {s} is NULL", .{g.root}) else "nothing yet", t.faint);
            return;
        }

        // The drawing: one place for every node the program will ever make,
        // so none moves when another comes or goes.
        const subject = box.h >= theme.layout.split.subject.band.h - 1;
        const size = if (subject) theme.metric.node.subject else theme.metric.node.beside;
        const label: f32 = if (subject) theme.size.mono.small else theme.size.mono.context;
        const value_size: f32 = if (subject) theme.size.mono.flight else theme.size.mono.small;
        var slots: usize = 0;
        for (rec.allocations) |a| slots += @intFromBool(a.size == things[0].type.record.size);
        slots = @max(slots, 1);
        const n: f32 = @floatFromInt(slots);
        const x0 = (half - 32 - n * size[0] - (n - 1) * size[2]) / 2;
        const ly = m.tag + @as(f32, if (subject) 44 else 16);
        const ny = ly + label * 1.2 + 4;
        const places = f.scratch.alloc(Rect, things.len) catch return;
        for (things, places, 0..) |o, *place, i| {
            place.* = .{ .x = x0 + @as(f32, @floatFromInt(o.slot orelse i)) * (size[0] + size[2]), .y = ny, .w = size[0], .h = size[1] };
            ties.anchor(u, .{ .node = o.addr }, place.*);
        }

        // Arrows first, under the nodes' edges.
        const since = now.since(.idea, 0);
        for (things, places) |o, place| for (o.type.record.fields) |field| {
            if (field.type != .pointer) continue;
            const from_addr = o.addr + field.offset;
            const start = ui.Vec{ place.x + place.w - theme.metric.node.pointer_w / 2 + 6, place.y + place.h / 2 };
            const new = if (Recording.word(now.moment(), from_addr, 8) catch null) |target| placeOf(things, places, target) else null;
            const old = if (Recording.word(now.before(), from_addr, 8) catch null) |target| placeOf(things, places, target) else null;
            const fresh = now.writeAge(from_addr, 8) == 0;
            const ink = ui.rgb(heap);
            const head = theme.metric.node.arrow_head;
            if (!fresh or !now.walking()) {
                if (if (now.landed(.idea, 0)) new else old) |to| u.route(route(u, start, place, to), ink, .{ .width = theme.stroke.line, .head = head, .progress = if (fresh) cursors.standard(now.moving(.idea, 0, time.redirect.head)) else 1 });
                continue;
            }
            // A pointer rewritten. Anticipation: as its half is armed the
            // old arrow goes dashed and faint. Then the half strikes, the
            // new arrow grows to the node it now points at, and that node
            // answers with a bright frame. The old one lingers, then goes.
            const armed = since >= -time.strike.arm;
            if (old) |to| {
                const ghost = if (armed) u.faded(1 - std.math.clamp((since - time.redirect.ghost_hold) / time.redirect.ghost_out, 0, 1)) else u;
                ghost.route(route(u, start, place, to), if (armed) ui.rgb(t.faint) else ink, .{ .dashed = armed, .head = if (armed) null else head, .width = if (armed) theme.stroke.rule else theme.stroke.line });
            }
            if (new) |to| {
                u.route(route(u, start, place, to), ink, .{ .width = theme.stroke.line, .head = head, .progress = cursors.standard(std.math.clamp((since - time.snap) / time.redirect.head, 0, 1)) });
                const landed = since - time.snap - time.redirect.head;
                const out = 4;
                if (landed >= 0 and landed < time.redirect.landing) u.faded(1 - landed / time.redirect.landing).frame(.{ .x = to.x - out, .y = to.y - out, .w = to.w + 2 * out, .h = to.h + 2 * out }, theme.mark(.attention).solid, theme.stroke.rule);
            }
        };

        for (things, places) |o, place| {
            const new = for (before) |was| {
                if (was.addr == o.addr) break false;
            } else true;
            // What begins fades in; it does not pop.
            g.node(if (new) u.faded(now.moving(.idea, 0, time.quick)) else u, now, o, place, label, value_size);
        }
    }

    fn node(g: *const Nodes, u: ui.Ui, now: cursors.Now, o: objects.Object, r: Rect, label: f32, value_size: f32) void {
        const moment = now.shown(.idea);
        const heap = theme.color.region.heap;
        const pw = theme.metric.node.pointer_w;
        const value: Rect = .{ .x = r.x, .y = r.y, .w = r.w - pw - 2, .h = r.h };
        const pointer: Rect = .{ .x = r.x + r.w - pw, .y = r.y, .w = pw, .h = r.h };
        // Its address over it, in heap's ink: the digits of its row in the dump.
        const digits = u.print("{x}", .{o.addr});
        const lw = @as(f32, @floatFromInt(digits.len)) * label * 3 / 5;
        const ly = r.y - 4 - label * 1.2;
        u.text(.mono, label, r.x + (r.w - lw) / 2, ly + label * 0.96, digits, heap);
        ties.anchor(u, .{ .node_address = o.addr }, .{ .x = r.x, .y = ly, .w = r.w, .h = label * 1.2 });
        if (o.freed) {
            // Handed back: its bytes are still there, and nobody owns them.
            u.dashedFrame(r, theme.mark(.freed).solid, theme.stroke.line);
        } else {
            u.fill(value, theme.color.raised);
            u.fill(pointer, theme.color.well);
        }
        if (o.valueField()) |field| {
            const bytes: usize = @intCast(@min(8, field.type.size() orelse 8));
            const at = o.addr + field.offset;
            ties.anchor(u, .{ .node_part = at }, value);
            var ink: ui.Ink = .{};
            if (!o.freed) ink = u.cellWritten(value, now.written(at, bytes, .idea, 0), theme.color.raised);
            if (now.wasRead(at, bytes) and now.writeAge(at, bytes) != 0) u.cellRead(value, now.reading(.idea, 0));
            if (Recording.word(moment, at, bytes) catch null) |n| {
                const shift: u6 = @intCast(64 - 8 * bytes);
                const signed = @as(i64, @bitCast(n << shift)) >> shift;
                u.label(ink.face, value_size, value, .center, u.print("{d}", .{signed}), if (o.freed) ui.rgb(t.faint) else ink.ink);
            } else u.unknown(value);
        }
        // The first pointer field: the square its arrow leaves from, or a slash for null.
        for (o.type.record.fields) |field| {
            if (field.type != .pointer) continue;
            const at = o.addr + field.offset;
            ties.anchor(u, .{ .node_part = at }, pointer);
            const held = Recording.word(moment, at, 8) catch null;
            const struck = !o.freed and u.cellWritten(pointer, now.written(at, 8, .idea, 0), theme.color.well).face == .mono_bold;
            if (now.wasRead(at, 8) and now.writeAge(at, 8) != 0) u.cellRead(pointer, now.reading(.idea, 0));
            const sq = theme.metric.node.origin;
            if (held == null) {
                u.unknown(pointer);
            } else if (held.? == 0) {
                u.line(.{ pointer.x + 10, pointer.y + pointer.h - 8 }, .{ pointer.x + pointer.w - 10, pointer.y + 8 }, if (struck) t.ink else t.dim, theme.stroke.rule);
            } else u.fill(.{ .x = pointer.x + pointer.w / 2 - sq / 2, .y = pointer.y + pointer.h / 2 - sq / 2, .w = sq, .h = sq }, if (struck) t.ink else heap);
            break;
        }
        // Who points here: a pin under it, landing with its link.
        const names = g.pins(u, now, o.addr);
        const cx = r.x + r.w / 2;
        ties.anchor(u, .{ .node_pin = o.addr }, .{ .x = cx - 1, .y = r.y + r.h, .w = 2, .h = label + 10 });
        if (names.names.len > 0 and names.shows > 0) u.faded(names.shows).pinUnder(cx, r.y + r.h, names.names, heap, label);
    }

    const Pins = struct { names: []const []const u8, shows: f32 };

    /// The registers that hold `addr` (before this step, and after it once
    /// their link has landed), then the scene's variables that do.
    fn pins(g: *const Nodes, u: ui.Ui, now: cursors.Now, addr: u64) Pins {
        const rec = g.cursor.rec;
        var out: std.ArrayList([]const u8) = .empty;
        var shows: f32 = 0;
        const is = (now.moment().regs(rec.tid) catch null) orelse zt.Regs{};
        const was = (now.before().regs(rec.tid) catch null) orelse is;
        // The scene's variables first: what the narration names.
        const moment = now.shown(.idea);
        for (g.track) |name| {
            const v = rec.variable(u.f.scratch, moment, name) orelse continue;
            if (!rec.assigned(v, moment.index)) continue;
            if ((Recording.word(moment, v.addr, 8) catch null) != addr) continue;
            out.append(u.f.scratch, name) catch break;
            shows = 1;
        }
        if (!g.quiet) for (theme.metric.all_registers[0..16]) |name| {
            const i = context.index(name).?;
            const before = was.named(name) == addr;
            const after = is.named(name) == addr;
            if (!before and !after) continue;
            const s = ties.pinShows(now, i, .node);
            const this = if (before and after) 1 else if (after) s.new else s.old;
            if (this < 0.5) continue;
            out.append(u.f.scratch, name) catch break;
            shows = @max(shows, this);
        };
        return .{ .names = out.items, .shows = shows };
    }
};

fn placeOf(things: []const objects.Object, places: []const Rect, addr: u64) ?Rect {
    for (things, places) |o, place| if (o.addr == addr) return place;
    return null;
}

/// From the pointer square at `start` (in the node at `from`) to the node
/// at `to`: straight to a node on its right; to one on its left, under
/// the nodes, in from below.
fn route(u: ui.Ui, start: ui.Vec, from: Rect, to: Rect) []const ui.Vec {
    const out = u.f.scratch.alloc(ui.Vec, 4) catch return &.{};
    if (to.x > from.x) {
        out[0] = start;
        out[1] = .{ to.x - 3, to.y + to.h / 2 };
        return out[0..2];
    }
    const under = from.y + from.h + 6;
    out[0] = .{ start[0], from.y + from.h };
    out[1] = .{ start[0], under };
    const into = to.x + (to.w - theme.metric.node.pointer_w) / 2;
    out[2] = .{ into, under };
    out[3] = .{ into, to.y + to.h + 1 };
    return out;
}