ridl-cli 0.6.0

The `ridl` command-line toolchain: check, baseline, build, test, fmt, diff, lock, lsp, mcp, and describe, over the shared compiler crates.
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
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
//! The `[lints]` levels as the `ridl` command shows and applies them (ADR-0024
//! decision 6, docs/book/cli-reference.md and docs/book/lints.md): the `lint`
//! field of the JSON report, the lint note of the text report, the exit code of
//! `check` and `build` under `deny`, the commands that do not apply levels
//! (ADR-0024 decision 8), and the `--baseline` path, whose RIDL-407 is raised
//! by the CLI after `ridlc` returns.

use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicUsize, Ordering};

/// A unique directory under the system temp dir, removed on drop.
struct TempDir(PathBuf);

impl TempDir {
    fn new(label: &str) -> Self {
        static COUNTER: AtomicUsize = AtomicUsize::new(0);
        let mut path = std::env::temp_dir();
        path.push(format!(
            "ridl-lints-{label}-{}-{}",
            std::process::id(),
            COUNTER.fetch_add(1, Ordering::SeqCst),
        ));
        std::fs::create_dir_all(&path).expect("create the temp dir");
        Self(path)
    }

    fn path(&self) -> &Path {
        &self.0
    }

    fn write(&self, relative: &str, text: &str) -> PathBuf {
        let path = self.0.join(relative);
        std::fs::create_dir_all(path.parent().expect("a relative path has a parent"))
            .expect("create parent directories");
        std::fs::write(&path, text).expect("write the fixture file");
        path
    }
}

impl Drop for TempDir {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.0);
    }
}

/// Runs `ridl` with `args`, returning `(exit_code, stdout, stderr)`.
fn ridl(args: &[&OsStr]) -> (i32, String, String) {
    ridl_in(None, args)
}

/// Runs `ridl` with `args` from `current_dir` when one is given.
fn ridl_in(current_dir: Option<&Path>, args: &[&OsStr]) -> (i32, String, String) {
    let mut command = Command::new(env!("CARGO_BIN_EXE_ridl"));
    command.args(args);
    if let Some(dir) = current_dir {
        command.current_dir(dir);
    }
    let output = command.output().expect("the ridl binary must run");
    let code = output.status.code().expect("the process exits with a code");
    (
        code,
        String::from_utf8_lossy(&output.stdout).into_owned(),
        String::from_utf8_lossy(&output.stderr).into_owned(),
    )
}

/// A `signal` with no timing annotation, which draws RIDL-100
/// (`missing-timing`, a Warning by default). Seven lines, so the rendered
/// gutter is two spaces wide.
const SOURCE: &str = "package demo\n\ntype Speed: integer [0..300]\n\ninterface Sensor {\n  \
                      signal speed: Speed\n}\n";

const DENY: &str = "\n[lints]\nmissing-timing = \"deny\"\n";
const ALLOW: &str = "\n[lints]\nmissing-timing = \"allow\"\n";

/// A workspace with one member, `sensor`, whose manifest ends with `lints`:
/// the text of a `[lints]` table, or an empty string for none. Returns the
/// workspace root.
fn member_workspace(dir: &TempDir, lints: &str) -> PathBuf {
    dir.write("ridl.toml", "[workspace]\nmembers = [\"sensor\"]\n");
    dir.write(
        "sensor/ridl.toml",
        &format!("[package]\nname = \"demo\"\nversion = \"1.0.0\"\n{lints}"),
    );
    dir.write("sensor/sensor.ridl", SOURCE);
    dir.path().to_path_buf()
}

#[test]
fn json_carries_lint_field_and_deny_exits_1() {
    let dir = TempDir::new("json-deny");
    let root = member_workspace(&dir, DENY);
    // A second member file with an Error-code diagnostic, to check that an
    // Error code has no `lint` key. The file is broken on its own: no
    // trailing newline, so the parser's EOF diagnostic stays on line 2.
    dir.write("sensor/broken.ridl", "package demo\ntype X:");

    let (code, stdout, stderr) = ridl(&[
        "check".as_ref(),
        "--format".as_ref(),
        "json".as_ref(),
        root.as_os_str(),
    ]);

    assert_eq!(
        code, 1,
        "a lint at deny exits 1:\nstdout:\n{stdout}\nstderr:\n{stderr}"
    );
    let diagnostics: serde_json::Value = serde_json::from_str(&stdout).expect("stdout is JSON");
    let diagnostics = diagnostics.as_array().expect("a JSON array");
    let ridl_100 = diagnostics
        .iter()
        .find(|diagnostic| diagnostic["code"] == "RIDL-100")
        .expect("a RIDL-100 element");
    assert_eq!(ridl_100["severity"], "error", "{ridl_100}");
    assert_eq!(ridl_100["lint"], "missing-timing", "{ridl_100}");

    let error_code = diagnostics
        .iter()
        .find(|diagnostic| diagnostic["code"] != "RIDL-100" && diagnostic["severity"] == "error")
        .expect("an Error-code element");
    assert!(
        error_code.get("lint").is_none(),
        "an Error code has no `lint` key: {error_code}"
    );
}

/// A workspace with one member whose interface declares one `command`, with
/// the timing annotation `timing` (empty for none), under
/// `missing-response-bound = "deny"`. Returns the workspace root.
fn response_bound_workspace(dir: &TempDir, timing: &str) -> PathBuf {
    dir.write("ridl.toml", "[workspace]\nmembers = [\"actuator\"]\n");
    dir.write(
        "actuator/ridl.toml",
        "[package]\nname = \"demo\"\nversion = \"1.0.0\"\n\n[lints]\n\
         missing-response-bound = \"deny\"\n",
    );
    dir.write(
        "actuator/actuator.ridl",
        &format!(
            "package demo\n\ntype Speed: integer [0..300]\n\ninterface Actuator {{\n  \
             command setTarget(speed: Speed){timing}\n}}\n"
        ),
    );
    dir.path().to_path_buf()
}

