mq-lang 0.5.13

Core language implementation for mq query language
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
use itertools::Itertools;

use super::runtime_value::RuntimeValue;
use crate::ast::node as ast;
use crate::eval::Evaluator;
use crate::eval::env::Env;
use crate::{ModuleResolver, Shared, SharedCell, Token};

use std::{collections::HashSet, fmt::Debug};

#[derive(Debug, Clone, Copy, Eq, PartialEq, Default, Hash)]
pub enum DebuggerCommand {
    /// Continue normal execution.
    #[default]
    Continue,
    /// Step into the next expression, diving into functions.
    StepInto,
    /// Run to the next expression or statement, stepping over functions.
    StepOver,
    /// Run to the next statement, skipping over functions.
    Next,
    /// Run to the end of the current function call.
    FunctionExit,
    /// Quit the debugger.
    Quit,
}

/// Represents a breakpoint in the debugger.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub struct Breakpoint {
    /// Unique identifier for the breakpoint
    pub id: usize,
    /// Line number where the breakpoint is set
    pub line: usize,
    /// Column number where the breakpoint is set (optional)
    pub column: Option<usize>,
    /// Whether the breakpoint is enabled
    pub enabled: bool,
    /// Optional source file name for the breakpoint
    pub source: Option<String>,
}

#[derive(Debug, Clone, Default)]
pub struct Source {
    pub name: Option<String>,
    pub code: String,
}

/// Debugger state and context information
#[derive(Debug, Clone)]
pub struct DebugContext {
    /// Current runtime value being evaluated
    pub current_value: RuntimeValue,
    /// Current AST node being evaluated
    pub current_node: Shared<ast::Node>,
    /// Current token being evaluated
    pub token: Shared<Token>,
    /// Call stack of AST nodes representing the current execution path
    pub call_stack: Vec<Shared<ast::Node>>,
    /// Current evaluation environment info
    pub env: Shared<SharedCell<Env>>,
    /// Optional source
    pub source: Source,
}

impl Default for DebugContext {
    fn default() -> Self {
        Self {
            current_value: RuntimeValue::NONE,
            current_node: Shared::new(ast::Node {
                token_id: crate::ast::TokenId::new(0),
                expr: Shared::new(ast::Expr::Literal(ast::Literal::Number(0.0.into()))),
            }),
            token: Shared::new(Token {
                kind: crate::TokenKind::Eof,
                range: crate::Range::default(),
                module_id: crate::eval::module::ModuleId::new(0),
            }),
            call_stack: Vec::new(),
            env: Shared::new(SharedCell::new(Env::default())),
            source: Source::default(),
        }
    }
}

/// The main debugger struct that manages breakpoints and execution state
#[derive(Debug)]
pub struct Debugger {
    /// Set of active breakpoints
    breakpoints: HashSet<Breakpoint>,
    /// Call stack of AST nodes representing the current execution path
    call_stack: Vec<Shared<ast::Node>>,
    /// Next breakpoint ID to assign
    next_breakpoint_id: usize,
    /// Current debugger command
    current_command: DebuggerCommand,
    /// Whether the debugger is currently active
    active: bool,
    /// Current call stack depth for step operations
    step_depth: Option<usize>,
}

impl Default for Debugger {
    fn default() -> Self {
        Self::new()
    }
}

impl Debugger {
    /// Create a new debugger instance
    pub fn new() -> Self {
        Self {
            breakpoints: HashSet::new(),
            call_stack: Vec::new(),
            next_breakpoint_id: 1,
            current_command: DebuggerCommand::Continue,
            active: false,
            step_depth: None,
        }
    }

    /// Activate the debugger
    pub fn activate(&mut self) {
        self.active = true;
    }

    /// Deactivate the debugger
    pub fn deactivate(&mut self) {
        self.active = false;
    }

    /// Check if the debugger is active
    pub fn is_active(&self) -> bool {
        self.active
    }

    /// Add a breakpoint at the specified line
    pub fn add_breakpoint(&mut self, line: usize, column: Option<usize>, source: Option<String>) -> usize {
        let breakpoint = Breakpoint {
            id: self.next_breakpoint_id,
            line,
            column,
            enabled: true,
            source,
        };
        let id = breakpoint.id;
        self.breakpoints.insert(breakpoint);
        self.next_breakpoint_id += 1;
        id
    }

    pub fn push_call_stack(&mut self, node: Shared<ast::Node>) {
        self.call_stack.push(node);
    }

    pub fn pop_call_stack(&mut self) {
        self.call_stack.pop();
    }

