perl-ast 0.17.0

AST node definitions for Perl parsing, providing typed representations of Perl syntax constructs
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
// Acceptance tests for the NodeKindCategory + NodeKindFlags classification API.
//
// These tests were written BEFORE the implementation (TDD red phase).
// They encode the spec table from issue #911 plan-review comment id 4583604229.
//
// safe_for_breakpoint rule (plan-reviewer corrected):
//   false = recovery_artifact || "pure variant-level classification says no"
//   The corrected table has 43 true / 26 false.
//
// All assertions are deterministic (no randomness, no parser invocation).

use perl_ast::classification::NodeKindCategory;
use perl_ast::{Node, NodeKind, SourceLocation};

#[path = "helpers.rs"]
mod helpers;

fn loc() -> SourceLocation {
    SourceLocation::new(0, 1)
}

fn leaf() -> Node {
    Node::new(NodeKind::Identifier { name: "x".to_string() }, loc())
}

fn block_node() -> Node {
    Node::new(NodeKind::Block { statements: vec![] }, loc())
}

// ────────────────────────────────────────────────────────
// all_variants: delegates to helpers::all_nodekind_instances()
// ────────────────────────────────────────────────────────
// The canonical fixture lives in tests/helpers.rs. When a new NodeKind
// variant is added, update helpers.rs (one place for all integration tests).
fn all_variants() -> Vec<NodeKind> {
    helpers::all_nodekind_instances().into_iter().map(|n| n.kind).collect()
}

// ────────────────────────────────────────────────────────
// Test (a): every variant returns a category and flags without panicking
// ────────────────────────────────────────────────────────

#[test]
fn all_variants_have_category_and_flags() {
    for kind in all_variants() {
        let _cat = kind.category();
        let flags = kind.flags();
        // flags.validate() is checked separately
        let _ = flags;
    }
}

// ────────────────────────────────────────────────────────
// Test (b): recovery_artifact == true implies safe_for_breakpoint == false
// ────────────────────────────────────────────────────────

#[test]
fn recovery_implies_not_safe_for_breakpoint() {
    for kind in all_variants() {
        let flags = kind.flags();
        if flags.recovery_artifact {
            assert!(
                !flags.safe_for_breakpoint,
                "variant {:?} has recovery_artifact=true but safe_for_breakpoint=true",
                kind.kind_name(),
            );
        }
    }
}

// ────────────────────────────────────────────────────────
// Test (c): exact safe_for_breakpoint true/false sets from the spec table
// ────────────────────────────────────────────────────────

/// The exact set of variant names that must be safe_for_breakpoint=TRUE
/// per the plan-reviewer corrected table (41 variants after ratification).
/// Use and No removed (compile-time pragma/unimport; not runtime-breakable).
const SAFE_FOR_BREAKPOINT_TRUE: &[&str] = &[
    "ExpressionStatement",
    "VariableDeclaration",
    "VariableListDeclaration",
    "Assignment",
    "Binary",
    "Ternary",
    "Unary",
    "Diamond",
    "Readline",
    "Glob",
    "Heredoc",
    "Block",
    "Eval",
    "Do",
    "Defer",
    "Try",
    "If",
    "LabeledStatement",
    "While",
    "Tie",
    "Untie",
    "For",
    "Foreach",
    "Given",
    "When",
    "Default",
    "StatementModifier",
    "Subroutine",
    "Method",
    "Return",
    "LoopControl",
    "Goto",
    "MethodCall",
    "FunctionCall",
    "IndirectCall",
    "Match",
    "Substitution",
    "Transliteration",
    "Package",
    "PhaseBlock",
    "Class",
];

