compose-lens 0.1.2

Loss-aware parsing, processing, validation, and rendering of Compose projects
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
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
//! Source-aware native values from a merged and optionally profile-selected Compose project.

use crate::diagnostic::{Diagnostic, DiagnosticCode, DiagnosticLabel, Severity};
use crate::merge::{
    EntrySyntax, MergeProvenance, MergedEntry, MergedProject, MergedScalarKind, MergedValue, MergedValueKind,
};
use crate::model::{
    BindOptions, BooleanValue, Command, ComposeScalar, ConfigDefinition, HostAddress, ImageReference, Ipam, IpamConfig,
    KeyValueEntry, Labels, Located, LongPort, LongVolumeMount, MountType, NetworkDefinition, Port, SecretDefinition,
    SelinuxRelabel, ServiceNetwork, ServiceNetworks, ShortExtraHost, ShortPort, ShortVolumeMount, VolumeDefinition,
    VolumeMount,
};
use crate::profiles::ProfileSelection;
use crate::resolution::{SELECTION_PROJECT_MISMATCH, service_in_scope};
use crate::source::{SourceId, SourceSpan};
use std::fmt;
use std::path::{Path, PathBuf};

/// A value in the merged project has an unexpected mapping, sequence, scalar, or null form.
pub const PROJECT_EXPECTED_FORM: DiagnosticCode = DiagnosticCode::new("compose.project.expected-form");

/// A required field is absent from a merged native value.
pub const PROJECT_MISSING_FIELD: DiagnosticCode = DiagnosticCode::new("compose.project.missing-field");

/// A scalar cannot be represented by the requested native value type.
pub const PROJECT_INVALID_VALUE: DiagnosticCode = DiagnosticCode::new("compose.project.invalid-value");

/// A typed value together with every source span that contributed to it during merging.
#[derive(Clone, PartialEq, Eq)]
pub struct ProjectValue<T> {
    value: T,
    provenance: MergeProvenance,
    sensitive: bool,
}

impl<T: fmt::Debug> fmt::Debug for ProjectValue<T> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut debug = formatter.debug_struct("ProjectValue");
        if self.sensitive {
            debug.field("value", &"<redacted>");
        } else {
            debug.field("value", &self.value);
        }
        debug
            .field("provenance", &self.provenance)
            .field("sensitive", &self.sensitive)
            .finish()
    }
}

impl<T> ProjectValue<T> {
    fn new(value: T, source: &MergedValue) -> Self {
        Self {
            value,
            provenance: source.provenance().clone(),
            sensitive: source.is_sensitive(),
        }
    }

    /// Returns the typed effective value.
    #[must_use]
    pub const fn value(&self) -> &T {
        &self.value
    }

    /// Returns the merge operation and contributing spans in processing order.
    #[must_use]
    pub const fn provenance(&self) -> &MergeProvenance {
        &self.provenance
    }

    /// Returns the most recent source contributing to this value.
    #[must_use]
    pub fn effective_source(&self) -> Option<SourceSpan> {
        self.provenance.effective_source()
    }

    /// Reports whether this value contains sensitive interpolation output.
    #[must_use]
    pub const fn is_sensitive(&self) -> bool {
        self.sensitive
    }

    /// Removes the provenance wrapper and returns the typed value.
    #[must_use]
    pub fn into_value(self) -> T {
        self.value
    }
}

/// A merged mapping key and every location at which that key was authored.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectKey {
    value: String,
    sources: Vec<SourceSpan>,
}

impl ProjectKey {
    fn from_entry(entry: &MergedEntry) -> Self {
        Self {
            value: entry.key().to_owned(),
            sources: entry.key_sources().to_vec(),
        }
    }

    /// Returns the semantic key text.
    #[must_use]
    pub fn value(&self) -> &str {
        &self.value
    }

    /// Returns authored key locations in merge order.
    #[must_use]
    pub fn sources(&self) -> &[SourceSpan] {
        &self.sources
    }

    /// Returns the effective key location.
    #[must_use]
    pub fn effective_source(&self) -> Option<SourceSpan> {
        self.sources.last().copied()
    }
}

/// A field retained by the merged tree but outside the first native project-view boundary.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectFieldReference {
    path: Vec<String>,
    key: ProjectKey,
    provenance: MergeProvenance,
    extension: bool,
    sensitive: bool,
}

impl ProjectFieldReference {
    /// Returns the semantic path including the field name.
    #[must_use]
    pub fn path(&self) -> &[String] {
        &self.path
    }

    /// Returns the retained mapping key and all of its source locations.
    #[must_use]
    pub const fn key(&self) -> &ProjectKey {
        &self.key
    }

    /// Returns the field value's complete merge provenance.
    #[must_use]
    pub const fn provenance(&self) -> &MergeProvenance {
        &self.provenance
    }

    /// Reports whether the field name starts with `x-`.
    #[must_use]
    pub const fn is_extension(&self) -> bool {
        self.extension
    }

    /// Reports whether the retained value contains sensitive interpolation output.
    #[must_use]
    pub const fn is_sensitive(&self) -> bool {
        self.sensitive
    }
}

/// One effective environment variable after field-specific multi-file merging.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectEnvironmentEntry {
    name: ProjectKey,
    value: ProjectValue<ComposeScalar>,
    syntax: EntrySyntax,
}

impl ProjectEnvironmentEntry {
    /// Returns the variable name and its contributing key spans.
    #[must_use]
    pub const fn name(&self) -> &ProjectKey {
        &self.name
    }

    /// Returns the effective scalar, including a distinct host-environment null value.
    #[must_use]
    pub const fn value(&self) -> &ProjectValue<ComposeScalar> {
        &self.value
    }

    /// Returns the most recent mapping or list syntax contributing this entry.
    #[must_use]
    pub const fn syntax(&self) -> EntrySyntax {
        self.syntax
    }
}

/// A normalized-by-key environment view that retains each entry's authored syntax form.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectEnvironment {
    entries: Vec<ProjectEnvironmentEntry>,
}

/// One effective hostname-to-address mapping after field-specific project merging.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectExtraHost {
    hostname: ProjectKey,
    address: ProjectValue<HostAddress>,
    syntax: EntrySyntax,
}

