vcl-normalizer 0.1.2

VCL 4.1 functional-equivalence comparator
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
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
//! Canonical VCL pretty-printer.
//!
//! Outputs deterministic, re-parseable VCL from a normalized AST.
//! Rules: 4-space indent, K&R braces, one statement per line,
//! strings as "..." or {...} for special chars, durations as <n>s, bytes as <n>B.
//!
//! Comments (see `ast::CommentMap`) are attached by `Span`, not carried on
//! the node itself, so every function below that renders a Decl/Stmt/
//! Field/AclEntry/Arg takes the whole map and looks its node up by span.
//! They're print-only trivia -- `canon.rs`/`compare.rs` never see them.

use crate::ast;

/// Prints a normalized Program as canonical VCL text.
pub fn print(p: &ast::Program) -> String {
    let mut lines = vec!["vcl 4.1;".to_string()];

    for (i, decl) in p.decls.iter().enumerate() {
        lines.extend(print_decl(decl, &p.comments, i == 0));
    }

    for (i, c) in p.trailing_comments.iter().enumerate() {
        if i == 0 {
            lines.push(String::new());
        }
        render_comment_block(&mut lines, 0, c);
    }

    lines.join("\n")
}

/// The blank-line-before-leading-comments convention for a given list kind.
enum BlankRule {
    /// Top-level decls: always got a blank line before them pre-comments
    /// (comment or not) -- unless this is the first item in the list.
    Always,
    /// Statements, fields, acl entries: zero blank lines by default, one
    /// gained only when an actual leading-comment block is present (and
    /// this isn't the first item).
    IfLeading,
    /// Args: never -- a one-arg-per-line call is already a rare fallback
    /// rendering, and a blank line between a comma and the next arg's
    /// comment reads as visual noise no normal call-argument style uses.
    Never,
}

/// Wraps a node's own rendered lines (`core`) with its leading/trailing/
/// after comments, keyed by `span`. `blank_rule` reproduces the
/// pre-comments spacing convention for the node's *list kind* (see
/// `BlankRule`).
fn wrap_comments(
    cm: &ast::CommentMap,
    span: ast::Span,
    indent_level: usize,
    is_first: bool,
    blank_rule: BlankRule,
    core: impl FnOnce() -> Vec<String>,
) -> Vec<String> {
    let nc = cm.get(span);
    let leading: &[ast::LeadingComment] = nc.map_or(&[], |c| &c.leading);
    let want_blank = match blank_rule {
        BlankRule::Always => true,
        BlankRule::IfLeading => !leading.is_empty(),
        BlankRule::Never => false,
    };
    let mut out = Vec::new();
    if !is_first && want_blank {
        out.push(String::new());
    }
    for c in leading {
        render_comment_block(&mut out, indent_level, c);
    }

    let mut core_lines = core();
    if let Some(trailing) = nc.and_then(|c| c.trailing.as_ref()) {
        // A same-line trailing comment always shares a line with the
        // node's own *header* token (e.g. `backend web {  // note` for a
        // multi-line decl) -- so it belongs on the first rendered line,
        // not the last. For single-line nodes (fields, acl entries, most
        // statements) first and last are the same line anyway.
        if let Some(first) = core_lines.first_mut() {
            first.push_str("  ");
            first.push_str(&trailing.replace('\n', " "));
        }
    }
    out.extend(core_lines);

    if let Some(after) = nc.map(|c| c.after.as_slice()).filter(|a| !a.is_empty()) {
        out.push(String::new());
        for c in after {
            render_comment_block(&mut out, indent_level, c);
        }
    }
    out
}