/// `missing-response-bound = "deny"` makes the default response bound an
/// error: an unannotated command reports RIDL-112 as an error and exits 1,
/// and the same command with a written bound exits 0.
#[test]
fn missing_response_bound_deny_exits_1_until_the_bound_is_written() {
    let dir = TempDir::new("response-bound-deny");
    let root = response_bound_workspace(&dir, "");
    let (code, _, stderr) = ridl(&["check".as_ref(), root.as_os_str()]);
    assert_eq!(code, 1, "an untimed command at deny exits 1:\n{stderr}");
    assert!(
        stderr.contains("error[RIDL-112]"),
        "the lint is rendered as an error:\n{stderr}"
    );

    let dir = TempDir::new("response-bound-written");
    let root = response_bound_workspace(&dir, " @[..1s]");
    let (code, _, stderr) = ridl(&["check".as_ref(), root.as_os_str()]);
    assert_eq!(code, 0, "a written response bound exits 0:\n{stderr}");
    assert!(!stderr.contains("RIDL-112"), "no RIDL-112:\n{stderr}");
}

#[test]
fn text_deny_exits_1() {
    let dir = TempDir::new("text-deny");
    let root = member_workspace(&dir, DENY);

    let (code, _, stderr) = ridl(&["check".as_ref(), root.as_os_str()]);

    assert_eq!(code, 1, "a lint at deny exits 1:\n{stderr}");
    assert!(
        stderr.contains("error[RIDL-100]"),
        "the lint is rendered as an error:\n{stderr}"
    );
    assert!(
        !stderr.contains("warning[RIDL-100]"),
        "the lint is not rendered as a warning:\n{stderr}"
    );
}

#[test]
fn build_fails_on_deny() {
    let dir = TempDir::new("build-deny");
    let root = member_workspace(&dir, DENY);
    let out = TempDir::new("build-deny-out");

    let (code, _, stderr) = ridl(&[
        "build".as_ref(),
        "--out-dir".as_ref(),
        out.path().as_os_str(),
        "--emit".as_ref(),
        "ir-json".as_ref(),
        root.as_os_str(),
    ]);

    assert_eq!(code, 1, "a lint at deny fails the build:\n{stderr}");
    let written: Vec<PathBuf> = std::fs::read_dir(out.path())
        .expect("the out dir is readable")
        .map(|entry| entry.expect("a readable entry").path())
        .collect();
    assert!(written.is_empty(), "the build wrote: {written:?}");
}

/// `ridl diff` compiles both sides without applying levels (ADR-0024 decision
/// 8): a lint at `deny` on either side does not change its result.
#[test]
fn diff_ignores_deny() {
    let old = TempDir::new("diff-old");
    let old_root = member_workspace(&old, DENY);
    let new = TempDir::new("diff-new");
    let new_root = member_workspace(&new, DENY);

    let (code, stdout, stderr) =
        ridl(&["diff".as_ref(), old_root.as_os_str(), new_root.as_os_str()]);

    assert_eq!(
        code, 0,
        "a lint at deny does not change the diff:\nstdout:\n{stdout}\nstderr:\n{stderr}"
    );
}

/// `ridl baseline` publishes the snapshot without applying levels (ADR-0024
/// decision 8): a lint at `deny` does not block the publication.
#[test]
fn baseline_ignores_deny() {
    let dir = TempDir::new("baseline-deny");
    let root = member_workspace(&dir, DENY);
    let (code, _, stderr) = ridl(&["lock".as_ref(), root.as_os_str()]);
    assert_eq!(code, 0, "the fixture's lock is allocated: {stderr}");

    let (code, _, stderr) = ridl(&["baseline".as_ref(), root.as_os_str()]);

    assert_eq!(
        code, 0,
        "a lint at deny does not block the baseline:\n{stderr}"
    );
    let snapshot = root.join(".ridl").join("baseline").join("demo.ir.json");
    assert!(
        snapshot.is_file(),
        "the snapshot is written at {}",
        snapshot.display()
    );
}

/// `SOURCE` with one more interaction: the `signal` with no timing
/// annotation stays, and a command with a satisfiable precondition, which
/// `ridl test` samples, is declared beside it.
const SOURCE_WITH_CONTRACT: &str = "package demo\n\ntype Speed: integer [0..300]\n\n\
                                    interface Sensor {\n  signal speed: Speed\n  \
                                    command setRange(min: Speed, max: Speed) [\n    \
                                    require min < max\n  ] @[..50ms]\n}\n";

/// `ridl test` compiles the workspace without applying levels (ADR-0024
/// decision 8): a lint at `deny` does not stop the run, which exits 2 on a
/// compile error.
#[test]
fn test_ignores_deny() {
    let dir = TempDir::new("test-deny");
    dir.write(
        "ridl.toml",
        &format!("[package]\nname = \"demo\"\nversion = \"1.0.0\"\n{DENY}"),
    );
    dir.write("sensor.ridl", SOURCE_WITH_CONTRACT);
    let root = dir.path();
    // The fixture draws the denied lint: `ridl check` exits 1 over it.
    let (code, _, stderr) = ridl(&["check".as_ref(), root.as_os_str()]);
    assert_eq!(code, 1, "the fixture draws the denied lint:\n{stderr}");

    let (code, stdout, stderr) = ridl(&["test".as_ref(), root.as_os_str()]);

    assert_eq!(
        code, 0,
        "a lint at deny does not change the test run:\nstdout:\n{stdout}\nstderr:\n{stderr}"
    );
    assert!(
        stdout.contains("Sensor.setRange.require[0]"),
        "the contract is sampled:\n{stdout}"
    );
}