    pub fn current_call_stack(&self) -> Vec<Shared<ast::Node>> {
        self.call_stack.clone()
    }

    /// Remove a breakpoint by ID
    pub fn remove_breakpoint(&mut self, id: usize) -> bool {
        self.breakpoints.retain(|bp| bp.id != id);
        true
    }

    /// Remove a breakpoints by source
    pub fn remove_breakpoints(&mut self, source: &Option<String>) -> bool {
        self.breakpoints.retain(|bp| bp.source != *source);
        true
    }

    /// List all breakpoints
    pub fn list_breakpoints(&self) -> Vec<&Breakpoint> {
        self.breakpoints.iter().collect()
    }

    /// Set the current debugger command
    pub fn set_command(&mut self, command: DebuggerCommand) {
        self.current_command = command;
        match command {
            DebuggerCommand::StepInto | DebuggerCommand::StepOver | DebuggerCommand::Next => {
                self.step_depth = None;
            }
            DebuggerCommand::FunctionExit | DebuggerCommand::Quit => {
                // step_depth will be set to current depth - 1 when stepping
            }
            DebuggerCommand::Continue => {
                self.step_depth = None;
            }
        }
    }

    /// Returns the breakpoint that was hit at the current token location, if any.
    pub fn get_hit_breakpoint(&self, context: &DebugContext, token: Shared<Token>) -> Option<Breakpoint> {
        if !self.active {
            return None;
        }

        let line = token.range.start.line as usize;
        let column = token.range.start.column;

        self.find_active_breakpoint(line, column, &context.source)
    }

    pub fn next(&mut self, next_action: DebuggerAction) {
        self.handle_debugger_action(next_action.clone());
        self.current_command = next_action.clone().into();
    }

    /// Check if execution should pause at the current location and handle callbacks
    pub fn should_break(&mut self, context: &DebugContext) -> bool {
        if !self.active {
            return false;
        }

        match self.current_command {
            DebuggerCommand::Continue => false,
            DebuggerCommand::Quit => {
                self.deactivate();
                false
            }
            DebuggerCommand::StepInto => {
                self.current_command = DebuggerCommand::Continue;
                true
            }
            DebuggerCommand::StepOver => {
                if let Some(step_depth) = self.step_depth {
                    if context.call_stack.len() <= step_depth {
                        self.current_command = DebuggerCommand::Continue;
                        self.step_depth = None;
                        true
                    } else {
                        false
                    }
                } else {
                    self.step_depth = Some(context.call_stack.len());
                    self.current_command = DebuggerCommand::Continue;
                    true
                }
            }
            DebuggerCommand::Next => {
                if let Some(step_depth) = self.step_depth {
                    if context.call_stack.len() <= step_depth {
                        self.current_command = DebuggerCommand::Continue;
                        self.step_depth = None;
                        true
                    } else {
                        false
                    }
                } else {
                    self.step_depth = Some(context.call_stack.len());
                    self.current_command = DebuggerCommand::Continue;
                    true
                }
            }
            DebuggerCommand::FunctionExit => {
                // Break when we exit the current function
                if let Some(step_depth) = self.step_depth {
                    if context.call_stack.len() < step_depth {
                        self.current_command = DebuggerCommand::Continue;
                        self.step_depth = None;
                        true
                    } else {
                        false
                    }
                } else {
                    // Set target depth to current - 1
                    self.step_depth = Some(context.call_stack.len().saturating_sub(1));
                    false
                }
            }
        }
    }

    fn handle_debugger_action(&mut self, action: DebuggerAction) {
        match action {
            DebuggerAction::Breakpoint(Some(line_no)) => {
                self.add_breakpoint(line_no, None, None);
            }
            DebuggerAction::Breakpoint(None) => {
                println!(
                    "Breakpoints:\n{}",
                    self.breakpoints
                        .iter()
                        .sorted_by_key(|bp| (bp.line, bp.column))
                        .map(|bp| {
                            format!(
                                "  [{}] {}:{}{}",
                                bp.id,
                                bp.line,
                                bp.column.map(|col| col.to_string()).unwrap_or_else(|| "-".to_string()),
                                if bp.enabled { " (enabled)" } else { " (disabled)" },
                            )
                        })
                        .join("\n")
                );
            }
            DebuggerAction::Clear(Some(breakpoint_id)) => {
                self.remove_breakpoint(breakpoint_id);
            }
            DebuggerAction::Clear(None) => {
                self.clear_breakpoints();
            }
            DebuggerAction::Continue
            | DebuggerAction::Next
            | DebuggerAction::StepInto
            | DebuggerAction::StepOver
            | DebuggerAction::FunctionExit
            | DebuggerAction::Quit => {}
        }
    }

