ridl-core 0.3.0

The RIDL family compiler core: the incremental database, diagnostics, and the package and workspace model.
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
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
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
//! Filesystem discovery: from an entry path to a loaded [`Workspace`]
//! (docs/ROADMAP.md epic E1.3, ADR-0002 §1, §4–5).
//!
//! This is the only module in the crate that touches the filesystem, and it
//! sits behind the default-on `fs` feature (ADR-0007 decision 5) so the crate
//! still builds for `wasm32-unknown-unknown` with `--no-default-features`.
//!
//! [`load_workspace`] walks from an entry path — a source file, a package
//! directory, or a workspace root — reads the `ridl.toml` manifests, loads
//! every source file (`.typl` and `.ridl` alike — a package may mix both, E2
//! task 2) into [`InputFile`] inputs, and enforces the package↔directory law
//! (typl reference §3.1): every file in a package directory must declare that
//! directory's package name (TYPL-002), and more than one `package`
//! declaration in a file is TYPL-001. A bare `.typl` or `.ridl` file with no
//! manifest anywhere up the tree loads in **single-file mode**: one synthetic
//! package named from the file's declared package, exempt from TYPL-002 (the
//! task 20 CLI contract). Every package directory — the bare file's directory
//! included — is also read for an `interfaces.lock`, which rides on the
//! [`Package`] as its [`PackageLock`]; a malformed one is RIDL-410 on the
//! file's own line (lock design §2, §8).
//!
//! Problems in loaded content — manifest diagnostics, the law violations, a
//! nested workspace (MANI-004), a broken member (MANI-008), a file that is
//! not valid UTF-8 — are accumulated [`Diagnostic`]s, never an error return
//! (ADR-0004 §5). `std::io::Error` is reserved for real filesystem failures.

use std::collections::BTreeMap;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};

use ridl_syntax::ast::{AstNode as _, SourceFile};
use rowan::{TextRange, TextSize};

use crate::db::{InputFile, RidlDatabase, parse_file};
use crate::diag::{DiagCode, Diagnostic, FileId, Severity, SourceMap, Span};
use crate::interface_lock;
use crate::manifest::{Manifest, ManifestKind, parse_manifest};
use crate::package::{Package, PackageLock, PackageOrigin, Workspace, package_declarations};

/// The result of [`load_workspace`]: the salsa [`Workspace`] input, the
/// diagnostics the load accumulated, and the interned path+text table the
/// diagnostics' [`Span`]s point into (what the caller hands to
/// [`render`](crate::diag::render())).
pub struct LoadedWorkspace {
    pub workspace: Workspace,
    pub diagnostics: Vec<Diagnostic>,
    pub sources: SourceMap,
}

/// Loads the workspace reachable from `entry` into `db`.
///
/// `entry` may be:
///
/// - a `.typl` or `.ridl` file — the nearest `ridl.toml` up the tree is the
///   root; with no manifest anywhere up the tree the file loads in
///   single-file mode;
/// - a package directory or workspace root — the nearest `ridl.toml` at or
///   above the directory is the root; a `[package]` manifest loads that
///   package's directory tree, a `[workspace]` manifest loads every member.
///
/// `[imports]` maps stay scoped per ADR-0002 §5: each [`Package`] carries the
/// `[imports]` of the manifest governing its directory tree (step 2), and
/// [`Workspace::imports`] holds only the workspace root's `[imports]` (step
/// 3, the shared default). Nothing is merged — a member's pin never leaks to
/// a sibling member; the task 9 resolver walks the order itself. In a
/// standalone package load the manifest's `[imports]` ride on its packages
/// and [`Workspace::imports`] is empty.
pub fn load_workspace(db: &mut RidlDatabase, entry: &Path) -> io::Result<LoadedWorkspace> {
    let mut loader = Loader::default();

    if entry.is_file() {
        match entry.parent().and_then(find_manifest_root) {
            Some(root) => loader.load_root(db, &root)?,
            None => loader.load_single_file(db, entry)?,
        }
    } else if entry.is_dir() {
        match find_manifest_root(entry) {
            Some(root) => loader.load_root(db, &root)?,
            None => {
                return Err(io::Error::new(
                    io::ErrorKind::NotFound,
                    format!("no `ridl.toml` found at or above `{}`", entry.display()),
                ));
            }
        }
    } else {
        return Err(io::Error::new(
            io::ErrorKind::NotFound,
            format!("`{}` does not exist", entry.display()),
        ));
    }

    let workspace = Workspace::new(&*db, loader.packages, loader.workspace_imports);
    Ok(LoadedWorkspace {
        workspace,
        diagnostics: loader.diagnostics,
        sources: loader.sources,
    })
}

/// The nearest directory at or above `dir` that contains a `ridl.toml` — the
/// root [`load_workspace`] loads from. The language server calls it to tell a
/// directory with no manifest above it from a load that failed.
pub fn find_manifest_root(dir: &Path) -> Option<PathBuf> {
    dir.ancestors()
        .find(|candidate| candidate.join("ridl.toml").is_file())
        .map(Path::to_path_buf)
}

/// One loaded file plus its `package` declarations (dotted name, source
/// range), as [`Loader::load_file`] returns them.
type LoadedFile = (InputFile, Vec<(String, TextRange)>);

/// The accumulating state of one [`load_workspace`] run.
#[derive(Default)]
struct Loader {
    sources: SourceMap,
    diagnostics: Vec<Diagnostic>,
    packages: Vec<Package>,
    /// The workspace root's own `[imports]` (ADR-0002 §5 step 3). Stays empty
    /// in a standalone package load and in single-file mode.
    workspace_imports: BTreeMap<String, String>,
    /// The workspace root's `[defaults].timing` (ridl §9.1). A member's own
    /// `[defaults].timing` shadows it; when the member has none, this rides on
    /// the member's packages. Stays `None` in a standalone package load and in
    /// single-file mode (E2 task 9).
    workspace_default_timing: Option<String>,
}

impl Loader {
    /// Loads from a directory known to contain a `ridl.toml`, in whichever
    /// mode its manifest declares.
    fn load_root(&mut self, db: &mut RidlDatabase, root: &Path) -> io::Result<()> {
        let manifest_path = root.join("ridl.toml");
        let text = fs::read_to_string(&manifest_path)?;
        let file_id = self.sources.file_id(&path_string(&manifest_path), &text);
        let (manifest, diags) = parse_manifest(file_id, &text);
        self.diagnostics.extend(diags);
        let Some(Manifest {
            kind,
            imports,
            default_timing,
        }) = manifest
        else {
            return Ok(());
        };
        match kind {
            ManifestKind::Package { name, .. } => {
                // A standalone package: the manifest's `[imports]` and
                // `[defaults].timing` ride on its packages; the workspace maps
                // stay empty.
                self.load_package_tree(db, root, &name, &imports, &default_timing)?;
            }
            ManifestKind::Workspace { members } => {
                // ADR-0002 §5 step 3: the workspace root's `[imports]` and
                // `[defaults].timing` are the shared defaults. Member maps are
                // never merged into them.
                self.workspace_imports = imports;
                self.workspace_default_timing = default_timing;
                for member in &members {
                    self.load_member(db, root, member, file_id, &text)?;
                }
            }
        }
        Ok(())
    }

