perl-corpus 0.13.3

Test corpus management and generators for Perl parsers
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
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};

/// Assertion type for gold corpus diagnostics expectations
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "assertion")]
pub enum GoldAssertion {
    /// No diagnostics should be emitted for this fixture
    #[serde(rename = "no_diagnostics")]
    NoDiagnostics,

    /// A specific diagnostic should NOT be present
    #[serde(rename = "no_diagnostic")]
    NoDiagnostic { code: String },

    /// A diagnostic with the given code should be present
    #[serde(rename = "diagnostic_present")]
    DiagnosticPresent {
        code: String,
        #[serde(default)]
        byte_offset: Option<usize>,
        #[serde(default)]
        message_contains: Option<String>,
    },

    /// Expect exactly N diagnostics with the given code
    #[serde(rename = "diagnostic_count")]
    DiagnosticCount { code: String, count: usize },
}

/// Expected diagnostics for a gold corpus fixture
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GoldExpected {
    pub diagnostics: Vec<GoldAssertion>,
}

/// A gold corpus test fixture with expected results
#[derive(Debug, Clone)]
pub struct GoldFixture {
    pub name: String,
    pub fixture_path: PathBuf,
    pub expected: GoldExpected,
}

/// Load a single gold fixture from a directory
///
/// Expects a directory with:
/// - `fixture.pl` — the Perl source code to test
/// - `expected.json` — JSON file with GoldExpected assertions
pub fn load_gold_fixture<P: AsRef<Path>>(
    dir: P,
) -> Result<GoldFixture, Box<dyn std::error::Error>> {
    let dir = dir.as_ref();
    let name = dir.file_name().ok_or("No directory name")?.to_string_lossy().to_string();

    let fixture_path = dir.join("fixture.pl");
    let expected_path = dir.join("expected.json");

    if !fixture_path.exists() {
        return Err(format!("fixture.pl not found in {}", dir.display()).into());
    }
    if !expected_path.exists() {
        return Err(format!("expected.json not found in {}", dir.display()).into());
    }

    let expected_json = fs::read_to_string(&expected_path)?;
    let expected: GoldExpected = serde_json::from_str(&expected_json)?;

    Ok(GoldFixture { name, fixture_path, expected })
}

/// Load all gold fixtures from a directory
///
/// Walks the directory and loads all subdirectories as fixtures.
pub fn load_gold_fixtures<P: AsRef<Path>>(
    root: P,
) -> Result<Vec<GoldFixture>, Box<dyn std::error::Error>> {
    load_gold_fixtures_from(root)
}

/// Load all gold fixtures from a directory
///
/// Walks the directory and loads all subdirectories as fixtures.
pub fn load_gold_fixtures_from<P: AsRef<Path>>(
    root: P,
) -> Result<Vec<GoldFixture>, Box<dyn std::error::Error>> {
    let root = root.as_ref();
    let mut fixtures = Vec::new();

    if !root.exists() {
        return Err(format!("Gold fixtures directory not found: {}", root.display()).into());
    }

    for entry in fs::read_dir(root)? {
        let entry = entry?;
        let path = entry.path();

        if path.is_dir() {
            match load_gold_fixture(&path) {
                Ok(fixture) => fixtures.push(fixture),
                Err(e) => {
                    // Use tracing instead of eprintln
                    tracing::warn!("Failed to load fixture from {}: {}", path.display(), e);
                }
            }
        }
    }

    // Sort by name for consistent ordering
    fixtures.sort_by(|a, b| a.name.cmp(&b.name));

    Ok(fixtures)
}

// ---------------------------------------------------------------------------
// Editor Intelligence — Hover
// ---------------------------------------------------------------------------

/// Assertion kind for hover gold corpus entries
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "kind")]
pub enum HoverAssertionKind {
    /// Response must have non-null, non-empty content
    HoverNonNull,
    /// Response must be null (no hover available)
    HoverNull,
    /// Response content must contain `needle` (case-sensitive)
    HoverContains { needle: String },
    /// Response content must NOT contain `needle`
    HoverAbsent { needle: String },
}

/// A single hover assertion at a given (line, character) position
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HoverAssertion {
    #[serde(flatten)]
    pub kind: HoverAssertionKind,
    pub line: u32,
    pub character: u32,
    #[serde(default)]
    pub rationale: String,
}