/// Renders one leading/after comment. A single-line comment (`#`/`//`, or a
/// `/* ... */` that never actually contains a newline) is just indented in
/// place. A genuine multi-line `/* ... */` block is dedented (using its
/// continuation lines' shared leading whitespace as the baseline) and then
/// re-indented as a whole, so internal relative alignment (ASCII art,
/// manually lined-up columns) survives the shift to a new indent level.
/// `unindented` (merge-reattached comments only, see
/// `normalize::rename::merge_only`) forces column 0 regardless of level.
fn render_comment_block(out: &mut Vec<String>, indent_level: usize, c: &ast::LeadingComment) {
    let indent = if c.unindented {
        String::new()
    } else {
        "    ".repeat(indent_level)
    };
    if !c.text.contains('\n') {
        out.push(format!("{indent}{}", c.text));
        return;
    }
    let mut lines = c.text.split('\n');
    let first = lines.next().unwrap_or("");
    let rest: Vec<&str> = lines.collect();
    let min_indent = rest
        .iter()
        .filter(|l| !l.trim().is_empty())
        .map(|l| l.len() - l.trim_start_matches([' ', '\t']).len())
        .min()
        .unwrap_or(0);
    out.push(format!("{indent}{first}"));
    for l in rest {
        let stripped = l.get(min_indent..).unwrap_or_else(|| l.trim_start());
        out.push(format!("{indent}{stripped}"));
    }
}

fn print_decl(d: &ast::Decl, cm: &ast::CommentMap, is_first: bool) -> Vec<String> {
    wrap_comments(cm, d.span(), 0, is_first, BlankRule::Always, || match d {
        ast::Decl::Import { name, from, .. } => {
            vec![if let Some(f) = from {
                format!("import {} from {};", name, format_string(f))
            } else {
                format!("import {};", name)
            }]
        }

        ast::Decl::Backend {
            name, none, body, ..
        } => {
            if *none {
                vec![format!("backend {} none;", name)]
            } else if let Some(fields) = body {
                let mut lines = vec![format!("backend {} {{", name)];
                lines.extend(print_fields(fields, cm, 1));
                lines.push("}".to_string());
                lines
            } else {
                vec![format!("backend {} {{}};", name)]
            }
        }

        ast::Decl::Probe { name, body, .. } => {
            let mut lines = vec![format!("probe {} {{", name)];
            lines.extend(print_fields(body, cm, 1));
            lines.push("}".to_string());
            lines
        }

        ast::Decl::Acl { name, entries, .. } => {
            let mut lines = vec![format!("acl {} {{", name)];
            for (i, entry) in entries.iter().enumerate() {
                lines.extend(wrap_comments(
                    cm,
                    entry.span,
                    1,
                    i == 0,
                    BlankRule::IfLeading,
                    || vec![format!("    {}", acl_entry_to_string(entry))],
                ));
            }
            lines.push("}".to_string());
            lines
        }

        ast::Decl::Sub { name, body, .. } => {
            let mut lines = vec![format!("sub {} {{", name)];
            lines.extend(print_stmts(body, cm, 1));
            lines.push("}".to_string());
            lines
        }
    })
}

fn print_fields(fields: &[ast::Field], cm: &ast::CommentMap, indent_level: usize) -> Vec<String> {
    let indent = "    ".repeat(indent_level);
    let mut lines = Vec::new();
    for (i, field) in fields.iter().enumerate() {
        lines.extend(wrap_comments(
            cm,
            field.span,
            indent_level,
            i == 0,
            BlankRule::IfLeading,
            || vec![format!("{indent}{}", field_to_string(field, cm))],
        ));
    }
    lines
}

fn print_stmts(stmts: &[ast::Stmt], cm: &ast::CommentMap, indent_level: usize) -> Vec<String> {
    let mut lines = Vec::new();
    for (i, stmt) in stmts.iter().enumerate() {
        lines.extend(wrap_comments(
            cm,
            stmt.span(),
            indent_level,
            i == 0,
            BlankRule::IfLeading,
            || stmt_to_lines(stmt, indent_level, cm),
        ));
    }
    lines
}

