perl-dap-variables 0.12.2

Variable rendering for Perl DAP
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
//! Parser for Perl debugger variable output.
//!
//! This module provides utilities for parsing variable output from the Perl debugger
//! into structured [`PerlValue`] representations.

use crate::PerlValue;
use once_cell::sync::Lazy;
use regex::Regex;
use thiserror::Error;

/// Errors that can occur during variable parsing.
#[derive(Debug, Error)]
pub enum VariableParseError {
    /// The input format was not recognized.
    #[error("unrecognized variable format: {0}")]
    UnrecognizedFormat(String),

    /// A nested structure was too deep.
    #[error("maximum nesting depth exceeded ({0})")]
    MaxDepthExceeded(usize),

    /// A string literal was not properly terminated.
    #[error("unterminated string literal")]
    UnterminatedString,

    /// An array or hash was not properly closed.
    #[error("unterminated collection")]
    UnterminatedCollection,

    /// A regex pattern failed to compile.
    #[error("regex error: {0}")]
    RegexError(#[from] regex::Error),
}

// Compiled regex patterns for variable parsing.
// Stored as Results to avoid panics. All patterns are compile-time constants,
// so failure is not expected, but this provides graceful degradation.

static SCALAR_VAR_RE: Lazy<Result<Regex, regex::Error>> =
    Lazy::new(|| Regex::new(r"^\s*(?P<name>[\$\@\%][\w:]+)\s*=\s*(?P<value>.*?)$"));

static UNDEF_RE: Lazy<Result<Regex, regex::Error>> = Lazy::new(|| Regex::new(r"^undef$"));

static INTEGER_RE: Lazy<Result<Regex, regex::Error>> = Lazy::new(|| Regex::new(r"^-?\d+$"));

static NUMBER_RE: Lazy<Result<Regex, regex::Error>> =
    Lazy::new(|| Regex::new(r"^-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$"));

static QUOTED_STRING_RE: Lazy<Result<Regex, regex::Error>> =
    Lazy::new(|| Regex::new(r#"^'(?:[^'\\]|\\.)*'|^"(?:[^"\\]|\\.)*""#));

static ARRAY_REF_RE: Lazy<Result<Regex, regex::Error>> =
    Lazy::new(|| Regex::new(r"^ARRAY\(0x[0-9a-fA-F]+\)$"));

static HASH_REF_RE: Lazy<Result<Regex, regex::Error>> =
    Lazy::new(|| Regex::new(r"^HASH\(0x[0-9a-fA-F]+\)$"));

static CODE_REF_RE: Lazy<Result<Regex, regex::Error>> =
    Lazy::new(|| Regex::new(r"^CODE\(0x[0-9a-fA-F]+\)$"));

static OBJECT_RE: Lazy<Result<Regex, regex::Error>> = Lazy::new(|| {
    Regex::new(r"^(?P<class>[\w:]+)=(?P<type>ARRAY|HASH|SCALAR|GLOB)\(0x[0-9a-fA-F]+\)$")
});

static GLOB_RE: Lazy<Result<Regex, regex::Error>> =
    Lazy::new(|| Regex::new(r"^\*(?P<name>[\w:]+)$"));

/// Regex for parsing compiled regexp values (reserved for future use)
#[allow(dead_code)]
static REGEX_RE: Lazy<Result<Regex, regex::Error>> =
    Lazy::new(|| Regex::new(r"^(?:\(\?(?P<flags>[xism-]*)(?:-[xism]+)?:)?(?P<pattern>.*?)\)?$"));

// Accessor functions - return Option<&Regex>, treating compile failure as "no match"
fn scalar_var_re() -> Option<&'static Regex> {
    SCALAR_VAR_RE.as_ref().ok()
}
fn undef_re() -> Option<&'static Regex> {
    UNDEF_RE.as_ref().ok()
}
fn integer_re() -> Option<&'static Regex> {
    INTEGER_RE.as_ref().ok()
}
fn number_re() -> Option<&'static Regex> {
    NUMBER_RE.as_ref().ok()
}
fn quoted_string_re() -> Option<&'static Regex> {
    QUOTED_STRING_RE.as_ref().ok()
}
fn array_ref_re() -> Option<&'static Regex> {
    ARRAY_REF_RE.as_ref().ok()
}
fn hash_ref_re() -> Option<&'static Regex> {
    HASH_REF_RE.as_ref().ok()
}
fn code_ref_re() -> Option<&'static Regex> {
    CODE_REF_RE.as_ref().ok()
}
fn object_re() -> Option<&'static Regex> {
    OBJECT_RE.as_ref().ok()
}
fn glob_re() -> Option<&'static Regex> {
    GLOB_RE.as_ref().ok()
}

