Skip to main content

forge_lint/sol/med/
duplicate_storage_namespace.rs

1use super::DuplicateStorageNamespace;
2use crate::{
3    linter::{LateLintPass, LintContext},
4    sol::{Severity, SolLint},
5};
6use foundry_common::namespaced_storage::storage_namespace;
7use solar::sema::{Gcx, hir};
8use std::collections::BTreeMap;
9
10declare_forge_lint!(
11    DUPLICATE_STORAGE_NAMESPACE,
12    Severity::Med,
13    "duplicate-storage-namespace",
14    "ERC-7201 namespace is declared more than once"
15);
16
17impl<'gcx> LateLintPass<'gcx> for DuplicateStorageNamespace {
18    fn check_contract(
19        &mut self,
20        ctx: &LintContext,
21        gcx: Gcx<'gcx>,
22        contract: &'gcx hir::Contract<'gcx>,
23    ) {
24        let Some((&id, bases)) = contract.linearized_bases.split_first() else { return };
25        for (namespace, structs) in namespaced_structs(gcx, contract.linearized_bases) {
26            if structs.len() < 2 {
27                continue;
28            }
29            let first = gcx.item_canonical_name(structs[0]);
30            // Bases come first, so every struct declared here after the first occurrence collides.
31            for &strukt in &structs[1..] {
32                let strukt = gcx.hir.strukt(strukt);
33                if strukt.contract == Some(id) {
34                    ctx.emit_with_msg(
35                        &DUPLICATE_STORAGE_NAMESPACE,
36                        strukt.name.span,
37                        format!(
38                            "ERC-7201 namespace `{namespace}` is already declared by `{first}`"
39                        ),
40                    );
41                }
42            }
43            // Report the first inherited pair that no single base combines; a base that combines
44            // a pair already reports it.
45            let inherited = &structs
46                [..structs.partition_point(|&strukt| gcx.hir.strukt(strukt).contract != Some(id))];
47            let combined = |a: hir::StructId, b: hir::StructId| {
48                bases.iter().any(|&base| {
49                    let hierarchy = gcx.hir.contract(base).linearized_bases;
50                    [a, b].into_iter().all(|strukt| {
51                        gcx.hir
52                            .strukt(strukt)
53                            .contract
54                            .is_some_and(|declared_in| hierarchy.contains(&declared_in))
55                    })
56                })
57            };
58            if let Some((first, second)) = inherited.iter().enumerate().find_map(|(i, &first)| {
59                inherited[i + 1..]
60                    .iter()
61                    .find(|&&second| !combined(first, second))
62                    .map(|&second| (first, second))
63            }) {
64                ctx.emit_with_msg(
65                    &DUPLICATE_STORAGE_NAMESPACE,
66                    contract.name.span,
67                    format!(
68                        "ERC-7201 namespace `{namespace}` is declared by both `{}` and `{}`",
69                        gcx.item_canonical_name(first),
70                        gcx.item_canonical_name(second)
71                    ),
72                );
73            }
74        }
75    }
76}
77
78/// Returns the namespaced structs declared in `contracts`, grouped by namespace, most base first.
79///
80/// Malformed ERC-7201 annotations are skipped: they are not duplicates, and the storage layout
81/// decoder rejects them with a dedicated error.
82fn namespaced_structs<'gcx>(
83    gcx: Gcx<'gcx>,
84    contracts: &[hir::ContractId],
85) -> BTreeMap<&'gcx str, Vec<hir::StructId>> {
86    let mut namespaces = BTreeMap::<_, Vec<_>>::new();
87    for &contract in contracts.iter().rev() {
88        for id in gcx.hir.contract(contract).items.iter().filter_map(|item| item.as_struct()) {
89            if let Ok(Some(namespace)) = storage_namespace(gcx, gcx.hir.strukt(id)) {
90                namespaces.entry(namespace).or_default().push(id);
91            }
92        }
93    }
94    namespaces
95}