solar-interface 0.3.0

Source positions, diagnostics, and related helper functions
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
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
//! File resolver.
//!
//! Modified from [`solang`](https://github.com/hyperledger/solang/blob/0f032dcec2c6e96797fd66fa0175a02be0aba71c/src/file_resolver.rs).
//!
//! Follows solc's [import path resolution](https://docs.soliditylang.org/en/latest/path-resolution.html):
//! an import path becomes a source unit name, which is looked up among the loaded sources and then
//! on disk under the base path and the include paths.

use super::SourceFile;
use crate::{BytePos, Session, SourceMap};
use itertools::Itertools;
use solar_config::{CompileOpts, ImportRemapping};
use solar_data_structures::smallvec::{SmallVec, smallvec};
use std::{
    borrow::Cow,
    io,
    path::{Component, Path, PathBuf, Prefix},
    sync::{Arc, OnceLock},
};

/// An error that occurred while resolving a path.
#[derive(Debug, thiserror::Error)]
pub enum ResolveError {
    #[error("couldn't read stdin: {0}")]
    ReadStdin(#[source] io::Error),
    #[error("couldn't read {0}: {1}")]
    ReadFile(PathBuf, #[source] io::Error),
    #[error("file {0} not found")]
    NotFound(PathBuf),
    #[error("multiple files match {}: {}", .0.display(), .1.iter().map(|path| path.display()).format(", "))]
    MultipleMatches(PathBuf, Vec<PathBuf>),
}

/// Performs file resolution by applying import paths and mappings.
#[derive(derive_more::Debug)]
pub struct FileResolver<'a> {
    #[debug(skip)]
    source_map: &'a SourceMap,

    /// Include paths.
    include_paths: Vec<PathBuf>,
    /// Import remappings.
    remappings: Vec<ImportRemapping>,
    /// Base path for source unit names.
    base_path: Option<PathBuf>,

    /// Custom current directory.
    custom_current_dir: Option<PathBuf>,
    /// [`std::env::current_dir`] cache. Unused if the current directory is set manually.
    env_current_dir: OnceLock<Option<PathBuf>>,
    /// The start of the last source loaded before the first import that searches the disk.
    last_input: OnceLock<Option<BytePos>>,
}

impl<'a> FileResolver<'a> {
    /// Creates a new file resolver.
    pub fn new(source_map: &'a SourceMap) -> Self {
        let base_path = source_map.roots().as_ref().and_then(|roots| roots.base_path.clone());
        Self {
            source_map,
            include_paths: Vec::new(),
            remappings: Vec::new(),
            base_path,
            custom_current_dir: None,
            env_current_dir: OnceLock::new(),
            last_input: OnceLock::new(),
        }
    }

    /// Configures the file resolver from a session.
    pub fn configure_from_sess(&mut self, sess: &Session) {
        self.configure_from_opts(&sess.opts);
    }

    /// Configures the file resolver from compiler options.
    ///
    /// Relative base and include paths are relative to the current directory.
    pub fn configure_from_opts(&mut self, opts: &CompileOpts) {
        self.add_include_paths(opts.include_paths.iter().cloned());
        self.add_import_remappings(opts.import_remappings.iter().cloned());
        if let Some(base_path) = &opts.base_path {
            self.base_path = Some(self.absolute(base_path));
        }
    }

    /// Clears the internal state.
    pub fn clear(&mut self) {
        self.include_paths.clear();
        self.remappings.clear();
        self.base_path = None;
        self.custom_current_dir = None;
        self.env_current_dir.take();
        self.last_input.take();
    }

    /// Sets the current directory.
    ///
    /// # Panics
    ///
    /// Panics if `current_dir` is not an absolute path.
    #[track_caller]
    pub fn set_current_dir(&mut self, current_dir: &Path) {
        if !current_dir.is_absolute() {
            panic!("current_dir must be an absolute path");
        }
        self.custom_current_dir = Some(current_dir.to_path_buf());
    }

    /// Sets the base path.
    ///
    /// # Panics
    ///
    /// Panics if `base_path` is not an absolute path.
    #[track_caller]
    pub fn set_base_path(&mut self, base_path: &Path) {
        if !base_path.is_absolute() {
            panic!("base_path must be an absolute path");
        }
        self.base_path = Some(base_path.to_path_buf());
    }

    /// Adds include paths.
    ///
    /// Relative paths are relative to the current directory.
    pub fn add_include_paths(&mut self, paths: impl IntoIterator<Item = PathBuf>) {
        for path in paths {
            self.add_include_path(path);
        }
    }

    /// Adds an include path.
    ///
    /// Relative paths are relative to the current directory.
    pub fn add_include_path(&mut self, path: PathBuf) {
        let path = self.absolute(&path);
        self.include_paths.push(path)
    }

    /// Adds import remappings.
    pub fn add_import_remappings(&mut self, remappings: impl IntoIterator<Item = ImportRemapping>) {
        self.remappings.extend(remappings);
    }

    /// Adds an import remapping.
    pub fn add_import_remapping(&mut self, remapping: ImportRemapping) {
        self.remappings.push(remapping);
    }

    /// Returns the source map.
    pub fn source_map(&self) -> &'a SourceMap {
        self.source_map
    }

    /// Returns the current directory, or `.` if it could not be resolved.
    pub fn current_dir(&self) -> &Path {
        self.try_current_dir().unwrap_or(Path::new("."))
    }

    /// Returns the current directory, if resolved successfully.
    pub fn try_current_dir(&self) -> Option<&Path> {
        self.custom_current_dir.as_deref().or_else(|| self.env_current_dir())
    }

    /// Returns the base path for import resolution, which defaults to the current directory.
    pub fn try_base_path(&self) -> Option<&Path> {
        self.base_path.as_deref().or_else(|| self.try_current_dir())
    }

    fn env_current_dir(&self) -> Option<&Path> {
        self.env_current_dir
            .get_or_init(|| {
                std::env::current_dir()
                    .inspect_err(|e| debug!("failed to get current_dir: {e}"))
                    .ok()
            })
            .as_deref()
    }

    /// Canonicalizes a path using [`Self::current_dir`].
    pub fn canonicalize(&self, path: &Path) -> io::Result<PathBuf> {
        self.canonicalize_unchecked(&self.make_absolute(path))
    }

    fn canonicalize_unchecked(&self, path: &Path) -> io::Result<PathBuf> {
        self.source_map.file_loader().canonicalize_path(path)
    }