/// On-disk representation of `expected_hover.json`
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HoverGoldExpected {
    pub version: u32,
    pub fixture: String,
    pub assertions: Vec<HoverAssertion>,
}

/// A hover gold fixture (fixture.pl + expected_hover.json)
#[derive(Debug, Clone)]
pub struct HoverGoldFixture {
    pub name: String,
    pub fixture_path: PathBuf,
    pub hover_assertions: Vec<HoverAssertion>,
}

/// Load all hover gold fixtures from a directory.
///
/// Walks the directory and loads all subdirectories that contain both
/// `fixture.pl` and `expected_hover.json`. Directories that lack
/// `expected_hover.json` are silently skipped.
pub fn load_hover_gold_fixtures<P: AsRef<Path>>(
    root: P,
) -> Result<Vec<HoverGoldFixture>, Box<dyn std::error::Error>> {
    let root = root.as_ref();
    let mut fixtures = Vec::new();

    if !root.exists() {
        return Err(format!("Gold fixtures directory not found: {}", root.display()).into());
    }

    for entry in fs::read_dir(root)? {
        let entry = entry?;
        let path = entry.path();

        if !path.is_dir() {
            continue;
        }

        let fixture_path = path.join("fixture.pl");
        let hover_path = path.join("expected_hover.json");

        if !fixture_path.exists() || !hover_path.exists() {
            continue; // not a hover fixture
        }

        let name = path.file_name().ok_or("No directory name")?.to_string_lossy().to_string();
        let json = fs::read_to_string(&hover_path)?;
        let expected: HoverGoldExpected = serde_json::from_str(&json)
            .map_err(|e| format!("Parsing {}: {e}", hover_path.display()))?;

        fixtures.push(HoverGoldFixture {
            name,
            fixture_path,
            hover_assertions: expected.assertions,
        });
    }

    fixtures.sort_by(|a, b| a.name.cmp(&b.name));
    Ok(fixtures)
}

// ---------------------------------------------------------------------------
// Editor Intelligence — Goto-Definition
// ---------------------------------------------------------------------------

/// Assertion kind for goto-definition gold corpus entries
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "kind")]
pub enum GotoAssertionKind {
    /// Response must return at least one location
    GotoNonNull,
    /// Response must return no locations
    GotoNull,
    /// The first returned location must be on the given line
    GotoLine { expected_line: u32 },
}

/// A single goto-definition assertion at a given (line, character) position
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GotoAssertion {
    #[serde(flatten)]
    pub kind: GotoAssertionKind,
    pub line: u32,
    pub character: u32,
    #[serde(default)]
    pub rationale: String,
}

/// On-disk representation of `expected_goto.json`
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GotoGoldExpected {
    pub version: u32,
    pub fixture: String,
    pub assertions: Vec<GotoAssertion>,
}

/// A goto-definition gold fixture (fixture.pl + expected_goto.json)
#[derive(Debug, Clone)]
pub struct GotoGoldFixture {
    pub name: String,
    pub fixture_path: PathBuf,
    pub goto_assertions: Vec<GotoAssertion>,
}

/// Load all goto-definition gold fixtures from a directory.
///
/// Silently skips directories that lack `expected_goto.json`.
pub fn load_goto_gold_fixtures<P: AsRef<Path>>(
    root: P,
) -> Result<Vec<GotoGoldFixture>, Box<dyn std::error::Error>> {
    let root = root.as_ref();
    let mut fixtures = Vec::new();

    if !root.exists() {
        return Err(format!("Gold fixtures directory not found: {}", root.display()).into());
    }

    for entry in fs::read_dir(root)? {
        let entry = entry?;
        let path = entry.path();

        if !path.is_dir() {
            continue;
        }

        let fixture_path = path.join("fixture.pl");
        let goto_path = path.join("expected_goto.json");

        if !fixture_path.exists() || !goto_path.exists() {
            continue;
        }

        let name = path.file_name().ok_or("No directory name")?.to_string_lossy().to_string();
        let json = fs::read_to_string(&goto_path)?;
        let expected: GotoGoldExpected = serde_json::from_str(&json)
            .map_err(|e| format!("Parsing {}: {e}", goto_path.display()))?;

        fixtures.push(GotoGoldFixture { name, fixture_path, goto_assertions: expected.assertions });
    }

    fixtures.sort_by(|a, b| a.name.cmp(&b.name));
    Ok(fixtures)
}

