arblang 0.1.24

Visualize and modify Unix pipelines: pipe a stream in, arb spawns a dynamic TUI
Documentation
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
//! Debug Adapter (`arb --dap`): a real, steppable DAP over the same stdio
//! `Content-Length` framing as the LSP. The debugger model reinterprets arb's
//! stream world onto DAP concepts — the same per-line predicate scan the TUI
//! already runs against `expect /regex/` reactions, run headless and made to
//! *block* the feed thread on a condvar instead of firing an action:
//!
//! * program = the input stream (each incoming line is one step)
//! * breakpoint = a regex predicate on lines (a `SourceBreakpoint.condition`, or
//!   an unconditional breakpoint = single-step)
//! * stack trace = the query pipeline stages the paused line flows through
//! * scopes/vars = the matched line + stream stats + input control values
//! * evaluate = arb's real expression evaluator run against the paused line
//!
//! Because DAP owns stdio in `--dap` mode, the data stream cannot also be stdin:
//! the input source (an `input` file) and the spec (`program`) come from the
//! `launch` request. `next`/`stepIn`/`stepOut` collapse to one "advance to the
//! next line" (a stream has no call nesting).

use std::io::{self, BufRead};
use std::sync::atomic::{AtomicI64, Ordering};
use std::sync::{Condvar, Mutex, OnceLock};
use std::thread::JoinHandle;

use regex::Regex;
use serde_json::{json, Value};

use crate::lsp::{read_message, write_message};

/// How a paused feed thread should resume.
#[derive(Clone, Copy, PartialEq)]
enum Resume {
    Continue,
    Step,
}

/// A breakpoint: a regex predicate on incoming lines. `None` condition breaks on
/// every line (an unconditional breakpoint == single-step from that point).
struct Bp {
    line: u32,
    cond: Option<Regex>,
}

/// Shared debugger state: breakpoints, the resume signal, and the pause snapshot
/// the feed thread writes and the reader thread answers `variables`/`stackTrace`
/// from (so no executor round-trip is needed to inspect a paused line).
#[derive(Default)]
pub struct DapState {
    bps: Vec<Bp>,
    /// Function breakpoints: query-verb names (`where`, `tally`, `map`). A
    /// stream has no call stack, but the stack trace this adapter reports is the
    /// pipeline the paused line flows through — so the frame a client sees IS a
    /// named stage, and breaking on one by name is the same request DAP's
    /// function-breakpoint pane makes. Stored lowercased.
    fbps: Vec<String>,
    resume: Option<Resume>,
    stepping: bool,
    terminated: bool,
    // Pause snapshot.
    step_index: u64,
    matched_line: String,
    transformed: String,
    total: u64,
    rate: f64,
    controls: Vec<(String, String)>,
    pipeline: Vec<String>,
    stop_reason: String,
}

/// The condvar-guarded state the feed thread pauses on and the request handlers
/// wake.
pub struct DapShared {
    state: Mutex<DapState>,
    cv: Condvar,
}

impl DapShared {
    fn new() -> Self {
        DapShared {
            state: Mutex::new(DapState::default()),
            cv: Condvar::new(),
        }
    }
}

static SHARED: OnceLock<DapShared> = OnceLock::new();
static SEQ: AtomicI64 = AtomicI64::new(1);
static OUT: OnceLock<Mutex<io::Stdout>> = OnceLock::new();
static EXECUTOR: OnceLock<Mutex<Option<JoinHandle<()>>>> = OnceLock::new();

fn shared() -> &'static DapShared {
    SHARED.get_or_init(DapShared::new)
}

fn executor_slot() -> &'static Mutex<Option<JoinHandle<()>>> {
    EXECUTOR.get_or_init(|| Mutex::new(None))
}

fn next_seq() -> i64 {
    SEQ.fetch_add(1, Ordering::SeqCst)
}

/// Write one framed message to stdout. Both the reader loop and the feed thread
/// emit, so the writer is mutex-guarded.
fn send(msg: Value) {
    let out = OUT.get_or_init(|| Mutex::new(io::stdout()));
    let _ = write_message(&mut *out.lock().unwrap(), &msg);
}

