perl-pragma 0.17.0

Perl pragma extraction and analysis primitives
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
//! BDD-style behavior specification tests for perl-pragma.
//!
//! These scenarios describe pragma behavior from a consumer point of view:
//! "Given <context>, when <construct appears>, then <effective state>."

use perl_ast::SourceLocation;
use perl_ast::ast::{Node, NodeKind};
use perl_pragma::{CompileTimePragmaEnvironment, PragmaQueryCursor, PragmaState, PragmaTracker};

fn loc(start: usize, end: usize) -> SourceLocation {
    SourceLocation { start, end }
}

fn use_node(module: &str, args: &[&str], start: usize, end: usize) -> Node {
    Node {
        kind: NodeKind::Use {
            module: module.to_string(),
            args: args.iter().map(|s| s.to_string()).collect(),
            has_filter_risk: false,
        },
        location: loc(start, end),
    }
}

fn no_node(module: &str, args: &[&str], start: usize, end: usize) -> Node {
    Node {
        kind: NodeKind::No {
            module: module.to_string(),
            args: args.iter().map(|s| s.to_string()).collect(),
            has_filter_risk: false,
        },
        location: loc(start, end),
    }
}

fn block(stmts: Vec<Node>, start: usize, end: usize) -> Node {
    Node { kind: NodeKind::Block { statements: stmts }, location: loc(start, end) }
}

fn package_block(name: &str, body: Node, start: usize, end: usize) -> Node {
    Node {
        kind: NodeKind::Package {
            name: name.to_string(),
            name_span: loc(start, end),
            block: Some(Box::new(body)),
        },
        location: loc(start, end),
    }
}

fn phase_block(phase: &str, body: Node, start: usize, end: usize) -> Node {
    Node {
        kind: NodeKind::PhaseBlock {
            phase: phase.to_string(),
            phase_span: Some(loc(start, start + phase.len())),
            block: Box::new(body),
        },
        location: loc(start, end),
    }
}

fn program(stmts: Vec<Node>) -> Node {
    let end = stmts.last().map_or(0, |n| n.location.end);
    Node { kind: NodeKind::Program { statements: stmts }, location: loc(0, end) }
}

#[test]
fn given_fresh_file_when_no_pragmas_then_default_state_applies() {
    let ast = program(vec![]);
    let map = PragmaTracker::build(&ast);

    let state = PragmaTracker::state_for_offset(&map, 0);
    assert_eq!(state, PragmaState::default());
}

#[test]
fn given_use_strict_when_querying_after_statement_then_all_strict_modes_are_enabled() {
    let ast = program(vec![use_node("strict", &[], 0, 12)]);
    let map = PragmaTracker::build(&ast);

    let state = PragmaTracker::state_for_offset(&map, 8);
    assert!(state.strict_vars);
    assert!(state.strict_subs);
    assert!(state.strict_refs);
}

#[test]
fn given_use_strict_when_no_strict_refs_in_inner_block_then_refs_is_restored_outside_block() {
    let ast = program(vec![
        use_node("strict", &[], 0, 12),
        block(vec![no_node("strict", &["refs"], 15, 31)], 13, 33),
        use_node("warnings", &[], 34, 49),
    ]);
    let map = PragmaTracker::build(&ast);

    let inside = PragmaTracker::state_for_offset(&map, 25);
    assert!(!inside.strict_refs);

    let outside = PragmaTracker::state_for_offset(&map, 40);
    assert!(outside.strict_vars);
    assert!(outside.strict_subs);
    assert!(outside.strict_refs);
    assert!(outside.warnings);
}

#[test]
fn given_use_warnings_when_specific_category_is_disabled_then_other_categories_stay_active() {
    let ast = program(vec![
        use_node("warnings", &[], 0, 15),
        no_node("warnings", &["uninitialized"], 16, 41),
    ]);
    let map = PragmaTracker::build(&ast);

    let state = PragmaTracker::state_for_offset(&map, 30);
    assert!(state.warnings);
    assert!(!state.is_warning_active("uninitialized"));
    assert!(state.is_warning_active("deprecated"));
}

#[test]
fn given_use_v5_40_when_querying_state_then_effective_strict_warnings_and_feature_bundle_apply() {
    let ast = program(vec![use_node("v5.40", &[], 0, 12)]);
    let map = PragmaTracker::build(&ast);

    let state = PragmaTracker::state_for_offset(&map, 8);
    assert!(state.strict_vars);
    assert!(state.strict_subs);
    assert!(state.strict_refs);
    assert!(state.warnings);
    assert!(state.has_feature("builtin"));
}