/// Entering at a workspace member loads its workspace (ADR-0024 decision 9,
/// as ADR-0026 amends it), so the root's `[lints]` applies to the member: the
/// root's `deny` is an exit 1 from the root and from the member alike.
#[test]
fn member_entry_applies_root_lints() {
    let dir = TempDir::new("member-entry");
    dir.write(
        "ridl.toml",
        &format!("[workspace]\nmembers = [\"sensor\"]\n{DENY}"),
    );
    dir.write(
        "sensor/ridl.toml",
        "[package]\nname = \"demo\"\nversion = \"1.0.0\"\n",
    );
    dir.write("sensor/sensor.ridl", SOURCE);
    let root = dir.path();
    let (code, _, stderr) = ridl(&["check".as_ref(), root.as_os_str()]);
    assert_eq!(code, 1, "from the root, the root's deny applies:\n{stderr}");

    let member = root.join("sensor");
    let (code, _, stderr) = ridl(&["check".as_ref(), member.as_os_str()]);

    assert_eq!(
        code, 1,
        "from the member, the root's deny applies:\n{stderr}"
    );
    assert!(
        stderr.contains("error[RIDL-100]"),
        "the lint is an error at the root's level:\n{stderr}"
    );
}

/// A two-member workspace: `a` imports `Speed` from `b`, and `b` also holds
/// a file with an error. Returns the workspace root.
fn sibling_workspace(dir: &TempDir) -> PathBuf {
    dir.write("ridl.toml", "[workspace]\nmembers = [\"a\", \"b\"]\n");
    dir.write(
        "a/ridl.toml",
        "[package]\nname = \"a\"\nversion = \"1.0.0\"\n",
    );
    dir.write(
        "a/a.typl",
        "package a\nimport b.Speed\nstruct Cabin { primary: Speed }\n",
    );
    dir.write(
        "b/ridl.toml",
        "[package]\nname = \"b\"\nversion = \"1.0.0\"\n",
    );
    dir.write("b/speed.typl", "package b\ntype Speed: integer [0..300]\n");
    dir.write(
        "b/broken.typl",
        "package b\nstruct Broken { field: Missing }\n",
    );
    dir.path().to_path_buf()
}

/// Checking a member reports only the diagnostics of files under the member:
/// the error in member `b` is not shown when checking `a`, and the exit code
/// is 0. From the root, the same error is shown and the exit code is 1.
#[test]
fn member_entry_reports_only_the_member() {
    let dir = TempDir::new("member-scope");
    let root = sibling_workspace(&dir);

    let (code, _, stderr) = ridl(&["check".as_ref(), root.as_os_str()]);
    assert_eq!(code, 1, "from the root, b's error is reported:\n{stderr}");
    assert!(stderr.contains("broken.typl"), "{stderr}");

    let (code, _, stderr) = ridl(&["check".as_ref(), root.join("a").as_os_str()]);
    assert_eq!(code, 0, "from a, b's error is not reported:\n{stderr}");
    assert!(!stderr.contains("broken.typl"), "{stderr}");
}

/// A build entered at a member writes the whole workspace, so an error in
/// another member still blocks every artifact. The build says why and exits
/// 1, without showing the other member's diagnostics.
#[test]
fn member_build_writes_nothing_when_another_member_has_an_error() {
    let dir = TempDir::new("member-build");
    let root = sibling_workspace(&dir);
    let out = TempDir::new("member-build-out");

    let (code, _, stderr) = ridl(&[
        "build".as_ref(),
        "--out-dir".as_ref(),
        out.path().as_os_str(),
        "--emit".as_ref(),
        "ir-json".as_ref(),
        root.join("a").as_os_str(),
    ]);

    assert_eq!(code, 1, "{stderr}");
    assert!(
        stderr.contains("another member of the workspace has an error"),
        "{stderr}"
    );
    assert!(!stderr.contains("broken.typl"), "{stderr}");
    let written: Vec<PathBuf> = std::fs::read_dir(out.path())
        .expect("the out dir is readable")
        .map(|entry| entry.expect("a readable entry").path())
        .collect();
    assert!(written.is_empty(), "the build wrote: {written:?}");
}

/// A build entered at a member, while another member holds an RSDL-7xx
/// error, writes the packages and the system without the blocked deployment
/// (rsdl reference §13). The build exits 1 and says that another member has
/// an error, without showing it.
#[test]
fn member_build_exits_1_when_another_member_leaves_out_a_deployment() {
    let dir = TempDir::new("member-build-rsdl");
    dir.write("ridl.toml", "[workspace]\nmembers = [\"a\", \"demo\"]\n");
    dir.write(
        "a/ridl.toml",
        "[package]\nname = \"a\"\nversion = \"1.0.0\"\n",
    );
    dir.write("a/a.typl", "package a\ntype Level: integer [0..3]\n");
    dir.write(
        "demo/ridl.toml",
        "[package]\nname = \"veh.demo\"\nversion = \"1.0.0\"\n",
    );
    dir.write(
        "demo/lane.ridl",
        "package veh.demo\n\ntype Flag: boolean\n\n\
         interface LaneAssist {\n  signal active: Flag @[100ms..1s]\n}\n\n\
         service veh.demo.lane : LaneAssist\n",
    );
    // `Panel` is not placed in `Bad`: RSDL-701 blocks that deployment only.
    dir.write(
        "demo/topology.rsdl",
        "package veh.demo\n\n\
         component Lane { offers veh.demo.lane }\n\
         component Panel { requires LaneAssist }\n\
         system Vehicle { Lane, Panel }\n\
         deployment Good for Vehicle { machine A { Lane, Panel } }\n\
         deployment Bad for Vehicle { machine A { Lane } }\n",
    );
    let out = TempDir::new("member-build-rsdl-out");

    let (code, _, stderr) = ridl(&[
        "build".as_ref(),
        "--out-dir".as_ref(),
        out.path().as_os_str(),
        "--emit".as_ref(),
        "ir-json".as_ref(),
        dir.path().join("a").as_os_str(),
    ]);

    assert_eq!(code, 1, "{stderr}");
    assert!(
        stderr.contains("another member of the workspace has an error"),
        "{stderr}"
    );
    assert!(!stderr.contains("RSDL-701"), "{stderr}");
    assert!(
        out.path().join("a.ir.json").is_file(),
        "the packages are written"
    );
    let json = std::fs::read_to_string(out.path().join("veh.demo.Vehicle.system.json"))
        .expect("the system is written");
    assert!(json.contains("Good") && !json.contains("\"Bad\""), "{json}");
}