    /// Normalizes a path, removing `.` segments and applying `..` segments lexically.
    ///
    /// Does not perform I/O.
    pub fn normalize<'b>(&self, path: &'b Path) -> Cow<'b, Path> {
        Cow::Owned(lexical_normalize(path))
    }

    /// Makes the path absolute by joining it with the current directory.
    ///
    /// Does not perform I/O.
    pub fn make_absolute<'b>(&self, path: &'b Path) -> Cow<'b, Path> {
        if path.is_absolute() {
            Cow::Borrowed(path)
        } else if let Some(current_dir) = self.try_current_dir() {
            Cow::Owned(current_dir.join(path))
        } else {
            Cow::Borrowed(path)
        }
    }

    fn absolute(&self, path: &Path) -> PathBuf {
        absolute_path(self.try_current_dir(), path)
    }

    /// Returns the normalized filesystem paths that may satisfy `path`, in resolution order.
    ///
    /// This does not perform I/O or consult the source map. A returned path may remain relative if
    /// the resolver has no current directory. Use [`Self::resolve_file`] for exact resolution,
    /// including preloaded source-unit names and ambiguity detection.
    pub fn candidate_paths(&self, path: &Path, parent: Option<&Path>) -> Vec<PathBuf> {
        let Some(parent) = parent else { return vec![self.absolute(path)] };
        let unit = self.import_source_unit_name(path, parent);
        self.search_paths(&unit).iter().map(|candidate| self.absolute(candidate)).unique().collect()
    }

    /// Applies import remappings in the context of the source unit name of `parent`.
    pub fn remap_import_path<'b>(&self, path: &'b Path, parent: Option<&Path>) -> Cow<'b, Path> {
        match parent {
            Some(parent) => self.remap_import(path, &self.importer_names(parent)),
            None => self.remap_path(path, None),
        }
    }

    /// Resolves an import path.
    ///
    /// `parent` is the path of the file that contains the import. Pass an empty path for a source
    /// without one, like standard input. Without a parent, `path` is loaded directly, like a path
    /// on the command line, relative to the current directory.
    #[instrument(level = "trace", skip_all, fields(path = %path.display()))]
    pub fn resolve_file(
        &self,
        path: &Path,
        parent: Option<&Path>,
    ) -> Result<Arc<SourceFile>, ResolveError> {
        let file = match parent {
            Some(parent) => self.resolve_source_unit(path, parent)?,
            None => self.try_file(path)?,
        };
        file.ok_or_else(|| ResolveError::NotFound(path.into()))
    }

    fn resolve_source_unit(
        &self,
        path: &Path,
        parent: &Path,
    ) -> Result<Option<Arc<SourceFile>>, ResolveError> {
        let unit = self.import_source_unit_name(path, parent);
        if let Some(file) = self.get_source_unit(&unit) {
            return Ok(Some(file));
        }
        // An empty base path in the source map means that file names are source unit names, as in
        // Standard JSON.
        let roots = self.source_map().roots();
        if roots.as_ref().and_then(|roots| roots.base_path.as_deref()) == Some(Path::new("")) {
            return self.read_source_unit(path, &unit);
        }

        let last_input = *self
            .last_input
            .get_or_init(|| self.source_map().files().last().map(|file| file.start_pos));

        // Like solc, prefer an input file with this source unit name over searching the disk.
        // Files loaded for other imports don't count, so the result doesn't depend on their order.
        if let Some(last_input) = last_input
            && !unit.has_root()
        {
            let name = lexical_normalize(&unit);
            let input = self.roots().find_map(|root| {
                let path = generic_path(lexical_normalize(&root.join(&unit)));
                let file = self.source_map().get_file(&path)?;
                (file.start_pos <= last_input && self.source_unit_name(&path) == name)
                    .then_some(file)
            });
            if input.is_some() {
                return Ok(input);
            }
        }

        let mut found = SmallVec::<[_; 1]>::new();
        for candidate in self.search_paths(&unit) {
            // Quick deduplication when include paths are duplicated.
            if let Some(file) = self.load(&candidate)?
                && !found.iter().any(|f| Arc::ptr_eq(f, &file))
            {
                found.push(file);
            }
        }
        match found.len() {
            0 | 1 => Ok(found.pop()),
            _ => {
                let paths = found.iter().map(|file| real_path(file).to_path_buf()).collect();
                Err(ResolveError::MultipleMatches(path.into(), paths))
            }
        }
    }

    /// Reads a source unit through the file loader, like solc's file reader, and names it by the
    /// source unit name. This is how Standard JSON uses its read callback.
    fn read_source_unit(
        &self,
        path: &Path,
        unit: &Path,
    ) -> Result<Option<Arc<SourceFile>>, ResolveError> {
        // Read inside the source map's insertion, so that concurrent imports of the same name
        // wait for one read. Spellings of the name that differ only in `.` and `..` segments or
        // repeated separators name one source, so name it by a normalized spelling.
        let mut error = None;
        let file =
            self.source_map().new_source_file_with(normalize_unit(unit).into(), || {
                match self.read_roots(path, unit) {
                    Ok(Some(src)) => Ok(src),
                    Ok(None) => Err(io::ErrorKind::NotFound.into()),
                    Err(e) => Err(io::Error::other(error.insert(e).to_string())),
                }
            });
        match file {
            Ok(file) => Ok(Some(file)),
            Err(_) if let Some(error) = error => Err(error),
            Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
            Err(e) => Err(ResolveError::ReadFile(unit.into(), e)),
        }
    }

    /// Reads `unit` from each root once through the file loader, like solc's file reader.
    fn read_roots(&self, path: &Path, unit: &Path) -> Result<Option<String>, ResolveError> {
        let loader = self.source_map().file_loader();
        // Ask for a normalized name, so that the result doesn't depend on which spelling of it is
        // read first. Without a base path or include paths, keep a `file://` prefix, like libsolc.
        // Otherwise strip it, like solc's file reader.
        let unit = if self.roots().all(|root| root.as_os_str().is_empty()) {
            unit
        } else {
            strip_file_url(unit)
        };
        let candidates = if unit.has_root() {
            vec![normalize_unit(unit)]
        } else {
            self.roots().map(|root| normalize_unit(&root.join(unit))).collect()
        };
        let mut found = SmallVec::<[(PathBuf, String); 1]>::new();
        let mut read_error = None;
        for candidate in candidates {
            let Ok(path) = loader.canonicalize_path(&candidate) else { continue };
            if found.iter().any(|(found, _)| *found == path) {
                continue;
            }
            match loader.load_file(&path) {
                Ok(src) => found.push((path, src)),
                // A read callback need not serve every root.
                Err(e) => {
                    read_error.get_or_insert(ResolveError::ReadFile(path, e));
                }
            }
        }
        match found.len() {
            0 => read_error.map_or(Ok(None), Err),
            1 => Ok(found.pop().map(|(_, src)| src)),
            _ => {
                let paths = found.into_iter().map(|(path, _)| path).collect();
                Err(ResolveError::MultipleMatches(path.into(), paths))
            }
        }
    }

    /// Returns the source unit name that `path` refers to when imported from `parent`.
    fn import_source_unit_name<'b>(&self, path: &'b Path, parent: &Path) -> Cow<'b, Path> {
        let names = self.importer_names(parent);
        // Only paths starting with `./` or `../` are relative to the importing source unit;
        // `import "b.sol";` is looked up in the base path and include paths.
        let path = if path.starts_with("./") || path.starts_with("../") {
            // Unlike solc, use the importing file's path relative to the base path, which is
            // absolute outside of it, as build tools such as Foundry name those files.
            let base_relative = names.last().unwrap();
            Cow::Owned(join_relative_import(base_relative, path))
        } else {
            Cow::Borrowed(path)
        };
        match self.remap_import(&path, &names) {
            Cow::Owned(remapped) => Cow::Owned(remapped),
            Cow::Borrowed(_) => path,
        }
    }

    /// Returns the names of the importing file `parent` that remapping contexts match: its source
    /// unit name and, unlike solc, its path relative to the base path if that differs, which build
    /// tools such as Foundry use for files outside of it.
    fn importer_names<'b>(&self, parent: &'b Path) -> SmallVec<[&'b Path; 2]> {
        // An empty base path in the source map means that file names are source unit names, as in
        // Standard JSON.
        let roots = self.source_map().roots();
        if roots.as_ref().and_then(|roots| roots.base_path.as_deref()) == Some(Path::new("")) {
            return smallvec![parent];
        }
        let name = self.source_unit_name(parent);
        let base_relative = strip_root(parent, self.try_base_path());
        std::iter::once(name).chain((name != base_relative).then_some(base_relative)).collect()
    }

    /// Applies import remappings in the contexts of the importing file's names.
    fn remap_import<'b>(&self, path: &'b Path, contexts: &[&Path]) -> Cow<'b, Path> {
        let remapped = remap_in_contexts(&self.remappings, path, contexts);
        if remapped != path {
            trace!(remapped=%remapped.display());
        }
        remapped
    }

    /// Returns the base path, or an empty path without one, followed by the include paths.
    fn roots(&self) -> impl Iterator<Item = &Path> {
        let base_path = self.try_base_path().unwrap_or(Path::new(""));
        std::iter::once(base_path).chain(self.include_paths.iter().map(PathBuf::as_path))
    }

    /// Returns the source unit name of a loaded file, like solc does for command-line paths.
    fn source_unit_name<'b>(&self, path: &'b Path) -> &'b Path {
        source_unit_name(path, self.roots(), self.try_current_dir())
    }

    /// Returns the loaded source with the given source unit name.
    fn get_source_unit(&self, unit: &Path) -> Option<Arc<SourceFile>> {
        let source_map = self.source_map();
        source_map.get_file(unit).or_else(|| source_map.get_file(normalize_unit(unit)))
    }

    /// Returns the paths that the host filesystem loader looks up for a source unit name.
    fn search_paths<'b>(&self, unit: &'b Path) -> SmallVec<[Cow<'b, Path>; 2]> {
        let unit = strip_file_url(unit);
        // Unlike solc, look up absolute paths as is, even with a base path.
        if unit.has_root() {
            // A path with a root but no drive, like `/a.sol` on Windows, is on the base path's
            // drive.
            let rooted = match self.try_base_path() {
                Some(base_path) if !unit.is_absolute() => Cow::Owned(base_path.join(unit)),
                _ => Cow::Borrowed(unit),
            };
            return smallvec![rooted];
        }
        self.roots().map(|root| Cow::Owned(root.join(unit))).collect()
    }

    /// Applies the import path mappings to `path`.
    // Reference: <https://github.com/argotorg/solidity/blob/e202d30db8e7e4211ee973237ecbe485048aae97/libsolidity/interface/ImportRemapper.cpp#L32>
    pub fn remap_path<'b>(&self, path: &'b Path, parent: Option<&Path>) -> Cow<'b, Path> {
        let remapped = apply_import_remappings(&self.remappings, path, parent);
        if remapped != path {
            trace!(remapped=%remapped.display());
        }
        remapped
    }

    /// Loads stdin into the source map.
    pub fn load_stdin(&self) -> Result<Arc<SourceFile>, ResolveError> {
        self.source_map().load_stdin().map_err(ResolveError::ReadStdin)
    }

    /// Returns the source file with the given path, if it exists, without loading it.
    pub fn get_file(&self, path: &Path) -> Option<Arc<SourceFile>> {
        self.source_map()
            .get_file(path)
            .or_else(|| self.source_map().get_file(generic_path(self.absolute(path))))
    }

    /// Loads `path` into the source map. Returns `None` if the file doesn't exist.
    ///
    /// Relative paths are relative to the current directory.
    #[instrument(level = "debug", skip_all, fields(path = %path.display()))]
    pub fn try_file(&self, path: &Path) -> Result<Option<Arc<SourceFile>>, ResolveError> {
        if let Some(file) = self.source_map().get_file(path) {
            return Ok(Some(file));
        }
        self.load(&self.make_absolute(path))
    }

    /// Loads the file at `path`, named by its normalized path.
    fn load(&self, path: &Path) -> Result<Option<Arc<SourceFile>>, ResolveError> {
        let path = generic_path(lexical_normalize(path));
        // A file inside the base path may be loaded under its relative name, like the ones a build
        // tool preloads.
        let source_map = self.source_map();
        if let Some(file) = source_map
            .get_file(&path)
            .or_else(|| source_map.get_file(strip_root(&path, self.try_base_path())))
        {
            return Ok(Some(file));
        }
        // Check that the file exists. Its name keeps symbolic links, like solc.
        let Ok(canonical) = self.canonicalize_unchecked(&path) else {
            trace!(path=%path.display(), "not found");
            return Ok(None);
        };
        self.source_map()
            .load_file_with_name(path.into(), &canonical)
            .map(Some)
            .map_err(|e| ResolveError::ReadFile(canonical, e))
    }
}

