ixa/
debugger.rs

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
use crate::context::run_with_plugin;
use crate::define_data_plugin;
use crate::external_api::{
    breakpoint, global_properties, halt, next, people, population, run_ext_api, EmptyArgs,
};
use crate::{trace, Context, IxaError};
use crate::{HashMap, HashMapExt};
use clap::{ArgMatches, Command, FromArgMatches, Parser, Subcommand};
use rustyline;

use std::fmt::Write;

trait DebuggerCommand {
    /// Handle the command and any inputs; returning true will exit the debugger
    fn handle(
        &self,
        context: &mut Context,
        matches: &ArgMatches,
    ) -> Result<(bool, Option<String>), String>;
    fn extend(&self, command: Command) -> Command;
}

struct Debugger {
    rl: rustyline::DefaultEditor,
    cli: Command,
    commands: HashMap<&'static str, Box<dyn DebuggerCommand>>,
}
define_data_plugin!(DebuggerPlugin, Option<Debugger>, None);

impl Debugger {
    fn get_command(&self, name: &str) -> Option<&dyn DebuggerCommand> {
        self.commands.get(name).map(|command| &**command)
    }

    fn process_command(
        &self,
        l: &str,
        context: &mut Context,
    ) -> Result<(bool, Option<String>), String> {
        let args = shlex::split(l).ok_or("Error splitting lines")?;
        let matches = self
            .cli
            .clone() // cli can only be used once.
            .try_get_matches_from(args)
            .map_err(|e| e.to_string())?;

        if let Some((command, _)) = matches.subcommand() {
            // If the provided command is known, run its handler

            if let Some(handler) = self.get_command(command) {
                return handler.handle(context, &matches);
            }
            // Unexpected command: print an error
            return Err(format!("error: Unknown command: {command}"));
        }

        unreachable!("subcommand required");
    }
}

struct PopulationCommand;
impl DebuggerCommand for PopulationCommand {
    fn handle(
        &self,
        context: &mut Context,
        _matches: &ArgMatches,
    ) -> Result<(bool, Option<String>), String> {
        let output = format!(
            "{}",
            run_ext_api::<population::Api>(context, &EmptyArgs {})
                .unwrap()
                .population
        );
        Ok((false, Some(output)))
    }
    fn extend(&self, command: Command) -> Command {
        population::Args::augment_subcommands(command)
    }
}

struct PeopleCommand;
impl DebuggerCommand for PeopleCommand {
    fn extend(&self, command: Command) -> Command {
        people::Args::augment_subcommands(command)
    }
    fn handle(
        &self,
        context: &mut Context,
        matches: &ArgMatches,
    ) -> Result<(bool, Option<String>), String> {
        let args = people::Args::from_arg_matches(matches).unwrap();
        match run_ext_api::<people::Api>(context, &args) {
            Ok(people::Retval::Properties(props)) => Ok((
                false,
                Some(
                    props
                        .into_iter()
                        .map(|(k, v)| format!("{k}: {v}"))
                        .collect::<Vec<_>>()
                        .join("\n"),
                ),
            )),
            Ok(people::Retval::PropertyNames(names)) => Ok((
                false,
                Some(format!("Available properties:\n{}", names.join("\n"))),
            )),
            Ok(people::Retval::Tabulated(rows)) => Ok((
                false,
                Some(
                    rows.into_iter()
                        .map(|(props, count)| {
                            format!(
                                "{}: {}",
                                count,
                                props
                                    .into_iter()
                                    .map(|(k, v)| format!("{k}={v}"))
                                    .collect::<Vec<_>>()
                                    .join(", ")
                            )
                        })
                        .collect::<Vec<_>>()
                        .join("\n"),
                ),
            )),
            Err(e) => Ok((false, Some(format!("error: {e}")))),
        }
    }
}

struct GlobalPropertyCommand;
impl DebuggerCommand for GlobalPropertyCommand {
    fn extend(&self, command: Command) -> Command {
        global_properties::Args::augment_subcommands(command)
    }
    fn handle(
        &self,
        context: &mut Context,
        matches: &ArgMatches,
    ) -> Result<(bool, Option<String>), String> {
        let args = global_properties::Args::from_arg_matches(matches).unwrap();
        let ret = run_ext_api::<global_properties::Api>(context, &args);
        match ret {
            Err(IxaError::IxaError(e)) => Ok((false, Some(format!("error: {e}")))),
            Err(e) => Ok((false, Some(format!("error: {e}")))),
            Ok(global_properties::Retval::List(properties)) => Ok((
                false,
                Some(format!(
                    "{} global properties registered:\n{}",
                    properties.len(),
                    properties.join("\n")
                )),
            )),
            Ok(global_properties::Retval::Value(value)) => Ok((false, Some(value))),
        }
    }
}