/// Prints a whole `.name = value;` field line, including the trailing
/// separator. An inline probe block (`.probe = { ... }`) is the one
/// exception: its closing '}' is the terminator and real VCC rejects a
/// trailing ';' after it (confirmed against `varnishd -C`), unlike every
/// other field-value form.
fn field_to_string(field: &ast::Field, cm: &ast::CommentMap) -> String {
    match &field.value {
        ast::FieldValue::Probe(_) => {
            format!(
                ".{} = {}",
                field.name,
                field_value_to_string(&field.value, cm)
            )
        }
        _ => format!(
            ".{} = {};",
            field.name,
            field_value_to_string(&field.value, cm)
        ),
    }
}

fn field_value_to_string(fv: &ast::FieldValue, cm: &ast::CommentMap) -> String {
    match fv {
        ast::FieldValue::Expr(e) => expr_to_string(e),
        ast::FieldValue::ProbeRef(name) => name.clone(),
        ast::FieldValue::StringList(strs) => strs
            .iter()
            .map(|s| format_string(s))
            .collect::<Vec<_>>()
            .join(" "),
        ast::FieldValue::Probe(fields) => {
            let inner = print_fields(fields, cm, 2);
            let mut s = "{\n".to_string();
            for line in inner {
                s.push_str(&line);
                s.push('\n');
            }
            s.push_str("    }");
            s
        }
    }
}

fn acl_entry_to_string(e: &ast::AclEntry) -> String {
    let neg = if e.negated { "!" } else { "" };
    match e.mask {
        Some(m) => format!("{}{} / {};", neg, format_string(&e.addr), m),
        None => format!("{}{};", neg, format_string(&e.addr)),
    }
}

fn stmt_to_lines(s: &ast::Stmt, indent_level: usize, cm: &ast::CommentMap) -> Vec<String> {
    let indent = "    ".repeat(indent_level);

    match s {
        ast::Stmt::Set { lhs, rhs, .. } => {
            vec![format!(
                "{}set {} = {};",
                indent,
                lvalue_to_string(lhs),
                expr_to_string(rhs)
            )]
        }

        ast::Stmt::Unset { lhs, .. } => {
            vec![format!("{}unset {};", indent, lvalue_to_string(lhs))]
        }

        ast::Stmt::Call { sub, .. } => {
            vec![format!("{}call {};", indent, sub)]
        }

        ast::Stmt::Return { action, .. } => {
            if let Some(a) = action {
                let arg_strs: Vec<_> = a.args.iter().map(expr_to_string).collect();
                if arg_strs.is_empty() {
                    vec![format!("{}return ({});", indent, a.name)]
                } else {
                    vec![format!(
                        "{}return ({} ({}));",
                        indent,
                        a.name,
                        arg_strs.join(", ")
                    )]
                }
            } else {
                vec![format!("{}return;", indent)]
            }
        }

        ast::Stmt::Synthetic { value, .. } => {
            vec![format!("{}synthetic ({});", indent, expr_to_string(value))]
        }

        ast::Stmt::If {
            arms, else_body, ..
        } => {
            let mut lines = Vec::new();

            for (i, (cond, body)) in arms.iter().enumerate() {
                let if_or_elsif = if i == 0 { "if" } else { "else if" };
                lines.push(format!(
                    "{}{} ({}) {{",
                    indent,
                    if_or_elsif,
                    expr_to_string(cond)
                ));

                lines.extend(print_stmts(body, cm, indent_level + 1));

                if i < arms.len() - 1 {
                    lines.push(format!("{}}} ", indent));
                } else {
                    if else_body.is_some() {
                        lines.push(format!("{}}} ", indent));
                    } else {
                        lines.push(format!("{}}}", indent));
                    }
                }
            }

            if let Some(else_stmts) = else_body {
                let last_idx = lines.len() - 1;
                let last_line = lines[last_idx].trim_end().to_string() + " else {";
                lines[last_idx] = last_line;
                lines.extend(print_stmts(else_stmts, cm, indent_level + 1));
                lines.push(format!("{}}}", indent));
            }

            lines
        }

        ast::Stmt::New {
            name,
            vmod,
            ctor,
            args,
            ..
        } => print_call_like(
            &format!("{indent}new {name} = {vmod}.{ctor}"),
            &indent,
            args,
            cm,
            indent_level,
            " = ",
        ),

        ast::Stmt::Expr {
            expr: ast::Expr::Call { target, args },
            ..
        } => print_call_like(
            &format!("{indent}{}", target.join(".")),
            &indent,
            args,
            cm,
            indent_level,
            "=",
        ),

        ast::Stmt::Expr { expr, .. } => {
            vec![format!("{}{};", indent, expr_to_string(expr))]
        }
    }
}