/// The exact set of variant names that must be safe_for_breakpoint=FALSE
/// per the plan-reviewer corrected table (28 variants after ratification).
/// Use and No added (compile-time pragma/unimport; not runtime-breakable).
const SAFE_FOR_BREAKPOINT_FALSE: &[&str] = &[
    "Program",
    "Variable",
    "VariableWithAttributes",
    "Ellipsis",
    "Undef",
    "Number",
    "String",
    "ArrayLiteral",
    "HashLiteral",
    "Typeglob",
    "Regex",
    "Prototype",
    "Signature",
    "MandatoryParameter",
    "OptionalParameter",
    "SlurpyParameter",
    "NamedParameter",
    "DataSection",
    "Format",
    "Identifier",
    "Use",
    "No",
    "NestedVariableList",
    // Recovery nodes (6)
    "Error",
    "MissingExpression",
    "MissingStatement",
    "MissingIdentifier",
    "MissingBlock",
    "UnknownRest",
];

#[test]
fn safe_for_breakpoint_exact_true_set() {
    for kind in all_variants() {
        let name = kind.kind_name();
        let flags = kind.flags();
        if SAFE_FOR_BREAKPOINT_TRUE.contains(&name) {
            assert!(
                flags.safe_for_breakpoint,
                "expected {name} to be safe_for_breakpoint=true, got false",
            );
        }
    }
}

#[test]
fn safe_for_breakpoint_exact_false_set() {
    for kind in all_variants() {
        let name = kind.kind_name();
        let flags = kind.flags();
        if SAFE_FOR_BREAKPOINT_FALSE.contains(&name) {
            assert!(
                !flags.safe_for_breakpoint,
                "expected {name} to be safe_for_breakpoint=false, got true",
            );
        }
    }
}

#[test]
fn safe_for_breakpoint_covers_all_70_variants() {
    // Every variant must appear in exactly one of the two lists.
    // After ratification: 41 in TRUE, 29 in FALSE = 70 total variants (per acceptance.md)
    for kind in all_variants() {
        let name = kind.kind_name();
        let in_true = SAFE_FOR_BREAKPOINT_TRUE.contains(&name);
        let in_false = SAFE_FOR_BREAKPOINT_FALSE.contains(&name);
        assert!(
            in_true ^ in_false,
            "variant {name} must appear in exactly one of the safe_for_breakpoint lists"
        );
    }
}

// ────────────────────────────────────────────────────────
// Test (d): spot-check category assignments for representative variants
// ────────────────────────────────────────────────────────

#[test]
fn category_spot_checks() {
    // Program → Program
    assert_eq!(NodeKind::Program { statements: vec![] }.category(), NodeKindCategory::Program);

    // ExpressionStatement → Statement
    assert_eq!(
        NodeKind::ExpressionStatement { expression: Box::new(leaf()) }.category(),
        NodeKindCategory::Statement,
    );

    // VariableDeclaration → Declaration
    assert_eq!(
        NodeKind::VariableDeclaration {
            declarator: "my".to_string(),
            variable: Box::new(leaf()),
            attributes: vec![],
            initializer: None,
        }
        .category(),
        NodeKindCategory::Declaration
    );

    // Variable → Expression
    assert_eq!(
        NodeKind::Variable { sigil: "$".to_string(), name: "x".to_string() }.category(),
        NodeKindCategory::Expression
    );

    // Number → Literal
    assert_eq!(NodeKind::Number { value: "1".to_string() }.category(), NodeKindCategory::Literal);

    // Ellipsis → Operator
    assert_eq!(NodeKind::Ellipsis.category(), NodeKindCategory::Operator);

    // Block → Scope
    assert_eq!(NodeKind::Block { statements: vec![] }.category(), NodeKindCategory::Scope);

    // Error → Recovery
    assert_eq!(
        NodeKind::Error { message: "e".to_string(), expected: vec![], found: None, partial: None }
            .category(),
        NodeKindCategory::Recovery
    );

    // DataSection → Declaration (plan-reviewer correction: NOT Statement)
    assert_eq!(
        NodeKind::DataSection { marker: "__DATA__".to_string(), body: None }.category(),
        NodeKindCategory::Declaration
    );

    // PhaseBlock → Declaration (plan-reviewer correction)
    assert_eq!(
        NodeKind::PhaseBlock {
            phase: "BEGIN".to_string(),
            phase_span: None,
            block: Box::new(block_node()),
        }
        .category(),
        NodeKindCategory::Declaration
    );

    // Class → Declaration
    assert_eq!(
        NodeKind::Class {
            name: "Foo".to_string(),
            name_span: None,
            parents: vec![],
            body: Box::new(block_node())
        }
        .category(),
        NodeKindCategory::Declaration
    );

    // Subroutine → Declaration
    assert_eq!(
        NodeKind::Subroutine {
            name: Some("foo".to_string()),
            name_span: None,
            declarator: None,
            prototype: None,
            signature: None,
            attributes: vec![],
            body: Box::new(block_node()),
        }
        .category(),
        NodeKindCategory::Declaration
    );
}