/// A member entry resolves an import of a sibling member, from a relative
/// entry inside the member as well (`ridl check .` from `a`).
#[test]
fn member_entry_resolves_a_sibling_import() {
    let dir = TempDir::new("member-sibling");
    let root = sibling_workspace(&dir);
    std::fs::remove_file(root.join("b/broken.typl")).expect("remove the broken file");

    let (code, _, stderr) = ridl(&["check".as_ref(), root.join("a").as_os_str()]);
    assert_eq!(code, 0, "b.Speed resolves from a:\n{stderr}");

    let (code, _, stderr) = ridl_in(Some(&root.join("a")), &["check".as_ref(), ".".as_ref()]);
    assert_eq!(code, 0, "b.Speed resolves from `.` inside a:\n{stderr}");
}

#[test]
fn allow_is_absent_in_text_and_json() {
    let dir = TempDir::new("allow");
    let root = member_workspace(&dir, ALLOW);

    let (code, stdout, stderr) = ridl(&["check".as_ref(), root.as_os_str()]);
    assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}");
    assert!(
        !stderr.contains("RIDL-100"),
        "an allowed lint is absent from the text report:\n{stderr}"
    );

    let (code, stdout, stderr) = ridl(&[
        "check".as_ref(),
        "--format".as_ref(),
        "json".as_ref(),
        root.as_os_str(),
    ]);
    assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}");
    assert!(
        !stdout.contains("RIDL-100"),
        "an allowed lint is absent from the JSON report:\n{stdout}"
    );
}

/// The SARIF 2.1.0 schema, downloaded from
/// `https://json.schemastore.org/sarif-2.1.0.json`. Every reference in it is
/// internal, so the validator needs no network.
const SARIF_SCHEMA: &str = include_str!("fixtures/sarif-2.1.0.json");

/// Runs `ridl check --format sarif .` from `root` and returns the exit code
/// and the parsed log, after validating the log against the vendored schema.
fn sarif_check(root: &Path) -> (i32, serde_json::Value) {
    sarif_check_in(root, ".".as_ref())
}

/// Runs `ridl check --format sarif <entry>` from `current_dir` and returns
/// the exit code and the parsed log, after validating the log against the
/// vendored schema.
fn sarif_check_in(current_dir: &Path, entry: &OsStr) -> (i32, serde_json::Value) {
    let (code, stdout, stderr) = ridl_in(
        Some(current_dir),
        &[
            "check".as_ref(),
            "--format".as_ref(),
            "sarif".as_ref(),
            entry,
        ],
    );
    let log: serde_json::Value = serde_json::from_str(&stdout).unwrap_or_else(|err| {
        panic!("stdout is JSON ({err}):\nstdout:\n{stdout}\nstderr:\n{stderr}")
    });
    let schema: serde_json::Value =
        serde_json::from_str(SARIF_SCHEMA).expect("the vendored schema is JSON");
    let validator = jsonschema::validator_for(&schema).expect("the vendored schema compiles");
    let errors: Vec<String> = validator
        .iter_errors(&log)
        .map(|err| format!("{} at {}", err, err.instance_path()))
        .collect();
    assert!(
        errors.is_empty(),
        "the log validates against the SARIF 2.1.0 schema:\n{}\nlog:\n{stdout}",
        errors.join("\n")
    );
    (code, log)
}

/// The results of the one run whose `ruleId` is `code`.
fn sarif_results<'a>(log: &'a serde_json::Value, code: &str) -> Vec<&'a serde_json::Value> {
    log["runs"][0]["results"]
        .as_array()
        .expect("results is an array")
        .iter()
        .filter(|result| result["ruleId"] == code)
        .collect()
}

#[test]
fn sarif_validates_and_denies() {
    let dir = TempDir::new("sarif-deny");
    let root = member_workspace(&dir, DENY);
    let (code, log) = sarif_check(&root);
    assert_eq!(code, 1, "a lint at deny exits 1:\n{log}");
    let ridl_100 = sarif_results(&log, "RIDL-100");
    assert_eq!(ridl_100.len(), 1, "{log}");
    assert_eq!(ridl_100[0]["level"], "error", "{}", ridl_100[0]);
    assert_eq!(
        ridl_100[0]["locations"][0]["physicalLocation"]["artifactLocation"]["uri"],
        "sensor/sensor.ridl",
        "{}",
        ridl_100[0]
    );

    let dir = TempDir::new("sarif-allow");
    let root = member_workspace(&dir, ALLOW);
    let (code, log) = sarif_check(&root);
    assert_eq!(code, 0, "{log}");
    assert!(
        sarif_results(&log, "RIDL-100").is_empty(),
        "an allowed lint is absent from the SARIF log:\n{log}"
    );
}

/// A second file of the `demo` package, in its `sub` directory, with one
/// untimed signal: it draws one RIDL-100 and nothing else.
const SUB_SOURCE: &str = "package demo.sub\n\ntype Level: integer [0..10]\n\ninterface Gauge {\n  \
                          signal level: Level\n}\n";

/// A package at `ws/` with `ws/sensor.ridl` and `ws/sub/<sub_file>`, each
/// drawing one RIDL-100. The fixture for the artifact URI tests, which run
/// the binary from `dir` so that `ws/` is one level below the working
/// directory.
fn two_level_package(dir: &TempDir, sub_file: &str) {
    dir.write(
        "ws/ridl.toml",
        "[package]\nname = \"demo\"\nversion = \"1.0.0\"\n",
    );
    dir.write("ws/sensor.ridl", SOURCE);
    dir.write(&format!("ws/sub/{sub_file}"), SUB_SOURCE);
}

