Skip to main content

revive_solc_json_interface/standard_json/input/
mod.rs

1//! The `solc --standard-json` input.
2
3use std::collections::BTreeMap;
4#[cfg(feature = "resolc")]
5use std::collections::BTreeSet;
6#[cfg(feature = "resolc")]
7use std::path::Path;
8#[cfg(feature = "resolc")]
9use std::path::PathBuf;
10
11#[cfg(all(feature = "parallel", feature = "resolc"))]
12use rayon::iter::{IntoParallelIterator, IntoParallelRefMutIterator, ParallelIterator};
13use serde::Deserialize;
14use serde::Serialize;
15
16#[cfg(feature = "resolc")]
17use crate::standard_json::input::settings::metadata::Metadata as SolcStandardJsonInputSettingsMetadata;
18#[cfg(feature = "resolc")]
19use crate::standard_json::input::settings::optimizer::Optimizer as SolcStandardJsonInputSettingsOptimizer;
20#[cfg(feature = "resolc")]
21use crate::standard_json::input::settings::selection::Selection as SolcStandardJsonInputSettingsSelection;
22#[cfg(feature = "resolc")]
23use crate::SolcStandardJsonInputSettingsDebug;
24#[cfg(feature = "resolc")]
25use crate::SolcStandardJsonInputSettingsLibraries;
26#[cfg(feature = "resolc")]
27use crate::SolcStandardJsonInputSettingsPolkaVM;
28
29use self::language::Language;
30#[cfg(feature = "resolc")]
31use self::settings::warning::Warning;
32use self::settings::Settings;
33use self::source::Source;
34
35pub mod language;
36pub mod settings;
37pub mod source;
38
39/// The `solc --standard-json` input.
40#[derive(Clone, Debug, Serialize, Deserialize)]
41#[serde(rename_all = "camelCase")]
42pub struct Input {
43    /// The input language.
44    pub language: Language,
45    /// The input source code files hashmap.
46    pub sources: BTreeMap<String, Source>,
47    /// The compiler settings.
48    pub settings: Settings,
49    /// The suppressed warnings.
50    #[cfg(feature = "resolc")]
51    #[serde(default, skip_serializing)]
52    pub suppressed_warnings: Vec<Warning>,
53}
54
55#[cfg(feature = "resolc")]
56impl Input {
57    /// A shortcut constructor.
58    ///
59    /// If the `path` is `None`, the input is read from the stdin.
60    pub fn try_from(path: Option<&Path>) -> anyhow::Result<Self> {
61        let input_json = match path {
62            Some(path) => std::fs::read_to_string(path)
63                .map_err(|error| anyhow::anyhow!("Standard JSON file {path:?} reading: {error}")),
64            None => std::io::read_to_string(std::io::stdin())
65                .map_err(|error| anyhow::anyhow!("Standard JSON reading from stdin: {error}")),
66        }?;
67        revive_common::deserialize_from_str::<Self>(input_json.as_str())
68            .map_err(|error| anyhow::anyhow!("Standard JSON parsing: {error}"))
69    }
70
71    /// A shortcut constructor from paths.
72    pub fn try_from_solidity_paths(
73        evm_version: Option<revive_common::EVMVersion>,
74        paths: &[PathBuf],
75        libraries: &[String],
76        remappings: Vec<String>,
77        output_selection: SolcStandardJsonInputSettingsSelection,
78        optimizer: SolcStandardJsonInputSettingsOptimizer,
79        metadata: SolcStandardJsonInputSettingsMetadata,
80        debug: Option<SolcStandardJsonInputSettingsDebug>,
81        suppressed_warnings: Vec<Warning>,
82        polkavm: SolcStandardJsonInputSettingsPolkaVM,
83        llvm_arguments: Vec<String>,
84        detect_missing_libraries: bool,
85    ) -> anyhow::Result<Self> {
86        let mut paths: BTreeSet<PathBuf> = paths.iter().cloned().collect();
87        let reads_stdin = paths.contains(Path::new(self::source::STDIN_PATH));
88        let libraries = SolcStandardJsonInputSettingsLibraries::try_from(libraries)?;
89        for library_file in libraries.as_inner().keys() {
90            if reads_stdin && library_file == self::source::STDIN_SOURCE_NAME {
91                continue;
92            }
93            paths.insert(PathBuf::from(library_file));
94        }
95
96        #[cfg(feature = "parallel")]
97        let iter = paths.into_par_iter(); // Parallel iterator
98        #[cfg(not(feature = "parallel"))]
99        let iter = paths.into_iter(); // Sequential iterator
100
101        let sources = iter
102            .map(|path| {
103                let source = Source::try_read(path.as_path())?;
104                Ok((Source::name(path.as_path()), source))
105            })
106            .collect::<anyhow::Result<BTreeMap<String, Source>>>()?;
107
108        Self::try_from_solidity_sources(
109            evm_version,
110            sources,
111            libraries,
112            remappings,
113            output_selection,
114            optimizer,
115            metadata,
116            debug,
117            suppressed_warnings,
118            polkavm,
119            llvm_arguments,
120            detect_missing_libraries,
121        )
122    }
123
124    /// A shortcut constructor from source code.
125    /// Only for the integration test purposes.
126    pub fn try_from_solidity_sources(
127        evm_version: Option<revive_common::EVMVersion>,
128        sources: BTreeMap<String, Source>,
129        libraries: SolcStandardJsonInputSettingsLibraries,
130        remappings: Vec<String>,
131        output_selection: SolcStandardJsonInputSettingsSelection,
132        optimizer: SolcStandardJsonInputSettingsOptimizer,
133        metadata: SolcStandardJsonInputSettingsMetadata,
134        debug: Option<SolcStandardJsonInputSettingsDebug>,
135        suppressed_warnings: Vec<Warning>,
136        polkavm: SolcStandardJsonInputSettingsPolkaVM,
137        llvm_arguments: Vec<String>,
138        detect_missing_libraries: bool,
139    ) -> anyhow::Result<Self> {
140        Ok(Self {
141            language: Language::Solidity,
142            sources,
143            settings: Settings::new(
144                evm_version,
145                libraries,
146                remappings,
147                output_selection,
148                optimizer,
149                metadata,
150                debug,
151                polkavm,
152                suppressed_warnings.clone(),
153                llvm_arguments,
154                detect_missing_libraries,
155            ),
156            suppressed_warnings,
157        })
158    }
159
160    /// A shortcut constructor from paths to Yul source files.
161    pub fn from_yul_paths(
162        paths: &[PathBuf],
163        libraries: SolcStandardJsonInputSettingsLibraries,
164        optimizer: SolcStandardJsonInputSettingsOptimizer,
165        llvm_options: Vec<String>,
166    ) -> anyhow::Result<Self> {
167        let sources = paths
168            .iter()
169            .map(|path| {
170                let source = if path.as_os_str() == self::source::STDIN_PATH {
171                    Source::try_read(path.as_path())?
172                } else {
173                    Source::from(path.as_path())
174                };
175                Ok((Source::name(path.as_path()), source))
176            })
177            .collect::<anyhow::Result<BTreeMap<String, Source>>>()?;
178        Ok(Self::from_yul_sources(
179            sources,
180            libraries,
181            optimizer,
182            llvm_options,
183        ))
184    }
185
186    /// A shortcut constructor from Yul source code.
187    pub fn from_yul_sources(
188        sources: BTreeMap<String, Source>,
189        libraries: SolcStandardJsonInputSettingsLibraries,
190        optimizer: SolcStandardJsonInputSettingsOptimizer,
191        llvm_arguments: Vec<String>,
192    ) -> Self {
193        let output_selection = SolcStandardJsonInputSettingsSelection::new_yul_validation();
194
195        Self {
196            language: Language::Yul,
197            sources,
198            settings: Settings::new(
199                None,
200                libraries,
201                Default::default(),
202                output_selection,
203                optimizer,
204                Default::default(),
205                None,
206                Default::default(),
207                vec![],
208                llvm_arguments,
209                false,
210            ),
211            suppressed_warnings: vec![],
212        }
213    }
214
215    /// Extends the output selection with another one.
216    pub fn extend_selection(&mut self, selection: SolcStandardJsonInputSettingsSelection) {
217        self.settings.extend_selection(selection);
218    }
219
220    /// Tries to resolve all sources.
221    pub fn resolve_sources(&mut self) {
222        #[cfg(feature = "parallel")]
223        let iter = self.sources.par_iter_mut();
224        #[cfg(not(feature = "parallel"))]
225        let iter = self.sources.iter_mut();
226
227        iter.for_each(|(_path, source)| {
228            let _ = source.try_resolve();
229        });
230    }
231
232    /// Removes unneded output selections.
233    pub fn retain_output_selection(&mut self) {
234        self.settings.retain_output_selection();
235    }
236}