#[test]
fn given_use_builtin_qw_when_querying_scope_then_each_imported_name_is_available() {
    let ast = program(vec![use_node("builtin", &["qw(true false ceil)"], 0, 30)]);
    let map = PragmaTracker::build(&ast);

    let state = PragmaTracker::state_for_offset(&map, 12);
    assert!(state.has_builtin_import("true"));
    assert!(state.has_builtin_import("false"));
    assert!(state.has_builtin_import("ceil"));
}

#[test]
fn given_no_builtin_when_querying_scope_then_selected_imports_are_removed() {
    let ast = program(vec![
        use_node("builtin", &["qw(true false ceil)"], 0, 30),
        no_node("builtin", &["'false'"], 31, 49),
    ]);
    let map = PragmaTracker::build(&ast);

    let state = PragmaTracker::state_for_offset(&map, 40);
    assert!(state.has_builtin_import("true"));
    assert!(!state.has_builtin_import("false"));
    assert!(state.has_builtin_import("ceil"));
}

#[test]
fn given_use_feature_qw_when_querying_state_then_requested_features_and_unicode_strings_are_enabled()
 {
    let ast = program(vec![use_node("feature", &["'qw(signatures unicode_strings)'"], 0, 41)]);
    let map = PragmaTracker::build(&ast);

    let state = PragmaTracker::state_for_offset(&map, 20);
    assert!(state.strict_vars);
    assert!(state.strict_subs);
    assert!(state.strict_refs);
    assert!(state.unicode_strings);
}

#[test]
fn given_use_if_feature_bundle_when_querying_state_then_bundle_features_are_recorded() {
    let ast = program(vec![use_node("if", &["$]", ">=", "5.036", "feature", "':5.36'"], 0, 44)]);
    let map = PragmaTracker::build(&ast);

    let state = PragmaTracker::state_for_offset(&map, 20);
    assert!(state.has_feature("say"));
    assert!(state.has_feature("signatures"));
    assert!(state.has_feature("isa"));
}

#[test]
fn given_no_feature_all_then_use_feature_bundle_when_querying_state_then_bundle_is_reenabled() {
    let ast = program(vec![
        use_node("v5.40", &[], 0, 12),
        no_node("feature", &["':all'"], 13, 31),
        use_node("feature", &["':5.40'"], 32, 52),
    ]);
    let map = PragmaTracker::build(&ast);

    let state = PragmaTracker::state_for_offset(&map, 40);
    assert!(state.has_feature("builtin"));
    assert!(state.has_feature("say"));
}

#[test]
fn given_use_feature_signatures_when_querying_state_then_effective_strict_modes_are_enabled() {
    let ast = program(vec![use_node("feature", &["'signatures'"], 0, 24)]);
    let map = PragmaTracker::build(&ast);

    let state = PragmaTracker::state_for_offset(&map, 12);
    assert!(state.strict_vars);
    assert!(state.strict_subs);
    assert!(state.strict_refs);
}

#[test]
fn given_use_v5_38_when_querying_state_then_removed_features_are_absent_but_modern_features_are() {
    let ast = program(vec![use_node("v5.38", &[], 0, 10)]);
    let map = PragmaTracker::build(&ast);

    let state = PragmaTracker::state_for_offset(&map, 5);
    assert!(state.has_feature("module_true"));
    assert!(state.has_feature("signatures"));
    assert!(!state.has_feature("switch"));
    assert!(!state.has_feature("bareword_filehandles"));
}

#[test]
fn given_package_block_with_inner_no_strict_when_execution_continues_then_outer_state_is_restored()
{
    let ast = program(vec![
        use_node("strict", &[], 0, 12),
        package_block("Foo", block(vec![no_node("strict", &["subs"], 20, 36)], 18, 40), 13, 42),
        use_node("warnings", &[], 43, 58),
    ]);
    let map = PragmaTracker::build(&ast);

    let inside_package = PragmaTracker::state_for_offset(&map, 30);
    assert!(!inside_package.strict_subs);

    let after_package = PragmaTracker::state_for_offset(&map, 50);
    assert!(after_package.strict_subs);
    assert!(after_package.warnings);
}

