-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathparse.go
More file actions
551 lines (455 loc) · 12 KB
/
parse.go
File metadata and controls
551 lines (455 loc) · 12 KB
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
package spdx
import (
"errors"
"fmt"
"strings"
"unicode"
)
// Expression represents a parsed SPDX expression.
type Expression interface {
// String returns the normalized string representation.
String() string
// Licenses returns all license identifiers in the expression.
Licenses() []string
isExpr()
}
// License represents a single SPDX license identifier.
type License struct {
ID string // The canonical license ID
Plus bool // True if followed by +
Exception string // Exception ID if using WITH
}
func (l *License) String() string {
s := l.ID
if l.Plus {
s += "+"
}
if l.Exception != "" {
s += " WITH " + l.Exception
}
return s
}
func (l *License) Licenses() []string {
return []string{l.ID}
}
func (l *License) isExpr() {}
// LicenseRef represents a custom license reference.
type LicenseRef struct {
DocumentRef string // Optional document reference
LicenseRef string // The license reference ID
}
func (l *LicenseRef) String() string {
if l.DocumentRef != "" {
return "DocumentRef-" + l.DocumentRef + ":LicenseRef-" + l.LicenseRef
}
return "LicenseRef-" + l.LicenseRef
}
func (l *LicenseRef) Licenses() []string {
return []string{l.String()}
}
func (l *LicenseRef) isExpr() {}
// AndExpression represents an AND combination of expressions.
type AndExpression struct {
Left Expression
Right Expression
}
func (e *AndExpression) String() string {
left := e.Left.String()
right := e.Right.String()
// Wrap OR expressions in parentheses for correct precedence
if _, ok := e.Left.(*OrExpression); ok {
left = "(" + left + ")"
}
if _, ok := e.Right.(*OrExpression); ok {
right = "(" + right + ")"
}
return left + " AND " + right
}
func (e *AndExpression) Licenses() []string {
return append(e.Left.Licenses(), e.Right.Licenses()...)
}
func (e *AndExpression) isExpr() {}
// OrExpression represents an OR combination of expressions.
type OrExpression struct {
Left Expression
Right Expression
}
func (e *OrExpression) String() string {
left := e.Left.String()
right := e.Right.String()
// Wrap AND expressions and WITH licenses in parentheses for clarity
if _, ok := e.Left.(*AndExpression); ok {
left = "(" + left + ")"
}
if _, ok := e.Right.(*AndExpression); ok {
right = "(" + right + ")"
}
// License with exception should also be wrapped
if lic, ok := e.Right.(*License); ok && lic.Exception != "" {
right = "(" + right + ")"
}
if lic, ok := e.Left.(*License); ok && lic.Exception != "" {
left = "(" + left + ")"
}
return left + " OR " + right
}
func (e *OrExpression) Licenses() []string {
return append(e.Left.Licenses(), e.Right.Licenses()...)
}
func (e *OrExpression) isExpr() {}
// SpecialValue represents NONE or NOASSERTION.
type SpecialValue struct {
Value string
}
func (s *SpecialValue) String() string {
return s.Value
}
func (s *SpecialValue) Licenses() []string {
return nil
}
func (s *SpecialValue) isExpr() {}
// Parser errors
var (
ErrEmptyExpression = errors.New("empty expression")
ErrUnexpectedToken = errors.New("unexpected token")
ErrUnbalancedParens = errors.New("unbalanced parentheses")
ErrInvalidLicenseID = errors.New("invalid license identifier")
ErrInvalidException = errors.New("invalid exception identifier")
ErrMissingOperand = errors.New("missing operand")
ErrInvalidSpecialValue = errors.New("NONE and NOASSERTION must be standalone")
ErrExpressionTooLarge = errors.New("expression too large")
)
// tokenType represents the type of a lexer token.
type tokenType int
const (
tokenLicense tokenType = iota
tokenLicenseRef
tokenDocumentRef
tokenAnd
tokenOr
tokenWith
tokenPlus
tokenOpenParen
tokenCloseParen
tokenEOF
opAND = "AND"
opOR = "OR"
opWITH = "WITH"
)
type token struct {
typ tokenType
value string
}
// lexer tokenizes an SPDX expression.
type lexer struct {
input string
pos int
}
func newLexer(input string) *lexer {
return &lexer{input: input}
}
func (l *lexer) skipWhitespace() {
for l.pos < len(l.input) && unicode.IsSpace(rune(l.input[l.pos])) {
l.pos++
}
}
func (l *lexer) next() (token, error) {
l.skipWhitespace()
if l.pos >= len(l.input) {
return token{typ: tokenEOF}, nil
}
ch := l.input[l.pos]
switch ch {
case '(':
l.pos++
return token{typ: tokenOpenParen, value: "("}, nil
case ')':
l.pos++
return token{typ: tokenCloseParen, value: ")"}, nil
case '+':
l.pos++
return token{typ: tokenPlus, value: "+"}, nil
}
// Read identifier or keyword
start := l.pos
for l.pos < len(l.input) {
ch := l.input[l.pos]
if unicode.IsSpace(rune(ch)) || ch == '(' || ch == ')' || ch == '+' {
break
}
l.pos++
}
if l.pos == start {
return token{}, fmt.Errorf("unexpected character: %c", ch)
}
word := l.input[start:l.pos]
upper := strings.ToUpper(word)
switch upper {
case opAND:
return token{typ: tokenAnd, value: opAND}, nil
case opOR:
return token{typ: tokenOr, value: opOR}, nil
case opWITH:
return token{typ: tokenWith, value: opWITH}, nil
}
// Check for DocumentRef or LicenseRef
if strings.HasPrefix(upper, "DOCUMENTREF-") {
// DocumentRef-xxx:LicenseRef-yyy
return token{typ: tokenDocumentRef, value: word}, nil
}
if strings.HasPrefix(upper, "LICENSEREF-") {
return token{typ: tokenLicenseRef, value: word}, nil
}
return token{typ: tokenLicense, value: word}, nil
}
const (
maxParseDepth = 256
maxParseLength = 1 << 20 // 1 MiB
)
// parser parses SPDX expressions.
type parser struct {
lexer *lexer
current token
depth int
}
func newParser(input string) (*parser, error) {
p := &parser{lexer: newLexer(input)}
tok, err := p.lexer.next()
if err != nil {
return nil, err
}
p.current = tok
return p, nil
}
func (p *parser) advance() error {
tok, err := p.lexer.next()
if err != nil {
return err
}
p.current = tok
return nil
}
// Parse parses an SPDX expression string into an Expression tree.
// It handles both strict SPDX identifiers and informal license names
// (like "Apache 2" or "MIT License") by normalizing them automatically.
//
// Example:
//
// Parse("MIT") // *License{ID: "MIT"}
// Parse("MIT OR Apache-2.0") // *OrExpression{...}
// Parse("mit OR apache 2") // normalizes to "MIT OR Apache-2.0"
// Parse("GPL v3 AND BSD") // normalizes to "GPL-3.0-or-later AND BSD-2-Clause"
//
// For strict SPDX-only parsing (no fuzzy normalization), use ParseStrict.
func Parse(expression string) (Expression, error) {
expression = strings.TrimSpace(expression)
if expression == "" {
return nil, ErrEmptyExpression
}
if len(expression) > maxParseLength {
return nil, ErrExpressionTooLarge
}
// Pre-process: normalize informal license names while preserving operators
normalized, err := normalizeExpressionString(expression)
if err != nil {
return nil, err
}
p, err := newParser(normalized)
if err != nil {
return nil, err
}
expr, err := p.parseExpression()
if err != nil {
return nil, err
}
if p.current.typ != tokenEOF {
return nil, fmt.Errorf("%w: %s", ErrUnexpectedToken, p.current.value)
}
return expr, nil
}
// ParseStrict parses an SPDX expression requiring strict SPDX identifiers.
// Unlike Parse, it does not normalize informal license names.
// Use this when you need to validate that an expression uses only
// exact SPDX license identifiers.
//
// Example:
//
// ParseStrict("MIT OR Apache-2.0") // succeeds
// ParseStrict("mit OR apache 2") // fails - "apache 2" is not a valid SPDX ID
func ParseStrict(expression string) (Expression, error) {
expression = strings.TrimSpace(expression)
if expression == "" {
return nil, ErrEmptyExpression
}
if len(expression) > maxParseLength {
return nil, ErrExpressionTooLarge
}
p, err := newParser(expression)
if err != nil {
return nil, err
}
expr, err := p.parseExpression()
if err != nil {
return nil, err
}
if p.current.typ != tokenEOF {
return nil, fmt.Errorf("%w: %s", ErrUnexpectedToken, p.current.value)
}
return expr, nil
}
// parseExpression parses a full expression (handles OR, lowest precedence).
func (p *parser) parseExpression() (Expression, error) {
left, err := p.parseAnd()
if err != nil {
return nil, err
}
for p.current.typ == tokenOr {
if err := p.advance(); err != nil {
return nil, err
}
right, err := p.parseAnd()
if err != nil {
return nil, err
}
left = &OrExpression{Left: left, Right: right}
}
return left, nil
}
// parseAnd parses AND expressions (higher precedence than OR).
func (p *parser) parseAnd() (Expression, error) {
left, err := p.parseWith()
if err != nil {
return nil, err
}
for p.current.typ == tokenAnd {
if err := p.advance(); err != nil {
return nil, err
}
right, err := p.parseWith()
if err != nil {
return nil, err
}
left = &AndExpression{Left: left, Right: right}
}
return left, nil
}
// parseWith parses WITH expressions (higher precedence than AND).
func (p *parser) parseWith() (Expression, error) {
left, err := p.parseAtom()
if err != nil {
return nil, err
}
// WITH only applies to licenses, not expressions
if p.current.typ == tokenWith {
license, ok := left.(*License)
if !ok {
return nil, fmt.Errorf("%w: WITH can only follow a license", ErrUnexpectedToken)
}
if err := p.advance(); err != nil {
return nil, err
}
if p.current.typ != tokenLicense {
return nil, fmt.Errorf("%w: expected exception after WITH", ErrMissingOperand)
}
exception := lookupException(p.current.value)
if exception == "" {
return nil, fmt.Errorf("%w: %s", ErrInvalidException, p.current.value)
}
license.Exception = exception
if err := p.advance(); err != nil {
return nil, err
}
}
return left, nil
}
// parseAtom parses atomic expressions (licenses, refs, parenthesized expressions).
func (p *parser) parseAtom() (Expression, error) {
switch p.current.typ {
case tokenOpenParen:
p.depth++
if p.depth > maxParseDepth {
return nil, ErrExpressionTooLarge
}
if err := p.advance(); err != nil {
return nil, err
}
expr, err := p.parseExpression()
if err != nil {
return nil, err
}
if p.current.typ != tokenCloseParen {
return nil, ErrUnbalancedParens
}
if err := p.advance(); err != nil {
return nil, err
}
p.depth--
return expr, nil
case tokenLicense:
value := p.current.value
upper := strings.ToUpper(value)
// Handle special values
if upper == "NONE" || upper == "NOASSERTION" {
if err := p.advance(); err != nil {
return nil, err
}
return &SpecialValue{Value: upper}, nil
}
// Look up the canonical license ID
id := lookupLicense(value)
if id == "" {
return nil, fmt.Errorf("%w: %s", ErrInvalidLicenseID, value)
}
license := &License{ID: id}
if err := p.advance(); err != nil {
return nil, err
}
// Check for +
if p.current.typ == tokenPlus {
license.Plus = true
if err := p.advance(); err != nil {
return nil, err
}
}
return license, nil
case tokenLicenseRef:
ref := parseLicenseRef(p.current.value)
if err := p.advance(); err != nil {
return nil, err
}
return ref, nil
case tokenDocumentRef:
ref := parseDocumentRef(p.current.value)
if err := p.advance(); err != nil {
return nil, err
}
return ref, nil
case tokenEOF:
return nil, ErrMissingOperand
default:
return nil, fmt.Errorf("%w: %s", ErrUnexpectedToken, p.current.value)
}
}
// parseLicenseRef parses "LicenseRef-xxx" into a LicenseRef.
func parseLicenseRef(s string) *LicenseRef {
// Remove "LicenseRef-" prefix (case insensitive)
upper := strings.ToUpper(s)
if strings.HasPrefix(upper, "LICENSEREF-") {
return &LicenseRef{LicenseRef: s[11:]}
}
return &LicenseRef{LicenseRef: s}
}
// parseDocumentRef parses "DocumentRef-xxx:LicenseRef-yyy" into a LicenseRef.
func parseDocumentRef(s string) *LicenseRef {
// Format: DocumentRef-xxx:LicenseRef-yyy
upper := strings.ToUpper(s)
if strings.HasPrefix(upper, "DOCUMENTREF-") {
rest := s[12:] // after "DocumentRef-"
if idx := strings.Index(strings.ToUpper(rest), ":LICENSEREF-"); idx != -1 {
docRef := rest[:idx]
licRef := rest[idx+12:] // after ":LicenseRef-"
return &LicenseRef{DocumentRef: docRef, LicenseRef: licRef}
}
}
return &LicenseRef{LicenseRef: s}
}