/// Renders `{prefix}(args);` -- the common shape of a bare call statement
/// (`std.log(...)`) and a `new x = vmod.ctor(...)` constructor call. Stays
/// on one line unless some arg carries a comment, in which case it expands
/// to one arg per line so there's somewhere for that comment to go.
fn print_call_like(
    prefix: &str,
    indent: &str,
    args: &[ast::Arg],
    cm: &ast::CommentMap,
    indent_level: usize,
    named_sep: &str,
) -> Vec<String> {
    let visible: Vec<&ast::Arg> = args
        .iter()
        .filter(|a| !matches!(a.value, ast::Expr::Omitted))
        .collect();

    if !visible.iter().any(|a| has_comments(cm, a.span)) {
        let arg_strs: Vec<String> = visible
            .iter()
            .map(|a| arg_to_string(a, named_sep))
            .collect();
        return vec![format!("{prefix}({});", arg_strs.join(", "))];
    }

    let arg_indent = "    ".repeat(indent_level + 1);
    let mut lines = vec![format!("{prefix}(")];
    for (i, a) in visible.iter().enumerate() {
        let comma = if i + 1 < visible.len() { "," } else { "" };
        lines.extend(wrap_comments(
            cm,
            a.span,
            indent_level + 1,
            i == 0,
            BlankRule::Never,
            || {
                vec![format!(
                    "{arg_indent}{}{comma}",
                    arg_to_string(a, named_sep)
                )]
            },
        ));
    }
    lines.push(format!("{indent});"));
    lines
}

fn has_comments(cm: &ast::CommentMap, span: ast::Span) -> bool {
    cm.get(span)
        .is_some_and(|c| !c.leading.is_empty() || c.trailing.is_some() || !c.after.is_empty())
}

fn arg_to_string(a: &ast::Arg, named_sep: &str) -> String {
    if let Some(name) = &a.name {
        format!("{name}{named_sep}{}", expr_to_string(&a.value))
    } else {
        expr_to_string(&a.value)
    }
}

/// Prints an expression as a single-line string (no trailing newline).
pub fn expr_to_string(e: &ast::Expr) -> String {
    match e {
        ast::Expr::Str(s) => format_string(s),

        ast::Expr::Num(n) => n.clone(),

        ast::Expr::Duration(d) => format_duration(*d),

        ast::Expr::Bytes(b) => format!("{}B", b),

        ast::Expr::Bool(b) => if *b { "true" } else { "false" }.to_string(),

        ast::Expr::Omitted => String::new(),

        ast::Expr::CSource(c) => format!("C{{ {} }}C", c),

        ast::Expr::Var(parts) => parts.join("."),

        ast::Expr::Call { target, args } => {
            let target_str = target.join(".");
            let arg_strs: Vec<_> = args
                .iter()
                .filter(|a| !matches!(a.value, ast::Expr::Omitted))
                .map(|a| {
                    if let Some(name) = &a.name {
                        format!("{}={}", name, expr_to_string(&a.value))
                    } else {
                        expr_to_string(&a.value)
                    }
                })
                .collect();

            format!("{}({})", target_str, arg_strs.join(", "))
        }

        ast::Expr::Unary { op, expr } => {
            let op_str = match op {
                ast::UnOp::Not => "!",
                ast::UnOp::Neg => "-",
            };
            format!("{}{}", op_str, expr_to_string(expr))
        }

        ast::Expr::Binary { op, lhs, rhs } => {
            let op_str = match op {
                ast::BinOp::Eq => "==",
                ast::BinOp::Ne => "!=",
                ast::BinOp::Match => "~",
                ast::BinOp::NotMatch => "!~",
                ast::BinOp::Lt => "<",
                ast::BinOp::Le => "<=",
                ast::BinOp::Gt => ">",
                ast::BinOp::Ge => ">=",
                ast::BinOp::And => "&&",
                ast::BinOp::Or => "||",
                ast::BinOp::Add => "+",
                ast::BinOp::Sub => "-",
                ast::BinOp::Mul => "*",
                ast::BinOp::Div => "/",
            };

            // Always parenthesize nested binaries for determinism and re-parseability
            let lhs_str = match &**lhs {
                ast::Expr::Binary { .. } => format!("({})", expr_to_string(lhs)),
                _ => expr_to_string(lhs),
            };

            let rhs_str = match &**rhs {
                ast::Expr::Binary { .. } => format!("({})", expr_to_string(rhs)),
                _ => expr_to_string(rhs),
            };

            format!("{} {} {}", lhs_str, op_str, rhs_str)
        }
    }
}

