perl-dap 0.13.3

Debug Adapter Protocol server for Perl
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
//! DAP Message Dispatcher
#![allow(deprecated)]

mod handlers;
mod state;

use crate::protocol::{Event, Request, Response};
use anyhow::Result;
use serde_json::Value;

use handlers::{
    handle_configuration_done, handle_initialize, handle_inline_values, handle_set_breakpoints,
};
use state::DispatcherState;

#[deprecated(
    since = "0.2.0",
    note = "Use DebugAdapter directly; DapDispatcher will be removed in a future release"
)]
pub struct DispatchResult {
    pub response: Response,
    pub events: Vec<Event>,
}

#[deprecated(
    since = "0.2.0",
    note = "Use DebugAdapter directly; DapDispatcher will be removed in a future release"
)]
#[derive(Debug, Clone)]
pub struct DapDispatcher {
    state: DispatcherState,
}

impl DapDispatcher {
    pub fn new() -> Self {
        Self { state: DispatcherState::new() }
    }

    pub fn dispatch(&self, request: &Request) -> Response {
        self.dispatch_with_events(request).response
    }

    pub fn dispatch_with_events(&self, request: &Request) -> DispatchResult {
        let result = self.dispatch_inner(request);
        let success = result.is_ok();
        let response = self.create_response(request, result);
        let events = match (request.command.as_str(), success) {
            ("initialize", true) => vec![self.create_initialized_event()],
            _ => Vec::new(),
        };
        DispatchResult { response, events }
    }

    fn dispatch_inner(&self, request: &Request) -> Result<Value> {
        match request.command.as_str() {
            "initialize" => handle_initialize(request),
            "configurationDone" => handle_configuration_done(&self.state),
            "setBreakpoints" => handle_set_breakpoints(&self.state, request),
            "inlineValues" => handle_inline_values(request),
            _ => anyhow::bail!("Unknown command: {}", request.command),
        }
    }

    fn create_initialized_event(&self) -> Event {
        let mut seq = self.state.event_seq.lock().unwrap_or_else(|e| e.into_inner());
        let event_seq = *seq;
        *seq += 1;
        if let Ok(mut init) = self.state.initialized.lock() {
            *init = true;
        }

        Event {
            seq: event_seq,
            msg_type: "event".to_string(),
            event: "initialized".to_string(),
            body: None,
        }
    }

    fn create_response(&self, request: &Request, result: Result<Value>) -> Response {
        let mut seq = self.state.response_seq.lock().unwrap_or_else(|e| e.into_inner());
        let response_seq = *seq;
        *seq += 1;

        match result {
            Ok(body) => Response {
                seq: response_seq,
                msg_type: "response".to_string(),
                request_seq: request.seq,
                success: true,
                command: request.command.clone(),
                message: None,
                body: Some(body),
            },
            Err(err) => Response {
                seq: response_seq,
                msg_type: "response".to_string(),
                request_seq: request.seq,
                success: false,
                command: request.command.clone(),
                message: Some(err.to_string()),
                body: None,
            },
        }
    }