// ---------------------------------------------------------------------------
// Editor Intelligence — Completion
// ---------------------------------------------------------------------------

/// Assertion kind for completion gold corpus entries
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "kind")]
pub enum CompletionAssertionKind {
    /// Completion list must not be empty
    CompletionNonEmpty,
    /// Item must be at position [0] in the list
    CompletionTop1 { expected_label: String },
    /// Item must be in positions [0..4]
    CompletionTop5 { expected_label: String },
    /// Item must appear anywhere in the list
    CompletionPresent { expected_label: String },
    /// Label must NOT appear in the list
    CompletionNoiseAbsent { forbidden_label: String },
}

/// A single completion assertion at a given (line, character) position
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompletionAssertion {
    #[serde(flatten)]
    pub kind: CompletionAssertionKind,
    pub line: u32,
    pub character: u32,
    #[serde(default)]
    pub rationale: String,
}

/// On-disk representation of `expected_completion.json`
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompletionGoldExpected {
    pub version: u32,
    pub fixture: String,
    pub assertions: Vec<CompletionAssertion>,
}

/// A completion gold fixture (fixture.pl + expected_completion.json)
#[derive(Debug, Clone)]
pub struct CompletionGoldFixture {
    pub name: String,
    pub fixture_path: PathBuf,
    pub completion_assertions: Vec<CompletionAssertion>,
}

/// Load all completion gold fixtures from a directory.
///
/// Silently skips directories that lack `expected_completion.json`.
pub fn load_completion_gold_fixtures<P: AsRef<Path>>(
    root: P,
) -> Result<Vec<CompletionGoldFixture>, Box<dyn std::error::Error>> {
    let root = root.as_ref();
    let mut fixtures = Vec::new();

    if !root.exists() {
        return Err(format!("Gold fixtures directory not found: {}", root.display()).into());
    }

    for entry in fs::read_dir(root)? {
        let entry = entry?;
        let path = entry.path();

        if !path.is_dir() {
            continue;
        }

        let fixture_path = path.join("fixture.pl");
        let completion_path = path.join("expected_completion.json");

        if !fixture_path.exists() || !completion_path.exists() {
            continue;
        }

        let name = path.file_name().ok_or("No directory name")?.to_string_lossy().to_string();
        let json = fs::read_to_string(&completion_path)?;
        let expected: CompletionGoldExpected = serde_json::from_str(&json)
            .map_err(|e| format!("Parsing {}: {e}", completion_path.display()))?;

        fixtures.push(CompletionGoldFixture {
            name,
            fixture_path,
            completion_assertions: expected.assertions,
        });
    }

    fixtures.sort_by(|a, b| a.name.cmp(&b.name));
    Ok(fixtures)
}

// ---------------------------------------------------------------------------
// Editor Intelligence — Document Symbols
// ---------------------------------------------------------------------------

/// Assertion kind for document-symbol gold corpus entries
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "kind")]
pub enum DocumentSymbolAssertionKind {
    /// Symbols list must not be empty
    SymbolNonEmpty,
    /// Symbol with exact `name` must be present in returned symbols
    SymbolPresent { name: String },
    /// Symbol with exact `name` must not be present
    SymbolAbsent { name: String },
    /// Exactly `count` symbols should be returned
    SymbolCount { count: usize },
}

/// A single document-symbol assertion
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DocumentSymbolAssertion {
    #[serde(flatten)]
    pub kind: DocumentSymbolAssertionKind,
    #[serde(default)]
    pub rationale: String,
}

/// On-disk representation of `expected_symbols.json`
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DocumentSymbolGoldExpected {
    pub version: u32,
    pub fixture: String,
    pub assertions: Vec<DocumentSymbolAssertion>,
}

/// A document-symbol gold fixture (fixture.pl + expected_symbols.json)
#[derive(Debug, Clone)]
pub struct DocumentSymbolGoldFixture {
    pub name: String,
    pub fixture_path: PathBuf,
    pub symbol_assertions: Vec<DocumentSymbolAssertion>,
}

