Skip to main content

solar_ast/ast/
semver.rs

1use crate::BoxSlice;
2use semver::Op;
3use solar_data_structures::smallvec::{SmallVec, smallvec};
4use solar_interface::Span;
5use std::{cmp::Ordering, fmt};
6
7pub use semver::Op as SemverOp;
8
9// We use the same approach as Solc.
10// See [`SemverReq::dis`] field docs for more details on how the requirements are treated.
11
12// Solc implementation notes:
13// - uses `unsigned` (`u32`) for version integers: https://github.com/argotorg/solidity/blob/e81f2bdbd66e9c8780f74b8a8d67b4dc2c87945e/liblangutil/SemVerHandler.cpp#L258
14// - version numbers can be `*/x/X`, which are represented as `u32::MAX`: https://github.com/argotorg/solidity/blob/e81f2bdbd66e9c8780f74b8a8d67b4dc2c87945e/liblangutil/SemVerHandler.cpp#L263
15// - ranges are parsed as `>=start, <=end`: https://github.com/argotorg/solidity/blob/e81f2bdbd66e9c8780f74b8a8d67b4dc2c87945e/liblangutil/SemVerHandler.cpp#L209
16//   we however dedicate a separate node for this: [`SemverReqComponentKind::Range`]
17
18/// A SemVer version number.
19#[derive(Clone, Copy)]
20pub enum SemverVersionNumber {
21    /// A number.
22    Number(u32),
23    /// `*`, `X`, or `x`.
24    Wildcard,
25}
26
27impl From<u64> for SemverVersionNumber {
28    #[inline]
29    fn from(n: u64) -> Self {
30        match n.try_into() {
31            Ok(n) => Self::Number(n),
32            Err(_) => Self::Wildcard,
33        }
34    }
35}
36
37impl From<SemverVersionNumber> for u64 {
38    #[inline]
39    fn from(value: SemverVersionNumber) -> Self {
40        match value {
41            SemverVersionNumber::Number(n) => n as Self,
42            SemverVersionNumber::Wildcard => Self::MAX,
43        }
44    }
45}
46
47impl fmt::Display for SemverVersionNumber {
48    #[inline]
49    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50        match self {
51            Self::Number(n) => n.fmt(f),
52            Self::Wildcard => "*".fmt(f),
53        }
54    }
55}
56
57impl fmt::Debug for SemverVersionNumber {
58    #[inline]
59    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60        fmt::Display::fmt(self, f)
61    }
62}
63
64impl PartialEq for SemverVersionNumber {
65    #[inline]
66    fn eq(&self, other: &Self) -> bool {
67        match (self, other) {
68            (Self::Wildcard, _) | (_, Self::Wildcard) => true,
69            (Self::Number(a), Self::Number(b)) => a == b,
70        }
71    }
72}
73
74impl Eq for SemverVersionNumber {}
75
76impl PartialOrd for SemverVersionNumber {
77    #[inline]
78    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
79        Some(self.cmp(other))
80    }
81}
82
83impl Ord for SemverVersionNumber {
84    #[inline]
85    fn cmp(&self, other: &Self) -> Ordering {
86        match (self, other) {
87            (Self::Wildcard, _) | (_, Self::Wildcard) => Ordering::Equal,
88            (Self::Number(a), Self::Number(b)) => a.cmp(b),
89        }
90    }
91}
92
93/// A SemVer version.
94#[derive(Clone)]
95pub struct SemverVersion {
96    pub span: Span,
97    /// Major version.
98    pub major: SemverVersionNumber,
99    /// Minor version. Optional.
100    pub minor: Option<SemverVersionNumber>,
101    /// Patch version. Optional.
102    pub patch: Option<SemverVersionNumber>,
103    // Pre-release and build metadata are not supported.
104}
105
106impl PartialEq for SemverVersion {
107    #[inline]
108    fn eq(&self, other: &Self) -> bool {
109        self.cmp(other) == Ordering::Equal
110    }
111}
112
113impl Eq for SemverVersion {}
114
115impl PartialOrd for SemverVersion {
116    #[inline]
117    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
118        Some(self.cmp(other))
119    }
120}
121
122impl Ord for SemverVersion {
123    #[inline]
124    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
125        #[inline]
126        fn cmp_opt(a: &Option<SemverVersionNumber>, b: &Option<SemverVersionNumber>) -> Ordering {
127            match (a, b) {
128                (Some(a), Some(b)) => a.cmp(b),
129                _ => Ordering::Equal,
130            }
131        }
132
133        self.major
134            .cmp(&other.major)
135            .then_with(|| cmp_opt(&self.minor, &other.minor))
136            .then_with(|| cmp_opt(&self.patch, &other.patch))
137    }
138}
139
140impl fmt::Display for SemverVersion {
141    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142        let Self { span: _, major, minor, patch } = *self;
143        write!(f, "{major}")?;
144        if let Some(minor) = minor {
145            write!(f, ".{minor}")?;
146        }
147        if let Some(patch) = patch {
148            if minor.is_none() {
149                f.write_str(".*")?;
150            }
151            write!(f, ".{patch}")?;
152        }
153        Ok(())
154    }
155}
156
157impl fmt::Debug for SemverVersion {
158    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159        f.debug_struct("SemverVersion")
160            .field("span", &self.span)
161            .field("version", &format_args!("{self}"))
162            .finish()
163    }
164}
165
166impl From<semver::Version> for SemverVersion {
167    #[inline]
168    fn from(version: semver::Version) -> Self {
169        Self::from(&version)
170    }
171}
172
173impl From<&semver::Version> for SemverVersion {
174    #[inline]
175    fn from(version: &semver::Version) -> Self {
176        Self {
177            span: Span::DUMMY,
178            major: version.major.into(),
179            minor: Some(version.minor.into()),
180            patch: Some(version.patch.into()),
181        }
182    }
183}
184
185impl From<SemverVersion> for semver::Version {
186    #[inline]
187    fn from(version: SemverVersion) -> Self {
188        Self::new(
189            version.major.into(),
190            version.minor.map(Into::into).unwrap_or(0),
191            version.patch.map(Into::into).unwrap_or(0),
192        )
193    }
194}
195
196impl SemverVersion {
197    /// Creates a new [::semver] version from this version.
198    #[inline]
199    pub fn into_semver(self) -> semver::Version {
200        self.into()
201    }
202}
203
204/// A SemVer version requirement. This is a list of components, and is empty only when parsing
205/// it failed.
206#[derive(Debug)]
207pub struct SemverReq<'ast> {
208    /// The components of this requirement.
209    ///
210    /// Or-ed list of and-ed components, meaning that `matches` is evaluated as
211    /// `any([all(c) for c in dis])`.
212    /// E.g.: `^0 <=1 || 0.5.0 - 0.6.0 ... || ...` -> `[[^0, <=1], [0.5.0 - 0.6.0, ...], ...]`
213    pub dis: BoxSlice<'ast, SemverReqCon<'ast>>,
214}
215
216impl fmt::Display for SemverReq<'_> {
217    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
218        for (i, con) in self.dis.iter().enumerate() {
219            if i > 0 {
220                f.write_str(" || ")?;
221            }
222            write!(f, "{con}")?;
223        }
224        Ok(())
225    }
226}
227
228impl SemverReq<'_> {
229    /// Returns `true` if the given version satisfies this requirement.
230    pub fn matches(&self, version: &SemverVersion) -> bool {
231        self.dis.iter().any(|c| c.matches(version))
232    }
233
234    /// Converts this requirement to a [::semver] version requirement.
235    pub fn to_semver(&self) -> SemverVersionReqCompat {
236        SemverVersionReqCompat { reqs: self.dis.iter().map(SemverReqCon::to_semver).collect() }
237    }
238}
239
240/// A list of or-ed [`semver::VersionReq`].
241///
242/// Obtained with [`SemverReq::to_semver`].
243pub struct SemverVersionReqCompat {
244    /// The list of requirements.
245    pub reqs: Vec<semver::VersionReq>,
246}
247
248impl SemverVersionReqCompat {
249    /// Returns `true` if the given version satisfies this requirement.
250    pub fn matches(&self, version: &semver::Version) -> bool {
251        self.reqs.iter().any(|r| r.matches(version))
252    }
253}
254
255/// A list of conjoint SemVer version requirement components.
256#[derive(Debug)]
257pub struct SemverReqCon<'ast> {
258    pub span: Span,
259    /// The list of components. See [`SemverReq::dis`] for more details.
260    pub components: BoxSlice<'ast, SemverReqComponent>,
261}
262
263impl fmt::Display for SemverReqCon<'_> {
264    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
265        for (j, component) in self.components.iter().enumerate() {
266            if j > 0 {
267                f.write_str(" ")?;
268            }
269            write!(f, "{component}")?;
270        }
271        Ok(())
272    }
273}
274
275impl SemverReqCon<'_> {
276    /// Converts this requirement to a [::semver] version requirement.
277    pub fn to_semver(&self) -> semver::VersionReq {
278        semver::VersionReq {
279            comparators: self.components.iter().flat_map(SemverReqComponent::to_semver).collect(),
280        }
281    }
282
283    /// Returns `true` if the given version satisfies this requirement.
284    pub fn matches(&self, version: &SemverVersion) -> bool {
285        self.components.iter().all(|c| c.matches(version))
286    }
287}
288
289/// A single SemVer version requirement component.
290#[derive(Clone, Debug)]
291pub struct SemverReqComponent {
292    pub span: Span,
293    pub kind: SemverReqComponentKind,
294}
295
296impl fmt::Display for SemverReqComponent {
297    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
298        self.kind.fmt(f)
299    }
300}
301
302impl SemverReqComponent {
303    /// Converts this requirement component to a [::semver] comparator.
304    pub fn to_semver(&self) -> SmallVec<[semver::Comparator; 2]> {
305        self.kind.to_semver()
306    }
307
308    /// Returns `true` if the given version satisfies this requirement component.
309    pub fn matches(&self, version: &SemverVersion) -> bool {
310        self.kind.matches(version)
311    }
312}
313
314/// A SemVer version requirement component.
315#[derive(Clone, Debug)]
316pub enum SemverReqComponentKind {
317    /// `v`, `=v`
318    Op(Option<Op>, SemverVersion),
319    /// `l - r`
320    Range(SemverVersion, SemverVersion),
321}
322
323impl fmt::Display for SemverReqComponentKind {
324    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
325        match self {
326            Self::Op(op, version) => {
327                if let Some(op) = op {
328                    let op = match op {
329                        Op::Exact => "=",
330                        Op::Greater => ">",
331                        Op::GreaterEq => ">=",
332                        Op::Less => "<",
333                        Op::LessEq => "<=",
334                        Op::Tilde => "~",
335                        Op::Caret => "^",
336                        Op::Wildcard => "*",
337                        _ => "",
338                    };
339                    f.write_str(op)?;
340                }
341                write!(f, "{version}")
342            }
343            Self::Range(left, right) => write!(f, "{left} - {right}"),
344        }
345    }
346}
347
348impl SemverReqComponentKind {
349    /// Converts this requirement component to a [::semver] comparator.
350    pub fn to_semver(&self) -> SmallVec<[semver::Comparator; 2]> {
351        let cvt_op = |op: Option<Op>, version: &SemverVersion| semver::Comparator {
352            op: op.unwrap_or(Op::Exact),
353            major: version.major.into(),
354            minor: version.minor.map(Into::into),
355            patch: version.patch.map(Into::into),
356            pre: Default::default(),
357        };
358        match self {
359            Self::Op(op, version) => smallvec![cvt_op(*op, version)],
360            Self::Range(start, end) => smallvec![
361                cvt_op(Some(semver::Op::GreaterEq), start),
362                cvt_op(Some(semver::Op::LessEq), end)
363            ],
364        }
365    }
366
367    /// Returns `true` if the given version satisfies this requirement component.
368    pub fn matches(&self, version: &SemverVersion) -> bool {
369        match self {
370            Self::Op(op, other) => matches_op(op.unwrap_or(Op::Exact), version, other),
371            Self::Range(start, end) => {
372                matches_op(Op::GreaterEq, version, start) && matches_op(Op::LessEq, version, end)
373            }
374        }
375    }
376}
377
378fn matches_op(op: Op, a: &SemverVersion, b: &SemverVersion) -> bool {
379    match op {
380        Op::Exact => a == b,
381        Op::Greater => a > b,
382        Op::GreaterEq => a >= b,
383        Op::Less => a < b,
384        Op::LessEq => a <= b,
385        Op::Tilde => matches_tilde(a, b),
386        Op::Caret => matches_caret(a, b),
387        Op::Wildcard => true,
388        _ => false,
389    }
390}
391
392fn matches_tilde(a: &SemverVersion, b: &SemverVersion) -> bool {
393    // https://github.com/argotorg/solidity/blob/e81f2bdbd66e9c8780f74b8a8d67b4dc2c87945e/liblangutil/SemVerHandler.cpp#L80
394    if !matches_op(Op::GreaterEq, a, b) {
395        return false;
396    }
397
398    let mut a = a.clone();
399    a.patch = None;
400    matches_op(Op::LessEq, &a, b)
401}
402
403fn matches_caret(a: &SemverVersion, b: &SemverVersion) -> bool {
404    // https://github.com/argotorg/solidity/blob/e81f2bdbd66e9c8780f74b8a8d67b4dc2c87945e/liblangutil/SemVerHandler.cpp#L95
405    if !matches_op(Op::GreaterEq, a, b) {
406        return false;
407    }
408
409    let mut a = a.clone();
410    if a.major > SemverVersionNumber::Number(0) {
411        a.minor = None;
412    }
413    a.patch = None;
414    matches_op(Op::LessEq, &a, b)
415}
416
417// Tests in `crates/parse/src/parser/item.rs`