/// Applies `remappings` to `path` using the same selection rules as [`FileResolver`].
pub fn apply_import_remappings<'a>(
    remappings: &[ImportRemapping],
    path: &'a Path,
    parent: Option<&Path>,
) -> Cow<'a, Path> {
    remap_in_contexts(remappings, path, &[parent.unwrap_or(Path::new(""))])
}

/// Like [`apply_import_remappings`], but a remapping applies if its context matches any of
/// `contexts`.
fn remap_in_contexts<'a>(
    remappings: &[ImportRemapping],
    path: &'a Path,
    contexts: &[&Path],
) -> Cow<'a, Path> {
    let contexts = contexts.iter().map(|context| context.to_string_lossy()).collect_vec();
    let contexts = contexts.iter().map(|context| sanitize_path(context)).collect_vec();

    let mut longest_prefix = 0;
    let mut longest_context = 0;
    let mut best_match_target = None;
    let path_text = path.to_string_lossy();
    let path_text = sanitize_path(&path_text);
    let mut unprefixed_path = &*path_text;
    for ImportRemapping { context, prefix, path: target } in remappings {
        let context = &*sanitize_path(context);
        let prefix = &*sanitize_path(prefix);

        // Skip if current context is closer.
        if context.len() < longest_context {
            continue;
        }
        // Skip if current context is not a prefix of the context.
        if !contexts.iter().any(|context_path| context_path.starts_with(context)) {
            continue;
        }
        // Skip if we already have a closer prefix match.
        if prefix.len() < longest_prefix && context.len() == longest_context {
            continue;
        }
        // Skip if the prefix does not match.
        let Some(up) = path_text.strip_prefix(prefix) else {
            continue;
        };
        longest_context = context.len();
        longest_prefix = prefix.len();
        best_match_target = Some(sanitize_path(target));
        unprefixed_path = up;
    }
    if let Some(best_match_target) = best_match_target {
        Cow::Owned(PathBuf::from(format!("{best_match_target}{unprefixed_path}")))
    } else {
        Cow::Borrowed(path)
    }
}

/// Joins the components of `path` with `/`, like boost's `generic_string`.
fn generic_path(path: PathBuf) -> PathBuf {
    // `/` is not a separator after a verbatim `\\?\` prefix.
    #[cfg(windows)]
    if !matches!(path.components().next(), Some(Component::Prefix(p)) if p.kind().is_verbatim())
        && let Some(s) = path.to_str()
        && let Cow::Owned(s) = sanitize_path(s)
    {
        return s.into();
    }
    path
}

fn sanitize_path(s: &str) -> Cow<'_, str> {
    #[cfg(windows)]
    {
        if s.contains('\\') {
            return Cow::Owned(s.replace('\\', "/"));
        }
    }
    Cow::Borrowed(s)
}

/// Strips a `file://` prefix, which solc's file reader accepts.
fn strip_file_url(path: &Path) -> &Path {
    path.to_str().and_then(|s| s.strip_prefix("file://")).map_or(path, Path::new)
}

/// Joins `path` with the current directory, if any, and normalizes it.
pub(crate) fn absolute_path(current_dir: Option<&Path>, path: &Path) -> PathBuf {
    match current_dir {
        Some(current_dir) if !path.is_absolute() => lexical_normalize(&current_dir.join(path)),
        _ => lexical_normalize(path),
    }
}

/// Strips the first root that strictly contains `path`.
fn strip_root(path: &Path, roots: impl IntoIterator<Item: AsRef<Path>>) -> &Path {
    roots
        .into_iter()
        .filter(|root| !root.as_ref().as_os_str().is_empty())
        .find_map(|root| path.strip_prefix(root).ok().filter(|p| !p.as_os_str().is_empty()))
        .unwrap_or(path)
}

/// Returns the source unit name of a file loaded from disk, like solc does for command-line paths:
/// its path relative to the first root that contains it, without the current directory's drive.
pub(crate) fn source_unit_name<'a>(
    path: &'a Path,
    roots: impl IntoIterator<Item: AsRef<Path>>,
    current_dir: Option<&Path>,
) -> &'a Path {
    strip_current_drive(strip_root(path, roots), current_dir)
}