    /// Loads one workspace member directory: its manifest, then its package
    /// tree. A member manifest that declares `[workspace]` is a nested
    /// workspace — MANI-004 — and loads nothing.
    fn load_member(
        &mut self,
        db: &mut RidlDatabase,
        workspace_root: &Path,
        member: &str,
        workspace_file: FileId,
        workspace_text: &str,
    ) -> io::Result<()> {
        let manifest_path = workspace_root.join(member).join("ridl.toml");
        if !manifest_path.is_file() {
            // T7 records member paths unvalidated; the loader validates them
            // against the filesystem (MANI-008).
            self.diagnostics.push(error(
                DiagCode::MANI_008,
                workspace_file,
                member_entry_range(workspace_text, member),
                format!("workspace member `{member}` has no `ridl.toml`"),
            ));
            return Ok(());
        }
        let text = fs::read_to_string(&manifest_path)?;
        let file_id = self.sources.file_id(&path_string(&manifest_path), &text);
        let (manifest, diags) = parse_manifest(file_id, &text);
        self.diagnostics.extend(diags);
        let Some(Manifest {
            kind,
            imports,
            default_timing,
        }) = manifest
        else {
            return Ok(());
        };
        match kind {
            ManifestKind::Workspace { .. } => {
                self.diagnostics.push(error(
                    DiagCode::MANI_004,
                    file_id,
                    workspace_section_range(&text),
                    format!(
                        "workspace member `{member}` declares `[workspace]`; nested workspaces are forbidden"
                    ),
                ));
            }
            ManifestKind::Package { name, .. } => {
                // ADR-0002 §5 step 2: the member's `[imports]` ride on the
                // member's packages only — never merged into the workspace
                // map, never visible to a sibling member. Its
                // `[defaults].timing` shadows the workspace default (ridl §9.1);
                // when the member configures none, the workspace default rides
                // on the member's packages.
                let member_default_timing =
                    default_timing.or_else(|| self.workspace_default_timing.clone());
                self.load_package_tree(
                    db,
                    &workspace_root.join(member),
                    &name,
                    &imports,
                    &member_default_timing,
                )?;
            }
        }
        Ok(())
    }

    /// Loads the package rooted at `dir` under the package name `name`, then
    /// every subdirectory as its own package named by its path — the
    /// package↔directory law's "the name mirrors the directory path relative
    /// to the manifest root" (ADR-0002 §1). Every package in the tree carries
    /// `imports`, the governing manifest's `[imports]`. Directories are
    /// visited in name order; hidden directories, symlinked directories
    /// (following them could revisit the tree in a cycle), and directories
    /// with their own `ridl.toml` (separate package roots) are skipped.
    fn load_package_tree(
        &mut self,
        db: &mut RidlDatabase,
        dir: &Path,
        name: &str,
        imports: &BTreeMap<String, String>,
        default_timing: &Option<String>,
    ) -> io::Result<()> {
        let mut source_files = Vec::new();
        let mut subdirs = Vec::new();
        for entry in fs::read_dir(dir)? {
            let entry = entry?;
            let path = entry.path();
            let is_symlink = entry.file_type()?.is_symlink();
            if path.is_dir() {
                if !is_symlink {
                    subdirs.push(path);
                }
            } else if path
                .extension()
                .is_some_and(|ext| ext == "typl" || ext == "ridl" || ext == "rsdl")
            {
                source_files.push(path);
            }
        }
        source_files.sort();
        subdirs.sort();

        if !source_files.is_empty() {
            let mut files = Vec::new();
            for path in &source_files {
                if let Some((input, _)) = self.load_file(db, path, Some(name))? {
                    files.push(input);
                }
            }
            let lock = self.read_lock(dir)?;
            self.packages.push(Package::new(
                &*db,
                name.to_string(),
                files,
                PackageOrigin::WorkspaceMember,
                imports.clone(),
                default_timing.clone(),
                lock,
            ));
        }

        for subdir in subdirs {
            let Some(dir_name) = subdir.file_name().map(|n| n.to_string_lossy().into_owned())
            else {
                continue;
            };
            if dir_name.starts_with('.') || subdir.join("ridl.toml").is_file() {
                continue;
            }
            self.load_package_tree(
                db,
                &subdir,
                &format!("{name}.{dir_name}"),
                imports,
                default_timing,
            )?;
        }
        Ok(())
    }

    /// Loads one bare source file as a synthetic package named from its
    /// declared package — single-file mode, exempt from TYPL-002 (TYPL-001
    /// still applies). With no usable declaration the file stem names the
    /// package; the parser's FORM-104 for the missing declaration lives on
    /// `parse_file(..).errors()`, like every parse error — loader diagnostics
    /// carry only the manifest and law findings.
    fn load_single_file(&mut self, db: &mut RidlDatabase, path: &Path) -> io::Result<()> {
        let Some((input, decls)) = self.load_file(db, path, None)? else {
            // A non-UTF8 file: the diagnostic is recorded, nothing loads.
            return Ok(());
        };
        let name = decls
            .first()
            .map(|(name, _)| name.clone())
            .filter(|name| !name.is_empty())
            .unwrap_or_else(|| {
                path.file_stem()
                    .map(|stem| stem.to_string_lossy().into_owned())
                    .unwrap_or_else(|| "package".to_string())
            });
        // The file's directory is the package directory, so the lock is read
        // there too (plan decision PD-8).
        let lock = match path.parent() {
            Some(dir) => self.read_lock(dir)?,
            None => None,
        };
        self.packages.push(Package::new(
            &*db,
            name,
            vec![input],
            PackageOrigin::WorkspaceMember,
            BTreeMap::new(),
            None,
            lock,
        ));
        Ok(())
    }