    #[cfg(test)]
    pub fn breakpoint_store(&self) -> &crate::breakpoints::BreakpointStore {
        &self.state.breakpoint_store
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::protocol::{Capabilities, InlineValuesResponseBody, SetBreakpointsResponseBody};
    use perl_tdd_support::must;
    use serde_json::json;
    use std::io::Write;
    use tempfile::NamedTempFile;

    /// Create a temp file with valid Perl code for testing breakpoints.
    /// NOTE: Avoid sub immediately followed by for loop (triggers parser hang - known issue)
    fn create_test_perl_file() -> (NamedTempFile, String) {
        let mut file = must(NamedTempFile::with_suffix(".pl"));
        let perl_code = r#"#!/usr/bin/perl
use strict;
use warnings;

my $x = 1;
my $y = 2;
my $z = $x + $y;

if ($x > 0) {
    print "positive\n";
}

my @arr = (1, 2, 3);
while (my $item = shift @arr) {
    my $doubled = $item * 2;
    print "$doubled\n";
}

sub process {
    my ($value) = @_;
    my $result = $value * 2;
    return $result;
}

print "done\n";
my $final = process($x);
print "result: $final\n";
"#;
        must(file.write_all(perl_code.as_bytes()));
        must(file.flush());
        let path = file.path().to_string_lossy().to_string();
        (file, path)
    }

    #[test]
    fn test_dispatcher_new() {
        let dispatcher = DapDispatcher::new();
        let breakpoints = dispatcher.breakpoint_store().get_breakpoints("/test.pl");
        assert_eq!(breakpoints.len(), 0);
    }

    #[test]
    fn test_handle_initialize() -> Result<(), Box<dyn std::error::Error>> {
        let dispatcher = DapDispatcher::new();
        let request = Request {
            seq: 1,
            msg_type: "request".to_string(),
            command: "initialize".to_string(),
            arguments: Some(json!({
                "clientId": "vscode",
                "clientName": "Visual Studio Code",
                "adapterId": "perl-rs",
                "linesStartAt1": true,
                "columnsStartAt1": true,
            })),
        };

        let response = dispatcher.dispatch(&request);

        if !response.success {
            eprintln!("Error: {:?}", response.message);
        }
        assert!(response.success);
        assert_eq!(response.command, "initialize");
        assert!(response.body.is_some());

        // Parse capabilities
        let capabilities: Capabilities =
            serde_json::from_value(response.body.ok_or("Expected body")?)?;
        assert_eq!(capabilities.supports_configuration_done_request, Some(true));
        assert_eq!(capabilities.supports_evaluate_for_hovers, Some(true));
        Ok(())
    }

    #[test]
    fn test_handle_set_breakpoints() -> Result<(), Box<dyn std::error::Error>> {
        let (_file, source_path) = create_test_perl_file();
        let dispatcher = DapDispatcher::new();
        let request = Request {
            seq: 2,
            msg_type: "request".to_string(),
            command: "setBreakpoints".to_string(),
            arguments: Some(json!({
                "source": {
                    "path": source_path,
                    "name": "script.pl"
                },
                "breakpoints": [
                    { "line": 10, "column": 0 },
                    { "line": 25, "column": 0 }
                ]
            })),
        };

        let response = dispatcher.dispatch(&request);

        assert!(response.success);
        assert_eq!(response.command, "setBreakpoints");
        assert!(response.body.is_some());

        // Parse response body
        let body: SetBreakpointsResponseBody =
            serde_json::from_value(response.body.ok_or("Expected body")?)?;
        assert_eq!(body.breakpoints.len(), 2);
        assert_eq!(body.breakpoints[0].line, 10);
        assert_eq!(body.breakpoints[1].line, 25);
        assert!(body.breakpoints[0].verified);
        assert!(body.breakpoints[1].verified);
        Ok(())
    }

    #[test]
    fn test_handle_set_breakpoints_replace_semantics() -> Result<(), Box<dyn std::error::Error>> {
        let (_file, source_path) = create_test_perl_file();
        let dispatcher = DapDispatcher::new();

        // Set initial breakpoints
        let request1 = Request {
            seq: 2,
            msg_type: "request".to_string(),
            command: "setBreakpoints".to_string(),
            arguments: Some(json!({
                "source": { "path": &source_path },
                "breakpoints": [{ "line": 10 }]
            })),
        };
        dispatcher.dispatch(&request1);

        // Replace with new breakpoints
        let request2 = Request {
            seq: 3,
            msg_type: "request".to_string(),
            command: "setBreakpoints".to_string(),
            arguments: Some(json!({
                "source": { "path": &source_path },
                "breakpoints": [{ "line": 20 }, { "line": 26 }]
            })),
        };
        let response = dispatcher.dispatch(&request2);

        assert!(response.success);
        let body: SetBreakpointsResponseBody =
            serde_json::from_value(response.body.ok_or("Expected body")?)?;
        assert_eq!(body.breakpoints.len(), 2);
        assert_eq!(body.breakpoints[0].line, 20);
        assert_eq!(body.breakpoints[1].line, 26);
        Ok(())
    }

    #[test]
    fn test_handle_set_breakpoints_preserves_order() -> Result<(), Box<dyn std::error::Error>> {
        let (_file, source_path) = create_test_perl_file();
        let dispatcher = DapDispatcher::new();
        let request = Request {
            seq: 2,
            msg_type: "request".to_string(),
            command: "setBreakpoints".to_string(),
            arguments: Some(json!({
                "source": { "path": &source_path },
                // Use lines within our 27-line test file, but out of order
                "breakpoints": [
                    { "line": 25 },
                    { "line": 10 },
                    { "line": 15 }
                ]
            })),
        };

        let response = dispatcher.dispatch(&request);

        assert!(response.success);
        let body: SetBreakpointsResponseBody =
            serde_json::from_value(response.body.ok_or("Expected body")?)?;

        // Order must match request
        assert_eq!(body.breakpoints[0].line, 25);
        assert_eq!(body.breakpoints[1].line, 10);
        assert_eq!(body.breakpoints[2].line, 15);
        Ok(())
    }

    #[test]
    fn test_handle_unknown_command() -> Result<(), Box<dyn std::error::Error>> {
        let dispatcher = DapDispatcher::new();
        let request = Request {
            seq: 99,
            msg_type: "request".to_string(),
            command: "unknownCommand".to_string(),
            arguments: None,
        };

        let response = dispatcher.dispatch(&request);

        assert!(!response.success);
        assert_eq!(response.command, "unknownCommand");
        assert!(response.message.is_some());
        assert!(
            response.message.ok_or("Expected message")?.contains("Unknown command: unknownCommand")
        );
        Ok(())
    }

    #[test]
    fn test_handle_set_breakpoints_missing_arguments() {
        let dispatcher = DapDispatcher::new();
        let request = Request {
            seq: 2,
            msg_type: "request".to_string(),
            command: "setBreakpoints".to_string(),
            arguments: None,
        };

        let response = dispatcher.dispatch(&request);

        assert!(!response.success);
        assert!(response.message.is_some());
    }

    #[test]
    fn test_handle_inline_values() -> Result<(), Box<dyn std::error::Error>> {
        let mut file = NamedTempFile::with_suffix(".pl")?;
        let perl_code = "my $x = 1;\nmy $y = $x + 2;\n";
        file.write_all(perl_code.as_bytes())?;
        file.flush()?;
        let path = file.path().to_string_lossy().to_string();

        let dispatcher = DapDispatcher::new();
        let request = Request {
            seq: 3,
            msg_type: "request".to_string(),
            command: "inlineValues".to_string(),
            arguments: Some(json!({
                "source": { "path": path },
                "startLine": 1,
                "endLine": 2
            })),
        };

        let response = dispatcher.dispatch(&request);
        assert!(response.success);

        let body: InlineValuesResponseBody =
            serde_json::from_value(response.body.ok_or("Expected body")?)?;
        assert!(body.inline_values.iter().any(|v| v.text.contains("$x")));
        assert!(body.inline_values.iter().any(|v| v.text.contains("$y")));
        Ok(())
    }

    #[test]
    fn test_response_sequence_numbers() {
        let dispatcher = DapDispatcher::new();

        let request1 = Request {
            seq: 1,
            msg_type: "request".to_string(),
            command: "initialize".to_string(),
            arguments: None,
        };
        let response1 = dispatcher.dispatch(&request1);

        let request2 = Request {
            seq: 2,
            msg_type: "request".to_string(),
            command: "initialize".to_string(),
            arguments: None,
        };
        let response2 = dispatcher.dispatch(&request2);

        // Response sequence numbers should increment
        assert_eq!(response1.seq, 1);
        assert_eq!(response2.seq, 2);
    }

    #[test]
    fn test_initialize_emits_initialized_event() {
        let dispatcher = DapDispatcher::new();
        let request = Request {
            seq: 1,
            msg_type: "request".to_string(),
            command: "initialize".to_string(),
            arguments: Some(json!({
                "clientId": "vscode",
                "adapterId": "perl-rs",
            })),
        };

        let result = dispatcher.dispatch_with_events(&request);

        // Response should be successful
        assert!(result.response.success);
        assert_eq!(result.response.command, "initialize");

        // Should emit initialized event
        assert_eq!(result.events.len(), 1);
        let event = &result.events[0];
        assert_eq!(event.event, "initialized");
        assert_eq!(event.msg_type, "event");
        assert!(event.body.is_none()); // initialized event has no body
    }

    #[test]
    fn test_configuration_done_after_initialize() {
        let dispatcher = DapDispatcher::new();

        // First, initialize
        let init_request = Request {
            seq: 1,
            msg_type: "request".to_string(),
            command: "initialize".to_string(),
            arguments: None,
        };
        let init_result = dispatcher.dispatch_with_events(&init_request);
        assert!(init_result.response.success);

        // Then, configurationDone should succeed
        let config_done_request = Request {
            seq: 2,
            msg_type: "request".to_string(),
            command: "configurationDone".to_string(),
            arguments: None,
        };
        let response = dispatcher.dispatch(&config_done_request);

        assert!(response.success);
        assert_eq!(response.command, "configurationDone");
    }

    #[test]
    fn test_configuration_done_before_initialize_fails() -> Result<(), Box<dyn std::error::Error>> {
        let dispatcher = DapDispatcher::new();

        // configurationDone without initialize should fail
        let request = Request {
            seq: 1,
            msg_type: "request".to_string(),
            command: "configurationDone".to_string(),
            arguments: None,
        };
        let response = dispatcher.dispatch(&request);

        assert!(!response.success);
        assert!(response.message.is_some());
        assert!(response.message.ok_or("Expected message")?.contains("before initialized"));
        Ok(())
    }

    #[test]
    fn test_event_sequence_numbers() {
        let dispatcher = DapDispatcher::new();

        // Multiple initializations should have incrementing event seq numbers
        let request1 = Request {
            seq: 1,
            msg_type: "request".to_string(),
            command: "initialize".to_string(),
            arguments: None,
        };
        let result1 = dispatcher.dispatch_with_events(&request1);

        let request2 = Request {
            seq: 2,
            msg_type: "request".to_string(),
            command: "initialize".to_string(),
            arguments: None,
        };
        let result2 = dispatcher.dispatch_with_events(&request2);

        // Event sequence numbers should increment
        assert_eq!(result1.events[0].seq, 1);
        assert_eq!(result2.events[0].seq, 2);
    }

    #[test]
    fn test_failed_initialize_no_event() {
        let dispatcher = DapDispatcher::new();

        // Invalid arguments that cause parsing to fail
        let request = Request {
            seq: 1,
            msg_type: "request".to_string(),
            command: "initialize".to_string(),
            arguments: Some(json!({
                "adapterId": 123 // Should be string, not number
            })),
        };

        let result = dispatcher.dispatch_with_events(&request);

        // If initialization fails, no event should be emitted
        if !result.response.success {
            assert!(result.events.is_empty());
        }
    }
}