    fn find_active_breakpoint(&self, line: usize, column: usize, source: &Source) -> Option<Breakpoint> {
        for breakpoint in &self.breakpoints {
            if !breakpoint.enabled {
                continue;
            }

            if breakpoint.source != source.name {
                continue;
            }

            if breakpoint.line == line {
                if let Some(bp_column) = breakpoint.column
                    && bp_column != column
                {
                    continue;
                }

                return Some(breakpoint.clone());
            }
        }

        None
    }

    /// Get the current debugger command
    pub fn current_command(&self) -> DebuggerCommand {
        self.current_command
    }

    /// Clear all breakpoints
    pub fn clear_breakpoints(&mut self) {
        self.breakpoints.clear();
    }
}

type LineNo = usize;
type BreakpointId = usize;

/// Result of debugger callback execution
#[derive(Debug, Clone, PartialEq)]
pub enum DebuggerAction {
    /// Set a breakpoint at a specific location.
    Breakpoint(Option<LineNo>),
    /// Continue normal execution
    Continue,
    /// Clear breakpoints at a specific location
    Clear(Option<BreakpointId>),
    /// Step into next expression
    StepInto,
    /// Step over current expression
    StepOver,
    /// Step to next statement
    Next,
    /// Run until function exit
    FunctionExit,
    /// Quit the debugger
    Quit,
}

impl From<DebuggerCommand> for DebuggerAction {
    fn from(command: DebuggerCommand) -> Self {
        match command {
            DebuggerCommand::Continue => DebuggerAction::Continue,
            DebuggerCommand::StepInto => DebuggerAction::StepInto,
            DebuggerCommand::StepOver => DebuggerAction::StepOver,
            DebuggerCommand::Next => DebuggerAction::Next,
            DebuggerCommand::FunctionExit => DebuggerAction::FunctionExit,
            DebuggerCommand::Quit => DebuggerAction::Quit,
        }
    }
}

impl From<DebuggerAction> for DebuggerCommand {
    fn from(action: DebuggerAction) -> Self {
        match action {
            DebuggerAction::Breakpoint(_) => DebuggerCommand::Continue,
            DebuggerAction::Clear(_) => DebuggerCommand::Continue,
            DebuggerAction::Continue => DebuggerCommand::Continue,
            DebuggerAction::StepInto => DebuggerCommand::StepInto,
            DebuggerAction::StepOver => DebuggerCommand::StepOver,
            DebuggerAction::Next => DebuggerCommand::Next,
            DebuggerAction::FunctionExit => DebuggerCommand::FunctionExit,
            DebuggerAction::Quit => DebuggerCommand::Quit,
        }
    }
}

pub trait DebuggerHandler: std::fmt::Debug + Send + Sync {
    // Called when a breakpoint is hit.
    fn on_breakpoint_hit(&self, _breakpoint: &Breakpoint, _context: &DebugContext) -> DebuggerAction {
        // Default behavior: continue execution
        DebuggerAction::Continue
    }

    /// Called when stepping through execution.
    fn on_step(&self, _context: &DebugContext) -> DebuggerAction {
        DebuggerAction::Continue
    }
}

#[derive(Debug, Default)]
pub struct DefaultDebuggerHandler;

impl DebuggerHandler for DefaultDebuggerHandler {}

impl<T: ModuleResolver> Evaluator<T> {
    pub fn debugger(&self) -> Shared<SharedCell<Debugger>> {
        Shared::clone(&self.debugger)
    }