impl ProjectExtraHost {
    /// Returns the hostname and every contributing source location.
    #[must_use]
    pub const fn hostname(&self) -> &ProjectKey {
        &self.hostname
    }

    /// Returns the raw-preserving IP address or implementation token.
    #[must_use]
    pub const fn address(&self) -> &ProjectValue<HostAddress> {
        &self.address
    }

    /// Returns the most recent mapping or list syntax contributing this entry.
    #[must_use]
    pub const fn syntax(&self) -> EntrySyntax {
        self.syntax
    }
}

/// Ordered effective `extra_hosts` entries with field and item provenance.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectExtraHosts {
    entries: Vec<ProjectExtraHost>,
}

impl ProjectExtraHosts {
    /// Returns host mappings in effective merge order.
    #[must_use]
    pub fn entries(&self) -> &[ProjectExtraHost] {
        &self.entries
    }
}

impl ProjectEnvironment {
    /// Returns environment variables in effective merge order.
    #[must_use]
    pub fn entries(&self) -> &[ProjectEnvironmentEntry] {
        &self.entries
    }

    /// Finds an effective environment variable by name.
    #[must_use]
    pub fn get(&self, name: &str) -> Option<&ProjectEnvironmentEntry> {
        self.entries.iter().find(|entry| entry.name.value == name)
    }
}

/// One selected service with the native fields needed by the first conversion boundary.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectService {
    name: ProjectKey,
    provenance: MergeProvenance,
    image: Option<ProjectValue<ImageReference>>,
    command: Option<ProjectValue<Command>>,
    environment: Option<ProjectValue<ProjectEnvironment>>,
    extra_hosts: Option<ProjectValue<ProjectExtraHosts>>,
    ports: Option<ProjectValue<Vec<ProjectValue<Port>>>>,
    volumes: Option<ProjectValue<Vec<ProjectValue<VolumeMount>>>>,
    networks: Option<ProjectValue<ServiceNetworks>>,
    profiles: Option<ProjectValue<Vec<ProjectValue<String>>>>,
    unmodeled_fields: Vec<ProjectFieldReference>,
}

impl ProjectService {
    /// Returns the service name and all contributing key spans.
    #[must_use]
    pub const fn name(&self) -> &ProjectKey {
        &self.name
    }

    /// Returns provenance for the complete effective service mapping.
    #[must_use]
    pub const fn provenance(&self) -> &MergeProvenance {
        &self.provenance
    }

    /// Returns the effective image reference.
    #[must_use]
    pub const fn image(&self) -> Option<&ProjectValue<ImageReference>> {
        self.image.as_ref()
    }

    /// Returns the effective command without normalizing scalar and list forms.
    #[must_use]
    pub const fn command(&self) -> Option<&ProjectValue<Command>> {
        self.command.as_ref()
    }

    /// Returns environment entries normalized by key with per-entry syntax retained.
    #[must_use]
    pub const fn environment(&self) -> Option<&ProjectValue<ProjectEnvironment>> {
        self.environment.as_ref()
    }

    /// Returns effective service host mappings with per-entry provenance and syntax.
    #[must_use]
    pub const fn extra_hosts(&self) -> Option<&ProjectValue<ProjectExtraHosts>> {
        self.extra_hosts.as_ref()
    }

    /// Returns the effective port collection and per-item provenance.
    #[must_use]
    pub const fn ports(&self) -> Option<&ProjectValue<Vec<ProjectValue<Port>>>> {
        self.ports.as_ref()
    }

    /// Returns the effective volume-mount collection and per-item provenance.
    #[must_use]
    pub const fn volumes(&self) -> Option<&ProjectValue<Vec<ProjectValue<VolumeMount>>>> {
        self.volumes.as_ref()
    }

    /// Returns effective network attachments with short and long forms retained.
    #[must_use]
    pub const fn networks(&self) -> Option<&ProjectValue<ServiceNetworks>> {
        self.networks.as_ref()
    }

    /// Returns effective profile names and their individual provenance.
    #[must_use]
    pub const fn profiles(&self) -> Option<&ProjectValue<Vec<ProjectValue<String>>>> {
        self.profiles.as_ref()
    }

    /// Returns fields retained outside this initial native project-view boundary.
    #[must_use]
    pub fn unmodeled_fields(&self) -> &[ProjectFieldReference] {
        &self.unmodeled_fields
    }
}

/// One named top-level resource with key and definition provenance kept separately.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectResource<T> {
    name: ProjectKey,
    definition: ProjectValue<T>,
}

impl<T> ProjectResource<T> {
    /// Returns the model name and all authored key locations.
    #[must_use]
    pub const fn name(&self) -> &ProjectKey {
        &self.name
    }

    /// Returns the native effective definition and its merge provenance.
    #[must_use]
    pub const fn definition(&self) -> &ProjectValue<T> {
        &self.definition
    }
}

/// The native consumer view of one merged and optionally profile-selected Compose project.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectView {
    source_ids: Vec<SourceId>,
    base_directory: PathBuf,
    provenance: MergeProvenance,
    name: Option<ProjectValue<String>>,
    services: Vec<ProjectService>,
    networks: Vec<ProjectResource<NetworkDefinition>>,
    volumes: Vec<ProjectResource<VolumeDefinition>>,
    configs: Vec<ProjectResource<ConfigDefinition>>,
    secrets: Vec<ProjectResource<SecretDefinition>>,
    unmodeled_fields: Vec<ProjectFieldReference>,
}

impl ProjectView {
    /// Returns source documents in merge order.
    #[must_use]
    pub fn source_ids(&self) -> &[SourceId] {
        &self.source_ids
    }

    /// Returns the project directory inherited from the first loaded document.
    #[must_use]
    pub fn base_directory(&self) -> &Path {
        &self.base_directory
    }

    /// Returns provenance for the complete merged root.
    #[must_use]
    pub const fn provenance(&self) -> &MergeProvenance {
        &self.provenance
    }

    /// Returns the effective explicit project name.
    #[must_use]
    pub const fn name(&self) -> Option<&ProjectValue<String>> {
        self.name.as_ref()
    }

    /// Returns profile-active services in merged order.
    #[must_use]
    pub fn services(&self) -> &[ProjectService] {
        &self.services
    }

    /// Finds one profile-active service.
    #[must_use]
    pub fn service(&self, name: &str) -> Option<&ProjectService> {
        self.services.iter().find(|service| service.name.value == name)
    }

