| 1 |
//! License expression parsing for DEP-5 copyright files. |
| 2 |
//! |
| 3 |
//! License expressions combine license names with `or`, `and`, and `with` operators. |
| 4 |
//! `and` binds tighter than `or`. A comma before an operator lowers its precedence, |
| 5 |
//! e.g. `A or B, and C` means `(A or B) and C`. |
| 6 |
//! |
| 7 |
//! The `with` keyword attaches an exception to the preceding license name |
| 8 |
//! (e.g. `GPL-2+ with OpenSSL-exception`). |
| 9 |
//! |
| 10 |
//! License names between operators are taken verbatim, including any spaces, |
| 11 |
//! so malformed names such as `Apache 2.0` survive a parse/display round trip |
| 12 |
//! rather than being truncated at the first space. |
| 13 |
|
| 14 |
/// An error from the strict expression parsers. |
| 15 |
/// |
| 16 |
/// [`LicenseExpr::parse`] never fails (malformed input degrades to verbatim |
| 17 |
/// names); [`LicenseExpr::parse_strict`] and [`LicenseExpr::parse_spdx`] |
| 18 |
/// report malformed input with this error instead, so callers can fall back |
| 19 |
/// to treating the field as an opaque literal. |
| 20 |
#[derive(Clone, PartialEq, Eq, Debug)] |
| 21 |
pub struct ExprParseError { |
| 22 |
message: String, |
| 23 |
input: String, |
| 24 |
} |
| 25 |
|
| 26 |
impl ExprParseError { |
| 27 |
fn new(message: impl Into<String>, input: &str) -> Self { |
| 28 |
ExprParseError { |
| 29 |
message: message.into(), |
| 30 |
input: input.to_string(), |
| 31 |
} |
| 32 |
} |
| 33 |
|
| 34 |
/// The expression that failed to parse. |
| 35 |
pub fn input(&self) -> &str { |
| 36 |
&self.input |
| 37 |
} |
| 38 |
|
| 39 |
/// What was wrong with it, without the expression itself. |
| 40 |
pub fn message(&self) -> &str { |
| 41 |
&self.message |
| 42 |
} |
| 43 |
} |
| 44 |
|
| 45 |
impl std::fmt::Display for ExprParseError { |
| 46 |
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 47 |
write!(f, "{} in license expression {:?}", self.message, self.input) |
| 48 |
} |
| 49 |
} |
| 50 |
|
| 51 |
impl std::error::Error for ExprParseError {} |
| 52 |
|
| 53 |
/// A parsed license expression from a DEP-5 copyright file. |
| 54 |
#[derive(Clone, PartialEq, Eq, Debug)] |
| 55 |
pub enum LicenseExpr { |
| 56 |
/// A single license name, e.g. `MIT`. |
| 57 |
Name(String), |
| 58 |
|
| 59 |
/// A license with an exception, e.g. `GPL-2+ with OpenSSL-exception`. |
| 60 |
WithException(String, String), |
| 61 |
|
| 62 |
/// All of these licenses apply simultaneously. |
| 63 |
And(Vec<LicenseExpr>), |
| 64 |
|
| 65 |
/// Any one of these licenses may be chosen. |
| 66 |
Or(Vec<LicenseExpr>), |
| 67 |
} |
| 68 |
|
| 69 |
impl LicenseExpr { |
| 70 |
/// Parse a license expression string. |
| 71 |
/// |
| 72 |
/// # Examples |
| 73 |
/// |
| 74 |
/// ``` |
| 75 |
/// use debian_copyright::LicenseExpr; |
| 76 |
/// |
| 77 |
/// let expr = LicenseExpr::parse("GPL-2+ or MIT"); |
| 78 |
/// assert_eq!(expr, LicenseExpr::Or(vec![ |
| 79 |
/// LicenseExpr::Name("GPL-2+".to_string()), |
| 80 |
/// LicenseExpr::Name("MIT".to_string()), |
| 81 |
/// ])); |
| 82 |
/// |
| 83 |
/// let expr = LicenseExpr::parse("GPL-2+ with OpenSSL-exception"); |
| 84 |
/// assert_eq!(expr, LicenseExpr::WithException( |
| 85 |
/// "GPL-2+".to_string(), |
| 86 |
/// "OpenSSL-exception".to_string(), |
| 87 |
/// )); |
| 88 |
/// ``` |
| 89 |
pub fn parse(input: &str) -> Self { |
| 90 |
let tokens = tokenize(input); |
| 91 |
if tokens.is_empty() { |
| 92 |
return LicenseExpr::Name(String::new()); |
| 93 |
} |
| 94 |
parse_expr(input, &tokens) |
| 95 |
} |
| 96 |
|
| 97 |
/// Parse a license expression string, rejecting malformed input. |
| 98 |
/// |
| 99 |
/// Unlike [`parse`](Self::parse), which accepts anything (unparseable |
| 100 |
/// constructs survive verbatim inside names), this enforces the DEP-5 |
| 101 |
/// short-name grammar: a license name is a single token, operators may |
| 102 |
/// not dangle, and a comma must introduce a lowered `and`/`or`. Callers |
| 103 |
/// use it to detect fields that are not really expressions and treat |
| 104 |
/// them as opaque literals instead. |
| 105 |
/// |
| 106 |
/// # Examples |
| 107 |
/// |
| 108 |
/// ``` |
| 109 |
/// use debian_copyright::LicenseExpr; |
| 110 |
/// |
| 111 |
/// assert!(LicenseExpr::parse_strict("GPL-2+ or MIT").is_ok()); |
| 112 |
/// assert!(LicenseExpr::parse_strict("Apache 2.0").is_err()); |
| 113 |
/// assert!(LicenseExpr::parse_strict("MIT or").is_err()); |
| 114 |
/// ``` |
| 115 |
pub fn parse_strict(input: &str) -> Result<Self, ExprParseError> { |
| 116 |
let tokens = tokenize(input); |
| 117 |
StrictParser { |
| 118 |
input, |
| 119 |
tokens: &tokens, |
| 120 |
pos: 0, |
| 121 |
} |
| 122 |
.parse() |
| 123 |
} |
| 124 |
|
| 125 |
/// Parse an SPDX license expression. |
| 126 |
/// |
| 127 |
/// SPDX expressions use uppercase `AND`/`OR`/`WITH` operators (accepted |
| 128 |
/// case-insensitively here, as found in the wild) and parentheses for |
| 129 |
/// grouping; `WITH` attaches an exception identifier to a single license |
| 130 |
/// id. The resulting tree uses the same [`LicenseExpr`] vocabulary as the |
| 131 |
/// DEP-5 parsers, with leaf names kept verbatim; use |
| 132 |
/// [`map_names`](Self::map_names) to convert them to DEP-5 names. |
| 133 |
/// |
| 134 |
/// # Examples |
| 135 |
/// |
| 136 |
/// ``` |
| 137 |
/// use debian_copyright::LicenseExpr; |
| 138 |
/// |
| 139 |
/// let expr = LicenseExpr::parse_spdx("(MIT AND ISC) OR GPL-2.0-only").unwrap(); |
| 140 |
/// assert_eq!(expr, LicenseExpr::Or(vec![ |
| 141 |
/// LicenseExpr::And(vec![ |
| 142 |
/// LicenseExpr::Name("MIT".to_string()), |
| 143 |
/// LicenseExpr::Name("ISC".to_string()), |
| 144 |
/// ]), |
| 145 |
/// LicenseExpr::Name("GPL-2.0-only".to_string()), |
| 146 |
/// ])); |
| 147 |
/// ``` |
| 148 |
pub fn parse_spdx(input: &str) -> Result<Self, ExprParseError> { |
| 149 |
let tokens = spdx_tokenize(input); |
| 150 |
SpdxParser { |
| 151 |
input, |
| 152 |
tokens: &tokens, |
| 153 |
pos: 0, |
| 154 |
} |
| 155 |
.parse() |
| 156 |
} |
| 157 |
|
| 158 |
/// Render the expression as an unambiguous SPDX string. |
| 159 |
/// |
| 160 |
/// Compound operands are parenthesised, so the result round-trips |
| 161 |
/// through [`parse_spdx`](Self::parse_spdx) even for nestings DEP-5 |
| 162 |
/// cannot express. Leaf names and exceptions are emitted verbatim; use |
| 163 |
/// [`map_names`](Self::map_names) first to convert DEP-5 names to SPDX |
| 164 |
/// identifiers. |
| 165 |
/// |
| 166 |
/// # Examples |
| 167 |
/// |
| 168 |
/// ``` |
| 169 |
/// use debian_copyright::LicenseExpr; |
| 170 |
/// |
| 171 |
/// let expr = LicenseExpr::parse_spdx("(MIT AND ISC) OR GPL-2.0-only").unwrap(); |
| 172 |
/// assert_eq!(expr.to_spdx_string(), "(MIT AND ISC) OR GPL-2.0-only"); |
| 173 |
/// ``` |
| 174 |
pub fn to_spdx_string(&self) -> String { |
| 175 |
fn operand(expr: &LicenseExpr) -> String { |
| 176 |
match expr { |
| 177 |
LicenseExpr::And(_) | LicenseExpr::Or(_) => { |
| 178 |
format!("({})", expr.to_spdx_string()) |
| 179 |
} |
| 180 |
_ => expr.to_spdx_string(), |
| 181 |
} |
| 182 |
} |
| 183 |
match self { |
| 184 |
LicenseExpr::Name(n) => n.clone(), |
| 185 |
LicenseExpr::WithException(n, e) => format!("{} WITH {}", n, e), |
| 186 |
LicenseExpr::And(exprs) => exprs.iter().map(operand).collect::<Vec<_>>().join(" AND "), |
| 187 |
LicenseExpr::Or(exprs) => exprs.iter().map(operand).collect::<Vec<_>>().join(" OR "), |
| 188 |
} |
| 189 |
} |
| 190 |
|
| 191 |
/// Rebuild the expression with every leaf name and exception converted. |
| 192 |
/// |
| 193 |
/// Superseded by [`map_leaves`](Self::map_leaves), which takes one closure |
| 194 |
/// over a whole leaf rather than two interchangeable ones. The two |
| 195 |
/// converters here have the same signature, so passing them in the wrong |
| 196 |
/// order compiles and silently swaps names for exceptions. |
| 197 |
#[deprecated(since = "0.1.55", note = "use LicenseExpr::map_leaves instead")] |
| 198 |
pub fn map_names( |
| 199 |
&self, |
| 200 |
convert_name: &dyn Fn(&str) -> String, |
| 201 |
convert_exception: &dyn Fn(&str) -> String, |
| 202 |
) -> LicenseExpr { |
| 203 |
self.map_leaves(|leaf| match leaf { |
| 204 |
LicenseExpr::Name(n) => LicenseExpr::Name(convert_name(n)), |
| 205 |
LicenseExpr::WithException(n, e) => { |
| 206 |
LicenseExpr::WithException(convert_name(n), convert_exception(e)) |
| 207 |
} |
| 208 |
other => other.clone(), |
| 209 |
}) |
| 210 |
} |
| 211 |
|
| 212 |
/// Rebuild the expression with every leaf converted. |
| 213 |
/// |
| 214 |
/// Structural: the and/or/with shape is untouched, and `convert` is called |
| 215 |
/// on each [`Name`](LicenseExpr::Name) and |
| 216 |
/// [`WithException`](LicenseExpr::WithException) leaf in turn. This is how |
| 217 |
/// an expression moves between vocabularies, e.g. an SPDX-parsed tree into |
| 218 |
/// DEP-5 short names. Passing the leaf whole (rather than a name and an |
| 219 |
/// exception separately) means a conversion sees the license and its |
| 220 |
/// exception together, which matters when the pair maps to a single name. |
| 221 |
/// |
| 222 |
/// # Examples |
| 223 |
/// |
| 224 |
/// ``` |
| 225 |
/// use debian_copyright::LicenseExpr; |
| 226 |
/// |
| 227 |
/// let expr = LicenseExpr::parse_spdx("MIT OR GPL-2.0-only").unwrap(); |
| 228 |
/// let mapped = expr.map_leaves(|leaf| match leaf { |
| 229 |
/// LicenseExpr::Name(name) if name == "MIT" => LicenseExpr::Name("Expat".to_string()), |
| 230 |
/// other => other.clone(), |
| 231 |
/// }); |
| 232 |
/// assert_eq!(mapped.to_string(), "Expat or GPL-2.0-only"); |
| 233 |
/// ``` |
| 234 |
pub fn map_leaves(&self, convert: impl Fn(&LicenseExpr) -> LicenseExpr) -> LicenseExpr { |
| 235 |
fn walk(expr: &LicenseExpr, convert: &impl Fn(&LicenseExpr) -> LicenseExpr) -> LicenseExpr { |
| 236 |
match expr { |
| 237 |
LicenseExpr::Name(_) | LicenseExpr::WithException(..) => convert(expr), |
| 238 |
LicenseExpr::And(exprs) => { |
| 239 |
LicenseExpr::And(exprs.iter().map(|e| walk(e, convert)).collect()) |
| 240 |
} |
| 241 |
LicenseExpr::Or(exprs) => { |
| 242 |
LicenseExpr::Or(exprs.iter().map(|e| walk(e, convert)).collect()) |
| 243 |
} |
| 244 |
} |
| 245 |
} |
| 246 |
walk(self, &convert) |
| 247 |
} |
| 248 |
|
| 249 |
/// The expression's leaves ([`Name`](LicenseExpr::Name) and |
| 250 |
/// [`WithException`](LicenseExpr::WithException) nodes), in order. |
| 251 |
/// |
| 252 |
/// Unlike [`license_names`](Self::license_names) this keeps the |
| 253 |
/// exception attached to its license, so a caller grouping by "license |
| 254 |
/// as licensed" (where `GPL-2 with an exception` is not `GPL-2`) can key |
| 255 |
/// off each leaf as a whole. |
| 256 |
/// |
| 257 |
/// # Examples |
| 258 |
/// |
| 259 |
/// ``` |
| 260 |
/// use debian_copyright::LicenseExpr; |
| 261 |
/// |
| 262 |
/// let expr = LicenseExpr::parse("GPL-2+ with OpenSSL-exception or MIT"); |
| 263 |
/// let leaves = expr.leaves(); |
| 264 |
/// assert_eq!(leaves.len(), 2); |
| 265 |
/// assert_eq!(leaves[0].to_string(), "GPL-2+ with OpenSSL-exception"); |
| 266 |
/// assert_eq!(leaves[1].to_string(), "MIT"); |
| 267 |
/// ``` |
| 268 |
pub fn leaves(&self) -> Vec<&LicenseExpr> { |
| 269 |
let mut out = Vec::new(); |
| 270 |
fn collect<'a>(expr: &'a LicenseExpr, out: &mut Vec<&'a LicenseExpr>) { |
| 271 |
match expr { |
| 272 |
LicenseExpr::Name(_) | LicenseExpr::WithException(..) => out.push(expr), |
| 273 |
LicenseExpr::And(exprs) | LicenseExpr::Or(exprs) => { |
| 274 |
for expr in exprs { |
| 275 |
collect(expr, out); |
| 276 |
} |
| 277 |
} |
| 278 |
} |
| 279 |
} |
| 280 |
collect(self, &mut out); |
| 281 |
out |
| 282 |
} |
| 283 |
|
| 284 |
/// Returns the individual license names contained in this expression. |
| 285 |
/// |
| 286 |
/// For `WithException` variants, only the license name is returned, |
| 287 |
/// not the exception name. |
| 288 |
pub fn license_names(&self) -> Vec<&str> { |
| 289 |
let mut names = Vec::new(); |
| 290 |
self.collect_names(&mut names); |
| 291 |
names |
| 292 |
} |
| 293 |
|
| 294 |
/// Locate each license name in `input` along with its byte range. |
| 295 |
/// |
| 296 |
/// Returns each license name paired with the half-open byte range it |
| 297 |
/// occupies in `input`. Exception words after `with` are skipped, matching |
| 298 |
/// [`license_names`](Self::license_names). Unlike `license_names`, no |
| 299 |
/// entry is emitted for expressions that contain no name token, since |
| 300 |
/// there is no meaningful range to report. |
| 301 |
/// |
| 302 |
/// # Examples |
| 303 |
/// |
| 304 |
/// ``` |
| 305 |
/// use debian_copyright::LicenseExpr; |
| 306 |
/// |
| 307 |
/// let input = "GPL-2+ or MIT"; |
| 308 |
/// assert_eq!( |
| 309 |
/// LicenseExpr::name_ranges(input), |
| 310 |
/// vec![("GPL-2+", 0..6), ("MIT", 10..13)], |
| 311 |
/// ); |
| 312 |
/// |
| 313 |
/// let input = "GPL-2+ with OpenSSL-exception or MIT"; |
| 314 |
/// assert_eq!( |
| 315 |
/// LicenseExpr::name_ranges(input), |
| 316 |
/// vec![("GPL-2+", 0..6), ("MIT", 33..36)], |
| 317 |
/// ); |
| 318 |
/// ``` |
| 319 |
pub fn name_ranges(input: &str) -> Vec<(&str, std::ops::Range<usize>)> { |
| 320 |
let tokens = tokenize(input); |
| 321 |
let mut out = Vec::new(); |
| 322 |
let mut i = 0; |
| 323 |
while i < tokens.len() { |
| 324 |
match &tokens[i].kind { |
| 325 |
TokenKind::Word => { |
| 326 |
let last = word_run_end(&tokens, i); |
| 327 |
let range = tokens[i].range.start..tokens[last].range.end; |
| 328 |
out.push((&input[range.clone()], range)); |
| 329 |
i = last + 1; |
| 330 |
if matches!(tokens.get(i).map(|t| &t.kind), Some(TokenKind::With)) { |
| 331 |
i += 1; |
| 332 |
if matches!(tokens.get(i).map(|t| &t.kind), Some(TokenKind::Word)) { |
| 333 |
i = word_run_end(&tokens, i) + 1; |
| 334 |
} |
| 335 |
} |
| 336 |
} |
| 337 |
_ => { |
| 338 |
i += 1; |
| 339 |
} |
| 340 |
} |
| 341 |
} |
| 342 |
out |
| 343 |
} |
| 344 |
|
| 345 |
/// Whether this expression contains a top-level `or`, in which case a |
| 346 |
/// parent operator must be written in its comma-lowered form (`, and` / |
| 347 |
/// `, or`) to keep the intended grouping. |
| 348 |
fn needs_comma_join(&self) -> bool { |
| 349 |
match self { |
| 350 |
LicenseExpr::Or(_) => true, |
| 351 |
LicenseExpr::And(exprs) => exprs.iter().any(|e| e.needs_comma_join()), |
| 352 |
LicenseExpr::Name(_) | LicenseExpr::WithException(..) => false, |
| 353 |
} |
| 354 |
} |
| 355 |
|
| 356 |
fn collect_names<'a>(&'a self, names: &mut Vec<&'a str>) { |
| 357 |
match self { |
| 358 |
LicenseExpr::Name(n) => names.push(n), |
| 359 |
LicenseExpr::WithException(n, _) => names.push(n), |
| 360 |
LicenseExpr::And(exprs) | LicenseExpr::Or(exprs) => { |
| 361 |
for expr in exprs { |
| 362 |
expr.collect_names(names); |
| 363 |
} |
| 364 |
} |
| 365 |
} |
| 366 |
} |
| 367 |
} |
| 368 |
|
| 369 |
impl std::str::FromStr for LicenseExpr { |
| 370 |
type Err = ExprParseError; |
| 371 |
|
| 372 |
/// Parse a DEP-5 license expression, rejecting malformed input. |
| 373 |
/// |
| 374 |
/// This is [`LicenseExpr::parse_strict`], not the lenient |
| 375 |
/// [`LicenseExpr::parse`]: a `FromStr` that never fails would make the |
| 376 |
/// `Result` a lie. Reading arbitrary copyright fields, where prose in a |
| 377 |
/// `License` field must survive rather than fail, wants `parse` instead. |
| 378 |
/// |
| 379 |
/// # Examples |
| 380 |
/// |
| 381 |
/// ``` |
| 382 |
/// use debian_copyright::LicenseExpr; |
| 383 |
/// |
| 384 |
/// let expr: LicenseExpr = "GPL-2+ or MIT".parse().unwrap(); |
| 385 |
/// assert_eq!(expr.license_names(), vec!["GPL-2+", "MIT"]); |
| 386 |
/// assert!("Apache 2.0".parse::<LicenseExpr>().is_err()); |
| 387 |
/// ``` |
| 388 |
fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 389 |
LicenseExpr::parse_strict(s) |
| 390 |
} |
| 391 |
} |
| 392 |
|
| 393 |
impl std::fmt::Display for LicenseExpr { |
| 394 |
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 395 |
match self { |
| 396 |
LicenseExpr::Name(n) => f.write_str(n), |
| 397 |
LicenseExpr::WithException(n, e) => write!(f, "{} with {}", n, e), |
| 398 |
LicenseExpr::And(exprs) => { |
| 399 |
// `and` normally binds tighter than `or`, so an operand with |
| 400 |
// a top-level `or` forces the comma-lowered form: `A or B, and C`. |
| 401 |
let sep = if exprs.iter().any(|e| e.needs_comma_join()) { |
| 402 |
", and " |
| 403 |
} else { |
| 404 |
" and " |
| 405 |
}; |
| 406 |
for (i, expr) in exprs.iter().enumerate() { |
| 407 |
if i > 0 { |
| 408 |
f.write_str(sep)?; |
| 409 |
} |
| 410 |
write!(f, "{}", expr)?; |
| 411 |
} |
| 412 |
Ok(()) |
| 413 |
} |
| 414 |
LicenseExpr::Or(exprs) => { |
| 415 |
// An operand that itself uses the comma-lowered form needs |
| 416 |
// this `or` comma-lowered too: `A, and B or C, or D`. |
| 417 |
let sep = if exprs.iter().any(|e| e.needs_comma_join()) { |
| 418 |
", or " |
| 419 |
} else { |
| 420 |
" or " |
| 421 |
}; |
| 422 |
for (i, expr) in exprs.iter().enumerate() { |
| 423 |
if i > 0 { |
| 424 |
f.write_str(sep)?; |
| 425 |
} |
| 426 |
write!(f, "{}", expr)?; |
| 427 |
} |
| 428 |
Ok(()) |
| 429 |
} |
| 430 |
} |
| 431 |
} |
| 432 |
} |
| 433 |
|
| 434 |
#[derive(Debug, PartialEq, Eq, Clone)] |
| 435 |
enum TokenKind { |
| 436 |
Word, |
| 437 |
Or, |
| 438 |
And, |
| 439 |
With, |
| 440 |
Comma, |
| 441 |
} |
| 442 |
|
| 443 |
#[derive(Debug, Clone)] |
| 444 |
struct Token { |
| 445 |
kind: TokenKind, |
| 446 |
range: std::ops::Range<usize>, |
| 447 |
} |
| 448 |
|
| 449 |
/// Given that `tokens[start]` is a `Word`, return the index of the last token |
| 450 |
/// of the name run it begins: consecutive `Word` tokens, where a comma joins |
| 451 |
/// the run only when another word follows it. This mirrors how `parse` groups |
| 452 |
/// words into names (a comma directly before `and`/`or` is an operator, |
| 453 |
/// anywhere else it is preserved as part of the surrounding name). |
| 454 |
fn word_run_end(tokens: &[Token], start: usize) -> usize { |
| 455 |
let mut i = start; |
| 456 |
loop { |
| 457 |
let next = i + 1; |
| 458 |
match tokens.get(next).map(|t| &t.kind) { |
| 459 |
Some(TokenKind::Word) => i = next, |
| 460 |
Some(TokenKind::Comma) |
| 461 |
if matches!(tokens.get(next + 1).map(|t| &t.kind), Some(TokenKind::Word)) => |
| 462 |
{ |
| 463 |
i = next + 1; |
| 464 |
} |
| 465 |
_ => break, |
| 466 |
} |
| 467 |
} |
| 468 |
i |
| 469 |
} |
| 470 |
|
| 471 |
fn tokenize(input: &str) -> Vec<Token> { |
| 472 |
let mut tokens = Vec::new(); |
| 473 |
let mut pos = 0; |
| 474 |
while pos < input.len() { |
| 475 |
let Some(offset) = input[pos..].find(|c: char| !c.is_whitespace()) else { |
| 476 |
break; |
| 477 |
}; |
| 478 |
let start = pos + offset; |
| 479 |
pos = match input[start..].find(char::is_whitespace) { |
| 480 |
Some(offset) => start + offset, |
| 481 |
None => input.len(), |
| 482 |
}; |
| 483 |
let mut end = pos; |
| 484 |
let mut trailing_comma = false; |
| 485 |
if end > start && input.as_bytes()[end - 1] == b',' { |
| 486 |
trailing_comma = true; |
| 487 |
end -= 1; |
| 488 |
} |
| 489 |
if end > start { |
| 490 |
let word = &input[start..end]; |
| 491 |
let kind = if word.eq_ignore_ascii_case("or") { |
| 492 |
TokenKind::Or |
| 493 |
} else if word.eq_ignore_ascii_case("and") { |
| 494 |
TokenKind::And |
| 495 |
} else if word.eq_ignore_ascii_case("with") { |
| 496 |
TokenKind::With |
| 497 |
} else { |
| 498 |
TokenKind::Word |
| 499 |
}; |
| 500 |
tokens.push(Token { |
| 501 |
kind, |
| 502 |
range: start..end, |
| 503 |
}); |
| 504 |
} |
| 505 |
if trailing_comma { |
| 506 |
tokens.push(Token { |
| 507 |
kind: TokenKind::Comma, |
| 508 |
range: end..end + 1, |
| 509 |
}); |
| 510 |
} |
| 511 |
} |
| 512 |
tokens |
| 513 |
} |
| 514 |
|
| 515 |
/// Consume consecutive `Word` tokens starting at `*pos` and return the range |
| 516 |
/// of `input` they span, or `None` if the token at `*pos` is not a `Word`. |
| 517 |
/// The span preserves whatever separated the words in the input. |
| 518 |
fn take_words(tokens: &[Token], pos: &mut usize) -> Option<std::ops::Range<usize>> { |
| 519 |
let start = match tokens.get(*pos) { |
| 520 |
Some(Token { |
| 521 |
kind: TokenKind::Word, |
| 522 |
range, |
| 523 |
}) => range.start, |
| 524 |
_ => return None, |
| 525 |
}; |
| 526 |
let mut end = tokens[*pos].range.end; |
| 527 |
*pos += 1; |
| 528 |
while let Some(Token { |
| 529 |
kind: TokenKind::Word, |
| 530 |
range, |
| 531 |
}) = tokens.get(*pos) |
| 532 |
{ |
| 533 |
end = range.end; |
| 534 |
*pos += 1; |
| 535 |
} |
| 536 |
Some(start..end) |
| 537 |
} |
| 538 |
|
| 539 |
/// Parse a single license term: a name optionally followed by `with <exception>`. |
| 540 |
/// A name consumes all words until the next `or`, `and`, `with`, comma, or end, |
| 541 |
/// so names containing spaces (as found in malformed files) survive parsing. |
| 542 |
fn parse_term(input: &str, tokens: &[Token], pos: &mut usize) -> LicenseExpr { |
| 543 |
let name = match take_words(tokens, pos) { |
| 544 |
Some(range) => input[range].to_string(), |
| 545 |
None => return LicenseExpr::Name(String::new()), |
| 546 |
}; |
| 547 |
|
| 548 |
if matches!(tokens.get(*pos).map(|t| &t.kind), Some(TokenKind::With)) { |
| 549 |
*pos += 1; |
| 550 |
let exception = match take_words(tokens, pos) { |
| 551 |
Some(range) => input[range].to_string(), |
| 552 |
None => String::new(), |
| 553 |
}; |
| 554 |
LicenseExpr::WithException(name, exception) |
| 555 |
} else { |
| 556 |
LicenseExpr::Name(name) |
| 557 |
} |
| 558 |
} |
| 559 |
|
| 560 |
/// Parse a token stream into a `LicenseExpr`. |
| 561 |
/// |
| 562 |
/// Handles comma-lowered precedence by splitting on `, and` / `, or` first, |
| 563 |
/// then parsing each segment with normal precedence (`and` > `or`). |
| 564 |
fn parse_expr(input: &str, tokens: &[Token]) -> LicenseExpr { |
| 565 |
// Split into segments at comma boundaries (comma + operator = low precedence). |
| 566 |
let mut segments: Vec<(Vec<Token>, Option<TokenKind>)> = Vec::new(); |
| 567 |
let mut current: Vec<Token> = Vec::new(); |
| 568 |
|
| 569 |
let mut i = 0; |
| 570 |
while i < tokens.len() { |
| 571 |
if tokens[i].kind == TokenKind::Comma { |
| 572 |
if i + 1 < tokens.len() && matches!(tokens[i + 1].kind, TokenKind::Or | TokenKind::And) |
| 573 |
{ |
| 574 |
let op = tokens[i + 1].kind.clone(); |
| 575 |
segments.push((std::mem::take(&mut current), Some(op))); |
| 576 |
i += 2; |
| 577 |
} else { |
| 578 |
i += 1; |
| 579 |
} |
| 580 |
} else { |
| 581 |
current.push(tokens[i].clone()); |
| 582 |
i += 1; |
| 583 |
} |
| 584 |
} |
| 585 |
if !current.is_empty() { |
| 586 |
segments.push((current, None)); |
| 587 |
} |
| 588 |
|
| 589 |
// A lone comma produces tokens but no segments. |
| 590 |
if segments.is_empty() { |
| 591 |
return LicenseExpr::Name(String::new()); |
| 592 |
} |
| 593 |
|
| 594 |
if segments.len() == 1 { |
| 595 |
return parse_segment(input, &segments[0].0); |
| 596 |
} |
| 597 |
|
| 598 |
// Group segments by their joining low-precedence operator. |
| 599 |
// Low-precedence `and` binds tighter than low-precedence `or`. |
| 600 |
// Nested same-operator expressions are spliced into their parent so |
| 601 |
// `A, and B and C` and `A and B and C` parse to the same flat tree. |
| 602 |
fn push_and_operand(group: &mut Vec<LicenseExpr>, expr: LicenseExpr) { |
| 603 |
match expr { |
| 604 |
LicenseExpr::And(exprs) => group.extend(exprs), |
| 605 |
other => group.push(other), |
| 606 |
} |
| 607 |
} |
| 608 |
|
| 609 |
let mut and_groups: Vec<Vec<LicenseExpr>> = vec![Vec::new()]; |
| 610 |
push_and_operand(&mut and_groups[0], parse_segment(input, &segments[0].0)); |
| 611 |
|
| 612 |
for i in 1..segments.len() { |
| 613 |
let preceding_op = segments[i - 1].1.as_ref().unwrap_or(&TokenKind::Or); |
| 614 |
if !matches!(preceding_op, TokenKind::And) { |
| 615 |
and_groups.push(Vec::new()); |
| 616 |
} |
| 617 |
push_and_operand( |
| 618 |
and_groups.last_mut().unwrap(), |
| 619 |
parse_segment(input, &segments[i].0), |
| 620 |
); |
| 621 |
} |
| 622 |
|
| 623 |
let mut or_operands = Vec::new(); |
| 624 |
for group in and_groups { |
| 625 |
let expr = if group.len() == 1 { |
| 626 |
group.into_iter().next().unwrap() |
| 627 |
} else { |
| 628 |
LicenseExpr::And(group) |
| 629 |
}; |
| 630 |
match expr { |
| 631 |
LicenseExpr::Or(exprs) => or_operands.extend(exprs), |
| 632 |
other => or_operands.push(other), |
| 633 |
} |
| 634 |
} |
| 635 |
|
| 636 |
if or_operands.len() == 1 { |
| 637 |
or_operands.into_iter().next().unwrap() |
| 638 |
} else { |
| 639 |
LicenseExpr::Or(or_operands) |
| 640 |
} |
| 641 |
} |
| 642 |
|
| 643 |
/// Parse a segment (no comma-lowered operators) with normal precedence: `and` > `or`. |
| 644 |
fn parse_segment(input: &str, tokens: &[Token]) -> LicenseExpr { |
| 645 |
// Split on `or` (lower precedence), then each part on `and`. |
| 646 |
let mut or_groups: Vec<Vec<Token>> = vec![Vec::new()]; |
| 647 |
for tok in tokens { |
| 648 |
if tok.kind == TokenKind::Or { |
| 649 |
or_groups.push(Vec::new()); |
| 650 |
} else { |
| 651 |
or_groups.last_mut().unwrap().push(tok.clone()); |
| 652 |
} |
| 653 |
} |
| 654 |
|
| 655 |
let or_exprs: Vec<LicenseExpr> = or_groups |
| 656 |
.into_iter() |
| 657 |
.map(|group| { |
| 658 |
let mut and_groups: Vec<Vec<Token>> = vec![Vec::new()]; |
| 659 |
for tok in &group { |
| 660 |
if tok.kind == TokenKind::And { |
| 661 |
and_groups.push(Vec::new()); |
| 662 |
} else { |
| 663 |
and_groups.last_mut().unwrap().push(tok.clone()); |
| 664 |
} |
| 665 |
} |
| 666 |
|
| 667 |
let and_exprs: Vec<LicenseExpr> = and_groups |
| 668 |
.into_iter() |
| 669 |
.map(|toks| { |
| 670 |
let mut pos = 0; |
| 671 |
parse_term(input, &toks, &mut pos) |
| 672 |
}) |
| 673 |
.collect(); |
| 674 |
|
| 675 |
if and_exprs.len() == 1 { |
| 676 |
and_exprs.into_iter().next().unwrap() |
| 677 |
} else { |
| 678 |
LicenseExpr::And(and_exprs) |
| 679 |
} |
| 680 |
}) |
| 681 |
.collect(); |
| 682 |
|
| 683 |
if or_exprs.len() == 1 { |
| 684 |
or_exprs.into_iter().next().unwrap() |
| 685 |
} else { |
| 686 |
LicenseExpr::Or(or_exprs) |
| 687 |
} |
| 688 |
} |
| 689 |
|
| 690 |
/// Strict recursive-descent parser for the DEP-5 short-name grammar |
| 691 |
/// (copyright-format 1.0 sec 7.2). The comma is a precedence level looser |
| 692 |
/// than `or`, applied as a left-associative fold: |
| 693 |
/// |
| 694 |
/// ```text |
| 695 |
/// comma-expr := or-expr ( "," ("and"|"or") or-expr )* |
| 696 |
/// or-expr := and-expr ( "or" and-expr )* |
| 697 |
/// and-expr := with-expr ( "and" with-expr )* |
| 698 |
/// with-expr := NAME ( "with" NAME+ )? |
| 699 |
/// ``` |
| 700 |
struct StrictParser<'a> { |
| 701 |
input: &'a str, |
| 702 |
tokens: &'a [Token], |
| 703 |
pos: usize, |
| 704 |
} |
| 705 |
|
| 706 |
impl<'a> StrictParser<'a> { |
| 707 |
fn err<T>(&self, message: &str) -> Result<T, ExprParseError> { |
| 708 |
Err(ExprParseError::new(message, self.input)) |
| 709 |
} |
| 710 |
|
| 711 |
fn peek(&self) -> Option<&TokenKind> { |
| 712 |
self.tokens.get(self.pos).map(|t| &t.kind) |
| 713 |
} |
| 714 |
|
| 715 |
fn parse(mut self) -> Result<LicenseExpr, ExprParseError> { |
| 716 |
if self.tokens.is_empty() { |
| 717 |
return self.err("empty expression"); |
| 718 |
} |
| 719 |
let expr = self.comma_expr()?; |
| 720 |
if self.pos != self.tokens.len() { |
| 721 |
return self.err("trailing tokens"); |
| 722 |
} |
| 723 |
Ok(expr) |
| 724 |
} |
| 725 |
|
| 726 |
fn comma_expr(&mut self) -> Result<LicenseExpr, ExprParseError> { |
| 727 |
let mut acc = self.or_expr()?; |
| 728 |
while self.peek() == Some(&TokenKind::Comma) { |
| 729 |
self.pos += 1; |
| 730 |
let op = match self.peek() { |
| 731 |
Some(TokenKind::And) => TokenKind::And, |
| 732 |
Some(TokenKind::Or) => TokenKind::Or, |
| 733 |
_ => return self.err("expected 'and' or 'or' after comma"), |
| 734 |
}; |
| 735 |
self.pos += 1; |
| 736 |
let rhs = self.or_expr()?; |
| 737 |
// Splice same-operator operands so the tree matches what the |
| 738 |
// lenient parser builds for the equivalent expression. |
| 739 |
acc = match (op, acc) { |
| 740 |
(TokenKind::And, LicenseExpr::And(mut exprs)) => { |
| 741 |
exprs.push(rhs); |
| 742 |
LicenseExpr::And(exprs) |
| 743 |
} |
| 744 |
(TokenKind::And, acc) => LicenseExpr::And(vec![acc, rhs]), |
| 745 |
(_, LicenseExpr::Or(mut exprs)) => { |
| 746 |
exprs.push(rhs); |
| 747 |
LicenseExpr::Or(exprs) |
| 748 |
} |
| 749 |
(_, acc) => LicenseExpr::Or(vec![acc, rhs]), |
| 750 |
}; |
| 751 |
} |
| 752 |
Ok(acc) |
| 753 |
} |
| 754 |
|
| 755 |
fn or_expr(&mut self) -> Result<LicenseExpr, ExprParseError> { |
| 756 |
let mut terms = vec![self.and_expr()?]; |
| 757 |
while self.peek() == Some(&TokenKind::Or) { |
| 758 |
self.pos += 1; |
| 759 |
terms.push(self.and_expr()?); |
| 760 |
} |
| 761 |
Ok(if terms.len() == 1 { |
| 762 |
terms.pop().unwrap() |
| 763 |
} else { |
| 764 |
LicenseExpr::Or(terms) |
| 765 |
}) |
| 766 |
} |
| 767 |
|
| 768 |
fn and_expr(&mut self) -> Result<LicenseExpr, ExprParseError> { |
| 769 |
let mut terms = vec![self.with_expr()?]; |
| 770 |
while self.peek() == Some(&TokenKind::And) { |
| 771 |
self.pos += 1; |
| 772 |
terms.push(self.with_expr()?); |
| 773 |
} |
| 774 |
Ok(if terms.len() == 1 { |
| 775 |
terms.pop().unwrap() |
| 776 |
} else { |
| 777 |
LicenseExpr::And(terms) |
| 778 |
}) |
| 779 |
} |
| 780 |
|
| 781 |
fn with_expr(&mut self) -> Result<LicenseExpr, ExprParseError> { |
| 782 |
let name = self.name()?; |
| 783 |
if self.peek() != Some(&TokenKind::With) { |
| 784 |
return Ok(LicenseExpr::Name(name)); |
| 785 |
} |
| 786 |
self.pos += 1; |
| 787 |
// The exception phrase may span several words ("Autoconf exception"). |
| 788 |
let start = match self.tokens.get(self.pos) { |
| 789 |
Some(Token { |
| 790 |
kind: TokenKind::Word, |
| 791 |
range, |
| 792 |
}) => range.start, |
| 793 |
_ => return self.err("expected exception after 'with'"), |
| 794 |
}; |
| 795 |
let mut end = self.tokens[self.pos].range.end; |
| 796 |
self.pos += 1; |
| 797 |
while let Some(Token { |
| 798 |
kind: TokenKind::Word, |
| 799 |
range, |
| 800 |
}) = self.tokens.get(self.pos) |
| 801 |
{ |
| 802 |
end = range.end; |
| 803 |
self.pos += 1; |
| 804 |
} |
| 805 |
Ok(LicenseExpr::WithException( |
| 806 |
name, |
| 807 |
self.input[start..end].to_string(), |
| 808 |
)) |
| 809 |
} |
| 810 |
|
| 811 |
fn name(&mut self) -> Result<String, ExprParseError> { |
| 812 |
match self.tokens.get(self.pos) { |
| 813 |
Some(Token { |
| 814 |
kind: TokenKind::Word, |
| 815 |
range, |
| 816 |
}) => { |
| 817 |
self.pos += 1; |
| 818 |
// A second consecutive word would be a multi-word name, which |
| 819 |
// the short-name grammar does not allow. |
| 820 |
if let Some(TokenKind::Word) = self.peek() { |
| 821 |
return self.err("expected operator between license names"); |
| 822 |
} |
| 823 |
Ok(self.input[range.clone()].to_string()) |
| 824 |
} |
| 825 |
Some(_) => self.err("expected license name"), |
| 826 |
None => self.err("unexpected end of expression"), |
| 827 |
} |
| 828 |
} |
| 829 |
} |
| 830 |
|
| 831 |
#[derive(Debug, PartialEq, Eq)] |
| 832 |
enum SpdxToken<'a> { |
| 833 |
Id(&'a str), |
| 834 |
And, |
| 835 |
Or, |
| 836 |
With, |
| 837 |
Open, |
| 838 |
Close, |
| 839 |
} |
| 840 |
|
| 841 |
fn spdx_tokenize(input: &str) -> Vec<SpdxToken<'_>> { |
| 842 |
fn classify(word: &str) -> SpdxToken<'_> { |
| 843 |
if word.eq_ignore_ascii_case("and") { |
| 844 |
SpdxToken::And |
| 845 |
} else if word.eq_ignore_ascii_case("or") { |
| 846 |
SpdxToken::Or |
| 847 |
} else if word.eq_ignore_ascii_case("with") { |
| 848 |
SpdxToken::With |
| 849 |
} else { |
| 850 |
SpdxToken::Id(word) |
| 851 |
} |
| 852 |
} |
| 853 |
let mut tokens = Vec::new(); |
| 854 |
let mut start: Option<usize> = None; |
| 855 |
for (i, c) in input.char_indices() { |
| 856 |
match c { |
| 857 |
'(' | ')' => { |
| 858 |
if let Some(s) = start.take() { |
| 859 |
tokens.push(classify(&input[s..i])); |
| 860 |
} |
| 861 |
tokens.push(if c == '(' { |
| 862 |
SpdxToken::Open |
| 863 |
} else { |
| 864 |
SpdxToken::Close |
| 865 |
}); |
| 866 |
} |
| 867 |
c if c.is_whitespace() => { |
| 868 |
if let Some(s) = start.take() { |
| 869 |
tokens.push(classify(&input[s..i])); |
| 870 |
} |
| 871 |
} |
| 872 |
_ => { |
| 873 |
if start.is_none() { |
| 874 |
start = Some(i); |
| 875 |
} |
| 876 |
} |
| 877 |
} |
| 878 |
} |
| 879 |
if let Some(s) = start { |
| 880 |
tokens.push(classify(&input[s..])); |
| 881 |
} |
| 882 |
tokens |
| 883 |
} |
| 884 |
|
| 885 |
/// Recursive-descent parser for SPDX license expressions: |
| 886 |
/// |
| 887 |
/// ```text |
| 888 |
/// or-expr := and-expr ( "OR" and-expr )* |
| 889 |
/// and-expr := with-expr ( "AND" with-expr )* |
| 890 |
/// with-expr := atom ( "WITH" exception-id )? |
| 891 |
/// atom := license-id | "(" or-expr ")" |
| 892 |
/// ``` |
| 893 |
struct SpdxParser<'a> { |
| 894 |
input: &'a str, |
| 895 |
tokens: &'a [SpdxToken<'a>], |
| 896 |
pos: usize, |
| 897 |
} |
| 898 |
|
| 899 |
impl<'a> SpdxParser<'a> { |
| 900 |
fn err<T>(&self, message: &str) -> Result<T, ExprParseError> { |
| 901 |
Err(ExprParseError::new(message, self.input)) |
| 902 |
} |
| 903 |
|
| 904 |
fn parse(mut self) -> Result<LicenseExpr, ExprParseError> { |
| 905 |
if self.tokens.is_empty() { |
| 906 |
return self.err("empty expression"); |
| 907 |
} |
| 908 |
let expr = self.or_expr()?; |
| 909 |
if self.pos != self.tokens.len() { |
| 910 |
return self.err("trailing tokens"); |
| 911 |
} |
| 912 |
Ok(expr) |
| 913 |
} |
| 914 |
|
| 915 |
fn or_expr(&mut self) -> Result<LicenseExpr, ExprParseError> { |
| 916 |
let mut terms = vec![self.and_expr()?]; |
| 917 |
while self.tokens.get(self.pos) == Some(&SpdxToken::Or) { |
| 918 |
self.pos += 1; |
| 919 |
terms.push(self.and_expr()?); |
| 920 |
} |
| 921 |
Ok(if terms.len() == 1 { |
| 922 |
terms.pop().unwrap() |
| 923 |
} else { |
| 924 |
LicenseExpr::Or(terms) |
| 925 |
}) |
| 926 |
} |
| 927 |
|
| 928 |
fn and_expr(&mut self) -> Result<LicenseExpr, ExprParseError> { |
| 929 |
let mut terms = vec![self.with_expr()?]; |
| 930 |
while self.tokens.get(self.pos) == Some(&SpdxToken::And) { |
| 931 |
self.pos += 1; |
| 932 |
terms.push(self.with_expr()?); |
| 933 |
} |
| 934 |
Ok(if terms.len() == 1 { |
| 935 |
terms.pop().unwrap() |
| 936 |
} else { |
| 937 |
LicenseExpr::And(terms) |
| 938 |
}) |
| 939 |
} |
| 940 |
|
| 941 |
fn with_expr(&mut self) -> Result<LicenseExpr, ExprParseError> { |
| 942 |
let atom = self.atom()?; |
| 943 |
if self.tokens.get(self.pos) != Some(&SpdxToken::With) { |
| 944 |
return Ok(atom); |
| 945 |
} |
| 946 |
self.pos += 1; |
| 947 |
// SPDX: WITH applies to a license id only, not a parenthesised group. |
| 948 |
let LicenseExpr::Name(name) = atom else { |
| 949 |
return self.err("WITH must follow a license id"); |
| 950 |
}; |
| 951 |
match self.tokens.get(self.pos) { |
| 952 |
Some(SpdxToken::Id(exception)) => { |
| 953 |
self.pos += 1; |
| 954 |
Ok(LicenseExpr::WithException(name, exception.to_string())) |
| 955 |
} |
| 956 |
_ => self.err("expected exception id after WITH"), |
| 957 |
} |
| 958 |
} |
| 959 |
|
| 960 |
fn atom(&mut self) -> Result<LicenseExpr, ExprParseError> { |
| 961 |
match self.tokens.get(self.pos) { |
| 962 |
Some(SpdxToken::Id(id)) => { |
| 963 |
self.pos += 1; |
| 964 |
Ok(LicenseExpr::Name(id.to_string())) |
| 965 |
} |
| 966 |
Some(SpdxToken::Open) => { |
| 967 |
self.pos += 1; |
| 968 |
let expr = self.or_expr()?; |
| 969 |
if self.tokens.get(self.pos) != Some(&SpdxToken::Close) { |
| 970 |
return self.err("expected ')'"); |
| 971 |
} |
| 972 |
self.pos += 1; |
| 973 |
Ok(expr) |
| 974 |
} |
| 975 |
Some(_) => self.err("expected license id"), |
| 976 |
None => self.err("unexpected end of expression"), |
| 977 |
} |
| 978 |
} |
| 979 |
} |
| 980 |
|
| 981 |
#[cfg(test)] |
| 982 |
mod tests { |
| 983 |
use super::*; |
| 984 |
|
| 985 |
#[test] |
| 986 |
fn test_single_name() { |
| 987 |
assert_eq!(LicenseExpr::parse("MIT"), LicenseExpr::Name("MIT".into())); |
| 988 |
} |
| 989 |
|
| 990 |
#[test] |
| 991 |
fn test_or() { |
| 992 |
assert_eq!( |
| 993 |
LicenseExpr::parse("GPL-2+ or MIT"), |
| 994 |
LicenseExpr::Or(vec![ |
| 995 |
LicenseExpr::Name("GPL-2+".into()), |
| 996 |
LicenseExpr::Name("MIT".into()), |
| 997 |
]) |
| 998 |
); |
| 999 |
} |
| 1000 |
|
| 1001 |
#[test] |
| 1002 |
fn test_and() { |
| 1003 |
assert_eq!( |
| 1004 |
LicenseExpr::parse("Apache-2.0 and BSD-3-clause"), |
| 1005 |
LicenseExpr::And(vec![ |
| 1006 |
LicenseExpr::Name("Apache-2.0".into()), |
| 1007 |
LicenseExpr::Name("BSD-3-clause".into()), |
| 1008 |
]) |
| 1009 |
); |
| 1010 |
} |
| 1011 |
|
| 1012 |
#[test] |
| 1013 |
fn test_with_exception() { |
| 1014 |
assert_eq!( |
| 1015 |
LicenseExpr::parse("GPL-2+ with OpenSSL-exception"), |
| 1016 |
LicenseExpr::WithException("GPL-2+".into(), "OpenSSL-exception".into()) |
| 1017 |
); |
| 1018 |
} |
| 1019 |
|
| 1020 |
#[test] |
| 1021 |
fn test_with_multi_word_exception() { |
| 1022 |
assert_eq!( |
| 1023 |
LicenseExpr::parse("GPL-2+ with Autoconf exception"), |
| 1024 |
LicenseExpr::WithException("GPL-2+".into(), "Autoconf exception".into()) |
| 1025 |
); |
| 1026 |
} |
| 1027 |
|
| 1028 |
#[test] |
| 1029 |
fn test_with_exception_then_or() { |
| 1030 |
assert_eq!( |
| 1031 |
LicenseExpr::parse("GPL-2+ with OpenSSL-exception or MIT"), |
| 1032 |
LicenseExpr::Or(vec![ |
| 1033 |
LicenseExpr::WithException("GPL-2+".into(), "OpenSSL-exception".into()), |
| 1034 |
LicenseExpr::Name("MIT".into()), |
| 1035 |
]) |
| 1036 |
); |
| 1037 |
} |
| 1038 |
|
| 1039 |
#[test] |
| 1040 |
fn test_and_binds_tighter_than_or() { |
| 1041 |
// A or B and C → A or (B and C) |
| 1042 |
assert_eq!( |
| 1043 |
LicenseExpr::parse("A or B and C"), |
| 1044 |
LicenseExpr::Or(vec![ |
| 1045 |
LicenseExpr::Name("A".into()), |
| 1046 |
LicenseExpr::And(vec![ |
| 1047 |
LicenseExpr::Name("B".into()), |
| 1048 |
LicenseExpr::Name("C".into()), |
| 1049 |
]), |
| 1050 |
]) |
| 1051 |
); |
| 1052 |
} |
| 1053 |
|
| 1054 |
#[test] |
| 1055 |
fn test_comma_lowers_precedence() { |
| 1056 |
// A or B, and C → (A or B) and C |
| 1057 |
assert_eq!( |
| 1058 |
LicenseExpr::parse("A or B, and C"), |
| 1059 |
LicenseExpr::And(vec![ |
| 1060 |
LicenseExpr::Or(vec![ |
| 1061 |
LicenseExpr::Name("A".into()), |
| 1062 |
LicenseExpr::Name("B".into()), |
| 1063 |
]), |
| 1064 |
LicenseExpr::Name("C".into()), |
| 1065 |
]) |
| 1066 |
); |
| 1067 |
} |
| 1068 |
|
| 1069 |
#[test] |
| 1070 |
fn test_case_insensitive_operators() { |
| 1071 |
assert_eq!( |
| 1072 |
LicenseExpr::parse("GPL-2+ OR MIT"), |
| 1073 |
LicenseExpr::Or(vec![ |
| 1074 |
LicenseExpr::Name("GPL-2+".into()), |
| 1075 |
LicenseExpr::Name("MIT".into()), |
| 1076 |
]) |
| 1077 |
); |
| 1078 |
} |
| 1079 |
|
| 1080 |
#[test] |
| 1081 |
fn test_license_names() { |
| 1082 |
let expr = LicenseExpr::parse("GPL-2+ or MIT and BSD-3-clause"); |
| 1083 |
assert_eq!(expr.license_names(), vec!["GPL-2+", "MIT", "BSD-3-clause"]); |
| 1084 |
} |
| 1085 |
|
| 1086 |
#[test] |
| 1087 |
fn test_license_names_with_exception() { |
| 1088 |
let expr = LicenseExpr::parse("GPL-2+ with OpenSSL-exception or MIT"); |
| 1089 |
assert_eq!(expr.license_names(), vec!["GPL-2+", "MIT"]); |
| 1090 |
} |
| 1091 |
|
| 1092 |
#[test] |
| 1093 |
fn test_display_round_trip_simple() { |
| 1094 |
let input = "GPL-2+ or MIT"; |
| 1095 |
let expr = LicenseExpr::parse(input); |
| 1096 |
assert_eq!(expr.to_string(), input); |
| 1097 |
} |
| 1098 |
|
| 1099 |
#[test] |
| 1100 |
fn test_display_with_exception() { |
| 1101 |
let input = "GPL-2+ with OpenSSL-exception"; |
| 1102 |
let expr = LicenseExpr::parse(input); |
| 1103 |
assert_eq!(expr.to_string(), input); |
| 1104 |
} |
| 1105 |
|
| 1106 |
#[test] |
| 1107 |
fn test_name_ranges_simple() { |
| 1108 |
let input = "MIT"; |
| 1109 |
assert_eq!(LicenseExpr::name_ranges(input), vec![("MIT", 0..3)]); |
| 1110 |
} |
| 1111 |
|
| 1112 |
#[test] |
| 1113 |
fn test_name_ranges_or() { |
| 1114 |
let input = "GPL-2+ or MIT"; |
| 1115 |
assert_eq!( |
| 1116 |
LicenseExpr::name_ranges(input), |
| 1117 |
vec![("GPL-2+", 0..6), ("MIT", 10..13)], |
| 1118 |
); |
| 1119 |
} |
| 1120 |
|
| 1121 |
#[test] |
| 1122 |
fn test_name_ranges_and() { |
| 1123 |
let input = "Apache-2.0 and BSD-3-clause"; |
| 1124 |
assert_eq!( |
| 1125 |
LicenseExpr::name_ranges(input), |
| 1126 |
vec![("Apache-2.0", 0..10), ("BSD-3-clause", 15..27)], |
| 1127 |
); |
| 1128 |
} |
| 1129 |
|
| 1130 |
#[test] |
| 1131 |
fn test_name_ranges_with_exception() { |
| 1132 |
let input = "GPL-2+ with OpenSSL-exception or MIT"; |
| 1133 |
assert_eq!( |
| 1134 |
LicenseExpr::name_ranges(input), |
| 1135 |
vec![("GPL-2+", 0..6), ("MIT", 33..36)], |
| 1136 |
); |
| 1137 |
} |
| 1138 |
|
| 1139 |
#[test] |
| 1140 |
fn test_name_ranges_multi_word_exception() { |
| 1141 |
let input = "GPL-2+ with Autoconf exception or MIT"; |
| 1142 |
assert_eq!( |
| 1143 |
LicenseExpr::name_ranges(input), |
| 1144 |
vec![("GPL-2+", 0..6), ("MIT", 34..37)], |
| 1145 |
); |
| 1146 |
} |
| 1147 |
|
| 1148 |
#[test] |
| 1149 |
fn test_name_ranges_comma_lowered() { |
| 1150 |
let input = "A or B, and C"; |
| 1151 |
assert_eq!( |
| 1152 |
LicenseExpr::name_ranges(input), |
| 1153 |
vec![("A", 0..1), ("B", 5..6), ("C", 12..13)], |
| 1154 |
); |
| 1155 |
} |
| 1156 |
|
| 1157 |
#[test] |
| 1158 |
fn test_name_ranges_empty() { |
| 1159 |
assert_eq!(LicenseExpr::name_ranges(""), Vec::<(&str, _)>::new()); |
| 1160 |
assert_eq!(LicenseExpr::name_ranges(" "), Vec::<(&str, _)>::new()); |
| 1161 |
} |
| 1162 |
|
| 1163 |
#[test] |
| 1164 |
fn test_name_ranges_matches_license_names() { |
| 1165 |
let cases = [ |
| 1166 |
"GPL-2+ or MIT", |
| 1167 |
"Apache-2.0 and BSD-3-clause", |
| 1168 |
"GPL-2+ with OpenSSL-exception or MIT", |
| 1169 |
"A or B, and C", |
| 1170 |
"GPL-1+ or Artistic or Perl", |
| 1171 |
]; |
| 1172 |
for input in cases { |
| 1173 |
let from_expr: Vec<String> = LicenseExpr::parse(input) |
| 1174 |
.license_names() |
| 1175 |
.into_iter() |
| 1176 |
.map(str::to_owned) |
| 1177 |
.collect(); |
| 1178 |
let from_ranges: Vec<String> = LicenseExpr::name_ranges(input) |
| 1179 |
.into_iter() |
| 1180 |
.map(|(n, _)| n.to_owned()) |
| 1181 |
.collect(); |
| 1182 |
assert_eq!(from_ranges, from_expr, "mismatch for input {input:?}"); |
| 1183 |
} |
| 1184 |
} |
| 1185 |
|
| 1186 |
#[test] |
| 1187 |
fn test_multi_word_name() { |
| 1188 |
assert_eq!( |
| 1189 |
LicenseExpr::parse("Apache 2.0"), |
| 1190 |
LicenseExpr::Name("Apache 2.0".into()) |
| 1191 |
); |
| 1192 |
} |
| 1193 |
|
| 1194 |
#[test] |
| 1195 |
fn test_multi_word_name_in_or() { |
| 1196 |
assert_eq!( |
| 1197 |
LicenseExpr::parse("Creative Commons Attribution 3.0 or MIT"), |
| 1198 |
LicenseExpr::Or(vec![ |
| 1199 |
LicenseExpr::Name("Creative Commons Attribution 3.0".into()), |
| 1200 |
LicenseExpr::Name("MIT".into()), |
| 1201 |
]) |
| 1202 |
); |
| 1203 |
} |
| 1204 |
|
| 1205 |
#[test] |
| 1206 |
fn test_multi_word_name_with_exception() { |
| 1207 |
assert_eq!( |
| 1208 |
LicenseExpr::parse("Apache 2.0 with LLVM exception"), |
| 1209 |
LicenseExpr::WithException("Apache 2.0".into(), "LLVM exception".into()) |
| 1210 |
); |
| 1211 |
} |
| 1212 |
|
| 1213 |
#[test] |
| 1214 |
fn test_name_ranges_multi_word_name() { |
| 1215 |
let input = "Apache 2.0 or MIT"; |
| 1216 |
assert_eq!( |
| 1217 |
LicenseExpr::name_ranges(input), |
| 1218 |
vec![("Apache 2.0", 0..10), ("MIT", 14..17)], |
| 1219 |
); |
| 1220 |
} |
| 1221 |
|
| 1222 |
#[test] |
| 1223 |
fn test_non_ascii_name() { |
| 1224 |
assert_eq!( |
| 1225 |
LicenseExpr::parse("Ràndom"), |
| 1226 |
LicenseExpr::Name("Ràndom".into()) |
| 1227 |
); |
| 1228 |
} |
| 1229 |
|
| 1230 |
#[test] |
| 1231 |
fn test_display_comma_lowered_round_trip() { |
| 1232 |
let input = "A or B, and C"; |
| 1233 |
let expr = LicenseExpr::parse(input); |
| 1234 |
assert_eq!(expr.to_string(), input); |
| 1235 |
assert_eq!(LicenseExpr::parse(&expr.to_string()), expr); |
| 1236 |
} |
| 1237 |
|
| 1238 |
#[test] |
| 1239 |
fn test_display_comma_lowered_or_round_trip() { |
| 1240 |
let input = "A, and B or C, or D"; |
| 1241 |
let expr = LicenseExpr::parse(input); |
| 1242 |
assert_eq!(expr.to_string(), input); |
| 1243 |
assert_eq!(LicenseExpr::parse(&expr.to_string()), expr); |
| 1244 |
} |
| 1245 |
|
| 1246 |
#[test] |
| 1247 |
fn test_stray_comma_preserved_in_name() { |
| 1248 |
assert_eq!( |
| 1249 |
LicenseExpr::parse("A, B, and C"), |
| 1250 |
LicenseExpr::And(vec![ |
| 1251 |
LicenseExpr::Name("A, B".into()), |
| 1252 |
LicenseExpr::Name("C".into()), |
| 1253 |
]) |
| 1254 |
); |
| 1255 |
} |
| 1256 |
|
| 1257 |
#[test] |
| 1258 |
fn test_lone_comma() { |
| 1259 |
assert_eq!(LicenseExpr::parse(","), LicenseExpr::Name(String::new())); |
| 1260 |
} |
| 1261 |
|
| 1262 |
#[test] |
| 1263 |
fn test_parse_strict_valid() { |
| 1264 |
for input in [ |
| 1265 |
"MIT", |
| 1266 |
"GPL-2+ or MIT", |
| 1267 |
"Apache-2.0 and BSD-3-clause", |
| 1268 |
"GPL-2+ with OpenSSL-exception", |
| 1269 |
"GPL-2+ with Autoconf exception", |
| 1270 |
"A or B, and C", |
| 1271 |
"A, and B or C, or D", |
| 1272 |
"GPL-1+ or Artistic or Perl", |
| 1273 |
] { |
| 1274 |
let strict = LicenseExpr::parse_strict(input) |
| 1275 |
.unwrap_or_else(|e| panic!("strict parse failed for {input:?}: {e}")); |
| 1276 |
assert_eq!( |
| 1277 |
strict, |
| 1278 |
LicenseExpr::parse(input), |
| 1279 |
"tree mismatch for {input:?}" |
| 1280 |
); |
| 1281 |
} |
| 1282 |
} |
| 1283 |
|
| 1284 |
#[test] |
| 1285 |
fn test_parse_strict_rejects_malformed() { |
| 1286 |
for input in [ |
| 1287 |
"", |
| 1288 |
" ", |
| 1289 |
"Apache 2.0", |
| 1290 |
"MIT or", |
| 1291 |
"or MIT", |
| 1292 |
"MIT or or GPL-2", |
| 1293 |
"MIT with", |
| 1294 |
"MIT, GPL-2", |
| 1295 |
"A, B, and C", |
| 1296 |
",", |
| 1297 |
] { |
| 1298 |
assert!( |
| 1299 |
LicenseExpr::parse_strict(input).is_err(), |
| 1300 |
"strict parse accepted {input:?}" |
| 1301 |
); |
| 1302 |
} |
| 1303 |
} |
| 1304 |
|
| 1305 |
#[test] |
| 1306 |
fn test_parse_spdx_simple() { |
| 1307 |
assert_eq!( |
| 1308 |
LicenseExpr::parse_spdx("MIT OR Apache-2.0").unwrap(), |
| 1309 |
LicenseExpr::Or(vec![ |
| 1310 |
LicenseExpr::Name("MIT".into()), |
| 1311 |
LicenseExpr::Name("Apache-2.0".into()), |
| 1312 |
]) |
| 1313 |
); |
| 1314 |
} |
| 1315 |
|
| 1316 |
#[test] |
| 1317 |
fn test_parse_spdx_case_insensitive_operators() { |
| 1318 |
assert_eq!( |
| 1319 |
LicenseExpr::parse_spdx("MIT or Apache-2.0").unwrap(), |
| 1320 |
LicenseExpr::parse_spdx("MIT OR Apache-2.0").unwrap(), |
| 1321 |
); |
| 1322 |
} |
| 1323 |
|
| 1324 |
#[test] |
| 1325 |
fn test_parse_spdx_with() { |
| 1326 |
assert_eq!( |
| 1327 |
LicenseExpr::parse_spdx("GPL-2.0-only WITH Classpath-exception-2.0").unwrap(), |
| 1328 |
LicenseExpr::WithException("GPL-2.0-only".into(), "Classpath-exception-2.0".into()) |
| 1329 |
); |
| 1330 |
} |
| 1331 |
|
| 1332 |
#[test] |
| 1333 |
fn test_parse_spdx_parens_and_precedence() { |
| 1334 |
// Parens override the AND-binds-tighter default. |
| 1335 |
assert_eq!( |
| 1336 |
LicenseExpr::parse_spdx("MIT AND (ISC OR GPL-2.0-only)").unwrap(), |
| 1337 |
LicenseExpr::And(vec![ |
| 1338 |
LicenseExpr::Name("MIT".into()), |
| 1339 |
LicenseExpr::Or(vec![ |
| 1340 |
LicenseExpr::Name("ISC".into()), |
| 1341 |
LicenseExpr::Name("GPL-2.0-only".into()), |
| 1342 |
]), |
| 1343 |
]) |
| 1344 |
); |
| 1345 |
assert_eq!( |
| 1346 |
LicenseExpr::parse_spdx("MIT AND ISC OR GPL-2.0-only").unwrap(), |
| 1347 |
LicenseExpr::Or(vec![ |
| 1348 |
LicenseExpr::And(vec![ |
| 1349 |
LicenseExpr::Name("MIT".into()), |
| 1350 |
LicenseExpr::Name("ISC".into()), |
| 1351 |
]), |
| 1352 |
LicenseExpr::Name("GPL-2.0-only".into()), |
| 1353 |
]) |
| 1354 |
); |
| 1355 |
} |
| 1356 |
|
| 1357 |
#[test] |
| 1358 |
fn test_parse_spdx_rejects_malformed() { |
| 1359 |
for input in [ |
| 1360 |
"", |
| 1361 |
"MIT OR", |
| 1362 |
"(MIT", |
| 1363 |
"MIT)", |
| 1364 |
"MIT WITH", |
| 1365 |
"(MIT AND ISC) WITH X", |
| 1366 |
] { |
| 1367 |
assert!( |
| 1368 |
LicenseExpr::parse_spdx(input).is_err(), |
| 1369 |
"SPDX parse accepted {input:?}" |
| 1370 |
); |
| 1371 |
} |
| 1372 |
} |
| 1373 |
|
| 1374 |
#[test] |
| 1375 |
fn test_to_spdx_string_round_trip() { |
| 1376 |
for input in [ |
| 1377 |
"MIT", |
| 1378 |
"MIT OR Apache-2.0", |
| 1379 |
"(MIT AND ISC) OR GPL-2.0-only", |
| 1380 |
"GPL-2.0-only WITH Classpath-exception-2.0", |
| 1381 |
"MIT AND (ISC OR GPL-2.0-only)", |
| 1382 |
] { |
| 1383 |
let expr = LicenseExpr::parse_spdx(input).unwrap(); |
| 1384 |
assert_eq!( |
| 1385 |
LicenseExpr::parse_spdx(&expr.to_spdx_string()).unwrap(), |
| 1386 |
expr, |
| 1387 |
"round trip failed for {input:?}" |
| 1388 |
); |
| 1389 |
} |
| 1390 |
} |
| 1391 |
|
| 1392 |
#[allow(deprecated)] |
| 1393 |
#[test] |
| 1394 |
fn test_map_names() { |
| 1395 |
let expr = |
| 1396 |
LicenseExpr::parse_spdx("MIT OR GPL-2.0-only WITH Classpath-exception-2.0").unwrap(); |
| 1397 |
let mapped = expr.map_names( |
| 1398 |
&|name| match name { |
| 1399 |
"MIT" => "Expat".to_string(), |
| 1400 |
"GPL-2.0-only" => "GPL-2".to_string(), |
| 1401 |
other => other.to_string(), |
| 1402 |
}, |
| 1403 |
&|exception| match exception { |
| 1404 |
"Classpath-exception-2.0" => "ClassPath exception".to_string(), |
| 1405 |
other => other.to_string(), |
| 1406 |
}, |
| 1407 |
); |
| 1408 |
assert_eq!( |
| 1409 |
mapped.to_string(), |
| 1410 |
"Expat or GPL-2 with ClassPath exception" |
| 1411 |
); |
| 1412 |
} |
| 1413 |
|
| 1414 |
#[test] |
| 1415 |
fn test_map_leaves() { |
| 1416 |
let expr = |
| 1417 |
LicenseExpr::parse_spdx("MIT OR GPL-2.0-only WITH Classpath-exception-2.0").unwrap(); |
| 1418 |
let mapped = expr.map_leaves(|leaf| match leaf { |
| 1419 |
LicenseExpr::Name(name) if name == "MIT" => LicenseExpr::Name("Expat".to_string()), |
| 1420 |
LicenseExpr::WithException(name, exception) |
| 1421 |
if name == "GPL-2.0-only" && exception == "Classpath-exception-2.0" => |
| 1422 |
{ |
| 1423 |
LicenseExpr::WithException("GPL-2".to_string(), "ClassPath exception".to_string()) |
| 1424 |
} |
| 1425 |
other => other.clone(), |
| 1426 |
}); |
| 1427 |
assert_eq!( |
| 1428 |
mapped.to_string(), |
| 1429 |
"Expat or GPL-2 with ClassPath exception" |
| 1430 |
); |
| 1431 |
} |
| 1432 |
|
| 1433 |
#[test] |
| 1434 |
fn test_map_leaves_preserves_structure() { |
| 1435 |
let expr = LicenseExpr::parse("A or B, and C"); |
| 1436 |
let mapped = expr.map_leaves(|leaf| leaf.clone()); |
| 1437 |
assert_eq!(mapped, expr); |
| 1438 |
} |
| 1439 |
|
| 1440 |
#[test] |
| 1441 |
fn test_map_leaves_sees_license_and_exception_together() { |
| 1442 |
// A leaf whose license and exception together map to one DEP-5 name; |
| 1443 |
// the deprecated map_names could not express this. |
| 1444 |
let expr = LicenseExpr::parse_spdx("GPL-2.0-only WITH Font-exception-2.0").unwrap(); |
| 1445 |
let mapped = expr.map_leaves(|leaf| match leaf { |
| 1446 |
LicenseExpr::WithException(name, exception) |
| 1447 |
if name == "GPL-2.0-only" && exception == "Font-exception-2.0" => |
| 1448 |
{ |
| 1449 |
LicenseExpr::Name("GPL-2-with-font-exception".to_string()) |
| 1450 |
} |
| 1451 |
other => other.clone(), |
| 1452 |
}); |
| 1453 |
assert_eq!( |
| 1454 |
mapped, |
| 1455 |
LicenseExpr::Name("GPL-2-with-font-exception".into()) |
| 1456 |
); |
| 1457 |
} |
| 1458 |
|
| 1459 |
#[test] |
| 1460 |
fn test_from_str() { |
| 1461 |
let expr: LicenseExpr = "GPL-2+ or MIT".parse().unwrap(); |
| 1462 |
assert_eq!(expr, LicenseExpr::parse_strict("GPL-2+ or MIT").unwrap()); |
| 1463 |
assert!("Apache 2.0".parse::<LicenseExpr>().is_err()); |
| 1464 |
} |
| 1465 |
|
| 1466 |
#[test] |
| 1467 |
fn test_expr_parse_error_accessors() { |
| 1468 |
let err = LicenseExpr::parse_strict("MIT or").unwrap_err(); |
| 1469 |
assert_eq!(err.input(), "MIT or"); |
| 1470 |
assert_eq!(err.message(), "unexpected end of expression"); |
| 1471 |
assert_eq!( |
| 1472 |
err.to_string(), |
| 1473 |
r#"unexpected end of expression in license expression "MIT or""# |
| 1474 |
); |
| 1475 |
} |
| 1476 |
|
| 1477 |
#[test] |
| 1478 |
fn test_leaves() { |
| 1479 |
let expr = LicenseExpr::parse("A and B with C exception or D"); |
| 1480 |
let leaves: Vec<String> = expr.leaves().iter().map(|l| l.to_string()).collect(); |
| 1481 |
assert_eq!(leaves, vec!["A", "B with C exception", "D"]); |
| 1482 |
} |
| 1483 |
|
| 1484 |
#[test] |
| 1485 |
fn test_three_way_or() { |
| 1486 |
assert_eq!( |
| 1487 |
LicenseExpr::parse("GPL-1+ or Artistic or Perl"), |
| 1488 |
LicenseExpr::Or(vec![ |
| 1489 |
LicenseExpr::Name("GPL-1+".into()), |
| 1490 |
LicenseExpr::Name("Artistic".into()), |
| 1491 |
LicenseExpr::Name("Perl".into()), |
| 1492 |
]) |
| 1493 |
); |
| 1494 |
} |
| 1495 |
} |