Skip to main content

foundry_config/providers/
warnings.rs

1use crate::{Config, DEPRECATIONS, Warning};
2use figment::{
3    Error, Figment, Metadata, Profile, Provider,
4    value::{Dict, Map, Value},
5};
6use heck::ToSnakeCase;
7use std::collections::{BTreeMap, BTreeSet};
8
9/// Allowed keys for CompilationRestrictions.
10const COMPILATION_RESTRICTIONS_KEYS: &[&str] = &[
11    "paths",
12    "version",
13    "via_ir",
14    "bytecode_hash",
15    "min_optimizer_runs",
16    "optimizer_runs",
17    "max_optimizer_runs",
18    "min_evm_version",
19    "evm_version",
20    "max_evm_version",
21];
22
23/// Allowed keys for SettingsOverrides.
24const SETTINGS_OVERRIDES_KEYS: &[&str] =
25    &["name", "via_ir", "evm_version", "optimizer", "optimizer_runs", "bytecode_hash"];
26
27/// Allowed keys for external compiler adapter entries.
28const EXTERNAL_COMPILER_KEYS: &[&str] = &["id", "command", "args", "roots", "settings"];
29
30/// Allowed keys for VyperConfig.
31/// Required because VyperConfig uses `skip_serializing_if = "Option::is_none"` on all fields,
32/// causing the default serialization to produce an empty dict.
33const VYPER_KEYS: &[&str] = &[
34    "optimize",
35    "opt_level",
36    "optLevel",
37    "path",
38    "experimental_codegen",
39    "venom_experimental",
40    "debug",
41    "enable_decimals",
42    "venom",
43];
44
45/// Allowed keys for DocConfig.
46/// Required because DocConfig uses `skip_serializing_if = "Option::is_none"` on some fields
47/// (`repository`, `commit`, `path`), whose defaults are `None` and thus excluded from
48/// serialization.
49const DOC_KEYS: &[&str] =
50    &["out", "title", "book", "homepage", "repository", "commit", "path", "ignore"];
51
52/// Allowed keys for SymbolicConfig.
53/// Required because some compatibility aliases and empty length collections are skipped by default
54/// serialization, but they are still valid user-facing config keys.
55const SYMBOLIC_KEYS: &[&str] = &[
56    "enabled",
57    "seed_corpus",
58    "use_fuzz_corpus",
59    "corpus_seed_limit",
60    "use_fuzz_frontiers",
61    "check_invariant_frontiers",
62    "live",
63    "frontier_limit",
64    "frontier_ids",
65    "frontier_pcs",
66    "frontier_selectors",
67    "solver",
68    "solver_command",
69    "solver_portfolio",
70    "timeout",
71    "loop",
72    "depth",
73    "width",
74    "max_depth",
75    "max_paths",
76    "invariant_depth",
77    "exploration_order",
78    "max_solver_queries",
79    "default_dynamic_length",
80    "max_dynamic_length",
81    "array_lengths",
82    "dynamic_lengths",
83    "default_array_lengths",
84    "default_bytes_lengths",
85    "max_calldata_bytes",
86    "symbolic_call_targets",
87    "dump_smt",
88    "storage_layout",
89];
90
91/// Allowed keys for TracingConfig.
92/// Required because empty labels and optional trace depth are skipped by default serialization,
93/// but they are still valid user-facing config keys.
94const TRACING_KEYS: &[&str] = &[
95    "verbosity",
96    "labels",
97    "disable_labels",
98    "compact_labels",
99    "trace_depth",
100    "decode_internal",
101    "external_identification_timeout",
102];
103
104/// Allowed keys for the table form of an `[rpc_endpoints]` entry.
105const RPC_ENDPOINT_KEYS: &[&str] = &[
106    "endpoint",
107    "url",
108    "endpoints",
109    "retries",
110    "retry_backoff",
111    "compute_units_per_second",
112    "auth",
113];
114
115/// Allowed keys for an `[etherscan]` entry.
116const ETHERSCAN_KEYS: &[&str] = &["key", "url", "chain"];
117
118/// Reserved keys that should not trigger unknown key warnings.
119const RESERVED_KEYS: &[&str] = &["extends"];
120
121/// Keys kept for backward compatibility that should not trigger unknown key warnings.
122///
123/// Network flags are legacy aliases for canonical `network = "..."` values. They remain accepted
124/// when the corresponding network support is compiled, but are no longer serialized.
125const BACKWARD_COMPATIBLE_KEYS: &[&str] = &[
126    "solc_version",
127    "tempo",
128    "optimism",
129    #[cfg(feature = "monad")]
130    "monad",
131];
132
133const LABELS_KEY: &str = "labels";
134const TRACING_LABELS_KEY: &str = "tracing.labels";
135
136/// Generate warnings for unknown sections and deprecated keys
137pub struct WarningsProvider<P> {
138    provider: P,
139    profile: Profile,
140    old_warnings: Result<Vec<Warning>, Error>,
141}
142
143impl<P: Provider> WarningsProvider<P> {
144    const WARNINGS_KEY: &'static str = "__warnings";
145
146    /// Creates a new warnings provider.
147    pub fn new(
148        provider: P,
149        profile: impl Into<Profile>,
150        old_warnings: Result<Vec<Warning>, Error>,
151    ) -> Self {
152        Self { provider, profile: profile.into(), old_warnings }
153    }
154
155    /// Creates a new figment warnings provider.
156    pub fn for_figment(provider: P, figment: &Figment) -> Self {
157        let old_warnings = {
158            let warnings_res = figment.extract_inner(Self::WARNINGS_KEY);
159            if warnings_res.as_ref().err().is_some_and(|err| err.missing()) {
160                Ok(vec![])
161            } else {
162                warnings_res
163            }
164        };
165        Self::new(provider, figment.profile().clone(), old_warnings)
166    }
167
168    /// Collects all warnings.
169    pub fn collect_warnings(&self) -> Result<Vec<Warning>, Error> {
170        let data = self.provider.data().unwrap_or_default();
171
172        let mut out = self.old_warnings.clone()?;
173
174        // Add warning for unknown sections.
175        out.extend(data.keys().filter(|k| !Config::is_standalone_section(k.as_str())).map(
176            |unknown_section| {
177                let source = self.provider.metadata().source.map(|s| s.to_string());
178                Warning::UnknownSection { unknown_section: unknown_section.clone(), source }
179            },
180        ));
181
182        // Add warning for deprecated keys.
183        let deprecated_key_warning = |key| {
184            DEPRECATIONS.iter().find_map(|(deprecated_key, new_value)| {
185                (key == *deprecated_key).then(|| Warning::DeprecatedKey {
186                    old: deprecated_key.to_string(),
187                    new: new_value.to_string(),
188                })
189            })
190        };
191        let profiles = data
192            .iter()
193            .filter(|(profile, _)| **profile == Config::PROFILE_SECTION)
194            .map(|(_, dict)| dict);
195
196        let deprecated_profile_keys = profiles
197            .clone()
198            .flat_map(|dict| {
199                dict.keys().chain(dict.values().filter_map(Value::as_dict).flat_map(BTreeMap::keys))
200            })
201            .collect::<BTreeSet<_>>();
202        out.extend(deprecated_profile_keys.into_iter().filter_map(deprecated_key_warning));
203        self.collect_deprecated_label_warnings(&data, profiles.clone(), &mut out);
204
205        // Add warning for unknown keys within profiles (root keys only here).
206        if let Ok(default_map) = figment::providers::Serialized::defaults(&Config::default()).data()
207            && let Some(default_dict) = default_map.get(&Config::DEFAULT_PROFILE)
208        {
209            let mut allowed_keys: BTreeSet<String> = default_dict.keys().cloned().collect();
210            allowed_keys.insert("external_compilers".to_string());
211            for profile_map in profiles.clone() {
212                for (profile, value) in profile_map {
213                    let Some(profile_dict) = value.as_dict() else {
214                        continue;
215                    };
216
217                    let source = self
218                        .provider
219                        .metadata()
220                        .source
221                        .map(|s| s.to_string())
222                        .unwrap_or(Config::FILE_NAME.to_string());
223                    for key in profile_dict.keys() {
224                        let is_not_deprecated = !Self::is_deprecated_profile_key(key);
225                        let is_not_allowed = !allowed_keys.contains(key)
226                            && !allowed_keys.contains(&key.to_snake_case());
227                        let is_not_reserved =
228                            !RESERVED_KEYS.contains(&key.as_str()) && key != Self::WARNINGS_KEY;
229                        let is_not_backward_compatible =
230                            !BACKWARD_COMPATIBLE_KEYS.contains(&key.as_str());
231
232                        if is_not_deprecated
233                            && is_not_allowed
234                            && is_not_reserved
235                            && is_not_backward_compatible
236                        {
237                            out.push(Warning::UnknownKey {
238                                key: key.clone(),
239                                profile: profile.clone(),
240                                source: source.clone(),
241                            });
242                        }
243                    }
244
245                    // Add warning for unknown keys in nested sections within profiles.
246                    self.collect_nested_section_warnings(
247                        profile_dict,
248                        default_dict,
249                        &source,
250                        &mut out,
251                    );
252                }
253            }
254
255            // Add warning for unknown keys in standalone sections.
256            self.collect_standalone_section_warnings(&data, default_dict, &mut out);
257        }
258
259        Ok(out)
260    }
261
262    /// Collects warnings for unknown keys in standalone sections like `[lint]`, `[fmt]`, etc.
263    fn collect_standalone_section_warnings(
264        &self,
265        data: &Map<Profile, Dict>,
266        default_dict: &Dict,
267        out: &mut Vec<Warning>,
268    ) {
269        let source = self
270            .provider
271            .metadata()
272            .source
273            .map(|s| s.to_string())
274            .unwrap_or(Config::FILE_NAME.to_string());
275
276        for section_name in Config::STANDALONE_SECTIONS {
277            // Get the section from the parsed data
278            let section_profile = Profile::new(section_name);
279            let Some(section_dict) = data.get(&section_profile) else {
280                continue;
281            };
282
283            if Self::collect_entry_warnings(section_name, section_dict, &source, out) {
284                continue;
285            }
286
287            // Get allowed keys for this section from the default config
288            // Special case for vyper: VyperConfig uses skip_serializing_if on all Option fields,
289            // so the default serialization produces an empty dict. Use explicit keys instead.
290            let allowed_keys: BTreeSet<String> = if *section_name == "vyper" {
291                VYPER_KEYS.iter().map(|s| s.to_string()).collect()
292            } else if *section_name == "doc" {
293                DOC_KEYS.iter().map(|s| s.to_string()).collect()
294            } else if *section_name == "tracing" {
295                TRACING_KEYS.iter().map(|s| s.to_string()).collect()
296            } else if *section_name == "symbolic" {
297                SYMBOLIC_KEYS.iter().map(|s| s.to_string()).collect()
298            } else {
299                let Some(default_section_value) = default_dict.get(*section_name) else {
300                    continue;
301                };
302                let Some(default_section_dict) = default_section_value.as_dict() else {
303                    continue;
304                };
305                default_section_dict.keys().cloned().collect()
306            };
307
308            for key in section_dict.keys() {
309                let is_not_allowed =
310                    !allowed_keys.contains(key) && !allowed_keys.contains(&key.to_snake_case());
311                if is_not_allowed {
312                    out.push(Warning::UnknownSectionKey {
313                        key: key.clone(),
314                        section: section_name.to_string(),
315                        source: source.clone(),
316                    });
317                }
318            }
319        }
320    }
321
322    /// Collects warnings for unknown keys in nested sections within profiles,
323    /// like `compilation_restrictions`.
324    fn collect_nested_section_warnings(
325        &self,
326        profile_dict: &Dict,
327        default_dict: &Dict,
328        source: &str,
329        out: &mut Vec<Warning>,
330    ) {
331        // Check nested sections that are dicts (like `lint`, `fmt` when defined in profile)
332        for (key, value) in profile_dict {
333            let Some(nested_dict) = value.as_dict() else {
334                // Also check arrays of dicts (like `compilation_restrictions`)
335                if let Some(arr) = value.as_array() {
336                    // Get allowed keys for known array item types
337                    let allowed_keys = Self::get_array_item_allowed_keys(key);
338
339                    if allowed_keys.is_empty() {
340                        continue;
341                    }
342
343                    for item in arr {
344                        let Some(item_dict) = item.as_dict() else {
345                            continue;
346                        };
347                        for item_key in item_dict.keys() {
348                            let is_not_allowed = !allowed_keys.contains(item_key)
349                                && !allowed_keys.contains(&item_key.to_snake_case());
350                            if is_not_allowed {
351                                out.push(Warning::UnknownSectionKey {
352                                    key: item_key.clone(),
353                                    section: key.clone(),
354                                    source: source.to_string(),
355                                });
356                            }
357                        }
358                    }
359                }
360                continue;
361            };
362
363            if Self::collect_entry_warnings(key, nested_dict, source, out) {
364                continue;
365            }
366
367            // Get allowed keys from the default config for this nested section
368            // Special case for vyper: VyperConfig uses skip_serializing_if on all Option fields,
369            // so the default serialization produces an empty dict. Use explicit keys instead.
370            let allowed_keys: BTreeSet<String> = if key == "vyper" {
371                VYPER_KEYS.iter().map(|s| s.to_string()).collect()
372            } else if key == "doc" {
373                DOC_KEYS.iter().map(|s| s.to_string()).collect()
374            } else if key == "symbolic" {
375                SYMBOLIC_KEYS.iter().map(|s| s.to_string()).collect()
376            } else if key == "tracing" {
377                TRACING_KEYS.iter().map(|s| s.to_string()).collect()
378            } else {
379                let Some(default_value) = default_dict.get(key) else {
380                    continue;
381                };
382                let Some(default_nested_dict) = default_value.as_dict() else {
383                    continue;
384                };
385                default_nested_dict.keys().cloned().collect()
386            };
387
388            for nested_key in nested_dict.keys() {
389                let is_not_allowed = !allowed_keys.contains(nested_key)
390                    && !allowed_keys.contains(&nested_key.to_snake_case());
391                if is_not_allowed {
392                    out.push(Warning::UnknownSectionKey {
393                        key: nested_key.clone(),
394                        section: key.clone(),
395                        source: source.to_string(),
396                    });
397                }
398            }
399        }
400    }
401
402    /// Collects warnings for unknown keys in the entries of the sections keyed by alias,
403    /// `[rpc_endpoints]` and `[etherscan]`. Returns `false` for other sections.
404    fn collect_entry_warnings(
405        section_name: &str,
406        section_dict: &Dict,
407        source: &str,
408        out: &mut Vec<Warning>,
409    ) -> bool {
410        let allowed_keys = match section_name {
411            "rpc_endpoints" => RPC_ENDPOINT_KEYS,
412            "etherscan" => ETHERSCAN_KEYS,
413            _ => return false,
414        };
415        for (alias, entry) in section_dict {
416            // An RPC endpoint can also be a plain URL.
417            let Some(entry) = entry.as_dict() else { continue };
418            for key in entry.keys() {
419                if !allowed_keys.contains(&key.as_str()) {
420                    out.push(Warning::UnknownSectionKey {
421                        key: key.clone(),
422                        section: format!("{section_name}.{alias}"),
423                        source: source.to_string(),
424                    });
425                }
426            }
427        }
428        true
429    }
430
431    /// Returns the allowed keys for array item types based on the section name.
432    fn get_array_item_allowed_keys(section_name: &str) -> BTreeSet<String> {
433        match section_name {
434            "compilation_restrictions" => {
435                COMPILATION_RESTRICTIONS_KEYS.iter().map(|s| s.to_string()).collect()
436            }
437            "additional_compiler_profiles" => {
438                SETTINGS_OVERRIDES_KEYS.iter().map(|s| s.to_string()).collect()
439            }
440            "external_compilers" => EXTERNAL_COMPILER_KEYS.iter().map(|s| s.to_string()).collect(),
441            _ => BTreeSet::new(),
442        }
443    }
444
445    fn collect_deprecated_label_warnings<'a>(
446        &self,
447        data: &Map<Profile, Dict>,
448        profiles: impl Iterator<Item = &'a Dict>,
449        out: &mut Vec<Warning>,
450    ) {
451        if data.contains_key(&Profile::new(LABELS_KEY)) {
452            out.push(Self::deprecated_label_warning("[labels]", "[tracing.labels]"));
453        }
454
455        if profiles
456            .flat_map(BTreeMap::values)
457            .filter_map(Value::as_dict)
458            .any(|dict| dict.contains_key(LABELS_KEY))
459        {
460            out.push(Self::deprecated_label_warning(LABELS_KEY, TRACING_LABELS_KEY));
461        }
462
463        if let Some(dict) = data.get(&self.profile)
464            && dict.contains_key(LABELS_KEY)
465        {
466            out.push(Self::deprecated_label_warning(LABELS_KEY, TRACING_LABELS_KEY));
467        }
468    }
469
470    fn deprecated_label_warning(old: &str, new: &str) -> Warning {
471        Warning::DeprecatedKey { old: old.to_string(), new: new.to_string() }
472    }
473
474    fn is_deprecated_profile_key(key: &str) -> bool {
475        key == LABELS_KEY || DEPRECATIONS.iter().any(|(deprecated_key, _)| *deprecated_key == key)
476    }
477}
478
479impl<P: Provider> Provider for WarningsProvider<P> {
480    fn metadata(&self) -> Metadata {
481        if let Some(source) = self.provider.metadata().source {
482            Metadata::from("Warnings", source)
483        } else {
484            Metadata::named("Warnings")
485        }
486    }
487
488    fn data(&self) -> Result<Map<Profile, Dict>, Error> {
489        let warnings = self.collect_warnings()?;
490        Ok(Map::from([(
491            self.profile.clone(),
492            Dict::from([(Self::WARNINGS_KEY.to_string(), Value::serialize(warnings)?)]),
493        )]))
494    }
495
496    fn profile(&self) -> Option<Profile> {
497        Some(self.profile.clone())
498    }
499}