fn send_event(ev: &str, body: Value) {
    send(json!({ "seq": next_seq(), "type": "event", "event": ev, "body": body }));
}

/// Compile the `setBreakpoints` payload into line-predicate breakpoints. A bp
/// with a non-empty `condition` uses it as the match regex; one without breaks
/// on every line.
fn compile_bps(args: &Value) -> Vec<Bp> {
    args.get("breakpoints")
        .and_then(Value::as_array)
        .map(|arr| {
            arr.iter()
                .filter_map(|b| {
                    let line = b.get("line").and_then(Value::as_u64)? as u32;
                    let cond = b
                        .get("condition")
                        .and_then(Value::as_str)
                        .filter(|s| !s.trim().is_empty())
                        .and_then(|s| Regex::new(s).ok());
                    Some(Bp { line, cond })
                })
                .collect()
        })
        .unwrap_or_default()
}

/// Compile the `setFunctionBreakpoints` payload: the `name` of each requested
/// breakpoint, lowercased and trimmed. An empty name is dropped.
fn compile_fbps(args: &Value) -> Vec<String> {
    args.get("breakpoints")
        .and_then(Value::as_array)
        .map(|arr| {
            arr.iter()
                .filter_map(|b| {
                    let name = b.get("name").and_then(Value::as_str)?.trim().to_lowercase();
                    (!name.is_empty()).then_some(name)
                })
                .collect()
        })
        .unwrap_or_default()
}

/// The verb a pipeline stage label names. `stack_frames` labels a stage with the
/// `Debug` rendering of its `QueryOp` (`Where(Bin(…))`, `Tally`), so the verb is
/// the leading identifier — everything before the first non-alphanumeric char.
fn stage_verb(label: &str) -> &str {
    let end = label
        .find(|c: char| !c.is_ascii_alphanumeric())
        .unwrap_or(label.len());
    &label[..end]
}

/// Whether any function breakpoint names a stage of `pipeline`.
fn fbp_hit(fbps: &[String], pipeline: &[String]) -> bool {
    pipeline
        .iter()
        .any(|stage| fbps.iter().any(|n| stage_verb(stage).to_lowercase() == *n))
}

/// The stack frames for a paused line: frame 0 is the line, each deeper frame is
/// one pipeline stage it flows through.
fn stack_frames(st: &DapState) -> Vec<Value> {
    let mut frames = vec![json!({
        "id": 1, "name": format!("line {}", st.step_index),
        "line": st.step_index, "column": 1,
    })];
    for (i, op) in st.pipeline.iter().enumerate() {
        frames.push(json!({ "id": i + 2, "name": op, "line": st.step_index, "column": 1 }));
    }
    frames
}

/// The `variables` rows for a scope reference (1000 Stream / 2000 Controls /
/// 3000 Pipeline). All leaves.
fn variables_body(st: &DapState, vref: u64) -> Vec<Value> {
    let row = |n: &str, v: String| json!({ "name": n, "value": v, "variablesReference": 0 });
    match vref {
        1000 => vec![
            row("line", st.matched_line.clone()),
            row("out", st.transformed.clone()),
            row("step", st.step_index.to_string()),
            row("total", st.total.to_string()),
            row("rate", format!("{:.2}/s", st.rate)),
        ],
        2000 => st.controls.iter().map(|(k, v)| row(k, v.clone())).collect(),
        3000 => st
            .pipeline
            .iter()
            .enumerate()
            .map(|(i, op)| row(&format!("[{i}]"), op.clone()))
            .collect(),
        _ => Vec::new(),
    }
}

/// Evaluate an expression against the paused line: a control name resolves from
/// the snapshot, else it is parsed and run through arb's real evaluator (`x` =
/// line-as-number, `.field` = json/logfmt field).
fn evaluate_body(st: &DapState, expr: &str) -> String {
    if let Some((_, v)) = st.controls.iter().find(|(k, _)| k == expr) {
        return v.clone();
    }
    // In the DAP context `.field` means a stream field of the paused line (the
    // doc's promise), not a TUI control — so turn `.name` refs into bare field
    // names before parsing (`.lat` -> `lat`), which resolve via `field_num_pub`.
    // A decimal like `.5` is untouched (identifiers start with a letter/`_`).
    let normalized = Regex::new(r"\.([A-Za-z_]\w*)")
        .map(|re| re.replace_all(expr, "$1").into_owned())
        .unwrap_or_else(|_| expr.to_string());
    match crate::expr::parse(&normalized) {
        Ok(e) => {
            let line = st.matched_line.clone();
            let x = line.trim().parse::<f64>().unwrap_or(f64::NAN);
            let resolve = |n: &str| crate::query::field_num_pub(&line, n);
            crate::query::fmt_scalar(crate::expr::eval_ctx(&e, x, &resolve).unwrap_or(f64::NAN))
        }
        Err(_) => "<not a control or valid expression>".into(),
    }
}