/// Prints a statement as a single-line string (no trailing newline).
pub fn stmt_to_string(s: &ast::Stmt) -> String {
    // Single-line version of statements (no indent, used by compare.rs for snippets)
    match s {
        ast::Stmt::Set { lhs, rhs, .. } => {
            format!("set {} = {}", lvalue_to_string(lhs), expr_to_string(rhs))
        }

        ast::Stmt::Unset { lhs, .. } => {
            format!("unset {}", lvalue_to_string(lhs))
        }

        ast::Stmt::Call { sub, .. } => {
            format!("call {}", sub)
        }

        ast::Stmt::Return { action, .. } => {
            if let Some(a) = action {
                let arg_strs: Vec<_> = a.args.iter().map(expr_to_string).collect();
                if arg_strs.is_empty() {
                    format!("return ({})", a.name)
                } else {
                    format!("return ({} ({}))", a.name, arg_strs.join(", "))
                }
            } else {
                "return".to_string()
            }
        }

        ast::Stmt::Synthetic { value, .. } => {
            format!("synthetic ({})", expr_to_string(value))
        }

        ast::Stmt::If {
            arms, else_body, ..
        } => {
            // Simplified single-line representation (not a perfect reproduction, but good enough for snippets)
            let cond_str = expr_to_string(&arms[0].0);
            if arms.len() == 1 && else_body.is_none() {
                format!("if ({}) {{ ... }}", cond_str)
            } else {
                format!("if ({}) {{ ... }} [else ...]", cond_str)
            }
        }

        ast::Stmt::New {
            name,
            vmod,
            ctor,
            args,
            ..
        } => {
            let arg_strs: Vec<_> = args
                .iter()
                .filter(|a| !matches!(a.value, ast::Expr::Omitted))
                .map(|a| {
                    if let Some(aname) = &a.name {
                        format!("{}={}", aname, expr_to_string(&a.value))
                    } else {
                        expr_to_string(&a.value)
                    }
                })
                .collect();

            format!("new {} = {}.{}({})", name, vmod, ctor, arg_strs.join(", "))
        }

        ast::Stmt::Expr { expr, .. } => expr_to_string(expr),
    }
}

fn lvalue_to_string(lv: &ast::Lvalue) -> String {
    lv.parts.join(".")
}

fn format_string(s: &str) -> String {
    if s.contains('"') || s.contains('\n') {
        format!("{{\"{}\"", s) + "}"
    } else {
        format!("\"{}\"", s)
    }
}