    pub fn set_debugger_handler(&mut self, handler: Box<dyn DebuggerHandler>) {
        self.debugger_handler = Shared::new(SharedCell::new(handler));
    }
}

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

    use crate::{Arena, Range, TokenKind, ast::TokenId, eval::module::ModuleId};

    use super::*;

    fn make_token(line: usize, column: usize) -> Shared<Token> {
        Shared::new(Token {
            kind: TokenKind::Ident("dummy".into()),
            range: Range {
                start: crate::Position {
                    line: line as u32,
                    column,
                },
                end: crate::Position {
                    line: line as u32,
                    column: column + 1,
                },
            },
            module_id: ModuleId::new(0),
        })
    }

    fn make_node(token_id: TokenId) -> Shared<ast::Node> {
        Shared::new(ast::Node {
            token_id,
            expr: Shared::new(ast::Expr::Literal(ast::Literal::Number(42.0.into()))),
        })
    }

    fn make_debug_context(line: usize, column: usize) -> DebugContext {
        let mut arena = Arena::new(10);
        let token = make_token(line, column);
        let token_id = arena.alloc(Shared::clone(&token));
        let node = make_node(token_id);
        DebugContext {
            current_value: RuntimeValue::NONE,
            current_node: node,
            token: Shared::clone(&token),
            call_stack: Vec::new(),
            env: Shared::new(SharedCell::new(Env::default())),
            source: Source::default(),
        }
    }

    #[rstest]
    #[case(DebuggerCommand::Continue, false, "Continue: should not break")]
    #[case(DebuggerCommand::Quit, false, "Quit: should not break and deactivate")]
    #[case(DebuggerCommand::StepInto, true, "StepInto: should break once")]
    fn test_should_break_basic(#[case] command: DebuggerCommand, #[case] expected_hit: bool, #[case] _desc: &str) {
        let mut dbg = Debugger::new();
        dbg.activate();
        dbg.set_command(command);

        let ctx = make_debug_context(1, 1);
        let hit = dbg.should_break(&ctx);
        assert_eq!(hit, expected_hit);

        if command == DebuggerCommand::Quit {
            assert!(!dbg.is_active(), "Debugger should be deactivated after Quit");
        }
    }

    #[rstest]
    #[case(
        DebuggerCommand::StepOver,
        None,
        vec![],
        true,
        "StepOver: step_depth None, call_stack empty"
    )]
    #[case(
        DebuggerCommand::StepOver,
        Some(1),
        vec![0, 1],
        false,
        "StepOver: step_depth Some(1), call_stack.len()=2"
    )]
    #[case(
        DebuggerCommand::StepOver,
        Some(2),
        vec![0],
        true,
        "StepOver: step_depth Some(2), call_stack.len()=1"
    )]
    #[case(
        DebuggerCommand::Next,
        None,
        vec![],
        true,
        "Next: step_depth None, call_stack empty"
    )]
    #[case(
        DebuggerCommand::Next,
        Some(1),
        vec![0, 1],
        false,
        "Next: step_depth Some(1), call_stack.len()=2"
    )]
    #[case(
        DebuggerCommand::Next,
        Some(2),
        vec![0],
        true,
        "Next: step_depth Some(2), call_stack.len()=1"
    )]
    #[case(
        DebuggerCommand::FunctionExit,
        None,
        vec![],
        false,
        "FunctionExit: step_depth None, call_stack empty"
    )]
    #[case(
        DebuggerCommand::FunctionExit,
        Some(2),
        vec![0],
        true,
        "FunctionExit: step_depth Some(2), call_stack.len()=1"
    )]
    #[case(
        DebuggerCommand::FunctionExit,
        Some(1),
        vec![0, 1],
        false,
        "FunctionExit: step_depth Some(1), call_stack.len()=2"
    )]
    fn test_should_break_with_step_depth(
        #[case] command: DebuggerCommand,
        #[case] step_depth: Option<usize>,
        #[case] call_stack_indices: Vec<usize>,
        #[case] expected_hit: bool,
        #[case] _desc: &str,
    ) {
        let mut dbg = Debugger::new();
        dbg.activate();
        dbg.set_command(command);
        dbg.step_depth = step_depth;

        let ctx = make_debug_context(1, 1);
        let mut ctx = ctx;
        ctx.call_stack = call_stack_indices
            .into_iter()
            .map(|i| make_node(TokenId::new(i as u32)))
            .collect();

        let hit = dbg.should_break(&ctx);
        assert_eq!(hit, expected_hit);
    }

    #[test]
    fn test_add_and_remove_breakpoint() {
        let mut dbg = Debugger::new();
        let id = dbg.add_breakpoint(1, Some(2), None);
        assert_eq!(dbg.list_breakpoints().len(), 1);
        assert!(dbg.remove_breakpoint(id));
        assert_eq!(dbg.list_breakpoints().len(), 0);
    }

    #[test]
    fn test_clear_breakpoints() {
        let mut dbg = Debugger::new();
        dbg.add_breakpoint(1, None, None);
        dbg.add_breakpoint(2, Some(3), None);
        assert_eq!(dbg.list_breakpoints().len(), 2);
        dbg.clear_breakpoints();
        assert_eq!(dbg.list_breakpoints().len(), 0);
    }

    #[test]
    fn test_debugger_activate_deactivate() {
        let mut dbg = Debugger::new();
        assert!(!dbg.is_active());
        dbg.activate();
        assert!(dbg.is_active());
        dbg.deactivate();
        assert!(!dbg.is_active());
    }
}