/// The per-line step hook, parameterized over the shared state so it is testable
/// without the process-global. Blocks the calling (feed) thread whenever the
/// line hits a breakpoint or single-step is armed, until a resume/terminate.
#[allow(clippy::too_many_arguments)]
fn check_line_on(
    sh: &DapShared,
    idx: u64,
    line: &str,
    total: u64,
    rate: f64,
    transformed: &str,
    controls: &[(String, String)],
    pipeline: &[String],
) {
    let mut st = sh.state.lock().unwrap();
    if st.terminated {
        return;
    }
    let bp_hit = st
        .bps
        .iter()
        .any(|b| b.cond.as_ref().is_none_or(|re| re.is_match(line)));
    let fn_hit = fbp_hit(&st.fbps, pipeline);
    if !st.stepping && !bp_hit && !fn_hit {
        return;
    }
    st.stepping = false;
    st.step_index = idx;
    st.matched_line = line.to_string();
    st.transformed = transformed.to_string();
    st.total = total;
    st.rate = rate;
    st.controls = controls.to_vec();
    st.pipeline = pipeline.to_vec();
    st.stop_reason = if bp_hit {
        "breakpoint"
    } else if fn_hit {
        "function breakpoint"
    } else {
        "step"
    }
    .to_string();
    let reason = st.stop_reason.clone();
    drop(st);
    send_event(
        "stopped",
        json!({
            "reason": reason, "threadId": 1, "allThreadsStopped": true,
            "text": format!("line {idx}: {line}"),
        }),
    );
    let mut st = sh.state.lock().unwrap();
    loop {
        if st.terminated {
            return;
        }
        if let Some(r) = st.resume.take() {
            if r == Resume::Step {
                st.stepping = true;
            }
            return;
        }
        st = sh.cv.wait(st).unwrap();
    }
}

/// Feed-thread entry over the process-global shared state.
fn check_line(
    idx: u64,
    line: &str,
    total: u64,
    rate: f64,
    transformed: &str,
    controls: &[(String, String)],
    pipeline: &[String],
) {
    if let Some(sh) = SHARED.get() {
        check_line_on(sh, idx, line, total, rate, transformed, controls, pipeline);
    }
}

/// Parse the spec, open the input file, and drive `check_line` per line on a
/// background thread, emitting each transformed line as an `output` event.
fn spawn_feed(program: Option<String>, input: Option<String>) {
    let handle = std::thread::spawn(move || {
        let src = program
            .as_deref()
            .and_then(|p| std::fs::read_to_string(p).ok())
            .unwrap_or_default();
        let spec = crate::parser::parse(&src)
            .ok()
            .and_then(|c| crate::spec::build(&c).ok());
        let out_ops = spec.and_then(|s| s.out).unwrap_or_default();
        let labels: Vec<String> = out_ops.iter().map(|o| format!("{o:?}")).collect();
        let mut stream = crate::stream::StreamState::new();
        let reader: Box<dyn BufRead> =
            match input.as_deref().and_then(|p| std::fs::File::open(p).ok()) {
                Some(f) => Box::new(io::BufReader::new(f)),
                None => Box::new(io::BufReader::new(io::empty())),
            };
        let mut idx = 0u64;
        for line in reader.lines().map_while(Result::ok) {
            if shared().state.lock().unwrap().terminated {
                break;
            }
            idx += 1;
            stream.push(line.clone());
            let secs = stream.start.elapsed().as_secs_f64();
            let transformed = match crate::query::eval(&out_ops, std::slice::from_ref(&line), secs)
            {
                crate::query::QueryResult::Lines(v) => v.join("\n"),
                crate::query::QueryResult::Scalar(s) => crate::query::fmt_scalar(s),
                crate::query::QueryResult::Pairs(p) => p
                    .iter()
                    .map(|(k, v)| format!("{k}\t{v}"))
                    .collect::<Vec<_>>()
                    .join("\n"),
                // A refused pipeline has no transformed line; the debugger shows
                // the refusal in place of the value.
                crate::query::QueryResult::Error(e) => format!("arb: {e}"),
            };
            check_line(
                idx,
                &line,
                stream.total,
                stream.rate(),
                &transformed,
                &[],
                &labels,
            );
            // Skip the output write once terminated, so a disconnect stops the
            // feed thread reaching the (potentially blocking) stdout write again.
            if !transformed.is_empty() && !shared().state.lock().unwrap().terminated {
                send_event(
                    "output",
                    json!({ "category": "stdout", "output": format!("{transformed}\n") }),
                );
            }
        }
        send_event("terminated", json!({}));
        send_event("exited", json!({ "exitCode": 0 }));
    });
    *executor_slot().lock().unwrap() = Some(handle);
}