/// Exits the debugger and ends the simulation.
struct HaltCommand;
impl DebuggerCommand for HaltCommand {
    fn handle(
        &self,
        context: &mut Context,
        _matches: &ArgMatches,
    ) -> Result<(bool, Option<String>), String> {
        context.shutdown();
        Ok((true, None))
    }
    fn extend(&self, command: Command) -> Command {
        halt::Args::augment_subcommands(command)
    }
}

/// Adds a new debugger breakpoint at t
struct NextCommand;
impl DebuggerCommand for NextCommand {
    fn handle(
        &self,
        context: &mut Context,
        _matches: &ArgMatches,
    ) -> Result<(bool, Option<String>), String> {
        // We execute directly instead of setting `Context::break_requested` so as not to interfere
        // with anything else that might be requesting a break, or in case debugger sessions become
        // stateful.
        context.execute_single_step();
        Ok((false, None))
    }
    fn extend(&self, command: Command) -> Command {
        next::Args::augment_subcommands(command)
    }
}

struct BreakpointCommand;
/// Adds a new debugger breakpoint at t
impl DebuggerCommand for BreakpointCommand {
    fn handle(
        &self,
        context: &mut Context,
        matches: &ArgMatches,
    ) -> Result<(bool, Option<String>), String> {
        let args = breakpoint::Args::from_arg_matches(matches).unwrap();
        match run_ext_api::<breakpoint::Api>(context, &args) {
            Err(IxaError::IxaError(e)) => Ok((false, Some(format!("error: {e}")))),
            Ok(return_value) => {
                match return_value {
                    breakpoint::Retval::List(bp_list) => {
                        let mut msg = format!("Scheduled breakpoints: {}\n", bp_list.len());
                        for bp in bp_list {
                            _ = writeln!(&mut msg, "\t{bp}");
                        }
                        return Ok((false, Some(msg)));
                    }
                    breakpoint::Retval::Ok => { /* pass */ }
                }

                Ok((false, None))
            }
            _ => unimplemented!(),
        }
    }
    fn extend(&self, command: Command) -> Command {
        breakpoint::Args::augment_subcommands(command)
    }
}

struct ContinueCommand;
#[derive(Parser, Debug)]
enum ContinueSubcommand {
    /// Exits the debugger and continues the simulation
    Continue,
}
impl DebuggerCommand for ContinueCommand {
    fn handle(
        &self,
        _context: &mut Context,
        _matches: &ArgMatches,
    ) -> Result<(bool, Option<String>), String> {
        Ok((true, None))
    }
    fn extend(&self, command: Command) -> Command {
        ContinueSubcommand::augment_subcommands(command)
    }
}

// Build the debugger context.
fn init(context: &mut Context) {
    let debugger = context.get_data_container_mut(DebuggerPlugin);

    if debugger.is_none() {
        trace!("initializing debugger");
        let mut commands: HashMap<&'static str, Box<dyn DebuggerCommand>> = HashMap::new();
        commands.insert("breakpoint", Box::new(BreakpointCommand));
        commands.insert("continue", Box::new(ContinueCommand));
        commands.insert("global", Box::new(GlobalPropertyCommand));
        commands.insert("halt", Box::new(HaltCommand));
        commands.insert("next", Box::new(NextCommand));
        commands.insert("people", Box::new(PeopleCommand));
        commands.insert("population", Box::new(PopulationCommand));

        let mut cli = Command::new("repl")
            .multicall(true)
            .arg_required_else_help(true)
            .subcommand_required(true)
            .subcommand_value_name("DEBUGGER")
            .subcommand_help_heading("IXA DEBUGGER")
            .help_template("{all-args}");

        for handler in commands.values() {
            cli = handler.extend(cli);
        }

        *debugger = Some(Debugger {
            rl: rustyline::DefaultEditor::new().unwrap(),
            cli,
            commands,
        });
    }
}

fn exit_debugger() -> ! {
    println!("Got Ctrl-D, Exiting...");
    std::process::exit(0);
}

/// Starts a debugging session.
#[allow(clippy::missing_panics_doc)]
pub fn enter_debugger(context: &mut Context) {
    init(context);
    run_with_plugin::<DebuggerPlugin>(context, |context, data_container| {
        start_debugger(context, data_container.as_mut().unwrap()).expect("Error in debugger");
    });
}