// ────────────────────────────────────────────────────────
// Test: convenience methods on NodeKind
// ────────────────────────────────────────────────────────

#[test]
fn convenience_accessors_match_flags() {
    for kind in all_variants() {
        let flags = kind.flags();
        assert_eq!(
            kind.is_executable(),
            flags.executable,
            "is_executable mismatch for {}",
            kind.kind_name()
        );
        assert_eq!(
            kind.introduces_scope(),
            flags.introduces_scope,
            "introduces_scope mismatch for {}",
            kind.kind_name()
        );
        assert_eq!(
            kind.declares_symbol(),
            flags.declares_symbol,
            "declares_symbol mismatch for {}",
            kind.kind_name()
        );
        assert_eq!(
            kind.references_symbol(),
            flags.references_symbol,
            "references_symbol mismatch for {}",
            kind.kind_name()
        );
        assert_eq!(
            kind.safe_for_breakpoint(),
            flags.safe_for_breakpoint,
            "safe_for_breakpoint mismatch for {}",
            kind.kind_name()
        );
        assert_eq!(
            kind.is_recovery(),
            flags.recovery_artifact,
            "is_recovery mismatch for {}",
            kind.kind_name()
        );
    }
}

// ────────────────────────────────────────────────────────
// Test: flags validate() — recovery_artifact && safe_for_breakpoint is forbidden
// ────────────────────────────────────────────────────────

#[test]
fn flags_validate_all_variants() {
    for kind in all_variants() {
        let flags = kind.flags();
        assert!(
            flags.validate().is_ok(),
            "flags.validate() failed for variant {}: {:?}",
            kind.kind_name(),
            flags
        );
    }
}

// ────────────────────────────────────────────────────────
// Test: recovery category variants have recovery_artifact=true
// ────────────────────────────────────────────────────────

#[test]
fn recovery_category_implies_recovery_artifact() {
    for kind in all_variants() {
        let flags = kind.flags();
        let cat = kind.category();
        if cat == NodeKindCategory::Recovery {
            assert!(
                flags.recovery_artifact,
                "variant {} has Recovery category but recovery_artifact=false",
                kind.kind_name()
            );
        }
    }
}

// ────────────────────────────────────────────────────────
// Test: specific flags spot-checks against spec table
// ────────────────────────────────────────────────────────