fn format_duration(d: f64) -> String {
    // Format as <n>s, trimming trailing zeros
    if d.fract() == 0.0 {
        // It's an integer
        format!("{}s", d as u64)
    } else {
        // Has decimal part; format and trim trailing zeros
        let s = format!("{}", d);
        let trimmed = s.trim_end_matches('0').trim_end_matches('.');
        format!("{}s", trimmed)
    }
}

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

    #[test]
    fn c3_printer_deterministic_strings() {
        // String containing quote should use {"..."}
        let prog = program(vec![sub("vcl_recv", vec![expr_stmt(str_("test\"quote"))])]);
        let output = print(&prog);
        // Long string syntax is {" ... "} so {"test"quote"} is the correct output
        assert!(
            output.contains("{\"test\"quote\""),
            "String with quote should use {{\"...\"}} long-string syntax"
        );

        // Regular string should use "..."
        let prog2 = program(vec![sub("vcl_recv", vec![expr_stmt(str_("simple"))])]);
        let output2 = print(&prog2);
        assert!(
            output2.contains("\"simple\""),
            "Simple string should use \"...\" syntax"
        );
    }

    #[test]
    fn c3_printer_deterministic_durations() {
        // 60 seconds should be "60s" not "1m"
        let prog = program(vec![sub("vcl_recv", vec![expr_stmt(dur(60.0))])]);
        let output = print(&prog);
        assert!(output.contains("60s"), "Duration 60 should print as 60s");

        // 0.5 seconds should be "0.5s"
        let prog2 = program(vec![sub("vcl_recv", vec![expr_stmt(dur(0.5))])]);
        let output2 = print(&prog2);
        assert!(
            output2.contains("0.5s"),
            "Duration 0.5 should print as 0.5s"
        );

        // 3600 should be "3600s", not "1h"
        let prog3 = program(vec![sub("vcl_recv", vec![expr_stmt(dur(3600.0))])]);
        let output3 = print(&prog3);
        assert!(
            output3.contains("3600s"),
            "Duration 3600 should print as 3600s"
        );
    }

    #[test]
    fn c3_printer_deterministic_bytes() {
        let prog = program(vec![sub("vcl_recv", vec![expr_stmt(bytes(1024))])]);
        let output = print(&prog);
        assert!(output.contains("1024B"), "Bytes should print as <n>B");
    }

    #[test]
    fn c3_printer_nested_binary_parenthesized() {
        // a + b * c should be a + (b * c) with parens around nested binary
        let prog = program(vec![sub(
            "vcl_recv",
            vec![expr_stmt(bin(
                ast::BinOp::Add,
                num("1"),
                bin(ast::BinOp::Mul, num("2"), num("3")),
            ))],
        )]);
        let output = print(&prog);
        assert!(
            output.contains("1 + (2 * 3)"),
            "Nested binary should be parenthesized"
        );
    }

    #[test]
    fn c3_printer_omitted_args_skipped() {
        // Omitted arguments should not appear in output
        let args = vec![arg(num("1")), arg(ast::Expr::Omitted), arg(num("3"))];
        let prog = program(vec![sub(
            "vcl_recv",
            vec![expr_stmt(fcall(&["std", "log"], args))],
        )]);
        let output = print(&prog);
        // The output should have the call with arguments but omitted ones should be missing
        assert!(
            output.contains("std.log"),
            "Function call should be printed"
        );
    }

    #[test]
    fn printer_backend_with_fields() {
        let fields = vec![
            fexpr("host", str_("example.com")),
            fexpr("port", str_("8080")),
        ];
        let prog = program(vec![backend("web", fields)]);
        let output = print(&prog);

        assert!(
            output.contains("backend web {"),
            "Backend declaration should open"
        );
        assert!(
            output.contains(".host = \"example.com\";"),
            "First field should be present"
        );
        assert!(
            output.contains(".port = \"8080\";"),
            "Second field should be present"
        );
        assert!(output.contains("}"), "Backend should close");
    }

    #[test]
    fn printer_sub_with_statements() {
        let stmts = vec![
            set(&["req", "http", "x"], str_("1")),
            call("vcl_hit"),
            ret(None),
        ];
        let prog = program(vec![sub("vcl_recv", stmts)]);
        let output = print(&prog);

        assert!(
            output.contains("sub vcl_recv {"),
            "Sub declaration should open"
        );
        assert!(
            output.contains("set req.http.x = \"1\";"),
            "Set statement should be present"
        );
        assert!(
            output.contains("call vcl_hit;"),
            "Call statement should be present"
        );
        assert!(
            output.contains("return;"),
            "Return statement should be present"
        );
        assert!(output.contains("}"), "Sub should close");
    }

    #[test]
    fn printer_acl() {
        let entries = vec![
            acl_entry("1.2.3.4", Some(32), false),
            acl_entry("192.168.0.0", Some(16), false),
            acl_entry("10.0.0.0", Some(8), true),
        ];
        let prog = program(vec![acl("office", entries)]);
        let output = print(&prog);

        assert!(output.contains("acl office {"), "ACL should open");
        assert!(output.contains("\"1.2.3.4\" / 32;"), "ACL entry with mask");
        assert!(output.contains("!\"10.0.0.0\" / 8;"), "Negated ACL entry");
    }

    #[test]
    fn expr_to_string_binary_operator_spacing() {
        // Operators should have single spaces around them
        let expr = bin(ast::BinOp::Eq, var(&["a"]), var(&["b"]));
        let s = expr_to_string(&expr);
        assert_eq!(s, "a == b", "Binary operator should have single spaces");
    }

    #[test]
    fn expr_to_string_call_with_named_args() {
        let args = vec![arg(num("1")), narg("resolve", bool_(true))];
        let expr = fcall(&["std", "log"], args);
        let s = expr_to_string(&expr);
        assert!(s.contains("std.log"), "Call target should be correct");
        assert!(
            s.contains("resolve=true"),
            "Named argument should be formatted as name=value"
        );
    }

    #[test]
    fn printer_vcl_header() {
        let prog = program(vec![]);
        let output = print(&prog);
        assert!(
            output.starts_with("vcl 4.1;"),
            "Output should start with vcl 4.1; header"
        );
    }

    #[test]
    fn printer_blank_lines_between_decls() {
        let prog = program(vec![backend("b1", vec![]), backend("b2", vec![])]);
        let output = print(&prog);
        // Should have vcl 4.1; then blank line, then first backend, blank line, second backend
        let lines: Vec<&str> = output.lines().collect();
        // At least 4 lines: vcl 4.1; (1), blank (2), backend b1 (3), blank (4), backend b2 (5)
        assert!(
            lines.len() >= 5,
            "Should have blank lines between declarations"
        );
    }
}

