toride-ssh-config 0.1.0

SSH config file parsing, editing, and host resolution via a lossless AST
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
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
#![allow(clippy::unreadable_literal)]

use super::*;

#[test]
fn parse_simple_host_block() {
    let input = "\
Host example
    HostName example.com
    User alice
    IdentityFile ~/.ssh/id_ed25519

Host *
    ServerAliveInterval 60
";
    let ast = parse(input);
    assert_eq!(ast.nodes.len(), 3);

    match &ast.nodes[0] {
        ConfigNode::HostBlock(b) => {
            assert_eq!(b.patterns, &["example"]);
            assert_eq!(b.nodes.len(), 3);
        }
        _ => panic!("expected HostBlock"),
    }
}

#[test]
fn round_trip_preserves_content() {
    let input = "\
# My SSH config
Host example
    HostName=example.com
    User alice

Host *
    ServerAliveInterval 60
";
    let ast = parse(input);
    let output = ast.to_string_lossless();
    assert_eq!(output, input);
}

#[test]
fn parse_equals_separator() {
    let input = "Host=myserver\n    HostName=192.168.1.1\n";
    let ast = parse(input);
    match &ast.nodes[0] {
        ConfigNode::HostBlock(b) => {
            assert_eq!(b.header, "Host=myserver");
        }
        _ => panic!("expected HostBlock"),
    }
}

#[test]
fn split_trailing_comment_works() {
    let (val, comment) = split_trailing_comment("hello # a comment");
    assert_eq!(val, "hello");
    assert_eq!(comment, Some("a comment".to_owned()));

    let (val, comment) = split_trailing_comment("no comment");
    assert_eq!(val, "no comment");
    assert_eq!(comment, None);

    let (val, comment) = split_trailing_comment("\"path # here\" # real comment");
    assert_eq!(val, "\"path # here\"");
    assert_eq!(comment, Some("real comment".to_owned()));
}

#[test]
fn parse_directive_with_equals_in_value() {
    let (keyword, sep, rest) = parse_directive_parts("SetEnv FOO=bar");
    assert_eq!(keyword, "SetEnv");
    assert_eq!(sep, Separator::Space);
    assert_eq!(rest, "FOO=bar");
}

#[test]
fn parse_directive_equals_separator() {
    let (keyword, sep, rest) = parse_directive_parts("HostName=example.com");
    assert_eq!(keyword, "HostName");
    assert_eq!(sep, Separator::Equals);
    assert_eq!(rest, "example.com");
}

#[test]
fn round_trip_preserves_tab_indentation() {
    let input = "Host example\n\tHostName example.com\n\tUser alice\n";
    let ast = parse(input);
    let output = ast.to_string_lossless();
    assert_eq!(output, input);
}

#[test]
fn round_trip_with_comment_in_block() {
    let input = "Host example\n    # inline comment\n    HostName example.com\n";
    let ast = parse(input);
    let output = ast.to_string_lossless();
    assert_eq!(output, input);
}

// ---------------------------------------------------------------------------
// Edge-case tests
// ---------------------------------------------------------------------------

#[test]
fn parse_empty_input() {
    let ast = parse("");
    assert!(ast.nodes.is_empty());
}

#[test]
fn parse_only_whitespace() {
    let ast = parse("   \n  \n");
    // Whitespace-only lines are treated as blank lines
    assert!(ast.nodes.iter().all(|n| matches!(n, ConfigNode::BlankLine)));
}

#[test]
fn parse_only_comments() {
    let input = "# comment 1\n# comment 2\n";
    let ast = parse(input);
    assert_eq!(ast.nodes.len(), 2);
    assert!(
        ast.nodes
            .iter()
            .all(|n| matches!(n, ConfigNode::Comment { .. }))
    );
}

#[test]
fn parse_host_with_no_directives() {
    let input = "Host empty\n";
    let ast = parse(input);
    assert_eq!(ast.nodes.len(), 1);
    match &ast.nodes[0] {
        ConfigNode::HostBlock(b) => {
            assert_eq!(b.patterns, &["empty"]);
            assert!(b.nodes.is_empty());
        }
        _ => panic!("expected HostBlock"),
    }
}