#[test]
fn given_begin_block_with_use_strict_when_querying_inside_block_then_strict_is_active() {
    let ast = program(vec![phase_block(
        "BEGIN",
        block(vec![use_node("strict", &[], 8, 20)], 6, 22),
        0,
        22,
    )]);
    let map = PragmaTracker::build(&ast);

    let inside_begin = PragmaTracker::state_for_offset(&map, 12);
    assert!(inside_begin.strict_vars);
    assert!(inside_begin.strict_subs);
    assert!(inside_begin.strict_refs);
}

#[test]
fn given_begin_block_with_use_strict_when_querying_after_block_then_strict_is_not_active() {
    let ast = program(vec![phase_block(
        "BEGIN",
        block(vec![use_node("strict", &[], 8, 20)], 6, 22),
        0,
        22,
    )]);
    let map = PragmaTracker::build(&ast);

    let after_begin = PragmaTracker::state_for_offset(&map, 24);
    assert!(!after_begin.strict_vars);
    assert!(!after_begin.strict_subs);
    assert!(!after_begin.strict_refs);
}

#[test]
fn given_begin_block_with_use_warnings_when_querying_after_block_then_warnings_is_not_active() {
    let ast = program(vec![phase_block(
        "BEGIN",
        block(vec![use_node("warnings", &[], 8, 22)], 6, 24),
        0,
        24,
    )]);
    let map = PragmaTracker::build(&ast);

    let after_begin = PragmaTracker::state_for_offset(&map, 26);
    assert!(!after_begin.warnings);
}

#[test]
fn given_end_block_with_use_warnings_when_querying_after_block_then_warnings_is_not_active() {
    let ast = program(vec![phase_block(
        "END",
        block(vec![use_node("warnings", &[], 6, 20)], 4, 22),
        0,
        22,
    )]);
    let map = PragmaTracker::build(&ast);

    let after_end = PragmaTracker::state_for_offset(&map, 24);
    assert!(!after_end.warnings);
}

#[test]
fn given_init_block_with_use_strict_when_querying_after_block_then_strict_is_not_active() {
    let ast = program(vec![phase_block(
        "INIT",
        block(vec![use_node("strict", &[], 7, 19)], 5, 21),
        0,
        21,
    )]);
    let map = PragmaTracker::build(&ast);

    let after_init = PragmaTracker::state_for_offset(&map, 23);
    assert!(!after_init.strict_vars);
    assert!(!after_init.strict_subs);
    assert!(!after_init.strict_refs);
}

#[test]
fn given_check_block_with_use_strict_when_querying_after_block_then_strict_is_not_active() {
    let ast = program(vec![phase_block(
        "CHECK",
        block(vec![use_node("strict", &[], 8, 20)], 6, 22),
        0,
        22,
    )]);
    let map = PragmaTracker::build(&ast);

    let after_check = PragmaTracker::state_for_offset(&map, 24);
    assert!(!after_check.strict_vars);
    assert!(!after_check.strict_subs);
    assert!(!after_check.strict_refs);
}

#[test]
fn given_unitcheck_block_with_use_strict_when_querying_after_block_then_strict_is_not_active() {
    let ast = program(vec![phase_block(
        "UNITCHECK",
        block(vec![use_node("strict", &[], 12, 24)], 10, 26),
        0,
        26,
    )]);
    let map = PragmaTracker::build(&ast);

    let after_unitcheck = PragmaTracker::state_for_offset(&map, 28);
    assert!(!after_unitcheck.strict_vars);
    assert!(!after_unitcheck.strict_subs);
    assert!(!after_unitcheck.strict_refs);
}

#[test]
fn given_pragmas_when_querying_final_state_then_last_effective_state_is_returned() {
    let ast = program(vec![use_node("strict", &[], 0, 12), use_node("warnings", &[], 13, 28)]);
    let map = PragmaTracker::build(&ast);

    let final_state = PragmaTracker::final_state(&map);
    assert!(final_state.strict_vars);
    assert!(final_state.strict_subs);
    assert!(final_state.strict_refs);
    assert!(final_state.warnings);
}

#[test]
fn given_monotonic_lookups_when_using_cursor_then_states_match_offset_queries() {
    let ast = program(vec![
        use_node("strict", &[], 0, 12),
        block(vec![no_node("strict", &["refs"], 20, 36)], 18, 40),
        use_node("warnings", &[], 42, 57),
    ]);
    let map = PragmaTracker::build(&ast);

    let mut cursor = PragmaQueryCursor::new();
    let s1 = cursor.state_for_offset(&map, 8);
    let s2 = cursor.state_for_offset(&map, 30);
    let s3 = cursor.state_for_offset(&map, 50);

    assert_eq!(s1, PragmaTracker::state_for_offset(&map, 8));
    assert_eq!(s2, PragmaTracker::state_for_offset(&map, 30));
    assert_eq!(s3, PragmaTracker::state_for_offset(&map, 50));
}