/// Parser for Perl debugger variable output.
///
/// This parser converts text output from the Perl debugger's variable
/// inspection commands into structured [`PerlValue`] representations.
#[derive(Debug, Default)]
pub struct VariableParser {
    /// Maximum nesting depth for recursive parsing
    max_depth: usize,
}

impl VariableParser {
    /// Creates a new variable parser with default settings.
    #[must_use]
    pub fn new() -> Self {
        Self { max_depth: 50 }
    }

    /// Sets the maximum nesting depth for parsing.
    #[must_use]
    pub fn with_max_depth(mut self, depth: usize) -> Self {
        self.max_depth = depth;
        self
    }

    /// Parses a variable assignment line from debugger output.
    ///
    /// # Arguments
    ///
    /// * `line` - A line like "$var = value" or "@arr = (1, 2, 3)"
    ///
    /// # Returns
    ///
    /// A tuple of (variable name, parsed value) if successful.
    ///
    /// # Errors
    ///
    /// Returns a [`VariableParseError`] if the line cannot be parsed.
    pub fn parse_assignment(&self, line: &str) -> Result<(String, PerlValue), VariableParseError> {
        let re = scalar_var_re()
            .ok_or_else(|| VariableParseError::UnrecognizedFormat(line.to_string()))?;
        if let Some(caps) = re.captures(line) {
            let name = caps
                .name("name")
                .ok_or_else(|| VariableParseError::UnrecognizedFormat(line.to_string()))?
                .as_str()
                .to_string();
            let value_str = caps
                .name("value")
                .ok_or_else(|| VariableParseError::UnrecognizedFormat(line.to_string()))?
                .as_str();
            let value = self.parse_value(value_str, 0)?;
            Ok((name, value))
        } else {
            Err(VariableParseError::UnrecognizedFormat(line.to_string()))
        }
    }

    /// Parses a value string from debugger output.
    ///
    /// # Arguments
    ///
    /// * `text` - The value portion of debugger output
    ///
    /// # Returns
    ///
    /// The parsed [`PerlValue`].
    ///
    /// # Errors
    ///
    /// Returns a [`VariableParseError`] if the value cannot be parsed.
    pub fn parse_value(&self, text: &str, depth: usize) -> Result<PerlValue, VariableParseError> {
        if depth > self.max_depth {
            return Err(VariableParseError::MaxDepthExceeded(self.max_depth));
        }

        let text = text.trim();

        // Check for undef
        if undef_re().is_some_and(|re| re.is_match(text)) {
            return Ok(PerlValue::Undef);
        }

        // Check for integer
        if integer_re().is_some_and(|re| re.is_match(text)) {
            if let Ok(i) = text.parse::<i64>() {
                return Ok(PerlValue::Integer(i));
            }
        }

        // Check for number
        if number_re().is_some_and(|re| re.is_match(text)) {
            if let Ok(n) = text.parse::<f64>() {
                return Ok(PerlValue::Number(n));
            }
        }

        // Check for quoted string
        if quoted_string_re().is_some_and(|re| re.is_match(text)) {
            let unquoted = self.unquote_string(text)?;
            return Ok(PerlValue::Scalar(unquoted));
        }

        // Check for array reference notation
        if array_ref_re().is_some_and(|re| re.is_match(text)) {
            return Ok(PerlValue::Array(vec![]));
        }

        // Check for hash reference notation
        if hash_ref_re().is_some_and(|re| re.is_match(text)) {
            return Ok(PerlValue::Hash(vec![]));
        }

        // Check for code reference
        if code_ref_re().is_some_and(|re| re.is_match(text)) {
            return Ok(PerlValue::Code { name: None });
        }

        // Check for blessed object
        if let Some(caps) = object_re().and_then(|re| re.captures(text)) {
            let class = caps
                .name("class")
                .ok_or_else(|| VariableParseError::UnrecognizedFormat(text.to_string()))?
                .as_str()
                .to_string();
            let type_str = caps
                .name("type")
                .ok_or_else(|| VariableParseError::UnrecognizedFormat(text.to_string()))?
                .as_str();
            let inner = match type_str {
                "ARRAY" => PerlValue::Array(vec![]),
                "HASH" => PerlValue::Hash(vec![]),
                _ => PerlValue::Scalar(String::new()),
            };
            return Ok(PerlValue::Object { class, value: Box::new(inner) });
        }

        // Check for glob
        if let Some(caps) = glob_re().and_then(|re| re.captures(text)) {
            let name = caps
                .name("name")
                .ok_or_else(|| VariableParseError::UnrecognizedFormat(text.to_string()))?
                .as_str()
                .to_string();
            return Ok(PerlValue::Glob(name));
        }

        // Check for array literal
        if text.starts_with('(') && text.ends_with(')') {
            return self.parse_array_literal(text, depth);
        }

        // Check for array bracket literal
        if text.starts_with('[') && text.ends_with(']') {
            return self.parse_array_literal(text, depth);
        }

        // Check for hash literal
        if text.starts_with('{') && text.ends_with('}') {
            return self.parse_hash_literal(text, depth);
        }

        // Treat as unquoted scalar (bareword or other)
        Ok(PerlValue::Scalar(text.to_string()))
    }

