foundry_compilers/resolver/
parse.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
use foundry_compilers_core::utils;
use semver::VersionReq;
use solar_parse::{
    ast,
    interface::{sym, Pos},
};
use std::{
    ops::Range,
    path::{Path, PathBuf},
};

/// Represents various information about a Solidity file.
#[derive(Clone, Debug)]
pub struct SolData {
    pub license: Option<Spanned<String>>,
    pub version: Option<Spanned<String>>,
    pub experimental: Option<Spanned<String>>,
    pub imports: Vec<Spanned<SolImport>>,
    pub version_req: Option<VersionReq>,
    pub libraries: Vec<SolLibrary>,
    pub contract_names: Vec<String>,
    pub is_yul: bool,
    pub parse_result: Result<(), String>,
}

impl SolData {
    /// Returns the result of parsing the file.
    pub fn parse_result(&self) -> crate::Result<()> {
        self.parse_result.clone().map_err(crate::SolcError::ParseError)
    }

    #[allow(dead_code)]
    pub fn fmt_version<W: std::fmt::Write>(
        &self,
        f: &mut W,
    ) -> std::result::Result<(), std::fmt::Error> {
        if let Some(version) = &self.version {
            write!(f, "({})", version.data)?;
        }
        Ok(())
    }

    /// Extracts the useful data from a solidity source
    ///
    /// This will attempt to parse the solidity AST and extract the imports and version pragma. If
    /// parsing fails, we'll fall back to extract that info via regex
    pub fn parse(content: &str, file: &Path) -> Self {
        let is_yul = file.extension().map_or(false, |ext| ext == "yul");
        let mut version = None;
        let mut experimental = None;
        let mut imports = Vec::<Spanned<SolImport>>::new();
        let mut libraries = Vec::new();
        let mut contract_names = Vec::new();
        let mut parse_result = Ok(());

        let sess = solar_parse::interface::Session::builder()
            .with_buffer_emitter(Default::default())
            .build();
        sess.enter(|| {
            let arena = ast::Arena::new();
            let filename = solar_parse::interface::source_map::FileName::Real(file.to_path_buf());
            let Ok(mut parser) =
                solar_parse::Parser::from_source_code(&sess, &arena, filename, content.to_string())
            else {
                return;
            };
            let Ok(ast) = parser.parse_file().map_err(|e| e.emit()) else { return };
            for item in ast.items {
                let loc = item.span.lo().to_usize()..item.span.hi().to_usize();
                match &item.kind {
                    ast::ItemKind::Pragma(pragma) => match &pragma.tokens {
                        ast::PragmaTokens::Version(name, req) if name.name == sym::solidity => {
                            version = Some(Spanned::new(req.to_string(), loc));
                        }
                        ast::PragmaTokens::Custom(name, value)
                            if name.as_str() == "experimental" =>
                        {
                            let value =
                                value.as_ref().map(|v| v.as_str().to_string()).unwrap_or_default();
                            experimental = Some(Spanned::new(value, loc));
                        }
                        _ => {}
                    },

                    ast::ItemKind::Import(import) => {
                        let path = import.path.value.to_string();
                        let aliases = match &import.items {
                            ast::ImportItems::Plain(None) | ast::ImportItems::Glob(None) => &[][..],
                            ast::ImportItems::Plain(Some(alias))
                            | ast::ImportItems::Glob(Some(alias)) => &[(*alias, None)][..],
                            ast::ImportItems::Aliases(aliases) => aliases,
                        };
                        let sol_import = SolImport::new(PathBuf::from(path)).set_aliases(
                            aliases
                                .iter()
                                .map(|(id, alias)| match alias {
                                    Some(al) => SolImportAlias::Contract(
                                        al.name.to_string(),
                                        id.name.to_string(),
                                    ),
                                    None => SolImportAlias::File(id.name.to_string()),
                                })
                                .collect(),
                        );
                        imports.push(Spanned::new(sol_import, loc));
                    }

                    ast::ItemKind::Contract(contract) => {
                        if contract.kind.is_library() {
                            libraries.push(SolLibrary { is_inlined: library_is_inlined(contract) });
                        }
                        contract_names.push(contract.name.to_string());
                    }

                    _ => {}
                }
            }
        });
        if let Err(e) = sess.emitted_diagnostics().unwrap() {
            let e = e.to_string();
            trace!("failed parsing {file:?}: {e}");
            parse_result = Err(e);
        }
        let license = content.lines().next().and_then(|line| {
            utils::capture_outer_and_inner(
                line,
                &utils::RE_SOL_SDPX_LICENSE_IDENTIFIER,
                &["license"],
            )
            .first()
            .map(|(cap, l)| Spanned::new(l.as_str().to_owned(), cap.range()))
        });
        let version_req = version.as_ref().and_then(|v| Self::parse_version_req(v.data()).ok());

        Self {
            version_req,
            version,
            experimental,
            imports,
            license,
            libraries,
            contract_names,
            is_yul,
            parse_result,
        }
    }