/// The `file://` URI of an absolute path, percent-encoding every byte outside
/// the RFC 3986 unreserved set and `/`, as the binary is expected to write
/// the `%SRCROOT%` base.
fn file_uri(path: &Path) -> String {
    let mut uri = String::from("file://");
    for byte in path.to_str().expect("the temp dir is UTF-8").bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' | b'/' => {
                uri.push(byte as char);
            }
            _ => uri.push_str(&format!("%{byte:02X}")),
        }
    }
    uri
}

/// The `(uri, uriBaseId)` pair of each RIDL-100 result's primary location,
/// sorted by URI.
fn ridl_100_locations(log: &serde_json::Value) -> Vec<(String, Option<String>)> {
    let mut locations: Vec<(String, Option<String>)> = sarif_results(log, "RIDL-100")
        .iter()
        .map(|result| {
            let location = &result["locations"][0]["physicalLocation"]["artifactLocation"];
            (
                location["uri"]
                    .as_str()
                    .expect("uri is a string")
                    .to_string(),
                location["uriBaseId"].as_str().map(str::to_string),
            )
        })
        .collect();
    locations.sort();
    locations
}

/// Asserts that `log` names the working directory `cwd` as `%SRCROOT%`, as a
/// `file://` URI that ends with `/`, and that both RIDL-100 results carry
/// `sub_uri` and `ws/sensor.ridl` relative to that base.
fn assert_cwd_relative_uris(log: &serde_json::Value, cwd: &Path, sub_uri: &str) {
    let cwd = cwd.canonicalize().expect("the temp dir resolves");
    let expected_base = format!("{}/", file_uri(&cwd));
    assert_eq!(
        log["runs"][0]["originalUriBaseIds"]["%SRCROOT%"]["uri"], expected_base,
        "{log}"
    );
    let base = Some("%SRCROOT%".to_string());
    assert_eq!(
        ridl_100_locations(log),
        vec![
            ("ws/sensor.ridl".to_string(), base.clone()),
            (sub_uri.to_string(), base),
        ],
        "{log}"
    );
}

/// An entry at a file: the URIs are relative to the working directory, not to
/// the file's directory.
#[test]
fn sarif_uris_are_cwd_relative_from_a_file_entry() {
    let dir = TempDir::new("sarif-uri-file");
    two_level_package(&dir, "gauge.ridl");
    let (code, log) = sarif_check_in(dir.path(), "ws/sensor.ridl".as_ref());
    assert_eq!(code, 0, "{log}");
    assert_cwd_relative_uris(&log, dir.path(), "ws/sub/gauge.ridl");
}

/// An entry at a subdirectory of the package: the file above the entry and
/// the file inside it share one base, the working directory.
#[test]
fn sarif_uris_are_cwd_relative_from_a_subdirectory_entry() {
    let dir = TempDir::new("sarif-uri-subdir");
    two_level_package(&dir, "gauge.ridl");
    let (code, log) = sarif_check_in(dir.path(), "ws/sub".as_ref());
    assert_eq!(code, 0, "{log}");
    assert_cwd_relative_uris(&log, dir.path(), "ws/sub/gauge.ridl");
}

/// A file name with a space and a `#` is percent-encoded, so the URI is a
/// valid URI reference.
#[test]
fn sarif_uris_percent_encode_a_space_and_a_hash() {
    let dir = TempDir::new("sarif-uri-encode");
    two_level_package(&dir, "b c#1.ridl");
    let (code, log) = sarif_check_in(dir.path(), "ws".as_ref());
    assert_eq!(code, 0, "{log}");
    assert_cwd_relative_uris(&log, dir.path(), "ws/sub/b%20c%231.ridl");
}

/// The rendered note line for a file whose line numbers have one digit
/// (docs/book/lints.md).
const NOTE_LINE: &str = "  = lint: `missing-timing` (set its level in `[lints]` in ridl.toml)";

#[test]
fn text_shows_lint_note() {
    let dir = TempDir::new("note");
    let root = member_workspace(&dir, "");

    let (code, _, stderr) = ridl(&["check".as_ref(), root.as_os_str()]);

    assert_eq!(code, 0, "{stderr}");
    assert!(
        stderr.lines().any(|line| line == NOTE_LINE),
        "the text report holds the line {NOTE_LINE:?}:\n{stderr}"
    );
}

// The baseline fixtures mirror `baseline_desk.rs`: a standalone package,
// locked, published as a baseline, then edited so that an ordinal moves.

/// The published shape: three interactions at ordinals 1, 2, 3.
const BASE: &str = "package veh.cluster
type Speed: km/h [0.0..250.0 step 0.5]
type DoorState: integer [0..1]
interface VehicleStatus {
  signal currentSpeed: Speed @10ms
  event doorOpened: DoorState @[100ms..1s]
  event doorClosed: DoorState @[100ms..1s]
}
";

/// `doorClosed` moved ahead of `doorOpened`: the ordinals of both shift.
const REORDERED: &str = "package veh.cluster
type Speed: km/h [0.0..250.0 step 0.5]
type DoorState: integer [0..1]
interface VehicleStatus {
  signal currentSpeed: Speed @10ms
  event doorClosed: DoorState @[100ms..1s]
  event doorOpened: DoorState @[100ms..1s]
}
";

/// `BASE` with no timing on `currentSpeed`, which draws RIDL-100.
const BASE_UNTIMED: &str = "package veh.cluster
type Speed: km/h [0.0..250.0 step 0.5]
type DoorState: integer [0..1]
interface VehicleStatus {
  signal currentSpeed: Speed
  event doorOpened: DoorState @[100ms..1s]
  event doorClosed: DoorState @[100ms..1s]
}
";