#[cfg(test)]
mod comment_tests {
    use super::*;
    use crate::normalize::rename::merge_only;
    use crate::parser::parse_str;

    fn parse(body: &str) -> ast::Program {
        parse_str(&format!("vcl 4.1;\n{body}")).expect("parse ok")
    }

    #[test]
    fn pc1_first_decl_leading_comment_no_blank_line() {
        let p = parse("// leading\nimport std;\n");
        let out = print(&p);
        assert_eq!(out, "vcl 4.1;\n// leading\nimport std;");
    }

    #[test]
    fn pc2_later_decl_leading_comment_gets_blank_line() {
        let p = parse("import std;\n\n// leading\nimport other;\n");
        let out = print(&p);
        assert_eq!(out, "vcl 4.1;\nimport std;\n\n// leading\nimport other;");
    }

    #[test]
    fn pc3_trailing_comment_on_multiline_decl_header_line() {
        let p = parse("backend web { // note\n .host = \"1.2.3.4\";\n}\n");
        let out = print(&p);
        assert!(
            out.contains("backend web {  // note\n"),
            "trailing comment should attach to the opening line, got:\n{out}"
        );
    }

    #[test]
    fn pc4_inline_field_and_stmt_trailing_comments() {
        let p = parse("sub vcl_recv {\n    set req.http.x = \"1\"; // note\n}\n");
        let out = print(&p);
        assert!(out.contains("set req.http.x = \"1\";  // note"));
    }