#[test]
fn given_explicit_pragma_map_when_using_cursor_then_states_match_map_queries() {
    let ast = program(vec![
        use_node("strict", &[], 0, 12),
        block(vec![no_node("strict", &["refs"], 20, 36)], 18, 40),
        use_node("warnings", &[], 42, 57),
    ]);
    let environment = CompileTimePragmaEnvironment::build(&ast);
    let map = environment.map();

    let mut cursor = map.cursor();
    let s1 = cursor.state_at(map, 8);
    let s2 = cursor.state_at(map, 30);
    let s3 = cursor.state_at(map, 50);

    assert_eq!(s1, map.state_at(8));
    assert_eq!(s2, map.state_at(30));
    assert_eq!(s3, map.state_at(50));

    let backward = cursor.snapshot_at(map, 8);
    assert_eq!(backward, environment.snapshot_at(8));
}

/// The cursor's fallback to binary search must produce the same result as the
/// static `state_for_offset` when called with a backward (decreasing) offset.
/// This is important when a caller (e.g., a diagnostic pass) queries nodes out
/// of source order.
#[test]
fn given_backward_lookup_when_cursor_past_end_then_fallback_matches_static_query() {
    let ast = program(vec![
        use_node("strict", &[], 0, 12),
        block(vec![no_node("strict", &["refs"], 20, 36)], 18, 40),
        use_node("warnings", &[], 42, 57),
    ]);
    let map = PragmaTracker::build(&ast);

    // Advance cursor to the end of the map.
    let mut cursor = PragmaQueryCursor::new();
    let _ = cursor.state_for_offset(&map, 50);

    // Now query backward to an earlier offset — must fall back to binary search.
    let backward = cursor.state_for_offset(&map, 8);
    assert_eq!(
        backward,
        PragmaTracker::state_for_offset(&map, 8),
        "backward seek must match static query result"
    );
}

/// Querying an empty pragma map via the cursor must return the default state,
/// matching the behavior of the static `state_for_offset`.
#[test]
fn given_empty_pragma_map_cursor_returns_default() {
    let map: Vec<(std::ops::Range<usize>, perl_pragma::PragmaState)> = vec![];
    let mut cursor = PragmaQueryCursor::new();
    let state = cursor.state_for_offset(&map, 999);
    assert_eq!(state, PragmaTracker::state_for_offset(&map, 999));
}

#[test]
fn given_empty_pragma_map_when_querying_final_state_then_default_state_is_returned() {
    // PragmaTracker::final_state must not panic on an empty map and must return
    // the same all-false default that state_for_offset returns for an empty map.
    let state = PragmaTracker::final_state(&[]);
    assert!(!state.strict_vars);
    assert!(!state.strict_refs);
    assert!(!state.strict_subs);
    assert!(!state.warnings);
}

#[test]
fn given_cursor_when_offset_is_before_first_pragma_then_default_state_is_returned() {
    // Query an offset before the first pragma range; cursor must return default
    // state just as state_for_offset does (exercises the index=0 with start>offset
    // branch that calls partition_point returning 0).
    let ast = program(vec![use_node("strict", &[], 10, 22)]);
    let map = PragmaTracker::build(&ast);

    let mut cursor = PragmaQueryCursor::new();
    let s = cursor.state_for_offset(&map, 5);

    assert_eq!(s, PragmaTracker::state_for_offset(&map, 5));
    assert!(!s.strict_vars, "no pragma has started at offset 5");
}

/// `final_state` must return the restored top-level state even when the last
/// entry in the sorted pragma map is a scope-exit restore point (an entry
/// pushed by `build_scoped_body` at `body.end..body.end`).
///
/// In a file where a subroutine is the last thing and it overrides strict,
/// `final_state` should return the state AFTER the sub (restored to outer),
/// not the in-sub state.
#[test]
fn given_sub_last_in_file_when_querying_final_state_then_outer_state_is_returned() {
    // use strict; sub foo { no strict; }
    // After `sub foo` closes, state is restored to strict=true.
    // The pragma map's last entry is the restore point at end-of-sub,
    // which has strict_vars = true.
    let ast = program(vec![
        use_node("strict", &[], 0, 12),
        block(vec![no_node("strict", &[], 14, 24)], 13, 25),
    ]);
    let map = PragmaTracker::build(&ast);

    let final_state = PragmaTracker::final_state(&map);
    assert!(
        final_state.strict_vars,
        "final_state must reflect outer (restored) strict=true after a scoped block"
    );
    assert!(
        final_state.strict_subs,
        "final_state must reflect outer (restored) strict=true after a scoped block"
    );
}

