-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathconstraintparser.go
More file actions
650 lines (564 loc) · 15.2 KB
/
Copy pathconstraintparser.go
File metadata and controls
650 lines (564 loc) · 15.2 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
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
// Package semver implements logic to work with Sementic Versioning 2.0.0 in Go.
// It provides:
// - Parser for semantic versions
// - Validation of semantic versions
// - Sorting of semantic versions
// - Parser for semantic version range constraints
// - Range constraint matching
// - whether version contained in range
// - whether a range is contained in another range
package semver
import (
"fmt"
"sort"
"pkg.package-operator.run/semver/internal"
"pkg.package-operator.run/semver/internal/ranges"
)
const maxUint64 = ^uint64(0)
// MustNewConstraint parses the given string into a Version Constraint or panics.
func MustNewConstraint(data string) Constraint {
c, err := NewConstraint(data)
if err != nil {
panic(err)
}
return c
}
// NewConstraint parses the given string into a Version Constraint.
func NewConstraint(data string) (Constraint, error) {
c, err := parseConstraint([]byte(data))
if err != nil {
return nil, err
}
return &originalInputConstraint{
Constraint: c,
original: data,
}, nil
}
// parseConstraint bytes into a Version Constraint.
func parseConstraint(data []byte) (Constraint, error) {
var p parserState
p.init(data)
c, err := p.parse()
if err != nil {
return nil, err
}
return c, nil
}
type parserState struct {
scanner ranges.Scanner
c Constraint
or or // active || combined ranges or And constraints
and and // active && combined ranges
operator ranges.Token // EQUAL,NOT_EQUAL, GREATER, LESS, GREATER_EQUAL, LESS_EQUAL
expectingNumber bool // if we expect a number next
lastSemverPos int // previous position after versionClose()
semverPos int // 0=Major, 1=Minor, 2=Patch
version *Version // active version being parsed
max bool // false = min part of the range, true = max part of the range
activeRange *Range // active range being parsed
errors []string // scanner errors
}
func (p *parserState) init(src []byte) *parserState {
p.scanner.Init(src, func(pos internal.Position, msg string) {
p.errors = append(p.errors, fmt.Sprintf("%s: %s", pos, msg))
})
p.resetRange()
return p
}
func (p *parserState) addNumberToVersion(num uint64) {
if p.activeRange == nil {
p.activeRange = &Range{}
}
if p.max {
p.version = &p.activeRange.Max
} else {
p.version = &p.activeRange.Min
}
switch p.semverPos {
case 0:
p.version.Major = num
case 1:
p.version.Minor = num
case 2:
p.version.Patch = num
}
}
func (p *parserState) closeVersion(pos internal.Position) error {
if p.version == nil {
return nil
}
if p.expectingNumber {
// semver clause incomplete!
return fmt.Errorf("%s: semver clause incomplete", pos)
}
p.lastSemverPos = p.semverPos
p.semverPos = 0
if !p.max {
// move to max part of range next.
p.max = true
}
p.version = nil // no active version
return nil
}
func (p *parserState) closeRange(pos internal.Position) error {
if p.activeRange == nil {
return nil
}
if err := p.closeVersion(pos); err != nil {
return err
}
r := p.activeRange
switch p.operator {
case ranges.EQUAL, ranges.NOT_EQUAL:
r.Max = r.Min
switch p.lastSemverPos {
case 0:
r.Max.Minor = maxUint64
r.Max.Patch = maxUint64
case 1:
r.Max.Patch = maxUint64
}
case ranges.GREATER:
switch p.lastSemverPos {
// 1.x.x -> 2.x.x
case 0:
r.Min.Major++
// 1.2.x -> 1.3.x
case 1:
r.Min.Minor++
// 1.2.0 -> 1.2.1
default:
r.Min.Patch++
}
// x.x.x
r.Max = Version{Major: maxUint64, Minor: maxUint64, Patch: maxUint64}
case ranges.HYPHEN:
// x.0 => x.x
if r.Max.Major == maxUint64 {
r.Max.Minor = maxUint64
}
// 1.x.0 => 1.x.x
if r.Max.Minor == maxUint64 {
r.Max.Patch = maxUint64
}
case ranges.LESS:
r.Max = r.Min
switch {
// 1.2.0 => 1.1.x
case r.Max.Patch == 0 && r.Max.Minor > 0:
r.Max.Patch = maxUint64
r.Max.Minor--
// 1.0.0 => 0.x.x
case r.Max.Minor == 0:
r.Max.Patch = maxUint64
r.Max.Minor = maxUint64
r.Max.Major--
// 1.2.3 => 1.2.2
default:
r.Max.Patch--
}
r.Min = Version{} // 0.0.0
case ranges.LESS_EQUAL:
r.Max = r.Min
r.Min = Version{} // 0.0.0
case ranges.GREATER_EQUAL:
r.Max = Version{Major: maxUint64, Minor: maxUint64, Patch: maxUint64}
case ranges.TILDE:
r.Max = r.Min
r.Max.Patch = maxUint64
if r.Max.Minor == 0 {
r.Max.Minor = maxUint64
}
case ranges.CARET:
r.Max = r.Min
if r.Min.Major != 0 {
r.Max.Minor = maxUint64
}
r.Max.Patch = maxUint64
default:
return fmt.Errorf("%s: range closed without operator", pos)
}
var c Constraint
c = r
// negate result
if p.operator == ranges.NOT_EQUAL {
c = not{Range: *r}
}
p.and = append(p.and, c)
var err error
p.and, err = compactAndValidateLogicalAND(pos, p.and)
if err != nil {
return err
}
// reset
p.resetRange()
return nil
}
func (p *parserState) resetRange() {
p.max = false
p.activeRange = nil
p.operator = 0
}
func (p *parserState) close(pos internal.Position) error {
if err := p.closeRange(pos); err != nil {
return err
}
switch len(p.and) {
case 0:
case 1:
p.or = append(p.or, p.and[0])
default:
p.or = append(p.or, p.and)
}
// Compact OR'd ranges if possible
p.or = compactLogicalOR(p.or)
switch len(p.or) {
case 0:
case 1:
p.c = p.or[0]
default:
p.c = p.or
}
return nil
}
func (p *parserState) parse() (Constraint, error) {
parse:
for {
pos, tok, lit := p.scanner.Scan()
if len(p.errors) > 0 {
return nil, fmt.Errorf("%s", p.errors[0])
}
switch tok {
case ranges.ILLEGAL:
goto parse
case ranges.SPACE:
if err := p.closeVersion(pos); err != nil {
return nil, err
}
case ranges.EQUAL, ranges.NOT_EQUAL,
ranges.GREATER, ranges.GREATER_EQUAL,
ranges.LESS, ranges.LESS_EQUAL,
ranges.TILDE, ranges.CARET:
if err := p.closeRange(pos); err != nil {
return nil, err
}
p.operator = tok
case ranges.AND:
if p.activeRange == nil {
return nil, fmt.Errorf("%s: AND empty range constraint", pos)
}
if err := p.closeRange(pos); err != nil {
return nil, err
}
case ranges.OR:
if p.activeRange == nil {
return nil, fmt.Errorf("%s: OR empty range constraint", pos)
}
if err := p.closeRange(pos); err != nil {
return nil, err
}
// Shift current AND constraint into OR
if len(p.and) == 1 {
p.or = append(p.or, p.and[0])
} else {
p.or = append(p.or, p.and)
}
p.and = nil
case ranges.HYPHEN:
if p.operator == ranges.HYPHEN {
// we are already within a HYPON range.
// seeing a HYPON again is an error.
return nil, fmt.Errorf(`%s: double hyphen in range constraint`, pos)
}
if err := p.closeVersion(pos); err != nil {
return nil, err
}
p.operator = tok
p.max = true
p.expectingNumber = true
case ranges.EOF:
if err := p.close(pos); err != nil {
return nil, err
}
break parse
case ranges.NUMBER:
p.addNumberToVersion(lit)
p.expectingNumber = false
case ranges.WILDCARD:
if p.max {
p.addNumberToVersion(maxUint64)
} else {
p.addNumberToVersion(0)
}
if p.semverPos != 0 {
p.semverPos--
}
p.expectingNumber = false
case ranges.DOT:
p.expectingNumber = true
p.semverPos++
if p.semverPos > 2 {
return nil, fmt.Errorf("%s: found 3rd dot when parsing semver", pos)
}
}
}
if p.c == nil {
return nil, fmt.Errorf("%s: empty", internal.Position(1))
}
return p.c, nil
}
// compactLogicalOR combines adjacent or overlapping ranges in OR operations.
// For example, "1-2 || 2-3" → "1-3" (union of ranges).
func compactLogicalOR(constraints or) or {
if len(constraints) < 2 {
return constraints
}
// Extract only Range constraints
var ranges []Range
var other []Constraint
for _, c := range constraints {
if r, ok := c.(*Range); ok {
ranges = append(ranges, *r)
} else {
other = append(other, c)
}
}
if len(ranges) < 2 {
return constraints
}
// Sort ranges by min version
sort.Sort(AscendingMin(ranges))
// Merge overlapping or adjacent ranges
merged := []Range{ranges[0]}
for i := 1; i < len(ranges); i++ {
last := &merged[len(merged)-1]
current := ranges[i]
// Check if current range overlaps or is adjacent to the last merged range
// Adjacent means last.Max >= current.Min (allowing for touching at boundary)
if !last.Max.LessThan(current.Min) {
// Merge: extend last range's max if current goes further
if current.Max.GreaterThan(last.Max) {
last.Max = current.Max
}
} else {
// No overlap, add as new range
merged = append(merged, current)
}
}
// Rebuild constraint list
result := make(or, 0, len(merged)+len(other))
for i := range merged {
result = append(result, &merged[i])
}
result = append(result, other...)
return result
}
// simplifyIntersectingRanges checks if multiple ranges in AND only overlap at a single version
// and simplifies them to a single range with that version.
// For example, "1-2 && 2-3" → "2-2" (which represents =2.0.0).
func simplifyIntersectingRanges(ranges []Range) []Range {
if len(ranges) < 2 {
return ranges
}
// Calculate the intersection of all ranges
// Intersection min = max of all mins
// Intersection max = min of all maxs
intersectionMin := ranges[0].Min
intersectionMax := ranges[0].Max
for i := 1; i < len(ranges); i++ {
// Update min to the highest min
if ranges[i].Min.GreaterThan(intersectionMin) {
intersectionMin = ranges[i].Min
}
// Update max to the lowest max
if ranges[i].Max.LessThan(intersectionMax) {
intersectionMax = ranges[i].Max
}
}
// If intersection is a single version, replace all ranges with that single version
if intersectionMin.Same(intersectionMax) {
return []Range{{Min: intersectionMin, Max: intersectionMax}}
}
// Otherwise, return ranges as-is
return ranges
}
// compactAndValidateLogicalAND validates ranges make sense and don't overlap.
// It combines separate lower and upper bounds (e.g., ">=X && <=Y" → "X - Y")
// but does NOT combine full ranges, as AND represents intersection, not union.
func compactAndValidateLogicalAND(pos internal.Position, and and) (and, error) {
// Validate even single constraints to catch impossible ranges
if len(and) < 1 {
return and, nil
}
// Validate that constraints are not over-constrained before compaction
if err := validateNotOverConstrained(pos, and); err != nil {
return nil, err
}
if len(and) < 2 {
return and, nil
}
var newRanges []Range
var otherConstraints []Constraint
// find min version and max version
var (
maxVersion *Version
minVersion *Version
)
for _, c := range and {
r, ok := c.(*Range)
switch {
case ok && isMinUnconstraint(*r):
if maxVersion != nil {
return nil, fmt.Errorf(
"%s: <=%s is redundant with <=%s in logical AND",
pos, r.Max.String(), maxVersion,
)
}
maxVersion = &r.Max
case ok && isMaxUnconstraint(*r):
if minVersion != nil {
return nil, fmt.Errorf(
"%s: >=%s is redundant with >=%s in logical AND",
pos, r.Min.String(), minVersion,
)
}
minVersion = &r.Min
case ok:
// Don't combine full ranges in AND - they represent intersections, not unions.
// Only combine when we have separate lower/upper bounds (e.g., >=X && <=Y).
if minVersion != nil && maxVersion != nil {
// We already have a combined range, so this is a separate constraint
newRanges = append(newRanges, *r)
} else {
minVersion = &r.Min
maxVersion = &r.Max
}
default:
otherConstraints = append(otherConstraints, c)
}
}
if minVersion != nil && maxVersion != nil {
newRanges = append(newRanges, Range{
Min: *minVersion,
Max: *maxVersion,
})
}
sort.Sort(AscendingMin(newRanges))
// Simplify ranges that only overlap at a single version
simplifiedRanges := simplifyIntersectingRanges(newRanges)
out := make([]Constraint, 0, len(simplifiedRanges)+len(otherConstraints))
for _, r := range simplifiedRanges {
out = append(out, &r)
}
out = append(out, otherConstraints...)
if len(and) != len(out) {
// Recompact after constraint changes
return compactAndValidateLogicalAND(pos, out)
}
// Validate that the constraint is not over-constrained (impossible to satisfy)
if err := validateNotOverConstrained(pos, out); err != nil {
return nil, err
}
return out, nil
}
// validateNotOverConstrained checks if constraints in AND are impossible to satisfy.
func validateNotOverConstrained(pos internal.Position, constraints and) error {
var ranges []Range
var notConstraints []not
// Collect ranges and NOT constraints
for _, c := range constraints {
switch v := c.(type) {
case *Range:
// Check for impossible individual ranges (min > max)
if v.Min.GreaterThan(v.Max) {
return fmt.Errorf(
"%s: over-constrained, no version can satisfy %s (min > max)",
pos, v.String(),
)
}
ranges = append(ranges, *v)
case not:
notConstraints = append(notConstraints, v)
case and:
// Nested AND - validate recursively
if err := validateNotOverConstrained(pos, v); err != nil {
return err
}
case or:
// OR in AND - each branch should be valid on its own
// We don't validate OR branches as over-constrained since
// at least one branch might be satisfiable
}
}
// Check for non-overlapping ranges in AND
if len(ranges) > 1 {
// Check if all ranges have a common overlap
for i := range len(ranges) - 1 {
for j := i + 1; j < len(ranges); j++ {
if !rangesOverlap(ranges[i], ranges[j]) {
return fmt.Errorf(
"%s: over-constrained, ranges do not overlap: %s AND %s",
pos, ranges[i].String(), ranges[j].String(),
)
}
}
}
}
// Check if we have both >= and <= constraints that don't overlap
// This catches cases like ">=2.0.0 && <1.0.0"
var minBound *Version // from >= constraint
var maxBound *Version // from <= or < constraint
for _, r := range ranges {
// Check if this is a lower bound (>= or >)
if isMaxUnconstraint(r) {
if minBound == nil || r.Min.GreaterThan(*minBound) {
minBound = &r.Min
}
}
// Check if this is an upper bound (<= or <)
if isMinUnconstraint(r) {
if maxBound == nil || r.Max.LessThan(*maxBound) {
maxBound = &r.Max
}
}
}
// If we have both bounds, check if they're compatible
if minBound != nil && maxBound != nil {
if minBound.GreaterThan(*maxBound) {
return fmt.Errorf(
"%s: over-constrained, lower bound %s is greater than upper bound %s",
pos, minBound.String(), maxBound.String(),
)
}
}
// Check if NOT constraints exclude all versions in ranges
if len(ranges) > 0 && len(notConstraints) > 0 {
// For single-version ranges with NOT, check if they exclude that exact version
for _, r := range ranges {
if r.Min.Same(r.Max) {
// This is an equality constraint (e.g., =1.0.0)
for _, n := range notConstraints {
if n.Min.Same(r.Min) && n.Max.Same(r.Max) {
return fmt.Errorf(
"%s: over-constrained, %s AND %s excludes all versions",
pos, r.String(), n.String(),
)
}
}
}
}
}
return nil
}
// rangesOverlap checks if two ranges have any overlapping versions.
func rangesOverlap(a, b Range) bool {
// Ranges overlap if:
// - a.Min <= b.Max AND b.Min <= a.Max
return !a.Min.GreaterThan(b.Max) && !b.Min.GreaterThan(a.Max)
}
func isMinUnconstraint(r Range) bool {
return r.Min.Same(Version{})
}
func isMaxUnconstraint(r Range) bool {
return r.Max.Same(Version{Major: maxUint64, Minor: maxUint64, Patch: maxUint64})
}