/// `REORDERED` with no timing on `currentSpeed`.
const REORDERED_UNTIMED: &str = "package veh.cluster
type Speed: km/h [0.0..250.0 step 0.5]
type DoorState: integer [0..1]
interface VehicleStatus {
  signal currentSpeed: Speed
  event doorClosed: DoorState @[100ms..1s]
  event doorOpened: DoorState @[100ms..1s]
}
";

/// A standalone package at the root of `dir`, with `lints` appended to its
/// manifest, holding `source`, locked and published as a baseline. Returns
/// the workspace root and the baseline directory.
fn published_package(dir: &TempDir, lints: &str, source: &str) -> (PathBuf, PathBuf) {
    dir.write(
        "ridl.toml",
        &format!("[package]\nname = \"veh.cluster\"\nversion = \"1.0.0\"\n{lints}"),
    );
    dir.write("cluster.ridl", source);
    let root = dir.path().to_path_buf();
    let (code, _, stderr) = ridl(&["lock".as_ref(), root.as_os_str()]);
    assert_eq!(code, 0, "the fixture's lock is allocated: {stderr}");
    let (code, _, stderr) = ridl(&["baseline".as_ref(), root.as_os_str()]);
    assert_eq!(code, 0, "the baseline is written: {stderr}");
    (root.clone(), root.join(".ridl").join("baseline"))
}

const ALLOW_ORDINAL: &str = "\n[lints]\nordinal-changed = \"allow\"\n";
const DENY_ORDINAL: &str = "\n[lints]\nordinal-changed = \"deny\"\n";

/// `ordinal-changed = "deny"` reports RIDL-407 as an error, which exits 1
/// (cli-reference, "The baseline desk check").
#[test]
fn ordinal_changed_deny_fails_baseline() {
    let dir = TempDir::new("ordinal-deny");
    let (root, baseline) = published_package(&dir, DENY_ORDINAL, BASE);
    dir.write("cluster.ridl", REORDERED);

    let (code, _, stderr) = ridl(&[
        "check".as_ref(),
        "--baseline".as_ref(),
        baseline.as_os_str(),
        root.as_os_str(),
    ]);

    assert_eq!(
        code, 1,
        "the denied desk warning moves the exit code:\n{stderr}"
    );
    assert!(
        stderr.contains("error[RIDL-407]"),
        "`ordinal-changed = \"deny\"` reports the desk warning as an error:\n{stderr}"
    );
}

/// The entry names one file of the package, and the moved interaction is in
/// another. The compile covers the whole package, so the declaration index
/// must too: the RIDL-407 points at `cluster.ridl`, and the package's
/// `[lints]` scope reaches it. With a detached span the registry default
/// would apply instead, and `deny` would not change the exit code.
#[test]
fn ordinal_changed_deny_applies_through_a_file_entry() {
    let dir = TempDir::new("ordinal-deny-file-entry");
    let other = dir.write(
        "other.ridl",
        "package veh.cluster\ntype Other: integer [0..1]\n",
    );
    let (_, baseline) = published_package(&dir, DENY_ORDINAL, BASE);
    dir.write("cluster.ridl", REORDERED);

    let (code, _, stderr) = ridl(&[
        "check".as_ref(),
        "--baseline".as_ref(),
        baseline.as_os_str(),
        other.as_os_str(),
    ]);

    assert_eq!(
        code, 1,
        "the denied desk warning moves the exit code:\n{stderr}"
    );
    assert!(
        stderr.contains("error[RIDL-407]"),
        "the package's `[lints]` scope reaches the desk warning:\n{stderr}"
    );
    assert!(
        stderr.contains("cluster.ridl:6:3"),
        "the desk warning points at the moved declaration:\n{stderr}"
    );
}

/// RIDL-407 is raised by the CLI after `ridlc` returns, with its span
/// interned into the source map at that point. The levels are applied once
/// more over the whole run, and the scope lookup finds the interned path.
#[test]
fn ordinal_changed_allow_silences_baseline() {
    let dir = TempDir::new("ordinal-allow");
    let (root, baseline) = published_package(&dir, ALLOW_ORDINAL, BASE);
    dir.write("cluster.ridl", REORDERED);

    let (code, _, stderr) = ridl(&[
        "check".as_ref(),
        "--baseline".as_ref(),
        baseline.as_os_str(),
        root.as_os_str(),
    ]);

    assert_eq!(code, 0, "{stderr}");
    assert!(
        !stderr.contains("RIDL-407"),
        "`ordinal-changed = \"allow\"` silences the desk warning:\n{stderr}"
    );

    // The control: without the `[lints]` table the warning is present.
    let control = TempDir::new("ordinal-default");
    let (root, baseline) = published_package(&control, "", BASE);
    control.write("cluster.ridl", REORDERED);

    let (code, _, stderr) = ridl(&[
        "check".as_ref(),
        "--baseline".as_ref(),
        baseline.as_os_str(),
        root.as_os_str(),
    ]);

    assert_eq!(code, 0, "{stderr}");
    assert!(
        stderr.contains("warning[RIDL-407]"),
        "the default level keeps the desk warning:\n{stderr}"
    );
}

/// The same, with the workspace named by a relative entry (`.`) from its own
/// directory: the scope directory and the path the CLI interns for RIDL-407
/// are both derived from the entry as given, so they share one form.
#[test]
fn ordinal_changed_allow_silences_baseline_from_a_relative_entry() {
    let dir = TempDir::new("ordinal-allow-relative");
    let (root, _) = published_package(&dir, ALLOW_ORDINAL, BASE);
    dir.write("cluster.ridl", REORDERED);

    let (code, _, stderr) = ridl_in(
        Some(&root),
        &[
            "check".as_ref(),
            "--baseline".as_ref(),
            ".ridl/baseline".as_ref(),
            ".".as_ref(),
        ],
    );

    assert_eq!(code, 0, "{stderr}");
    assert!(
        !stderr.contains("RIDL-407"),
        "`ordinal-changed = \"allow\"` silences the desk warning from a relative entry:\n{stderr}"
    );
}