#[test]
fn parse_host_with_multiple_patterns() {
    let input = "Host web1 web2 *.example.com\n    User admin\n";
    let ast = parse(input);
    match &ast.nodes[0] {
        ConfigNode::HostBlock(b) => {
            assert_eq!(b.patterns, &["web1", "web2", "*.example.com"]);
        }
        _ => panic!("expected HostBlock"),
    }
}

#[test]
fn parse_directive_keyword_only() {
    let (keyword, sep, rest) = parse_directive_parts("ForwardAgent");
    assert_eq!(keyword, "ForwardAgent");
    assert_eq!(sep, Separator::Space);
    assert_eq!(rest, "");
}

#[test]
fn parse_directive_with_tab_separator() {
    let input = "Host example\n\tHostName example.com\n";
    let ast = parse(input);
    match &ast.nodes[0] {
        ConfigNode::HostBlock(b) => match &b.nodes[0] {
            ConfigNode::Directive(d) => {
                assert_eq!(d.keyword, "HostName");
                assert_eq!(d.indent, "\t");
            }
            _ => panic!("expected Directive"),
        },
        _ => panic!("expected HostBlock"),
    }
}

#[test]
fn parse_multiple_host_blocks() {
    let input = "\
Host web
    HostName web.example.com

Host db
    HostName db.example.com
";
    let ast = parse(input);
    assert_eq!(ast.nodes.len(), 3); // web, blank, db
    match &ast.nodes[0] {
        ConfigNode::HostBlock(b) => assert_eq!(b.patterns, &["web"]),
        _ => panic!("expected HostBlock"),
    }
    match &ast.nodes[2] {
        ConfigNode::HostBlock(b) => assert_eq!(b.patterns, &["db"]),
        _ => panic!("expected HostBlock"),
    }
}

#[test]
fn parse_match_block() {
    let input = "Match host web*\n    User admin\n";
    let ast = parse(input);
    assert_eq!(ast.nodes.len(), 1);
    match &ast.nodes[0] {
        ConfigNode::MatchBlock(b) => {
            assert_eq!(b.criteria, "host web*");
            assert_eq!(b.nodes.len(), 1);
        }
        _ => panic!("expected MatchBlock"),
    }
}

#[test]
fn round_trip_empty_input() {
    let ast = parse("");
    assert_eq!(ast.to_string_lossless(), "");
}

#[test]
fn line_indent_empty_string() {
    assert_eq!(line_indent(""), "");
}

#[test]
fn line_indent_no_indent() {
    assert_eq!(line_indent("hello"), "");
}

#[test]
fn line_indent_spaces() {
    assert_eq!(line_indent("    hello"), "    ");
}

#[test]
fn line_indent_tabs() {
    assert_eq!(line_indent("\thello"), "\t");
}

#[test]
fn line_indent_mixed() {
    assert_eq!(line_indent("  \t  hello"), "  \t  ");
}

// ---------------------------------------------------------------------------
// Weird edge-case tests
// ---------------------------------------------------------------------------

#[test]
fn parse_config_with_crlf_line_endings() {
    // Windows-edited SSH config files may use \r\n
    let input = "Host example\r\n    HostName example.com\r\n    User alice\r\n";
    let ast = parse(input);
    // CRLF means \r is part of the trimmed content
    match &ast.nodes[0] {
        ConfigNode::HostBlock(b) => {
            // The \r may be preserved in the header
            assert!(b.patterns[0].contains("example") || header_contains_r(&ast.nodes[0]));
            // At minimum, we should get a HostBlock back
            assert!(!b.nodes.is_empty());
        }
        _ => panic!("expected HostBlock"),
    }
}

fn header_contains_r(node: &ConfigNode) -> bool {
    match node {
        ConfigNode::HostBlock(b) => b.header.contains('\r'),
        _ => false,
    }
}