/// Drops the drive of a Windows path on the current directory's drive, like solc.
fn strip_current_drive<'a>(path: &'a Path, current_dir: Option<&Path>) -> &'a Path {
    if !cfg!(windows) {
        return path;
    }
    let mut components = path.components();
    if let Some(Component::Prefix(prefix)) = components.next()
        && matches!(prefix.kind(), Prefix::Disk(_))
        && current_dir.and_then(|dir| dir.components().next()) == Some(Component::Prefix(prefix))
    {
        return components.as_path();
    }
    path
}

/// Resolves a relative import against the source unit name of the importing file.
///
/// Only the import path is normalized; the importing name may contain `..` segments, or `//` in
/// URLs, that are part of its identity.
// Reference: <https://github.com/argotorg/solidity/blob/e202d30db8e7e4211ee973237ecbe485048aae97/libsolutil/CommonIO.cpp#L140>
fn join_relative_import(parent: &Path, path: &Path) -> PathBuf {
    let mut unit = parent.parent().unwrap_or(Path::new("")).to_path_buf();
    for component in path.components() {
        match component {
            Component::CurDir => {}
            Component::ParentDir => {
                unit.pop();
            }
            component => unit.push(component),
        }
    }
    unit
}

/// Removes `.` segments and applies `..` segments lexically, keeping the leading `..` segments of
/// a relative path.
fn lexical_normalize(path: &Path) -> PathBuf {
    let mut normalized = PathBuf::new();
    for component in path.components() {
        match component {
            Component::CurDir => {}
            Component::ParentDir => {
                if matches!(normalized.components().next_back(), Some(Component::Normal(_))) {
                    normalized.pop();
                } else if !normalized.has_root() {
                    normalized.push(component);
                }
            }
            component => normalized.push(component),
        }
    }
    normalized
}

/// Normalizes a source unit name like [`lexical_normalize`], with `/` separators, keeping the `//`
/// of a URL scheme.
fn normalize_unit(unit: &Path) -> PathBuf {
    if let Some(unit) = unit.to_str()
        && let Some((scheme, rest)) = unit.split_once("://")
        && !scheme.is_empty()
        && !scheme.contains(['/', '\\'])
    {
        let rest = generic_path(lexical_normalize(Path::new(rest)));
        return PathBuf::from(format!("{scheme}://{}", rest.display()));
    }
    generic_path(lexical_normalize(unit))
}