#[test]
fn given_scoped_block_when_building_explicit_map_then_restore_point_is_zero_length() {
    let ast = program(vec![
        use_node("strict", &[], 0, 12),
        block(vec![no_node("strict", &[], 14, 24)], 13, 25),
    ]);
    let environment = CompileTimePragmaEnvironment::build(&ast);
    let map = environment.map();

    assert!(
        map.entries().iter().any(|entry| entry.range.start == 25 && entry.range.end == 25),
        "lexical scope restore should be recorded as a zero-length transition"
    );

    let final_state = map.final_state();
    assert!(final_state.strict_vars);
    assert!(final_state.strict_subs);
    assert!(final_state.strict_refs);
}

/// Querying an empty `PragmaMap` via the explicit-map cursor API must return
/// the default snapshot, matching `CompileTimePragmaEnvironment::snapshot_at`.
/// This exercises the `entries.is_empty()` early-return branch in
/// `PragmaQueryCursor::entry_for_offset` through the public `snapshot_at` /
/// `state_at` methods (the existing empty-map test only covers the legacy
/// tuple `state_for_offset` API).
#[test]
fn given_empty_explicit_pragma_map_when_using_cursor_then_default_snapshot_is_returned() {
    let ast = program(vec![]);
    let environment = CompileTimePragmaEnvironment::build(&ast);
    let map = environment.map();
    assert!(map.entries().is_empty(), "program without pragmas must produce empty map");

    let mut cursor = map.cursor();
    let snapshot = cursor.snapshot_at(map, 999);
    let state = cursor.state_at(map, 999);

    assert_eq!(snapshot, environment.snapshot_at(999));
    assert_eq!(state, map.state_at(999));
    assert_eq!(state, PragmaState::default());
}

/// Querying an offset that precedes the first pragma range via the explicit-map
/// cursor API must return the default snapshot — same as the static
/// `PragmaMap::snapshot_at`. This exercises the `entries[index].range.start >
/// offset` branch in `entry_for_offset` where `partition_point` returns 0 and
/// the index is not decremented (mirroring the legacy `state_for_offset`
/// coverage for the same edge case).
#[test]
fn given_cursor_when_explicit_map_offset_is_before_first_pragma_then_default_snapshot_is_returned()
{
    let ast = program(vec![use_node("strict", &[], 10, 22)]);
    let environment = CompileTimePragmaEnvironment::build(&ast);
    let map = environment.map();

    let mut cursor = map.cursor();
    let snapshot = cursor.snapshot_at(map, 5);
    let state = cursor.state_at(map, 5);

    assert_eq!(snapshot, environment.snapshot_at(5));
    assert_eq!(state, map.state_at(5));
    assert!(!state.strict_vars, "no pragma has started at offset 5");
}

#[test]
fn given_use_warnings_when_qw_categories_are_disabled_then_each_category_is_tracked()
-> Result<(), Box<dyn std::error::Error>> {
    let ast = program(vec![
        use_node("warnings", &[], 0, 15),
        no_node("warnings", &["qw(uninitialized deprecated)"], 16, 55),
    ]);
    let map = PragmaTracker::build(&ast);

    let state = PragmaTracker::state_for_offset(&map, 30);
    assert!(state.warnings);
    assert!(!state.is_warning_active("uninitialized"));
    assert!(!state.is_warning_active("deprecated"));
    assert!(state.is_warning_active("void"));
    Ok(())
}

#[test]
fn given_disabled_warning_categories_when_specific_category_is_reenabled_then_other_disabled_categories_remain()
-> Result<(), Box<dyn std::error::Error>> {
    let ast = program(vec![
        use_node("warnings", &[], 0, 15),
        no_node("warnings", &["qw(uninitialized deprecated)"], 16, 55),
        use_node("warnings", &["'deprecated'"], 56, 84),
    ]);
    let map = PragmaTracker::build(&ast);

    let state = PragmaTracker::state_for_offset(&map, 70);
    assert!(state.warnings);
    assert!(!state.is_warning_active("uninitialized"));
    assert!(state.is_warning_active("deprecated"));
    Ok(())
}