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
// SPDX-FileCopyrightText: 2022 HH Partners
//
// SPDX-License-Identifier: MIT

//! The main struct of the library.

use std::{collections::HashSet, fmt::Display, string::ToString};

use crate::{
    error::SpdxExpressionError,
    expression_variant::{ExpressionVariant, SimpleExpression},
};

/// Main struct for SPDX License Expressions.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SpdxExpression {
    /// The parsed expression.
    inner: ExpressionVariant,
}

impl SpdxExpression {
    /// Parse `Self` from a string. The input expression needs to be a syntactically valid SPDX
    /// expression, `NONE` or `NOASSERTION`. The parser accepts license identifiers that are not
    /// valid SPDX.
    ///
    /// # Examples
    ///
    /// ```
    /// # use spdx_expression::SpdxExpression;
    /// # use spdx_expression::SpdxExpressionError;
    /// #
    /// let expression = SpdxExpression::parse("MIT")?;
    /// # Ok::<(), SpdxExpressionError>(())
    /// ```
    ///
    /// License expressions need to be syntactically valid, but they can include license
    /// identifiers not on the SPDX license list or not specified with `LicenseRef`.
    ///
    /// ```
    /// # use spdx_expression::SpdxExpression;
    /// # use spdx_expression::SpdxExpressionError;
    /// #
    /// let expression = SpdxExpression::parse("MIT OR InvalidLicenseId")?;
    /// # Ok::<(), SpdxExpressionError>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns `SpdxExpressionError` if the license expression is not syntactically valid.
    pub fn parse(expression: &str) -> Result<Self, SpdxExpressionError> {
        Ok(Self {
            inner: ExpressionVariant::parse(expression)
                .map_err(|err| SpdxExpressionError::Parse(err.to_string()))?,
        })
    }

    /// Get all license and exception identifiers from the `SpdxExpression`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::collections::HashSet;
    /// # use std::iter::FromIterator;
    /// # use spdx_expression::SpdxExpression;
    /// # use spdx_expression::SpdxExpressionError;
    /// #
    /// let expression = SpdxExpression::parse("MIT OR Apache-2.0")?;
    /// let licenses = expression.identifiers();
    /// assert_eq!(licenses, HashSet::from_iter(["Apache-2.0".to_string(), "MIT".to_string()]));
    /// # Ok::<(), SpdxExpressionError>(())
    /// ```
    ///
    /// ```
    /// # use std::collections::HashSet;
    /// # use std::iter::FromIterator;
    /// # use spdx_expression::SpdxExpression;
    /// # use spdx_expression::SpdxExpressionError;
    /// #
    /// let expression = SpdxExpression::parse("MIT OR GPL-2.0-only WITH Classpath-exception-2.0")?;
    /// let licenses = expression.identifiers();
    /// assert_eq!(
    ///     licenses,
    ///     HashSet::from_iter([
    ///         "MIT".to_string(),
    ///         "GPL-2.0-only".to_string(),
    ///         "Classpath-exception-2.0".to_string()
    ///     ])
    /// );
    /// # Ok::<(), SpdxExpressionError>(())
    /// ```
    pub fn identifiers(&self) -> HashSet<String> {
        let mut identifiers = self
            .licenses()
            .iter()
            .map(ToString::to_string)
            .collect::<HashSet<_>>();

        identifiers.extend(self.exceptions().iter().map(ToString::to_string));

        identifiers
    }

    /// Get all simple license expressions in `Self`. For licenses with exceptions, returns the
    /// license without the exception
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::collections::HashSet;
    /// # use std::iter::FromIterator;
    /// # use spdx_expression::SpdxExpression;
    /// # use spdx_expression::SpdxExpressionError;
    /// #
    /// let expression = SpdxExpression::parse(
    ///     "(MIT OR Apache-2.0 AND (GPL-2.0-only WITH Classpath-exception-2.0 OR ISC))",
    /// )
    /// .unwrap();
    ///
    /// let licenses = expression.licenses();
    ///
    /// assert_eq!(
    ///     licenses
    ///         .iter()
    ///         .map(|&license| license.identifier.as_str())
    ///         .collect::<HashSet<_>>(),
    ///     HashSet::from_iter(["Apache-2.0", "GPL-2.0-only", "ISC", "MIT"])
    /// );
    /// # Ok::<(), SpdxExpressionError>(())
    /// ```
    pub fn licenses(&self) -> HashSet<&SimpleExpression> {
        self.inner.licenses()
    }