    /// Returns effective top-level network definitions.
    #[must_use]
    pub fn networks(&self) -> &[ProjectResource<NetworkDefinition>] {
        &self.networks
    }

    /// Returns effective top-level volume definitions.
    #[must_use]
    pub fn volumes(&self) -> &[ProjectResource<VolumeDefinition>] {
        &self.volumes
    }

    /// Returns effective top-level config definitions.
    #[must_use]
    pub fn configs(&self) -> &[ProjectResource<ConfigDefinition>] {
        &self.configs
    }

    /// Returns effective top-level secret definitions.
    #[must_use]
    pub fn secrets(&self) -> &[ProjectResource<SecretDefinition>] {
        &self.secrets
    }

    /// Returns root fields retained outside this initial native project-view boundary.
    #[must_use]
    pub fn unmodeled_fields(&self) -> &[ProjectFieldReference] {
        &self.unmodeled_fields
    }
}

/// Recoverable result of building a typed merged project view.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectViewResult {
    view: Option<ProjectView>,
    diagnostics: Vec<Diagnostic>,
}

impl ProjectViewResult {
    /// Returns the typed view when the profile selection belongs to the project.
    #[must_use]
    pub const fn view(&self) -> Option<&ProjectView> {
        self.view.as_ref()
    }

    /// Returns project-view diagnostics in traversal order.
    #[must_use]
    pub fn diagnostics(&self) -> &[Diagnostic] {
        &self.diagnostics
    }

    /// Reports whether a view exists and contains no error diagnostics.
    #[must_use]
    pub fn is_valid(&self) -> bool {
        self.view.is_some()
            && self
                .diagnostics
                .iter()
                .all(|diagnostic| diagnostic.severity() != Severity::Error)
    }

    /// Separates the view and diagnostics.
    #[must_use]
    pub fn into_parts(self) -> (Option<ProjectView>, Vec<Diagnostic>) {
        (self.view, self.diagnostics)
    }
}

/// Builds native values directly from a merged project without canonical rendering or reparsing.
///
/// A matching selection filters inactive services. Omitting it includes every service. The
/// operation performs no file, environment, provider, or runtime access.
#[must_use]
pub fn build_project_view(project: &MergedProject, selection: Option<&ProfileSelection>) -> ProjectViewResult {
    if selection.is_some_and(|selection| !selection.belongs_to(project)) {
        return ProjectViewResult {
            view: None,
            diagnostics: vec![Diagnostic::new(
                SELECTION_PROJECT_MISMATCH,
                Severity::Error,
                "profile selection does not belong to the merged project",
            )],
        };
    }

    Builder::new(project, selection).build()
}

struct Builder<'a> {
    project: &'a MergedProject,
    selection: Option<&'a ProfileSelection>,
    diagnostics: Vec<Diagnostic>,
    root_unmodeled: Vec<ProjectFieldReference>,
    pending_unmodeled: Vec<ProjectFieldReference>,
}

impl<'a> Builder<'a> {
    const fn new(project: &'a MergedProject, selection: Option<&'a ProfileSelection>) -> Self {
        Self {
            project,
            selection,
            diagnostics: Vec::new(),
            root_unmodeled: Vec::new(),
            pending_unmodeled: Vec::new(),
        }
    }

    fn build(mut self) -> ProjectViewResult {
        let root = self.project.root();
        let entries = root.as_mapping().unwrap_or_default();
        let mut name = None;
        let mut services = Vec::new();
        let mut networks = Vec::new();
        let mut volumes = Vec::new();
        let mut configs = Vec::new();
        let mut secrets = Vec::new();

        for entry in entries {
            match entry.key() {
                "name" => name = self.project_string(entry.value(), "project name"),
                "services" => services = self.services(entry.value()),
                "networks" => networks = self.network_definitions(entry.value()),
                "volumes" => volumes = self.volume_definitions(entry.value()),
                "configs" => configs = self.config_definitions(entry.value()),
                "secrets" => secrets = self.secret_definitions(entry.value()),
                _ => self.record_root_unmodeled(&[], entry),
            }
        }

        ProjectViewResult {
            view: Some(ProjectView {
                source_ids: self.project.source_ids().to_vec(),
                base_directory: self.project.base_directory().to_path_buf(),
                provenance: root.provenance().clone(),
                name,
                services,
                networks,
                volumes,
                configs,
                secrets,
                unmodeled_fields: self.root_unmodeled,
            }),
            diagnostics: self.diagnostics,
        }
    }

    fn services(&mut self, value: &MergedValue) -> Vec<ProjectService> {
        let Some(entries) = self.mapping(value, "services must be a mapping") else {
            return Vec::new();
        };
        let selection = self.selection;
        let mut services = Vec::new();
        for entry in entries {
            if service_in_scope(selection, entry.key()) {
                services.extend(self.service(entry));
            }
        }
        services
    }

    fn service(&mut self, entry: &MergedEntry) -> Option<ProjectService> {
        let pending_start = self.pending_unmodeled.len();
        let value = entry.value();
        let fields = self.mapping(value, "service definition must be a mapping")?;
        let mut service = ProjectService {
            name: ProjectKey::from_entry(entry),
            provenance: value.provenance().clone(),
            image: None,
            command: None,
            environment: None,
            extra_hosts: None,
            ports: None,
            volumes: None,
            networks: None,
            profiles: None,
            unmodeled_fields: Vec::new(),
        };
        let path = ["services".to_owned(), entry.key().to_owned()];

        for field in fields {
            match field.key() {
                "image" => {
                    service.image = self
                        .project_string(field.value(), "service image")
                        .map(|value| ProjectValue {
                            value: ImageReference::parse(value.value),
                            provenance: value.provenance,
                            sensitive: value.sensitive,
                        });
                }
                "command" => service.command = self.command(field.value()),
                "environment" => service.environment = self.environment(field.value()),
                "extra_hosts" => service.extra_hosts = self.extra_hosts(field.value()),
                "ports" => service.ports = self.ports(field.value(), &path),
                "volumes" => service.volumes = self.volumes(field.value(), &path),
                "networks" => service.networks = self.service_networks(field.value(), &path),
                "profiles" => service.profiles = self.string_collection(field.value(), "profiles must be a sequence"),
                _ => service.unmodeled_fields.push(field_reference(&path, field)),
            }
        }
        service
            .unmodeled_fields
            .extend(self.pending_unmodeled.drain(pending_start..));
        Some(service)
    }