/// A lint at `deny` is an Error once the levels are applied, but it is not a
/// compile error: the desk check still runs, and the run reports both the
/// denied lint and the RIDL-407 (Review Focus 1).
#[test]
fn deny_lint_does_not_skip_desk_check() {
    let dir = TempDir::new("deny-desk");
    let (root, baseline) = published_package(&dir, DENY, BASE_UNTIMED);
    dir.write("cluster.ridl", REORDERED_UNTIMED);

    let (code, _, stderr) = ridl(&[
        "check".as_ref(),
        "--baseline".as_ref(),
        baseline.as_os_str(),
        root.as_os_str(),
    ]);

    assert_eq!(code, 1, "the denied lint moves the exit code:\n{stderr}");
    assert!(
        stderr.contains("error[RIDL-100]"),
        "the denied lint is reported as an error:\n{stderr}"
    );
    assert!(
        stderr.contains("warning[RIDL-407]"),
        "the desk check still runs beside the denied lint:\n{stderr}"
    );
}

#[test]
fn inconsistent_unit_levels_reach_compiler_and_cli_reports() {
    let source = "package a\ntype Speed: km/h [0.0..250.0 step 0.5]\ntype SpeedMs: m/s [0.0..100.0 step 0.5]\nstruct First { speed: Speed }\nstruct Second { speed: Speed }\nstruct Third { speed: SpeedMs }\n";
    for (level, expected_count, expected_severity, expected_exit) in [
        ("info", 1, "info", 0),
        ("allow", 0, "info", 0),
        ("deny", 1, "error", 1),
    ] {
        let dir = TempDir::new("unit-levels");
        dir.write("ridl.toml", &format!("[package]\nname = \"a\"\nversion = \"1.0.0\"\n[lints]\ninconsistent-unit = \"{level}\"\n"));
        dir.write("source.ridl", source);
        // Compilation preserves the catalogue severity for every level.
        let compiled =
            ridlc::compile_workspace(&mut ridl_core::RidlDatabase::default(), dir.path()).unwrap();
        // Preserve the incoming allowance for undocumented fixture items.
        let compiled_diagnostics = compiled
            .diagnostics
            .iter()
            .filter(|diagnostic| {
                diagnostic.code != ridl_core::lint::lint_by_name("missing-docs").unwrap().code
            })
            .collect::<Vec<_>>();
        assert_eq!(compiled_diagnostics.len(), 1, "{:?}", compiled_diagnostics);
        assert_eq!(compiled_diagnostics[0].code.as_str(), "TYPL-222");
        assert_eq!(
            compiled_diagnostics[0].severity,
            ridl_core::diag::Severity::Info
        );

        // The shared command driver applies levels; the binary must agree.
        let run = ridlc::run_check(dir.path(), ridl_core::Frozen::Yes).unwrap();
        // Preserve the incoming allowance for undocumented fixture items.
        let run_diagnostics = run
            .diagnostics
            .iter()
            .filter(|diagnostic| {
                diagnostic.code != ridl_core::lint::lint_by_name("missing-docs").unwrap().code
            })
            .collect::<Vec<_>>();
        assert_eq!(
            run_diagnostics.len(),
            expected_count,
            "{level}: {:?}",
            run_diagnostics
        );
        assert_eq!(run.has_error(), expected_exit == 1);
        if let Some(diagnostic) = run_diagnostics.first() {
            assert_eq!(diagnostic.code.as_str(), "TYPL-222");
            assert_eq!(
                diagnostic.severity,
                if level == "deny" {
                    ridl_core::diag::Severity::Error
                } else {
                    ridl_core::diag::Severity::Info
                }
            );
        }
        let (exit, stdout, stderr) = ridl(&[
            "check".as_ref(),
            "--format".as_ref(),
            "json".as_ref(),
            dir.path().as_os_str(),
        ]);
        assert_eq!(exit, expected_exit, "{level}: {stderr}");
        let diagnostics: serde_json::Value = serde_json::from_str(&stdout).unwrap();
        let diagnostics = diagnostics
            .as_array()
            .unwrap()
            .iter()
            .filter(|diagnostic| diagnostic["lint"] != "missing-docs")
            .collect::<Vec<_>>();
        assert_eq!(
            diagnostics.len(),
            expected_count,
            "{level}: {diagnostics:?}"
        );
        if let Some(diagnostic) = diagnostics.first() {
            assert_eq!(diagnostic["code"], "TYPL-222");
            assert_eq!(diagnostic["lint"], "inconsistent-unit");
            assert_eq!(diagnostic["severity"], expected_severity);
            assert_eq!(
                diagnostic["message"],
                "`speed` uses `m/s` here; elsewhere `speed` uses `km/h`"
            );
        }
    }
}

/// A type documented with a `/** */` block, which draws TYPL-410
/// (`doc-comment-style`, `allow` by default) and nothing else.
const BLOCK_DOC_SOURCE: &str = "package demo\n\n/** A speed. */\ntype Speed: integer [0..300]\n";

/// A workspace with one member whose only file is [`BLOCK_DOC_SOURCE`] and
/// whose manifest ends with `lints`. Returns the workspace root.
fn block_doc_workspace(dir: &TempDir, lints: &str) -> PathBuf {
    dir.write("ridl.toml", "[workspace]\nmembers = [\"speed\"]\n");
    dir.write(
        "speed/ridl.toml",
        &format!("[package]\nname = \"demo\"\nversion = \"1.0.0\"\n{lints}"),
    );
    dir.write("speed/speed.typl", BLOCK_DOC_SOURCE);
    dir.path().to_path_buf()
}

#[test]
fn doc_comment_style_is_silent_by_default() {
    let dir = TempDir::new("doc-style-default");
    let root = block_doc_workspace(&dir, "");

    let (code, stdout, stderr) = ridl(&["check".as_ref(), root.as_os_str()]);

    assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}");
    assert!(
        !stderr.contains("TYPL-410") && !stdout.contains("TYPL-410"),
        "a lint that is allowed by default is not reported:\n{stderr}"
    );
}

