Skip to main content

solar_interface/source_map/
file_resolver.rs

1//! File resolver.
2//!
3//! Modified from [`solang`](https://github.com/hyperledger/solang/blob/0f032dcec2c6e96797fd66fa0175a02be0aba71c/src/file_resolver.rs).
4//!
5//! Follows solc's [import path resolution](https://docs.soliditylang.org/en/latest/path-resolution.html):
6//! an import path becomes a source unit name, which is looked up among the loaded sources and then
7//! on disk under the base path and the include paths.
8
9use super::SourceFile;
10use crate::{BytePos, Session, SourceMap};
11use itertools::Itertools;
12use solar_config::{CompileOpts, ImportRemapping};
13use solar_data_structures::smallvec::{SmallVec, smallvec};
14use std::{
15    borrow::Cow,
16    io,
17    path::{Component, Path, PathBuf, Prefix},
18    sync::{Arc, OnceLock},
19};
20
21/// An error that occurred while resolving a path.
22#[derive(Debug, thiserror::Error)]
23pub enum ResolveError {
24    #[error("couldn't read stdin: {0}")]
25    ReadStdin(#[source] io::Error),
26    #[error("couldn't read {0}: {1}")]
27    ReadFile(PathBuf, #[source] io::Error),
28    #[error("file {0} not found")]
29    NotFound(PathBuf),
30    #[error("multiple files match {}: {}", .0.display(), .1.iter().map(|path| path.display()).format(", "))]
31    MultipleMatches(PathBuf, Vec<PathBuf>),
32}
33
34/// Performs file resolution by applying import paths and mappings.
35#[derive(derive_more::Debug)]
36pub struct FileResolver<'a> {
37    #[debug(skip)]
38    source_map: &'a SourceMap,
39
40    /// Include paths.
41    include_paths: Vec<PathBuf>,
42    /// Import remappings.
43    remappings: Vec<ImportRemapping>,
44    /// Base path for source unit names.
45    base_path: Option<PathBuf>,
46
47    /// Custom current directory.
48    custom_current_dir: Option<PathBuf>,
49    /// [`std::env::current_dir`] cache. Unused if the current directory is set manually.
50    env_current_dir: OnceLock<Option<PathBuf>>,
51    /// The start of the last source loaded before the first import that searches the disk.
52    last_input: OnceLock<Option<BytePos>>,
53}
54
55impl<'a> FileResolver<'a> {
56    /// Creates a new file resolver.
57    pub fn new(source_map: &'a SourceMap) -> Self {
58        let base_path = source_map.roots().as_ref().and_then(|roots| roots.base_path.clone());
59        Self {
60            source_map,
61            include_paths: Vec::new(),
62            remappings: Vec::new(),
63            base_path,
64            custom_current_dir: None,
65            env_current_dir: OnceLock::new(),
66            last_input: OnceLock::new(),
67        }
68    }
69
70    /// Configures the file resolver from a session.
71    pub fn configure_from_sess(&mut self, sess: &Session) {
72        self.configure_from_opts(&sess.opts);
73    }
74
75    /// Configures the file resolver from compiler options.
76    ///
77    /// Relative base and include paths are relative to the current directory.
78    pub fn configure_from_opts(&mut self, opts: &CompileOpts) {
79        self.add_include_paths(opts.include_paths.iter().cloned());
80        self.add_import_remappings(opts.import_remappings.iter().cloned());
81        if let Some(base_path) = &opts.base_path {
82            self.base_path = Some(self.absolute(base_path));
83        }
84    }
85
86    /// Clears the internal state.
87    pub fn clear(&mut self) {
88        self.include_paths.clear();
89        self.remappings.clear();
90        self.base_path = None;
91        self.custom_current_dir = None;
92        self.env_current_dir.take();
93        self.last_input.take();
94    }
95
96    /// Sets the current directory.
97    ///
98    /// # Panics
99    ///
100    /// Panics if `current_dir` is not an absolute path.
101    #[track_caller]
102    pub fn set_current_dir(&mut self, current_dir: &Path) {
103        if !current_dir.is_absolute() {
104            panic!("current_dir must be an absolute path");
105        }
106        self.custom_current_dir = Some(current_dir.to_path_buf());
107    }
108
109    /// Sets the base path.
110    ///
111    /// # Panics
112    ///
113    /// Panics if `base_path` is not an absolute path.
114    #[track_caller]
115    pub fn set_base_path(&mut self, base_path: &Path) {
116        if !base_path.is_absolute() {
117            panic!("base_path must be an absolute path");
118        }
119        self.base_path = Some(base_path.to_path_buf());
120    }
121
122    /// Adds include paths.
123    ///
124    /// Relative paths are relative to the current directory.
125    pub fn add_include_paths(&mut self, paths: impl IntoIterator<Item = PathBuf>) {
126        for path in paths {
127            self.add_include_path(path);
128        }
129    }
130
131    /// Adds an include path.
132    ///
133    /// Relative paths are relative to the current directory.
134    pub fn add_include_path(&mut self, path: PathBuf) {
135        let path = self.absolute(&path);
136        self.include_paths.push(path)
137    }
138
139    /// Adds import remappings.
140    pub fn add_import_remappings(&mut self, remappings: impl IntoIterator<Item = ImportRemapping>) {
141        self.remappings.extend(remappings);
142    }
143
144    /// Adds an import remapping.
145    pub fn add_import_remapping(&mut self, remapping: ImportRemapping) {
146        self.remappings.push(remapping);
147    }
148
149    /// Returns the source map.
150    pub fn source_map(&self) -> &'a SourceMap {
151        self.source_map
152    }
153
154    /// Returns the current directory, or `.` if it could not be resolved.
155    pub fn current_dir(&self) -> &Path {
156        self.try_current_dir().unwrap_or(Path::new("."))
157    }
158
159    /// Returns the current directory, if resolved successfully.
160    pub fn try_current_dir(&self) -> Option<&Path> {
161        self.custom_current_dir.as_deref().or_else(|| self.env_current_dir())
162    }
163
164    /// Returns the base path for import resolution, which defaults to the current directory.
165    pub fn try_base_path(&self) -> Option<&Path> {
166        self.base_path.as_deref().or_else(|| self.try_current_dir())
167    }
168
169    fn env_current_dir(&self) -> Option<&Path> {
170        self.env_current_dir
171            .get_or_init(|| {
172                std::env::current_dir()
173                    .inspect_err(|e| debug!("failed to get current_dir: {e}"))
174                    .ok()
175            })
176            .as_deref()
177    }
178
179    /// Canonicalizes a path using [`Self::current_dir`].
180    pub fn canonicalize(&self, path: &Path) -> io::Result<PathBuf> {
181        self.canonicalize_unchecked(&self.make_absolute(path))
182    }
183
184    fn canonicalize_unchecked(&self, path: &Path) -> io::Result<PathBuf> {
185        self.source_map.file_loader().canonicalize_path(path)
186    }
187
188    /// Normalizes a path, removing `.` segments and applying `..` segments lexically.
189    ///
190    /// Does not perform I/O.
191    pub fn normalize<'b>(&self, path: &'b Path) -> Cow<'b, Path> {
192        Cow::Owned(lexical_normalize(path))
193    }
194
195    /// Makes the path absolute by joining it with the current directory.
196    ///
197    /// Does not perform I/O.
198    pub fn make_absolute<'b>(&self, path: &'b Path) -> Cow<'b, Path> {
199        if path.is_absolute() {
200            Cow::Borrowed(path)
201        } else if let Some(current_dir) = self.try_current_dir() {
202            Cow::Owned(current_dir.join(path))
203        } else {
204            Cow::Borrowed(path)
205        }
206    }
207
208    fn absolute(&self, path: &Path) -> PathBuf {
209        absolute_path(self.try_current_dir(), path)
210    }
211
212    /// Returns the normalized filesystem paths that may satisfy `path`, in resolution order.
213    ///
214    /// This does not perform I/O or consult the source map. A returned path may remain relative if
215    /// the resolver has no current directory. Use [`Self::resolve_file`] for exact resolution,
216    /// including preloaded source-unit names and ambiguity detection.
217    pub fn candidate_paths(&self, path: &Path, parent: Option<&Path>) -> Vec<PathBuf> {
218        let Some(parent) = parent else { return vec![self.absolute(path)] };
219        let unit = self.import_source_unit_name(path, parent);
220        self.search_paths(&unit).iter().map(|candidate| self.absolute(candidate)).unique().collect()
221    }
222
223    /// Applies import remappings in the context of the source unit name of `parent`.
224    pub fn remap_import_path<'b>(&self, path: &'b Path, parent: Option<&Path>) -> Cow<'b, Path> {
225        match parent {
226            Some(parent) => self.remap_import(path, &self.importer_names(parent)),
227            None => self.remap_path(path, None),
228        }
229    }
230
231    /// Resolves an import path.
232    ///
233    /// `parent` is the path of the file that contains the import. Pass an empty path for a source
234    /// without one, like standard input. Without a parent, `path` is loaded directly, like a path
235    /// on the command line, relative to the current directory.
236    #[instrument(level = "trace", skip_all, fields(path = %path.display()))]
237    pub fn resolve_file(
238        &self,
239        path: &Path,
240        parent: Option<&Path>,
241    ) -> Result<Arc<SourceFile>, ResolveError> {
242        let file = match parent {
243            Some(parent) => self.resolve_source_unit(path, parent)?,
244            None => self.try_file(path)?,
245        };
246        file.ok_or_else(|| ResolveError::NotFound(path.into()))
247    }
248
249    fn resolve_source_unit(
250        &self,
251        path: &Path,
252        parent: &Path,
253    ) -> Result<Option<Arc<SourceFile>>, ResolveError> {
254        let unit = self.import_source_unit_name(path, parent);
255        if let Some(file) = self.get_source_unit(&unit) {
256            return Ok(Some(file));
257        }
258        // An empty base path in the source map means that file names are source unit names, as in
259        // Standard JSON.
260        let roots = self.source_map().roots();
261        if roots.as_ref().and_then(|roots| roots.base_path.as_deref()) == Some(Path::new("")) {
262            return self.read_source_unit(path, &unit);
263        }
264
265        let last_input = *self
266            .last_input
267            .get_or_init(|| self.source_map().files().last().map(|file| file.start_pos));
268
269        // Like solc, prefer an input file with this source unit name over searching the disk.
270        // Files loaded for other imports don't count, so the result doesn't depend on their order.
271        if let Some(last_input) = last_input
272            && !unit.has_root()
273        {
274            let name = lexical_normalize(&unit);
275            let input = self.roots().find_map(|root| {
276                let path = generic_path(lexical_normalize(&root.join(&unit)));
277                let file = self.source_map().get_file(&path)?;
278                (file.start_pos <= last_input && self.source_unit_name(&path) == name)
279                    .then_some(file)
280            });
281            if input.is_some() {
282                return Ok(input);
283            }
284        }
285
286        let mut found = SmallVec::<[_; 1]>::new();
287        for candidate in self.search_paths(&unit) {
288            // Quick deduplication when include paths are duplicated.
289            if let Some(file) = self.load(&candidate)?
290                && !found.iter().any(|f| Arc::ptr_eq(f, &file))
291            {
292                found.push(file);
293            }
294        }
295        match found.len() {
296            0 | 1 => Ok(found.pop()),
297            _ => {
298                let paths = found.iter().map(|file| real_path(file).to_path_buf()).collect();
299                Err(ResolveError::MultipleMatches(path.into(), paths))
300            }
301        }
302    }
303
304    /// Reads a source unit through the file loader, like solc's file reader, and names it by the
305    /// source unit name. This is how Standard JSON uses its read callback.
306    fn read_source_unit(
307        &self,
308        path: &Path,
309        unit: &Path,
310    ) -> Result<Option<Arc<SourceFile>>, ResolveError> {
311        // Read inside the source map's insertion, so that concurrent imports of the same name
312        // wait for one read. Spellings of the name that differ only in `.` and `..` segments or
313        // repeated separators name one source, so name it by a normalized spelling.
314        let mut error = None;
315        let file =
316            self.source_map().new_source_file_with(normalize_unit(unit).into(), || {
317                match self.read_roots(path, unit) {
318                    Ok(Some(src)) => Ok(src),
319                    Ok(None) => Err(io::ErrorKind::NotFound.into()),
320                    Err(e) => Err(io::Error::other(error.insert(e).to_string())),
321                }
322            });
323        match file {
324            Ok(file) => Ok(Some(file)),
325            Err(_) if let Some(error) = error => Err(error),
326            Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
327            Err(e) => Err(ResolveError::ReadFile(unit.into(), e)),
328        }
329    }
330
331    /// Reads `unit` from each root once through the file loader, like solc's file reader.
332    fn read_roots(&self, path: &Path, unit: &Path) -> Result<Option<String>, ResolveError> {
333        let loader = self.source_map().file_loader();
334        // Ask for a normalized name, so that the result doesn't depend on which spelling of it is
335        // read first. Without a base path or include paths, keep a `file://` prefix, like libsolc.
336        // Otherwise strip it, like solc's file reader.
337        let unit = if self.roots().all(|root| root.as_os_str().is_empty()) {
338            unit
339        } else {
340            strip_file_url(unit)
341        };
342        let candidates = if unit.has_root() {
343            vec![normalize_unit(unit)]
344        } else {
345            self.roots().map(|root| normalize_unit(&root.join(unit))).collect()
346        };
347        let mut found = SmallVec::<[(PathBuf, String); 1]>::new();
348        let mut read_error = None;
349        for candidate in candidates {
350            let Ok(path) = loader.canonicalize_path(&candidate) else { continue };
351            if found.iter().any(|(found, _)| *found == path) {
352                continue;
353            }
354            match loader.load_file(&path) {
355                Ok(src) => found.push((path, src)),
356                // A read callback need not serve every root.
357                Err(e) => {
358                    read_error.get_or_insert(ResolveError::ReadFile(path, e));
359                }
360            }
361        }
362        match found.len() {
363            0 => read_error.map_or(Ok(None), Err),
364            1 => Ok(found.pop().map(|(_, src)| src)),
365            _ => {
366                let paths = found.into_iter().map(|(path, _)| path).collect();
367                Err(ResolveError::MultipleMatches(path.into(), paths))
368            }
369        }
370    }
371
372    /// Returns the source unit name that `path` refers to when imported from `parent`.
373    fn import_source_unit_name<'b>(&self, path: &'b Path, parent: &Path) -> Cow<'b, Path> {
374        let names = self.importer_names(parent);
375        // Only paths starting with `./` or `../` are relative to the importing source unit;
376        // `import "b.sol";` is looked up in the base path and include paths.
377        let path = if path.starts_with("./") || path.starts_with("../") {
378            // Unlike solc, use the importing file's path relative to the base path, which is
379            // absolute outside of it, as build tools such as Foundry name those files.
380            let base_relative = names.last().unwrap();
381            Cow::Owned(join_relative_import(base_relative, path))
382        } else {
383            Cow::Borrowed(path)
384        };
385        match self.remap_import(&path, &names) {
386            Cow::Owned(remapped) => Cow::Owned(remapped),
387            Cow::Borrowed(_) => path,
388        }
389    }
390
391    /// Returns the names of the importing file `parent` that remapping contexts match: its source
392    /// unit name and, unlike solc, its path relative to the base path if that differs, which build
393    /// tools such as Foundry use for files outside of it.
394    fn importer_names<'b>(&self, parent: &'b Path) -> SmallVec<[&'b Path; 2]> {
395        // An empty base path in the source map means that file names are source unit names, as in
396        // Standard JSON.
397        let roots = self.source_map().roots();
398        if roots.as_ref().and_then(|roots| roots.base_path.as_deref()) == Some(Path::new("")) {
399            return smallvec![parent];
400        }
401        let name = self.source_unit_name(parent);
402        let base_relative = strip_root(parent, self.try_base_path());
403        std::iter::once(name).chain((name != base_relative).then_some(base_relative)).collect()
404    }
405
406    /// Applies import remappings in the contexts of the importing file's names.
407    fn remap_import<'b>(&self, path: &'b Path, contexts: &[&Path]) -> Cow<'b, Path> {
408        let remapped = remap_in_contexts(&self.remappings, path, contexts);
409        if remapped != path {
410            trace!(remapped=%remapped.display());
411        }
412        remapped
413    }
414
415    /// Returns the base path, or an empty path without one, followed by the include paths.
416    fn roots(&self) -> impl Iterator<Item = &Path> {
417        let base_path = self.try_base_path().unwrap_or(Path::new(""));
418        std::iter::once(base_path).chain(self.include_paths.iter().map(PathBuf::as_path))
419    }
420
421    /// Returns the source unit name of a loaded file, like solc does for command-line paths.
422    fn source_unit_name<'b>(&self, path: &'b Path) -> &'b Path {
423        source_unit_name(path, self.roots(), self.try_current_dir())
424    }
425
426    /// Returns the loaded source with the given source unit name.
427    fn get_source_unit(&self, unit: &Path) -> Option<Arc<SourceFile>> {
428        let source_map = self.source_map();
429        source_map.get_file(unit).or_else(|| source_map.get_file(normalize_unit(unit)))
430    }
431
432    /// Returns the paths that the host filesystem loader looks up for a source unit name.
433    fn search_paths<'b>(&self, unit: &'b Path) -> SmallVec<[Cow<'b, Path>; 2]> {
434        let unit = strip_file_url(unit);
435        // Unlike solc, look up absolute paths as is, even with a base path.
436        if unit.has_root() {
437            // A path with a root but no drive, like `/a.sol` on Windows, is on the base path's
438            // drive.
439            let rooted = match self.try_base_path() {
440                Some(base_path) if !unit.is_absolute() => Cow::Owned(base_path.join(unit)),
441                _ => Cow::Borrowed(unit),
442            };
443            return smallvec![rooted];
444        }
445        self.roots().map(|root| Cow::Owned(root.join(unit))).collect()
446    }
447
448    /// Applies the import path mappings to `path`.
449    // Reference: <https://github.com/argotorg/solidity/blob/e202d30db8e7e4211ee973237ecbe485048aae97/libsolidity/interface/ImportRemapper.cpp#L32>
450    pub fn remap_path<'b>(&self, path: &'b Path, parent: Option<&Path>) -> Cow<'b, Path> {
451        let remapped = apply_import_remappings(&self.remappings, path, parent);
452        if remapped != path {
453            trace!(remapped=%remapped.display());
454        }
455        remapped
456    }
457
458    /// Loads stdin into the source map.
459    pub fn load_stdin(&self) -> Result<Arc<SourceFile>, ResolveError> {
460        self.source_map().load_stdin().map_err(ResolveError::ReadStdin)
461    }
462
463    /// Returns the source file with the given path, if it exists, without loading it.
464    pub fn get_file(&self, path: &Path) -> Option<Arc<SourceFile>> {
465        self.source_map()
466            .get_file(path)
467            .or_else(|| self.source_map().get_file(generic_path(self.absolute(path))))
468    }
469
470    /// Loads `path` into the source map. Returns `None` if the file doesn't exist.
471    ///
472    /// Relative paths are relative to the current directory.
473    #[instrument(level = "debug", skip_all, fields(path = %path.display()))]
474    pub fn try_file(&self, path: &Path) -> Result<Option<Arc<SourceFile>>, ResolveError> {
475        if let Some(file) = self.source_map().get_file(path) {
476            return Ok(Some(file));
477        }
478        self.load(&self.make_absolute(path))
479    }
480
481    /// Loads the file at `path`, named by its normalized path.
482    fn load(&self, path: &Path) -> Result<Option<Arc<SourceFile>>, ResolveError> {
483        let path = generic_path(lexical_normalize(path));
484        // A file inside the base path may be loaded under its relative name, like the ones a build
485        // tool preloads.
486        let source_map = self.source_map();
487        if let Some(file) = source_map
488            .get_file(&path)
489            .or_else(|| source_map.get_file(strip_root(&path, self.try_base_path())))
490        {
491            return Ok(Some(file));
492        }
493        // Check that the file exists. Its name keeps symbolic links, like solc.
494        let Ok(canonical) = self.canonicalize_unchecked(&path) else {
495            trace!(path=%path.display(), "not found");
496            return Ok(None);
497        };
498        self.source_map()
499            .load_file_with_name(path.into(), &canonical)
500            .map(Some)
501            .map_err(|e| ResolveError::ReadFile(canonical, e))
502    }
503}
504
505/// Applies `remappings` to `path` using the same selection rules as [`FileResolver`].
506pub fn apply_import_remappings<'a>(
507    remappings: &[ImportRemapping],
508    path: &'a Path,
509    parent: Option<&Path>,
510) -> Cow<'a, Path> {
511    remap_in_contexts(remappings, path, &[parent.unwrap_or(Path::new(""))])
512}
513
514/// Like [`apply_import_remappings`], but a remapping applies if its context matches any of
515/// `contexts`.
516fn remap_in_contexts<'a>(
517    remappings: &[ImportRemapping],
518    path: &'a Path,
519    contexts: &[&Path],
520) -> Cow<'a, Path> {
521    let contexts = contexts.iter().map(|context| context.to_string_lossy()).collect_vec();
522    let contexts = contexts.iter().map(|context| sanitize_path(context)).collect_vec();
523
524    let mut longest_prefix = 0;
525    let mut longest_context = 0;
526    let mut best_match_target = None;
527    let path_text = path.to_string_lossy();
528    let path_text = sanitize_path(&path_text);
529    let mut unprefixed_path = &*path_text;
530    for ImportRemapping { context, prefix, path: target } in remappings {
531        let context = &*sanitize_path(context);
532        let prefix = &*sanitize_path(prefix);
533
534        // Skip if current context is closer.
535        if context.len() < longest_context {
536            continue;
537        }
538        // Skip if current context is not a prefix of the context.
539        if !contexts.iter().any(|context_path| context_path.starts_with(context)) {
540            continue;
541        }
542        // Skip if we already have a closer prefix match.
543        if prefix.len() < longest_prefix && context.len() == longest_context {
544            continue;
545        }
546        // Skip if the prefix does not match.
547        let Some(up) = path_text.strip_prefix(prefix) else {
548            continue;
549        };
550        longest_context = context.len();
551        longest_prefix = prefix.len();
552        best_match_target = Some(sanitize_path(target));
553        unprefixed_path = up;
554    }
555    if let Some(best_match_target) = best_match_target {
556        Cow::Owned(PathBuf::from(format!("{best_match_target}{unprefixed_path}")))
557    } else {
558        Cow::Borrowed(path)
559    }
560}
561
562/// Joins the components of `path` with `/`, like boost's `generic_string`.
563fn generic_path(path: PathBuf) -> PathBuf {
564    // `/` is not a separator after a verbatim `\\?\` prefix.
565    #[cfg(windows)]
566    if !matches!(path.components().next(), Some(Component::Prefix(p)) if p.kind().is_verbatim())
567        && let Some(s) = path.to_str()
568        && let Cow::Owned(s) = sanitize_path(s)
569    {
570        return s.into();
571    }
572    path
573}
574
575fn sanitize_path(s: &str) -> Cow<'_, str> {
576    #[cfg(windows)]
577    {
578        if s.contains('\\') {
579            return Cow::Owned(s.replace('\\', "/"));
580        }
581    }
582    Cow::Borrowed(s)
583}
584
585/// Strips a `file://` prefix, which solc's file reader accepts.
586fn strip_file_url(path: &Path) -> &Path {
587    path.to_str().and_then(|s| s.strip_prefix("file://")).map_or(path, Path::new)
588}
589
590/// Joins `path` with the current directory, if any, and normalizes it.
591pub(crate) fn absolute_path(current_dir: Option<&Path>, path: &Path) -> PathBuf {
592    match current_dir {
593        Some(current_dir) if !path.is_absolute() => lexical_normalize(&current_dir.join(path)),
594        _ => lexical_normalize(path),
595    }
596}
597
598/// Strips the first root that strictly contains `path`.
599fn strip_root(path: &Path, roots: impl IntoIterator<Item: AsRef<Path>>) -> &Path {
600    roots
601        .into_iter()
602        .filter(|root| !root.as_ref().as_os_str().is_empty())
603        .find_map(|root| path.strip_prefix(root).ok().filter(|p| !p.as_os_str().is_empty()))
604        .unwrap_or(path)
605}
606
607/// Returns the source unit name of a file loaded from disk, like solc does for command-line paths:
608/// its path relative to the first root that contains it, without the current directory's drive.
609pub(crate) fn source_unit_name<'a>(
610    path: &'a Path,
611    roots: impl IntoIterator<Item: AsRef<Path>>,
612    current_dir: Option<&Path>,
613) -> &'a Path {
614    strip_current_drive(strip_root(path, roots), current_dir)
615}
616
617/// Drops the drive of a Windows path on the current directory's drive, like solc.
618fn strip_current_drive<'a>(path: &'a Path, current_dir: Option<&Path>) -> &'a Path {
619    if !cfg!(windows) {
620        return path;
621    }
622    let mut components = path.components();
623    if let Some(Component::Prefix(prefix)) = components.next()
624        && matches!(prefix.kind(), Prefix::Disk(_))
625        && current_dir.and_then(|dir| dir.components().next()) == Some(Component::Prefix(prefix))
626    {
627        return components.as_path();
628    }
629    path
630}
631
632/// Resolves a relative import against the source unit name of the importing file.
633///
634/// Only the import path is normalized; the importing name may contain `..` segments, or `//` in
635/// URLs, that are part of its identity.
636// Reference: <https://github.com/argotorg/solidity/blob/e202d30db8e7e4211ee973237ecbe485048aae97/libsolutil/CommonIO.cpp#L140>
637fn join_relative_import(parent: &Path, path: &Path) -> PathBuf {
638    let mut unit = parent.parent().unwrap_or(Path::new("")).to_path_buf();
639    for component in path.components() {
640        match component {
641            Component::CurDir => {}
642            Component::ParentDir => {
643                unit.pop();
644            }
645            component => unit.push(component),
646        }
647    }
648    unit
649}
650
651/// Removes `.` segments and applies `..` segments lexically, keeping the leading `..` segments of
652/// a relative path.
653fn lexical_normalize(path: &Path) -> PathBuf {
654    let mut normalized = PathBuf::new();
655    for component in path.components() {
656        match component {
657            Component::CurDir => {}
658            Component::ParentDir => {
659                if matches!(normalized.components().next_back(), Some(Component::Normal(_))) {
660                    normalized.pop();
661                } else if !normalized.has_root() {
662                    normalized.push(component);
663                }
664            }
665            component => normalized.push(component),
666        }
667    }
668    normalized
669}
670
671/// Normalizes a source unit name like [`lexical_normalize`], with `/` separators, keeping the `//`
672/// of a URL scheme.
673fn normalize_unit(unit: &Path) -> PathBuf {
674    if let Some(unit) = unit.to_str()
675        && let Some((scheme, rest)) = unit.split_once("://")
676        && !scheme.is_empty()
677        && !scheme.contains(['/', '\\'])
678    {
679        let rest = generic_path(lexical_normalize(Path::new(rest)));
680        return PathBuf::from(format!("{scheme}://{}", rest.display()));
681    }
682    generic_path(lexical_normalize(unit))
683}
684
685fn real_path(file: &SourceFile) -> &Path {
686    file.name.as_real().unwrap_or(Path::new(""))
687}
688
689#[cfg(test)]
690mod tests {
691    use super::*;
692
693    #[cfg(windows)]
694    #[test]
695    fn remapping_contexts_use_generic_windows_separators() {
696        let remappings = ["src:pkg/=lib/source/".parse().unwrap()];
697        let remapped = apply_import_remappings(
698            &remappings,
699            Path::new("pkg/Target.sol"),
700            Some(Path::new(r"src\nested\Main.sol")),
701        );
702
703        assert_eq!(remapped, Path::new("lib/source/Target.sol"));
704    }
705
706    #[cfg(windows)]
707    #[test]
708    fn names_drop_the_current_drive() {
709        let current_dir = Some(Path::new(r"C:\project"));
710        for (path, name) in [
711            ("C:/other/A.sol", "/other/A.sol"),
712            ("c:/other/A.sol", "/other/A.sol"),
713            ("D:/other/A.sol", "D:/other/A.sol"),
714            (r"\\server\share\A.sol", r"\\server\share\A.sol"),
715        ] {
716            assert_eq!(
717                strip_current_drive(Path::new(path), current_dir),
718                Path::new(name),
719                "{path}"
720            );
721        }
722    }
723
724    #[cfg(windows)]
725    #[test]
726    fn resolved_names_use_generic_windows_separators() {
727        let tmp = tempfile::Builder::new().prefix("solar-file-resolver-test").tempdir().unwrap();
728        let base_path = tmp.path().to_path_buf();
729        std::fs::create_dir_all(base_path.join("src")).unwrap();
730        for path in ["src/A.sol", "src/B.sol"] {
731            std::fs::write(base_path.join(path), "").unwrap();
732        }
733
734        let sm = SourceMap::empty();
735        let mut resolver = FileResolver::new(&sm);
736        resolver.set_current_dir(&base_path);
737        let a = resolver.resolve_file(Path::new(r"src\A.sol"), None).unwrap();
738        let b = resolver.resolve_file(Path::new("./B.sol"), a.name.as_real()).unwrap();
739
740        for (file, name) in [(a, "src/A.sol"), (b, "src/B.sol")] {
741            let path = file.name.as_real().unwrap().strip_prefix(&base_path).unwrap();
742            assert_eq!(path.to_str(), Some(name));
743        }
744    }
745
746    struct TestCase<'a> {
747        remappings: &'a [&'a str],
748        sources: &'a [Source<'a>],
749    }
750    struct Source<'a> {
751        path: &'a str,
752        // `<import string> => <resolved path>`
753        imports: &'a [&'a str],
754    }
755
756    fn run(test_case: &TestCase<'_>) {
757        static ONCE: std::sync::Once = std::sync::Once::new();
758        ONCE.call_once(|| {
759            tracing_subscriber::fmt::fmt()
760                .with_test_writer()
761                .with_max_level(tracing::level_filters::LevelFilter::TRACE)
762                .init();
763        });
764
765        let tmp = tempfile::Builder::new().prefix("solar-file-resolver-test").tempdir().unwrap();
766        let base_path = tmp.path().to_path_buf();
767
768        let sm = SourceMap::empty();
769        sm.set_roots(Some(base_path.clone()), Vec::new(), None);
770        for source in test_case.sources {
771            let path = base_path.join(source.path);
772            if let Some(parent) = path.parent() {
773                let parent = parent.to_str().unwrap();
774                std::fs::create_dir_all(parent).expect(parent);
775            }
776            std::fs::write(&path, "").expect(source.path);
777            sm.load_file(&path).expect(source.path);
778        }
779
780        let mut file_resolver = FileResolver::new(&sm);
781        for &remapping in test_case.remappings {
782            file_resolver.add_import_remapping(remapping.parse().expect(remapping));
783        }
784        for &Source { path, imports } in test_case.sources {
785            for (i, &import) in imports.iter().enumerate() {
786                let res = (|| -> Result<(), Box<dyn std::error::Error>> {
787                    let (import, expected) = import
788                        .split_once(" => ")
789                        .ok_or("import is not in the format <import string> => <resolved path>")?;
790                    let parent = base_path.join(path);
791                    let resolved = file_resolver.resolve_file(import.as_ref(), Some(&parent))?;
792                    let actual_full = resolved.name.as_real().ok_or("resolved file has no path")?;
793                    let actual = actual_full.strip_prefix(&base_path).ok().ok_or(
794                        "resolved file path is not a subpath of the base path (not absolute?)",
795                    )?;
796                    let actual =
797                        actual.to_str().ok_or("resolved file path is not a valid string")?;
798                    if actual != expected {
799                        return Err(format!(
800                            "did not resolve to the expected path ({actual} != {expected})",
801                        )
802                        .into());
803                    }
804                    Ok(())
805                })();
806                match res {
807                    Ok(()) => {}
808                    Err(e) => panic!("{path}:{i}: [{import}] {e}"),
809                }
810            }
811        }
812    }
813
814    // Taken from: https://github.com/argotorg/solidity/blob/32c8f080c4cc939df5a3c7ca5ad6b6144ee9aa66/test/libsolidity/Imports.cpp
815    #[test]
816    fn remappings() {
817        run(&TestCase {
818            remappings: &["s=s_1.4.6", "t=Tee"],
819            sources: &[
820                Source { path: "a", imports: &["s/s.sol => s_1.4.6/s.sol"] },
821                Source { path: "b", imports: &["t/tee.sol => Tee/tee.sol"] },
822                Source { path: "s_1.4.6/s.sol", imports: &[] },
823                Source { path: "Tee/tee.sol", imports: &[] },
824            ],
825        })
826    }
827
828    #[test]
829    fn context_dependent_remappings() {
830        run(&TestCase {
831            remappings: &["a:s=s_1.4.6", "b:s=s_1.4.7"],
832            sources: &[
833                Source { path: "a/a.sol", imports: &["s/s.sol => s_1.4.6/s.sol"] },
834                Source { path: "b/b.sol", imports: &["s/s.sol => s_1.4.7/s.sol"] },
835                Source { path: "s_1.4.6/s.sol", imports: &[] },
836                Source { path: "s_1.4.7/s.sol", imports: &[] },
837            ],
838        })
839    }
840
841    #[test]
842    fn context_dependent_remappings_ensure_default_and_module_preserved() {
843        run(&TestCase {
844            remappings: &[
845                "foo=vendor/foo_2.0.0",
846                "vendor/bar:foo=vendor/foo_1.0.0",
847                "bar=vendor/bar",
848            ],
849            sources: &[
850                Source {
851                    path: "main.sol",
852                    imports: &[
853                        "foo/foo.sol => vendor/foo_2.0.0/foo.sol",
854                        "bar/bar.sol => vendor/bar/bar.sol",
855                    ],
856                },
857                Source {
858                    path: "vendor/bar/bar.sol",
859                    imports: &["foo/foo.sol => vendor/foo_1.0.0/foo.sol"],
860                },
861                Source { path: "vendor/foo_1.0.0/foo.sol", imports: &[] },
862                Source { path: "vendor/foo_2.0.0/foo.sol", imports: &[] },
863            ],
864        })
865    }
866
867    #[test]
868    fn context_dependent_remappings_order_independent() {
869        let sources = &[
870            Source { path: "a/main.sol", imports: &["x/y/z/z.sol => d/z.sol"] },
871            Source { path: "a/b/main.sol", imports: &["x/y/z/z.sol => e/y/z/z.sol"] },
872            Source { path: "d/z.sol", imports: &[] },
873            Source { path: "e/y/z/z.sol", imports: &[] },
874        ];
875        run(&TestCase { remappings: &["a:x/y/z=d", "a/b:x=e"], sources });
876        run(&TestCase { remappings: &["a/b:x=e", "a:x/y/z=d"], sources });
877    }
878
879    #[test]
880    fn top_level_relative_path_uses_current_dir() {
881        let tmp = tempfile::Builder::new().prefix("solar-file-resolver-test").tempdir().unwrap();
882        let cwd = tmp.path().join("cwd");
883        let sibling = tmp.path().join("sibling");
884        let source = sibling.join("a.sol");
885        let import = sibling.join("b.sol");
886        std::fs::create_dir_all(&cwd).unwrap();
887        std::fs::create_dir_all(&sibling).unwrap();
888        std::fs::write(&source, "").unwrap();
889        std::fs::write(&import, "").unwrap();
890
891        let sm = SourceMap::empty();
892        sm.set_roots(Some(cwd.clone()), Vec::new(), None);
893        let mut file_resolver = FileResolver::new(&sm);
894        file_resolver.set_current_dir(&cwd);
895        let resolved = file_resolver.resolve_file(Path::new("../sibling/a.sol"), None).unwrap();
896
897        assert_eq!(resolved.name.as_real(), Some(source.as_path()));
898
899        let parent = resolved.name.as_real().unwrap();
900        let relative_import =
901            file_resolver.resolve_file(Path::new("./b.sol"), Some(parent)).unwrap();
902        assert_eq!(relative_import.name.as_real(), Some(import.as_path()));
903
904        let direct_import = file_resolver.resolve_file(Path::new("b.sol"), Some(parent));
905        assert!(
906            matches!(direct_import, Err(ResolveError::NotFound(path)) if path == Path::new("b.sol"))
907        );
908    }
909
910    #[test]
911    fn top_level_path_takes_precedence_over_remapping() {
912        let tmp = tempfile::Builder::new().prefix("solar-file-resolver-test").tempdir().unwrap();
913        let base_path = tmp.path().to_path_buf();
914        let direct = base_path.join("src/A.sol");
915        let remapped = base_path.join("lib/A.sol");
916        for path in [&direct, &remapped] {
917            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
918            std::fs::write(path, "").unwrap();
919        }
920
921        let sm = SourceMap::empty();
922        sm.set_roots(Some(base_path.clone()), Vec::new(), None);
923        let mut resolver = FileResolver::new(&sm);
924        resolver.set_current_dir(&base_path);
925        resolver.add_import_remapping("src/=lib/".parse().unwrap());
926
927        let resolved = resolver.resolve_file(Path::new("src/A.sol"), None).unwrap();
928
929        assert_eq!(resolved.name.as_real(), Some(direct.as_path()));
930        assert_eq!(resolver.candidate_paths(Path::new("src/A.sol"), None), vec![direct]);
931    }
932
933    #[test]
934    fn relative_import_from_virtual_source_uses_source_unit_name() {
935        let sm = SourceMap::empty();
936        sm.set_roots(Some(PathBuf::new()), Vec::new(), None);
937        let mut file_resolver = FileResolver::new(&sm);
938        file_resolver.set_current_dir(&std::env::current_dir().unwrap());
939        let imported = sm.new_source_file(PathBuf::from("B.sol"), "").unwrap();
940
941        let resolved = file_resolver.resolve_file(Path::new("./B.sol"), Some(Path::new("A.sol")));
942
943        assert!(Arc::ptr_eq(&resolved.unwrap(), &imported));
944    }
945
946    #[test]
947    fn direct_import_without_current_dir_uses_source_unit_name() {
948        use crate::source_map::FileLoader;
949
950        struct Loader;
951
952        impl FileLoader for Loader {
953            fn canonicalize_path(&self, path: &Path) -> io::Result<PathBuf> {
954                Ok(path.to_path_buf())
955            }
956
957            fn load_stdin(&self) -> io::Result<String> {
958                unreachable!()
959            }
960
961            fn load_file(&self, path: &Path) -> io::Result<String> {
962                assert_eq!(path, Path::new("B.sol"));
963                Ok(String::new())
964            }
965
966            fn load_binary_file(&self, _path: &Path) -> io::Result<Vec<u8>> {
967                unreachable!()
968            }
969        }
970
971        let sm = SourceMap::empty();
972        sm.set_file_loader(Loader);
973        let file_resolver = FileResolver::new(&sm);
974        file_resolver.env_current_dir.set(None).unwrap();
975
976        let resolved = file_resolver.resolve_file(Path::new("B.sol"), Some(Path::new("A.sol")));
977
978        assert_eq!(resolved.unwrap().name.as_real(), Some(Path::new("B.sol")));
979    }
980
981    #[test]
982    fn direct_import_reuses_preloaded_source_unit_name() {
983        let tmp = tempfile::Builder::new().prefix("solar-file-resolver-test").tempdir().unwrap();
984        let base_path = tmp.path().to_path_buf();
985        let source_path = base_path.join("src/B.sol");
986        std::fs::create_dir_all(source_path.parent().unwrap()).unwrap();
987        std::fs::write(&source_path, "contract B {}").unwrap();
988
989        let sm = SourceMap::empty();
990        sm.set_roots(Some(base_path.clone()), Vec::new(), None);
991        let imported = sm.new_source_file(PathBuf::from("src/B.sol"), "contract B {}").unwrap();
992        let mut file_resolver = FileResolver::new(&sm);
993        file_resolver.set_current_dir(&base_path);
994
995        let resolved =
996            file_resolver.resolve_file(Path::new("src/B.sol"), Some(Path::new("test/A.sol")));
997
998        assert!(Arc::ptr_eq(&resolved.unwrap(), &imported));
999    }
1000
1001    #[test]
1002    fn absolute_remapping_reuses_preloaded_source_unit_name() {
1003        let tmp = tempfile::Builder::new().prefix("solar-file-resolver-test").tempdir().unwrap();
1004        let base_path = tmp.path().to_path_buf();
1005        for path in ["lib/dep/Test.sol", "lib/dep/Base.sol"] {
1006            let path = base_path.join(path);
1007            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
1008            std::fs::write(path, "").unwrap();
1009        }
1010
1011        let sm = SourceMap::empty();
1012        sm.set_roots(Some(base_path.clone()), Vec::new(), None);
1013        let test = sm.new_source_file(PathBuf::from("lib/dep/Test.sol"), "").unwrap();
1014        let base = sm.new_source_file(PathBuf::from("lib/dep/Base.sol"), "").unwrap();
1015        let mut file_resolver = FileResolver::new(&sm);
1016        file_resolver.set_current_dir(&base_path);
1017        file_resolver.add_import_remapping(
1018            format!("dep/={}/", base_path.join("lib/dep").display()).parse().unwrap(),
1019        );
1020
1021        // `dep/Test.sol` remaps to an absolute path that names the preloaded `lib/dep/Test.sol`.
1022        let resolved = file_resolver
1023            .resolve_file(Path::new("dep/Test.sol"), Some(Path::new("test/A.t.sol")))
1024            .unwrap();
1025        assert!(Arc::ptr_eq(&resolved, &test));
1026
1027        // Its relative imports then resolve to the same copies as direct imports do.
1028        let parent = resolved.name.as_real().unwrap();
1029        let relative = file_resolver.resolve_file(Path::new("./Base.sol"), Some(parent)).unwrap();
1030        let direct = file_resolver
1031            .resolve_file(Path::new("dep/Base.sol"), Some(Path::new("test/A.t.sol")))
1032            .unwrap();
1033        assert!(Arc::ptr_eq(&relative, &base));
1034        assert!(Arc::ptr_eq(&direct, &base));
1035    }
1036
1037    #[test]
1038    fn candidate_paths_follow_remapping_and_search_order() {
1039        let tmp = tempfile::Builder::new().prefix("solar-file-resolver-test").tempdir().unwrap();
1040        let base_path = tmp.path().to_path_buf();
1041        let source = base_path.join("src/Main.sol");
1042
1043        let sm = SourceMap::empty();
1044        sm.set_roots(Some(base_path.clone()), Vec::new(), None);
1045        let mut resolver = FileResolver::new(&sm);
1046        resolver.set_current_dir(&base_path);
1047        resolver.add_include_path(base_path.join("vendor"));
1048        resolver.add_import_remapping("oz=packages/openzeppelin".parse().unwrap());
1049
1050        assert_eq!(
1051            resolver.candidate_paths(Path::new("oz/contracts/Token.sol"), Some(&source)),
1052            vec![
1053                base_path.join("packages/openzeppelin/contracts/Token.sol"),
1054                base_path.join("vendor/packages/openzeppelin/contracts/Token.sol"),
1055            ]
1056        );
1057    }
1058
1059    #[test]
1060    fn candidate_paths_resolve_relative_imports_from_importer() {
1061        let tmp = tempfile::Builder::new().prefix("solar-file-resolver-test").tempdir().unwrap();
1062        let base_path = tmp.path().to_path_buf();
1063        let source = base_path.join("src/nested/Main.sol");
1064
1065        let sm = SourceMap::empty();
1066        sm.set_roots(Some(base_path.clone()), Vec::new(), None);
1067        let mut resolver = FileResolver::new(&sm);
1068        resolver.set_current_dir(&base_path);
1069        resolver.add_include_path(base_path.join("vendor"));
1070        resolver.add_import_remapping("src:pkg/=packages/pkg/".parse().unwrap());
1071
1072        // Like solc, the include paths are searched for the source unit name too.
1073        assert_eq!(
1074            resolver.candidate_paths(Path::new("../Shared.sol"), Some(&source)),
1075            vec![base_path.join("src/Shared.sol"), base_path.join("vendor/src/Shared.sol")]
1076        );
1077    }
1078
1079    #[test]
1080    fn candidate_paths_apply_context_dependent_remappings() {
1081        let tmp = tempfile::Builder::new().prefix("solar-file-resolver-test").tempdir().unwrap();
1082        let base_path = tmp.path().to_path_buf();
1083
1084        let sm = SourceMap::empty();
1085        sm.set_roots(Some(base_path.clone()), Vec::new(), None);
1086        let mut resolver = FileResolver::new(&sm);
1087        resolver.set_current_dir(&base_path);
1088        resolver.add_import_remapping("src:pkg/=lib/source/".parse().unwrap());
1089        resolver.add_import_remapping("test:pkg/=lib/test/".parse().unwrap());
1090
1091        assert_eq!(
1092            resolver.candidate_paths(
1093                Path::new("pkg/Dependency.sol"),
1094                Some(&base_path.join("src/Main.sol")),
1095            ),
1096            vec![base_path.join("lib/source/Dependency.sol")]
1097        );
1098        assert_eq!(
1099            resolver.candidate_paths(
1100                Path::new("pkg/Dependency.sol"),
1101                Some(&base_path.join("test/Main.t.sol")),
1102            ),
1103            vec![base_path.join("lib/test/Dependency.sol")]
1104        );
1105    }
1106
1107    fn write_files(root: &Path, paths: &[&str]) {
1108        for path in paths {
1109            let path = root.join(path);
1110            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
1111            std::fs::write(path, "").unwrap();
1112        }
1113    }
1114
1115    #[test]
1116    fn top_level_path_ignores_base_path() {
1117        let tmp = tempfile::Builder::new().prefix("solar-file-resolver-test").tempdir().unwrap();
1118        let root = tmp.path();
1119        write_files(root, &["src/A.sol", "src/B.sol"]);
1120
1121        let sm = SourceMap::empty();
1122        sm.set_roots(Some(root.join("src")), Vec::new(), None);
1123        let mut resolver = FileResolver::new(&sm);
1124        resolver.set_current_dir(root);
1125
1126        let a = resolver.resolve_file(Path::new("src/A.sol"), None).unwrap();
1127        let b = resolver.resolve_file(Path::new("B.sol"), a.name.as_real()).unwrap();
1128        assert_eq!(a.name.as_real(), Some(root.join("src/A.sol").as_path()));
1129        assert_eq!(b.name.as_real(), Some(root.join("src/B.sol").as_path()));
1130        assert_eq!(sm.filename_for_diagnostics(&a.name).to_string(), "A.sol");
1131    }
1132
1133    #[test]
1134    fn include_paths_name_source_units() {
1135        let tmp = tempfile::Builder::new().prefix("solar-file-resolver-test").tempdir().unwrap();
1136        let root = tmp.path();
1137        write_files(root, &["src/A.sol", "lib/dep/C.sol", "lib/dep/D.sol"]);
1138
1139        let sm = SourceMap::empty();
1140        sm.set_roots(Some(root.join("src")), vec![root.join("lib")], None);
1141        let mut resolver = FileResolver::new(&sm);
1142        resolver.set_current_dir(root);
1143        // Relative base and include paths are relative to the current directory.
1144        resolver.configure_from_opts(&CompileOpts {
1145            base_path: Some("src".into()),
1146            include_paths: vec!["lib".into()],
1147            ..Default::default()
1148        });
1149
1150        let c = resolver.resolve_file(Path::new("dep/C.sol"), Some(&root.join("src/A.sol")));
1151        let c = c.unwrap();
1152        // The source unit name `dep/C.sol` resolves relative imports in the include path.
1153        let d = resolver.resolve_file(Path::new("./D.sol"), c.name.as_real()).unwrap();
1154        for (file, name) in [(c, "dep/C.sol"), (d, "dep/D.sol")] {
1155            assert_eq!(file.name.as_real(), Some(root.join("lib").join(name).as_path()));
1156            assert_eq!(sm.filename_for_diagnostics(&file.name).to_string(), name);
1157        }
1158    }
1159
1160    #[test]
1161    fn nested_include_paths_name_by_base_path() {
1162        let tmp = tempfile::Builder::new().prefix("solar-file-resolver-test").tempdir().unwrap();
1163        let root = tmp.path();
1164        write_files(root, &["src/A.sol", "lib/dep/C.sol"]);
1165
1166        let sm = SourceMap::empty();
1167        sm.set_roots(Some(root.to_path_buf()), vec![root.join("lib")], None);
1168        let mut resolver = FileResolver::new(&sm);
1169        resolver.add_include_path(root.join("lib"));
1170
1171        // solc names this file `dep/C.sol`, by its import path.
1172        let c = resolver.resolve_file(Path::new("dep/C.sol"), Some(&root.join("src/A.sol")));
1173        assert_eq!(sm.filename_for_diagnostics(&c.unwrap().name).to_string(), "lib/dep/C.sol");
1174    }
1175
1176    #[test]
1177    fn relative_imports_leave_include_paths() {
1178        let tmp = tempfile::Builder::new().prefix("solar-file-resolver-test").tempdir().unwrap();
1179        let root = tmp.path();
1180        write_files(root, &["Events/Event.sol", "Tokens/Token.sol"]);
1181
1182        let sm = SourceMap::empty();
1183        let mut resolver = FileResolver::new(&sm);
1184        resolver.set_base_path(&root.join("base"));
1185        resolver.add_include_path(root.join("Events"));
1186
1187        let token = resolver
1188            .resolve_file(Path::new("../Tokens/Token.sol"), Some(&root.join("Events/Event.sol")))
1189            .unwrap();
1190        assert_eq!(token.name.as_real(), Some(root.join("Tokens/Token.sol").as_path()));
1191    }
1192
1193    #[test]
1194    fn remapping_contexts_match_absolute_paths_outside_base_path() {
1195        let tmp = tempfile::Builder::new().prefix("solar-file-resolver-test").tempdir().unwrap();
1196        let root = tmp.path();
1197        write_files(root, &["ext/foo/A.sol", "proj/y/X.sol", "proj/z/X.sol"]);
1198
1199        let sm = SourceMap::empty();
1200        let mut resolver = FileResolver::new(&sm);
1201        resolver.set_base_path(&root.join("proj"));
1202        resolver.add_include_path(root.join("ext"));
1203        resolver.add_import_remapping("x/=z/".parse().unwrap());
1204        // Build tools such as Foundry name files outside the base path by their absolute paths.
1205        resolver.add_import_remapping(ImportRemapping {
1206            context: root.join("ext/foo/").display().to_string(),
1207            prefix: "x/".into(),
1208            path: "y/".into(),
1209        });
1210
1211        let parent = root.join("ext/foo/A.sol");
1212        let resolved = resolver.resolve_file(Path::new("x/X.sol"), Some(&parent)).unwrap();
1213        assert_eq!(resolved.name.as_real(), Some(root.join("proj/y/X.sol").as_path()));
1214    }
1215
1216    #[test]
1217    fn absolute_names_in_include_paths_skip_relative_sources() {
1218        let tmp = tempfile::Builder::new().prefix("solar-file-resolver-test").tempdir().unwrap();
1219        let root = tmp.path();
1220        write_files(root, &["ext/src/X.sol"]);
1221
1222        let sm = SourceMap::empty();
1223        // A different file, named relative to the base path.
1224        sm.new_source_file(PathBuf::from("src/X.sol"), "").unwrap();
1225        let mut resolver = FileResolver::new(&sm);
1226        resolver.set_base_path(&root.join("proj"));
1227        resolver.add_include_path(root.join("ext"));
1228        resolver.add_import_remapping(ImportRemapping {
1229            context: String::new(),
1230            prefix: "dep/".into(),
1231            path: format!("{}/", root.join("ext/src").display()),
1232        });
1233
1234        let resolved = resolver.resolve_file(Path::new("dep/X.sol"), Some(Path::new("src/A.sol")));
1235        assert_eq!(resolved.unwrap().name.as_real(), Some(root.join("ext/src/X.sol").as_path()));
1236    }
1237
1238    #[test]
1239    fn include_path_imports_reuse_relative_sources() {
1240        let tmp = tempfile::Builder::new().prefix("solar-file-resolver-test").tempdir().unwrap();
1241        let root = tmp.path();
1242        write_files(root, &["lib/dep/X.sol"]);
1243
1244        let sm = SourceMap::empty();
1245        let preloaded = sm.new_source_file(PathBuf::from("lib/dep/X.sol"), "").unwrap();
1246        let mut resolver = FileResolver::new(&sm);
1247        resolver.set_base_path(root);
1248        resolver.add_include_path(root.join("lib"));
1249
1250        let resolved = resolver.resolve_file(Path::new("dep/X.sol"), Some(Path::new("src/A.sol")));
1251        assert!(Arc::ptr_eq(&resolved.unwrap(), &preloaded));
1252    }
1253
1254    #[test]
1255    fn unnamed_source_imports_use_source_unit_names() {
1256        let tmp = tempfile::Builder::new().prefix("solar-file-resolver-test").tempdir().unwrap();
1257        let root = tmp.path();
1258        write_files(root, &["A.sol", "src/A.sol", "lib/A.sol"]);
1259
1260        let sm = SourceMap::empty();
1261        let mut resolver = FileResolver::new(&sm);
1262        resolver.set_current_dir(root);
1263        resolver.add_import_remapping("src/=lib/".parse().unwrap());
1264
1265        // Imports from standard input are remapped, unlike paths on the command line.
1266        for (path, expected) in [("src/A.sol", "lib/A.sol"), ("./A.sol", "A.sol")] {
1267            let resolved = resolver.resolve_file(Path::new(path), Some(Path::new(""))).unwrap();
1268            assert_eq!(resolved.name.as_real(), Some(root.join(expected).as_path()), "{path}");
1269        }
1270        let resolved = resolver.resolve_file(Path::new("src/A.sol"), None).unwrap();
1271        assert_eq!(resolved.name.as_real(), Some(root.join("src/A.sol").as_path()));
1272    }
1273
1274    #[test]
1275    fn file_url_imports_load_from_disk() {
1276        let tmp = tempfile::Builder::new().prefix("solar-file-resolver-test").tempdir().unwrap();
1277        let root = tmp.path();
1278        write_files(root, &["A.sol"]);
1279
1280        let sm = SourceMap::empty();
1281        let resolver = FileResolver::new(&sm);
1282        let url = format!("file://{}", root.join("A.sol").display());
1283        let resolved = resolver.resolve_file(Path::new(&url), Some(Path::new("B.sol"))).unwrap();
1284        assert_eq!(resolved.name.as_real(), Some(root.join("A.sol").as_path()));
1285    }
1286}
1287
1288// ported-from: https://github.com/BenTheKush/solc_remapping_behavior_test
1289#[cfg(test)]
1290mod solang_import_resolution {
1291    use super::*;
1292    use std::collections::{HashMap, HashSet};
1293
1294    struct FixtureFile {
1295        path: &'static str,
1296        imports: &'static [&'static str],
1297    }
1298
1299    struct Scenario {
1300        name: &'static str,
1301        input: &'static str,
1302        remappings: &'static [&'static str],
1303        base_path: Option<&'static str>,
1304        include_paths: &'static [&'static str],
1305        should_resolve: bool,
1306    }
1307
1308    struct Harness<'a> {
1309        _tmp: tempfile::TempDir,
1310        root: PathBuf,
1311        cwd: PathBuf,
1312        imports: HashMap<PathBuf, &'a [&'a str]>,
1313    }
1314
1315    impl<'a> Harness<'a> {
1316        fn new(cwd: &str, files: &'a [FixtureFile]) -> Self {
1317            let tmp = tempfile::Builder::new()
1318                .prefix("solar-solang-import-resolution-test")
1319                .tempdir()
1320                .unwrap();
1321            let root = tmp.path().to_path_buf();
1322            let cwd = root.join(cwd);
1323            let mut imports = HashMap::default();
1324            for FixtureFile { path, imports: file_imports } in files {
1325                let path_on_disk = cwd.join(path);
1326                if let Some(parent) = path_on_disk.parent() {
1327                    std::fs::create_dir_all(parent).unwrap();
1328                }
1329                std::fs::write(path_on_disk, "").unwrap();
1330                let key = cwd.join(path).strip_prefix(&root).unwrap().to_path_buf();
1331                imports.insert(key, *file_imports);
1332            }
1333            Self { _tmp: tmp, root, cwd, imports }
1334        }
1335
1336        fn run(&self, scenario: &Scenario) -> Result<(), ResolveError> {
1337            let sm = SourceMap::empty();
1338            sm.set_roots(Some(self.cwd.clone()), Vec::new(), None);
1339            let mut file_resolver = FileResolver::new(&sm);
1340            file_resolver.set_current_dir(&self.cwd);
1341            if let Some(base_path) = scenario.base_path {
1342                file_resolver.set_base_path(&self.cwd.join(base_path));
1343            }
1344            for include_path in scenario.include_paths {
1345                file_resolver.add_include_path(self.cwd.join(include_path));
1346            }
1347            for remapping in scenario.remappings {
1348                file_resolver.add_import_remapping(remapping.parse().unwrap());
1349            }
1350
1351            let root_file = file_resolver.resolve_file(Path::new(scenario.input), None)?;
1352            let mut stack = vec![root_file];
1353            let mut seen = HashSet::new();
1354            while let Some(file) = stack.pop() {
1355                let path = file.name.as_real().unwrap();
1356                if !seen.insert(path.to_path_buf()) {
1357                    continue;
1358                }
1359
1360                let key = path.strip_prefix(&self.root).unwrap();
1361                for import in self.imports.get(key).copied().unwrap_or_default() {
1362                    stack.push(file_resolver.resolve_file(Path::new(import), Some(path))?);
1363                }
1364            }
1365            Ok(())
1366        }
1367    }
1368
1369    fn check_solang_import_resolution_scenarios(
1370        cwd: &str,
1371        files: &[FixtureFile],
1372        scenarios: &[Scenario],
1373    ) {
1374        let harness = Harness::new(cwd, files);
1375        for scenario in scenarios {
1376            let result = harness.run(scenario);
1377            assert_eq!(
1378                result.is_ok(),
1379                scenario.should_resolve,
1380                "{}: expected should_resolve={}, got {result:?}",
1381                scenario.name,
1382                scenario.should_resolve
1383            );
1384        }
1385    }
1386
1387    #[test]
1388    fn solang_import_resolution_corpus() {
1389        check_solang_import_resolution_scenarios(
1390            "01_solang_remap_target",
1391            &[
1392                FixtureFile { path: "contracts/Contract.sol", imports: &["lib/Lib.sol"] },
1393                FixtureFile { path: "resources/node_modules/lib/Lib.sol", imports: &[] },
1394            ],
1395            &[
1396                Scenario {
1397                    name: "01.1 no remapping",
1398                    input: "contracts/Contract.sol",
1399                    remappings: &[],
1400                    base_path: None,
1401                    include_paths: &[],
1402                    should_resolve: false,
1403                },
1404                Scenario {
1405                    name: "01.2 no base path or include path",
1406                    input: "contracts/Contract.sol",
1407                    remappings: &["lib=node_modules/lib"],
1408                    base_path: None,
1409                    include_paths: &[],
1410                    should_resolve: false,
1411                },
1412                Scenario {
1413                    name: "01.3 incomplete include paths",
1414                    input: "contracts/Contract.sol",
1415                    remappings: &["lib=node_modules/lib"],
1416                    base_path: Some("."),
1417                    include_paths: &[],
1418                    should_resolve: false,
1419                },
1420                Scenario {
1421                    name: "01.4 incorrect include paths",
1422                    input: "contracts/Contract.sol",
1423                    remappings: &["lib=node_modules/lib"],
1424                    base_path: Some("."),
1425                    include_paths: &["resources/node_modules"],
1426                    should_resolve: false,
1427                },
1428                Scenario {
1429                    name: "01.5 correct configuration",
1430                    input: "contracts/Contract.sol",
1431                    remappings: &["lib=node_modules/lib"],
1432                    base_path: Some("."),
1433                    include_paths: &["resources"],
1434                    should_resolve: true,
1435                },
1436            ],
1437        );
1438
1439        check_solang_import_resolution_scenarios(
1440            "02_solang_incorrect_direct_imports",
1441            &[
1442                FixtureFile { path: "Ambiguous.sol", imports: &[] },
1443                FixtureFile {
1444                    path: "contracts/Ambiguous.sol",
1445                    imports: &["Error: contracts/Ambiguous.sol should not be imported"],
1446                },
1447                FixtureFile { path: "contracts/Contract.sol", imports: &["Ambiguous.sol"] },
1448                FixtureFile {
1449                    path: "resources/node_modules/lib/Ambiguous.sol",
1450                    imports: &[
1451                        "Error: resources/node_modules/lib/Ambiguous.sol should not be imported",
1452                    ],
1453                },
1454                FixtureFile { path: "resources/node_modules/lib/Lib.sol", imports: &[] },
1455            ],
1456            &[
1457                Scenario {
1458                    name: "02.1 direct import default base path",
1459                    input: "contracts/Contract.sol",
1460                    remappings: &[],
1461                    base_path: None,
1462                    include_paths: &[],
1463                    should_resolve: true,
1464                },
1465                Scenario {
1466                    name: "02.2 direct import explicit base path",
1467                    input: "contracts/Contract.sol",
1468                    remappings: &[],
1469                    base_path: Some("."),
1470                    include_paths: &[],
1471                    should_resolve: true,
1472                },
1473            ],
1474        );
1475
1476        check_solang_import_resolution_scenarios(
1477            "03_ambiguous_imports_should_fail",
1478            &[
1479                FixtureFile { path: "Ambiguous.sol", imports: &["This should not be imported"] },
1480                FixtureFile { path: "contracts/Ambiguous.sol", imports: &[] },
1481                FixtureFile {
1482                    path: "contracts/Contract.sol",
1483                    imports: &["lib/Lib.sol", "Ambiguous.sol"],
1484                },
1485                FixtureFile { path: "resources/node_modules/lib/Ambiguous.sol", imports: &[] },
1486                FixtureFile { path: "resources/node_modules/lib/Lib.sol", imports: &[] },
1487            ],
1488            &[
1489                Scenario {
1490                    name: "03.1 ambiguous imports should fail",
1491                    input: "contracts/Contract.sol",
1492                    remappings: &["lib=resources/node_modules/lib"],
1493                    base_path: Some("."),
1494                    include_paths: &["contracts"],
1495                    should_resolve: false,
1496                },
1497                Scenario {
1498                    name: "03.2 import order resources then root",
1499                    input: "contracts/Contract.sol",
1500                    remappings: &["lib=resources/node_modules/lib"],
1501                    base_path: Some("."),
1502                    include_paths: &["resources/node_modules/lib", "."],
1503                    should_resolve: false,
1504                },
1505                Scenario {
1506                    name: "03.3 import order root then resources",
1507                    input: "contracts/Contract.sol",
1508                    remappings: &["lib=resources/node_modules/lib"],
1509                    base_path: Some("."),
1510                    include_paths: &[".", "resources/node_modules/lib"],
1511                    should_resolve: false,
1512                },
1513            ],
1514        );
1515
1516        check_solang_import_resolution_scenarios(
1517            "04_multiple_map_path_segments",
1518            &[
1519                FixtureFile { path: "contracts/Contract.sol", imports: &["lib/nested/Lib.sol"] },
1520                FixtureFile { path: "resources/node_modules/lib/nested/Lib.sol", imports: &[] },
1521            ],
1522            &[Scenario {
1523                name: "04.1 multiple import mapping segments",
1524                input: "contracts/Contract.sol",
1525                remappings: &["lib/nested=resources/node_modules/lib/nested"],
1526                base_path: Some("."),
1527                include_paths: &[],
1528                should_resolve: true,
1529            }],
1530        );
1531
1532        check_solang_import_resolution_scenarios(
1533            "05_import_path_order_should_not_matter",
1534            &[
1535                FixtureFile { path: "contracts/Contract.sol", imports: &["A.sol"] },
1536                FixtureFile { path: "contracts/nested1/A.sol", imports: &[] },
1537                FixtureFile { path: "contracts/nested2/A.sol", imports: &[] },
1538            ],
1539            &[
1540                Scenario {
1541                    name: "05.1 include order nested1 then nested2",
1542                    input: "contracts/Contract.sol",
1543                    remappings: &[],
1544                    base_path: None,
1545                    include_paths: &["contracts/nested1", "contracts/nested2"],
1546                    should_resolve: false,
1547                },
1548                Scenario {
1549                    name: "05.2 include order nested2 then nested1",
1550                    input: "contracts/Contract.sol",
1551                    remappings: &[],
1552                    base_path: None,
1553                    include_paths: &["contracts/nested2", "contracts/nested1"],
1554                    should_resolve: false,
1555                },
1556            ],
1557        );
1558
1559        check_solang_import_resolution_scenarios(
1560            "06_redundant_remaps",
1561            &[
1562                FixtureFile {
1563                    path: "contracts/Contract.sol",
1564                    imports: &["node_modules/lib/Lib.sol"],
1565                },
1566                FixtureFile { path: "resources/node_modules/lib/Lib.sol", imports: &[] },
1567            ],
1568            &[
1569                Scenario {
1570                    name: "06.1 multiple remappings",
1571                    input: "contracts/Contract.sol",
1572                    remappings: &[
1573                        "node_modules=resources/node_modules",
1574                        "node_modules=node_modules",
1575                    ],
1576                    base_path: Some("resources"),
1577                    include_paths: &[],
1578                    should_resolve: true,
1579                },
1580                Scenario {
1581                    name: "06.2 multiple remappings reversed",
1582                    input: "contracts/Contract.sol",
1583                    remappings: &[
1584                        "node_modules=node_modules",
1585                        "node_modules=resources/node_modules",
1586                    ],
1587                    base_path: Some("resources"),
1588                    include_paths: &[],
1589                    should_resolve: false,
1590                },
1591                Scenario {
1592                    name: "06.3 multiple remappings last wins",
1593                    input: "contracts/Contract.sol",
1594                    remappings: &[
1595                        "node_modules=node_modules",
1596                        "node_modules=resources/node_modules",
1597                        "node_modules=node_modules",
1598                    ],
1599                    base_path: Some("resources"),
1600                    include_paths: &[],
1601                    should_resolve: true,
1602                },
1603            ],
1604        );
1605    }
1606
1607    #[test]
1608    fn snapshots_base_path() {
1609        let sm = SourceMap::empty();
1610        sm.set_roots(Some(PathBuf::from("base")), Vec::new(), None);
1611        let resolver = FileResolver::new(&sm);
1612        sm.set_roots(None, Vec::new(), None);
1613        assert_eq!(resolver.try_base_path(), Some(Path::new("base")));
1614    }
1615}