#[test]
fn parse_config_with_trailing_whitespace() {
    let input = "Host example   \n    HostName example.com   \n";
    let ast = parse(input);
    // Trailing whitespace should be trimmed
    match &ast.nodes[0] {
        ConfigNode::HostBlock(b) => {
            assert_eq!(b.patterns[0], "example");
        }
        _ => panic!("expected HostBlock"),
    }
}

#[test]
fn parse_config_with_only_blank_lines() {
    let input = "\n\n\n\n";
    let ast = parse(input);
    assert_eq!(ast.nodes.len(), 4);
    assert!(ast.nodes.iter().all(|n| matches!(n, ConfigNode::BlankLine)));
}

#[test]
fn parse_config_with_mixed_blank_and_comments() {
    let input = "# comment 1\n\n# comment 2\n\n";
    let ast = parse(input);
    assert_eq!(ast.nodes.len(), 4);
    assert!(matches!(&ast.nodes[0], ConfigNode::Comment { .. }));
    assert!(matches!(&ast.nodes[1], ConfigNode::BlankLine));
    assert!(matches!(&ast.nodes[2], ConfigNode::Comment { .. }));
    assert!(matches!(&ast.nodes[3], ConfigNode::BlankLine));
}

#[test]
fn parse_host_with_very_long_name() {
    let long_name = "a".repeat(256);
    let input = format!("Host {long_name}\n    User alice\n");
    let ast = parse(&input);
    match &ast.nodes[0] {
        ConfigNode::HostBlock(b) => {
            assert_eq!(b.patterns[0], long_name);
        }
        _ => panic!("expected HostBlock"),
    }
}

#[test]
fn parse_host_with_special_characters() {
    let input = "Host my-host.example.com\n    User alice\n";
    let ast = parse(input);
    match &ast.nodes[0] {
        ConfigNode::HostBlock(b) => {
            assert_eq!(b.patterns[0], "my-host.example.com");
        }
        _ => panic!("expected HostBlock"),
    }
}

#[test]
fn parse_directive_with_equals_no_spaces() {
    let input = "Host=example\nHostName=example.com\nUser=alice\n";
    let ast = parse(input);
    match &ast.nodes[0] {
        ConfigNode::HostBlock(b) => {
            assert_eq!(b.header, "Host=example");
        }
        _ => panic!("expected HostBlock"),
    }
}

#[test]
fn round_trip_normalizes_crlf() {
    // CRLF is normalized to LF by the parser (lines() splits on \n, \r stays in content)
    let input = "Host example\r\n    User alice\r\n";
    let ast = parse(input);
    let output = ast.to_string_lossless();
    // The parser preserves \r as part of the line content
    // This is a known behavior — CRLF files will have \r in their content
    let _ = output;
}

#[test]
fn parse_comment_with_leading_whitespace() {
    let input = "    # indented comment\n";
    let ast = parse(input);
    match &ast.nodes[0] {
        ConfigNode::Comment { text, indent } => {
            assert_eq!(text, "# indented comment");
            assert_eq!(indent, "    ");
        }
        _ => panic!("expected Comment"),
    }
}

#[test]
fn parse_multiple_consecutive_blank_lines() {
    let input = "Host example\n\n\n\n    User alice\n";
    let ast = parse(input);
    // Blank lines inside a Host block are part of the block body.
    // A blank line (no whitespace) breaks out of the block, so:
    // "Host example\n" starts the block
    // "\n" is a blank line (breaks out of block)
    // "\n\n    User alice\n" — the remaining blank lines and indented User
    // form a separate block or standalone directives
    // The exact structure depends on the parser's blank-line handling
    assert!(!ast.nodes.is_empty());
}