/// Handle one DAP request, returning the immediate responses/events to send.
/// Asynchronous events (`stopped`/`output`/`terminated`) are emitted by the feed
/// thread. `_seq` is retained for signature compatibility; sequence numbers come
/// from the shared atomic so both threads stay monotonic.
pub fn handle(msg: &Value, _seq: &mut i64) -> Vec<Value> {
    let command = msg.get("command").and_then(Value::as_str).unwrap_or("");
    let req_seq = msg.get("seq").and_then(Value::as_i64).unwrap_or(0);
    let args = msg.get("arguments").cloned().unwrap_or(Value::Null);
    let resp = |body: Value| {
        json!({
            "seq": next_seq(), "type": "response", "request_seq": req_seq,
            "success": true, "command": command, "body": body,
        })
    };
    let event = |ev: &str, body: Value| json!({ "seq": next_seq(), "type": "event", "event": ev, "body": body });

    match command {
        "initialize" => vec![
            resp(json!({
                "supportsConfigurationDoneRequest": true,
                "supportsConditionalBreakpoints": true,
                "supportsFunctionBreakpoints": true,
                "supportsEvaluateForHovers": true,
                "supportsTerminateRequest": true,
            })),
            event("initialized", json!({})),
        ],
        "configurationDone" | "setExceptionBreakpoints" => vec![resp(json!({}))],
        "setBreakpoints" => {
            let bps = compile_bps(&args);
            let verified: Vec<Value> = bps
                .iter()
                .map(|b| json!({ "verified": true, "line": b.line }))
                .collect();
            shared().state.lock().unwrap().bps = bps;
            vec![resp(json!({ "breakpoints": verified }))]
        }
        // Break when the paused line reaches a named query VERB. Previously this
        // request fell through to the lenient catch-all below, which answers
        // `success: true` with an empty body — a client's function-breakpoint
        // pane would have shown the breakpoint as accepted and it would never
        // have fired. A name arb has no verb for is answered `verified: false`
        // with the reason, rather than silently accepted.
        "setFunctionBreakpoints" => {
            let names = compile_fbps(&args);
            let verified: Vec<Value> = names
                .iter()
                .map(|n| match crate::lsp::sig_of(n) {
                    Some(_) => json!({ "verified": true }),
                    None => json!({ "verified": false, "message": format!("no arb verb `{n}`") }),
                })
                .collect();
            shared().state.lock().unwrap().fbps = names;
            vec![resp(json!({ "breakpoints": verified }))]
        }
        "launch" => {
            if args.get("stopOnEntry").and_then(Value::as_bool) == Some(true) {
                shared().state.lock().unwrap().stepping = true;
            }
            let program = args
                .get("program")
                .and_then(Value::as_str)
                .map(str::to_string);
            let input = args
                .get("input")
                .and_then(Value::as_str)
                .map(str::to_string);
            spawn_feed(program, input);
            vec![resp(json!({}))]
        }
        "threads" => vec![resp(json!({ "threads": [{ "id": 1, "name": "stream" }] }))],
        "stackTrace" => {
            let st = shared().state.lock().unwrap();
            let frames = stack_frames(&st);
            let n = frames.len();
            vec![resp(json!({ "stackFrames": frames, "totalFrames": n }))]
        }
        "scopes" => vec![resp(json!({ "scopes": [
            { "name": "Stream", "variablesReference": 1000, "expensive": false },
            { "name": "Controls", "variablesReference": 2000, "expensive": false },
            { "name": "Pipeline", "variablesReference": 3000, "expensive": false },
        ] }))],
        "variables" => {
            let vref = args
                .get("variablesReference")
                .and_then(Value::as_u64)
                .unwrap_or(0);
            let st = shared().state.lock().unwrap();
            vec![resp(json!({ "variables": variables_body(&st, vref) }))]
        }
        "evaluate" => {
            let expr = args
                .get("expression")
                .and_then(Value::as_str)
                .unwrap_or("")
                .trim()
                .to_string();
            let st = shared().state.lock().unwrap();
            vec![resp(
                json!({ "result": evaluate_body(&st, &expr), "variablesReference": 0 }),
            )]
        }
        "continue" => {
            {
                let mut st = shared().state.lock().unwrap();
                st.resume = Some(Resume::Continue);
            }
            shared().cv.notify_all();
            vec![resp(json!({ "allThreadsContinued": true }))]
        }
        "next" | "stepIn" | "stepOut" => {
            {
                let mut st = shared().state.lock().unwrap();
                st.resume = Some(Resume::Step);
            }
            shared().cv.notify_all();
            vec![resp(json!({}))]
        }
        "disconnect" | "terminate" => {
            {
                let mut st = shared().state.lock().unwrap();
                st.terminated = true;
                st.resume = Some(Resume::Continue);
            }
            shared().cv.notify_all();
            // Detach the feed thread rather than join it: if it is blocked in a
            // `write()` to an un-drained stdout pipe, `join()` would hang forever
            // (the `terminated` flag can't interrupt a syscall).
            drop(executor_slot().lock().unwrap().take());
            // Teardown watchdog. The feed thread can be wedged mid-`write()` to a
            // full stdout pipe (a client that stopped draining) *while holding the
            // `OUT` mutex*, so the disconnect-response `send()` in `run()` would
            // deadlock on that same mutex and the process would never exit. In the
            // normal (draining) case `run()` sends the response and exits in
            // microseconds, well before this fires; only the wedged case waits it
            // out, bounding the hang to 200ms instead of forever.
            std::thread::spawn(|| {
                std::thread::sleep(std::time::Duration::from_millis(200));
                crate::hosted::exit(0);
            });
            vec![resp(json!({}))]
        }
        // Unknown requests succeed with an empty body (lenient, DAP-tolerant).
        _ => vec![resp(json!({}))],
    }
}