fn real_path(file: &SourceFile) -> &Path {
    file.name.as_real().unwrap_or(Path::new(""))
}

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

    #[cfg(windows)]
    #[test]
    fn remapping_contexts_use_generic_windows_separators() {
        let remappings = ["src:pkg/=lib/source/".parse().unwrap()];
        let remapped = apply_import_remappings(
            &remappings,
            Path::new("pkg/Target.sol"),
            Some(Path::new(r"src\nested\Main.sol")),
        );

        assert_eq!(remapped, Path::new("lib/source/Target.sol"));
    }

    #[cfg(windows)]
    #[test]
    fn names_drop_the_current_drive() {
        let current_dir = Some(Path::new(r"C:\project"));
        for (path, name) in [
            ("C:/other/A.sol", "/other/A.sol"),
            ("c:/other/A.sol", "/other/A.sol"),
            ("D:/other/A.sol", "D:/other/A.sol"),
            (r"\\server\share\A.sol", r"\\server\share\A.sol"),
        ] {
            assert_eq!(
                strip_current_drive(Path::new(path), current_dir),
                Path::new(name),
                "{path}"
            );
        }
    }

    #[cfg(windows)]
    #[test]
    fn resolved_names_use_generic_windows_separators() {
        let tmp = tempfile::Builder::new().prefix("solar-file-resolver-test").tempdir().unwrap();
        let base_path = tmp.path().to_path_buf();
        std::fs::create_dir_all(base_path.join("src")).unwrap();
        for path in ["src/A.sol", "src/B.sol"] {
            std::fs::write(base_path.join(path), "").unwrap();
        }

        let sm = SourceMap::empty();
        let mut resolver = FileResolver::new(&sm);
        resolver.set_current_dir(&base_path);
        let a = resolver.resolve_file(Path::new(r"src\A.sol"), None).unwrap();
        let b = resolver.resolve_file(Path::new("./B.sol"), a.name.as_real()).unwrap();

        for (file, name) in [(a, "src/A.sol"), (b, "src/B.sol")] {
            let path = file.name.as_real().unwrap().strip_prefix(&base_path).unwrap();
            assert_eq!(path.to_str(), Some(name));
        }
    }

    struct TestCase<'a> {
        remappings: &'a [&'a str],
        sources: &'a [Source<'a>],
    }
    struct Source<'a> {
        path: &'a str,
        // `<import string> => <resolved path>`
        imports: &'a [&'a str],
    }

    fn run(test_case: &TestCase<'_>) {
        static ONCE: std::sync::Once = std::sync::Once::new();
        ONCE.call_once(|| {
            tracing_subscriber::fmt::fmt()
                .with_test_writer()
                .with_max_level(tracing::level_filters::LevelFilter::TRACE)
                .init();
        });

        let tmp = tempfile::Builder::new().prefix("solar-file-resolver-test").tempdir().unwrap();
        let base_path = tmp.path().to_path_buf();

        let sm = SourceMap::empty();
        sm.set_roots(Some(base_path.clone()), Vec::new(), None);
        for source in test_case.sources {
            let path = base_path.join(source.path);
            if let Some(parent) = path.parent() {
                let parent = parent.to_str().unwrap();
                std::fs::create_dir_all(parent).expect(parent);
            }
            std::fs::write(&path, "").expect(source.path);
            sm.load_file(&path).expect(source.path);
        }

        let mut file_resolver = FileResolver::new(&sm);
        for &remapping in test_case.remappings {
            file_resolver.add_import_remapping(remapping.parse().expect(remapping));
        }
        for &Source { path, imports } in test_case.sources {
            for (i, &import) in imports.iter().enumerate() {
                let res = (|| -> Result<(), Box<dyn std::error::Error>> {
                    let (import, expected) = import
                        .split_once(" => ")
                        .ok_or("import is not in the format <import string> => <resolved path>")?;
                    let parent = base_path.join(path);
                    let resolved = file_resolver.resolve_file(import.as_ref(), Some(&parent))?;
                    let actual_full = resolved.name.as_real().ok_or("resolved file has no path")?;
                    let actual = actual_full.strip_prefix(&base_path).ok().ok_or(
                        "resolved file path is not a subpath of the base path (not absolute?)",
                    )?;
                    let actual =
                        actual.to_str().ok_or("resolved file path is not a valid string")?;
                    if actual != expected {
                        return Err(format!(
                            "did not resolve to the expected path ({actual} != {expected})",
                        )
                        .into());
                    }
                    Ok(())
                })();
                match res {
                    Ok(()) => {}
                    Err(e) => panic!("{path}:{i}: [{import}] {e}"),
                }
            }
        }
    }

    // Taken from: https://github.com/argotorg/solidity/blob/32c8f080c4cc939df5a3c7ca5ad6b6144ee9aa66/test/libsolidity/Imports.cpp
    #[test]
    fn remappings() {
        run(&TestCase {
            remappings: &["s=s_1.4.6", "t=Tee"],
            sources: &[
                Source { path: "a", imports: &["s/s.sol => s_1.4.6/s.sol"] },
                Source { path: "b", imports: &["t/tee.sol => Tee/tee.sol"] },
                Source { path: "s_1.4.6/s.sol", imports: &[] },
                Source { path: "Tee/tee.sol", imports: &[] },
            ],
        })
    }

    #[test]
    fn context_dependent_remappings() {
        run(&TestCase {
            remappings: &["a:s=s_1.4.6", "b:s=s_1.4.7"],
            sources: &[
                Source { path: "a/a.sol", imports: &["s/s.sol => s_1.4.6/s.sol"] },
                Source { path: "b/b.sol", imports: &["s/s.sol => s_1.4.7/s.sol"] },
                Source { path: "s_1.4.6/s.sol", imports: &[] },
                Source { path: "s_1.4.7/s.sol", imports: &[] },
            ],
        })
    }

    #[test]
    fn context_dependent_remappings_ensure_default_and_module_preserved() {
        run(&TestCase {
            remappings: &[
                "foo=vendor/foo_2.0.0",
                "vendor/bar:foo=vendor/foo_1.0.0",
                "bar=vendor/bar",
            ],
            sources: &[
                Source {
                    path: "main.sol",
                    imports: &[
                        "foo/foo.sol => vendor/foo_2.0.0/foo.sol",
                        "bar/bar.sol => vendor/bar/bar.sol",
                    ],
                },
                Source {
                    path: "vendor/bar/bar.sol",
                    imports: &["foo/foo.sol => vendor/foo_1.0.0/foo.sol"],
                },
                Source { path: "vendor/foo_1.0.0/foo.sol", imports: &[] },
                Source { path: "vendor/foo_2.0.0/foo.sol", imports: &[] },
            ],
        })
    }

    #[test]
    fn context_dependent_remappings_order_independent() {
        let sources = &[
            Source { path: "a/main.sol", imports: &["x/y/z/z.sol => d/z.sol"] },
            Source { path: "a/b/main.sol", imports: &["x/y/z/z.sol => e/y/z/z.sol"] },
            Source { path: "d/z.sol", imports: &[] },
            Source { path: "e/y/z/z.sol", imports: &[] },
        ];
        run(&TestCase { remappings: &["a:x/y/z=d", "a/b:x=e"], sources });
        run(&TestCase { remappings: &["a/b:x=e", "a:x/y/z=d"], sources });
    }

    #[test]
    fn top_level_relative_path_uses_current_dir() {
        let tmp = tempfile::Builder::new().prefix("solar-file-resolver-test").tempdir().unwrap();
        let cwd = tmp.path().join("cwd");
        let sibling = tmp.path().join("sibling");
        let source = sibling.join("a.sol");
        let import = sibling.join("b.sol");
        std::fs::create_dir_all(&cwd).unwrap();
        std::fs::create_dir_all(&sibling).unwrap();
        std::fs::write(&source, "").unwrap();
        std::fs::write(&import, "").unwrap();

        let sm = SourceMap::empty();
        sm.set_roots(Some(cwd.clone()), Vec::new(), None);
        let mut file_resolver = FileResolver::new(&sm);
        file_resolver.set_current_dir(&cwd);
        let resolved = file_resolver.resolve_file(Path::new("../sibling/a.sol"), None).unwrap();

        assert_eq!(resolved.name.as_real(), Some(source.as_path()));

        let parent = resolved.name.as_real().unwrap();
        let relative_import =
            file_resolver.resolve_file(Path::new("./b.sol"), Some(parent)).unwrap();
        assert_eq!(relative_import.name.as_real(), Some(import.as_path()));

        let direct_import = file_resolver.resolve_file(Path::new("b.sol"), Some(parent));
        assert!(
            matches!(direct_import, Err(ResolveError::NotFound(path)) if path == Path::new("b.sol"))
        );
    }

    #[test]
    fn top_level_path_takes_precedence_over_remapping() {
        let tmp = tempfile::Builder::new().prefix("solar-file-resolver-test").tempdir().unwrap();
        let base_path = tmp.path().to_path_buf();
        let direct = base_path.join("src/A.sol");
        let remapped = base_path.join("lib/A.sol");
        for path in [&direct, &remapped] {
            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
            std::fs::write(path, "").unwrap();
        }

        let sm = SourceMap::empty();
        sm.set_roots(Some(base_path.clone()), Vec::new(), None);
        let mut resolver = FileResolver::new(&sm);
        resolver.set_current_dir(&base_path);
        resolver.add_import_remapping("src/=lib/".parse().unwrap());

        let resolved = resolver.resolve_file(Path::new("src/A.sol"), None).unwrap();

        assert_eq!(resolved.name.as_real(), Some(direct.as_path()));
        assert_eq!(resolver.candidate_paths(Path::new("src/A.sol"), None), vec![direct]);
    }

    #[test]
    fn relative_import_from_virtual_source_uses_source_unit_name() {
        let sm = SourceMap::empty();
        sm.set_roots(Some(PathBuf::new()), Vec::new(), None);
        let mut file_resolver = FileResolver::new(&sm);
        file_resolver.set_current_dir(&std::env::current_dir().unwrap());
        let imported = sm.new_source_file(PathBuf::from("B.sol"), "").unwrap();

        let resolved = file_resolver.resolve_file(Path::new("./B.sol"), Some(Path::new("A.sol")));

        assert!(Arc::ptr_eq(&resolved.unwrap(), &imported));
    }

    #[test]
    fn direct_import_without_current_dir_uses_source_unit_name() {
        use crate::source_map::FileLoader;

        struct Loader;

        impl FileLoader for Loader {
            fn canonicalize_path(&self, path: &Path) -> io::Result<PathBuf> {
                Ok(path.to_path_buf())
            }

            fn load_stdin(&self) -> io::Result<String> {
                unreachable!()
            }

            fn load_file(&self, path: &Path) -> io::Result<String> {
                assert_eq!(path, Path::new("B.sol"));
                Ok(String::new())
            }

            fn load_binary_file(&self, _path: &Path) -> io::Result<Vec<u8>> {
                unreachable!()
            }
        }

        let sm = SourceMap::empty();
        sm.set_file_loader(Loader);
        let file_resolver = FileResolver::new(&sm);
        file_resolver.env_current_dir.set(None).unwrap();

        let resolved = file_resolver.resolve_file(Path::new("B.sol"), Some(Path::new("A.sol")));

        assert_eq!(resolved.unwrap().name.as_real(), Some(Path::new("B.sol")));
    }

    #[test]
    fn direct_import_reuses_preloaded_source_unit_name() {
        let tmp = tempfile::Builder::new().prefix("solar-file-resolver-test").tempdir().unwrap();
        let base_path = tmp.path().to_path_buf();
        let source_path = base_path.join("src/B.sol");
        std::fs::create_dir_all(source_path.parent().unwrap()).unwrap();
        std::fs::write(&source_path, "contract B {}").unwrap();

        let sm = SourceMap::empty();
        sm.set_roots(Some(base_path.clone()), Vec::new(), None);
        let imported = sm.new_source_file(PathBuf::from("src/B.sol"), "contract B {}").unwrap();
        let mut file_resolver = FileResolver::new(&sm);
        file_resolver.set_current_dir(&base_path);

        let resolved =
            file_resolver.resolve_file(Path::new("src/B.sol"), Some(Path::new("test/A.sol")));

        assert!(Arc::ptr_eq(&resolved.unwrap(), &imported));
    }

    #[test]
    fn absolute_remapping_reuses_preloaded_source_unit_name() {
        let tmp = tempfile::Builder::new().prefix("solar-file-resolver-test").tempdir().unwrap();
        let base_path = tmp.path().to_path_buf();
        for path in ["lib/dep/Test.sol", "lib/dep/Base.sol"] {
            let path = base_path.join(path);
            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
            std::fs::write(path, "").unwrap();
        }

        let sm = SourceMap::empty();
        sm.set_roots(Some(base_path.clone()), Vec::new(), None);
        let test = sm.new_source_file(PathBuf::from("lib/dep/Test.sol"), "").unwrap();
        let base = sm.new_source_file(PathBuf::from("lib/dep/Base.sol"), "").unwrap();
        let mut file_resolver = FileResolver::new(&sm);
        file_resolver.set_current_dir(&base_path);
        file_resolver.add_import_remapping(
            format!("dep/={}/", base_path.join("lib/dep").display()).parse().unwrap(),
        );

        // `dep/Test.sol` remaps to an absolute path that names the preloaded `lib/dep/Test.sol`.
        let resolved = file_resolver
            .resolve_file(Path::new("dep/Test.sol"), Some(Path::new("test/A.t.sol")))
            .unwrap();
        assert!(Arc::ptr_eq(&resolved, &test));

        // Its relative imports then resolve to the same copies as direct imports do.
        let parent = resolved.name.as_real().unwrap();
        let relative = file_resolver.resolve_file(Path::new("./Base.sol"), Some(parent)).unwrap();
        let direct = file_resolver
            .resolve_file(Path::new("dep/Base.sol"), Some(Path::new("test/A.t.sol")))
            .unwrap();
        assert!(Arc::ptr_eq(&relative, &base));
        assert!(Arc::ptr_eq(&direct, &base));
    }

    #[test]
    fn candidate_paths_follow_remapping_and_search_order() {
        let tmp = tempfile::Builder::new().prefix("solar-file-resolver-test").tempdir().unwrap();
        let base_path = tmp.path().to_path_buf();
        let source = base_path.join("src/Main.sol");

        let sm = SourceMap::empty();
        sm.set_roots(Some(base_path.clone()), Vec::new(), None);
        let mut resolver = FileResolver::new(&sm);
        resolver.set_current_dir(&base_path);
        resolver.add_include_path(base_path.join("vendor"));
        resolver.add_import_remapping("oz=packages/openzeppelin".parse().unwrap());

        assert_eq!(
            resolver.candidate_paths(Path::new("oz/contracts/Token.sol"), Some(&source)),
            vec![
                base_path.join("packages/openzeppelin/contracts/Token.sol"),
                base_path.join("vendor/packages/openzeppelin/contracts/Token.sol"),
            ]
        );
    }

    #[test]
    fn candidate_paths_resolve_relative_imports_from_importer() {
        let tmp = tempfile::Builder::new().prefix("solar-file-resolver-test").tempdir().unwrap();
        let base_path = tmp.path().to_path_buf();
        let source = base_path.join("src/nested/Main.sol");

        let sm = SourceMap::empty();
        sm.set_roots(Some(base_path.clone()), Vec::new(), None);
        let mut resolver = FileResolver::new(&sm);
        resolver.set_current_dir(&base_path);
        resolver.add_include_path(base_path.join("vendor"));
        resolver.add_import_remapping("src:pkg/=packages/pkg/".parse().unwrap());

        // Like solc, the include paths are searched for the source unit name too.
        assert_eq!(
            resolver.candidate_paths(Path::new("../Shared.sol"), Some(&source)),
            vec![base_path.join("src/Shared.sol"), base_path.join("vendor/src/Shared.sol")]
        );
    }

    #[test]
    fn candidate_paths_apply_context_dependent_remappings() {
        let tmp = tempfile::Builder::new().prefix("solar-file-resolver-test").tempdir().unwrap();
        let base_path = tmp.path().to_path_buf();

        let sm = SourceMap::empty();
        sm.set_roots(Some(base_path.clone()), Vec::new(), None);
        let mut resolver = FileResolver::new(&sm);
        resolver.set_current_dir(&base_path);
        resolver.add_import_remapping("src:pkg/=lib/source/".parse().unwrap());
        resolver.add_import_remapping("test:pkg/=lib/test/".parse().unwrap());

        assert_eq!(
            resolver.candidate_paths(
                Path::new("pkg/Dependency.sol"),
                Some(&base_path.join("src/Main.sol")),
            ),
            vec![base_path.join("lib/source/Dependency.sol")]
        );
        assert_eq!(
            resolver.candidate_paths(
                Path::new("pkg/Dependency.sol"),
                Some(&base_path.join("test/Main.t.sol")),
            ),
            vec![base_path.join("lib/test/Dependency.sol")]
        );
    }

    fn write_files(root: &Path, paths: &[&str]) {
        for path in paths {
            let path = root.join(path);
            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
            std::fs::write(path, "").unwrap();
        }
    }

    #[test]
    fn top_level_path_ignores_base_path() {
        let tmp = tempfile::Builder::new().prefix("solar-file-resolver-test").tempdir().unwrap();
        let root = tmp.path();
        write_files(root, &["src/A.sol", "src/B.sol"]);

        let sm = SourceMap::empty();
        sm.set_roots(Some(root.join("src")), Vec::new(), None);
        let mut resolver = FileResolver::new(&sm);
        resolver.set_current_dir(root);

        let a = resolver.resolve_file(Path::new("src/A.sol"), None).unwrap();
        let b = resolver.resolve_file(Path::new("B.sol"), a.name.as_real()).unwrap();
        assert_eq!(a.name.as_real(), Some(root.join("src/A.sol").as_path()));
        assert_eq!(b.name.as_real(), Some(root.join("src/B.sol").as_path()));
        assert_eq!(sm.filename_for_diagnostics(&a.name).to_string(), "A.sol");
    }

    #[test]
    fn include_paths_name_source_units() {
        let tmp = tempfile::Builder::new().prefix("solar-file-resolver-test").tempdir().unwrap();
        let root = tmp.path();
        write_files(root, &["src/A.sol", "lib/dep/C.sol", "lib/dep/D.sol"]);

        let sm = SourceMap::empty();
        sm.set_roots(Some(root.join("src")), vec![root.join("lib")], None);
        let mut resolver = FileResolver::new(&sm);
        resolver.set_current_dir(root);
        // Relative base and include paths are relative to the current directory.
        resolver.configure_from_opts(&CompileOpts {
            base_path: Some("src".into()),
            include_paths: vec!["lib".into()],
            ..Default::default()
        });

        let c = resolver.resolve_file(Path::new("dep/C.sol"), Some(&root.join("src/A.sol")));
        let c = c.unwrap();
        // The source unit name `dep/C.sol` resolves relative imports in the include path.
        let d = resolver.resolve_file(Path::new("./D.sol"), c.name.as_real()).unwrap();
        for (file, name) in [(c, "dep/C.sol"), (d, "dep/D.sol")] {
            assert_eq!(file.name.as_real(), Some(root.join("lib").join(name).as_path()));
            assert_eq!(sm.filename_for_diagnostics(&file.name).to_string(), name);
        }
    }

    #[test]
    fn nested_include_paths_name_by_base_path() {
        let tmp = tempfile::Builder::new().prefix("solar-file-resolver-test").tempdir().unwrap();
        let root = tmp.path();
        write_files(root, &["src/A.sol", "lib/dep/C.sol"]);

        let sm = SourceMap::empty();
        sm.set_roots(Some(root.to_path_buf()), vec![root.join("lib")], None);
        let mut resolver = FileResolver::new(&sm);
        resolver.add_include_path(root.join("lib"));

        // solc names this file `dep/C.sol`, by its import path.
        let c = resolver.resolve_file(Path::new("dep/C.sol"), Some(&root.join("src/A.sol")));
        assert_eq!(sm.filename_for_diagnostics(&c.unwrap().name).to_string(), "lib/dep/C.sol");
    }

    #[test]
    fn relative_imports_leave_include_paths() {
        let tmp = tempfile::Builder::new().prefix("solar-file-resolver-test").tempdir().unwrap();
        let root = tmp.path();
        write_files(root, &["Events/Event.sol", "Tokens/Token.sol"]);

        let sm = SourceMap::empty();
        let mut resolver = FileResolver::new(&sm);
        resolver.set_base_path(&root.join("base"));
        resolver.add_include_path(root.join("Events"));

        let token = resolver
            .resolve_file(Path::new("../Tokens/Token.sol"), Some(&root.join("Events/Event.sol")))
            .unwrap();
        assert_eq!(token.name.as_real(), Some(root.join("Tokens/Token.sol").as_path()));
    }

    #[test]
    fn remapping_contexts_match_absolute_paths_outside_base_path() {
        let tmp = tempfile::Builder::new().prefix("solar-file-resolver-test").tempdir().unwrap();
        let root = tmp.path();
        write_files(root, &["ext/foo/A.sol", "proj/y/X.sol", "proj/z/X.sol"]);

        let sm = SourceMap::empty();
        let mut resolver = FileResolver::new(&sm);
        resolver.set_base_path(&root.join("proj"));
        resolver.add_include_path(root.join("ext"));
        resolver.add_import_remapping("x/=z/".parse().unwrap());
        // Build tools such as Foundry name files outside the base path by their absolute paths.
        resolver.add_import_remapping(ImportRemapping {
            context: root.join("ext/foo/").display().to_string(),
            prefix: "x/".into(),
            path: "y/".into(),
        });

        let parent = root.join("ext/foo/A.sol");
        let resolved = resolver.resolve_file(Path::new("x/X.sol"), Some(&parent)).unwrap();
        assert_eq!(resolved.name.as_real(), Some(root.join("proj/y/X.sol").as_path()));
    }

    #[test]
    fn absolute_names_in_include_paths_skip_relative_sources() {
        let tmp = tempfile::Builder::new().prefix("solar-file-resolver-test").tempdir().unwrap();
        let root = tmp.path();
        write_files(root, &["ext/src/X.sol"]);

        let sm = SourceMap::empty();
        // A different file, named relative to the base path.
        sm.new_source_file(PathBuf::from("src/X.sol"), "").unwrap();
        let mut resolver = FileResolver::new(&sm);
        resolver.set_base_path(&root.join("proj"));
        resolver.add_include_path(root.join("ext"));
        resolver.add_import_remapping(ImportRemapping {
            context: String::new(),
            prefix: "dep/".into(),
            path: format!("{}/", root.join("ext/src").display()),
        });

        let resolved = resolver.resolve_file(Path::new("dep/X.sol"), Some(Path::new("src/A.sol")));
        assert_eq!(resolved.unwrap().name.as_real(), Some(root.join("ext/src/X.sol").as_path()));
    }

    #[test]
    fn include_path_imports_reuse_relative_sources() {
        let tmp = tempfile::Builder::new().prefix("solar-file-resolver-test").tempdir().unwrap();
        let root = tmp.path();
        write_files(root, &["lib/dep/X.sol"]);

        let sm = SourceMap::empty();
        let preloaded = sm.new_source_file(PathBuf::from("lib/dep/X.sol"), "").unwrap();
        let mut resolver = FileResolver::new(&sm);
        resolver.set_base_path(root);
        resolver.add_include_path(root.join("lib"));

        let resolved = resolver.resolve_file(Path::new("dep/X.sol"), Some(Path::new("src/A.sol")));
        assert!(Arc::ptr_eq(&resolved.unwrap(), &preloaded));
    }

    #[test]
    fn unnamed_source_imports_use_source_unit_names() {
        let tmp = tempfile::Builder::new().prefix("solar-file-resolver-test").tempdir().unwrap();
        let root = tmp.path();
        write_files(root, &["A.sol", "src/A.sol", "lib/A.sol"]);

        let sm = SourceMap::empty();
        let mut resolver = FileResolver::new(&sm);
        resolver.set_current_dir(root);
        resolver.add_import_remapping("src/=lib/".parse().unwrap());

        // Imports from standard input are remapped, unlike paths on the command line.
        for (path, expected) in [("src/A.sol", "lib/A.sol"), ("./A.sol", "A.sol")] {
            let resolved = resolver.resolve_file(Path::new(path), Some(Path::new(""))).unwrap();
            assert_eq!(resolved.name.as_real(), Some(root.join(expected).as_path()), "{path}");
        }
        let resolved = resolver.resolve_file(Path::new("src/A.sol"), None).unwrap();
        assert_eq!(resolved.name.as_real(), Some(root.join("src/A.sol").as_path()));
    }

    #[test]
    fn file_url_imports_load_from_disk() {
        let tmp = tempfile::Builder::new().prefix("solar-file-resolver-test").tempdir().unwrap();
        let root = tmp.path();
        write_files(root, &["A.sol"]);

        let sm = SourceMap::empty();
        let resolver = FileResolver::new(&sm);
        let url = format!("file://{}", root.join("A.sol").display());
        let resolved = resolver.resolve_file(Path::new(&url), Some(Path::new("B.sol"))).unwrap();
        assert_eq!(resolved.name.as_real(), Some(root.join("A.sol").as_path()));
    }
}