    /// Parses an array literal like (1, 2, 3) or [1, 2, 3].
    fn parse_array_literal(
        &self,
        text: &str,
        depth: usize,
    ) -> Result<PerlValue, VariableParseError> {
        // Remove outer delimiters (works for both '(' and '[')
        let inner = &text[1..text.len() - 1];

        if inner.trim().is_empty() {
            return Ok(PerlValue::Array(vec![]));
        }

        let elements = self.split_elements(inner)?;
        let parsed: Result<Vec<PerlValue>, _> =
            elements.iter().map(|e| self.parse_value(e, depth + 1)).collect();

        Ok(PerlValue::Array(parsed?))
    }

    /// Parses a hash literal like {key => value, ...}.
    fn parse_hash_literal(
        &self,
        text: &str,
        depth: usize,
    ) -> Result<PerlValue, VariableParseError> {
        // Remove outer braces
        let inner = &text[1..text.len() - 1];

        if inner.trim().is_empty() {
            return Ok(PerlValue::Hash(vec![]));
        }

        let elements = self.split_elements(inner)?;
        let mut pairs = Vec::new();

        for element in elements {
            if let Some((key, value)) = element.split_once("=>") {
                let key = self.unquote_key(key.trim());
                let value = self.parse_value(value.trim(), depth + 1)?;
                pairs.push((key, value));
            } else {
                // Treat as key with undef value
                let key = self.unquote_key(element.trim());
                pairs.push((key, PerlValue::Undef));
            }
        }

        Ok(PerlValue::Hash(pairs))
    }

    /// Splits a comma-separated list while respecting nested structures.
    fn split_elements(&self, text: &str) -> Result<Vec<String>, VariableParseError> {
        let mut elements = Vec::new();
        let mut current = String::new();
        let mut paren_depth: u32 = 0;
        let mut bracket_depth: u32 = 0;
        let mut brace_depth: u32 = 0;
        let mut in_string = false;
        let mut string_char = ' ';
        let mut escape_next = false;

        for ch in text.chars() {
            if escape_next {
                current.push(ch);
                escape_next = false;
                continue;
            }

            if ch == '\\' {
                current.push(ch);
                escape_next = true;
                continue;
            }

            if in_string {
                current.push(ch);
                if ch == string_char {
                    in_string = false;
                }
                continue;
            }

            match ch {
                '"' | '\'' => {
                    current.push(ch);
                    in_string = true;
                    string_char = ch;
                }
                '(' => {
                    current.push(ch);
                    paren_depth += 1;
                }
                ')' => {
                    current.push(ch);
                    paren_depth = paren_depth.saturating_sub(1);
                }
                '[' => {
                    current.push(ch);
                    bracket_depth += 1;
                }
                ']' => {
                    current.push(ch);
                    bracket_depth = bracket_depth.saturating_sub(1);
                }
                '{' => {
                    current.push(ch);
                    brace_depth += 1;
                }
                '}' => {
                    current.push(ch);
                    brace_depth = brace_depth.saturating_sub(1);
                }
                ',' if paren_depth == 0 && bracket_depth == 0 && brace_depth == 0 => {
                    let trimmed = current.trim().to_string();
                    if !trimmed.is_empty() {
                        elements.push(trimmed);
                    }
                    current = String::new();
                }
                _ => {
                    current.push(ch);
                }
            }
        }

        // Add the last element
        let trimmed = current.trim().to_string();
        if !trimmed.is_empty() {
            elements.push(trimmed);
        }

        Ok(elements)
    }

