comply 0.1.1

REUSE Specification compliance tool and library: lint, annotate, and fix SPDX license headers
Documentation
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
// SPDX-FileCopyrightText: COMPLY contributors
//
// SPDX-License-Identifier: MIT OR Apache-2.0

use core::fmt;
use std::collections::BTreeSet;

use crate::error::Error;

// Generated by scripts/generate-spdx.py from the SPDX License List.
#[path = "spdx_list.rs"]
mod spdx_list;

pub(crate) use spdx_list::{DEPRECATED_LICENSES, KNOWN_EXCEPTIONS, KNOWN_LICENSES};

/// A parsed SPDX license expression.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Expression {
    /// A single license identifier, e.g. `MIT`
    Simple { id: LicenseId },
    /// A license WITH exception, e.g. `Apache-2.0 WITH LLVM-exception`
    With {
        license: Box<Self>,
        exception: LicenseId,
    },
    /// Conjunction, e.g. `MIT AND Apache-2.0`
    And { left: Box<Self>, right: Box<Self> },
    /// Disjunction, e.g. `MIT OR Apache-2.0`
    Or { left: Box<Self>, right: Box<Self> },
}

/// An SPDX license or exception identifier.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LicenseId {
    /// The raw identifier string, e.g. `MIT`, `Apache-2.0`, `LicenseRef-custom`
    pub id: String,
}

impl Expression {
    /// Every license and exception identifier this expression references.
    ///
    /// A `WITH` exception is returned in its own right: REUSE requires a
    /// License File for the exception as well as for the license it modifies.
    #[must_use]
    pub fn identifiers(&self) -> BTreeSet<String> {
        let mut out = BTreeSet::new();
        self.collect_identifiers(&mut out);
        out
    }

    fn collect_identifiers(&self, out: &mut BTreeSet<String>) {
        match self {
            Self::Simple { id } => {
                out.insert(id.id.clone());
            }
            Self::With { license, exception } => {
                license.collect_identifiers(out);
                out.insert(exception.id.clone());
            }
            Self::And { left, right } | Self::Or { left, right } => {
                left.collect_identifiers(out);
                right.collect_identifiers(out);
            }
        }
    }
}

impl fmt::Display for Expression {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Simple { id } => write!(f, "{}", id.id),
            Self::With { license, exception } => {
                write!(f, "{license} WITH {}", exception.id)
            }
            Self::And { left, right } => write!(f, "{left} AND {right}"),
            Self::Or { left, right } => write!(f, "{left} OR {right}"),
        }
    }
}

/// Characters that delimit tokens in an SPDX expression.
const WHITESPACE: &[char] = &[' ', '\t', '\n', '\r'];
const SPECIAL: &[char] = &['(', ')'];

/// Parse an SPDX license expression string.
///
/// Supports:
/// - Simple identifiers: `MIT`, `Apache-2.0`
/// - Disjunctive: `MIT OR Apache-2.0`
/// - Conjunctive: `MIT AND Apache-2.0`
/// - With exceptions: `Apache-2.0 WITH LLVM-exception`
/// - Parenthesized groups: `(MIT OR Apache-2.0)`
/// - `LicenseRef-*` identifiers
#[allow(clippy::missing_errors_doc)]
pub fn parse(input: &str) -> Result<Expression, Error> {
    let tokens = tokenize(input);
    let mut pos = 0;
    let expr = parse_or(&tokens, &mut pos)?;
    if pos < tokens.len() {
        return Err(Error::Spdx(format!(
            "unexpected token '{}' after expression",
            tokens[pos]
        )));
    }
    Ok(expr)
}

/// Validate that a string is a valid SPDX license expression.
#[allow(clippy::missing_errors_doc)]
pub fn validate(input: &str) -> Result<(), Error> {
    parse(input)?;
    Ok(())
}

/// Check whether a license identifier is a known SPDX license.
#[must_use]
pub fn is_known_license(id: &str) -> bool {
    KNOWN_LICENSES.contains(&id)
}