#[test]
fn parse_host_block_followed_immediately_by_another() {
    let input = "Host a\n    User alice\nHost b\n    User bob\n";
    let ast = parse(input);
    assert_eq!(ast.nodes.len(), 2); // no blank line between
    match &ast.nodes[0] {
        ConfigNode::HostBlock(b) => assert_eq!(b.patterns[0], "a"),
        _ => panic!("expected HostBlock"),
    }
    match &ast.nodes[1] {
        ConfigNode::HostBlock(b) => assert_eq!(b.patterns[0], "b"),
        _ => panic!("expected HostBlock"),
    }
}

// ---------------------------------------------------------------------------
// Production-grade weird edge cases
// ---------------------------------------------------------------------------

#[test]
fn parse_config_with_no_trailing_newline() {
    let input = "Host example\n    User alice";
    let ast = parse(input);
    match &ast.nodes[0] {
        ConfigNode::HostBlock(b) => {
            assert_eq!(b.nodes.len(), 1);
        }
        _ => panic!("expected HostBlock"),
    }
}

#[test]
fn parse_config_with_only_newline() {
    let ast = parse("\n");
    assert_eq!(ast.nodes.len(), 1);
    assert!(matches!(&ast.nodes[0], ConfigNode::BlankLine));
}

#[test]
fn parse_config_with_bom() {
    // UTF-8 BOM is \u{FEFF} — Windows editors sometimes add this
    let input = "\u{FEFF}Host example\n    User alice\n";
    let ast = parse(input);
    // The BOM should be handled gracefully (either preserved or stripped)
    assert!(!ast.nodes.is_empty());
}

#[test]
fn parse_config_with_tabs_and_spaces_mixed() {
    let input = "Host example\n\t  User alice\n  \tPort 22\n";
    let ast = parse(input);
    match &ast.nodes[0] {
        ConfigNode::HostBlock(b) => {
            assert_eq!(b.nodes.len(), 2);
        }
        _ => panic!("expected HostBlock"),
    }
}

#[test]
fn parse_config_with_carriage_return_only() {
    // Old Mac line endings (\r without \n)
    let input = "Host example\r    User alice\r";
    let ast = parse(input);
    // \r-only is not a line separator in Rust's lines(), so it's one big line
    // The parser should handle this gracefully
    let _ = ast;
}

#[test]
fn parse_host_with_empty_pattern() {
    // "Host " with nothing after it
    let input = "Host \n    User alice\n";
    let ast = parse(input);
    // Should parse as a Host block with empty pattern
    match &ast.nodes[0] {
        ConfigNode::HostBlock(b) => {
            assert!(b.patterns.is_empty() || b.patterns.contains(&String::new()));
        }
        _ => panic!("expected HostBlock"),
    }
}

#[test]
fn parse_host_with_only_negation_pattern() {
    let input = "Host !badhost\n    User alice\n";
    let ast = parse(input);
    match &ast.nodes[0] {
        ConfigNode::HostBlock(b) => {
            assert_eq!(b.patterns[0], "!badhost");
        }
        _ => panic!("expected HostBlock"),
    }
}

#[test]
fn parse_match_with_exec_criteria() {
    // Match exec is unsupported but should not panic
    let input = "Match exec \"/bin/true\"\n    User alice\n";
    let ast = parse(input);
    match &ast.nodes[0] {
        ConfigNode::MatchBlock(b) => {
            assert!(b.criteria.contains("exec"));
        }
        _ => panic!("expected MatchBlock"),
    }
}

#[test]
fn parse_directive_with_very_long_value() {
    let long_value = "x".repeat(100000);
    let input = format!("Host example\n    HostName {long_value}\n");
    let ast = parse(&input);
    match &ast.nodes[0] {
        ConfigNode::HostBlock(b) => match &b.nodes[0] {
            ConfigNode::Directive(d) => {
                assert_eq!(d.value.len(), 100000);
            }
            _ => panic!("expected Directive"),
        },
        _ => panic!("expected HostBlock"),
    }
}

#[test]
fn parse_config_with_control_characters() {
    // Control characters in config (tab is ok, others are unusual)
    let input = "Host example\n\tUser alice\n";
    let ast = parse(input);
    match &ast.nodes[0] {
        ConfigNode::HostBlock(b) => {
            assert_eq!(b.nodes.len(), 1);
        }
        _ => panic!("expected HostBlock"),
    }
}