    #[test]
    fn pc5_first_stmt_leading_comment_no_blank_line_after_brace() {
        let p = parse("sub vcl_recv {\n    // leading\n    return (lookup);\n}\n");
        let out = print(&p);
        assert!(
            out.contains("sub vcl_recv {\n    // leading\n    return (lookup);\n}"),
            "got:\n{out}"
        );
    }

    #[test]
    fn pc6_later_stmt_leading_comment_gets_blank_line() {
        let p = parse(
            "sub vcl_recv {\n    set req.http.x = \"1\";\n\n    // leading\n    return (lookup);\n}\n",
        );
        let out = print(&p);
        assert!(out.contains("set req.http.x = \"1\";\n\n    // leading\n    return (lookup);"));
    }

    #[test]
    fn pc7_orphan_comment_before_closing_brace_attaches_to_previous_stmt() {
        let p = parse("sub vcl_recv {\n    return (lookup);\n\n    // orphan\n}\n");
        let out = print(&p);
        assert!(
            out.contains("return (lookup);\n\n    // orphan\n}"),
            "got:\n{out}"
        );
    }

    #[test]
    fn pc8_eof_trailing_comment_survives_decl_reordering() {
        // sub, acl, backend, import is NOT kind-rank order -- sort.rs
        // reorders to import, backend, acl, sub. The trailing comment must
        // still land at the very end, not wherever `sub` (originally last)
        // ends up.
        let mut p = parse(
            "sub vcl_recv { return (lookup); }\nacl a { \"1.2.3.4\"/32; }\nbackend b { .host = \"x\"; }\nimport std;\n\n# eof\n",
        );
        crate::normalize::sort::run(&mut p);
        let out = print(&p);
        assert!(out.trim_end().ends_with("# eof"), "got:\n{out}");
        let sub_pos = out.find("sub vcl_recv").unwrap();
        let eof_pos = out.find("# eof").unwrap();
        assert!(
            eof_pos > sub_pos,
            "eof comment must print after sub, got:\n{out}"
        );
    }

    #[test]
    fn pc9_block_comment_preserves_relative_alignment_on_reindent() {
        let p = parse(
            "sub vcl_recv {\n    /* line one\n       extra indent\n    */\n    return (lookup);\n}\n",
        );
        let out = print(&p);
        let lines: Vec<&str> = out.lines().collect();
        let start = lines.iter().position(|l| l.contains("line one")).unwrap();
        assert_eq!(lines[start], "    /* line one");
        assert_eq!(lines[start + 1], "       extra indent");
        assert_eq!(lines[start + 2], "    */");
    }

    #[test]
    fn pc10_arg_comment_forces_one_per_line_no_blank_before_it() {
        let p = parse("sub vcl_recv {\n    std.log(\"a\", /* c */ \"b\");\n}\n");
        let out = print(&p);
        assert!(out.contains("std.log(\n"), "got:\n{out}");
        assert!(
            !out.contains("\n\n        /* c */"),
            "no blank line should precede an arg's leading comment, got:\n{out}"
        );
        assert!(out.contains("/* c */\n        \"b\""), "got:\n{out}");
    }

    #[test]
    fn pc11_merge_reattaches_fragment_decl_comment_unindented() {
        let mut p = parse(
            "sub vcl_recv {\n    set req.http.a = \"1\";\n}\n// second fragment\nsub vcl_recv {\n    set req.http.b = \"2\";\n}\n",
        );
        merge_only(&mut p);
        let out = print(&p);
        assert_eq!(p.decls.len(), 1, "fragments should be merged into one sub");
        assert!(
            out.contains("\n// second fragment\n    set req.http.b"),
            "reattached comment should be unindented (column 0), got:\n{out}"
        );
    }

    #[test]
    fn pc12_comments_never_affect_canonical_json() {
        let commented = parse("// note\nimport std;\n// another\n");
        let plain = parse("import std;\n");
        assert_eq!(
            crate::canon::to_string(&commented),
            crate::canon::to_string(&plain),
            "comments must never affect canonical JSON"
        );
    }
}