// ported-from: https://github.com/BenTheKush/solc_remapping_behavior_test
#[cfg(test)]
mod solang_import_resolution {
    use super::*;
    use std::collections::{HashMap, HashSet};

    struct FixtureFile {
        path: &'static str,
        imports: &'static [&'static str],
    }

    struct Scenario {
        name: &'static str,
        input: &'static str,
        remappings: &'static [&'static str],
        base_path: Option<&'static str>,
        include_paths: &'static [&'static str],
        should_resolve: bool,
    }

    struct Harness<'a> {
        _tmp: tempfile::TempDir,
        root: PathBuf,
        cwd: PathBuf,
        imports: HashMap<PathBuf, &'a [&'a str]>,
    }

    impl<'a> Harness<'a> {
        fn new(cwd: &str, files: &'a [FixtureFile]) -> Self {
            let tmp = tempfile::Builder::new()
                .prefix("solar-solang-import-resolution-test")
                .tempdir()
                .unwrap();
            let root = tmp.path().to_path_buf();
            let cwd = root.join(cwd);
            let mut imports = HashMap::default();
            for FixtureFile { path, imports: file_imports } in files {
                let path_on_disk = cwd.join(path);
                if let Some(parent) = path_on_disk.parent() {
                    std::fs::create_dir_all(parent).unwrap();
                }
                std::fs::write(path_on_disk, "").unwrap();
                let key = cwd.join(path).strip_prefix(&root).unwrap().to_path_buf();
                imports.insert(key, *file_imports);
            }
            Self { _tmp: tmp, root, cwd, imports }
        }

        fn run(&self, scenario: &Scenario) -> Result<(), ResolveError> {
            let sm = SourceMap::empty();
            sm.set_roots(Some(self.cwd.clone()), Vec::new(), None);
            let mut file_resolver = FileResolver::new(&sm);
            file_resolver.set_current_dir(&self.cwd);
            if let Some(base_path) = scenario.base_path {
                file_resolver.set_base_path(&self.cwd.join(base_path));
            }
            for include_path in scenario.include_paths {
                file_resolver.add_include_path(self.cwd.join(include_path));
            }
            for remapping in scenario.remappings {
                file_resolver.add_import_remapping(remapping.parse().unwrap());
            }

            let root_file = file_resolver.resolve_file(Path::new(scenario.input), None)?;
            let mut stack = vec![root_file];
            let mut seen = HashSet::new();
            while let Some(file) = stack.pop() {
                let path = file.name.as_real().unwrap();
                if !seen.insert(path.to_path_buf()) {
                    continue;
                }

                let key = path.strip_prefix(&self.root).unwrap();
                for import in self.imports.get(key).copied().unwrap_or_default() {
                    stack.push(file_resolver.resolve_file(Path::new(import), Some(path))?);
                }
            }
            Ok(())
        }
    }

    fn check_solang_import_resolution_scenarios(
        cwd: &str,
        files: &[FixtureFile],
        scenarios: &[Scenario],
    ) {
        let harness = Harness::new(cwd, files);
        for scenario in scenarios {
            let result = harness.run(scenario);
            assert_eq!(
                result.is_ok(),
                scenario.should_resolve,
                "{}: expected should_resolve={}, got {result:?}",
                scenario.name,
                scenario.should_resolve
            );
        }
    }

    #[test]
    fn solang_import_resolution_corpus() {
        check_solang_import_resolution_scenarios(
            "01_solang_remap_target",
            &[
                FixtureFile { path: "contracts/Contract.sol", imports: &["lib/Lib.sol"] },
                FixtureFile { path: "resources/node_modules/lib/Lib.sol", imports: &[] },
            ],
            &[
                Scenario {
                    name: "01.1 no remapping",
                    input: "contracts/Contract.sol",
                    remappings: &[],
                    base_path: None,
                    include_paths: &[],
                    should_resolve: false,
                },
                Scenario {
                    name: "01.2 no base path or include path",
                    input: "contracts/Contract.sol",
                    remappings: &["lib=node_modules/lib"],
                    base_path: None,
                    include_paths: &[],
                    should_resolve: false,
                },
                Scenario {
                    name: "01.3 incomplete include paths",
                    input: "contracts/Contract.sol",
                    remappings: &["lib=node_modules/lib"],
                    base_path: Some("."),
                    include_paths: &[],
                    should_resolve: false,
                },
                Scenario {
                    name: "01.4 incorrect include paths",
                    input: "contracts/Contract.sol",
                    remappings: &["lib=node_modules/lib"],
                    base_path: Some("."),
                    include_paths: &["resources/node_modules"],
                    should_resolve: false,
                },
                Scenario {
                    name: "01.5 correct configuration",
                    input: "contracts/Contract.sol",
                    remappings: &["lib=node_modules/lib"],
                    base_path: Some("."),
                    include_paths: &["resources"],
                    should_resolve: true,
                },
            ],
        );

        check_solang_import_resolution_scenarios(
            "02_solang_incorrect_direct_imports",
            &[
                FixtureFile { path: "Ambiguous.sol", imports: &[] },
                FixtureFile {
                    path: "contracts/Ambiguous.sol",
                    imports: &["Error: contracts/Ambiguous.sol should not be imported"],
                },
                FixtureFile { path: "contracts/Contract.sol", imports: &["Ambiguous.sol"] },
                FixtureFile {
                    path: "resources/node_modules/lib/Ambiguous.sol",
                    imports: &[
                        "Error: resources/node_modules/lib/Ambiguous.sol should not be imported",
                    ],
                },
                FixtureFile { path: "resources/node_modules/lib/Lib.sol", imports: &[] },
            ],
            &[
                Scenario {
                    name: "02.1 direct import default base path",
                    input: "contracts/Contract.sol",
                    remappings: &[],
                    base_path: None,
                    include_paths: &[],
                    should_resolve: true,
                },
                Scenario {
                    name: "02.2 direct import explicit base path",
                    input: "contracts/Contract.sol",
                    remappings: &[],
                    base_path: Some("."),
                    include_paths: &[],
                    should_resolve: true,
                },
            ],
        );

        check_solang_import_resolution_scenarios(
            "03_ambiguous_imports_should_fail",
            &[
                FixtureFile { path: "Ambiguous.sol", imports: &["This should not be imported"] },
                FixtureFile { path: "contracts/Ambiguous.sol", imports: &[] },
                FixtureFile {
                    path: "contracts/Contract.sol",
                    imports: &["lib/Lib.sol", "Ambiguous.sol"],
                },
                FixtureFile { path: "resources/node_modules/lib/Ambiguous.sol", imports: &[] },
                FixtureFile { path: "resources/node_modules/lib/Lib.sol", imports: &[] },
            ],
            &[
                Scenario {
                    name: "03.1 ambiguous imports should fail",
                    input: "contracts/Contract.sol",
                    remappings: &["lib=resources/node_modules/lib"],
                    base_path: Some("."),
                    include_paths: &["contracts"],
                    should_resolve: false,
                },
                Scenario {
                    name: "03.2 import order resources then root",
                    input: "contracts/Contract.sol",
                    remappings: &["lib=resources/node_modules/lib"],
                    base_path: Some("."),
                    include_paths: &["resources/node_modules/lib", "."],
                    should_resolve: false,
                },
                Scenario {
                    name: "03.3 import order root then resources",
                    input: "contracts/Contract.sol",
                    remappings: &["lib=resources/node_modules/lib"],
                    base_path: Some("."),
                    include_paths: &[".", "resources/node_modules/lib"],
                    should_resolve: false,
                },
            ],
        );

        check_solang_import_resolution_scenarios(
            "04_multiple_map_path_segments",
            &[
                FixtureFile { path: "contracts/Contract.sol", imports: &["lib/nested/Lib.sol"] },
                FixtureFile { path: "resources/node_modules/lib/nested/Lib.sol", imports: &[] },
            ],
            &[Scenario {
                name: "04.1 multiple import mapping segments",
                input: "contracts/Contract.sol",
                remappings: &["lib/nested=resources/node_modules/lib/nested"],
                base_path: Some("."),
                include_paths: &[],
                should_resolve: true,
            }],
        );

        check_solang_import_resolution_scenarios(
            "05_import_path_order_should_not_matter",
            &[
                FixtureFile { path: "contracts/Contract.sol", imports: &["A.sol"] },
                FixtureFile { path: "contracts/nested1/A.sol", imports: &[] },
                FixtureFile { path: "contracts/nested2/A.sol", imports: &[] },
            ],
            &[
                Scenario {
                    name: "05.1 include order nested1 then nested2",
                    input: "contracts/Contract.sol",
                    remappings: &[],
                    base_path: None,
                    include_paths: &["contracts/nested1", "contracts/nested2"],
                    should_resolve: false,
                },
                Scenario {
                    name: "05.2 include order nested2 then nested1",
                    input: "contracts/Contract.sol",
                    remappings: &[],
                    base_path: None,
                    include_paths: &["contracts/nested2", "contracts/nested1"],
                    should_resolve: false,
                },
            ],
        );

        check_solang_import_resolution_scenarios(
            "06_redundant_remaps",
            &[
                FixtureFile {
                    path: "contracts/Contract.sol",
                    imports: &["node_modules/lib/Lib.sol"],
                },
                FixtureFile { path: "resources/node_modules/lib/Lib.sol", imports: &[] },
            ],
            &[
                Scenario {
                    name: "06.1 multiple remappings",
                    input: "contracts/Contract.sol",
                    remappings: &[
                        "node_modules=resources/node_modules",
                        "node_modules=node_modules",
                    ],
                    base_path: Some("resources"),
                    include_paths: &[],
                    should_resolve: true,
                },
                Scenario {
                    name: "06.2 multiple remappings reversed",
                    input: "contracts/Contract.sol",
                    remappings: &[
                        "node_modules=node_modules",
                        "node_modules=resources/node_modules",
                    ],
                    base_path: Some("resources"),
                    include_paths: &[],
                    should_resolve: false,
                },
                Scenario {
                    name: "06.3 multiple remappings last wins",
                    input: "contracts/Contract.sol",
                    remappings: &[
                        "node_modules=node_modules",
                        "node_modules=resources/node_modules",
                        "node_modules=node_modules",
                    ],
                    base_path: Some("resources"),
                    include_paths: &[],
                    should_resolve: true,
                },
            ],
        );
    }

    #[test]
    fn snapshots_base_path() {
        let sm = SourceMap::empty();
        sm.set_roots(Some(PathBuf::from("base")), Vec::new(), None);
        let resolver = FileResolver::new(&sm);
        sm.set_roots(None, Vec::new(), None);
        assert_eq!(resolver.try_base_path(), Some(Path::new("base")));
    }
}