#[test]
fn round_trip_no_trailing_newline() {
    let input = "Host example\n    User alice";
    let ast = parse(input);
    let output = ast.to_string_lossless();
    // The parser adds a trailing newline to each directive
    assert!(output.starts_with("Host example"));
    assert!(output.contains("User alice"));
}

#[test]
fn parse_host_with_multiple_negation_patterns() {
    let input = "Host * !bad1 !bad2\n    User alice\n";
    let ast = parse(input);
    match &ast.nodes[0] {
        ConfigNode::HostBlock(b) => {
            assert_eq!(b.patterns, &["*", "!bad1", "!bad2"]);
        }
        _ => panic!("expected HostBlock"),
    }
}

#[test]
fn parse_comment_with_hash_in_value() {
    let input = "Host example\n    # This is a comment with # inside\n";
    let ast = parse(input);
    match &ast.nodes[0] {
        ConfigNode::HostBlock(b) => match &b.nodes[0] {
            ConfigNode::Comment { text, .. } => {
                assert!(text.contains('#'));
            }
            _ => panic!("expected Comment"),
        },
        _ => panic!("expected HostBlock"),
    }
}

#[test]
fn parse_directive_with_hash_in_quoted_value() {
    let input = "Host example\n    IdentityFile \"path#with#hash\"\n";
    let ast = parse(input);
    match &ast.nodes[0] {
        ConfigNode::HostBlock(b) => {
            match &b.nodes[0] {
                ConfigNode::Directive(d) => {
                    // The # inside quotes should not be treated as a comment
                    assert!(d.value.contains('#') || d.comment.is_some());
                }
                _ => panic!("expected Directive"),
            }
        }
        _ => panic!("expected HostBlock"),
    }
}

// ---------------------------------------------------------------------------
// Edge case: = separator roundtrip preservation
// ---------------------------------------------------------------------------

#[test]
fn round_trip_preserves_equals_separator() {
    let input = "Host=myserver\n    HostName=example.com\n    User=alice\n";
    let ast = parse(input);
    let output = ast.to_string_lossless();
    assert_eq!(output, input);
}

#[test]
fn round_trip_preserves_mixed_separators() {
    // Mix of = and space separators in the same block
    let input = "Host example\n    HostName=example.com\n    User alice\n";
    let ast = parse(input);
    let output = ast.to_string_lossless();
    assert_eq!(output, input);
}

#[test]
fn round_trip_preserves_multiple_blank_lines() {
    let input =
        "Host example\n    HostName example.com\n\n\n\nHost other\n    HostName other.com\n";
    let ast = parse(input);
    let output = ast.to_string_lossless();
    assert_eq!(output, input);
}

#[test]
fn round_trip_preserves_trailing_newline() {
    let input = "Host example\n    HostName example.com\n";
    let ast = parse(input);
    let output = ast.to_string_lossless();
    assert_eq!(output, input);
    assert!(output.ends_with('\n'));
}

#[test]
fn round_trip_preserves_inline_comment_with_equals() {
    // The AST parser strips the space after # in inline comments.
    let input = "Host example\n    HostName=example.com #my server\n";
    let ast = parse(input);
    let output = ast.to_string_lossless();
    assert_eq!(output, input);
}

#[test]
fn parse_empty_config() {
    let ast = parse("");
    assert!(ast.nodes.is_empty());
    assert_eq!(ast.to_string_lossless(), "");
}

#[test]
fn parse_only_comments_roundtrip() {
    let input = "# comment 1\n# comment 2\n";
    let ast = parse(input);
    assert_eq!(ast.nodes.len(), 2);
    assert!(
        ast.nodes
            .iter()
            .all(|n| matches!(n, ConfigNode::Comment { .. }))
    );
    assert_eq!(ast.to_string_lossless(), input);
}

