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
|
use std::collections::HashMap;
use std::sync::LazyLock;
include!(concat!(env!("OUT_DIR"), "/spdx_data.rs"));
/// Information about an SPDX license.
#[derive(Debug, Clone)]
pub struct LicenseInfo {
pub identifier: &'static str,
pub full_name: &'static str,
pub osi_approved: bool,
pub deprecated: bool,
}
impl LicenseInfo {
/// Canonical SPDX URL for this license. Mirrors Composer's
/// `SpdxLicenses::getLicenseByIdentifier()` which constructs the URL from
/// the identifier rather than storing it in the data file.
pub fn url(&self) -> String {
format!(
"https://spdx.org/licenses/{}.html#licenseText",
self.identifier
)
}
}
/// Information about an SPDX license exception.
#[derive(Debug, Clone)]
pub struct ExceptionInfo {
pub identifier: &'static str,
pub full_name: &'static str,
}
/// SPDX license database with expression validation.
pub struct SpdxLicenses {
licenses: HashMap<&'static str, LicenseInfo>,
exceptions: HashMap<&'static str, ExceptionInfo>,
}
impl SpdxLicenses {
/// Build the license database from generated data.
pub fn new() -> Self {
let mut licenses = HashMap::with_capacity(LICENSES.len());
for &(lower, id, full_name, osi, deprecated) in LICENSES {
licenses.insert(
lower,
LicenseInfo {
identifier: id,
full_name,
osi_approved: osi,
deprecated,
},
);
}
let mut exceptions = HashMap::with_capacity(EXCEPTIONS.len());
for &(lower, id, full_name) in EXCEPTIONS {
exceptions.insert(
lower,
ExceptionInfo {
identifier: id,
full_name,
},
);
}
Self {
licenses,
exceptions,
}
}
/// Look up a license by its SPDX identifier (case-insensitive).
pub fn get_license_by_identifier(&self, id: &str) -> Option<&LicenseInfo> {
self.licenses.get(id.to_lowercase().as_str())
}
/// Validate an SPDX license expression.
///
/// Supports compound expressions with AND/OR, the WITH operator for
/// exceptions, the `+` (or-later) operator, LicenseRef, and the special
/// values `NONE` and `NOASSERTION`.
pub fn validate(&self, license: &str) -> bool {
if license.is_empty() {
return false;
}
// Fast path: check simple license identifier first.
if self.is_valid_license_id(license) {
return true;
}
// Composer anchors its regex with `^...$` and never permits leading or
// trailing whitespace. Reject it here so the tokenizer (which skips
// whitespace as a token separator) doesn't accept it.
let bytes = license.as_bytes();
if bytes[0].is_ascii_whitespace() || bytes[bytes.len() - 1].is_ascii_whitespace() {
return false;
}
// Special values
if license.eq_ignore_ascii_case("NONE") || license.eq_ignore_ascii_case("NOASSERTION") {
return true;
}
let mut parser = Parser::new(license, self);
parser.parse_expression() && parser.is_at_end()
}
fn is_valid_license_id(&self, id: &str) -> bool {
self.licenses.contains_key(id.to_lowercase().as_str())
}
fn is_valid_exception_id(&self, id: &str) -> bool {
self.exceptions.contains_key(id.to_lowercase().as_str())
}
}
impl Default for SpdxLicenses {
fn default() -> Self {
Self::new()
}
}
/// Global static SPDX license database.
static SPDX: LazyLock<SpdxLicenses> = LazyLock::new(SpdxLicenses::new);
/// Get a reference to the global SPDX license database.
pub fn spdx() -> &'static SpdxLicenses {
&SPDX
}
// ---------------------------------------------------------------------------
// SPDX expression parser (recursive descent)
// ---------------------------------------------------------------------------
//
// Grammar:
// expression = compound_expr
// compound_expr = head_expr (("AND" | "OR") compound_expr)?
// head_expr = simple_expr ("WITH" exception_id)?
// | "(" compound_expr ")"
// simple_expr = license_id "+"?
// | license_ref
// license_ref = ("DocumentRef-" idstring ":")? "LicenseRef-" idstring
// idstring = [a-zA-Z0-9-.]+
struct Parser<'a> {
tokens: Vec<&'a str>,
pos: usize,
db: &'a SpdxLicenses,
}
impl<'a> Parser<'a> {
fn new(input: &'a str, db: &'a SpdxLicenses) -> Self {
let tokens = Self::tokenize(input);
Self { tokens, pos: 0, db }
}
fn tokenize(input: &str) -> Vec<&str> {
let mut tokens = Vec::new();
let mut chars = input.char_indices().peekable();
while let Some(&(i, c)) = chars.peek() {
if c.is_whitespace() {
chars.next();
continue;
}
if c == '(' || c == ')' || c == '+' {
tokens.push(&input[i..i + 1]);
chars.next();
continue;
}
// Identifier or keyword: consume until whitespace or special char
let start = i;
loop {
chars.next();
match chars.peek() {
Some(&(_, ch)) if !ch.is_whitespace() && ch != '(' && ch != ')' => {
// '+' only breaks if it's right after an identifier
if ch == '+' {
break;
}
}
_ => break,
}
}
let end = chars.peek().map_or(input.len(), |&(j, _)| j);
tokens.push(&input[start..end]);
}
tokens
}
fn peek(&self) -> Option<&'a str> {
self.tokens.get(self.pos).copied()
}
fn advance(&mut self) -> Option<&'a str> {
let tok = self.tokens.get(self.pos).copied();
if tok.is_some() {
self.pos += 1;
}
tok
}
fn is_at_end(&self) -> bool {
self.pos >= self.tokens.len()
}
fn expect(&mut self, expected: &str) -> bool {
if self.peek() == Some(expected) {
self.advance();
true
} else {
false
}
}
/// Parse the top-level expression.
fn parse_expression(&mut self) -> bool {
self.parse_compound_expr()
}
/// compound_expr = head_expr (("AND" | "OR") compound_expr)?
fn parse_compound_expr(&mut self) -> bool {
if !self.parse_head_expr() {
return false;
}
if let Some(tok) = self.peek()
&& (tok == "AND" || tok == "OR")
{
self.advance();
return self.parse_compound_expr();
}
true
}
/// head_expr = "(" compound_expr ")" | simple_expr ("WITH" exception_id)?
fn parse_head_expr(&mut self) -> bool {
if self.expect("(") {
if !self.parse_compound_expr() {
return false;
}
return self.expect(")");
}
if !self.parse_simple_expr() {
return false;
}
// Optional WITH clause
if self.peek() == Some("WITH") {
self.advance();
return self.parse_exception_id();
}
true
}
/// simple_expr = license_ref | license_id "+"?
fn parse_simple_expr(&mut self) -> bool {
let tok = match self.peek() {
Some(t) => t,
None => return false,
};
// LicenseRef / DocumentRef
if tok.starts_with("LicenseRef-") || tok.starts_with("DocumentRef-") {
return self.parse_license_ref();
}
// Regular license identifier — could be multi-token with "-"
// We just consume the current token and check
self.advance();
// Handle '+' (or-later) operator
if self.peek() == Some("+") {
self.advance();
}
self.db.is_valid_license_id(tok)
}
/// license_ref = ("DocumentRef-" idstring ":")? "LicenseRef-" idstring
fn parse_license_ref(&mut self) -> bool {
let tok = match self.advance() {
Some(t) => t,
None => return false,
};
if let Some(rest) = tok.strip_prefix("DocumentRef-") {
// Must contain ":LicenseRef-" within
if let Some(colon_pos) = rest.find(":LicenseRef-") {
let doc_id = &rest[..colon_pos];
let license_ref_id = &rest[colon_pos + ":LicenseRef-".len()..];
return is_valid_idstring(doc_id) && is_valid_idstring(license_ref_id);
}
return false;
}
if let Some(id) = tok.strip_prefix("LicenseRef-") {
return is_valid_idstring(id);
}
false
}
fn parse_exception_id(&mut self) -> bool {
match self.advance() {
Some(id) => self.db.is_valid_exception_id(id),
None => false,
}
}
}
/// Check that a string matches `[a-zA-Z0-9.-]+`.
fn is_valid_idstring(s: &str) -> bool {
!s.is_empty()
&& s.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'-')
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn valid_identifiers() {
let db = spdx();
assert!(db.validate("MIT"));
assert!(db.validate("Apache-2.0"));
assert!(db.validate("GPL-3.0-only"));
assert!(db.validate("0BSD"));
}
#[test]
fn case_insensitive() {
let db = spdx();
assert!(db.validate("mit"));
assert!(db.validate("apache-2.0"));
assert!(db.validate("Mit"));
}
#[test]
fn or_expression() {
let db = spdx();
assert!(db.validate("MIT OR Apache-2.0"));
}
#[test]
fn and_expression() {
let db = spdx();
assert!(db.validate("MIT AND Apache-2.0"));
}
#[test]
fn with_exception() {
let db = spdx();
assert!(db.validate("GPL-2.0-only WITH Classpath-exception-2.0"));
}
#[test]
fn complex_expression() {
let db = spdx();
assert!(db.validate("(MIT AND Apache-2.0) OR GPL-3.0-only"));
assert!(db.validate("(MIT OR Apache-2.0) AND (GPL-2.0-only OR BSD-2-Clause)"));
}
#[test]
fn special_values() {
let db = spdx();
assert!(db.validate("NONE"));
assert!(db.validate("NOASSERTION"));
assert!(db.validate("none"));
assert!(db.validate("noassertion"));
}
#[test]
fn or_later_operator() {
let db = spdx();
assert!(db.validate("Apache-2.0+"));
assert!(db.validate("GPL-2.0-only+"));
}
#[test]
fn license_ref() {
let db = spdx();
assert!(db.validate("LicenseRef-custom"));
assert!(db.validate("LicenseRef-my-license.1"));
assert!(db.validate("DocumentRef-spdx-tool-1.2:LicenseRef-MIT-Style-2"));
}
#[test]
fn invalid_expressions() {
let db = spdx();
assert!(!db.validate(""));
assert!(!db.validate("totally-not-a-license"));
assert!(!db.validate("MIT AND"));
assert!(!db.validate("AND MIT"));
assert!(!db.validate("MIT OR"));
assert!(!db.validate("(MIT"));
assert!(!db.validate("MIT)"));
assert!(!db.validate("MIT WITH"));
assert!(!db.validate("MIT WITH not-an-exception"));
}
#[test]
fn no_edge_whitespace_allowed() {
// Composer's `^(NONE|NOASSERTION|...)$` (with `x` flag) admits no
// leading or trailing whitespace; mirror that.
let db = spdx();
assert!(db.validate("MIT"));
assert!(!db.validate(" MIT"));
assert!(!db.validate("MIT "));
assert!(!db.validate(" MIT "));
assert!(!db.validate("\tMIT"));
assert!(!db.validate("MIT\t"));
assert!(!db.validate("\nMIT"));
}
#[test]
fn license_lookup() {
let db = spdx();
let mit = db.get_license_by_identifier("MIT").unwrap();
assert_eq!(mit.identifier, "MIT");
assert!(mit.osi_approved);
assert!(!mit.deprecated);
assert!(db.get_license_by_identifier("mit").is_some());
assert!(db.get_license_by_identifier("nonexistent").is_none());
}
#[test]
fn license_url_uses_canonical_id() {
let db = spdx();
let mit = db.get_license_by_identifier("MIT").unwrap();
assert_eq!(mit.url(), "https://spdx.org/licenses/MIT.html#licenseText");
// Lookup is case-insensitive, but the URL uses the canonical casing
// from the database, mirroring Composer's `getLicenseByIdentifier`.
let mit_lower = db.get_license_by_identifier("mit").unwrap();
assert_eq!(
mit_lower.url(),
"https://spdx.org/licenses/MIT.html#licenseText"
);
}
}
|