/// Load all document-symbol gold fixtures from a directory.
///
/// Silently skips directories that lack `expected_symbols.json`.
pub fn load_document_symbol_gold_fixtures<P: AsRef<Path>>(
    root: P,
) -> Result<Vec<DocumentSymbolGoldFixture>, Box<dyn std::error::Error>> {
    let root = root.as_ref();
    let mut fixtures = Vec::new();

    if !root.exists() {
        return Err(format!("Gold fixtures directory not found: {}", root.display()).into());
    }

    for entry in fs::read_dir(root)? {
        let entry = entry?;
        let path = entry.path();

        if !path.is_dir() {
            continue;
        }

        let fixture_path = path.join("fixture.pl");
        let symbols_path = path.join("expected_symbols.json");

        if !fixture_path.exists() || !symbols_path.exists() {
            continue;
        }

        let name = path.file_name().ok_or("No directory name")?.to_string_lossy().to_string();
        let json = fs::read_to_string(&symbols_path)?;
        let expected: DocumentSymbolGoldExpected = serde_json::from_str(&json)
            .map_err(|e| format!("Parsing {}: {e}", symbols_path.display()))?;

        fixtures.push(DocumentSymbolGoldFixture {
            name,
            fixture_path,
            symbol_assertions: expected.assertions,
        });
    }

    fixtures.sort_by(|a, b| a.name.cmp(&b.name));
    Ok(fixtures)
}

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

    #[test]
    fn test_gold_assertion_deserialization() -> Result<(), serde_json::Error> {
        let json = r#"{"assertion": "no_diagnostics"}"#;
        let assertion: GoldAssertion = serde_json::from_str(json)?;
        assert!(matches!(assertion, GoldAssertion::NoDiagnostics));
        Ok(())
    }

    #[test]
    fn test_gold_assertion_diagnostic_present() -> Result<(), serde_json::Error> {
        let json = r#"{"assertion": "diagnostic_present", "code": "PL100", "byte_offset": 24}"#;
        let assertion: GoldAssertion = serde_json::from_str(json)?;
        assert!(
            matches!(
                &assertion,
                GoldAssertion::DiagnosticPresent {
                    code,
                    byte_offset: Some(24),
                    ..
                } if code == "PL100"
            ),
            "Expected DiagnosticPresent variant with code PL100 and byte_offset 24"
        );
        Ok(())
    }

    #[test]
    fn test_gold_expected_deserialization() -> Result<(), serde_json::Error> {
        let json = r#"{"diagnostics": [{"assertion": "no_diagnostics"}]}"#;
        let expected: GoldExpected = serde_json::from_str(json)?;
        assert_eq!(expected.diagnostics.len(), 1);
        Ok(())
    }

    #[test]
    fn test_malformed_json_returns_error() {
        // Malformed expected.json must produce a serde error, not panic
        let bad_json = r#"{"diagnostics": [{"assertion": "unknown_variant"}]}"#;
        let result: Result<GoldExpected, _> = serde_json::from_str(bad_json);
        assert!(result.is_err(), "unknown assertion variant should fail to deserialize");
    }

    #[test]
    fn test_empty_diagnostics_array_deserializes() -> Result<(), serde_json::Error> {
        // empty array is valid JSON but the harness will catch it as vacuous
        let json = r#"{"diagnostics": []}"#;
        let expected: GoldExpected = serde_json::from_str(json)?;
        assert_eq!(expected.diagnostics.len(), 0);
        Ok(())
    }

    #[test]
    fn test_no_diagnostic_deserialization() -> Result<(), serde_json::Error> {
        let json = r#"{"assertion": "no_diagnostic", "code": "PL100"}"#;
        let assertion: GoldAssertion = serde_json::from_str(json)?;
        assert!(
            matches!(&assertion, GoldAssertion::NoDiagnostic { code } if code == "PL100"),
            "Expected NoDiagnostic variant with code PL100"
        );
        Ok(())
    }

    #[test]
    fn test_diagnostic_count_deserialization() -> Result<(), serde_json::Error> {
        let json = r#"{"assertion": "diagnostic_count", "code": "PL001", "count": 3}"#;
        let assertion: GoldAssertion = serde_json::from_str(json)?;
        assert!(
            matches!(&assertion, GoldAssertion::DiagnosticCount { code, count: 3 } if code == "PL001"),
            "Expected DiagnosticCount variant with code PL001 and count 3"
        );
        Ok(())
    }
}