    /// Removes quotes from a string value.
    fn unquote_string(&self, text: &str) -> Result<String, VariableParseError> {
        if text.len() < 2 {
            return Err(VariableParseError::UnterminatedString);
        }

        let first = text.chars().next();
        let last = text.chars().next_back();

        match (first, last) {
            (Some('"'), Some('"')) | (Some('\''), Some('\'')) => {
                let inner = &text[1..text.len() - 1];
                Ok(self.unescape_string(inner))
            }
            _ => Ok(text.to_string()),
        }
    }

    /// Removes quotes from a hash key (or returns as-is if not quoted).
    fn unquote_key(&self, text: &str) -> String {
        if text.len() >= 2 {
            let first = text.chars().next();
            let last = text.chars().next_back();

            match (first, last) {
                (Some('"'), Some('"')) | (Some('\''), Some('\'')) => {
                    return self.unescape_string(&text[1..text.len() - 1]);
                }
                _ => {}
            }
        }
        text.to_string()
    }

    /// Unescapes common escape sequences in a string.
    fn unescape_string(&self, text: &str) -> String {
        let mut result = String::with_capacity(text.len());
        let mut chars = text.chars().peekable();

        while let Some(ch) = chars.next() {
            if ch == '\\' {
                match chars.next() {
                    Some('n') => result.push('\n'),
                    Some('r') => result.push('\r'),
                    Some('t') => result.push('\t'),
                    Some('\\') => result.push('\\'),
                    Some('"') => result.push('"'),
                    Some('\'') => result.push('\''),
                    Some(other) => {
                        result.push('\\');
                        result.push(other);
                    }
                    None => result.push('\\'),
                }
            } else {
                result.push(ch);
            }
        }

        result
    }