    /// Returns the corresponding SemVer version requirement for the solidity version.
    ///
    /// Note: This is a workaround for the fact that `VersionReq::parse` does not support whitespace
    /// separators and requires comma separated operators. See [VersionReq].
    pub fn parse_version_req(version: &str) -> Result<VersionReq, semver::Error> {
        let version = version.replace(' ', ",");

        // Somehow, Solidity semver without an operator is considered to be "exact",
        // but lack of operator automatically marks the operator as Caret, so we need
        // to manually patch it? :shrug:
        let exact = !matches!(&version[0..1], "*" | "^" | "=" | ">" | "<" | "~");
        let mut version = VersionReq::parse(&version)?;
        if exact {
            version.comparators[0].op = semver::Op::Exact;
        }

        Ok(version)
    }
}

#[derive(Clone, Debug)]
pub struct SolImport {
    path: PathBuf,
    aliases: Vec<SolImportAlias>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SolImportAlias {
    File(String),
    Contract(String, String),
}

impl SolImport {
    pub fn new(path: PathBuf) -> Self {
        Self { path, aliases: vec![] }
    }

    pub fn path(&self) -> &PathBuf {
        &self.path
    }

    pub fn aliases(&self) -> &Vec<SolImportAlias> {
        &self.aliases
    }

    fn set_aliases(mut self, aliases: Vec<SolImportAlias>) -> Self {
        self.aliases = aliases;
        self
    }
}

/// Minimal representation of a contract inside a solidity file
#[derive(Clone, Debug)]
pub struct SolLibrary {
    pub is_inlined: bool,
}

impl SolLibrary {
    /// Returns `true` if all functions of this library will be inlined.
    ///
    /// This checks if all functions are either internal or private, because internal functions can
    /// only be accessed from within the current contract or contracts deriving from it. They cannot
    /// be accessed externally. Since they are not exposed to the outside through the contract’s
    /// ABI, they can take parameters of internal types like mappings or storage references.
    ///
    /// See also <https://docs.soliditylang.org/en/latest/contracts.html#libraries>
    pub fn is_inlined(&self) -> bool {
        self.is_inlined
    }
}

/// A spanned item.
#[derive(Clone, Debug)]
pub struct Spanned<T> {
    /// The byte range of `data` in the file.
    pub span: Range<usize>,
    /// The data of the item.
    pub data: T,
}

impl<T> Spanned<T> {
    /// Creates a new data unit with the given data and location.
    pub fn new(data: T, span: Range<usize>) -> Self {
        Self { data, span }
    }

    /// Returns the underlying data.
    pub fn data(&self) -> &T {
        &self.data
    }

    /// Returns the location.
    pub fn span(&self) -> Range<usize> {
        self.span.clone()
    }

    /// Returns the location adjusted by an offset.
    ///
    /// Used to determine new position of the unit within the file after content manipulation.
    pub fn loc_by_offset(&self, offset: isize) -> Range<usize> {
        utils::range_by_offset(&self.span, offset)
    }
}

fn library_is_inlined(contract: &ast::ItemContract<'_>) -> bool {
    contract
        .body
        .iter()
        .filter_map(|item| match &item.kind {
            ast::ItemKind::Function(f) => Some(f),
            _ => None,
        })
        .all(|f| {
            !matches!(
                f.header.visibility,
                Some(ast::Visibility::Public | ast::Visibility::External)
            )
        })
}