    fn command(&mut self, value: &MergedValue) -> Option<ProjectValue<Command>> {
        let span = effective_span(value);
        let command = match value.kind() {
            MergedValueKind::Null(_) => Command::Null(span),
            MergedValueKind::Scalar(scalar) => Command::String(Located::new(scalar.value().to_owned(), span)),
            MergedValueKind::Sequence(values) => {
                let mut arguments = Vec::new();
                for value in values {
                    arguments.push(self.located_string(value, "command list item must be a scalar")?);
                }
                Command::List {
                    span,
                    values: arguments,
                }
            }
            _ => {
                self.expected(value, "command must be null, a scalar, or a sequence");
                return None;
            }
        };
        Some(ProjectValue::new(command, value))
    }

    fn environment(&mut self, value: &MergedValue) -> Option<ProjectValue<ProjectEnvironment>> {
        let mut entries = Vec::new();
        match value.kind() {
            MergedValueKind::Mapping(values) => {
                for entry in values {
                    let scalar = self.compose_scalar(entry.value(), "environment value must be a scalar or null")?;
                    entries.push(ProjectEnvironmentEntry {
                        name: ProjectKey::from_entry(entry),
                        value: ProjectValue::new(scalar, entry.value()),
                        syntax: entry.syntax(),
                    });
                }
            }
            MergedValueKind::Sequence(values) => {
                for item in values {
                    let raw = self.located_string(item, "environment list item must be a scalar")?;
                    let (name, scalar, syntax) = raw.value().split_once('=').map_or_else(
                        || (raw.value().clone(), ComposeScalar::Null, EntrySyntax::ListKeyOnly),
                        |(name, value)| {
                            (
                                name.to_owned(),
                                ComposeScalar::String(value.to_owned()),
                                EntrySyntax::ListKeyValue,
                            )
                        },
                    );
                    entries.push(ProjectEnvironmentEntry {
                        name: ProjectKey {
                            value: name,
                            sources: item.provenance().sources().to_vec(),
                        },
                        value: ProjectValue::new(scalar, item),
                        syntax,
                    });
                }
            }
            _ => {
                self.expected(value, "environment must be a mapping or sequence");
                return None;
            }
        }
        Some(ProjectValue::new(ProjectEnvironment { entries }, value))
    }

    fn extra_hosts(&mut self, value: &MergedValue) -> Option<ProjectValue<ProjectExtraHosts>> {
        let mut entries = Vec::new();
        match value.kind() {
            MergedValueKind::Mapping(values) => {
                for entry in values {
                    let scalar = self.scalar(entry.value(), "extra_hosts address must be a scalar")?;
                    entries.push(ProjectExtraHost {
                        hostname: ProjectKey::from_entry(entry),
                        address: ProjectValue::new(HostAddress::parse(scalar.value().to_owned()), entry.value()),
                        syntax: EntrySyntax::Mapping,
                    });
                }
            }
            MergedValueKind::Sequence(values) => {
                for item in values {
                    let raw = self.located_string(item, "extra_hosts list item must be a scalar")?;
                    let parsed = ShortExtraHost::parse(raw);
                    let (Some(hostname), Some(address)) = (parsed.hostname(), parsed.address()) else {
                        self.invalid(
                            effective_span(item),
                            "extra_hosts entry must contain a hostname and address",
                        );
                        continue;
                    };
                    entries.push(ProjectExtraHost {
                        hostname: ProjectKey {
                            value: hostname.to_owned(),
                            sources: item.provenance().sources().to_vec(),
                        },
                        address: ProjectValue::new(address.clone(), item),
                        syntax: EntrySyntax::ListKeyValue,
                    });
                }
            }
            _ => {
                self.expected(value, "extra_hosts must be a mapping or sequence");
                return None;
            }
        }
        Some(ProjectValue::new(ProjectExtraHosts { entries }, value))
    }

    fn project_string(&mut self, value: &MergedValue, description: &str) -> Option<ProjectValue<String>> {
        let scalar = self.scalar(value, &format!("{description} must be a non-null scalar"))?;
        Some(ProjectValue::new(scalar.value().to_owned(), value))
    }

    fn string_collection(
        &mut self,
        value: &MergedValue,
        message: &str,
    ) -> Option<ProjectValue<Vec<ProjectValue<String>>>> {
        let Some(values) = value.as_sequence() else {
            self.expected(value, message);
            return None;
        };
        let mut strings = Vec::new();
        for value in values {
            let scalar = self.scalar(value, "sequence item must be a non-null scalar")?;
            strings.push(ProjectValue::new(scalar.value().to_owned(), value));
        }
        Some(ProjectValue::new(strings, value))
    }

    fn scalar<'value>(
        &mut self,
        value: &'value MergedValue,
        message: &str,
    ) -> Option<&'value crate::merge::MergedScalar> {
        let Some(scalar) = value.as_scalar() else {
            self.expected(value, message);
            return None;
        };
        Some(scalar)
    }

    fn located_string(&mut self, value: &MergedValue, message: &str) -> Option<Located<String>> {
        let scalar = self.scalar(value, message)?;
        Some(Located::new(scalar.value().to_owned(), effective_span(value)))
    }

    fn compose_scalar(&mut self, value: &MergedValue, message: &str) -> Option<ComposeScalar> {
        match value.kind() {
            MergedValueKind::Null(_) => Some(ComposeScalar::Null),
            MergedValueKind::Scalar(scalar) => Some(match scalar.kind() {
                MergedScalarKind::String => ComposeScalar::String(scalar.value().to_owned()),
                MergedScalarKind::Boolean => ComposeScalar::Boolean(scalar.value().eq_ignore_ascii_case("true")),
                MergedScalarKind::Number => ComposeScalar::Number(scalar.value().to_owned()),
            }),
            _ => {
                self.expected(value, message);
                None
            }
        }
    }

    fn mapping<'value>(&mut self, value: &'value MergedValue, message: &str) -> Option<&'value [MergedEntry]> {
        let Some(entries) = value.as_mapping() else {
            self.expected(value, message);
            return None;
        };
        Some(entries)
    }

    fn expected(&mut self, value: &MergedValue, message: &str) {
        self.diagnostics.push(
            Diagnostic::new(PROJECT_EXPECTED_FORM, Severity::Error, message).with_label(DiagnosticLabel::primary(
                effective_span(value),
                "unexpected merged value form",
            )),
        );
    }

    fn missing(&mut self, value: &MergedValue, message: &str) {
        self.diagnostics.push(
            Diagnostic::new(PROJECT_MISSING_FIELD, Severity::Error, message).with_label(DiagnosticLabel::primary(
                effective_span(value),
                "required field is missing",
            )),
        );
    }

    fn invalid(&mut self, span: SourceSpan, message: &str) {
        self.diagnostics.push(
            Diagnostic::new(PROJECT_INVALID_VALUE, Severity::Error, message)
                .with_label(DiagnosticLabel::primary(span, "invalid native value")),
        );
    }

    fn record_root_unmodeled(&mut self, path: &[String], entry: &MergedEntry) {
        self.root_unmodeled.push(field_reference(path, entry));
    }

    fn record_pending_unmodeled(&mut self, path: &[String], entry: &MergedEntry) {
        self.pending_unmodeled.push(field_reference(path, entry));
    }
}