/// Run the DAP over stdio until EOF, `disconnect`, or `terminate`.
pub fn run() {
    let stdin = io::stdin();
    let mut r = stdin.lock();
    let mut seq: i64 = 0;
    while let Ok(Some(msg)) = read_message(&mut r) {
        let cmd = msg
            .get("command")
            .and_then(Value::as_str)
            .unwrap_or("")
            .to_string();
        for out in handle(&msg, &mut seq) {
            send(out);
        }
        if cmd == "disconnect" || cmd == "terminate" {
            break;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn shared_state_defaults() {
        let st = DapState::default();
        assert!(st.bps.is_empty());
        assert!(!st.terminated);
        assert!(!st.stepping);
    }

    #[test]
    fn setbreakpoints_compiles_condition() {
        let bps = compile_bps(&json!({ "breakpoints": [{ "line": 3, "condition": "ERROR" }] }));
        assert_eq!(bps.len(), 1);
        assert_eq!(bps[0].line, 3);
        assert!(bps[0].cond.as_ref().unwrap().is_match("ERROR: boom"));
        // A bp with no condition breaks on every line (cond is None).
        let uncond = compile_bps(&json!({ "breakpoints": [{ "line": 1 }] }));
        assert!(uncond[0].cond.is_none());
    }

    /// A function breakpoint names a query VERB and fires when the paused
    /// line's pipeline holds a stage with that name. The pipeline labels are the
    /// `Debug` rendering of each `QueryOp`, so the match has to look past the
    /// operand payload — `Where(Bin(Gt, …))` is the `where` stage.
    #[test]
    fn function_breakpoint_matches_a_pipeline_verb_by_name() {
        let names =
            compile_fbps(&json!({ "breakpoints": [{ "name": " Where " }, { "name": "" }] }));
        assert_eq!(names, ["where"], "trimmed, lowercased, empties dropped");

        let pipeline = vec![
            "In".to_string(),
            "Where(Bin(Gt))".to_string(),
            "Tally".into(),
        ];
        assert!(fbp_hit(&names, &pipeline));
        // A verb the pipeline does not contain must not fire, and neither must
        // an empty breakpoint set — otherwise every line would stop.
        assert!(!fbp_hit(&["sort".to_string()], &pipeline));
        assert!(!fbp_hit(&[], &pipeline));
        // A name that is a PREFIX of a stage is not that stage.
        assert!(!fbp_hit(&["wher".to_string()], &pipeline));
    }

    #[test]
    fn variables_stream_scope_rows() {
        let mut st = DapState {
            matched_line: "hi".into(),
            transformed: "HI".into(),
            step_index: 2,
            total: 5,
            rate: 1.5,
            ..Default::default()
        };
        let names: Vec<String> = variables_body(&st, 1000)
            .iter()
            .map(|r| r["name"].as_str().unwrap().to_string())
            .collect();
        assert_eq!(names, ["line", "out", "step", "total", "rate"]);
        // Controls scope reflects the snapshot's input values.
        st.controls = vec![("th".into(), "7".into())];
        assert_eq!(variables_body(&st, 2000)[0]["value"], "7");
    }

    #[test]
    fn evaluate_arith_over_line_and_control() {
        let mut st = DapState {
            matched_line: "42".into(),
            ..Default::default()
        };
        // Real expression evaluated against the paused line (x = line-as-number).
        assert_eq!(evaluate_body(&st, "x*2"), "84");
        // A control name resolves from the snapshot directly.
        st.controls = vec![("th".into(), "9".into())];
        assert_eq!(evaluate_body(&st, "th"), "9");
    }

    #[test]
    fn evaluate_resolves_json_fields_dotted_or_bare() {
        let st = DapState {
            matched_line: r#"{"lat":9,"code":500}"#.into(),
            ..Default::default()
        };
        // `.field` (jq-style) and the bare name both resolve to the stream field.
        assert_eq!(evaluate_body(&st, ".lat"), "9");
        assert_eq!(evaluate_body(&st, "lat"), "9");
        assert_eq!(evaluate_body(&st, ".lat > 5"), "1");
        assert_eq!(evaluate_body(&st, ".code - .lat"), "491");
    }

    #[test]
    fn stack_frames_are_line_then_pipeline() {
        let st = DapState {
            step_index: 3,
            pipeline: vec!["Match".into(), "Upper".into()],
            ..Default::default()
        };
        let f = stack_frames(&st);
        assert_eq!(f.len(), 3); // line + 2 ops
        assert_eq!(f[0]["name"], "line 3");
        assert_eq!(f[1]["name"], "Match");
    }

    #[test]
    fn check_line_no_bp_no_step_returns() {
        // Empty bps + stepping false => fast path, no block, no panic.
        let sh = DapShared::new();
        check_line_on(&sh, 1, "line", 1, 0.0, "line", &[], &[]);
    }

    #[test]
    fn disconnect_releases_blocked_thread() {
        use std::sync::Arc;
        let sh = Arc::new(DapShared::new());
        sh.state.lock().unwrap().stepping = true; // pauses on the first line
        let sh2 = sh.clone();
        let t = std::thread::spawn(move || {
            check_line_on(&sh2, 1, "x", 1, 0.0, "x", &[], &[]);
        });
        // Repeatedly signal terminate + wake until the paused thread exits.
        while !t.is_finished() {
            {
                let mut st = sh.state.lock().unwrap();
                st.terminated = true;
                st.resume = Some(Resume::Continue);
            }
            sh.cv.notify_all();
            std::thread::yield_now();
        }
        t.join().unwrap();
    }
}