    /// Get all exception identifiers for `Self`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::collections::HashSet;
    /// # use std::iter::FromIterator;
    /// # use spdx_expression::SpdxExpression;
    /// # use spdx_expression::SpdxExpressionError;
    /// #
    /// let expression = SpdxExpression::parse(
    ///     "(MIT OR Apache-2.0 AND (GPL-2.0-only WITH Classpath-exception-2.0 OR ISC))",
    /// )
    /// .unwrap();
    ///
    /// let exceptions = expression.exceptions();
    ///
    /// assert_eq!(exceptions, HashSet::from_iter(["Classpath-exception-2.0"]));
    /// # Ok::<(), SpdxExpressionError>(())
    /// ```
    pub fn exceptions(&self) -> HashSet<&str> {
        self.inner.exceptions()
    }
}

impl Display for SpdxExpression {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.inner)
    }
}

#[cfg(test)]
mod tests {
    use std::iter::FromIterator;

    use super::*;

    #[test]
    fn test_parsing_works() {
        let expression = SpdxExpression::parse("MIT AND (Apache-2.0 OR ISC)").unwrap();
        assert_eq!(expression.to_string(), "MIT AND (Apache-2.0 OR ISC)");
    }

    #[test]
    fn test_identifiers_from_simple_expression() {
        let expression = SpdxExpression::parse("MIT").unwrap();
        let licenses = expression.identifiers();
        assert_eq!(licenses, HashSet::from_iter(["MIT".to_string()]));
    }

    #[test]
    fn test_identifiers_from_compound_or_expression() {
        let expression = SpdxExpression::parse("MIT OR Apache-2.0").unwrap();
        let licenses = expression.identifiers();
        assert_eq!(
            licenses,
            HashSet::from_iter(["Apache-2.0".to_string(), "MIT".to_string()])
        );
    }

    #[test]
    fn test_identifiers_from_compound_parentheses_expression() {
        let expression = SpdxExpression::parse(
            "(MIT OR Apache-2.0 AND (GPL-2.0-only WITH Classpath-exception-2.0 OR ISC))",
        )
        .unwrap();
        let licenses = expression.identifiers();
        assert_eq!(
            licenses,
            HashSet::from_iter([
                "Apache-2.0".to_string(),
                "Classpath-exception-2.0".to_string(),
                "GPL-2.0-only".to_string(),
                "ISC".to_string(),
                "MIT".to_string()
            ])
        );
    }

    #[test]
    fn test_licenses_from_compound_parentheses_expression() {
        let expression = SpdxExpression::parse(
            "(MIT OR Apache-2.0 AND (GPL-2.0-only WITH Classpath-exception-2.0 OR ISC))",
        )
        .unwrap();

        let licenses = expression.licenses();

        assert_eq!(
            licenses
                .iter()
                .map(|&license| license.identifier.as_str())
                .collect::<HashSet<_>>(),
            HashSet::from_iter(["Apache-2.0", "GPL-2.0-only", "ISC", "MIT"])
        );
    }

    #[test]
    fn test_exceptions_from_compound_parentheses_expression() {
        let expression = SpdxExpression::parse(
            "(MIT OR Apache-2.0 AND (GPL-2.0-only WITH Classpath-exception-2.0 OR ISC))",
        )
        .unwrap();

        let exceptions = expression.exceptions();

        assert_eq!(exceptions, HashSet::from_iter(["Classpath-exception-2.0"]));
    }
}