    /// Reads `dir/interfaces.lock` for the package rooted at `dir` (lock
    /// design §2). An absent file is `None`. A malformed file — one that is
    /// not valid UTF-8 included — is RIDL-410 on the offending line of the
    /// lock file itself, through this loader's source map, at the empty range
    /// 0..0 when there is no line to point at (plan decision PD-3); the
    /// package then carries no lock. Any other I/O failure is the error.
    fn read_lock(&mut self, dir: &Path) -> io::Result<Option<PackageLock>> {
        let path = path_string(&dir.join(interface_lock::FILE_NAME));
        let text = match interface_lock::read(dir) {
            Ok(Some(text)) => text,
            Ok(None) => return Ok(None),
            Err(err) if err.kind() == io::ErrorKind::InvalidData => {
                let file_id = self.sources.file_id(&path, "");
                self.diagnostics.push(error(
                    DiagCode::RIDL_410,
                    file_id,
                    byte_range(0, 0),
                    malformed_lock_message("the file is not valid UTF-8"),
                ));
                return Ok(None);
            }
            Err(err) => return Err(err),
        };
        match interface_lock::parse(&text) {
            Ok(lock) => Ok(Some(PackageLock { path, text, lock })),
            Err(malformed) => {
                let file_id = self.sources.file_id(&path, &text);
                self.diagnostics.push(error(
                    DiagCode::RIDL_410,
                    file_id,
                    malformed.range,
                    malformed_lock_message(&malformed.message),
                ));
                Ok(None)
            }
        }
    }

    /// Reads one source file into an [`InputFile`], parses it through the
    /// salsa query, and enforces the package↔directory law: every `package`
    /// declaration after the first is TYPL-001; when `expected` is given and
    /// the first declared name differs, TYPL-002 with the declaration line as
    /// the primary span. Returns the input plus the file's declarations, or
    /// `None` for a file that is not valid UTF-8 — recorded as a diagnostic
    /// and skipped, never an abort of the whole load (ADR-0004 §5).
    fn load_file(
        &mut self,
        db: &mut RidlDatabase,
        path: &Path,
        expected: Option<&str>,
    ) -> io::Result<Option<LoadedFile>> {
        let path_str = path_string(path);
        let text = match fs::read_to_string(path) {
            Ok(text) => text,
            Err(err) if err.kind() == io::ErrorKind::InvalidData => {
                // No text means no spans; the diagnostic points at the start
                // of the interned (empty) file. No code is cataloged for a
                // broken source encoding, so it carries the `NONE` sentinel.
                let file_id = self.sources.file_id(&path_str, "");
                self.diagnostics.push(error(
                    DiagCode::NONE,
                    file_id,
                    byte_range(0, 0),
                    format!("`{path_str}` is not valid UTF-8; the file is skipped"),
                ));
                return Ok(None);
            }
            Err(err) => return Err(err),
        };
        let file_id = self.sources.file_id(&path_str, &text);
        let input = InputFile::new(&*db, path_str, text);

        let parse = parse_file(&*db, input);
        let source =
            SourceFile::cast(parse.syntax()).expect("parser roots every tree in a SourceFile");
        let decls = package_declarations(&source);

        for (_, range) in decls.iter().skip(1) {
            self.diagnostics.push(error(
                DiagCode::TYPL_001,
                file_id,
                *range,
                "more than one `package` declaration in this file".to_string(),
            ));
        }
        if let Some((declared, range)) = decls.first()
            && crate::std_lib::is_reserved_package_name(declared)
        {
            // Reported on the declaration rather than on the manifest or the
            // directory, because that is the one place both paths meet: a
            // workspace member and single-file mode both arrive here, and the
            // issue this closes (driftsys/ridl#203) names both.
            //
            // The message states only the unreachability, which always holds.
            // The artifact overwrite that issue reports is a consequence in
            // package and workspace mode, where the output base is the package
            // name; in single-file mode the base is the file stem, so it
            // collides only when that stem is itself `ridl.std`, whatever the
            // extension. That distinction belongs in the catalogue entry, not
            // in a message that would then be false for some of the inputs it
            // greets.
            self.diagnostics.push(error(
                DiagCode::TYPL_010,
                file_id,
                *range,
                format!(
                    "`{declared}` is provided by the compiler, so a package cannot declare it; every package already imports all of `{declared}` implicitly (typl §3.2), which leaves these declarations unreachable under their own name. Rename the package"
                ),
            ));
        }
        if let (Some(expected), Some((declared, range))) = (expected, decls.first())
            && !declared.is_empty()
            && declared != expected
        {
            self.diagnostics.push(error(
                DiagCode::TYPL_002,
                file_id,
                *range,
                format!(
                    "package name `{declared}` does not mirror the directory path; every file in this directory must declare `package {expected}`"
                ),
            ));
        }
        Ok(Some((input, decls)))
    }
}

/// The interned string form of a filesystem path.
fn path_string(path: &Path) -> String {
    path.to_string_lossy().into_owned()
}

/// The RIDL-410 message: what is wrong with the lock file, then the fix the
/// lock design §8 names.
fn malformed_lock_message(reason: &str) -> String {
    format!(
        "`{}` is malformed: {reason} — resolve the conflict or restore the file from version \
         control, then run `ridl lock`",
        interface_lock::FILE_NAME
    )
}

/// The byte range of the quoted `member` entry inside a workspace manifest's
/// text, or the whole file when it cannot be found (T7 does not retain member
/// spans).
fn member_entry_range(text: &str, member: &str) -> TextRange {
    let quoted = format!("\"{member}\"");
    match text.find(&quoted) {
        Some(start) => byte_range(start, start + quoted.len()),
        None => byte_range(0, text.len()),
    }
}

/// The byte range of the `[workspace]` section header inside a manifest's
/// text, or the whole file as a fallback.
fn workspace_section_range(text: &str) -> TextRange {
    const HEADER: &str = "[workspace]";
    match text.find(HEADER) {
        Some(start) => byte_range(start, start + HEADER.len()),
        None => byte_range(0, text.len()),
    }
}

/// A `rowan::TextRange` over byte offsets.
fn byte_range(start: usize, end: usize) -> TextRange {
    TextRange::new(TextSize::from(start as u32), TextSize::from(end as u32))
}