/// Enters the debugger REPL, interrupting the normal simulation event loop. This private
/// function is called from the public API `enter_debug()`.
fn start_debugger(context: &mut Context, debugger: &mut Debugger) -> Result<(), IxaError> {
    let t = context.get_current_time();

    println!("Debugging simulation at t={t}");
    loop {
        let line = match debugger.rl.readline(&format!("t={t} $ ")) {
            Ok(line) => line,
            Err(
                rustyline::error::ReadlineError::WindowResized
                | rustyline::error::ReadlineError::Interrupted,
            ) => continue,
            Err(rustyline::error::ReadlineError::Eof) => exit_debugger(),
            Err(err) => return Err(IxaError::IxaError(format!("Read error: {err}"))),
        };
        debugger
            .rl
            .add_history_entry(line.clone())
            .expect("Should be able to add to input");
        let line = line.trim();
        if line.is_empty() {
            continue;
        }

        match debugger.process_command(line, context) {
            Ok((quit, message)) => {
                if let Some(message) = message {
                    println!("{message}");
                }
                if quit {
                    break;
                }
            }
            Err(err) => {
                eprintln!("{err}");
            }
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::{enter_debugger, init, run_with_plugin, DebuggerPlugin};
    use crate::tests::run_external_runner;
    use crate::{define_global_property, define_person_property, ContextGlobalPropertiesExt};
    use crate::{Context, ContextPeopleExt, ExecutionPhase};
    use assert_approx_eq::assert_approx_eq;

    fn process_line(line: &str, context: &mut Context) -> (bool, Option<String>) {
        // Temporarily take the data container out of context so that
        // we can operate on context.
        init(context);
        let data_container = context.get_data_container_mut(DebuggerPlugin);
        let debugger = data_container.take().unwrap();

        let res = debugger.process_command(line, context).unwrap();
        let data_container = context.get_data_container_mut(DebuggerPlugin);
        *data_container = Some(debugger);
        res
    }

    define_global_property!(FooGlobal, String);
    define_global_property!(BarGlobal, u32);
    define_person_property!(Age, u8);
    define_person_property!(Smile, u32);

    #[test]
    fn test_cli_debugger_breakpoint_set() {
        let context = &mut Context::new();
        let (quits, _output) = process_line("breakpoint set 4.0\n", context);

        assert!(!quits, "should not exit");

        let list = context.list_breakpoints(0);
        assert_eq!(list.len(), 1);
        if let Some(schedule) = list.first() {
            assert_eq!(schedule.priority, ExecutionPhase::First);
            assert_eq!(schedule.plan_id, 0u64);
            assert_approx_eq!(schedule.time, 4.0f64);
        }
    }

    #[test]
    fn test_cli_debugger_breakpoint_list() {
        let context = &mut Context::new();

        context.schedule_debugger(1.0, None, Box::new(enter_debugger));
        context.schedule_debugger(2.0, Some(ExecutionPhase::First), Box::new(enter_debugger));
        context.schedule_debugger(3.0, Some(ExecutionPhase::Normal), Box::new(enter_debugger));
        context.schedule_debugger(4.0, Some(ExecutionPhase::Last), Box::new(enter_debugger));

        let expected = r"Scheduled breakpoints: 4
	0: t=1 (First)
	1: t=2 (First)
	2: t=3 (Normal)
	3: t=4 (Last)
";

        let (quits, output) = process_line("breakpoint list\n", context);

        assert!(!quits, "should not exit");
        assert!(output.is_some());
        assert_eq!(output.unwrap(), expected);
    }

    #[test]
    fn test_cli_debugger_breakpoint_delete_id() {
        let context = &mut Context::new();

        context.schedule_debugger(1.0, None, Box::new(enter_debugger));
        context.schedule_debugger(2.0, None, Box::new(enter_debugger));

        let (quits, _output) = process_line("breakpoint delete 0\n", context);
        assert!(!quits, "should not exit");
        let list = context.list_breakpoints(0);

        assert_eq!(list.len(), 1);
        if let Some(schedule) = list.first() {
            assert_eq!(schedule.priority, ExecutionPhase::First);
            assert_eq!(schedule.plan_id, 1u64);
            assert_approx_eq!(schedule.time, 2.0f64);
        }
    }

    #[test]
    fn test_cli_debugger_breakpoint_delete_all() {
        let context = &mut Context::new();

        context.schedule_debugger(1.0, None, Box::new(enter_debugger));
        context.schedule_debugger(2.0, None, Box::new(enter_debugger));

        let (quits, _output) = process_line("breakpoint delete --all\n", context);
        assert!(!quits, "should not exit");
        let list = context.list_breakpoints(0);
        assert_eq!(list.len(), 0);
    }

    #[test]
    fn test_cli_debugger_breakpoint_disable_enable() {
        let context = &mut Context::new();

        let (quits, _output) = process_line("breakpoint disable\n", context);
        assert!(!quits, "should not exit");
        assert!(!context.breakpoints_are_enabled());

        let (quits, _output) = process_line("breakpoint enable\n", context);
        assert!(!quits, "should not exit");
        assert!(context.breakpoints_are_enabled());
    }

    #[test]
    fn test_cli_debugger_integration() {
        run_external_runner("runner_test_debug")
            .unwrap()
            .args(["--debugger", "1.0"])
            .write_stdin("population\n")
            .write_stdin("continue\n")
            .assert()
            .success();
    }

    #[test]
    fn test_cli_debugger_population() {
        let context = &mut Context::new();
        // Add 2 people
        context.add_person(()).unwrap();
        context.add_person(()).unwrap();

        let (quits, output) = process_line("population\n", context);

        assert!(!quits, "should not exit");
        assert!(output.unwrap().contains('2'));
    }

    #[test]
    fn test_cli_debugger_people_get() {
        let context = &mut Context::new();
        // Add 2 people
        context.add_person((Age, 10)).unwrap();
        context.add_person((Age, 5)).unwrap();
        assert_eq!(context.remaining_plan_count(), 0);
        let (_, output) = process_line("people get 0 Age", context);
        assert_eq!(output.unwrap(), "Age: 10");
        let (_, output) = process_line("people get 1 Age", context);
        assert_eq!(output.unwrap(), "Age: 5");
    }

    #[test]
    fn test_cli_debugger_people_properties() {
        let context = &mut Context::new();
        // Add 2 people
        context.add_person(((Age, 10), (Smile, 50))).unwrap();
        context.add_person(((Age, 5), (Smile, 60))).unwrap();
        let (_, output) = process_line("people get 0 Smile", context);
        assert_eq!(output.unwrap(), "Smile: 50");
        let (_, output) = process_line("people properties", context);
        let properties = output.unwrap();
        assert!(properties.contains("Smile"));
        assert!(properties.contains("Age"));
    }

    #[test]
    fn test_cli_debugger_people_tabulate() {
        let context = &mut Context::new();
        // Add 3 people
        context.add_person(((Age, 10), (Smile, 50))).unwrap();
        context.add_person(((Age, 10), (Smile, 60))).unwrap();
        context.add_person(((Age, 10), (Smile, 60))).unwrap();
        let (_, output) = process_line("people tabulate Age", context);
        assert_eq!(output.unwrap(), "3: Age=10");
        let (_, output) = process_line("people tabulate Smile", context);
        let results = output.unwrap();
        assert!(results.contains("1: Smile=50"));
        assert!(results.contains("2: Smile=60"));
    }

    #[test]
    fn test_cli_debugger_global_list() {
        let context = &mut Context::new();
        let (_quits, output) = process_line("global list\n", context);
        let expected = format!(
            "{} global properties registered:",
            context.list_registered_global_properties().len()
        );
        // Note: the global property names are also listed as part of the output
        assert!(output.unwrap().contains(&expected));
    }

    #[test]
    fn test_cli_debugger_global_no_args() {
        let input = "global get\n";
        let context = &mut Context::new();
        init(context);
        // We can't use process_line here because we an expect an error to be
        // returned rather than string output
        run_with_plugin::<DebuggerPlugin>(context, |context, data_container| {
            let debugger = data_container.take().unwrap();

            let result = debugger.process_command(input, context);
            let data_container = context.get_data_container_mut(DebuggerPlugin);
            *data_container = Some(debugger);

            assert!(result.is_err());
            assert!(result
                .unwrap_err()
                .contains("required arguments were not provided"));
        });
    }

    #[test]
    fn test_cli_debugger_global_get_unregistered_prop() {
        let context = &mut Context::new();
        let (_quits, output) = process_line("global get NotExist\n", context);
        assert_eq!(output.unwrap(), "error: No global property: NotExist");
    }

    #[test]
    fn test_cli_debugger_global_get_registered_prop() {
        let context = &mut Context::new();
        context
            .set_global_property_value(FooGlobal, "hello".to_string())
            .unwrap();
        let (_quits, output) = process_line("global get ixa.FooGlobal\n", context);
        assert_eq!(output.unwrap(), "\"hello\"");
    }

    #[test]
    fn test_cli_debugger_global_get_empty_prop() {
        define_global_property!(EmptyGlobal, String);
        let context = &mut Context::new();
        let (_quits, output) = process_line("global get ixa.EmptyGlobal\n", context);
        assert_eq!(
            output.unwrap(),
            "error: Property ixa.EmptyGlobal is not set"
        );
    }

    #[test]
    fn test_cli_continue() {
        let context = &mut Context::new();
        let (quits, _) = process_line("continue\n", context);
        assert!(quits, "should exit");
    }

    #[test]
    fn test_cli_next() {
        let context = &mut Context::new();
        assert_eq!(context.remaining_plan_count(), 0);
        let (quits, _) = process_line("next\n", context);
        assert!(!quits, "should not exit");
    }
}