#[test]
fn flags_spot_checks() {
    // Program: introduces_scope=true, contains_children=true
    {
        let kind = NodeKind::Program { statements: vec![] };
        let f = kind.flags();
        assert!(!f.executable, "Program.executable should be false");
        assert!(f.introduces_scope, "Program.introduces_scope should be true");
        assert!(f.contains_children, "Program.contains_children should be true");
        assert!(!f.safe_for_breakpoint, "Program.safe_for_breakpoint should be false");
    }

    // Subroutine: introduces_scope=true, declares_symbol=true
    {
        let kind = NodeKind::Subroutine {
            name: Some("foo".to_string()),
            name_span: None,
            declarator: None,
            prototype: None,
            signature: None,
            attributes: vec![],
            body: Box::new(block_node()),
        };
        let f = kind.flags();
        assert!(!f.executable, "Subroutine.executable should be false");
        assert!(f.introduces_scope, "Subroutine.introduces_scope should be true");
        assert!(f.declares_symbol, "Subroutine.declares_symbol should be true");
        assert!(f.safe_for_breakpoint, "Subroutine.safe_for_breakpoint should be true");
    }

    // Error: recovery_artifact=true, safe_for_breakpoint=false
    {
        let kind = NodeKind::Error {
            message: "e".to_string(),
            expected: vec![],
            found: None,
            partial: None,
        };
        let f = kind.flags();
        assert!(f.recovery_artifact, "Error.recovery_artifact should be true");
        assert!(!f.safe_for_breakpoint, "Error.safe_for_breakpoint should be false");
    }

    // Package: executable=true, introduces_scope=true, declares_symbol=true
    {
        let kind = NodeKind::Package { name: "Foo".to_string(), name_span: loc(), block: None };
        let f = kind.flags();
        assert!(f.executable, "Package.executable should be true");
        assert!(f.introduces_scope, "Package.introduces_scope should be true");
        assert!(f.declares_symbol, "Package.declares_symbol should be true");
        assert!(f.safe_for_breakpoint, "Package.safe_for_breakpoint should be true");
    }

    // Identifier: references_symbol=true, safe_for_breakpoint=false
    {
        let kind = NodeKind::Identifier { name: "foo".to_string() };
        let f = kind.flags();
        assert!(!f.executable, "Identifier.executable should be false");
        assert!(f.references_symbol, "Identifier.references_symbol should be true");
        assert!(!f.safe_for_breakpoint, "Identifier.safe_for_breakpoint should be false");
    }

    // Heredoc: executable=true (the <<EOF line is stoppable), safe_for_breakpoint=true
    {
        let kind = NodeKind::Heredoc {
            delimiter: "EOF".to_string(),
            content: "body".to_string(),
            interpolated: false,
            indented: false,
            command: false,
            body_span: None,
        };
        let f = kind.flags();
        assert!(f.executable, "Heredoc.executable should be true");
        assert!(f.safe_for_breakpoint, "Heredoc.safe_for_breakpoint should be true");
    }
}

// ────────────────────────────────────────────────────────
// Test: the ALL_KIND_NAMES count matches the variants we constructed
// ────────────────────────────────────────────────────────

#[test]
fn all_kind_names_count_matches_variants() {
    let constructed = all_variants().len();
    let named = NodeKind::ALL_KIND_NAMES.len();
    assert_eq!(
        constructed, named,
        "all_variants() produced {constructed} variants but ALL_KIND_NAMES has {named} entries"
    );
}

// ────────────────────────────────────────────────────────
// Test: Instance-dependent flags documented
//
// Per acceptance.md §Instance-dependent semantics (Hazards):
// Eval, Package, and PhaseBlock have conservative variant-level flags.
// The DAP/LSP consumer must verify AST structure or phase name to determine
// actual behavior. These tests document the variant-level flags and the
// consumer responsibility boundaries.
// ────────────────────────────────────────────────────────

#[test]
fn instance_dependent_flags_eval() {
    // Eval::safe_for_breakpoint = true (prefilter, variant-level).
    // BUT: consumer must check if child is NodeKind::Block to know scope behavior.
    // - eval BLOCK { ... } has scope (block present)
    // - eval STRING or eval EXPR does not have scope (block is not Block kind)

    let eval_with_block = NodeKind::Eval { block: Box::new(block_node()) };
    let f = eval_with_block.flags();

    assert!(
        f.safe_for_breakpoint,
        "Eval variant flag safe_for_breakpoint should be true (prefilter)"
    );
    assert!(
        f.introduces_scope,
        "Eval variant flag introduces_scope should be true (conservative prefilter)"
    );

    // Comment: Consumer (Phase 8 DAP layer) must check if block field contains
    // a Block node to know if scope is actually introduced at runtime.
}