    /// Parses multiple variable lines (e.g., from 'V' command output).
    ///
    /// # Arguments
    ///
    /// * `output` - Multi-line debugger output
    ///
    /// # Returns
    ///
    /// A vector of (name, value) pairs for successfully parsed variables.
    pub fn parse_variables(&self, output: &str) -> Vec<(String, PerlValue)> {
        output.lines().filter_map(|line| self.parse_assignment(line).ok()).collect()
    }
}

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

    #[test]
    fn test_parse_undef() {
        let parser = VariableParser::new();
        let result = parser.parse_value("undef", 0);
        assert!(matches!(result, Ok(PerlValue::Undef)));
    }

    #[test]
    fn test_parse_integer() {
        let parser = VariableParser::new();

        let result = parser.parse_value("42", 0);
        assert!(matches!(result, Ok(PerlValue::Integer(42))));

        let result = parser.parse_value("-17", 0);
        assert!(matches!(result, Ok(PerlValue::Integer(-17))));
    }

    #[test]
    fn test_parse_number() {
        let parser = VariableParser::new();

        let result = parser.parse_value("3.25", 0);
        assert!(matches!(result, Ok(PerlValue::Number(n)) if (n - 3.25).abs() < 0.001));

        let result = parser.parse_value("1.5e10", 0);
        assert!(matches!(result, Ok(PerlValue::Number(_))));
    }

    #[test]
    fn test_parse_quoted_string() {
        let parser = VariableParser::new();

        let result = parser.parse_value("\"hello\"", 0);
        assert!(matches!(result, Ok(PerlValue::Scalar(s)) if s == "hello"));

        let result = parser.parse_value("'world'", 0);
        assert!(matches!(result, Ok(PerlValue::Scalar(s)) if s == "world"));
    }

    #[test]
    fn test_parse_string_with_escapes() {
        let parser = VariableParser::new();

        let result = parser.parse_value("\"line1\\nline2\"", 0);
        assert!(matches!(result, Ok(PerlValue::Scalar(s)) if s.contains('\n')));
    }

    #[test]
    fn test_parse_array_reference() {
        let parser = VariableParser::new();

        let result = parser.parse_value("ARRAY(0x1234abcd)", 0);
        assert!(matches!(result, Ok(PerlValue::Array(_))));
    }

    #[test]
    fn test_parse_hash_reference() {
        let parser = VariableParser::new();

        let result = parser.parse_value("HASH(0x5678abcd)", 0);
        assert!(matches!(result, Ok(PerlValue::Hash(_))));
    }

    #[test]
    fn test_parse_code_reference() {
        let parser = VariableParser::new();

        let result = parser.parse_value("CODE(0xdeadbeef)", 0);
        assert!(matches!(result, Ok(PerlValue::Code { name: None })));
    }

    #[test]
    fn test_parse_object() {
        let parser = VariableParser::new();

        let result = parser.parse_value("My::Class=HASH(0x1234)", 0);
        assert!(matches!(result, Ok(PerlValue::Object { class, .. }) if class == "My::Class"));
    }

    #[test]
    fn test_parse_glob() {
        let parser = VariableParser::new();

        let result = parser.parse_value("*main::foo", 0);
        assert!(matches!(result, Ok(PerlValue::Glob(name)) if name == "main::foo"));
    }

    #[test]
    fn test_parse_array_literal() {
        let parser = VariableParser::new();

        let result = parser.parse_value("(1, 2, 3)", 0);
        assert!(matches!(result, Ok(PerlValue::Array(arr)) if arr.len() == 3));

        let result = parser.parse_value("[1, 2, 3]", 0);
        assert!(matches!(result, Ok(PerlValue::Array(arr)) if arr.len() == 3));

        let result = parser.parse_value("()", 0);
        assert!(matches!(result, Ok(PerlValue::Array(arr)) if arr.is_empty()));
    }

    #[test]
    fn test_parse_hash_literal() {
        let parser = VariableParser::new();

        let result = parser.parse_value("{foo => 1, bar => 2}", 0);
        assert!(matches!(result, Ok(PerlValue::Hash(pairs)) if pairs.len() == 2));

        let result = parser.parse_value("{}", 0);
        assert!(matches!(result, Ok(PerlValue::Hash(pairs)) if pairs.is_empty()));
    }

    #[test]
    fn test_parse_assignment() {
        let parser = VariableParser::new();

        let result = parser.parse_assignment("$x = 42");
        assert!(matches!(result, Ok((name, PerlValue::Integer(42))) if name == "$x"));

        let result = parser.parse_assignment("@arr = (1, 2, 3)");
        assert!(matches!(result, Ok((name, PerlValue::Array(_))) if name == "@arr"));

        let result = parser.parse_assignment("%hash = {a => 1}");
        assert!(matches!(result, Ok((name, PerlValue::Hash(_))) if name == "%hash"));
    }

    #[test]
    fn test_parse_variables_multi_line() {
        let parser = VariableParser::new();

        let output = "$x = 1\n$y = 2\n$z = \"hello\"";
        let vars = parser.parse_variables(output);

        assert_eq!(vars.len(), 3);
        assert_eq!(vars[0].0, "$x");
        assert_eq!(vars[1].0, "$y");
        assert_eq!(vars[2].0, "$z");
    }

    #[test]
    fn test_max_depth_exceeded() {
        let parser = VariableParser::new().with_max_depth(2);

        // Create deeply nested structure
        let result = parser.parse_value("(((1)))", 0);
        assert!(matches!(result, Err(VariableParseError::MaxDepthExceeded(_))));
    }

    #[test]
    fn test_parse_nested_structure() {
        let parser = VariableParser::new();

        let result = parser.parse_value("{arr => [1, 2], hash => {a => 1}}", 0);
        assert!(matches!(result, Ok(PerlValue::Hash(pairs)) if pairs.len() == 2));
    }
}