Skip to main content

foundry_config/providers/
remappings.rs

1use crate::{
2    Config, FigmentProviders, Warning, foundry_toml_dir_entries, remappings_from_env_var,
3    remappings_from_newline,
4};
5use figment::{
6    Error, Figment, Metadata, Profile, Provider,
7    value::{Dict, Map},
8};
9use foundry_compilers::artifacts::remappings::{RelativeRemapping, Remapping, RemappingDiscovery};
10use rayon::prelude::*;
11use std::{
12    borrow::Cow,
13    cmp::Reverse,
14    collections::{
15        BTreeMap, BTreeSet, HashMap, HashSet, btree_map::Entry, hash_map::Entry as HashEntry,
16    },
17    fs,
18    path::{Component, MAIN_SEPARATOR, Path, PathBuf},
19};
20
21#[cfg(windows)]
22use path_slash::PathExt as _;
23
24const GENERATED_REMAPPINGS_KEY: &str = "__generated_remappings";
25
26#[derive(Default)]
27struct RemappingsOutput {
28    /// All explicit, dependency, and auto-detected remappings exposed to the config.
29    remappings: Vec<Remapping>,
30    /// Dependency declarations and contextual refinements scoped by this provider.
31    ///
32    /// These are tracked so the later CLI merge can distinguish them from equivalent explicit
33    /// contextual remappings.
34    generated_contextual_remappings: Vec<Remapping>,
35    /// Existing configuration warnings and warnings for newly scoped declarations.
36    warnings: Vec<Warning>,
37}
38
39/// Wrapper types over a `Vec<Remapping>` that only appends unique remappings.
40#[derive(Clone, Debug, Default)]
41pub struct Remappings {
42    /// Remappings.
43    remappings: Vec<Remapping>,
44    /// Source, test and script configured project dirs.
45    /// Remappings of these dirs from libs are ignored.
46    project_paths: Vec<Remapping>,
47}
48
49impl Remappings {
50    /// Create a new `Remappings` wrapper with an empty vector.
51    pub const fn new() -> Self {
52        Self { remappings: Vec::new(), project_paths: Vec::new() }
53    }
54
55    /// Create a new `Remappings` wrapper with a vector of remappings.
56    pub const fn new_with_remappings(remappings: Vec<Remapping>) -> Self {
57        Self { remappings, project_paths: Vec::new() }
58    }
59
60    /// Extract project paths that cannot be remapped by dependencies.
61    pub fn with_figment(mut self, figment: &Figment) -> Self {
62        let mut add_project_remapping = |path: &str| {
63            if let Ok(path) = figment.find_value(path)
64                && let Some(path) = path.into_string()
65            {
66                let remapping = Remapping {
67                    context: None,
68                    name: project_path_remapping_name(Path::new(&path)),
69                    path: format!("{path}/"),
70                };
71                self.project_paths.push(remapping);
72            }
73        };
74        add_project_remapping("src");
75        add_project_remapping("test");
76        add_project_remapping("script");
77        self
78    }
79
80    /// Consumes the wrapper and returns the inner remappings vector.
81    pub fn into_inner(self) -> Vec<Remapping> {
82        let mut seen = HashSet::new();
83        self.remappings
84            .iter()
85            .filter(|r| seen.insert((r.context.as_deref(), r.name.as_str())))
86            .cloned()
87            .collect()
88    }
89
90    /// Push an element to the remappings vector, but only if it's not already present.
91    fn push(&mut self, remapping: Remapping) -> bool {
92        // Special handling for .sol file remappings, only allow one remapping per source file.
93        if remapping.name.ends_with(".sol") && !remapping.path.ends_with(".sol") {
94            return false;
95        }
96
97        if self.remappings.iter().any(|existing| {
98            let same_context = match (&existing.context, &remapping.context) {
99                (Some(existing), Some(context)) => {
100                    existing.len() == context.len() && context_starts_with(existing, context)
101                }
102                (None, None) => true,
103                _ => false,
104            };
105            if remapping.name.ends_with(".sol") {
106                // For .sol files, only prevent duplicate source names in the same context
107                return existing.name == remapping.name
108                    && same_context
109                    && existing.path == remapping.path;
110            }
111
112            // Autodetected remappings are added from the root project down through its libraries,
113            // so an existing root alias remains authoritative over an equal or more specific
114            // dependency alias. For example, an existing `@utils/=src/` suppresses an incoming
115            // `@utils/libraries/=lib/utils/`, preventing a dependency from overriding part of the
116            // root namespace. The reverse direction is intentional: an existing
117            // `@prb/math/=src/math/` can coexist with an incoming `@prb/=lib/prb/`; the root alias
118            // resolves its subtree while the dependency alias acts as a fallback for the rest of
119            // the namespace.
120            // Compare without one optional trailing slash so `pkg` and `pkg/` denote the same
121            // alias while preserving significant repeated slashes.
122            remapping_name_is_prefix(&existing.name, &remapping.name) && same_context
123        }) {
124            return false;
125        };
126
127        // Ignore global remappings of root project src, test or script dir.
128        // See <https://github.com/foundry-rs/foundry/issues/3440>.
129        if remapping.context.is_none()
130            && self
131                .project_paths
132                .iter()
133                .any(|project_path| remapping.name.eq_ignore_ascii_case(&project_path.name))
134        {
135            return false;
136        };
137
138        self.remappings.push(remapping);
139        true
140    }
141
142    /// Extend the remappings vector, leaving out the remappings that are already present.
143    pub fn extend(&mut self, remappings: Vec<Remapping>) {
144        for remapping in remappings {
145            self.push(remapping);
146        }
147    }
148
149    /// Extract generated contextual refinements from a Figment.
150    pub fn generated_from_figment(figment: &Figment) -> Vec<Remapping> {
151        figment.extract_inner(GENERATED_REMAPPINGS_KEY).unwrap_or_default()
152    }
153
154    /// Returns configuration warnings not resolved by these authoritative remappings.
155    pub fn warnings_from_figment(&self, figment: &Figment) -> Vec<Warning> {
156        let mut warnings = figment.extract_inner::<Vec<Warning>>("__warnings").unwrap_or_default();
157        suppress_overridden_remapping_warnings(&mut warnings, &self.remappings);
158        warnings
159    }
160
161    /// Merge config remappings while preserving CLI precedence over generated refinements.
162    ///
163    /// Narrow CLI aliases are overlaid into generated contexts; explicit contexts are unchanged.
164    pub fn extend_with_config_remappings(
165        &mut self,
166        config_remappings: Vec<Remapping>,
167        generated_contextual_remappings: &[Remapping],
168    ) {
169        let authoritative = self.remappings.clone();
170        let mut suppressed = HashSet::new();
171        let mut overlays = Vec::new();
172        for (index, remapping) in config_remappings.iter().enumerate().filter(|(_, remapping)| {
173            remapping.context.is_some() && generated_contextual_remappings.contains(remapping)
174        }) {
175            if let Some(contextual) = contextual_overlays(&authoritative, remapping) {
176                overlays.extend(contextual);
177            } else {
178                suppressed.insert(index);
179            }
180        }
181        self.extend(overlays);
182        for (index, remapping) in config_remappings.into_iter().enumerate() {
183            if !suppressed.contains(&index) {
184                self.push(remapping);
185            }
186        }
187    }
188}
189
190struct CachedNestedConfig {
191    src: PathBuf,
192    libs: Vec<PathBuf>,
193    remappings: Vec<Remapping>,
194    file_remappings: Vec<Remapping>,
195}
196
197#[derive(Clone, Copy, Debug, PartialEq, Eq)]
198enum NestedRemappingKind {
199    Declaration,
200    UnscopedDeclaration,
201    PackageEntry,
202}
203
204/// A figment provider that checks if the remappings were previously set and if they're unset looks
205/// up the fs via
206///   - `DAPP_REMAPPINGS` || `FOUNDRY_REMAPPINGS` env var
207///   - `<root>/remappings.txt` file
208///   - `Remapping::find_many`.
209pub struct RemappingsProvider<'a> {
210    /// Whether to auto detect remappings from the `lib_paths`
211    pub auto_detect_remappings: bool,
212    /// The lib/dependency directories to scan for remappings
213    pub lib_paths: Cow<'a, Vec<PathBuf>>,
214    /// the root path used to turn an absolute `Remapping`, as we're getting it from
215    /// `Remapping::find_many` into a relative one.
216    pub root: &'a Path,
217    /// This contains either:
218    ///   - previously set remappings
219    ///   - a `MissingField` error, which means previous provider didn't set the "remappings" field
220    ///   - other error, like formatting
221    pub remappings: Result<Vec<Remapping>, Error>,
222    /// Source, test and script directories owned by the root project.
223    pub project_paths: Vec<PathBuf>,
224    /// Extra directories the compiler searches for imports.
225    pub include_paths: Vec<PathBuf>,
226    /// Warnings collected by earlier configuration providers.
227    pub warnings: Result<Vec<Warning>, Error>,
228}
229
230impl RemappingsProvider<'_> {
231    /// Find and parse remappings for the projects
232    ///
233    /// **Order**
234    ///
235    /// Remappings are built in this order (last item takes precedence)
236    /// - Autogenerated remappings
237    /// - toml remappings
238    /// - `remappings.txt`
239    /// - Environment variables
240    /// - CLI parameters
241    fn get_remappings(&self, remappings: Vec<Remapping>) -> Result<RemappingsOutput, Error> {
242        trace!("get all remappings from {:?}", self.root);
243        let mut warnings = self.warnings.clone()?;
244        /// Prioritizes remappings by shortest path, then a `src` target, then lexical path.
245        ///   - ("a", "1/2") over ("a", "1/2/3")
246        ///   - ("a", "1/src") over ("a", "1/lib")
247        ///
248        /// grouped by remapping context
249        fn insert_closest(
250            mappings: &mut BTreeMap<Option<String>, BTreeMap<String, PathBuf>>,
251            context: Option<String>,
252            key: String,
253            path: PathBuf,
254        ) {
255            let context_mappings = mappings.entry(context).or_default();
256            match context_mappings.entry(key) {
257                Entry::Occupied(mut entry) => {
258                    let existing = entry.get();
259                    if (path.components().count(), !path.ends_with("src"), &path)
260                        < (existing.components().count(), !existing.ends_with("src"), existing)
261                    {
262                        entry.insert(path);
263                    }
264                }
265                Entry::Vacant(entry) => {
266                    entry.insert(path);
267                }
268            }
269        }
270
271        // Let's first just extend the remappings with the ones that were passed in,
272        // without any filtering.
273        let mut user_remappings = Vec::new();
274
275        // check env vars
276        if let Some(env_remappings) = remappings_from_env_var("DAPP_REMAPPINGS")
277            .or_else(|| remappings_from_env_var("FOUNDRY_REMAPPINGS"))
278        {
279            user_remappings
280                .extend(env_remappings.map_err::<Error, _>(|err| err.to_string().into())?);
281        }
282
283        // check remappings.txt file
284        let remappings_file = self.root.join("remappings.txt");
285        if remappings_file.is_file() {
286            let content = fs::read_to_string(remappings_file).map_err(|err| err.to_string())?;
287            let remappings_from_file: Result<Vec<_>, _> =
288                remappings_from_newline(&content).collect();
289            user_remappings
290                .extend(remappings_from_file.map_err::<Error, _>(|err| err.to_string().into())?);
291        }
292
293        user_remappings.extend(remappings);
294        let mut authoritative_user_remappings = user_remappings.clone();
295        for remapping in &mut authoritative_user_remappings {
296            if let Some(context) = &mut remapping.context {
297                *context = self.root.join(&*context).display().to_string();
298            }
299        }
300        // Let's now use the wrapper to conditionally extend the remappings with the autodetected
301        // ones. We want to avoid duplicates, and the wrapper will handle this for us.
302        let mut all_remappings = Remappings::new_with_remappings(user_remappings);
303
304        // scan all library dirs and autodetect remappings
305        if self.auto_detect_remappings {
306            let (nested_foundry_remappings, auto_detected_remappings) = rayon::join(
307                || self.find_nested_foundry_remappings(),
308                || self.auto_detect_remappings(),
309            );
310            let mut nested_foundry_remappings = nested_foundry_remappings?;
311
312            let configured_package_entries = nested_foundry_remappings
313                .iter()
314                .filter(|(_, _, kind)| *kind == NestedRemappingKind::PackageEntry)
315                .map(|(lib, remapping, _)| (lib.clone(), remapping.clone()))
316                .collect::<Vec<_>>();
317            let RemappingDiscovery { global, contextual } = auto_detected_remappings;
318            let mut global = global
319                .into_iter()
320                .map(|remapping| configured_auto_remapping(remapping, &configured_package_entries))
321                .collect::<Vec<_>>();
322            let mut contextual = contextual
323                .into_iter()
324                .map(|remapping| configured_auto_remapping(remapping, &configured_package_entries))
325                .collect::<Vec<_>>();
326            let safe_alias = |remapping: &Remapping| {
327                !["lib/", "src/", "contracts/"].contains(&remapping.name.as_str())
328            };
329            global.retain(&safe_alias);
330            contextual.retain(safe_alias);
331            // Dependencies commonly omit nested checkouts and use a hoisted installation. A
332            // missing declared target must not shadow that discovered package within its owner.
333            nested_foundry_remappings.retain(|(_, remapping, kind)| {
334                *kind == NestedRemappingKind::PackageEntry
335                    || Path::new(&remapping.path).exists()
336                    || !global
337                        .iter()
338                        .any(|auto| remapping_name_is_prefix(&auto.name, &remapping.name))
339            });
340            let mut targets_by_alias = BTreeMap::<_, BTreeSet<_>>::new();
341            for remapping in global.iter().chain(&contextual) {
342                targets_by_alias
343                    .entry(remapping.name.clone())
344                    .or_default()
345                    .insert(PathBuf::from(&remapping.path));
346            }
347            let ambiguous_aliases = targets_by_alias
348                .into_iter()
349                .filter_map(|(name, targets)| (targets.len() > 1).then_some(name))
350                .collect::<BTreeSet<_>>();
351            let mut lib_remappings = BTreeMap::new();
352            let mut explicit_contextual_remappings = Vec::new();
353            let mut unscoped_contextual_remappings = BTreeSet::new();
354            for (lib, r, kind) in nested_foundry_remappings
355                .iter()
356                .filter(|(_, remapping, _)| remapping.context.is_some())
357            {
358                let scoped = match kind {
359                    NestedRemappingKind::Declaration => scope_nested_remapping(r.clone(), lib),
360                    NestedRemappingKind::UnscopedDeclaration => Some(r.clone()),
361                    NestedRemappingKind::PackageEntry => None,
362                };
363                if let Some(scoped) = scoped
364                    && let Some(overlays) =
365                        contextual_overlays(&authoritative_user_remappings, &scoped)
366                {
367                    if *kind == NestedRemappingKind::UnscopedDeclaration {
368                        unscoped_contextual_remappings.extend(overlays.iter().cloned());
369                        unscoped_contextual_remappings.insert(scoped.clone());
370                    }
371                    explicit_contextual_remappings.extend(overlays);
372                    explicit_contextual_remappings.push(scoped);
373                }
374            }
375            let mut authoritative_remappings = authoritative_user_remappings;
376            authoritative_remappings.extend(explicit_contextual_remappings.iter().cloned());
377            // Reuse global selection and prefix precedence to identify declarations that actually
378            // supplied root imports before scoping. Losing declarations need no migration advice.
379            let mut previous_globals = BTreeMap::new();
380            for remapping in nested_foundry_remappings
381                .iter()
382                .map(|(_, remapping, _)| remapping)
383                .chain(&global)
384                .filter(|remapping| remapping.context.is_none())
385            {
386                insert_closest(
387                    &mut previous_globals,
388                    None,
389                    remapping.name.clone(),
390                    remapping.path.clone().into(),
391                );
392            }
393            let mut previous_remappings = all_remappings.clone();
394            previous_remappings.extend(
395                previous_globals
396                    .into_values()
397                    .flat_map(|remappings| {
398                        remappings.into_iter().map(|(name, path)| Remapping {
399                            context: None,
400                            name,
401                            path: path.to_string_lossy().into(),
402                        })
403                    })
404                    .collect(),
405            );
406            let previous_globals = previous_remappings
407                .into_inner()
408                .into_iter()
409                .filter(|remapping| remapping.context.is_none())
410                .map(|remapping| remapping.into_relative(self.root))
411                .collect::<BTreeSet<_>>();
412            let mut contextual_remappings = Vec::new();
413            let mut scoped_remappings = Vec::new();
414            for (lib, r, kind) in &nested_foundry_remappings {
415                if r.context.is_some() {
416                    continue;
417                }
418                // Preserve unique aliases while isolating declarations that can change another
419                // import namespace. External sources retain their existing declaration scope.
420                if *kind == NestedRemappingKind::Declaration
421                    && (self.project_paths.iter().any(|path| {
422                        let path = path.strip_prefix(self.root).unwrap_or(path);
423                        remappings_conflict(
424                            r,
425                            &Remapping {
426                                context: None,
427                                name: project_path_remapping_name(path),
428                                path: self.root.join(path).display().to_string(),
429                            },
430                            self.root,
431                        )
432                    }) || (self.root.join(&r.name).exists()
433                        && foundry_compilers::utils::canonicalized(self.root.join(&r.name))
434                            != foundry_compilers::utils::canonicalized(self.root.join(&r.path)))
435                        || nested_foundry_remappings
436                            .iter()
437                            .filter(|(owner, _, kind)| {
438                                owner != lib || *kind == NestedRemappingKind::PackageEntry
439                            })
440                            .map(|(_, mapping, _)| mapping)
441                            .chain(&global)
442                            .chain(&contextual)
443                            .any(|other| remappings_conflict(r, other, self.root)))
444                {
445                    if let Some(contextual) = scope_nested_remapping(r.clone(), lib) {
446                        scoped_remappings.push(relative_remapping_preserving_context_boundary(
447                            contextual.clone(),
448                            self.root,
449                        ));
450                        if let Some(overlays) =
451                            contextual_overlays(&authoritative_remappings, &contextual)
452                        {
453                            contextual_remappings.extend(overlays);
454                            contextual_remappings.push(contextual);
455                        }
456                    }
457                    continue;
458                }
459                // Preserve existing contextual refinements for external-source dependencies.
460                if *kind == NestedRemappingKind::UnscopedDeclaration
461                    && global.iter().chain(&contextual).any(|auto| {
462                        auto.name == r.name
463                            && Path::new(&r.path) != Path::new(&auto.path)
464                            && (auto
465                                .context
466                                .as_deref()
467                                .is_some_and(|context| Path::new(context) == lib)
468                                || (auto.context == r.context
469                                    && Path::new(&r.path).starts_with(&auto.path)))
470                    })
471                {
472                    let mut refinement = r.clone();
473                    refinement.context = Some(format!("{}{MAIN_SEPARATOR}", lib.display()));
474                    if let Some(overlays) =
475                        contextual_overlays(&authoritative_remappings, &refinement)
476                    {
477                        contextual_remappings.extend(overlays);
478                        contextual_remappings.push(refinement);
479                    }
480                }
481                insert_closest(
482                    &mut lib_remappings,
483                    r.context.clone(),
484                    r.name.clone(),
485                    PathBuf::from(&r.path),
486                );
487            }
488            for remapping in contextual
489                .into_iter()
490                .filter(|remapping| ambiguous_aliases.contains(&remapping.name))
491                .flat_map(expand_scoped_contextual_remapping)
492            {
493                if let Some(overlays) = contextual_overlays(&authoritative_remappings, &remapping) {
494                    contextual_remappings.extend(overlays);
495                    contextual_remappings.push(remapping);
496                }
497            }
498            sort_by_context_specificity(&mut contextual_remappings);
499            for r in global {
500                insert_closest(&mut lib_remappings, r.context, r.name, r.path.into());
501            }
502
503            let explicit_remappings = all_remappings
504                .remappings
505                .iter()
506                .map(|r| relative_remapping_preserving_context_boundary(r.clone(), self.root))
507                .collect::<Vec<_>>();
508            sort_by_context_specificity(&mut explicit_contextual_remappings);
509            let mut generated_remappings = Vec::new();
510            for contextual in
511                explicit_contextual_remappings.into_iter().chain(contextual_remappings)
512            {
513                let relative =
514                    relative_remapping_preserving_context_boundary(contextual.clone(), self.root);
515                if !explicit_remappings.contains(&relative)
516                    && all_remappings.push(contextual.clone())
517                    && !unscoped_contextual_remappings.contains(&contextual)
518                {
519                    generated_remappings.push(contextual);
520                }
521            }
522            all_remappings.extend(
523                lib_remappings
524                    .into_iter()
525                    .flat_map(|(context, remappings)| {
526                        remappings.into_iter().map(move |(name, path)| Remapping {
527                            context: context.clone(),
528                            name,
529                            path: path.to_string_lossy().into(),
530                        })
531                    })
532                    .collect(),
533            );
534
535            warnings.extend(scoped_remapping_warnings(
536                scoped_remappings,
537                &previous_globals,
538                &all_remappings.remappings,
539                &self.project_paths,
540                &self.include_paths,
541                self.root,
542            ));
543            suppress_overridden_remapping_warnings(&mut warnings, &authoritative_remappings);
544            return Ok(RemappingsOutput {
545                remappings: all_remappings.into_inner(),
546                generated_contextual_remappings: generated_remappings,
547                warnings,
548            });
549        }
550
551        Ok(RemappingsOutput {
552            remappings: all_remappings.into_inner(),
553            warnings,
554            ..Default::default()
555        })
556    }
557
558    /// Returns all remappings declared in foundry.toml files of libraries
559    fn find_nested_foundry_remappings(
560        &self,
561    ) -> Result<Vec<(PathBuf, Remapping, NestedRemappingKind)>, Error> {
562        let root = dunce::canonicalize(self.root).unwrap_or_else(|_| self.root.to_path_buf());
563        let lexical_root = normalize_remapping_context(self.root);
564        let mut pending = self
565            .lib_paths
566            .iter()
567            .map(|path| if path.is_absolute() { path.clone() } else { self.root.join(path) })
568            .flat_map(foundry_toml_dir_entries)
569            .collect::<BTreeSet<_>>();
570        let mut seen = HashSet::from([root.clone()]);
571        let mut configs = HashMap::<PathBuf, Option<CachedNestedConfig>>::new();
572        let mut remappings = Vec::new();
573
574        while let Some(entry) = pending.pop_first() {
575            if entry.canonical == root {
576                continue;
577            }
578
579            // Load dependency config inputs without recursively installing another remappings
580            // provider. Canonical identity is used only to read each config once; emitted paths
581            // retain the lexical dependency identity.
582            let config = match configs.entry(entry.canonical.clone()) {
583                HashEntry::Occupied(config) => config.into_mut(),
584                HashEntry::Vacant(config) => {
585                    trace!(lib = ?entry.canonical, "find all remappings of nested foundry.toml");
586                    config.insert(load_nested_config(&entry.canonical)?)
587                }
588            };
589            let Some(config) = config else {
590                continue;
591            };
592
593            // Sources outside the project use relative source names, and relative imports can
594            // normalize away an external source's lexical owner. Preserve their old declaration
595            // scope rather than encoding the absolute checkout in source names.
596            let source = foundry_compilers::utils::canonicalized(entry.canonical.join(&config.src));
597            let source = normalize_remapping_context(&source);
598            let declaration_kind = if normalize_remapping_context(&entry.path)
599                .starts_with(&lexical_root)
600                && source.starts_with(&entry.canonical)
601            {
602                NestedRemappingKind::Declaration
603            } else {
604                NestedRemappingKind::UnscopedDeclaration
605            };
606
607            remappings.extend(config.remappings.iter().cloned().map(|remapping| {
608                (
609                    entry.path.clone(),
610                    rebase_nested_remapping(remapping, &entry.canonical, &entry.path),
611                    declaration_kind,
612                )
613            }));
614            remappings.extend(config.file_remappings.iter().cloned().map(|remapping| {
615                (
616                    entry.path.clone(),
617                    RelativeRemapping::new(remapping, &entry.path).into(),
618                    declaration_kind,
619                )
620            }));
621
622            // Preserve existing physical nested-config discovery. Symlink discovery is limited to
623            // direct configured-library entries; nested symlink graphs remain out of scope.
624            if !fs::symlink_metadata(&entry.path)
625                .is_ok_and(|metadata| metadata.file_type().is_symlink())
626                && seen.insert(entry.canonical.clone())
627            {
628                // Nested library roots must stay inside both dependency identities.
629                for lib in config
630                    .libs
631                    .iter()
632                    .filter_map(|lib| contained_library_path(&entry.path, &entry.canonical, lib))
633                {
634                    pending.extend(foundry_toml_dir_entries(lib).into_iter().filter(|entry| {
635                        !fs::symlink_metadata(&entry.path)
636                            .is_ok_and(|metadata| metadata.file_type().is_symlink())
637                    }));
638                }
639            }
640
641            // Custom source directories are not auto-detected. Standard source directories only
642            // need synthesis while missing; when present, package-root autodetection preserves
643            // imports that include the source directory, such as `forge-std/src/...`.
644            let standard_src = [Path::new("src"), Path::new("contracts"), Path::new("lib")];
645            if (!standard_src.contains(&config.src.as_path())
646                || !entry.canonical.join(&config.src).is_dir())
647                && let Some(name) = entry.path.file_name().and_then(|name| name.to_str())
648            {
649                let source = if config.src.is_absolute()
650                    && let Ok(relative) = source.strip_prefix(&entry.canonical)
651                {
652                    entry.path.join(relative)
653                } else {
654                    entry.path.join(&config.src)
655                };
656                let mut remapping = Remapping {
657                    context: None,
658                    name: format!("{name}/"),
659                    path: source.display().to_string(),
660                };
661                if !remapping.path.ends_with('/') {
662                    remapping.path.push('/');
663                }
664                remappings.push((entry.path, remapping, NestedRemappingKind::PackageEntry));
665            }
666        }
667
668        Ok(remappings)
669    }
670
671    /// Auto detect remappings from the lib paths
672    fn auto_detect_remappings(&self) -> RemappingDiscovery {
673        let mut discovery = RemappingDiscovery::default();
674        for mut current in self
675            .lib_paths
676            .par_iter()
677            .map(|lib| {
678                let lib = self.root.join(lib);
679                trace!(?lib, "find all remappings");
680                Remapping::find_many_with_context(&lib)
681            })
682            .collect::<Vec<_>>()
683        {
684            discovery.global.append(&mut current.global);
685            discovery.contextual.append(&mut current.contextual);
686        }
687        discovery
688    }
689}
690
691/// Returns the normalized library directories the dependency at `root` configures, as nested
692/// remapping discovery accepts them.
693pub fn dependency_library_paths(root: &Path) -> Vec<PathBuf> {
694    let figment = Config::with_root(root).to_figment(FigmentProviders::Cast);
695    let Ok(config) = Config::from_figment_fallback(figment) else { return Vec::new() };
696    let canonical = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
697    config
698        .libs
699        .iter()
700        .filter_map(|lib| contained_library_path(root, &canonical, lib))
701        .map(|lib| normalize_remapping_context(&lib))
702        .collect()
703}
704
705/// Joins a dependency's library directory when it is relative and stays inside both the
706/// dependency's lexical and canonical directory, so symlinks and parent components cannot
707/// impersonate another owner.
708fn contained_library_path(owner: &Path, canonical: &Path, lib: &Path) -> Option<PathBuf> {
709    let joined = owner.join(lib);
710    (lib.is_relative()
711        && normalize_remapping_context(&joined).starts_with(normalize_remapping_context(owner))
712        && dunce::canonicalize(&joined).is_ok_and(|joined| joined.starts_with(canonical)))
713    .then_some(joined)
714}
715
716fn load_nested_config(root: &Path) -> Result<Option<CachedNestedConfig>, Error> {
717    let figment = Config::with_root(root).to_figment(FigmentProviders::Cast);
718    let Ok(config) = Config::from_figment_fallback(figment) else { return Ok(None) };
719    let src = config.src.clone();
720    let libs = config.libs.clone();
721    let remappings = config.sanitized().remappings.into_iter().map(Remapping::from).collect();
722    let remappings_file = root.join("remappings.txt");
723    let file_remappings = if remappings_file.is_file() {
724        let content = fs::read_to_string(remappings_file).map_err(|err| err.to_string())?;
725        remappings_from_newline(&content)
726            .collect::<Result<Vec<_>, _>>()
727            .map_err::<Error, _>(|err| err.to_string().into())?
728    } else {
729        Vec::new()
730    };
731    Ok(Some(CachedNestedConfig { src, libs, remappings, file_remappings }))
732}
733
734fn remapping_name_is_prefix(prefix: &str, name: &str) -> bool {
735    let prefix = prefix.strip_suffix('/').unwrap_or(prefix);
736    let name = name.strip_suffix('/').unwrap_or(name);
737    prefix == name || name.strip_prefix(prefix).is_some_and(|suffix| suffix.starts_with('/'))
738}
739
740fn contextual_overlays(
741    authoritative: &[Remapping],
742    refinement: &Remapping,
743) -> Option<Vec<Remapping>> {
744    let applicable = |mapping: &&Remapping| {
745        mapping.context.as_deref().is_none_or(|context| {
746            refinement
747                .context
748                .as_deref()
749                .is_some_and(|refinement| context_starts_with(refinement, context))
750        })
751    };
752    if authoritative
753        .iter()
754        .filter(applicable)
755        .any(|mapping| remapping_name_is_prefix(&mapping.name, &refinement.name))
756    {
757        return None;
758    }
759    let mut overlays = authoritative
760        .iter()
761        .filter(applicable)
762        .filter(|mapping| remapping_name_is_prefix(&refinement.name, &mapping.name))
763        .cloned()
764        .collect::<Vec<_>>();
765    overlays.sort_by_key(|mapping| Reverse(mapping.name.len()));
766    for overlay in &mut overlays {
767        overlay.context.clone_from(&refinement.context);
768    }
769    Some(overlays)
770}
771
772fn context_starts_with(path: &str, base: &str) -> bool {
773    #[cfg(windows)]
774    {
775        path.replace('\\', "/").starts_with(&base.replace('\\', "/"))
776    }
777    #[cfg(not(windows))]
778    path.starts_with(base)
779}
780
781/// Narrows an npm scope mapping to its installed packages so missing siblings can use the global
782/// hoisted-package fallback.
783fn expand_scoped_contextual_remapping(remapping: Remapping) -> Vec<Remapping> {
784    let scope = remapping.name.trim_end_matches('/');
785    let path = Path::new(&remapping.path);
786    if !scope.starts_with('@')
787        || path.file_name().and_then(|name| name.to_str()) != Some(scope)
788        || path.parent().and_then(|parent| parent.file_name()).and_then(|name| name.to_str())
789            != Some("node_modules")
790    {
791        return vec![remapping];
792    }
793
794    let Ok(entries) = fs::read_dir(path) else { return vec![remapping] };
795    let mut packages = Vec::new();
796    for entry in entries {
797        let Ok(entry) = entry else { return vec![remapping] };
798        if !entry.path().is_dir() {
799            continue;
800        }
801        let Ok(name) = entry.file_name().into_string() else { return vec![remapping] };
802        let mut path = entry.path().display().to_string();
803        if !path.ends_with(['/', '\\']) {
804            path.push(MAIN_SEPARATOR);
805        }
806        packages.push(Remapping {
807            context: remapping.context.clone(),
808            name: format!("{scope}/{name}/"),
809            path,
810        });
811    }
812    packages.sort_by(|a, b| a.name.cmp(&b.name));
813    if packages.is_empty() { vec![remapping] } else { packages }
814}
815
816fn configured_auto_remapping(
817    mut remapping: Remapping,
818    configured_package_entries: &[(PathBuf, Remapping)],
819) -> Remapping {
820    let path = Path::new(&remapping.path);
821    let context = remapping.context.as_deref().map(Path::new);
822    if let Some((_, (_, configured))) = configured_package_entries
823        .iter()
824        .filter(|(lib, configured)| {
825            configured.name == remapping.name
826                && context.is_none_or(|owner| lib != owner && lib.starts_with(owner))
827        })
828        .filter_map(|entry @ (lib, _)| {
829            if path.starts_with(lib) {
830                Some(((0, usize::MAX - lib.components().count()), entry))
831            } else if context.is_some_and(|context| lib.starts_with(context))
832                && lib.starts_with(path)
833            {
834                Some(((1, lib.components().count()), entry))
835            } else {
836                None
837            }
838        })
839        .min_by(|(rank_a, (lib_a, _)), (rank_b, (lib_b, _))| {
840            rank_a.cmp(rank_b).then_with(|| lib_a.cmp(lib_b))
841        })
842    {
843        remapping.path.clone_from(&configured.path);
844    }
845    remapping
846}
847
848fn rebase_nested_remapping(
849    mut remapping: Remapping,
850    canonical: &Path,
851    lexical: &Path,
852) -> Remapping {
853    let rebase = |value: &str| {
854        let path = Path::new(value);
855        path.strip_prefix(canonical)
856            .map(|relative| lexical.join(relative).display().to_string())
857            .unwrap_or_else(|_| value.to_string())
858    };
859    remapping.path = rebase(&remapping.path);
860    if let Some(context) = &mut remapping.context {
861        let has_boundary = context.ends_with(['/', '\\']);
862        *context = if Path::new(context).is_absolute() {
863            rebase(context)
864        } else {
865            normalize_remapping_context(&lexical.join(&*context)).display().to_string()
866        };
867        if has_boundary && !context.ends_with(['/', '\\']) {
868            context.push(MAIN_SEPARATOR);
869        }
870    }
871    remapping
872}
873
874pub fn relative_remapping_preserving_context_boundary(
875    remapping: Remapping,
876    root: &Path,
877) -> RelativeRemapping {
878    let has_boundary =
879        remapping.context.as_deref().is_some_and(|context| context.ends_with(['/', '\\']));
880    let mut remapping = RelativeRemapping::new(remapping, root);
881    // Slash conversion on Windows only preserves a trailing native separator.
882    if has_boundary
883        && let Some(context) = &mut remapping.context
884        && !context.ends_with(MAIN_SEPARATOR)
885    {
886        if context.ends_with(['/', '\\']) {
887            context.pop();
888        }
889        context.push(MAIN_SEPARATOR);
890    }
891    remapping
892}
893
894/// Restricts dependency declarations to their lexical installation directory.
895fn scope_nested_remapping(mut remapping: Remapping, owner: &Path) -> Option<Remapping> {
896    let owner = normalize_remapping_context(owner);
897    let owner_prefix = format!("{}{MAIN_SEPARATOR}", owner.display());
898    let context = if let Some(context) = &remapping.context {
899        let has_boundary = context.ends_with(['/', '\\']);
900        let mut context = normalize_remapping_context(&owner.join(context)).display().to_string();
901        if has_boundary && !context.ends_with(MAIN_SEPARATOR) {
902            context.push(MAIN_SEPARATOR);
903        }
904        // Solidity contexts are lexical prefixes. Intersect them with an owner prefix that
905        // includes its directory boundary, so `lib/a` cannot affect `lib/abc`.
906        if owner_prefix.starts_with(&context) {
907            owner_prefix
908        } else if context.starts_with(&owner_prefix) {
909            context
910        } else {
911            return None;
912        }
913    } else {
914        owner_prefix
915    };
916    remapping.context = Some(context);
917    Some(remapping)
918}
919
920fn normalize_remapping_context(path: &Path) -> PathBuf {
921    let mut normalized = PathBuf::new();
922    for component in path.components() {
923        match component {
924            Component::CurDir => {}
925            Component::ParentDir => {
926                normalized.pop();
927            }
928            _ => normalized.push(component.as_os_str()),
929        }
930    }
931    normalized
932}
933
934/// Sorts by descending context depth, then by context, preserving order within each context.
935fn sort_by_context_specificity(remappings: &mut [Remapping]) {
936    remappings.sort_by(|a, b| {
937        let a_context = a.context.as_deref().unwrap_or_default();
938        let b_context = b.context.as_deref().unwrap_or_default();
939        Path::new(b_context)
940            .components()
941            .count()
942            .cmp(&Path::new(a_context).components().count())
943            .then_with(|| {
944                #[cfg(windows)]
945                {
946                    // Equivalent contexts must retain declaration order before deduplication.
947                    a_context.replace('\\', "/").cmp(&b_context.replace('\\', "/"))
948                }
949                #[cfg(not(windows))]
950                a_context.cmp(b_context)
951            })
952    });
953}
954
955/// Compares the targets of the overlapping part of two import namespaces.
956fn remappings_conflict(first: &Remapping, second: &Remapping, root: &Path) -> bool {
957    let (broad, narrow) = if remapping_name_is_prefix(&first.name, &second.name) {
958        (first, second)
959    } else if remapping_name_is_prefix(&second.name, &first.name) {
960        (second, first)
961    } else {
962        return false;
963    };
964    let broad_name = broad.name.strip_suffix('/').unwrap_or(&broad.name);
965    let narrow_name = narrow.name.strip_suffix('/').unwrap_or(&narrow.name);
966    let suffix = narrow_name.strip_prefix(broad_name).unwrap().trim_start_matches('/');
967    let broad_target = root.join(&broad.path).join(suffix);
968    let narrow_target = root.join(&narrow.path);
969    normalize_remapping_context(&foundry_compilers::utils::canonicalized(broad_target))
970        != normalize_remapping_context(&foundry_compilers::utils::canonicalized(narrow_target))
971}
972
973fn suppress_overridden_remapping_warnings(
974    warnings: &mut Vec<Warning>,
975    authoritative: &[Remapping],
976) {
977    warnings.retain(|warning| match warning {
978        Warning::ScopedDependencyRemapping { remapping, .. } => {
979            !authoritative.iter().any(|mapping| {
980                mapping.context.is_none()
981                    && remapping_name_is_prefix(&mapping.name, &remapping.name)
982            })
983        }
984        _ => true,
985    });
986}
987
988/// Returns migration advice for scoped declarations whose former global target root imports
989/// silently replace.
990///
991/// Root imports still resolve when a root mapping covers the alias, or when the root or an include
992/// path contains it. Otherwise imports of it fail with actionable compiler help, so warning here
993/// would flag projects that never import the alias.
994fn scoped_remapping_warnings(
995    scoped: Vec<RelativeRemapping>,
996    previous_globals: &BTreeSet<RelativeRemapping>,
997    current: &[Remapping],
998    project_paths: &[PathBuf],
999    include_paths: &[PathBuf],
1000    root: &Path,
1001) -> Vec<Warning> {
1002    let mut warned = BTreeSet::new();
1003    scoped
1004        .into_iter()
1005        .filter_map(|remapping| {
1006            let mut global = remapping.clone();
1007            global.context = None;
1008            let original = global.clone().to_relative_remapping();
1009            if !previous_globals.contains(&global)
1010                // Project-path aliases could not have supplied root imports before scoping.
1011                || project_paths.iter().any(|path| {
1012                    original.name.eq_ignore_ascii_case(&project_path_remapping_name(path))
1013                })
1014                || !warned.insert(global.clone())
1015            {
1016                return None;
1017            }
1018            // Like solc, the longest root alias wins; without one, the root or an include path
1019            // resolves it.
1020            let resolved = match current
1021                .iter()
1022                .filter(|mapping| {
1023                    mapping.context.is_none()
1024                        && remapping_name_is_prefix(&mapping.name, &global.name)
1025                })
1026                .max_by_key(|mapping| mapping.name.len())
1027            {
1028                Some(mapping) if remappings_conflict(mapping, &original, root) => {
1029                    let mut target =
1030                        RelativeRemapping::new(mapping.clone(), root).to_relative_remapping();
1031                    // Render the target with `/`, like the remappings in the same warning.
1032                    target.slash_path();
1033                    let suffix = original.name[mapping.name.trim_end_matches('/').len()..]
1034                        .trim_start_matches('/');
1035                    if suffix.is_empty() {
1036                        target.path
1037                    } else {
1038                        format!("{}/{suffix}", target.path.trim_end_matches('/'))
1039                    }
1040                }
1041                None => {
1042                    let found = std::iter::once(root.to_path_buf())
1043                        .chain(include_paths.iter().map(|path| root.join(path)))
1044                        .map(|base| base.join(&original.name))
1045                        .find(|path| path.exists())?;
1046                    let found =
1047                        project_path_remapping_name(found.strip_prefix(root).unwrap_or(&found));
1048                    if original.name.ends_with('/') {
1049                        found
1050                    } else {
1051                        found.trim_end_matches('/').to_string()
1052                    }
1053                }
1054                _ => return None,
1055            };
1056            Some(Warning::ScopedDependencyRemapping { remapping, resolved })
1057        })
1058        .collect()
1059}
1060
1061fn project_path_remapping_name(path: &Path) -> String {
1062    #[cfg(windows)]
1063    let path = path.to_slash_lossy();
1064    #[cfg(not(windows))]
1065    let path = path.to_string_lossy();
1066    format!("{path}/")
1067}
1068
1069impl Provider for RemappingsProvider<'_> {
1070    fn metadata(&self) -> Metadata {
1071        Metadata::named("Remapping Provider")
1072    }
1073
1074    fn data(&self) -> Result<Map<Profile, Dict>, Error> {
1075        let output = match &self.remappings {
1076            Ok(remappings) => self.get_remappings(remappings.clone()),
1077            Err(err) => {
1078                if let figment::error::Kind::MissingField(_) = err.kind {
1079                    self.get_remappings(vec![])
1080                } else {
1081                    return Err(err.clone());
1082                }
1083            }
1084        }?;
1085
1086        // turn the absolute remapping into a relative one by stripping the `root`
1087        let remappings = output
1088            .remappings
1089            .into_iter()
1090            .map(|r| relative_remapping_preserving_context_boundary(r, self.root).to_string())
1091            .collect::<Vec<_>>();
1092        let generated_remappings = output
1093            .generated_contextual_remappings
1094            .into_iter()
1095            .map(|r| relative_remapping_preserving_context_boundary(r, self.root).to_string())
1096            .collect::<Vec<_>>();
1097
1098        Ok(Map::from([(
1099            Config::selected_profile(),
1100            Dict::from([
1101                ("remappings".to_string(), figment::value::Value::from(remappings)),
1102                ("__warnings".to_string(), figment::value::Value::serialize(output.warnings)?),
1103                (
1104                    GENERATED_REMAPPINGS_KEY.to_string(),
1105                    figment::value::Value::from(generated_remappings),
1106                ),
1107            ]),
1108        )]))
1109    }
1110
1111    fn profile(&self) -> Option<Profile> {
1112        Some(Config::selected_profile())
1113    }
1114}
1115
1116#[cfg(test)]
1117mod tests {
1118    use super::*;
1119    use tempfile::tempdir;
1120
1121    #[cfg(unix)]
1122    use std::os::unix::fs::symlink;
1123
1124    #[cfg(unix)]
1125    #[test]
1126    fn nested_remappings_ignore_symlinks_back_to_the_project_root() {
1127        let temp = tempdir().unwrap();
1128        let root = temp.path();
1129        fs::create_dir(root.join("lib")).unwrap();
1130        fs::write(root.join(Config::FILE_NAME), "").unwrap();
1131        symlink(root, root.join("lib/self")).unwrap();
1132        let libs = vec![PathBuf::from("lib")];
1133        let provider = RemappingsProvider {
1134            auto_detect_remappings: true,
1135            lib_paths: Cow::Borrowed(&libs),
1136            root,
1137            remappings: Ok(vec![]),
1138            project_paths: Vec::new(),
1139            include_paths: Vec::new(),
1140            warnings: Ok(Vec::new()),
1141        };
1142
1143        assert!(provider.find_nested_foundry_remappings().unwrap().is_empty());
1144    }
1145
1146    #[cfg(unix)]
1147    #[test]
1148    fn nested_remappings_visit_each_config_once_across_a_dependency_cycle() {
1149        let temp = tempdir().unwrap();
1150        let root = temp.path().join("project");
1151        let dependency = temp.path().join("dependency");
1152        fs::create_dir_all(root.join("lib")).unwrap();
1153        fs::create_dir_all(dependency.join("lib")).unwrap();
1154        fs::create_dir(dependency.join("custom-source")).unwrap();
1155        fs::write(root.join(Config::FILE_NAME), "").unwrap();
1156        fs::write(
1157            dependency.join(Config::FILE_NAME),
1158            "[profile.default]\nsrc = \"custom-source\"\n",
1159        )
1160        .unwrap();
1161        symlink(&dependency, root.join("lib/dependency-alias")).unwrap();
1162        symlink(&root, dependency.join("lib/back")).unwrap();
1163        let libs = vec![PathBuf::from("lib")];
1164        let provider = RemappingsProvider {
1165            auto_detect_remappings: true,
1166            lib_paths: Cow::Borrowed(&libs),
1167            root: &root,
1168            remappings: Ok(vec![]),
1169            project_paths: Vec::new(),
1170            include_paths: Vec::new(),
1171            warnings: Ok(Vec::new()),
1172        };
1173
1174        assert_eq!(
1175            provider.find_nested_foundry_remappings().unwrap(),
1176            vec![(
1177                root.join("lib/dependency-alias"),
1178                Remapping {
1179                    context: None,
1180                    name: "dependency-alias/".to_string(),
1181                    path: format!("{}/", root.join("lib/dependency-alias/custom-source").display()),
1182                },
1183                NestedRemappingKind::PackageEntry,
1184            )]
1185        );
1186    }
1187
1188    #[cfg(unix)]
1189    #[test]
1190    fn nested_remappings_traverse_physical_dependency_after_symlink_alias() {
1191        let temp = tempdir().unwrap();
1192        let root = temp.path().join("project");
1193        let dependency = root.join("lib/z-dependency");
1194        let nested = dependency.join("lib/nested");
1195        fs::create_dir_all(&nested).unwrap();
1196        fs::create_dir(nested.join("custom-source")).unwrap();
1197        fs::write(root.join(Config::FILE_NAME), "").unwrap();
1198        fs::write(dependency.join(Config::FILE_NAME), "[profile.default]\nlibs = [\"lib\"]\n")
1199            .unwrap();
1200        fs::write(nested.join(Config::FILE_NAME), "[profile.default]\nsrc = \"custom-source\"\n")
1201            .unwrap();
1202        symlink(&dependency, root.join("lib/a-dependency-alias")).unwrap();
1203        let libs = vec![PathBuf::from("lib")];
1204        let provider = RemappingsProvider {
1205            auto_detect_remappings: true,
1206            lib_paths: Cow::Borrowed(&libs),
1207            root: &root,
1208            remappings: Ok(vec![]),
1209            project_paths: Vec::new(),
1210            include_paths: Vec::new(),
1211            warnings: Ok(Vec::new()),
1212        };
1213
1214        assert!(provider.find_nested_foundry_remappings().unwrap().contains(&(
1215            nested.clone(),
1216            Remapping {
1217                context: None,
1218                name: "nested/".to_string(),
1219                path: format!("{}/", nested.join("custom-source").display()),
1220            },
1221            NestedRemappingKind::PackageEntry,
1222        )));
1223    }
1224
1225    #[test]
1226    fn relative_remapping_preserves_context_directory_boundary() {
1227        let remapping = Remapping {
1228            context: Some("lib/outer/".to_string()),
1229            name: "inner/".to_string(),
1230            path: format!("lib{MAIN_SEPARATOR}outer{MAIN_SEPARATOR}lib{MAIN_SEPARATOR}inner"),
1231        };
1232
1233        let remapping = relative_remapping_preserving_context_boundary(remapping, Path::new("."));
1234        assert!(remapping.context.as_ref().unwrap().ends_with(MAIN_SEPARATOR));
1235        assert_eq!(remapping.to_string(), "lib/outer/:inner/=lib/outer/lib/inner/");
1236    }
1237
1238    #[test]
1239    fn config_merge_only_suppresses_generated_refinements() {
1240        let cli = Remapping {
1241            context: None,
1242            name: "pkg/sub/".to_string(),
1243            path: "src/local/".to_string(),
1244        };
1245        let contextual = Remapping {
1246            context: Some("lib/dep/".to_string()),
1247            name: "pkg/".to_string(),
1248            path: "lib/dep/vendor/pkg/".to_string(),
1249        };
1250        let mut explicit = Remappings::new_with_remappings(vec![cli.clone()]);
1251        explicit.extend_with_config_remappings(vec![contextual.clone()], &[]);
1252        assert_eq!(explicit.into_inner(), vec![cli.clone(), contextual.clone()]);
1253
1254        let global = Remapping {
1255            context: None,
1256            name: "pkg/".to_string(),
1257            path: "lib/dep/lib/pkg/".to_string(),
1258        };
1259        let refinement = Remapping {
1260            context: Some("lib/dep/".to_string()),
1261            name: "pkg/".to_string(),
1262            path: "lib/dep/lib/pkg/contracts/".to_string(),
1263        };
1264        let cli_deep = Remapping {
1265            context: None,
1266            name: "pkg/sub/deep/".to_string(),
1267            path: "src/deep/".to_string(),
1268        };
1269        let mut generated = Remappings::new_with_remappings(vec![cli.clone(), cli_deep.clone()]);
1270        generated.extend_with_config_remappings(
1271            vec![refinement.clone(), global.clone()],
1272            std::slice::from_ref(&refinement),
1273        );
1274        let mut overlay = cli.clone();
1275        overlay.context.clone_from(&refinement.context);
1276        let mut deep_overlay = cli_deep.clone();
1277        deep_overlay.context.clone_from(&refinement.context);
1278        assert_eq!(
1279            generated.into_inner(),
1280            vec![cli.clone(), cli_deep, deep_overlay, overlay, refinement, global.clone()]
1281        );
1282
1283        let broad_cli =
1284            Remapping { context: None, name: "pkg/".to_string(), path: "src/local/".to_string() };
1285        let mut generated = Remappings::new_with_remappings(vec![broad_cli.clone(), cli.clone()]);
1286        generated.extend_with_config_remappings(
1287            vec![contextual.clone(), global],
1288            std::slice::from_ref(&contextual),
1289        );
1290        assert_eq!(generated.into_inner(), vec![broad_cli, cli]);
1291
1292        let contextual_cli = Remapping {
1293            context: Some("lib/dep/".to_string()),
1294            name: "pkg/".to_string(),
1295            path: "src/contextual/".to_string(),
1296        };
1297        let nested_refinement = Remapping {
1298            context: Some("lib/dep/lib/nested/".to_string()),
1299            name: "pkg/".to_string(),
1300            path: "lib/dep/lib/nested/lib/pkg/".to_string(),
1301        };
1302        let mut generated = Remappings::new_with_remappings(vec![contextual_cli.clone()]);
1303        generated.extend_with_config_remappings(
1304            vec![nested_refinement.clone()],
1305            std::slice::from_ref(&nested_refinement),
1306        );
1307        assert_eq!(generated.into_inner(), vec![contextual_cli]);
1308    }
1309
1310    #[cfg(windows)]
1311    #[test]
1312    fn contextual_overlay_accepts_mixed_windows_separators() {
1313        let authoritative = Remapping {
1314            context: Some(r"C:\workspace\lib/a/".to_string()),
1315            name: "shared/".to_string(),
1316            path: "src/override/".to_string(),
1317        };
1318        let refinement = Remapping {
1319            context: Some(r"C:\workspace\lib\a\lib\x\".to_string()),
1320            name: "shared/".to_string(),
1321            path: "lib/a/lib/x/lib/shared/src/".to_string(),
1322        };
1323
1324        assert!(contextual_overlays(&[authoritative], &refinement).is_none());
1325    }
1326
1327    #[test]
1328    fn nested_remapping_groups_are_sorted() {
1329        let root = tempfile::tempdir().unwrap();
1330        for dependency in ["zeta", "alpha"] {
1331            let dependency = root.path().join("lib").join(dependency);
1332            fs::create_dir_all(&dependency).unwrap();
1333            fs::write(dependency.join(Config::FILE_NAME), "[profile.default]\n").unwrap();
1334            fs::write(dependency.join("remappings.txt"), "pkg/=src/\n").unwrap();
1335        }
1336        let libs = vec![PathBuf::from("lib")];
1337        let provider = RemappingsProvider {
1338            auto_detect_remappings: true,
1339            lib_paths: Cow::Borrowed(&libs),
1340            root: root.path(),
1341            remappings: Ok(Vec::new()),
1342            project_paths: Vec::new(),
1343            include_paths: Vec::new(),
1344            warnings: Ok(Vec::new()),
1345        };
1346
1347        let dependencies = provider
1348            .find_nested_foundry_remappings()
1349            .unwrap()
1350            .into_iter()
1351            .map(|(dependency, _, _)| {
1352                dependency.file_name().unwrap().to_string_lossy().into_owned()
1353            })
1354            .collect::<Vec<_>>();
1355        assert_eq!(dependencies, ["alpha", "alpha", "zeta", "zeta"]);
1356    }
1357
1358    #[test]
1359    fn test_sol_file_remappings() {
1360        let mut remappings = Remappings::new();
1361
1362        // First valid remapping
1363        remappings.push(Remapping {
1364            context: None,
1365            name: "MyContract.sol".to_string(),
1366            path: "implementations/Contract1.sol".to_string(),
1367        });
1368
1369        // Same source to different target (should be rejected)
1370        remappings.push(Remapping {
1371            context: None,
1372            name: "MyContract.sol".to_string(),
1373            path: "implementations/Contract2.sol".to_string(),
1374        });
1375
1376        // Different source to same target (should be allowed)
1377        remappings.push(Remapping {
1378            context: None,
1379            name: "OtherContract.sol".to_string(),
1380            path: "implementations/Contract1.sol".to_string(),
1381        });
1382
1383        // Exact duplicate (should be silently ignored)
1384        remappings.push(Remapping {
1385            context: None,
1386            name: "MyContract.sol".to_string(),
1387            path: "implementations/Contract1.sol".to_string(),
1388        });
1389
1390        // Invalid .sol remapping (target not .sol)
1391        remappings.push(Remapping {
1392            context: None,
1393            name: "Invalid.sol".to_string(),
1394            path: "implementations/Contract1.txt".to_string(),
1395        });
1396
1397        let result = remappings.into_inner();
1398        assert_eq!(result.len(), 2, "Should only have 2 valid remappings");
1399
1400        // Verify the correct remappings exist
1401        assert!(
1402            result
1403                .iter()
1404                .any(|r| r.name == "MyContract.sol" && r.path == "implementations/Contract1.sol"),
1405            "Should keep first mapping of MyContract.sol"
1406        );
1407        assert!(
1408            !result
1409                .iter()
1410                .any(|r| r.name == "MyContract.sol" && r.path == "implementations/Contract2.sol"),
1411            "Should keep first mapping of MyContract.sol"
1412        );
1413        assert!(result.iter().any(|r| r.name == "OtherContract.sol" && r.path == "implementations/Contract1.sol"),
1414            "Should allow different source to same target");
1415
1416        // Verify the rejected remapping doesn't exist
1417        assert!(
1418            !result
1419                .iter()
1420                .any(|r| r.name == "MyContract.sol" && r.path == "implementations/Contract2.sol"),
1421            "Should reject same source to different target"
1422        );
1423    }
1424
1425    #[test]
1426    fn test_mixed_remappings() {
1427        let mut remappings = Remappings::new();
1428
1429        remappings.push(Remapping {
1430            context: None,
1431            name: "@openzeppelin-contracts/".to_string(),
1432            path: "lib/openzeppelin-contracts/".to_string(),
1433        });
1434        remappings.push(Remapping {
1435            context: None,
1436            name: "@openzeppelin/contracts/".to_string(),
1437            path: "lib/openzeppelin/contracts/".to_string(),
1438        });
1439
1440        remappings.push(Remapping {
1441            context: None,
1442            name: "MyContract.sol".to_string(),
1443            path: "os/Contract.sol".to_string(),
1444        });
1445
1446        let result = remappings.into_inner();
1447        assert_eq!(result.len(), 3, "Should have 3 remappings");
1448        assert_eq!(result.first().unwrap().name, "@openzeppelin-contracts/");
1449        assert_eq!(result.first().unwrap().path, "lib/openzeppelin-contracts/");
1450        assert_eq!(result.get(1).unwrap().name, "@openzeppelin/contracts/");
1451        assert_eq!(result.get(1).unwrap().path, "lib/openzeppelin/contracts/");
1452        assert_eq!(result.get(2).unwrap().name, "MyContract.sol");
1453        assert_eq!(result.get(2).unwrap().path, "os/Contract.sol");
1454    }
1455
1456    #[test]
1457    fn test_remappings_with_context() {
1458        let mut remappings = Remappings::new();
1459
1460        // Same name but different contexts
1461        remappings.push(Remapping {
1462            context: Some("test/".to_string()),
1463            name: "MyContract.sol".to_string(),
1464            path: "test/Contract.sol".to_string(),
1465        });
1466        remappings.push(Remapping {
1467            context: Some("prod/".to_string()),
1468            name: "MyContract.sol".to_string(),
1469            path: "prod/Contract.sol".to_string(),
1470        });
1471
1472        let result = remappings.into_inner();
1473        assert_eq!(result.len(), 2, "Should allow same name with different contexts");
1474        assert!(
1475            result
1476                .iter()
1477                .any(|r| r.context == Some("test/".to_string()) && r.path == "test/Contract.sol")
1478        );
1479        assert!(
1480            result
1481                .iter()
1482                .any(|r| r.context == Some("prod/".to_string()) && r.path == "prod/Contract.sol")
1483        );
1484    }
1485
1486    #[test]
1487    fn configured_auto_remapping_uses_nearest_owned_package() {
1488        let configured = vec![
1489            (
1490                PathBuf::from("lib/shared"),
1491                Remapping {
1492                    context: None,
1493                    name: "shared/".to_string(),
1494                    path: "lib/shared/outer-src/".to_string(),
1495                },
1496            ),
1497            (
1498                PathBuf::from("lib/shared/lib/shared"),
1499                Remapping {
1500                    context: None,
1501                    name: "shared/".to_string(),
1502                    path: "lib/shared/lib/shared/inner-src/".to_string(),
1503                },
1504            ),
1505        ];
1506        let candidate = |context: &str, path: &str| Remapping {
1507            context: Some(context.to_string()),
1508            name: "shared/".to_string(),
1509            path: path.to_string(),
1510        };
1511
1512        assert_eq!(
1513            configured_auto_remapping(
1514                candidate("lib/shared/", "lib/shared/lib/shared/src/"),
1515                &configured,
1516            ),
1517            candidate("lib/shared/", "lib/shared/lib/shared/inner-src/")
1518        );
1519        assert_eq!(
1520            configured_auto_remapping(candidate("lib/shared/", "lib/shared/lib/"), &configured),
1521            candidate("lib/shared/", "lib/shared/lib/shared/inner-src/")
1522        );
1523
1524        let nested = candidate("lib/shared/lib/nested/", "lib/shared/lib/nested/lib/shared/src/");
1525        assert_eq!(
1526            configured_auto_remapping(nested.clone(), &configured),
1527            nested,
1528            "configured ancestors must not rewrite remappings owned by nested dependencies",
1529        );
1530    }
1531
1532    #[test]
1533    fn test_root_remapping_prefix_precedence_is_directional() {
1534        let remapping = |name: &str, path: &str| Remapping {
1535            context: None,
1536            name: name.to_string(),
1537            path: path.to_string(),
1538        };
1539
1540        let mut narrow_root =
1541            Remappings::new_with_remappings(vec![remapping("pkg/sub/", "src/local/")]);
1542        narrow_root.extend(vec![remapping("pkg/", "lib/pkg/src/")]);
1543        assert_eq!(
1544            narrow_root.into_inner(),
1545            vec![remapping("pkg/sub/", "src/local/"), remapping("pkg/", "lib/pkg/src/")]
1546        );
1547
1548        let mut broad_root = Remappings::new_with_remappings(vec![remapping("pkg/", "src/local/")]);
1549        broad_root.extend(vec![
1550            remapping("pkg/sub/", "lib/pkg/src/sub/"),
1551            remapping("pkg-other/", "lib/pkg-other/src/"),
1552        ]);
1553        assert_eq!(
1554            broad_root.into_inner(),
1555            vec![remapping("pkg/", "src/local/"), remapping("pkg-other/", "lib/pkg-other/src/")]
1556        );
1557
1558        let mut duplicate = Remappings::new_with_remappings(vec![remapping("pkg/", "src/local/")]);
1559        duplicate.extend(vec![remapping("pkg/", "lib/pkg/src/")]);
1560        assert_eq!(duplicate.remappings, vec![remapping("pkg/", "src/local/")]);
1561
1562        // The first remapping wins regardless of whether either name carries a trailing slash.
1563        for (existing, incoming) in
1564            [("pkg", "pkg"), ("pkg", "pkg/"), ("pkg/", "pkg"), ("pkg", "pkg/sub/")]
1565        {
1566            let mut duplicate =
1567                Remappings::new_with_remappings(vec![remapping(existing, "src/local/")]);
1568            duplicate.extend(vec![remapping(incoming, "lib/pkg/src/")]);
1569            assert_eq!(
1570                duplicate.remappings,
1571                vec![remapping(existing, "src/local/")],
1572                "{existing} then {incoming}"
1573            );
1574        }
1575
1576        // Repeated slashes are significant Solidity import-prefix characters.
1577        for incoming in ["pkg/", "pkg/sub/"] {
1578            let existing = remapping("pkg//", "src/double-slash/");
1579            let mut distinct = Remappings::new_with_remappings(vec![existing.clone()]);
1580            let incoming = remapping(incoming, "lib/pkg/src/");
1581            distinct.extend(vec![incoming.clone()]);
1582            assert_eq!(distinct.remappings, vec![existing, incoming]);
1583        }
1584
1585        let contextual_remapping = |context: &str, name: &str, path: &str| Remapping {
1586            context: Some(context.to_string()),
1587            name: name.to_string(),
1588            path: path.to_string(),
1589        };
1590        let mut same_context = Remappings::new_with_remappings(vec![contextual_remapping(
1591            "src/",
1592            "pkg/",
1593            "src/local/",
1594        )]);
1595        same_context.extend(vec![contextual_remapping("src/", "pkg/sub/", "lib/pkg/src/sub/")]);
1596        assert_eq!(
1597            same_context.remappings,
1598            vec![contextual_remapping("src/", "pkg/", "src/local/")]
1599        );
1600
1601        let mut different_context = Remappings::new_with_remappings(vec![contextual_remapping(
1602            "src/",
1603            "pkg/",
1604            "src/local/",
1605        )]);
1606        different_context.extend(vec![contextual_remapping(
1607            "test/",
1608            "pkg/sub/",
1609            "lib/pkg/src/sub/",
1610        )]);
1611        assert_eq!(
1612            different_context.remappings,
1613            vec![
1614                contextual_remapping("src/", "pkg/", "src/local/"),
1615                contextual_remapping("test/", "pkg/sub/", "lib/pkg/src/sub/"),
1616            ]
1617        );
1618
1619        let mut narrow_root_without_slash =
1620            Remappings::new_with_remappings(vec![remapping("pkg/sub", "src/local/")]);
1621        narrow_root_without_slash.extend(vec![remapping("pkg", "lib/pkg/src/")]);
1622        assert_eq!(
1623            narrow_root_without_slash.remappings,
1624            vec![remapping("pkg/sub", "src/local/"), remapping("pkg", "lib/pkg/src/")]
1625        );
1626
1627        let mut broad_root_without_slash =
1628            Remappings::new_with_remappings(vec![remapping("pkg", "src/local/")]);
1629        broad_root_without_slash.extend(vec![
1630            remapping("pkg/sub", "lib/pkg/src/sub/"),
1631            remapping("pkg-other", "lib/pkg-other/src/"),
1632        ]);
1633        assert_eq!(
1634            broad_root_without_slash.remappings,
1635            vec![remapping("pkg", "src/local/"), remapping("pkg-other", "lib/pkg-other/src/")]
1636        );
1637    }
1638
1639    #[test]
1640    fn dependency_remappings_are_scoped_to_their_owner() {
1641        figment::Jail::expect_with(|_| {
1642            let temp = tempdir().unwrap();
1643            let root = dunce::canonicalize(temp.path()).unwrap();
1644            let owner = root.join("lib/a-helper");
1645            fs::create_dir_all(owner.join("src")).unwrap();
1646            fs::create_dir_all(root.join("lib/victim/src")).unwrap();
1647            fs::write(owner.join("src/Helper.sol"), "contract Helper {}\n").unwrap();
1648            fs::write(root.join("lib/victim/src/Victim.sol"), "contract Victim {}\n").unwrap();
1649            fs::write(root.join(Config::FILE_NAME), "[profile.default]\n").unwrap();
1650
1651            for (remapping, scoped) in [
1652                ("victim/=src/".to_string(), Some("lib/a-helper/")),
1653                ("../../src/:victim/=src/".to_string(), None),
1654                ("../a-helper-other/:victim/=src/".to_string(), None),
1655                ("../../:victim/=src/".to_string(), Some("lib/a-helper/")),
1656                // The parser treats a Windows drive letter's colon as the context separator.
1657                #[cfg(unix)]
1658                (format!("{}:victim/=src/", root.display()), Some("lib/a-helper/")),
1659                ("src/../src/Pre:victim/=src/".to_string(), Some("lib/a-helper/src/Pre")),
1660            ] {
1661                fs::write(
1662                    owner.join(Config::FILE_NAME),
1663                    format!("[profile.default]\nremappings = [{remapping:?}]\n"),
1664                )
1665                .unwrap();
1666                let config = Config::load_with_root(&root).unwrap();
1667                let mut expected = Vec::new();
1668                if let Some(scoped) = scoped {
1669                    expected.push(format!("{scoped}:victim/=lib/a-helper/src/"));
1670                }
1671                expected.extend([
1672                    "a-helper/=lib/a-helper/src/".to_string(),
1673                    "victim/=lib/victim/src/".to_string(),
1674                ]);
1675                assert_eq!(
1676                    config
1677                        .get_all_remappings()
1678                        .map(|remapping| remapping.to_string())
1679                        .collect::<Vec<_>>(),
1680                    expected,
1681                    "remapping: {remapping}"
1682                );
1683            }
1684
1685            Ok(())
1686        });
1687    }
1688
1689    #[test]
1690    fn external_sources_preserve_dependency_declarations() {
1691        figment::Jail::expect_with(|_| {
1692            let temp = tempdir().unwrap();
1693            let root = dunce::canonicalize(temp.path()).unwrap();
1694            let owner = root.join("lib/a");
1695            let source = root.join("external");
1696            fs::create_dir_all(owner.join("src/internal")).unwrap();
1697            fs::create_dir_all(&source).unwrap();
1698            fs::write(root.join(Config::FILE_NAME), "[profile.default]\n").unwrap();
1699            fs::write(source.join("A.sol"), "contract A {}\n").unwrap();
1700            fs::write(owner.join("remappings.txt"), "file-alias/=src/internal/\n").unwrap();
1701
1702            for src in [source.display().to_string(), "../../external".to_string()] {
1703                fs::write(
1704                    owner.join(Config::FILE_NAME),
1705                    format!(
1706                        "[profile.default]\nsrc = {src:?}\nremappings = [\"private/=src/internal/\", \"../../external/:contextual/=src/internal/\"]\n"
1707                    ),
1708                )
1709                .unwrap();
1710                let config = Config::load_with_root(&root).unwrap();
1711                let remappings = config.get_all_remappings().collect::<Vec<_>>();
1712                let package = remappings.iter().find(|remapping| remapping.name == "a/").unwrap();
1713                assert_eq!(dunce::canonicalize(root.join(&package.path)).unwrap(), source);
1714                for alias in ["private/", "file-alias/"] {
1715                    let remapping =
1716                        remappings.iter().find(|remapping| remapping.name == alias).unwrap();
1717                    assert_eq!(remapping.context, None);
1718                    assert_eq!(remapping.path, "lib/a/src/internal/");
1719                }
1720                let contextual =
1721                    remappings.iter().find(|remapping| remapping.name == "contextual/").unwrap();
1722                assert_eq!(contextual.context.as_deref(), Some("external/"));
1723                assert_eq!(remappings.len(), 4);
1724            }
1725
1726            Ok(())
1727        });
1728    }
1729
1730    #[cfg(unix)]
1731    #[test]
1732    fn symlinked_external_source_preserves_global_aliases() {
1733        figment::Jail::expect_with(|_| {
1734            let temp = tempdir().unwrap();
1735            let root = dunce::canonicalize(temp.path()).unwrap();
1736            let owner = root.join("lib/a");
1737            let source = root.join("external");
1738            fs::create_dir_all(&owner).unwrap();
1739            fs::create_dir_all(&source).unwrap();
1740            fs::write(root.join(Config::FILE_NAME), "[profile.default]\n").unwrap();
1741            fs::write(
1742                owner.join(Config::FILE_NAME),
1743                "[profile.default]\nremappings = [\"private/=src/\"]\n",
1744            )
1745            .unwrap();
1746            fs::write(source.join("A.sol"), "contract A {}\n").unwrap();
1747            symlink(&source, owner.join("src")).unwrap();
1748
1749            let config = Config::load_with_root(&root).unwrap();
1750            let remapping =
1751                config.get_all_remappings().find(|remapping| remapping.name == "private/").unwrap();
1752            assert_eq!(remapping.context, None);
1753            assert_eq!(remapping.path, "lib/a/src/");
1754
1755            Ok(())
1756        });
1757    }
1758
1759    #[test]
1760    fn equally_deep_packages_preserve_source_precedence() {
1761        figment::Jail::expect_with(|_| {
1762            for (source_a, source_b) in [("custom-source", "src"), ("custom/src", "src")] {
1763                let temp = tempdir().unwrap();
1764                let root = temp.path();
1765                fs::write(root.join(Config::FILE_NAME), "[profile.default]\n").unwrap();
1766                for (name, source) in [("a", source_a), ("b", source_b)] {
1767                    let owner = root.join("lib").join(name);
1768                    let package = owner.join("lib/shared");
1769                    fs::create_dir_all(owner.join("src")).unwrap();
1770                    fs::create_dir_all(package.join(source)).unwrap();
1771                    fs::write(owner.join(Config::FILE_NAME), "[profile.default]\n").unwrap();
1772                    fs::write(owner.join("src/Owner.sol"), "contract Owner {}\n").unwrap();
1773                    fs::write(
1774                        package.join(Config::FILE_NAME),
1775                        format!("[profile.default]\nsrc = {source:?}\n"),
1776                    )
1777                    .unwrap();
1778                    fs::write(package.join(source).join("Shared.sol"), "contract Shared {}\n")
1779                        .unwrap();
1780                }
1781
1782                let config = Config::load_with_root(root).unwrap();
1783                let shared = config
1784                    .get_all_remappings()
1785                    .find(|remapping| remapping.context.is_none() && remapping.name == "shared/")
1786                    .unwrap();
1787                assert_eq!(
1788                    Path::new(&shared.path),
1789                    Path::new("lib/b/lib/shared").join(source_b),
1790                    "{source_a} vs {source_b}"
1791                );
1792            }
1793
1794            Ok(())
1795        });
1796    }
1797
1798    #[test]
1799    fn package_precedence_uses_target_depth_before_installation_depth() {
1800        figment::Jail::expect_with(|_| {
1801            let temp = tempdir().unwrap();
1802            let root = temp.path();
1803            fs::write(root.join(Config::FILE_NAME), "[profile.default]\n").unwrap();
1804            for (package, source) in [
1805                ("lib/shared", "custom/deep/source/extra"),
1806                ("lib/outer", "src"),
1807                ("lib/outer/lib/shared", "custom"),
1808            ] {
1809                let package = root.join(package);
1810                fs::create_dir_all(package.join(source)).unwrap();
1811                fs::write(
1812                    package.join(Config::FILE_NAME),
1813                    format!(
1814                        "[profile.default]\nsrc = {:?}\n",
1815                        package.join(source).display().to_string()
1816                    ),
1817                )
1818                .unwrap();
1819                fs::write(package.join(source).join("Contract.sol"), "contract Contract {}\n")
1820                    .unwrap();
1821            }
1822
1823            let config = Config::load_with_root(root).unwrap();
1824            let shared = config
1825                .get_all_remappings()
1826                .find(|remapping| remapping.context.is_none() && remapping.name == "shared/")
1827                .unwrap();
1828            assert_eq!(Path::new(&shared.path), Path::new("lib/outer/lib/shared/custom"));
1829
1830            Ok(())
1831        });
1832    }
1833
1834    #[cfg(unix)]
1835    #[test]
1836    fn nested_library_paths_cannot_forge_dependency_owners() {
1837        figment::Jail::expect_with(|_| {
1838            let temp = tempdir().unwrap();
1839            let root = dunce::canonicalize(temp.path()).unwrap();
1840            let owner = root.join("lib/h");
1841            let substitute = owner.join("p/victim");
1842            for path in [
1843                owner.join("src"),
1844                owner.join("p/q/r"),
1845                substitute.join("evil-src"),
1846                root.join("lib/victim/src"),
1847            ] {
1848                fs::create_dir_all(path).unwrap();
1849            }
1850            fs::write(root.join(Config::FILE_NAME), "[profile.default]\n").unwrap();
1851            fs::write(
1852                owner.join(Config::FILE_NAME),
1853                "[profile.default]\nlibs = [\"evil/../..\"]\n",
1854            )
1855            .unwrap();
1856            fs::write(
1857                substitute.join(Config::FILE_NAME),
1858                "[profile.default]\nsrc = \"evil-src\"\nremappings = [\"solmate/=evil-src/\"]\n",
1859            )
1860            .unwrap();
1861            fs::write(root.join("lib/victim/foundry.toml"), "[profile.default]\n").unwrap();
1862            symlink("p/q/r", owner.join("evil")).unwrap();
1863
1864            let config = Config::load_with_root(&root).unwrap();
1865            assert_eq!(
1866                config
1867                    .get_all_remappings()
1868                    .filter(|remapping| remapping.name == "solmate/")
1869                    .map(|remapping| remapping.to_string())
1870                    .collect::<Vec<_>>(),
1871                Vec::<String>::new(),
1872            );
1873
1874            Ok(())
1875        });
1876    }
1877
1878    #[cfg(unix)]
1879    #[test]
1880    fn nested_library_symlinks_stay_inside_their_owner() {
1881        figment::Jail::expect_with(|_| {
1882            for external in [false, true] {
1883                let temp = tempdir().unwrap();
1884                let root = dunce::canonicalize(temp.path()).unwrap();
1885                let owner = root.join("lib/h");
1886                let packages = if external { root.join("outside") } else { owner.join("packages") };
1887                let source = packages.join("nested/src");
1888                fs::create_dir_all(owner.join("src")).unwrap();
1889                fs::create_dir_all(&source).unwrap();
1890                fs::write(root.join(Config::FILE_NAME), "[profile.default]\n").unwrap();
1891                fs::write(
1892                    owner.join(Config::FILE_NAME),
1893                    "[profile.default]\nlibs = [\"vendor\"]\n",
1894                )
1895                .unwrap();
1896                fs::write(
1897                    packages.join("nested/foundry.toml"),
1898                    "[profile.default]\nremappings = [\"private/=src/\"]\n",
1899                )
1900                .unwrap();
1901                symlink(&packages, owner.join("vendor")).unwrap();
1902
1903                let config = Config::load_with_root(&root).unwrap();
1904                assert_eq!(
1905                    config
1906                        .get_all_remappings()
1907                        .filter(|remapping| remapping.name == "private/")
1908                        .map(|remapping| dunce::canonicalize(root.join(&remapping.path)).unwrap())
1909                        .collect::<BTreeSet<_>>(),
1910                    if external { BTreeSet::new() } else { BTreeSet::from([source]) },
1911                    "external={external}",
1912                );
1913            }
1914
1915            Ok(())
1916        });
1917    }
1918
1919    #[test]
1920    fn nested_library_paths_must_be_relative_and_contained() {
1921        figment::Jail::expect_with(|_| {
1922            let temp = tempdir().unwrap();
1923            let root = dunce::canonicalize(temp.path()).unwrap();
1924            let owner = root.join("lib/h");
1925            let internal = owner.join("vendor");
1926            let external = root.join("lib/outside");
1927            fs::create_dir_all(owner.join("src")).unwrap();
1928            fs::write(root.join(Config::FILE_NAME), "[profile.default]\n").unwrap();
1929            for packages in [&internal, &external] {
1930                fs::create_dir_all(packages.join("nested/src")).unwrap();
1931                fs::write(
1932                    packages.join("nested/foundry.toml"),
1933                    "[profile.default]\nremappings = [\"private/=src/\"]\n",
1934                )
1935                .unwrap();
1936            }
1937
1938            for (lib, allowed) in [
1939                ("vendor".to_string(), true),
1940                ("vendor/../vendor".to_string(), true),
1941                ("../outside".to_string(), false),
1942                (internal.display().to_string(), false),
1943                (external.display().to_string(), false),
1944            ] {
1945                fs::write(
1946                    owner.join(Config::FILE_NAME),
1947                    format!("[profile.default]\nlibs = [{lib:?}]\n"),
1948                )
1949                .unwrap();
1950                let config = Config::load_with_root(&root).unwrap();
1951                assert_eq!(
1952                    config
1953                        .get_all_remappings()
1954                        .filter(|remapping| remapping.name == "private/")
1955                        .map(|remapping| dunce::canonicalize(root.join(&remapping.path)).unwrap())
1956                        .collect::<BTreeSet<_>>(),
1957                    if allowed {
1958                        BTreeSet::from([internal.join("nested/src")])
1959                    } else {
1960                        BTreeSet::new()
1961                    },
1962                    "libs={lib:?}",
1963                );
1964            }
1965
1966            Ok(())
1967        });
1968    }
1969
1970    #[test]
1971    fn scoped_dependency_aliases_warn_about_previous_global_targets() {
1972        figment::Jail::expect_with(|_| {
1973            let temp = tempdir().unwrap();
1974            let root = temp.path();
1975            let owner = root.join("lib/a");
1976            fs::create_dir_all(owner.join("src/pinned")).unwrap();
1977            fs::create_dir_all(owner.join("lib/shared/src")).unwrap();
1978            fs::write(root.join(Config::FILE_NAME), "[profile.default]\nunknown_key = true\n")
1979                .unwrap();
1980            fs::write(
1981                owner.join(Config::FILE_NAME),
1982                "[profile.default]\nremappings = [\"shared/=src/pinned/\"]\n",
1983            )
1984            .unwrap();
1985            fs::write(owner.join("src/pinned/Version.sol"), "contract Pinned {}\n").unwrap();
1986            fs::write(owner.join("lib/shared/src/Version.sol"), "contract Discovered {}\n")
1987                .unwrap();
1988
1989            let config = Config::load_with_root(root).unwrap();
1990            assert_eq!(config.warnings.len(), 2);
1991            assert!(
1992                matches!(&config.warnings[0], crate::Warning::UnknownKey { key, .. } if key == "unknown_key")
1993            );
1994            assert_eq!(
1995                config.warnings[1].to_string(),
1996                "Dependency remapping `shared/=lib/a/src/pinned/` now applies only within `lib/a/`. Root imports of `shared/` now resolve to `lib/a/lib/shared/src/` instead. Adding `shared/=lib/a/src/pinned/` to your root remappings restores the previous resolution for the whole project, including other dependencies; to keep a dependency's own target, also add `<dependency>/:shared/=<target>`."
1997            );
1998            assert_eq!(
1999                config
2000                    .get_all_remappings()
2001                    .find(|mapping| mapping.context.is_none() && mapping.name == "shared/")
2002                    .unwrap()
2003                    .path,
2004                "lib/a/lib/shared/src/"
2005            );
2006
2007            // Choosing an owner-only override does not restore the old root alias.
2008            fs::write(
2009                root.join(Config::FILE_NAME),
2010                "[profile.default]\nremappings = [\"lib/a/:shared/=src/selected/\"]\n",
2011            )
2012            .unwrap();
2013            let config = Config::load_with_root(root).unwrap();
2014            assert_eq!(config.warnings.len(), 1);
2015            assert_eq!(
2016                config
2017                    .get_all_remappings()
2018                    .find(|mapping| mapping.context.is_none() && mapping.name == "shared/")
2019                    .unwrap()
2020                    .path,
2021                "lib/a/lib/shared/src/"
2022            );
2023
2024            Ok(())
2025        });
2026    }
2027
2028    #[test]
2029    fn dependency_alias_conflicts_compare_overlapping_targets() {
2030        figment::Jail::expect_with(|_| {
2031            for (alias, target, scoped) in [
2032                ("pkg/", "src/", true),
2033                ("pkg/", "../a/src/./", false),
2034                #[cfg(unix)]
2035                ("pkg/", "linked/", false),
2036                ("pkg/sub/", "src/", true),
2037                ("pkg/sub/", "../a/src/sub/", false),
2038                ("pkg-other/", "src/", false),
2039            ] {
2040                let temp = tempdir().unwrap();
2041                let root = temp.path();
2042                for name in ["a", "b"] {
2043                    let owner = root.join("lib").join(name);
2044                    fs::create_dir_all(owner.join("src/sub")).unwrap();
2045                    fs::write(owner.join("src/Version.sol"), "contract Version {}\n").unwrap();
2046                    fs::write(
2047                        owner.join(Config::FILE_NAME),
2048                        format!(
2049                            "[profile.default]\nremappings = [{:?}]\n",
2050                            if name == "a" {
2051                                "pkg/=src/".to_string()
2052                            } else {
2053                                format!("{alias}={target}")
2054                            }
2055                        ),
2056                    )
2057                    .unwrap();
2058                }
2059                #[cfg(unix)]
2060                symlink(root.join("lib/a/src"), root.join("lib/b/linked")).unwrap();
2061                fs::write(root.join(Config::FILE_NAME), "[profile.default]\n").unwrap();
2062
2063                let config = Config::load_with_root(root).unwrap();
2064                let aliases = config
2065                    .get_all_remappings()
2066                    .filter(|mapping| mapping.name == "pkg/" || mapping.name == alias)
2067                    .collect::<Vec<_>>();
2068                // No root mapping covers a scoped alias, so root imports fail with compiler help
2069                // instead of resolving silently elsewhere.
2070                assert!(config.warnings.is_empty(), "{alias}={target}");
2071                assert!(
2072                    aliases.iter().all(|mapping| mapping.context.is_some() == scoped),
2073                    "{alias}={target}"
2074                );
2075            }
2076
2077            Ok(())
2078        });
2079    }
2080
2081    #[test]
2082    fn scoped_dependency_alias_shadowed_by_root_or_include_path_warns() {
2083        figment::Jail::expect_with(|_| {
2084            let temp = tempdir().unwrap();
2085            let root = temp.path();
2086            fs::create_dir_all(root.join("lib/a/src/utils")).unwrap();
2087            fs::create_dir_all(root.join("utils")).unwrap();
2088            fs::write(
2089                root.join("lib/a").join(Config::FILE_NAME),
2090                "[profile.default]\nremappings = [\"utils/=src/utils/\"]\n",
2091            )
2092            .unwrap();
2093            fs::write(root.join("lib/a/src/utils/U.sol"), "contract Dependency {}\n").unwrap();
2094            fs::write(root.join("utils/U.sol"), "contract Root {}\n").unwrap();
2095            fs::write(root.join(Config::FILE_NAME), "[profile.default]\n").unwrap();
2096
2097            // Root imports of `utils/` now silently resolve to the root directory.
2098            let config = Config::load_with_root(root).unwrap();
2099            assert_eq!(
2100                config.warnings.iter().map(ToString::to_string).collect::<Vec<_>>(),
2101                [
2102                    "Dependency remapping `utils/=lib/a/src/utils/` now applies only within `lib/a/`. Root imports of `utils/` now resolve to `utils/` instead. Adding `utils/=lib/a/src/utils/` to your root remappings restores the previous resolution for the whole project, including other dependencies; to keep a dependency's own target, also add `<dependency>/:utils/=<target>`."
2103                ]
2104            );
2105
2106            // An include path can supply the replacement too, once another dependency's
2107            // conflicting declaration scopes the alias.
2108            fs::remove_dir_all(root.join("utils")).unwrap();
2109            fs::create_dir_all(root.join("lib/b/src/other")).unwrap();
2110            fs::write(
2111                root.join("lib/b").join(Config::FILE_NAME),
2112                "[profile.default]\nremappings = [\"utils/=src/other/\"]\n",
2113            )
2114            .unwrap();
2115            fs::create_dir_all(root.join("vendor/utils")).unwrap();
2116            fs::write(root.join("vendor/utils/U.sol"), "contract Vendored {}\n").unwrap();
2117            assert!(Config::load_with_root(root).unwrap().warnings.is_empty());
2118            fs::write(
2119                root.join(Config::FILE_NAME),
2120                "[profile.default]\ninclude_paths = [\"vendor\"]\n",
2121            )
2122            .unwrap();
2123            assert_eq!(
2124                Config::load_with_root(root)
2125                    .unwrap()
2126                    .warnings
2127                    .iter()
2128                    .map(ToString::to_string)
2129                    .collect::<Vec<_>>(),
2130                [
2131                    "Dependency remapping `utils/=lib/a/src/utils/` now applies only within `lib/a/`. Root imports of `utils/` now resolve to `vendor/utils/` instead. Adding `utils/=lib/a/src/utils/` to your root remappings restores the previous resolution for the whole project, including other dependencies; to keep a dependency's own target, also add `<dependency>/:utils/=<target>`."
2132                ]
2133            );
2134
2135            Ok(())
2136        });
2137    }
2138
2139    #[test]
2140    fn dependency_aliases_cannot_replace_configured_project_paths() {
2141        figment::Jail::expect_with(|_| {
2142            let temp = tempdir().unwrap();
2143            let root = temp.path();
2144            let owner = root.join("lib/a");
2145            fs::create_dir_all(owner.join("src")).unwrap();
2146            fs::write(owner.join("src/Version.sol"), "contract Version {}\n").unwrap();
2147            for (key, path) in [
2148                ("src", "custom/root"),
2149                ("test", "custom/root"),
2150                ("script", "custom/root"),
2151                #[cfg(windows)]
2152                ("src", r"custom\root"),
2153            ] {
2154                fs::write(
2155                    root.join(Config::FILE_NAME),
2156                    format!("[profile.default]\n{key} = '{path}'\n"),
2157                )
2158                .unwrap();
2159                fs::write(
2160                    owner.join(Config::FILE_NAME),
2161                    "[profile.default]\nremappings = [\"custom/root/=src/\"]\n",
2162                )
2163                .unwrap();
2164                let config = Config::load_with_root(root).unwrap();
2165                assert_eq!(config.warnings, [], "{key}");
2166                let mapping = config
2167                    .get_all_remappings()
2168                    .find(|mapping| mapping.name == "custom/root/")
2169                    .unwrap();
2170                assert_eq!(mapping.context.as_deref(), Some("lib/a/"), "{key}");
2171            }
2172
2173            Ok(())
2174        });
2175    }
2176
2177    #[test]
2178    fn unique_dependency_alias_keeps_its_contextual_refinement() {
2179        figment::Jail::expect_with(|_| {
2180            let temp = tempdir().unwrap();
2181            let root = temp.path();
2182            let owner = root.join("lib/a");
2183            fs::create_dir_all(owner.join("src/special")).unwrap();
2184            fs::create_dir_all(owner.join("overrides")).unwrap();
2185            fs::write(root.join(Config::FILE_NAME), "[profile.default]\n").unwrap();
2186            fs::write(
2187                owner.join(Config::FILE_NAME),
2188                "[profile.default]\nremappings = [\"@custom/=src/\", \"Custom.sol=src/Version.sol\", \"src/special/:@custom/=overrides/\"]\n",
2189            )
2190            .unwrap();
2191            fs::write(owner.join("src/Version.sol"), "contract Version {}\n").unwrap();
2192            fs::write(owner.join("overrides/Version.sol"), "contract Refined {}\n").unwrap();
2193
2194            let config = Config::load_with_root(root).unwrap();
2195            assert_eq!(
2196                config.get_all_remappings().map(|mapping| mapping.to_string()).collect::<Vec<_>>(),
2197                [
2198                    "lib/a/src/special/:@custom/=lib/a/overrides/",
2199                    "@custom/=lib/a/src/",
2200                    "Custom.sol=lib/a/src/Version.sol",
2201                    "a/=lib/a/src/",
2202                ]
2203            );
2204            assert_eq!(config.warnings, []);
2205            Ok(())
2206        });
2207    }
2208
2209    #[cfg(unix)]
2210    #[test]
2211    fn symlinked_libraries_preserve_lexical_project_scopes() {
2212        figment::Jail::expect_with(|_| {
2213            let temp = tempdir().unwrap();
2214            let project = temp.path().join("project");
2215            let linked_root = temp.path().join("linked-project");
2216            fs::create_dir_all(project.join("lib")).unwrap();
2217            symlink(&project, &linked_root).unwrap();
2218            for name in ["a", "b"] {
2219                let package = temp.path().join("shared").join(name);
2220                fs::create_dir_all(package.join("src")).unwrap();
2221                fs::write(package.join("src/Inner.sol"), "contract Inner {}\n").unwrap();
2222                fs::write(
2223                    package.join(Config::FILE_NAME),
2224                    format!(
2225                        "[profile.default]\nsrc = {:?}\nremappings = [\"@priv/=src/\"]\n",
2226                        if name == "a" { package.join("src") } else { PathBuf::from("src") }
2227                    ),
2228                )
2229                .unwrap();
2230                symlink(&package, project.join("lib").join(name)).unwrap();
2231            }
2232            let provider = RemappingsProvider {
2233                auto_detect_remappings: true,
2234                lib_paths: Cow::Owned(vec!["lib".into()]),
2235                root: &linked_root,
2236                remappings: Ok(Vec::new()),
2237                project_paths: Vec::new(),
2238                include_paths: Vec::new(),
2239                warnings: Ok(Vec::new()),
2240            };
2241            assert_eq!(
2242                Figment::from(provider).extract_inner::<Vec<String>>("remappings").unwrap(),
2243                [
2244                    "lib/a/:@priv/=lib/a/src/",
2245                    "lib/b/:@priv/=lib/b/src/",
2246                    "a/=lib/a/src/",
2247                    "b/=lib/b/src/",
2248                ]
2249            );
2250            Ok(())
2251        });
2252    }
2253
2254    #[test]
2255    fn scoped_dependency_aliases_do_not_warn_when_global_target_survives() {
2256        figment::Jail::expect_with(|_| {
2257            let temp = tempdir().unwrap();
2258            let root = temp.path();
2259            fs::write(root.join(Config::FILE_NAME), "[profile.default]\n").unwrap();
2260            for name in ["a", "b"] {
2261                let owner = root.join("lib").join(name);
2262                fs::create_dir_all(owner.join("src")).unwrap();
2263                fs::write(owner.join("src/Version.sol"), "contract Version {}\n").unwrap();
2264                fs::write(
2265                    owner.join(Config::FILE_NAME),
2266                    "[profile.default]\nremappings = [\"a/=src/\"]\n",
2267                )
2268                .unwrap();
2269            }
2270
2271            let config = Config::load_with_root(root).unwrap();
2272            assert_eq!(config.warnings, []);
2273            assert_eq!(
2274                config.get_all_remappings().map(|mapping| mapping.to_string()).collect::<Vec<_>>(),
2275                ["lib/a/:a/=lib/a/src/", "lib/b/:a/=lib/b/src/", "a/=lib/a/src/", "b/=lib/b/src/",]
2276            );
2277            Ok(())
2278        });
2279    }
2280
2281    #[cfg(windows)]
2282    #[test]
2283    fn remapping_precedence_accepts_mixed_windows_separators() {
2284        let declared = Remapping {
2285            context: Some(r"C:\workspace\lib/a\".to_string()),
2286            name: "shared/".to_string(),
2287            path: "lib/a/src/pinned/".to_string(),
2288        };
2289        let discovered = Remapping {
2290            context: Some("C:/workspace/lib/a/".to_string()),
2291            name: "shared/".to_string(),
2292            path: "lib/a/lib/shared/src/".to_string(),
2293        };
2294        let mut contextual = vec![declared.clone(), discovered.clone()];
2295        sort_by_context_specificity(&mut contextual);
2296        let mut remappings = Remappings::new();
2297        remappings.extend(contextual);
2298        assert_eq!(remappings.clone().into_inner(), vec![declared.clone()]);
2299
2300        // Directory boundaries and longer contexts remain significant Solidity prefixes.
2301        let distinct = ["C:/workspace/lib/a", "C:/workspace/lib/abc/", "C:/workspace/lib/a/lib/x/"]
2302            .map(|context| Remapping { context: Some(context.to_string()), ..discovered.clone() });
2303        remappings.extend(distinct.to_vec());
2304        assert_eq!(remappings.into_inner(), [vec![declared], distinct.to_vec()].concat());
2305    }
2306}