/// Check whether a license identifier is a known SPDX exception.
#[must_use]
pub fn is_known_exception(id: &str) -> bool {
    KNOWN_EXCEPTIONS.contains(&id)
}

/// Every license identifier in the bundled SPDX License List, sorted.
#[must_use]
pub const fn known_licenses() -> &'static [&'static str] {
    KNOWN_LICENSES
}

/// Every license exception identifier in the bundled SPDX License List, sorted.
#[must_use]
pub const fn known_exceptions() -> &'static [&'static str] {
    KNOWN_EXCEPTIONS
}

/// The identifiers the SPDX License List has deprecated.
///
/// Still valid to parse -- `lint` reports them rather than rejecting them.
#[must_use]
pub const fn deprecated_licenses() -> &'static [&'static str] {
    DEPRECATED_LICENSES
}

/// Tokenize an SPDX expression string into tokens.
fn tokenize(input: &str) -> Vec<String> {
    let mut tokens = Vec::new();
    let mut chars = input.chars().peekable();

    while let Some(&ch) = chars.peek() {
        if ch == '(' || ch == ')' {
            tokens.push(ch.to_string());
            chars.next();
        } else if WHITESPACE.contains(&ch) {
            chars.next();
        } else {
            let mut token = String::new();
            while let Some(&ch) = chars.peek() {
                if SPECIAL.contains(&ch) || WHITESPACE.contains(&ch) {
                    break;
                }
                token.push(ch);
                chars.next();
            }
            if !token.is_empty() {
                tokens.push(token);
            }
        }
    }

    tokens
}

/// Parse an OR expression (lowest precedence).
fn parse_or(tokens: &[String], pos: &mut usize) -> Result<Expression, Error> {
    let mut left = parse_and(tokens, pos)?;

    while *pos < tokens.len() && tokens[*pos].eq_ignore_ascii_case("OR") {
        *pos += 1;
        let right = parse_and(tokens, pos)?;
        left = Expression::Or {
            left: Box::new(left),
            right: Box::new(right),
        };
    }

    Ok(left)
}

/// Parse an AND expression.
fn parse_and(tokens: &[String], pos: &mut usize) -> Result<Expression, Error> {
    let mut left = parse_with(tokens, pos)?;

    while *pos < tokens.len() && tokens[*pos].eq_ignore_ascii_case("AND") {
        *pos += 1;
        let right = parse_with(tokens, pos)?;
        left = Expression::And {
            left: Box::new(left),
            right: Box::new(right),
        };
    }

    Ok(left)
}

/// Parse a WITH expression.
fn parse_with(tokens: &[String], pos: &mut usize) -> Result<Expression, Error> {
    let mut expr = parse_primary(tokens, pos)?;

    if *pos < tokens.len() && tokens[*pos].eq_ignore_ascii_case("WITH") {
        *pos += 1;
        let exception = parse_identifier(tokens, pos)?;
        expr = Expression::With {
            license: Box::new(expr),
            exception: LicenseId { id: exception },
        };
    }

    Ok(expr)
}

/// Parse a primary expression (simple id or parenthesized).
fn parse_primary(tokens: &[String], pos: &mut usize) -> Result<Expression, Error> {
    if *pos >= tokens.len() {
        return Err(Error::Spdx("unexpected end of expression".into()));
    }

    if tokens[*pos] == "(" {
        *pos += 1;
        let expr = parse_or(tokens, pos)?;
        if *pos >= tokens.len() || tokens[*pos] != ")" {
            return Err(Error::Spdx("missing closing parenthesis".into()));
        }
        *pos += 1;
        return Ok(expr);
    }

    let id = parse_identifier(tokens, pos)?;
    Ok(Expression::Simple {
        id: LicenseId { id },
    })
}

