Skip to main content

foundry_cheatcodes/inspector/
analysis.rs

1//! Cheatcode information, extracted from the syntactic and semantic analysis of the sources.
2
3use alloy_primitives::map::HashSet;
4use foundry_common::fmt::{StructDefinitions, TypeDefMap};
5use solar::sema::{self, Compiler, Gcx, hir};
6use std::sync::{Arc, OnceLock};
7use thiserror::Error;
8
9/// Represents a failure in one of the lazy analysis steps.
10#[derive(Debug, Clone, PartialEq, Eq, Error)]
11pub enum AnalysisError {
12    /// Indicates that the resolution of struct definitions failed.
13    #[error("unable to resolve struct definitions")]
14    StructDefinitionsResolutionFailed,
15}
16
17/// Provides cached, on-demand syntactic and semantic analysis of a completed `Compiler` instance.
18///
19/// This struct acts as a facade over the `Compiler`, offering lazy-loaded analysis for tools like
20/// cheatcode inspectors. It assumes the compiler has already completed parsing and lowering.
21///
22/// # Adding with new analyses types
23///
24/// To add support for a new type of cached analysis, follow this pattern:
25///
26/// 1. Add a new `pub OnceCell<Result<T, AnalysisError>>` field to `CheatcodeAnalysis`, where `T` is
27///    the type of the data that you are adding support for.
28///
29/// 2. Implement a getter method for the new field. Inside the getter, use
30///    `self.field.get_or_init()` to compute and cache the value on the first call.
31///
32/// 3. Inside the closure passed to `get_or_init()`, create a dedicated visitor to traverse the HIR
33///    using `self.compiler.enter()` and collect the required data.
34///
35/// This ensures all analyses remain lazy, efficient, and consistent with the existing design.
36#[derive(Clone)]
37pub struct CheatcodeAnalysis {
38    /// A shared, thread-safe reference to solar's `Compiler` instance.
39    pub compiler: Arc<Compiler>,
40
41    /// Cached struct definitions in the sources.
42    /// Used to keep field order when parsing JSON values.
43    struct_defs: OnceLock<Result<StructDefinitions, AnalysisError>>,
44}
45
46impl std::fmt::Debug for CheatcodeAnalysis {
47    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48        f.debug_struct("CheatcodeAnalysis")
49            .field("compiler", &"<compiler>")
50            .field("struct_defs", &self.struct_defs)
51            .finish()
52    }
53}
54
55impl CheatcodeAnalysis {
56    pub const fn new(compiler: Arc<solar::sema::Compiler>) -> Self {
57        Self { compiler, struct_defs: OnceLock::new() }
58    }
59
60    /// Lazily initializes and returns the struct definitions.
61    pub fn struct_defs(&self) -> Result<&StructDefinitions, &AnalysisError> {
62        self.struct_defs
63            .get_or_init(|| {
64                self.compiler.enter(|compiler| {
65                    let gcx = compiler.gcx();
66
67                    StructDefinitionResolver::new(gcx).process()
68                })
69            })
70            .as_ref()
71    }
72}
73
74// -- STRUCT DEFINITIONS -------------------------------------------------------
75
76/// Generates a map of all struct definitions from the HIR using the resolved `Ty` system.
77struct StructDefinitionResolver<'gcx> {
78    gcx: Gcx<'gcx>,
79    struct_defs: TypeDefMap,
80    /// Structs whose resolution has started. A struct can hold itself through a dynamic array.
81    visited: HashSet<hir::StructId>,
82}
83
84impl<'gcx> StructDefinitionResolver<'gcx> {
85    /// Constructs a new generator.
86    pub fn new(gcx: Gcx<'gcx>) -> Self {
87        Self { gcx, struct_defs: TypeDefMap::new(), visited: HashSet::default() }
88    }
89
90    /// Processes the HIR to generate all the struct definitions.
91    pub fn process(mut self) -> Result<StructDefinitions, AnalysisError> {
92        for id in self.hir().strukt_ids() {
93            self.resolve_struct_definition(id)?;
94        }
95        Ok(self.struct_defs.into())
96    }
97
98    #[inline]
99    fn hir(&self) -> &'gcx hir::Hir<'gcx> {
100        &self.gcx.hir
101    }
102
103    /// The recursive core of the generator. Resolves a single struct and adds it to the cache.
104    fn resolve_struct_definition(&mut self, id: hir::StructId) -> Result<(), AnalysisError> {
105        let qualified_name = self.get_fully_qualified_name(id);
106        if !self.visited.insert(id) || self.struct_defs.contains_key(&qualified_name) {
107            return Ok(());
108        }
109
110        let hir = self.hir();
111        let strukt = hir.strukt(id);
112        let mut fields = Vec::with_capacity(strukt.fields.len());
113
114        for &field_id in strukt.fields {
115            let var = hir.variable(field_id);
116            let name =
117                var.name.ok_or(AnalysisError::StructDefinitionsResolutionFailed)?.to_string();
118            if let Some(ty_str) = self.ty_to_string(self.gcx.type_of_hir_ty(&var.ty)) {
119                fields.push((name, ty_str));
120            }
121        }
122
123        // Only insert if there are fields, to avoid adding empty entries
124        if !fields.is_empty() {
125            self.struct_defs.insert(qualified_name, fields);
126        }
127
128        Ok(())
129    }
130
131    /// Converts a resolved `Ty` into its canonical string representation.
132    fn ty_to_string(&mut self, ty: sema::Ty<'gcx>) -> Option<String> {
133        let ty = ty.peel_refs();
134        let res = match ty.kind {
135            sema::ty::TyKind::Elementary(e) => e.to_string(),
136            sema::ty::TyKind::Array(ty, size) => {
137                let inner_type = self.ty_to_string(ty)?;
138                format!("{inner_type}[{size}]")
139            }
140            sema::ty::TyKind::DynArray(ty) => {
141                let inner_type = self.ty_to_string(ty)?;
142                format!("{inner_type}[]")
143            }
144            sema::ty::TyKind::Struct(id) => {
145                // Ensure the nested struct is resolved before proceeding.
146                self.resolve_struct_definition(id).ok()?;
147                self.get_fully_qualified_name(id)
148            }
149            sema::ty::TyKind::Udvt(ty, _) => self.ty_to_string(ty)?,
150            // For now, map enums to `uint8`
151            sema::ty::TyKind::Enum(_) => "uint8".to_string(),
152            // For now, map contracts to `address`
153            sema::ty::TyKind::Contract(_) => "address".to_string(),
154            // Explicitly disallow unsupported types
155            _ => return None,
156        };
157
158        Some(res)
159    }
160
161    /// Helper to get the fully qualified name `Contract.Struct`.
162    fn get_fully_qualified_name(&self, id: hir::StructId) -> String {
163        let hir = self.hir();
164        let strukt = hir.strukt(id);
165        if let Some(contract_id) = strukt.contract {
166            format!("{}.{}", hir.contract(contract_id).name.as_str(), strukt.name.as_str())
167        } else {
168            strukt.name.as_str().into()
169        }
170    }
171}