/// Builds an error [`Diagnostic`]; loader diagnostics carry no secondary
/// labels or fix-its.
fn error(code: DiagCode, file: FileId, range: TextRange, message: String) -> Diagnostic {
    Diagnostic {
        code,
        severity: Severity::Error,
        message,
        primary: Span { file, range },
        labels: Vec::new(),
        fixits: Vec::new(),
    }
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;
    use std::sync::atomic::{AtomicUsize, Ordering};

    use salsa::Setter;
    use salsa::plumbing::AsId;

    use super::*;

    /// 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-core-workspace-{label}-{}-{}",
                std::process::id(),
                COUNTER.fetch_add(1, Ordering::SeqCst),
            ));
            fs::create_dir_all(&path).expect("create the temp dir");
            Self(path)
        }

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

        /// Writes `text` at `relative`, creating parent directories.
        fn write(&self, relative: &str, text: &str) -> PathBuf {
            let path = self.0.join(relative);
            fs::create_dir_all(path.parent().expect("relative paths have a parent"))
                .expect("create parent directories");
            fs::write(&path, text).expect("write the fixture file");
            path
        }
    }

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

    fn codes(diags: &[Diagnostic]) -> Vec<&str> {
        diags.iter().map(|d| d.code.as_str()).collect()
    }

    const PACKAGE_MANIFEST: &str = "[package]\nname = \"veh.common\"\nversion = \"1.0.0\"\n";

    /// TYPL-010: a workspace member cannot declare a name the compiler
    /// provides (driftsys/ridl#203). Before this check the member compiled
    /// clean, its declarations were unreachable because every package already
    /// imports all of `ridl.std` implicitly, and its generated artifact was
    /// overwritten by the standard package's own.
    #[test]
    fn a_package_declaring_a_reserved_name_is_refused() {
        const SOURCE: &str = "package ridl.std\ntype MyOwnType: m\n";
        let dir = TempDir::new("reserved-name");
        dir.write(
            "ridl.toml",
            "[package]\nname = \"ridl.std\"\nversion = \"1.0.0\"\n",
        );
        dir.write("own.typl", SOURCE);

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the package loads");
        assert_eq!(
            codes(&loaded.diagnostics),
            vec!["TYPL-010"],
            "got: {:?}",
            loaded.diagnostics
        );
        let diagnostic = &loaded.diagnostics[0];
        assert!(
            diagnostic.message.contains("ridl.std"),
            "the message names the package: {}",
            diagnostic.message
        );
        // The message states only what holds for every input that draws it.
        // The artifact collision does not: in single-file mode the output base
        // is the file stem. Asserting the absence keeps that clause from
        // returning to the message without the test noticing.
        assert!(
            diagnostic.message.contains("unreachable"),
            "the message states the consequence that always holds: {}",
            diagnostic.message
        );
        for conditional in ["artifact", "overwrit"] {
            assert!(
                !diagnostic.message.contains(conditional),
                "`{conditional}` is true only where the output base is the package name, \
                 so it belongs in the catalogue entry, not the message: {}",
                diagnostic.message
            );
        }
        // The declaration is what is pointed at, not the manifest or the
        // directory: it is the one place a workspace member and single-file
        // mode both pass through. Both ends are asserted, against the source
        // itself, so an over-wide span covering the whole file cannot pass.
        let declaration = SOURCE
            .lines()
            .next()
            .expect("the declaration is the first line");
        assert_eq!(
            (
                usize::from(diagnostic.primary.range.start()),
                usize::from(diagnostic.primary.range.end()),
            ),
            (0, declaration.len()),
            "reported on `{declaration}` exactly"
        );
    }

    /// The same refusal in single-file mode — `ridlc build ridl_std.typl`,
    /// the second form driftsys/ridl#203 names. Single-file mode is exempt
    /// from TYPL-002, so nothing else would have caught it.
    #[test]
    fn a_single_file_declaring_a_reserved_name_is_refused() {
        let dir = TempDir::new("reserved-name-single");
        let file = dir.write("ridl_std.typl", "package ridl.std\ntype MyOwnType: m\n");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, &file).expect("single-file mode loads");
        assert_eq!(
            codes(&loaded.diagnostics),
            vec!["TYPL-010"],
            "got: {:?}",
            loaded.diagnostics
        );
    }

    /// A name that merely starts with `ridl.` is not reserved: the reservation
    /// is the set of packages the compiler provides, not a namespace policy.
    #[test]
    fn only_a_compiler_provided_name_is_reserved() {
        let dir = TempDir::new("near-reserved");
        dir.write(
            "ridl.toml",
            "[package]\nname = \"ridl.stdlib\"\nversion = \"1.0.0\"\n",
        );
        dir.write("own.typl", "package ridl.stdlib\ntype MyOwnType: m\n");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the package loads");
        assert_eq!(
            loaded.diagnostics,
            Vec::new(),
            "`ridl.stdlib` is not a package the compiler provides"
        );
    }

    /// (a) A two-file package loads, both files parse, and editing one
    /// re-parses only it — asserted by the re-executed query's `database_key`
    /// (issue #102).
    #[test]
    fn two_file_package_loads_and_edit_reparses_only_the_edited_file() {
        let dir = TempDir::new("two-file");
        dir.write("ridl.toml", PACKAGE_MANIFEST);
        dir.write("a.typl", "package veh.common\ntype A: m\n");
        dir.write("b.typl", "package veh.common\ntype B: s\n");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the package loads");
        assert_eq!(
            loaded.diagnostics,
            Vec::new(),
            "a clean package, no diagnostics"
        );

        let packages = loaded.workspace.packages(&db).clone();
        assert_eq!(packages.len(), 1, "one package directory, one package");
        assert_eq!(packages[0].name(&db).as_str(), "veh.common");
        assert_eq!(*packages[0].origin(&db), PackageOrigin::WorkspaceMember);
        assert_eq!(
            packages[0].imports(&db),
            &BTreeMap::new(),
            "a manifest without `[imports]` yields an empty package map",
        );
        assert_eq!(
            loaded.workspace.imports(&db),
            &BTreeMap::new(),
            "a standalone load leaves the workspace map empty",
        );

        let files = packages[0].files(&db).clone();
        assert_eq!(files.len(), 2, "both .typl files load");
        for file in &files {
            assert_eq!(
                parse_file(&db, *file).errors(),
                &[],
                "both files parse clean"
            );
        }
        let a = files
            .iter()
            .copied()
            .find(|f| f.path(&db).ends_with("a.typl"))
            .expect("a.typl is loaded");
        let b = files
            .iter()
            .copied()
            .find(|f| f.path(&db).ends_with("b.typl"))
            .expect("b.typl is loaded");

        // Drain the executions the load itself ran; unchanged inputs are then
        // pure memo hits.
        db.take_executed_queries();
        let _ = parse_file(&db, a);
        let _ = parse_file(&db, b);
        assert_eq!(
            db.take_executed_queries(),
            Vec::new(),
            "re-querying unchanged inputs must run no executions",
        );

        // Edit A's text only: exactly one re-execution, and it is A's parse.
        a.set_text(&mut db)
            .to("package veh.common\ntype A: kg\n".to_string());
        let _ = parse_file(&db, a);
        let _ = parse_file(&db, b);
        let executed = db.take_executed_queries();
        assert_eq!(
            executed.len(),
            1,
            "editing one file re-parses exactly one file"
        );
        assert_eq!(
            salsa::attach(&db, || format!("{:?}", executed[0])),
            format!("parse_file({:?})", a.as_id()),
            "the re-executed query is the parse of the edited file",
        );
    }

    /// (b) A file that declares a different package than its directory
    /// requires is TYPL-002, primary span on the `package` line.
    #[test]
    fn typl_002_on_a_mismatching_file() {
        let dir = TempDir::new("mismatch");
        dir.write("ridl.toml", PACKAGE_MANIFEST);
        let bad_text = "package veh.wrong\ntype B: s\n";
        let bad_path = dir.write("bad.typl", bad_text);

        let mut db = RidlDatabase::default();
        let mut loaded = load_workspace(&mut db, dir.path()).expect("the package loads");
        assert_eq!(codes(&loaded.diagnostics), vec!["TYPL-002"]);

        let diag = &loaded.diagnostics[0];
        assert_eq!(diag.severity, Severity::Error);
        assert_eq!(
            diag.primary.range,
            byte_range(0, "package veh.wrong".len()),
            "the primary span is the mismatching `package` line",
        );
        assert_eq!(
            diag.primary.file,
            loaded.sources.file_id(&path_string(&bad_path), bad_text),
            "the span points into the mismatching file",
        );

        // The law is a diagnostic, not an exclusion: the file stays loaded.
        let packages = loaded.workspace.packages(&db).clone();
        assert_eq!(packages.len(), 1);
        assert_eq!(packages[0].files(&db).len(), 1);
    }

    /// (c) More than one `package` declaration in a file is TYPL-001 on each
    /// declaration after the first.
    #[test]
    fn typl_001_on_a_double_package_declaration() {
        let dir = TempDir::new("double-decl");
        dir.write("ridl.toml", PACKAGE_MANIFEST);
        dir.write(
            "dup.typl",
            "package veh.common\npackage veh.extra\ntype A: m\n",
        );

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the package loads");
        assert_eq!(codes(&loaded.diagnostics), vec!["TYPL-001"]);
        assert_eq!(
            loaded.diagnostics[0].primary.range,
            byte_range(19, 36),
            "the primary span is the second `package` declaration",
        );
    }

    /// (d) Workspace mode loads every member and keeps `[imports]` scoped per
    /// ADR-0002 §5: each member package carries only its own manifest's map
    /// (step 2 — a member's pin never leaks to a sibling), and the workspace
    /// map holds only the root's `[imports]` (step 3), never a merge.
    #[test]
    fn workspace_mode_scopes_imports_per_package() {
        let dir = TempDir::new("workspace");
        dir.write(
            "ridl.toml",
            "[workspace]\nmembers = [\"m-one\", \"m-two\"]\n\n[imports]\n\"third.dep\" = \"https://registry.example.com/third/dep@v1.0.0\"\n\"shared.util\" = \"https://registry.example.com/shared/util@v1.0.0\"\n",
        );
        dir.write(
            "m-one/ridl.toml",
            "[package]\nname = \"veh.one\"\nversion = \"1.0.0\"\n\n[imports]\n\"third.dep\" = \"https://mirror.example.com/third/dep@v2.0.0\"\n\"member.only\" = \"https://registry.example.com/member/only@v1.0.0\"\n",
        );
        dir.write("m-one/one.typl", "package veh.one\ntype A: m\n");
        dir.write(
            "m-two/ridl.toml",
            "[package]\nname = \"veh.two\"\nversion = \"1.0.0\"\n\n[imports]\n\"two.only\" = \"https://registry.example.com/two/only@v1.0.0\"\n",
        );
        dir.write("m-two/two.typl", "package veh.two\ntype B: s\n");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the workspace loads");
        assert_eq!(loaded.diagnostics, Vec::new(), "a clean workspace");

        let packages = loaded.workspace.packages(&db).clone();
        let names: Vec<String> = packages.iter().map(|p| p.name(&db).clone()).collect();
        assert_eq!(
            names,
            vec!["veh.one", "veh.two"],
            "both members load, in member order"
        );

        // Step 3: the workspace map is the root's `[imports]`, un-merged —
        // the member pin for `third.dep` must NOT overwrite the root's.
        let workspace_imports = loaded.workspace.imports(&db).clone();
        assert_eq!(
            workspace_imports.get("third.dep").map(String::as_str),
            Some("https://registry.example.com/third/dep@v1.0.0"),
            "the workspace map keeps the root pin, not the member pin",
        );
        assert_eq!(
            workspace_imports.get("shared.util").map(String::as_str),
            Some("https://registry.example.com/shared/util@v1.0.0"),
        );
        assert_eq!(workspace_imports.len(), 2, "no member entry leaks upward");

        // Step 2: each member package carries its own manifest's map only.
        let one_imports = packages[0].imports(&db).clone();
        assert_eq!(
            one_imports.get("third.dep").map(String::as_str),
            Some("https://mirror.example.com/third/dep@v2.0.0"),
            "the member's own pin shadows the workspace default for it alone",
        );
        assert_eq!(
            one_imports.get("member.only").map(String::as_str),
            Some("https://registry.example.com/member/only@v1.0.0"),
        );
        assert!(
            !one_imports.contains_key("two.only"),
            "a sibling's pin never leaks into another member",
        );
        assert_eq!(one_imports.len(), 2, "no workspace entry is merged in");

        let two_imports = packages[1].imports(&db).clone();
        assert_eq!(
            two_imports.get("two.only").map(String::as_str),
            Some("https://registry.example.com/two/only@v1.0.0"),
        );
        assert!(
            !two_imports.contains_key("member.only"),
            "the sibling's pin never leaks into this member",
        );
        assert!(
            !two_imports.contains_key("third.dep"),
            "neither the root default nor the sibling's pin is merged in",
        );
        assert_eq!(two_imports.len(), 1);
    }

    /// `[defaults].timing` follows the ADR-0002 §5 precedence merged at load:
    /// a member's own `[defaults]` shadows the workspace `[defaults]`; a member
    /// without one inherits the workspace default (ridl §9.1, E2 task 9).
    #[test]
    fn defaults_timing_precedence_package_shadows_workspace() {
        let dir = TempDir::new("defaults-timing");
        dir.write(
            "ridl.toml",
            "[workspace]\nmembers = [\"m-own\", \"m-inherit\"]\n\n[defaults]\ntiming = \"[100ms..1000ms]\"\n",
        );
        // m-own configures its own default — it shadows the workspace default.
        dir.write(
            "m-own/ridl.toml",
            "[package]\nname = \"veh.own\"\nversion = \"1.0.0\"\n\n[defaults]\ntiming = \"[50ms..2s]\"\n",
        );
        dir.write("m-own/own.typl", "package veh.own\ntype A: m\n");
        // m-inherit configures none — it inherits the workspace default.
        dir.write(
            "m-inherit/ridl.toml",
            "[package]\nname = \"veh.inherit\"\nversion = \"1.0.0\"\n",
        );
        dir.write("m-inherit/inherit.typl", "package veh.inherit\ntype B: s\n");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the workspace loads");
        assert_eq!(loaded.diagnostics, Vec::new(), "a clean workspace");

        let packages = loaded.workspace.packages(&db).clone();
        let own = packages
            .iter()
            .find(|p| p.name(&db) == "veh.own")
            .expect("m-own loads");
        assert_eq!(
            own.default_timing(&db).as_deref(),
            Some("[50ms..2s]"),
            "the member's own `[defaults]` shadows the workspace default",
        );
        let inherit = packages
            .iter()
            .find(|p| p.name(&db) == "veh.inherit")
            .expect("m-inherit loads");
        assert_eq!(
            inherit.default_timing(&db).as_deref(),
            Some("[100ms..1000ms]"),
            "a member without `[defaults]` inherits the workspace default",
        );
    }

    /// A standalone package's `[defaults].timing` rides on every package in its
    /// directory tree, and single-file mode carries none (ridl §9.1).
    #[test]
    fn standalone_defaults_timing_rides_on_the_tree() {
        let dir = TempDir::new("standalone-defaults");
        dir.write(
            "ridl.toml",
            "[package]\nname = \"veh.common\"\nversion = \"1.0.0\"\n\n[defaults]\ntiming = \"[20ms..200ms]\"\n",
        );
        dir.write("a.typl", "package veh.common\ntype A: m\n");
        dir.write("sub/s.typl", "package veh.common.sub\ntype S: s\n");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the package tree loads");
        assert_eq!(loaded.diagnostics, Vec::new());
        for package in loaded.workspace.packages(&db) {
            assert_eq!(
                package.default_timing(&db).as_deref(),
                Some("[20ms..200ms]"),
                "every package in the tree carries the manifest default",
            );
        }

        // Single-file mode: a bare file with no manifest anywhere up the tree.
        let bare = TempDir::new("standalone-defaults-bare");
        let single = bare.write("iface.ridl", "package solo\ntype A: m\n");
        let mut single_db = RidlDatabase::default();
        let single_loaded =
            load_workspace(&mut single_db, &single).expect("single-file mode loads");
        assert_eq!(
            single_loaded.workspace.packages(&single_db)[0].default_timing(&single_db),
            &None,
            "single-file mode carries no configured default",
        );
    }

    /// (e) A member manifest that declares `[workspace]` is a nested
    /// workspace: MANI-004, and the member loads nothing.
    #[test]
    fn mani_004_on_a_nested_workspace_member() {
        let dir = TempDir::new("nested");
        dir.write(
            "ridl.toml",
            "[workspace]\nmembers = [\"m-bad\", \"m-good\"]\n",
        );
        let bad_text = "[workspace]\nmembers = []\n";
        let bad_path = dir.write("m-bad/ridl.toml", bad_text);
        dir.write(
            "m-good/ridl.toml",
            "[package]\nname = \"veh.good\"\nversion = \"1.0.0\"\n",
        );
        dir.write("m-good/good.typl", "package veh.good\ntype A: m\n");

        let mut db = RidlDatabase::default();
        let mut loaded = load_workspace(&mut db, dir.path()).expect("the workspace loads");
        assert_eq!(codes(&loaded.diagnostics), vec!["MANI-004"]);

        let diag = &loaded.diagnostics[0];
        assert_eq!(diag.severity, Severity::Error);
        assert_eq!(
            diag.primary.file,
            loaded.sources.file_id(&path_string(&bad_path), bad_text),
            "the span points into the member's own manifest",
        );
        assert_eq!(
            diag.primary.range,
            byte_range(0, "[workspace]".len()),
            "the span is the `[workspace]` section header",
        );

        let packages = loaded.workspace.packages(&db).clone();
        let names: Vec<String> = packages.iter().map(|p| p.name(&db).clone()).collect();
        assert_eq!(names, vec!["veh.good"], "the nested member loads nothing");
    }

    /// A workspace member path with no manifest is MANI-008 and skipped; the
    /// rest of the workspace still loads.
    #[test]
    fn mani_008_on_a_missing_member_directory() {
        let dir = TempDir::new("missing-member");
        dir.write(
            "ridl.toml",
            "[workspace]\nmembers = [\"m-gone\", \"m-good\"]\n",
        );
        dir.write(
            "m-good/ridl.toml",
            "[package]\nname = \"veh.good\"\nversion = \"1.0.0\"\n",
        );
        dir.write("m-good/good.typl", "package veh.good\ntype A: m\n");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the workspace loads");
        assert_eq!(codes(&loaded.diagnostics), vec!["MANI-008"]);
        assert_eq!(loaded.diagnostics[0].severity, Severity::Error);
        assert!(loaded.diagnostics[0].message.contains("m-gone"));

        let packages = loaded.workspace.packages(&db).clone();
        assert_eq!(packages.len(), 1);
        assert_eq!(packages[0].name(&db).as_str(), "veh.good");
    }

    /// A subdirectory of a package root is its own package, named by its
    /// directory path relative to the manifest root (ADR-0002 §1); every
    /// package in the tree carries the governing manifest's `[imports]`.
    #[test]
    fn a_subdirectory_is_its_own_package_named_by_its_path() {
        let dir = TempDir::new("subdir");
        dir.write(
            "ridl.toml",
            "[package]\nname = \"veh.common\"\nversion = \"1.0.0\"\n\n[imports]\n\"some.dep\" = \"https://registry.example.com/some/dep@v1.0.0\"\n",
        );
        dir.write("a.typl", "package veh.common\ntype A: m\n");
        dir.write("types/t.typl", "package veh.common.types\ntype T: s\n");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the package tree loads");
        assert_eq!(loaded.diagnostics, Vec::new());

        let packages = loaded.workspace.packages(&db).clone();
        let names: Vec<String> = packages.iter().map(|p| p.name(&db).clone()).collect();
        assert_eq!(names, vec!["veh.common", "veh.common.types"]);
        for package in &packages {
            assert_eq!(
                package.imports(&db).get("some.dep").map(String::as_str),
                Some("https://registry.example.com/some/dep@v1.0.0"),
                "every package in the manifest's tree carries its `[imports]`",
            );
        }
        assert_eq!(
            loaded.workspace.imports(&db),
            &BTreeMap::new(),
            "a standalone load leaves the workspace map empty",
        );
    }

    /// E2 task 2 step (g): a package directory may mix `.typl` and `.ridl`
    /// files — `.ridl` is accepted everywhere `.typl` is, under the same
    /// package↔directory law.
    #[test]
    fn a_package_directory_mixes_typl_and_ridl_files() {
        let dir = TempDir::new("mixed");
        dir.write("ridl.toml", PACKAGE_MANIFEST);
        dir.write("a.typl", "package veh.common\ntype A: m\n");
        dir.write("b.ridl", "package veh.common\ntype B: s\n");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the package loads");
        assert_eq!(loaded.diagnostics, Vec::new(), "a clean mixed package");

        let packages = loaded.workspace.packages(&db).clone();
        assert_eq!(packages.len(), 1, "one package directory, one package");
        let files = packages[0].files(&db).clone();
        assert_eq!(files.len(), 2, "both the .typl and the .ridl file load");
        for file in &files {
            assert_eq!(
                parse_file(&db, *file).errors(),
                &[],
                "both files parse clean"
            );
        }
        assert!(files.iter().any(|f| f.path(&db).ends_with("a.typl")));
        assert!(files.iter().any(|f| f.path(&db).ends_with("b.ridl")));
    }

    /// A package directory loads its `.rsdl` files beside its `.typl` and
    /// `.ridl` files (rsdl reference §2: a package may hold all three), each
    /// parsed under the profile its extension selects.
    #[test]
    fn a_package_directory_loads_its_rsdl_files() {
        let dir = TempDir::new("rsdl");
        dir.write("ridl.toml", PACKAGE_MANIFEST);
        dir.write("a.typl", "package veh.common\ntype A: m\n");
        dir.write("b.ridl", "package veh.common\ntype B: s\n");
        dir.write("c.rsdl", "package veh.common\n");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the package loads");
        assert_eq!(loaded.diagnostics, Vec::new(), "a clean mixed package");

        let packages = loaded.workspace.packages(&db).clone();
        assert_eq!(packages.len(), 1, "one package directory, one package");
        let files = packages[0].files(&db).clone();
        let paths: Vec<&str> = files.iter().map(|f| f.path(&db).as_str()).collect();
        assert_eq!(files.len(), 3, "the .rsdl file loads too: {paths:?}");
        let rsdl = files
            .iter()
            .find(|f| f.path(&db).ends_with("c.rsdl"))
            .expect("the .rsdl file is a package file");
        assert_eq!(
            crate::db::profile_of_path(rsdl.path(&db)),
            ridl_syntax::Profile::Rsdl
        );
        assert_eq!(
            parse_file(&db, *rsdl).errors(),
            &[],
            "the .rsdl file parses clean"
        );
    }

    /// Single-file mode accepts a bare `.ridl` entry, like a bare `.typl`.
    #[test]
    fn single_file_mode_accepts_a_bare_ridl_entry() {
        let dir = TempDir::new("single-ridl");
        let path = dir.write("iface.ridl", "package veh.iface\ntype A: m\n");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, &path).expect("single-file mode loads");
        assert_eq!(loaded.diagnostics, Vec::new(), "exempt from TYPL-002");

        let packages = loaded.workspace.packages(&db).clone();
        assert_eq!(packages.len(), 1, "one synthetic package");
        assert_eq!(
            packages[0].name(&db).as_str(),
            "veh.iface",
            "named from the file's declared package",
        );
    }

    /// A symlinked directory is not followed by the tree walk — following it
    /// could revisit the tree in a cycle and duplicate packages endlessly.
    #[cfg(unix)]
    #[test]
    fn a_symlinked_directory_is_not_followed() {
        let dir = TempDir::new("symlink");
        dir.write("ridl.toml", PACKAGE_MANIFEST);
        dir.write("a.typl", "package veh.common\ntype A: m\n");
        // A symlink pointing back at the package root: a cycle.
        std::os::unix::fs::symlink(dir.path(), dir.path().join("loop"))
            .expect("create the directory symlink");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the package loads");
        assert_eq!(loaded.diagnostics, Vec::new());

        let packages = loaded.workspace.packages(&db).clone();
        assert_eq!(packages.len(), 1, "the symlink cycle adds no packages");
        assert_eq!(packages[0].name(&db).as_str(), "veh.common");
    }

    /// A `.typl` file that is not valid UTF-8 becomes a diagnostic and is
    /// skipped; the rest of the package still loads (ADR-0004 §5 — never a
    /// hard error for content problems).
    #[test]
    fn a_non_utf8_file_is_reported_and_skipped() {
        let dir = TempDir::new("non-utf8");
        dir.write("ridl.toml", PACKAGE_MANIFEST);
        dir.write("a.typl", "package veh.common\ntype A: m\n");
        fs::write(dir.path().join("bad.typl"), [0xFF, 0xFE, 0x00, 0x9F])
            .expect("write the non-UTF8 fixture");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the load continues");
        assert_eq!(loaded.diagnostics.len(), 1);
        assert!(
            loaded.diagnostics[0].message.contains("UTF-8"),
            "the diagnostic names the encoding problem",
        );

        let packages = loaded.workspace.packages(&db).clone();
        assert_eq!(packages.len(), 1);
        let files = packages[0].files(&db).clone();
        assert_eq!(files.len(), 1, "only the valid file loads");
        assert!(files[0].path(&db).ends_with("a.typl"));
    }

    /// (g) Single-file mode: a bare `.typl` file with no manifest up the tree
    /// loads as one synthetic package named from its declared package, exempt
    /// from TYPL-002. The E0 walking-skeleton fixture is the contract input.
    #[test]
    fn single_file_mode_loads_the_e0_fixture() {
        let fixture = concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../ridl-syntax/fixtures/walking_skeleton.typl",
        );
        let text = fs::read_to_string(fixture).expect("the E0 fixture exists");
        assert!(
            text.contains("package fixtures"),
            "the fixture declares `package fixtures`",
        );

        // Copied into an empty temp dir so no manifest exists up the tree —
        // and the directory name never matches the declared package, which
        // proves the TYPL-002 exemption.
        let dir = TempDir::new("single-file");
        let path = dir.write("walking_skeleton.typl", &text);

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, &path).expect("single-file mode loads");
        assert_eq!(loaded.diagnostics, Vec::new(), "exempt from TYPL-002");

        let packages = loaded.workspace.packages(&db).clone();
        assert_eq!(packages.len(), 1, "one synthetic package");
        assert_eq!(
            packages[0].name(&db).as_str(),
            "fixtures",
            "named from the file's declared package",
        );
        assert_eq!(*packages[0].origin(&db), PackageOrigin::WorkspaceMember);

        let files = packages[0].files(&db).clone();
        assert_eq!(files.len(), 1);
        assert_eq!(
            parse_file(&db, files[0]).errors(),
            &[],
            "the fixture parses clean"
        );
    }

    // --- the interface lock (lock design §2, §8) --------------------------

    const LOCK_TEXT: &str = "\
# interfaces.lock — written by ridl lock; do not edit by hand.
next 3
Cabin 1
service:veh.common.climate 2
";

    /// A well-formed `interfaces.lock` beside the sources rides on the
    /// package: its path, its text and the parsed table (the text and path
    /// travel so a later checker diagnostic can point into the file).
    #[test]
    fn a_lock_beside_the_sources_rides_on_the_package() {
        let dir = TempDir::new("lock");
        dir.write("ridl.toml", PACKAGE_MANIFEST);
        dir.write("a.ridl", "package veh.common\ntype A: m\n");
        let lock_path = dir.write("interfaces.lock", LOCK_TEXT);

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the package loads");
        assert_eq!(
            loaded.diagnostics,
            Vec::new(),
            "a well-formed lock draws nothing"
        );

        let packages = loaded.workspace.packages(&db).clone();
        let lock = packages[0]
            .lock(&db)
            .as_ref()
            .expect("the lock rides on the package");
        assert_eq!(lock.path, path_string(&lock_path));
        assert_eq!(lock.text, LOCK_TEXT);
        assert_eq!(lock.lock.next, 3);
        assert_eq!(lock.lock.entries.len(), 2);
        assert_eq!(
            lock.lock.entries[1].key,
            crate::interface_lock::LockKey::Service("veh.common.climate".to_string())
        );
    }

    #[test]
    fn a_package_with_no_lock_has_none() {
        let dir = TempDir::new("no-lock");
        dir.write("ridl.toml", PACKAGE_MANIFEST);
        dir.write("a.ridl", "package veh.common\ntype A: m\n");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the package loads");
        assert_eq!(loaded.diagnostics, Vec::new());
        let packages = loaded.workspace.packages(&db).clone();
        assert_eq!(*packages[0].lock(&db), None);
    }

    /// RIDL-410 is reported on the offending line of the lock file itself,
    /// through the loader's source map (PD-3), and the package then carries
    /// no lock.
    #[test]
    fn a_malformed_lock_is_ridl_410_on_its_own_line() {
        let dir = TempDir::new("bad-lock");
        dir.write("ridl.toml", PACKAGE_MANIFEST);
        dir.write("a.ridl", "package veh.common\ntype A: m\n");
        let text = "# interfaces.lock — written by ridl lock; do not edit by hand.\n\
                    next 2\n\
                    Cabin 1\n\
                    Door 1\n";
        let lock_path = dir.write("interfaces.lock", text);

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the package loads");
        assert_eq!(codes(&loaded.diagnostics), ["RIDL-410"]);
        let diagnostic = &loaded.diagnostics[0];
        assert_eq!(diagnostic.severity, Severity::Error);
        assert_eq!(
            loaded.sources.path(diagnostic.primary.file),
            Some(path_string(&lock_path).as_str()),
            "the span is in the lock file"
        );
        assert_eq!(loaded.sources.text(diagnostic.primary.file), Some(text));
        let line_start = text
            .find("Door 1")
            .expect("the offending line is in the text");
        assert_eq!(
            diagnostic.primary.range,
            byte_range(line_start, line_start + "Door 1".len()),
            "the span is the offending line"
        );
        assert_eq!(
            diagnostic.message,
            "`interfaces.lock` is malformed: number 1 is on two entries: `Cabin` and `Door` — \
             resolve the conflict or restore the file from version control, then run `ridl lock`"
        );

        let packages = loaded.workspace.packages(&db).clone();
        assert_eq!(
            *packages[0].lock(&db),
            None,
            "a malformed lock does not ride on the package"
        );
    }

    /// PD-3: an empty lock file, which has no `next` line, is reported at
    /// 0..0 of the file.
    #[test]
    fn an_empty_lock_is_ridl_410_at_the_start_of_the_file() {
        let dir = TempDir::new("empty-lock");
        dir.write("ridl.toml", PACKAGE_MANIFEST);
        dir.write("a.ridl", "package veh.common\ntype A: m\n");
        dir.write("interfaces.lock", "");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the package loads");
        assert_eq!(codes(&loaded.diagnostics), ["RIDL-410"]);
        assert_eq!(loaded.diagnostics[0].primary.range, byte_range(0, 0));
        assert!(
            loaded.diagnostics[0].message.contains("no `next` line"),
            "got: {}",
            loaded.diagnostics[0].message
        );
    }

    /// A lock file that is not valid UTF-8 is RIDL-410 at 0..0 too — the
    /// treatment the loader gives a source file that is not valid UTF-8.
    #[test]
    fn a_lock_that_is_not_utf8_is_ridl_410() {
        let dir = TempDir::new("binary-lock");
        dir.write("ridl.toml", PACKAGE_MANIFEST);
        dir.write("a.ridl", "package veh.common\ntype A: m\n");
        fs::write(dir.path().join("interfaces.lock"), [0xff, 0xfe, b'\n'])
            .expect("write the bytes");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the package loads");
        assert_eq!(codes(&loaded.diagnostics), ["RIDL-410"]);
        assert!(
            loaded.diagnostics[0].message.contains("not valid UTF-8"),
            "got: {}",
            loaded.diagnostics[0].message
        );
        assert_eq!(loaded.diagnostics[0].primary.range, byte_range(0, 0));
        let packages = loaded.workspace.packages(&db).clone();
        assert_eq!(*packages[0].lock(&db), None);
    }

    /// PD-8: a bare `.ridl` file with no manifest reads `interfaces.lock`
    /// from the file's directory.
    #[test]
    fn single_file_mode_reads_the_lock_beside_the_file() {
        let dir = TempDir::new("single-lock");
        let path = dir.write("iface.ridl", "package veh.iface\ntype A: m\n");
        dir.write("interfaces.lock", LOCK_TEXT);

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, &path).expect("single-file mode loads");
        assert_eq!(loaded.diagnostics, Vec::new());
        let packages = loaded.workspace.packages(&db).clone();
        let lock = packages[0]
            .lock(&db)
            .as_ref()
            .expect("the lock rides on the synthetic package");
        assert_eq!(lock.lock.next, 3);
    }

    /// The file is per package (lock design §2): a subdirectory package reads
    /// its own directory's lock, not its parent's.
    #[test]
    fn a_subdirectory_package_reads_its_own_lock() {
        let dir = TempDir::new("subdir-lock");
        dir.write("ridl.toml", PACKAGE_MANIFEST);
        dir.write("a.ridl", "package veh.common\ntype A: m\n");
        dir.write("interfaces.lock", LOCK_TEXT);
        dir.write("sub/b.ridl", "package veh.common.sub\ntype B: m\n");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the tree loads");
        assert_eq!(loaded.diagnostics, Vec::new());
        let packages = loaded.workspace.packages(&db).clone();
        assert_eq!(packages.len(), 2);
        assert!(
            packages[0].lock(&db).is_some(),
            "the root package has a lock"
        );
        assert_eq!(
            *packages[1].lock(&db),
            None,
            "the subdirectory package has none"
        );
    }
}