/// Parse a single identifier token.
fn parse_identifier(tokens: &[String], pos: &mut usize) -> Result<String, Error> {
    if *pos >= tokens.len() {
        return Err(Error::Spdx(
            "expected identifier, found end of expression".into(),
        ));
    }

    let token = &tokens[*pos];
    if SPECIAL.contains(&token.chars().next().unwrap_or('\0')) {
        return Err(Error::Spdx(format!("expected identifier, found '{token}'")));
    }

    // Uppercase operator tokens are not identifiers.
    let upper = token.to_uppercase();
    if upper == "AND" || upper == "OR" || upper == "WITH" {
        return Err(Error::Spdx(format!("expected identifier, found '{token}'")));
    }

    *pos += 1;
    Ok(token.clone())
}

// ---------------------------------------------------------------------------
// Known SPDX license list (subset of SPDX License List 3.28+)
// Sorted alphabetically for binary search.
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    // -- bundled list enumeration -------------------------------------------

    #[test]
    fn the_bundled_lists_are_exposed_sorted_and_agree_with_the_predicates() {
        let licenses = known_licenses();
        let exceptions = known_exceptions();
        let deprecated = deprecated_licenses();

        assert!(licenses.len() > 700, "got {}", licenses.len());
        assert!(exceptions.len() > 30, "got {}", exceptions.len());
        assert!(!deprecated.is_empty());

        // Sorted, so `supported-licenses` output is stable without re-sorting.
        assert!(licenses.windows(2).all(|w| w[0] <= w[1]));
        assert!(exceptions.windows(2).all(|w| w[0] <= w[1]));

        // The enumeration and the membership predicates read the same data.
        assert!(is_known_license(licenses[0]));
        assert!(is_known_exception(exceptions[0]));
        assert!(licenses.contains(&"MIT"));
        assert!(deprecated.contains(&"GPL-3.0"));
    }

    // -- parse() tests ------------------------------------------------------

    #[test]
    fn identifiers_collects_every_licence_an_expression_references() {
        let ids = |e: &str| {
            parse(e)
                .unwrap()
                .identifiers()
                .into_iter()
                .collect::<Vec<_>>()
        };

        assert_eq!(ids("MIT"), ["MIT"]);
        assert_eq!(ids("MIT OR Apache-2.0"), ["Apache-2.0", "MIT"]);
        assert_eq!(ids("MIT AND Apache-2.0"), ["Apache-2.0", "MIT"]);
        assert_eq!(
            ids("(MIT OR Apache-2.0) AND ISC"),
            ["Apache-2.0", "ISC", "MIT"]
        );
        assert_eq!(
            ids("MIT OR MIT"),
            ["MIT"],
            "a licence named twice is still one licence"
        );
    }

    #[test]
    fn identifiers_includes_the_exception_of_a_with_expression() {
        // The reference tool requires a license file for the exception too,
        // so it has to come back as a referenced identifier in its own right.
        let ids = parse("GPL-3.0-only WITH Autoconf-exception-3.0")
            .unwrap()
            .identifiers()
            .into_iter()
            .collect::<Vec<_>>();

        assert_eq!(ids, ["Autoconf-exception-3.0", "GPL-3.0-only"]);
    }

    #[test]
    fn display_round_trips_every_expression_shape() {
        for expr in ["MIT", "MIT OR Apache-2.0", "MIT AND Apache-2.0"] {
            assert_eq!(parse(expr).unwrap().to_string(), expr);
        }
        assert_eq!(
            parse("GPL-3.0-only WITH Autoconf-exception-3.0")
                .unwrap()
                .to_string(),
            "GPL-3.0-only WITH Autoconf-exception-3.0"
        );
    }

    #[test]
    fn an_expression_ending_in_an_operator_is_rejected() {
        let err = parse("MIT AND").unwrap_err().to_string();

        assert!(
            err.contains("end of expression"),
            "a dangling operator should say what was expected, got: {err}"
        );
    }

    #[test]
    fn a_trailing_with_has_no_exception_to_attach() {
        let err = parse("GPL-3.0-only WITH").unwrap_err().to_string();

        assert!(
            err.contains("expected identifier, found end of expression"),
            "got: {err}"
        );
    }

    #[test]
    fn a_parenthesis_where_an_identifier_belongs_is_rejected() {
        let err = parse("MIT AND )").unwrap_err().to_string();

        assert!(err.contains("expected identifier"), "got: {err}");
    }

    #[test]
    fn parse_simple_mit() {
        let expr = parse("MIT").unwrap();
        assert_eq!(
            expr,
            Expression::Simple {
                id: LicenseId { id: "MIT".into() }
            }
        );
    }

    #[test]
    fn parse_simple_apache() {
        let expr = parse("Apache-2.0").unwrap();
        assert_eq!(
            expr,
            Expression::Simple {
                id: LicenseId {
                    id: "Apache-2.0".into()
                }
            }
        );
    }

    #[test]
    fn parse_simple_license_ref() {
        let expr = parse("LicenseRef-custom").unwrap();
        assert_eq!(
            expr,
            Expression::Simple {
                id: LicenseId {
                    id: "LicenseRef-custom".into()
                }
            }
        );
    }

    #[test]
    fn parse_or_expression() {
        let expr = parse("MIT OR Apache-2.0").unwrap();
        assert_eq!(
            expr,
            Expression::Or {
                left: Box::new(Expression::Simple {
                    id: LicenseId { id: "MIT".into() }
                }),
                right: Box::new(Expression::Simple {
                    id: LicenseId {
                        id: "Apache-2.0".into()
                    }
                }),
            }
        );
    }

    #[test]
    fn parse_and_expression() {
        let expr = parse("MIT AND Apache-2.0").unwrap();
        assert_eq!(
            expr,
            Expression::And {
                left: Box::new(Expression::Simple {
                    id: LicenseId { id: "MIT".into() }
                }),
                right: Box::new(Expression::Simple {
                    id: LicenseId {
                        id: "Apache-2.0".into()
                    }
                }),
            }
        );
    }

    #[test]
    fn parse_with_expression() {
        let expr = parse("Apache-2.0 WITH LLVM-exception").unwrap();
        assert_eq!(
            expr,
            Expression::With {
                license: Box::new(Expression::Simple {
                    id: LicenseId {
                        id: "Apache-2.0".into()
                    }
                }),
                exception: LicenseId {
                    id: "LLVM-exception".into()
                },
            }
        );
    }

    #[test]
    fn parse_parenthesized_expression() {
        let expr = parse("(MIT OR Apache-2.0) AND BSD-3-Clause").unwrap();
        assert_eq!(
            expr,
            Expression::And {
                left: Box::new(Expression::Or {
                    left: Box::new(Expression::Simple {
                        id: LicenseId { id: "MIT".into() }
                    }),
                    right: Box::new(Expression::Simple {
                        id: LicenseId {
                            id: "Apache-2.0".into()
                        }
                    }),
                }),
                right: Box::new(Expression::Simple {
                    id: LicenseId {
                        id: "BSD-3-Clause".into()
                    }
                }),
            }
        );
    }

    #[test]
    fn parse_chained_or() {
        let expr = parse("MIT OR Apache-2.0 OR BSD-3-Clause").unwrap();
        assert_eq!(
            expr,
            Expression::Or {
                left: Box::new(Expression::Or {
                    left: Box::new(Expression::Simple {
                        id: LicenseId { id: "MIT".into() }
                    }),
                    right: Box::new(Expression::Simple {
                        id: LicenseId {
                            id: "Apache-2.0".into()
                        }
                    }),
                }),
                right: Box::new(Expression::Simple {
                    id: LicenseId {
                        id: "BSD-3-Clause".into()
                    }
                }),
            }
        );
    }

    #[test]
    fn parse_or_has_lower_precedence_than_and() {
        // `MIT OR Apache-2.0 AND BSD-3-Clause` parses as `MIT OR (Apache-2.0 AND BSD-3-Clause)`
        let expr = parse("MIT OR Apache-2.0 AND BSD-3-Clause").unwrap();
        assert_eq!(
            expr,
            Expression::Or {
                left: Box::new(Expression::Simple {
                    id: LicenseId { id: "MIT".into() }
                }),
                right: Box::new(Expression::And {
                    left: Box::new(Expression::Simple {
                        id: LicenseId {
                            id: "Apache-2.0".into()
                        }
                    }),
                    right: Box::new(Expression::Simple {
                        id: LicenseId {
                            id: "BSD-3-Clause".into()
                        }
                    }),
                }),
            }
        );
    }

    // -- validate() tests ---------------------------------------------------

    #[test]
    fn validate_valid_expression() {
        assert!(validate("MIT").is_ok());
        assert!(validate("MIT OR Apache-2.0").is_ok());
        assert!(validate("(MIT OR Apache-2.0) AND BSD-3-Clause").is_ok());
    }

    #[test]
    fn validate_empty_string_fails() {
        assert!(validate("").is_err());
    }

    #[test]
    fn validate_operator_only_fails() {
        assert!(validate("OR").is_err());
        assert!(validate("AND").is_err());
    }

    #[test]
    fn validate_unclosed_paren_fails() {
        assert!(validate("(MIT OR Apache-2.0").is_err());
    }

    #[test]
    fn validate_extra_tokens_fails() {
        assert!(validate("MIT OR").is_err());
    }

    #[test]
    fn validate_trailing_paren_fails() {
        assert!(validate("MIT)").is_err());
    }

    // -- is_known_license() tests -------------------------------------------

    #[test]
    fn known_license_mit() {
        assert!(is_known_license("MIT"));
    }

    #[test]
    fn known_license_apache() {
        assert!(is_known_license("Apache-2.0"));
    }

    #[test]
    fn known_license_gpl() {
        assert!(is_known_license("GPL-3.0-only"));
    }

    #[test]
    fn known_license_cc0() {
        assert!(is_known_license("CC0-1.0"));
    }

    #[test]
    fn unknown_license_is_not_known() {
        assert!(!is_known_license("NONEXISTENT-LICENSE"));
    }

    #[test]
    fn license_ref_is_not_in_known_list() {
        // LicenseRef-* identifiers are valid expressions but are not "known"
        assert!(!is_known_license("LicenseRef-custom"));
    }

    // -- is_known_exception() tests -----------------------------------------

    #[test]
    fn known_exception_llvm() {
        assert!(is_known_exception("LLVM-exception"));
    }

    #[test]
    fn known_exception_classpath() {
        assert!(is_known_exception("Classpath-exception-2.0"));
    }

    #[test]
    fn unknown_exception_is_not_known() {
        assert!(!is_known_exception("MadeUp-exception"));
    }

    // -- Display tests ------------------------------------------------------

    #[test]
    fn display_simple() {
        let expr = Expression::Simple {
            id: LicenseId { id: "MIT".into() },
        };
        assert_eq!(expr.to_string(), "MIT");
    }

    #[test]
    fn display_or() {
        let expr = Expression::Or {
            left: Box::new(Expression::Simple {
                id: LicenseId { id: "MIT".into() },
            }),
            right: Box::new(Expression::Simple {
                id: LicenseId {
                    id: "Apache-2.0".into(),
                },
            }),
        };
        assert_eq!(expr.to_string(), "MIT OR Apache-2.0");
    }

    #[test]
    fn display_with() {
        let expr = Expression::With {
            license: Box::new(Expression::Simple {
                id: LicenseId {
                    id: "Apache-2.0".into(),
                },
            }),
            exception: LicenseId {
                id: "LLVM-exception".into(),
            },
        };
        assert_eq!(expr.to_string(), "Apache-2.0 WITH LLVM-exception");
    }
}