#[test]
fn doc_comment_style_at_warn_is_reported() {
    let dir = TempDir::new("doc-style-warn");
    let root = block_doc_workspace(&dir, "\n[lints]\ndoc-comment-style = \"warn\"\n");

    let (code, stdout, stderr) = ridl(&["check".as_ref(), root.as_os_str()]);

    assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}");
    assert!(
        stderr.contains("warning[TYPL-410]"),
        "the lint at warn is rendered as a warning:\n{stderr}"
    );
}

#[test]
fn doc_comment_style_at_deny_exits_1() {
    let dir = TempDir::new("doc-style-deny");
    let root = block_doc_workspace(&dir, "\n[lints]\ndoc-comment-style = \"deny\"\n");

    let (code, stdout, stderr) = ridl(&["check".as_ref(), root.as_os_str()]);

    assert_eq!(code, 1, "stdout:\n{stdout}\nstderr:\n{stderr}");
    assert!(
        stderr.contains("error[TYPL-410]"),
        "the lint at deny is rendered as an error:\n{stderr}"
    );
}

/// The commands that apply no `[lints]` levels (ADR-0024 decision 8) still
/// leave out a lint that is `allow` by default: `ridl baseline` and
/// `ridl lock` render the warnings of the compile.
#[test]
fn doc_comment_style_is_silent_in_baseline_and_lock() {
    let dir = TempDir::new("doc-style-baseline");
    let root = block_doc_workspace(&dir, "");

    let (code, stdout, stderr) = ridl(&["lock".as_ref(), root.as_os_str()]);
    assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}");
    assert!(
        !stderr.contains("TYPL-410"),
        "`ridl lock` does not report an allow-by-default lint:\n{stderr}"
    );

    let (code, stdout, stderr) = ridl(&["baseline".as_ref(), root.as_os_str()]);
    assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}");
    assert!(
        !stderr.contains("TYPL-410"),
        "`ridl baseline` does not report an allow-by-default lint:\n{stderr}"
    );
}

/// `ridl diff` renders the diagnostics of a side that does not compile, with
/// no `[lints]` levels; an allow-by-default lint is left out of them.
#[test]
fn doc_comment_style_is_silent_in_a_diff_compile_error() {
    let dir = TempDir::new("doc-style-diff");
    let old = dir.write("old/speed.typl", BLOCK_DOC_SOURCE);
    let new = dir.write(
        "new/speed.typl",
        &format!("{BLOCK_DOC_SOURCE}type Broken: Missing\n"),
    );

    let (code, stdout, stderr) = ridl(&["diff".as_ref(), old.as_os_str(), new.as_os_str()]);

    assert_eq!(code, 2, "stdout:\n{stdout}\nstderr:\n{stderr}");
    assert!(
        stderr.contains("error"),
        "the new side does not compile:\n{stderr}"
    );
    assert!(
        !stderr.contains("TYPL-410"),
        "`ridl diff` does not report an allow-by-default lint:\n{stderr}"
    );
}

/// A two-member workspace for `missing-docs`: member `a` is documented and
/// imports `Speed` from member `b`, whose declarations have no docs. Returns
/// the workspace root.
fn undocumented_dependency_workspace(dir: &TempDir) -> PathBuf {
    dir.write("ridl.toml", "[workspace]\nmembers = [\"a\", \"b\"]\n");
    dir.write(
        "a/ridl.toml",
        "[package]\nname = \"a\"\nversion = \"1.0.0\"\n",
    );
    dir.write(
        "a/a.typl",
        "package a\nimport b.Speed\n/// The cabin.\nstruct Cabin {\n  /// The primary speed.\n  \
         primary: Speed\n}\n",
    );
    dir.write(
        "b/ridl.toml",
        "[package]\nname = \"b\"\nversion = \"1.0.0\"\n",
    );
    dir.write(
        "b/speed.typl",
        "package b\ntype Speed: integer [0..300]\nstruct Pair {\n  left: Speed\n}\n",
    );
    dir.path().to_path_buf()
}

/// TYPL-406 obeys ADR-0024 decision 10: checking member `a` does not report
/// the undocumented items of member `b`, which is outside the entry's
/// directory tree. From the root, the same items are reported.
#[test]
fn missing_docs_skips_dependencies() {
    let dir = TempDir::new("missing-docs-deps");
    let root = undocumented_dependency_workspace(&dir);

    let (code, stdout, stderr) = ridl(&["check".as_ref(), root.join("a").as_os_str()]);
    assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}");
    assert!(
        !stderr.contains("TYPL-406") && !stdout.contains("TYPL-406"),
        "the dependency's undocumented items are not reported:\n{stderr}"
    );

    let (code, stdout, stderr) = ridl(&["check".as_ref(), root.as_os_str()]);
    assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}");
    assert_eq!(
        stderr.matches("warning[TYPL-406]").count(),
        3,
        "from the root, `Speed`, `Pair` and `left` are reported:\n{stderr}"
    );
}

#[test]
fn missing_docs_at_allow_is_silent() {
    let dir = TempDir::new("missing-docs-allow");
    dir.write("ridl.toml", "[workspace]\nmembers = [\"b\"]\n");
    dir.write(
        "b/ridl.toml",
        "[package]\nname = \"b\"\nversion = \"1.0.0\"\n\n[lints]\nmissing-docs = \"allow\"\n",
    );
    dir.write(
        "b/speed.typl",
        "package b\ntype Speed: integer [0..300]\nstruct Pair {\n  left: Speed\n}\n",
    );

    let (code, stdout, stderr) = ridl(&["check".as_ref(), dir.path().as_os_str()]);

    assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}");
    assert!(
        !stderr.contains("TYPL-406") && !stdout.contains("TYPL-406"),
        "a lint at allow is not reported:\n{stderr}"
    );
}