impl Builder<'_> {
    fn ports(&mut self, value: &MergedValue, service_path: &[String]) -> Option<ProjectValue<Vec<ProjectValue<Port>>>> {
        let Some(values) = value.as_sequence() else {
            self.expected(value, "service ports must be a sequence");
            return None;
        };
        let mut ports = Vec::new();
        for (index, item) in values.iter().enumerate() {
            let mut path = service_path.to_vec();
            path.push("ports".to_owned());
            path.push(index.to_string());
            let port = match item.kind() {
                MergedValueKind::Scalar(scalar) => Port::Short(ShortPort::parse(Located::new(
                    scalar.value().to_owned(),
                    effective_span(item),
                ))),
                MergedValueKind::Mapping(fields) => Port::Long(Box::new(self.long_port(item, fields, &path))),
                _ => {
                    self.expected(item, "service port must use scalar short syntax or mapping long syntax");
                    continue;
                }
            };
            ports.push(ProjectValue::new(port, item));
        }
        Some(ProjectValue::new(ports, value))
    }

    fn long_port(&mut self, value: &MergedValue, fields: &[MergedEntry], path: &[String]) -> LongPort {
        let mut port = LongPort::new(effective_span(value));
        let mut has_target = false;
        for field in fields {
            match field.key() {
                "target" => {
                    if let Some(value) = self.located_string(field.value(), "port target must be a scalar") {
                        port.set_target(value);
                        has_target = true;
                    }
                }
                "published" => self
                    .located_string(field.value(), "published port must be a scalar")
                    .into_iter()
                    .for_each(|value| port.set_published(value)),
                "host_ip" => self
                    .located_string(field.value(), "port host_ip must be a scalar")
                    .into_iter()
                    .for_each(|value| port.set_host_ip(value)),
                "protocol" => self
                    .located_string(field.value(), "port protocol must be a scalar")
                    .into_iter()
                    .for_each(|value| port.set_protocol(value)),
                "app_protocol" => self
                    .located_string(field.value(), "port app_protocol must be a scalar")
                    .into_iter()
                    .for_each(|value| port.set_app_protocol(value)),
                "mode" => self
                    .located_string(field.value(), "port mode must be a scalar")
                    .into_iter()
                    .for_each(|value| port.set_mode(value)),
                "name" => self
                    .located_string(field.value(), "port name must be a scalar")
                    .into_iter()
                    .for_each(|value| port.set_name(value)),
                _ => self.record_pending_unmodeled(path, field),
            }
        }
        if !has_target {
            self.missing(value, "long-syntax port is missing `target`");
        }
        port
    }

    fn volumes(
        &mut self,
        value: &MergedValue,
        service_path: &[String],
    ) -> Option<ProjectValue<Vec<ProjectValue<VolumeMount>>>> {
        let Some(values) = value.as_sequence() else {
            self.expected(value, "service volumes must be a sequence");
            return None;
        };
        let mut mounts = Vec::new();
        for (index, item) in values.iter().enumerate() {
            let mut path = service_path.to_vec();
            path.push("volumes".to_owned());
            path.push(index.to_string());
            let mount = match item.kind() {
                MergedValueKind::Scalar(scalar) => VolumeMount::Short(ShortVolumeMount::new(Located::new(
                    scalar.value().to_owned(),
                    effective_span(item),
                ))),
                MergedValueKind::Mapping(fields) => VolumeMount::Long(Box::new(self.long_volume(item, fields, &path))),
                _ => {
                    self.expected(
                        item,
                        "service volume must use scalar short syntax or mapping long syntax",
                    );
                    continue;
                }
            };
            mounts.push(ProjectValue::new(mount, item));
        }
        Some(ProjectValue::new(mounts, value))
    }

    fn long_volume(&mut self, value: &MergedValue, fields: &[MergedEntry], path: &[String]) -> LongVolumeMount {
        let mut mount = LongVolumeMount::new(effective_span(value));
        let mut has_type = false;
        let mut has_target = false;
        for field in fields {
            match field.key() {
                "type" => {
                    if let Some(value) = self.located_string(field.value(), "volume type must be a scalar") {
                        mount.set_mount_type(Located::new(MountType::from_text(value.value().clone()), value.span()));
                        has_type = true;
                    }
                }
                "source" => self
                    .located_string(field.value(), "volume source must be a scalar")
                    .into_iter()
                    .for_each(|value| mount.set_source(value)),
                "target" => {
                    if let Some(value) = self.located_string(field.value(), "volume target must be a scalar") {
                        mount.set_target(value);
                        has_target = true;
                    }
                }
                "read_only" => self
                    .located_boolean(field.value(), "volume read_only must be a boolean")
                    .into_iter()
                    .for_each(|value| mount.set_read_only(value)),
                "bind" => self
                    .bind_options(field.value(), path)
                    .into_iter()
                    .for_each(|value| mount.set_bind(value)),
                _ => self.record_pending_unmodeled(path, field),
            }
        }
        if !has_type {
            self.missing(value, "long-syntax volume is missing `type`");
        }
        if !has_target {
            self.missing(value, "long-syntax volume is missing `target`");
        }
        mount
    }

    fn bind_options(&mut self, value: &MergedValue, parent_path: &[String]) -> Option<BindOptions> {
        let fields = self.mapping(value, "volume bind options must be a mapping")?;
        let mut bind = BindOptions::new(effective_span(value));
        let mut path = parent_path.to_vec();
        path.push("bind".to_owned());
        for field in fields {
            match field.key() {
                "propagation" => self
                    .located_string(field.value(), "bind propagation must be a scalar")
                    .into_iter()
                    .for_each(|value| bind.set_propagation(value)),
                "create_host_path" => self
                    .located_boolean(field.value(), "bind create_host_path must be a boolean")
                    .into_iter()
                    .for_each(|value| bind.set_create_host_path(value)),
                "selinux" => {
                    if let Some(value) = self.located_string(field.value(), "bind SELinux mode must be a scalar") {
                        let mode = match value.value().as_str() {
                            "z" => Some(SelinuxRelabel::Shared),
                            "Z" => Some(SelinuxRelabel::Private),
                            _ => None,
                        };
                        if let Some(mode) = mode {
                            bind.set_selinux(Located::new(mode, value.span()));
                        } else {
                            self.invalid(value.span(), "bind SELinux mode must be `z` or `Z`");
                        }
                    }
                }
                _ => self.record_pending_unmodeled(&path, field),
            }
        }
        Some(bind)
    }

    fn service_networks(
        &mut self,
        value: &MergedValue,
        service_path: &[String],
    ) -> Option<ProjectValue<ServiceNetworks>> {
        let span = effective_span(value);
        let networks = match value.kind() {
            MergedValueKind::Sequence(values) => {
                let mut names = Vec::new();
                for value in values {
                    names.push(self.located_string(value, "service network name must be a scalar")?);
                }
                ServiceNetworks::Short { span, names }
            }
            MergedValueKind::Mapping(entries) => {
                let mut networks = Vec::new();
                for entry in entries {
                    let mut path = service_path.to_vec();
                    path.push("networks".to_owned());
                    path.push(entry.key().to_owned());
                    networks.push(self.service_network(entry, &path)?);
                }
                ServiceNetworks::Long { span, networks }
            }
            _ => {
                self.expected(value, "service networks must be a sequence or mapping");
                return None;
            }
        };
        Some(ProjectValue::new(networks, value))
    }

    fn service_network(&mut self, entry: &MergedEntry, path: &[String]) -> Option<ServiceNetwork> {
        let value = entry.value();
        let span = effective_span(value);
        let mut network = ServiceNetwork::new(Located::new(entry.key().to_owned(), entry_span(entry)), span);
        let fields = match value.kind() {
            MergedValueKind::Null(_) => return Some(network),
            MergedValueKind::Mapping(fields) => fields,
            _ => {
                self.expected(value, "service network attachment must be a mapping or null");
                return None;
            }
        };
        for field in fields {
            match field.key() {
                "aliases" => self
                    .located_string_sequence(field.value(), "network aliases must be a sequence")
                    .into_iter()
                    .for_each(|value| network.set_aliases(value)),
                "interface_name" => self
                    .located_string(field.value(), "network interface_name must be a scalar")
                    .into_iter()
                    .for_each(|value| network.set_interface_name(value)),
                "ipv4_address" => self
                    .located_string(field.value(), "network ipv4_address must be a scalar")
                    .into_iter()
                    .for_each(|value| network.set_ipv4_address(value)),
                "ipv6_address" => self
                    .located_string(field.value(), "network ipv6_address must be a scalar")
                    .into_iter()
                    .for_each(|value| network.set_ipv6_address(value)),
                "link_local_ips" => self
                    .located_string_sequence(field.value(), "link_local_ips must be a sequence")
                    .into_iter()
                    .for_each(|value| network.set_link_local_ips(value)),
                "mac_address" => self
                    .located_string(field.value(), "network mac_address must be a scalar")
                    .into_iter()
                    .for_each(|value| network.set_mac_address(value)),
                "driver_opts" => self
                    .key_value_mapping(field.value(), "network driver_opts must be a mapping")
                    .into_iter()
                    .for_each(|value| network.set_driver_opts(value)),
                "gw_priority" => self
                    .located_string(field.value(), "network gw_priority must be a scalar")
                    .into_iter()
                    .for_each(|value| network.set_gw_priority(value)),
                "priority" => self
                    .located_string(field.value(), "network priority must be a scalar")
                    .into_iter()
                    .for_each(|value| network.set_priority(value)),
                _ => self.record_pending_unmodeled(path, field),
            }
        }
        Some(network)
    }

    fn located_boolean(&mut self, value: &MergedValue, message: &str) -> Option<Located<BooleanValue>> {
        let scalar = self.scalar(value, message)?;
        let boolean = if scalar.kind() == MergedScalarKind::Boolean {
            BooleanValue::Literal(scalar.value().eq_ignore_ascii_case("true"))
        } else if scalar.value().contains('$') {
            BooleanValue::Expression(scalar.value().to_owned())
        } else {
            self.invalid(effective_span(value), message);
            return None;
        };
        Some(Located::new(boolean, effective_span(value)))
    }

    fn located_string_sequence(&mut self, value: &MergedValue, message: &str) -> Option<Vec<Located<String>>> {
        let Some(values) = value.as_sequence() else {
            self.expected(value, message);
            return None;
        };
        let mut strings = Vec::new();
        for value in values {
            strings.push(self.located_string(value, "sequence item must be a scalar")?);
        }
        Some(strings)
    }

    fn key_value_mapping(&mut self, value: &MergedValue, message: &str) -> Option<Vec<KeyValueEntry>> {
        let Some(entries) = value.as_mapping() else {
            self.expected(value, message);
            return None;
        };
        let mut values = Vec::new();
        for entry in entries {
            let scalar = self.compose_scalar(entry.value(), "mapping value must be a scalar or null")?;
            let value_span = effective_span(entry.value());
            values.push(KeyValueEntry::new(
                Located::new(entry.key().to_owned(), entry_span(entry)),
                Located::new(scalar, value_span),
                value_span,
            ));
        }
        Some(values)
    }

    fn network_definitions(&mut self, value: &MergedValue) -> Vec<ProjectResource<NetworkDefinition>> {
        let Some(entries) = self.mapping(value, "top-level networks must be a mapping") else {
            return Vec::new();
        };
        entries
            .iter()
            .filter_map(|entry| {
                let definition = self.network_definition(entry)?;
                Some(ProjectResource {
                    name: ProjectKey::from_entry(entry),
                    definition: ProjectValue::new(definition, entry.value()),
                })
            })
            .collect()
    }

    fn network_definition(&mut self, entry: &MergedEntry) -> Option<NetworkDefinition> {
        let value = entry.value();
        let span = effective_span(value);
        let mut network = NetworkDefinition::new(Located::new(entry.key().to_owned(), entry_span(entry)), span);
        let fields = match value.kind() {
            MergedValueKind::Null(_) => return Some(network),
            MergedValueKind::Mapping(fields) => fields,
            _ => {
                self.expected(value, "network definition must be a mapping or null");
                return None;
            }
        };
        let path = ["networks".to_owned(), entry.key().to_owned()];
        for field in fields {
            match field.key() {
                "driver" => self
                    .located_string(field.value(), "network driver must be a scalar")
                    .into_iter()
                    .for_each(|value| network.set_driver(value)),
                "driver_opts" => self
                    .key_value_mapping(field.value(), "network driver_opts must be a mapping")
                    .into_iter()
                    .for_each(|value| network.set_driver_opts(value)),
                "attachable" => self
                    .located_boolean(field.value(), "network attachable must be a boolean")
                    .into_iter()
                    .for_each(|value| network.set_attachable(value)),
                "enable_ipv4" => self
                    .located_boolean(field.value(), "network enable_ipv4 must be a boolean")
                    .into_iter()
                    .for_each(|value| network.set_enable_ipv4(value)),
                "enable_ipv6" => self
                    .located_boolean(field.value(), "network enable_ipv6 must be a boolean")
                    .into_iter()
                    .for_each(|value| network.set_enable_ipv6(value)),
                "external" => self
                    .located_boolean(field.value(), "network external must be a boolean")
                    .into_iter()
                    .for_each(|value| network.set_external(value)),
                "internal" => self
                    .located_boolean(field.value(), "network internal must be a boolean")
                    .into_iter()
                    .for_each(|value| network.set_internal(value)),
                "ipam" => self
                    .ipam(field.value(), &path)
                    .into_iter()
                    .for_each(|value| network.set_ipam(value)),
                "labels" => self
                    .labels(field.value())
                    .into_iter()
                    .for_each(|value| network.set_labels(value)),
                "name" => self
                    .located_string(field.value(), "network custom name must be a scalar")
                    .into_iter()
                    .for_each(|value| network.set_custom_name(value)),
                _ => self.record_root_unmodeled(&path, field),
            }
        }
        Some(network)
    }

    fn ipam(&mut self, value: &MergedValue, parent_path: &[String]) -> Option<Ipam> {
        let fields = self.mapping(value, "network IPAM must be a mapping")?;
        let mut ipam = Ipam::new(effective_span(value));
        let mut path = parent_path.to_vec();
        path.push("ipam".to_owned());
        for field in fields {
            match field.key() {
                "driver" => self
                    .located_string(field.value(), "IPAM driver must be a scalar")
                    .into_iter()
                    .for_each(|value| ipam.set_driver(value)),
                "config" => self
                    .ipam_configs(field.value(), &path)
                    .into_iter()
                    .for_each(|value| ipam.set_config(value)),
                "options" => self
                    .key_value_mapping(field.value(), "IPAM options must be a mapping")
                    .into_iter()
                    .for_each(|value| ipam.set_options(value)),
                _ => self.record_root_unmodeled(&path, field),
            }
        }
        Some(ipam)
    }

    fn ipam_configs(&mut self, value: &MergedValue, parent_path: &[String]) -> Option<Vec<IpamConfig>> {
        let Some(values) = value.as_sequence() else {
            self.expected(value, "IPAM config must be a sequence");
            return None;
        };
        let mut configs = Vec::new();
        for (index, value) in values.iter().enumerate() {
            let Some(fields) = value.as_mapping() else {
                self.expected(value, "IPAM config entry must be a mapping");
                continue;
            };
            let mut config = IpamConfig::new(effective_span(value));
            let mut path = parent_path.to_vec();
            path.push("config".to_owned());
            path.push(index.to_string());
            for field in fields {
                match field.key() {
                    "subnet" => self
                        .located_string(field.value(), "IPAM subnet must be a scalar")
                        .into_iter()
                        .for_each(|value| config.set_subnet(value)),
                    "ip_range" => self
                        .located_string(field.value(), "IPAM ip_range must be a scalar")
                        .into_iter()
                        .for_each(|value| config.set_ip_range(value)),
                    "gateway" => self
                        .located_string(field.value(), "IPAM gateway must be a scalar")
                        .into_iter()
                        .for_each(|value| config.set_gateway(value)),
                    "aux_addresses" => self
                        .key_value_mapping(field.value(), "IPAM aux_addresses must be a mapping")
                        .into_iter()
                        .for_each(|value| config.set_aux_addresses(value)),
                    _ => self.record_root_unmodeled(&path, field),
                }
            }
            configs.push(config);
        }
        Some(configs)
    }

    fn volume_definitions(&mut self, value: &MergedValue) -> Vec<ProjectResource<VolumeDefinition>> {
        let Some(entries) = self.mapping(value, "top-level volumes must be a mapping") else {
            return Vec::new();
        };
        entries
            .iter()
            .filter_map(|entry| {
                let definition = self.volume_definition(entry)?;
                Some(ProjectResource {
                    name: ProjectKey::from_entry(entry),
                    definition: ProjectValue::new(definition, entry.value()),
                })
            })
            .collect()
    }

    fn volume_definition(&mut self, entry: &MergedEntry) -> Option<VolumeDefinition> {
        let value = entry.value();
        let span = effective_span(value);
        let mut volume = VolumeDefinition::new(Located::new(entry.key().to_owned(), entry_span(entry)), span);
        let fields = match value.kind() {
            MergedValueKind::Null(_) => return Some(volume),
            MergedValueKind::Mapping(fields) => fields,
            _ => {
                self.expected(value, "volume definition must be a mapping or null");
                return None;
            }
        };
        let path = ["volumes".to_owned(), entry.key().to_owned()];
        for field in fields {
            match field.key() {
                "driver" => self
                    .located_string(field.value(), "volume driver must be a scalar")
                    .into_iter()
                    .for_each(|value| volume.set_driver(value)),
                "driver_opts" => self
                    .key_value_mapping(field.value(), "volume driver_opts must be a mapping")
                    .into_iter()
                    .for_each(|value| volume.set_driver_opts(value)),
                "external" => self
                    .located_boolean(field.value(), "volume external must be a boolean")
                    .into_iter()
                    .for_each(|value| volume.set_external(value)),
                "labels" => self
                    .labels(field.value())
                    .into_iter()
                    .for_each(|value| volume.set_labels(value)),
                "name" => self
                    .located_string(field.value(), "volume custom name must be a scalar")
                    .into_iter()
                    .for_each(|value| volume.set_custom_name(value)),
                _ => self.record_root_unmodeled(&path, field),
            }
        }
        Some(volume)
    }

    fn config_definitions(&mut self, value: &MergedValue) -> Vec<ProjectResource<ConfigDefinition>> {
        let Some(entries) = self.mapping(value, "top-level configs must be a mapping") else {
            return Vec::new();
        };
        entries
            .iter()
            .filter_map(|entry| {
                let definition = self.config_definition(entry)?;
                Some(ProjectResource {
                    name: ProjectKey::from_entry(entry),
                    definition: ProjectValue::new(definition, entry.value()),
                })
            })
            .collect()
    }

    fn config_definition(&mut self, entry: &MergedEntry) -> Option<ConfigDefinition> {
        let value = entry.value();
        let span = effective_span(value);
        let mut config = ConfigDefinition::new(Located::new(entry.key().to_owned(), entry_span(entry)), span);
        let fields = match value.kind() {
            MergedValueKind::Null(_) => return Some(config),
            MergedValueKind::Mapping(fields) => fields,
            _ => {
                self.expected(value, "config definition must be a mapping or null");
                return None;
            }
        };
        let path = ["configs".to_owned(), entry.key().to_owned()];
        for field in fields {
            match field.key() {
                "file" => self
                    .located_string(field.value(), "config file must be a scalar")
                    .into_iter()
                    .for_each(|value| config.set_file(value)),
                "environment" => self
                    .located_string(field.value(), "config environment must be a scalar")
                    .into_iter()
                    .for_each(|value| config.set_environment(value)),
                "content" => self
                    .located_string(field.value(), "config content must be a scalar")
                    .into_iter()
                    .for_each(|value| config.set_content(value)),
                "external" => self
                    .located_boolean(field.value(), "config external must be a boolean")
                    .into_iter()
                    .for_each(|value| config.set_external(value)),
                "name" => self
                    .located_string(field.value(), "config custom name must be a scalar")
                    .into_iter()
                    .for_each(|value| config.set_custom_name(value)),
                _ => self.record_root_unmodeled(&path, field),
            }
        }
        Some(config)
    }

    fn secret_definitions(&mut self, value: &MergedValue) -> Vec<ProjectResource<SecretDefinition>> {
        let Some(entries) = self.mapping(value, "top-level secrets must be a mapping") else {
            return Vec::new();
        };
        entries
            .iter()
            .filter_map(|entry| {
                let definition = self.secret_definition(entry)?;
                Some(ProjectResource {
                    name: ProjectKey::from_entry(entry),
                    definition: ProjectValue::new(definition, entry.value()),
                })
            })
            .collect()
    }

    fn secret_definition(&mut self, entry: &MergedEntry) -> Option<SecretDefinition> {
        let value = entry.value();
        let span = effective_span(value);
        let mut secret = SecretDefinition::new(Located::new(entry.key().to_owned(), entry_span(entry)), span);
        let fields = match value.kind() {
            MergedValueKind::Null(_) => return Some(secret),
            MergedValueKind::Mapping(fields) => fields,
            _ => {
                self.expected(value, "secret definition must be a mapping or null");
                return None;
            }
        };
        let path = ["secrets".to_owned(), entry.key().to_owned()];
        for field in fields {
            match field.key() {
                "file" => self
                    .located_string(field.value(), "secret file must be a scalar")
                    .into_iter()
                    .for_each(|value| secret.set_file(value)),
                "environment" => self
                    .located_string(field.value(), "secret environment must be a scalar")
                    .into_iter()
                    .for_each(|value| secret.set_environment(value)),
                "external" => self
                    .located_boolean(field.value(), "secret external must be a boolean")
                    .into_iter()
                    .for_each(|value| secret.set_external(value)),
                "name" => self
                    .located_string(field.value(), "secret custom name must be a scalar")
                    .into_iter()
                    .for_each(|value| secret.set_custom_name(value)),
                _ => self.record_root_unmodeled(&path, field),
            }
        }
        Some(secret)
    }

    fn labels(&mut self, value: &MergedValue) -> Option<Labels> {
        let span = effective_span(value);
        match value.kind() {
            MergedValueKind::Sequence(_) => self
                .located_string_sequence(value, "labels must be a scalar sequence")
                .map(|values| Labels::List { span, values }),
            MergedValueKind::Mapping(_) => self
                .key_value_mapping(value, "labels must be a scalar mapping")
                .map(|entries| Labels::Map { span, entries }),
            _ => {
                self.expected(value, "labels must be a sequence or mapping");
                None
            }
        }
    }
}

fn field_reference(path: &[String], entry: &MergedEntry) -> ProjectFieldReference {
    let mut complete_path = path.to_vec();
    complete_path.push(entry.key().to_owned());
    ProjectFieldReference {
        path: complete_path,
        key: ProjectKey::from_entry(entry),
        provenance: entry.value().provenance().clone(),
        extension: entry.key().starts_with("x-"),
        sensitive: entry.value().is_sensitive(),
    }
}

fn effective_span(value: &MergedValue) -> SourceSpan {
    value
        .provenance()
        .effective_source()
        .or_else(|| value.provenance().sources().first().copied())
        .unwrap_or_else(|| SourceSpan::from_valid_offsets(SourceId::new(0), 0, 0))
}

fn entry_span(entry: &MergedEntry) -> SourceSpan {
    entry
        .key_sources()
        .last()
        .copied()
        .or_else(|| entry.key_sources().first().copied())
        .unwrap_or_else(|| effective_span(entry.value()))
}