#[test]
fn instance_dependent_flags_package() {
    // Package::safe_for_breakpoint = true (prefilter, variant-level).
    // Package::introduces_scope = true (prefilter, variant-level).
    // BUT: consumer must check block field to distinguish behavior:
    // - package Foo { ... } form: block is Some(Block node) → scope is real
    // - package Foo; form: block is None → no scope created

    let pkg_with_block = NodeKind::Package {
        name: "Foo".to_string(),
        name_span: loc(),
        block: Some(Box::new(block_node())),
    };
    let f = pkg_with_block.flags();

    assert!(
        f.safe_for_breakpoint,
        "Package variant flag safe_for_breakpoint should be true (prefilter)"
    );
    assert!(
        f.introduces_scope,
        "Package variant flag introduces_scope should be true (conservative prefilter)"
    );

    let pkg_without_block =
        NodeKind::Package { name: "Bar".to_string(), name_span: loc(), block: None };
    let f2 = pkg_without_block.flags();

    assert!(
        f2.safe_for_breakpoint,
        "Package variant flag safe_for_breakpoint should be true even without block (prefilter)"
    );
    assert!(
        f2.introduces_scope,
        "Package variant flag introduces_scope should be true even without block (prefilter)"
    );

    // Comment: Consumer must check block.is_some() to distinguish statement form
    // (package Foo;) from block form (package Foo { ... }).
}

#[test]
fn instance_dependent_flags_phaseblock() {
    // PhaseBlock::safe_for_breakpoint = true (prefilter, variant-level).
    // PhaseBlock::introduces_scope = true (prefilter, variant-level).
    // BUT: consumer must check phase field to determine runtime stoppability:
    // - BEGIN, CHECK, UNITCHECK: compile-time phase (not stoppable in runtime session)
    // - END: run-time cleanup (stoppable at exit)
    // - INIT: initialization (may be stoppable depending on timing)

    let begin_block = NodeKind::PhaseBlock {
        phase: "BEGIN".to_string(),
        phase_span: None,
        block: Box::new(block_node()),
    };
    let f = begin_block.flags();

    assert!(
        f.safe_for_breakpoint,
        "PhaseBlock variant flag safe_for_breakpoint should be true (has block, prefilter)"
    );
    assert!(
        f.introduces_scope,
        "PhaseBlock variant flag introduces_scope should be true (has block, prefilter)"
    );

    let end_block = NodeKind::PhaseBlock {
        phase: "END".to_string(),
        phase_span: None,
        block: Box::new(block_node()),
    };
    let f2 = end_block.flags();

    assert!(
        f2.safe_for_breakpoint,
        "PhaseBlock variant flag safe_for_breakpoint should be true (all phases have same variant flags)"
    );
    assert!(
        f2.introduces_scope,
        "PhaseBlock variant flag introduces_scope should be true (all phases have same variant flags)"
    );

    // Comment: Consumer (Phase 8 DAP layer) must check phase field to determine
    // if breakpoint is actually stoppable at runtime:
    // - BEGIN/CHECK/UNITCHECK: not stoppable in runtime session
    // - END: stoppable at shutdown
    // - INIT: maybe stoppable depending on attach timing
    // The variant flags are conservative (all true) and serve as a prefilter.
}

// ────────────────────────────────────────────────────────
// Test: Use and No safe_for_breakpoint=false coverage
//
// Direct test for Use/No variants to ensure llvm-cov measures coverage of
// the modified match arms in classification.rs (where Use/No changed from
// safe_for_breakpoint=true to false). The main test suite exercises these
// variants indirectly; this test directly asserts the flag value.
// ────────────────────────────────────────────────────────

#[test]
fn use_not_safe_for_breakpoint() {
    let use_kind =
        NodeKind::Use { module: "strict".to_string(), args: vec![], has_filter_risk: false };
    assert!(
        !use_kind.flags().safe_for_breakpoint,
        "Use must have safe_for_breakpoint=false (compile-time pragma)"
    );
}

#[test]
fn no_not_safe_for_breakpoint() {
    let no_kind =
        NodeKind::No { module: "warnings".to_string(), args: vec![], has_filter_risk: false };
    assert!(
        !no_kind.flags().safe_for_breakpoint,
        "No must have safe_for_breakpoint=false (compile-time unimport)"
    );
}