#[test]
fn parse_only_blank_lines() {
    let input = "\n\n\n";
    let ast = parse(input);
    assert_eq!(ast.nodes.len(), 3);
    assert!(ast.nodes.iter().all(|n| matches!(n, ConfigNode::BlankLine)));
    assert_eq!(ast.to_string_lossless(), input);
}

#[test]
fn round_trip_preserves_deeply_nested_indent() {
    // Some users use unusual indentation
    let input = "Host example\n            HostName example.com\n";
    let ast = parse(input);
    let output = ast.to_string_lossless();
    assert_eq!(output, input);
}

// ---------------------------------------------------------------------------
// Property-based round-trip test
// ---------------------------------------------------------------------------
//
// The lossless AST parser's central invariant is that for any config it
// faithfully round-trips, `parse(x).to_string_lossless() == x`. The hand-picked
// cases above only exercise the shapes the author thought of; this proptest
// generates a wide variety of config texts (drawn from the subset the parser
// is *documented* to preserve byte-for-byte) and asserts the invariant holds.
//
// We generate inputs by *construction* rather than from arbitrary `String`s:
// the parser has known, intentional non-lossless behaviours for inputs outside
// its contract (keyword-only directives gain a trailing space, CRLF is
// normalized to LF, whitespace-only lines collapse to blank lines, runs of
// spaces inside a header collapse). Those edge cases are covered by the
// dedicated tests above; the property test stays inside the lossless contract
// so a failure unambiguously means a real regression.

use proptest::prelude::*;

/// A safe alphabet for keyword tokens, host patterns, and comment text.
///
/// Excludes `\r`, `#`, `=`, `"`, `'`, and whitespace so the generated token
/// cannot accidentally introduce a separator, an inline comment, a quoting
/// boundary, or a line break.
fn safe_token() -> impl Strategy<Value = String> {
    "[A-Za-z0-9._\\-*/?]{1,12}"
}

/// A safe directive value: no `#` (would start a comment), no `=`, no quotes,
/// no whitespace, no control chars. Non-empty so the directive is never
/// rendered keyword-only (keyword-only directives are an intentional
/// non-lossless edge case).
fn safe_value() -> impl Strategy<Value = String> {
    "[A-Za-z0-9._\\-/:+]{1,16}"
}

/// Leading indentation: a run of spaces or a single tab (no mixing). Empty
/// for top-level lines; non-empty for lines inside a block.
fn indent_str() -> impl Strategy<Value = String> {
    prop_oneof![Just(String::new()), "[ ]{1,8}", Just("\t".to_owned())]
}

/// One top-level config line that the parser is contracted to preserve.
fn top_level_line() -> impl Strategy<Value = String> {
    prop_oneof![
        // Blank line (exactly empty — whitespace-only would collapse).
        Just("\n".to_owned()),
        // Comment line: `#` + safe text, no trailing whitespace.
        safe_token().prop_map(|t| format!("#{t}\n")),
        // Standalone directive: `Keyword Value\n`.
        (safe_token(), safe_value()).prop_map(|(k, v)| format!("{k} {v}\n")),
        // Host block with one indented directive body.
        (safe_token(), indent_str(), safe_token(), safe_value())
            .prop_map(|(pat, ind, dk, dval)| { format!("Host {pat}\n{ind}{dk} {dval}\n") }),
        // Match block with one indented directive body.
        (safe_token(), indent_str(), safe_token(), safe_value())
            .prop_map(|(crit, ind, dk, dval)| { format!("Match host {crit}\n{ind}{dk} {dval}\n") }),
    ]
}

proptest! {
    #![proptest_config(ProptestConfig::with_cases(512))]

    /// `parse` followed by `to_string_lossless` is the identity on every
    /// generated config inside the parser's lossless contract.
    #[test]
    fn prop_parse_to_string_lossless_roundtrip(lines in prop::collection::vec(top_level_line(), 0..16)) {
        let input: String = lines.concat();
        let rendered = parse(&input).to_string_lossless();
        prop_assert_eq!(rendered, input);
    }
}