composer-semver 0.2.0

A faithful Rust port of composer/semver: Composer-flavored Version, Constraint, and Stability — normalize, compare, and match version constraints.
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
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
//! Composer-flavored constraint: parse + `matches`.
//!
//! Mirrors `Composer\Semver\VersionParser::parseConstraints` and
//! `Constraint::matches` from `composer/semver` (commit
//! `09af5e85b5f1380e4e098dde28950e2549cba4ed`, the version the
//! conformance fixtures were generated from).
//!
//! Grammar (informally):
//!
//! ```text
//! constraint := alt ("||" alt)*
//! alt        := atom (sep atom)*      -- sep is whitespace or ","
//! atom       := "*" | "x"
//!             | partial "-" partial         -- hyphenated range
//!             | caret_or_tilde version
//!             | op version                  -- >, >=, <, <=, =, ==, !=
//!             | partial_or_wildcard         -- 1, 1.2, 1.2.3, 1.2.*, 2.x.x
//! ```
//!
//! Each atom canonicalizes into an `And` of [`Op { op, version }`]
//! atoms; multi-atom intersections are `And`; `||`-joined groups are
//! `Or`. Matching is then a straight tree walk against the candidate
//! version using [`Version::compare`].

use crate::bound::Bound;
use crate::version::{
    CmpOp, Suffix, Version, VersionKind, is_branch_alias as composer_semver_is_branch_alias,
};
use regex::Regex;
use std::sync::OnceLock;

#[derive(Debug, Clone, Eq, PartialEq)]
pub enum Constraint {
    /// `*` / `x` — matches everything.
    Any,
    /// `op X.Y.Z` — atomic operator clause. `explicit_lower_bound` is
    /// true when this clause is a `>=`/`>` whose version was written
    /// in full (`^1.2.3`, `>=1.2.3`) rather than synthesized from a
    /// partial expansion (`1` → `>=1.0.0`). Composer admits same-numeric
    /// prereleases at the lower bound only in the explicit case.
    Op {
        op: CmpOp,
        version: Version,
        explicit_lower_bound: bool,
    },
    /// Whitespace-or-comma-joined intersection.
    And(Vec<Constraint>),
    /// `||`-joined union.
    Or(Vec<Constraint>),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ParseError {
    Invalid(String),
}

impl std::fmt::Display for ParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Invalid(s) => write!(f, "invalid constraint: {s:?}"),
        }
    }
}

impl std::error::Error for ParseError {}

impl Constraint {
    /// Parse a Composer constraint string.
    ///
    /// # Panics
    ///
    /// Doesn't: the internal `.unwrap()`s reach `parsed.into_iter().next()`
    /// only when `parsed.len() == 1` was just checked.
    pub fn parse(input: &str) -> Result<Self, ParseError> {
        let trimmed = input.trim();
        if trimmed.is_empty() {
            return Err(ParseError::Invalid(input.to_owned()));
        }
        // Split on `||` first.
        let alts: Vec<&str> = re_or_split()
            .split(trimmed)
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .collect();
        if alts.is_empty() {
            return Err(ParseError::Invalid(input.to_owned()));
        }
        let parsed: Vec<Constraint> = alts
            .into_iter()
            .map(parse_intersection)
            .collect::<Result<_, _>>()?;
        Ok(if parsed.len() == 1 {
            parsed.into_iter().next().unwrap()
        } else {
            Self::Or(parsed)
        })
    }

    /// Return whether `version` satisfies this constraint.
    ///
    /// Differs from `version.compare(op, target)` in the
    /// prerelease-vs-stable edge case: when `version` is a prerelease
    /// (e.g. `1.2.3-beta`) and `target` is the stable form with the
    /// same numeric body (`1.2.3`), Composer's constraint engine
    /// treats them as `Equal` rather than the normal "prerelease <
    /// stable" ordering. This is what makes `1.2.3-beta` satisfy
    /// `^1.2.3` and *not* satisfy `<1.2.3`.
    pub fn matches(&self, version: &Version) -> bool {
        match self {
            Self::Any => true,
            Self::Op {
                op,
                version: target,
                explicit_lower_bound,
            } => matches_atom(version, *op, target, *explicit_lower_bound),
            Self::And(items) => items.iter().all(|c| c.matches(version)),
            Self::Or(items) => items.iter().any(|c| c.matches(version)),
        }
    }

    /// The lowest version this constraint admits, as a [`Bound`]. Port
    /// of `Constraint::getLowerBound` + `MultiConstraint::extractBounds`
    /// (commit `09af5e8`):
    ///
    /// - atomic `==`/`>=` → inclusive bound at the version; `>` →
    ///   exclusive; `<`/`<=`/`!=` → [`Bound::zero`]; a `dev-` branch
    ///   reference → `Bound::zero` (Composer's `strpos(... 'dev-') === 0`
    ///   short-circuit).
    /// - `And` (conjunctive) → the *greatest* of the members' lower
    ///   bounds; `Or` (disjunctive) → the *least*.
    ///
    /// `Any` (`*` / `x`) is `Bound::zero`, matching
    /// `MatchAllConstraint`.
    #[must_use]
    pub fn lower_bound(&self) -> Bound {
        match self {
            Self::Any => Bound::zero(),
            Self::Op { op, version, .. } => {
                if version.normalized.starts_with("dev-") {
                    return Bound::zero();
                }
                match op {
                    CmpOp::Eq | CmpOp::Ge => Bound::new(version.normalized.clone(), true),
                    CmpOp::Gt => Bound::new(version.normalized.clone(), false),
                    CmpOp::Lt | CmpOp::Le | CmpOp::Ne => Bound::zero(),
                }
            }
            Self::And(items) => fold_bound(items, true, Constraint::lower_bound),
            Self::Or(items) => fold_bound(items, false, Constraint::lower_bound),
        }
    }

    /// The highest version this constraint admits, as a [`Bound`].
    /// Mirror of [`Constraint::lower_bound`] on the upper side:
    /// `==`/`<=` → inclusive; `<` → exclusive; `>`/`>=`/`!=`/`*` →
    /// [`Bound::positive_infinity`]. `And` → the *least* of the members'
    /// upper bounds; `Or` → the *greatest*.
    #[must_use]
    pub fn upper_bound(&self) -> Bound {
        match self {
            Self::Any => Bound::positive_infinity(),
            Self::Op { op, version, .. } => {
                if version.normalized.starts_with("dev-") {
                    return Bound::positive_infinity();
                }
                match op {
                    CmpOp::Eq | CmpOp::Le => Bound::new(version.normalized.clone(), true),
                    CmpOp::Lt => Bound::new(version.normalized.clone(), false),
                    CmpOp::Gt | CmpOp::Ge | CmpOp::Ne => Bound::positive_infinity(),
                }
            }
            // For the upper fold the direction flips: conjunctive keeps
            // the smaller (`'<'`), disjunctive the larger (`'>'`).
            Self::And(items) => fold_bound(items, false, Constraint::upper_bound),
            Self::Or(items) => fold_bound(items, true, Constraint::upper_bound),
        }
    }

    /// Whether `self` and `other` admit at least one common version —
    /// i.e. their version intervals overlap. Used by the autoloader's
    /// `platform_check.php` generator to honor `replace`/`provide` of an
    /// extension (Composer's `$provided->matches($link->getConstraint())`).
    ///
    /// `Or` is the union of its members, so it intersects `other` iff
    /// any member does. Everything else reduces to a single contiguous
    /// interval, so the two overlap iff `max(lowers) <= min(uppers)`
    /// (with endpoint inclusivity deciding the touching case).
    #[must_use]
    pub fn intersects(&self, other: &Constraint) -> bool {
        match (self, other) {
            (Self::Or(items), _) => items.iter().any(|c| c.intersects(other)),
            (_, Self::Or(items)) => items.iter().any(|c| self.intersects(c)),
            (Self::Any, _) | (_, Self::Any) => true,
            _ => intervals_overlap(self, other),
        }
    }
}

/// Fold a member list into a single bound. `keep_greater` selects the
/// max (`true`) or the min (`false`) under [`Bound::compare_to`], which
/// is exactly what `MultiConstraint::extractBounds` does for the
/// conjunctive/disjunctive cases. `extract` pulls the per-member bound
/// (lower or upper).
fn fold_bound(
    items: &[Constraint],
    keep_greater: bool,
    extract: fn(&Constraint) -> Bound,
) -> Bound {
    let mut acc: Option<Bound> = None;
    for c in items {
        let b = extract(c);
        match &acc {
            None => acc = Some(b),
            Some(cur) => {
                if b.compare_to(cur, keep_greater) {
                    acc = Some(b);
                }
            }
        }
    }
    acc.unwrap_or_else(Bound::zero)
}

/// Overlap test for two single-interval constraints: the effective
/// lower bound is the greater of the two lowers, the effective upper is
/// the lesser of the two uppers, and the interval is non-empty iff the
/// lower sits below the upper (or they touch and both endpoints are
/// inclusive).
fn intervals_overlap(a: &Constraint, b: &Constraint) -> bool {
    let la = a.lower_bound();
    let lb = b.lower_bound();
    let ua = a.upper_bound();
    let ub = b.upper_bound();
    let lower = if la.compare_to(&lb, true) { la } else { lb };
    let upper = if ua.compare_to(&ub, false) { ua } else { ub };

    if lower.is_zero() || upper.is_positive_infinity() {
        return true;
    }
    if lower.is_positive_infinity() {
        return false;
    }
    // Both bounds are concrete versions: the interval is non-empty when
    // `lower < upper`, or when they coincide and neither endpoint
    // excludes the shared version.
    match lower.version_cmp(&upper) {
        std::cmp::Ordering::Less => true,
        std::cmp::Ordering::Greater => false,
        std::cmp::Ordering::Equal => lower.is_inclusive() && upper.is_inclusive(),
    }
}

fn matches_atom(candidate: &Version, op: CmpOp, target: &Version, explicit_lower: bool) -> bool {
    if same_numeric_prerelease_vs_stable(candidate, target) {
        // Upper-bound ops (`<`, `<=`) always treat the prerelease as
        // "equal to" the stable so it sits at the boundary; the
        // candidate consequently doesn't satisfy a strict `<`.
        // Lower-bound ops (`>=`, `>`) only honor that equality when
        // the constraint was written with a full version (a partial
        // expansion `1` → `>=1.0.0` should reject `1.0.0-beta`).
        // `==`/`!=` follow the same "treat as equal" path because
        // Composer's matchSpecific does too.
        let admit_as_equal = match op {
            CmpOp::Lt | CmpOp::Le | CmpOp::Eq | CmpOp::Ne => true,
            CmpOp::Gt | CmpOp::Ge => explicit_lower,
        };
        if admit_as_equal {
            return matches!(op, CmpOp::Eq | CmpOp::Ge | CmpOp::Le);
        }
    }
    candidate.compare(op, target)
}

/// True iff `a` and `b` are both numeric, have the same numeric
/// segments, and exactly one is a prerelease (Prerelease /
/// `PrereleaseDev` / `PatchDev` / Dev) while the other is Stable.
fn same_numeric_prerelease_vs_stable(a: &Version, b: &Version) -> bool {
    let (
        VersionKind::Numeric {
            segments_raw: sa,
            suffix: suf_a,
        },
        VersionKind::Numeric {
            segments_raw: sb,
            suffix: suf_b,
        },
    ) = (&a.kind, &b.kind)
    else {
        return false;
    };
    if !segments_equal_numerically(sa, sb) {
        return false;
    }
    is_prerelease(suf_a) ^ is_prerelease(suf_b)
}

fn is_prerelease(s: &Suffix) -> bool {
    matches!(
        s,
        Suffix::Prerelease { .. }
            | Suffix::PrereleaseDev { .. }
            | Suffix::PatchDev(_)
            | Suffix::Dev
    )
}

fn segments_equal_numerically(a: &[String], b: &[String]) -> bool {
    let len = a.len().max(b.len());
    for i in 0..len {
        let va: u64 = a.get(i).and_then(|s| s.parse().ok()).unwrap_or(0);
        let vb: u64 = b.get(i).and_then(|s| s.parse().ok()).unwrap_or(0);
        if va != vb {
            return false;
        }
    }
    true
}

// ---- top-level splitters -----------------------------------------------

fn re_or_split() -> &'static Regex {
    static R: OnceLock<Regex> = OnceLock::new();
    R.get_or_init(|| Regex::new(r"\s*\|\|?\s*").unwrap())
}

/// One `||`-alt: a whitespace-or-comma-separated list of atoms,
/// possibly with a hyphenated range form (`A - B`) inside. Returns
/// the intersection as an [`And`] (or the bare atom if there's only
/// one).
fn parse_intersection(s: &str) -> Result<Constraint, ParseError> {
    // Handle hyphenated range `A - B` first — the `-` is whitespace-
    // delimited (`A-B` without spaces would be a single token).
    if let Some(range) = parse_hyphen_range(s)? {
        return Ok(range);
    }
    let tokens = tokenize_intersection(s);
    let parsed: Vec<Constraint> = tokens
        .iter()
        .map(|t| parse_atom(t))
        .collect::<Result<_, _>>()?;
    if parsed.is_empty() {
        return Err(ParseError::Invalid(s.to_owned()));
    }
    Ok(if parsed.len() == 1 {
        parsed.into_iter().next().unwrap()
    } else {
        Constraint::And(parsed)
    })
}

/// Tokenize an intersection: split on whitespace OR `,`, but keep
/// operator + version pairs glued together (`>= 1.2.3` becomes one
/// token `>=1.2.3`).
fn tokenize_intersection(s: &str) -> Vec<String> {
    let mut out: Vec<String> = Vec::new();
    let mut cur = String::new();
    let mut chars = s.chars().peekable();
    while let Some(ch) = chars.next() {
        if ch == ',' || ch.is_whitespace() {
            // If we're mid-operator (e.g. just saw `>=`), absorb the
            // whitespace and continue building the token from the
            // next non-space chars. We detect this by checking if
            // `cur` is a pure-operator prefix.
            if !cur.is_empty() && is_pending_operator(&cur) {
                // Skip whitespace and continue with the version.
                while let Some(&peek) = chars.peek() {
                    if peek.is_whitespace() {
                        chars.next();
                    } else {
                        break;
                    }
                }
                continue;
            }
            if !cur.is_empty() {
                out.push(std::mem::take(&mut cur));
            }
            continue;
        }
        cur.push(ch);
    }
    if !cur.is_empty() {
        out.push(cur);
    }
    out
}

/// True when the current accumulator looks like an operator prefix
/// that's waiting for its version operand. Catches `>=`, `<=`, `>`,
/// `<`, `=`, `==`, `!=`, `<>`.
fn is_pending_operator(s: &str) -> bool {
    matches!(s, ">" | ">=" | "<" | "<=" | "=" | "==" | "!=" | "<>")
}

// ---- hyphenated range --------------------------------------------------

fn re_hyphen() -> &'static Regex {
    static R: OnceLock<Regex> = OnceLock::new();
    R.get_or_init(|| {
        // `(A) ... - ... (B)` — the dash must have whitespace on at
        // least one side (so `2.4.0-alpha` is not split). Build
        // metadata after either side is allowed (we strip it on the
        // partial parse).
        Regex::new(r"^(?P<lo>[^\s]+)\s+-\s+(?P<hi>[^\s]+)$").unwrap()
    })
}

fn parse_hyphen_range(s: &str) -> Result<Option<Constraint>, ParseError> {
    let Some(caps) = re_hyphen().captures(s.trim()) else {
        return Ok(None);
    };
    let lo_str = caps.name("lo").unwrap().as_str();
    let hi_str = caps.name("hi").unwrap().as_str();
    let lo = expand_partial_lower(lo_str)?;
    let hi = expand_partial_upper(hi_str)?;
    Ok(Some(Constraint::And(vec![
        Constraint::Op {
            op: CmpOp::Ge,
            version: lo,
            explicit_lower_bound: false,
        },
        Constraint::Op {
            op: CmpOp::Le,
            version: hi,
            explicit_lower_bound: false,
        },
    ])))
}

/// Expand a partial version (`1.2` / `1` / `1.2.3`) for the lower
/// bound of a hyphenated range — missing segments become `0`.
fn expand_partial_lower(s: &str) -> Result<Version, ParseError> {
    // Strip build metadata; doesn't affect comparison.
    let cleaned = s.split_once('+').map_or(s, |(left, _)| left);
    let padded = pad_partial(cleaned);
    Version::parse(&padded).map_err(|e| ParseError::Invalid(e.to_string()))
}

/// Expand a partial version for the upper bound — missing segments
/// become `9999999` so the comparison `<=` reaches every patch in
/// the named minor / major.
fn expand_partial_upper(s: &str) -> Result<Version, ParseError> {
    let cleaned = s.split_once('+').map_or(s, |(left, _)| left);
    // Composer's `1.0 - 2.0` is `>=1.0.0, <2.1` — partials on the
    // upper bound expand to "anything in the named scope". For our
    // representation we keep the inclusive form by parsing with the
    // 9999999 pads.
    let segs = split_partial_segments(cleaned);
    if segs.is_empty() {
        return Err(ParseError::Invalid(s.to_owned()));
    }
    let padded = pad_segments_with(segs, "9999999", 4);
    let candidate = padded.join(".");
    Version::parse(&candidate).map_err(|e| ParseError::Invalid(e.to_string()))
}

// ---- atom parsing ------------------------------------------------------

fn parse_atom(token: &str) -> Result<Constraint, ParseError> {
    let s = token.trim();
    if s.is_empty() {
        return Err(ParseError::Invalid(token.to_owned()));
    }
    // Strip any `#<commit-ref>` suffix Composer accepts on any
    // constraint atom (`"acme/foo": "3.x-dev#abc1234"`). For
    // resolution purposes the ref is purely informational — the
    // installer uses it to pin a specific commit of the branch, but
    // the matcher behaves the same as without it.
    let s = s.split_once('#').map_or(s, |(left, _)| left).trim_end();
    // `*` / `x` / `X`
    if matches!(s, "*" | "x" | "X") {
        return Ok(Constraint::Any);
    }

    // Branch references appear in Composer constraints in two
    // related shapes (cross-referenced against Composer's
    // `Composer\Semver\VersionParser::parseConstraint` "Basic
    // Comparators" fallback + `parseStability`):
    //   1. `Nx-dev` / `N.x-dev` / `N.M.x-dev` — numeric-flavor
    //      branch alias (e.g. `3.x-dev`). `Version::parse`
    //      normalizes this to `N.9999999.9999999.9999999-dev`.
    //   2. `dev-<branch-name>` — bare branch reference (e.g.
    //      `dev-main`, `dev-feature/foo`). `Version::parse` keeps
    //      this as `VersionKind::Branch("<name>")`.
    // Both map to an `==` constraint against the same string
    // re-parsed as a Version — matches Composer's "operator `=`,
    // version normalized" handling. Composer matches `dev-`
    // case-insensitively (`stripos`/`/i` regex) so we do too.
    // Marked explicit-lower-bound so any same-numeric-prerelease
    // comparison falls through to standard ordering.
    let is_dev_branch = s.len() >= 4 && s.as_bytes()[..4].eq_ignore_ascii_case(b"dev-");
    if composer_semver_is_branch_alias(s) || is_dev_branch {
        let v = Version::parse(s).map_err(|e| ParseError::Invalid(format!("{token}: {e}")))?;
        return Ok(Constraint::Op {
            op: CmpOp::Eq,
            version: v,
            explicit_lower_bound: true,
        });
    }

    // Caret: `^X.Y.Z`
    if let Some(rest) = s.strip_prefix('^') {
        return parse_caret(rest.trim());
    }
    // Tilde: `~X.Y.Z`
    if let Some(rest) = s.strip_prefix('~') {
        return parse_tilde(rest.trim());
    }

    // Operators: `>=`, `<=`, `>`, `<`, `=`, `==`, `!=`, `<>`.
    for prefix in &[">=", "<=", "==", "!=", "<>", ">", "<", "="] {
        if let Some(rest) = s.strip_prefix(*prefix) {
            let op = match *prefix {
                ">=" => CmpOp::Ge,
                "<=" => CmpOp::Le,
                ">" => CmpOp::Gt,
                "<" => CmpOp::Lt,
                "==" | "=" => CmpOp::Eq,
                "!=" | "<>" => CmpOp::Ne,
                _ => unreachable!(),
            };
            let v = Version::parse(rest.trim())
                .map_err(|e| ParseError::Invalid(format!("{token}: {e}")))?;
            // Explicit lower bound iff the user wrote `>=`/`>` with
            // all three numeric segments. Three+ written segments
            // implies an intentional pre-release boundary; fewer
            // implies partial expansion semantics.
            let explicit_lower_bound =
                matches!(op, CmpOp::Ge | CmpOp::Gt) && wrote_full_version(rest.trim());
            return Ok(Constraint::Op {
                op,
                version: v,
                explicit_lower_bound,
            });
        }
    }

    // Wildcard inside a numeric expression: `1.2.*`, `2.x.x`,
    // `1.2.X`.
    if contains_wildcard(s) {
        return parse_wildcard(s);
    }

    // Bare partial or full version: `1.2.3` → ==, `1.2` → range
    // covering all of 1.2, `1` → range covering all of 1.
    match parse_partial_or_exact(s) {
        Ok(c) => Ok(c),
        Err(e) => {
            // Composer's `parseConstraint` "Basic Comparators"
            // fallback: if normalize fails AND the constraint ends
            // in `-dev` AND its body is "name-safe"
            // (`[0-9a-zA-Z-./]+`), retry as `dev-<body>`. This is
            // what makes `master-dev` work as a synonym for
            // `dev-master`. Only the constraint path does this —
            // `Version::normalize` itself rejects these.
            if let Some(body) = strip_dev_suffix(s) {
                if is_name_safe(body) {
                    if let Ok(v) = Version::parse(&format!("dev-{body}")) {
                        return Ok(Constraint::Op {
                            op: CmpOp::Eq,
                            version: v,
                            explicit_lower_bound: true,
                        });
                    }
                }
            }
            Err(e)
        }
    }
}

fn strip_dev_suffix(s: &str) -> Option<&str> {
    if s.len() >= 5 && s.as_bytes()[s.len() - 4..].eq_ignore_ascii_case(b"-dev") {
        Some(&s[..s.len() - 4])
    } else {
        None
    }
}

/// Composer's `{^[0-9a-zA-Z-./]+$}` gate on the `<name>-dev` recovery.
fn is_name_safe(s: &str) -> bool {
    !s.is_empty()
        && s.bytes()
            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'/'))
}

fn contains_wildcard(s: &str) -> bool {
    s.split('.').any(|p| matches!(p, "*" | "x" | "X"))
}

fn parse_caret(rest: &str) -> Result<Constraint, ParseError> {
    // The upper bound bumps the first element that is either non-zero
    // OR the last one the user actually wrote — Composer's
    // `parseCaretConstraint` position rule (VersionParser):
    //
    //   `^1.2.3` / `^1` / `^1.2` → `<2.0.0`   (major ≥ 1 → bump major)
    //   `^0`                     → `<1.0.0`   (minor unwritten → bump major)
    //   `^0.3` / `^0.3.0`        → `<0.4.0`   (minor non-zero → bump minor)
    //   `^0.0`                   → `<0.1.0`   (patch unwritten → bump minor)
    //   `^0.0.3`                 → `<0.0.4`   (patch non-zero → bump patch)
    //
    // The subtlety is the all-zeros prefix: which element is "fluid"
    // depends on how many were specified, not just on their values.
    // Treating bare `^0` as `^0.0.0` (the previous behavior) yielded
    // `<0.0.1`, which excludes every real 0.x release — exactly what
    // broke `openai-php/client: "^0"` in the Mage-OS graph.
    let segs = split_partial_numeric(rest)?;
    if segs.is_empty() {
        return Err(ParseError::Invalid(rest.to_owned()));
    }
    let major: u32 = segs[0].parse().unwrap_or(0);
    let minor: u32 = segs.get(1).and_then(|s| s.parse().ok()).unwrap_or(0);
    let minor_specified = segs.len() >= 2;
    let patch_specified = segs.len() >= 3;
    let lower = Version::parse(rest)
        .or_else(|_| Version::parse(&pad_partial(rest)))
        .map_err(|e| ParseError::Invalid(format!("^{rest}: {e}")))?;
    let upper_str = if major > 0 || !minor_specified {
        format!("{}.0.0.0", major + 1)
    } else if minor > 0 || !patch_specified {
        format!("0.{}.0.0", minor + 1)
    } else {
        // `^0.0.Z` → `>=0.0.Z, <0.0.Z+1` (only the patch is fluid).
        let patch: u32 = segs.get(2).and_then(|s| s.parse().ok()).unwrap_or(0);
        format!("0.0.{}.0", patch + 1)
    };
    let upper = Version::parse(&upper_str)
        .map_err(|e| ParseError::Invalid(format!("^{rest} upper: {e}")))?;
    // The caret's lower bound is "explicit" when the user wrote a
    // full X.Y.Z — that's when prereleases of X.Y.Z are admissible.
    let explicit_lower = wrote_full_version(rest);
    Ok(Constraint::And(vec![
        Constraint::Op {
            op: CmpOp::Ge,
            version: lower,
            explicit_lower_bound: explicit_lower,
        },
        Constraint::Op {
            op: CmpOp::Lt,
            version: upper,
            explicit_lower_bound: false,
        },
    ]))
}

fn parse_tilde(rest: &str) -> Result<Constraint, ParseError> {
    // `~X.Y.Z[-stab]` → `>=X.Y.Z[-stab], <X.Y+1.0`
    // `~X.Y`         → `>=X.Y.0, <X+1.0.0`     (major-floor)
    // `~X`           → `>=X.0.0, <X+1.0.0`
    let segs = split_partial_numeric(rest)?;
    if segs.is_empty() {
        return Err(ParseError::Invalid(rest.to_owned()));
    }
    let lower = Version::parse(rest)
        .or_else(|_| Version::parse(&pad_partial(rest)))
        .map_err(|e| ParseError::Invalid(format!("~{rest}: {e}")))?;
    let upper_str = match segs.len() {
        1 => {
            let major: u32 = segs[0].parse().unwrap_or(0);
            format!("{}.0.0.0", major + 1)
        }
        2 => {
            let major: u32 = segs[0].parse().unwrap_or(0);
            format!("{}.0.0.0", major + 1)
        }
        _ => {
            let major: u32 = segs[0].parse().unwrap_or(0);
            let minor: u32 = segs[1].parse().unwrap_or(0);
            format!("{}.{}.0.0", major, minor + 1)
        }
    };
    let upper = Version::parse(&upper_str)
        .map_err(|e| ParseError::Invalid(format!("~{rest} upper: {e}")))?;
    let explicit_lower = wrote_full_version(rest);
    Ok(Constraint::And(vec![
        Constraint::Op {
            op: CmpOp::Ge,
            version: lower,
            explicit_lower_bound: explicit_lower,
        },
        Constraint::Op {
            op: CmpOp::Lt,
            version: upper,
            explicit_lower_bound: false,
        },
    ]))
}

fn parse_wildcard(s: &str) -> Result<Constraint, ParseError> {
    // `1.2.*` → `>=1.2.0, <1.3.0`
    // `2.*.*` → `>=2.0.0, <3.0.0` (wildcard at position 1)
    // `2.x.x` → same as above
    let parts: Vec<&str> = s.split('.').collect();
    // The position of the FIRST wildcard determines the floor.
    let first_wild = parts
        .iter()
        .position(|p| matches!(*p, "*" | "x" | "X"))
        .ok_or_else(|| ParseError::Invalid(s.to_owned()))?;
    let numeric_prefix: Vec<u32> = parts[..first_wild]
        .iter()
        .map(|p| p.parse().unwrap_or(0))
        .collect();
    let lower_segs: Vec<String> = numeric_prefix
        .iter()
        .map(u32::to_string)
        .chain(std::iter::repeat_n(
            "0".to_owned(),
            4usize.saturating_sub(first_wild),
        ))
        .collect();
    let lower = Version::parse(&lower_segs.join("."))
        .map_err(|e| ParseError::Invalid(format!("{s} lower: {e}")))?;

    let mut upper_segs = numeric_prefix.clone();
    if first_wild == 0 {
        // `*` alone → Any.
        return Ok(Constraint::Any);
    }
    *upper_segs.last_mut().unwrap() += 1;
    let upper_str: String = upper_segs
        .iter()
        .map(u32::to_string)
        .chain(std::iter::repeat_n(
            "0".to_owned(),
            4usize.saturating_sub(upper_segs.len()),
        ))
        .collect::<Vec<_>>()
        .join(".");
    let upper =
        Version::parse(&upper_str).map_err(|e| ParseError::Invalid(format!("{s} upper: {e}")))?;
    Ok(Constraint::And(vec![
        Constraint::Op {
            op: CmpOp::Ge,
            version: lower,
            explicit_lower_bound: false,
        },
        Constraint::Op {
            op: CmpOp::Lt,
            version: upper,
            explicit_lower_bound: false,
        },
    ]))
}

fn parse_partial_or_exact(s: &str) -> Result<Constraint, ParseError> {
    // Strip build metadata (`+...`) — Composer accepts it on
    // constraint atoms and ignores it for matching.
    let cleaned = s.split_once('+').map_or(s, |(left, _)| left);
    let segs = split_partial_numeric(cleaned)?;
    if segs.len() >= 3 {
        // Fully qualified → exact match (==). Exact equality with a
        // full version is intentionally "explicit" too — the user
        // pinned the version on the nose.
        let v = Version::parse(cleaned).map_err(|e| ParseError::Invalid(format!("{s}: {e}")))?;
        return Ok(Constraint::Op {
            op: CmpOp::Eq,
            version: v,
            explicit_lower_bound: true,
        });
    }
    // Partial — expand into a wildcard-style range.
    // `1.2` → `>=1.2.0, <1.3.0`
    // `1`   → `>=1.0.0, <2.0.0`
    let major: u32 = segs[0].parse().unwrap_or(0);
    let lower_str = pad_partial(cleaned);
    let lower =
        Version::parse(&lower_str).map_err(|e| ParseError::Invalid(format!("{s} lower: {e}")))?;
    let upper_str = if segs.len() == 1 {
        format!("{}.0.0.0", major + 1)
    } else {
        let minor: u32 = segs[1].parse().unwrap_or(0);
        format!("{}.{}.0.0", major, minor + 1)
    };
    let upper =
        Version::parse(&upper_str).map_err(|e| ParseError::Invalid(format!("{s} upper: {e}")))?;
    Ok(Constraint::And(vec![
        Constraint::Op {
            op: CmpOp::Ge,
            version: lower,
            explicit_lower_bound: false,
        },
        Constraint::Op {
            op: CmpOp::Lt,
            version: upper,
            explicit_lower_bound: false,
        },
    ]))
}

// ---- helpers -----------------------------------------------------------

/// True iff `s` looks like a full Composer version (three or more
/// numeric segments before any stability/build tail). Used to decide
/// whether a constraint's lower bound is "explicit" enough to admit
/// same-numeric prereleases.
fn wrote_full_version(s: &str) -> bool {
    let s = s.trim();
    let s = s.strip_prefix(['v', 'V']).unwrap_or(s);
    let body = s.split_once(['-', '+']).map_or(s, |(left, _)| left);
    let segs: Vec<&str> = body.split('.').filter(|p| !p.is_empty()).collect();
    segs.len() >= 3 && segs.iter().all(|p| p.chars().all(|c| c.is_ascii_digit()))
}

fn split_partial_numeric(s: &str) -> Result<Vec<String>, ParseError> {
    let cleaned = s
        .strip_prefix(['v', 'V'])
        .unwrap_or(s)
        .split_once('-')
        .map_or(s.strip_prefix(['v', 'V']).unwrap_or(s), |(left, _)| left);
    let segs: Vec<String> = cleaned
        .split('.')
        .filter(|p| !p.is_empty())
        .map(str::to_owned)
        .collect();
    if segs.is_empty() {
        return Err(ParseError::Invalid(s.to_owned()));
    }
    // Ensure leading segment is numeric (rejects garbage like
    // `>=abc`).
    if !segs[0].chars().all(|c| c.is_ascii_digit()) {
        return Err(ParseError::Invalid(s.to_owned()));
    }
    Ok(segs)
}

fn split_partial_segments(s: &str) -> Vec<String> {
    let stripped = s.strip_prefix(['v', 'V']).unwrap_or(s);
    let cleaned = stripped.split_once('-').map_or(stripped, |(left, _)| left);
    cleaned
        .split('.')
        .filter(|p| !p.is_empty())
        .map(str::to_owned)
        .collect()
}

/// Pad a partial numeric to 4 segments with `"0"` and reattach any
/// stability suffix.
fn pad_partial(s: &str) -> String {
    let stripped = s.strip_prefix(['v', 'V']).unwrap_or(s);
    let (body, tail) = match stripped.split_once('-') {
        Some((b, t)) => (b, format!("-{t}")),
        None => (stripped, String::new()),
    };
    let segs: Vec<&str> = body.split('.').filter(|p| !p.is_empty()).collect();
    let mut padded: Vec<String> = segs.iter().map(|p| (*p).to_owned()).collect();
    while padded.len() < 4 {
        padded.push("0".to_owned());
    }
    format!("{}{}", padded.join("."), tail)
}

fn pad_segments_with(mut segs: Vec<String>, pad: &str, target: usize) -> Vec<String> {
    while segs.len() < target {
        segs.push(pad.to_owned());
    }
    segs
}

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

    /// Caret on all-zero / partial-zero versions follows Composer's
    /// position rule: the bumped element depends on what was written,
    /// not just on the values. Regression for `openai-php/client: "^0"`
    /// in the Mage-OS graph, which the old `^0 == ^0.0.0` shortcut
    /// turned into `<0.0.1` — excluding every published 0.x release.
    #[test]
    fn caret_zero_partial_versions_match_composer() {
        // `^0` admits the whole 0.x line, up to (not incl.) 1.0.0.
        let c = Constraint::parse("^0").unwrap();
        assert!(c.matches(&Version::parse("0.0.1").unwrap()));
        assert!(c.matches(&Version::parse("0.19.2").unwrap()));
        assert!(!c.matches(&Version::parse("1.0.0").unwrap()));

        // `^0.0` → `<0.1.0` (patch unwritten → bump minor).
        let c = Constraint::parse("^0.0").unwrap();
        assert!(c.matches(&Version::parse("0.0.9").unwrap()));
        assert!(!c.matches(&Version::parse("0.1.0").unwrap()));

        // `^0.3` → `<0.4.0` (minor non-zero → bump minor).
        let c = Constraint::parse("^0.3").unwrap();
        assert!(c.matches(&Version::parse("0.3.7").unwrap()));
        assert!(!c.matches(&Version::parse("0.4.0").unwrap()));

        // `^0.0.3` → `<0.0.4` (patch non-zero → bump patch).
        let c = Constraint::parse("^0.0.3").unwrap();
        assert!(c.matches(&Version::parse("0.0.3").unwrap()));
        assert!(!c.matches(&Version::parse("0.0.4").unwrap()));

        // `^1` is unchanged: `<2.0.0`.
        let c = Constraint::parse("^1").unwrap();
        assert!(c.matches(&Version::parse("1.9.9").unwrap()));
        assert!(!c.matches(&Version::parse("2.0.0").unwrap()));
    }

    /// Composer accepts `Nx-dev` / `N.x-dev` / `N.M.x-dev` as
    /// constraint strings meaning "exactly the named dev branch."
    /// They parse to an `==` constraint against the same string
    /// re-parsed as a Version (which already canonicalizes
    /// `3.x-dev` into `3.9999999.9999999.9999999-dev`).
    #[test]
    fn nx_dev_constraint_matches_same_branch_version() {
        let c = Constraint::parse("3.x-dev").unwrap();
        let v = Version::parse("3.x-dev").unwrap();
        assert!(c.matches(&v), "got constraint {c:?}");
    }

    #[test]
    fn nx_dev_constraint_rejects_other_major_branch() {
        let c = Constraint::parse("3.x-dev").unwrap();
        let other = Version::parse("2.x-dev").unwrap();
        assert!(!c.matches(&other), "got constraint {c:?}");
    }

    #[test]
    fn nx_dev_constraint_rejects_stable_release() {
        // `3.x-dev` is the exact dev branch; a stable `3.0.0` does
        // not satisfy it.
        let c = Constraint::parse("3.x-dev").unwrap();
        let stable = Version::parse("3.0.0").unwrap();
        assert!(!c.matches(&stable), "got constraint {c:?}");
    }

    #[test]
    fn n_dot_x_dev_handles_two_segment_form() {
        let c = Constraint::parse("1.x-dev").unwrap();
        let v = Version::parse("1.x-dev").unwrap();
        assert!(c.matches(&v));
    }

    #[test]
    fn n_dot_m_dot_x_dev_handles_three_segment_form() {
        // `1.0.x-dev` parses to `1.0.9999999.9999999-dev`.
        let c = Constraint::parse("1.0.x-dev").unwrap();
        let v = Version::parse("1.0.x-dev").unwrap();
        assert!(c.matches(&v));
    }

    #[test]
    fn dev_branch_constraint_matches_named_branch() {
        // `"dep": "dev-main"` is the bare branch form — pinned to
        // the named branch. Parses to `==` against
        // `Version::Branch("main")`.
        let c = Constraint::parse("dev-main").unwrap();
        let v = Version::parse("dev-main").unwrap();
        assert!(c.matches(&v), "constraint {c:?} should match {v:?}");
    }

    #[test]
    fn dev_branch_constraint_rejects_other_branches() {
        let c = Constraint::parse("dev-main").unwrap();
        let other = Version::parse("dev-feature-x").unwrap();
        assert!(!c.matches(&other));
    }

    #[test]
    fn name_dash_dev_suffix_is_synonym_for_dev_dash_name() {
        // Composer's `parseConstraint` (NOT `normalize`) recovers
        // `master-dev` as a synonym for `dev-master` via the
        // catch-block fallback. Char class: `[0-9a-zA-Z-./]+`.
        let c = Constraint::parse("master-dev").unwrap();
        let v = Version::parse("dev-master").unwrap();
        assert!(c.matches(&v), "constraint {c:?} should match {v:?}");
    }

    #[test]
    fn name_dash_dev_rejects_unsafe_chars() {
        // Bodies with characters outside Composer's recovery
        // char-class (`[0-9a-zA-Z-./]+`) must still fail.
        assert!(Constraint::parse("foo bar-dev").is_err());
        assert!(Constraint::parse("1.0.0<1.0.5-dev").is_err());
    }

    #[test]
    fn name_dash_dev_does_not_swallow_numeric_dev_versions() {
        // `1.0.0-dev` is a Dev-stability classical version handled
        // by `parse_partial_or_exact`, not the recovery path.
        let c = Constraint::parse("1.0.0-dev").unwrap();
        let v = Version::parse("1.0.0-dev").unwrap();
        assert!(c.matches(&v));
    }

    // ---- lower_bound / intersects (platform_check substrate) ----------

    fn lb(s: &str) -> (String, bool) {
        let b = Constraint::parse(s).unwrap().lower_bound();
        (b.version().to_owned(), b.is_inclusive())
    }

    #[test]
    fn lower_bound_atomic_ops() {
        assert_eq!(lb(">=8.1"), ("8.1.0.0".to_owned(), true));
        assert_eq!(lb(">8.0"), ("8.0.0.0".to_owned(), false));
        assert_eq!(lb("8.1.2"), ("8.1.2.0".to_owned(), true)); // == form
        // Upper-only / negation constraints floor at zero.
        assert!(Constraint::parse("<8.0").unwrap().lower_bound().is_zero());
        assert!(Constraint::parse("!=8.0").unwrap().lower_bound().is_zero());
        assert!(Constraint::parse("*").unwrap().lower_bound().is_zero());
    }

    #[test]
    fn lower_bound_caret_tilde_take_the_floor() {
        // Caret/tilde are conjunctive ranges; the lower bound is the
        // written floor, inclusive. Matches Composer's platform check
        // emitting `PHP_VERSION_ID >= 80100` for `^8.1`.
        assert_eq!(lb("^8.1"), ("8.1.0.0".to_owned(), true));
        assert_eq!(lb("~8.2.3"), ("8.2.3.0".to_owned(), true));
        assert_eq!(lb("^8"), ("8.0.0.0".to_owned(), true));
    }

    #[test]
    fn lower_bound_conjunction_takes_the_greater() {
        // `>=7.4 <8.3` → floor is 7.4 (the `<8.3` clause contributes a
        // zero lower bound, which loses).
        assert_eq!(lb(">=7.4 <8.3"), ("7.4.0.0".to_owned(), true));
    }

    #[test]
    fn lower_bound_disjunction_takes_the_least() {
        // `^7.4 || ^8.0` → floor is the lower alternative, 7.4.
        assert_eq!(lb("^7.4 || ^8.0"), ("7.4.0.0".to_owned(), true));
    }

    #[test]
    fn intersects_any_provider_matches_everything() {
        // A polyfill that `provide`s `ext-x: *` covers any requirement.
        let provided = Constraint::parse("*").unwrap();
        assert!(provided.intersects(&Constraint::parse("^2.0").unwrap()));
        assert!(provided.intersects(&Constraint::parse("*").unwrap()));
    }

    #[test]
    fn intersects_overlapping_and_disjoint_ranges() {
        let p = Constraint::parse("^1.0").unwrap();
        assert!(p.intersects(&Constraint::parse(">=1.5").unwrap())); // overlap
        assert!(!p.intersects(&Constraint::parse("^2.0").unwrap())); // disjoint
        // Touching at an inclusive/exclusive boundary: `<2.0` and
        // `>=2.0` do not overlap (`^1.0` upper is exclusive 2.0).
        assert!(!p.intersects(&Constraint::parse(">=2.0").unwrap()));
    }

    #[test]
    fn intersects_disjunction_member_overlap() {
        let provided = Constraint::parse("^1.0 || ^3.0").unwrap();
        assert!(provided.intersects(&Constraint::parse("^3.1").unwrap()));
        assert!(!provided.intersects(&Constraint::parse("^2.0").unwrap()));
    }

    #[test]
    fn dev_branch_constraint_handles_slashed_branch_name() {
        // Composer accepts branch names with slashes
        // (e.g. `dev-fix/some-bug`). Parses through Version::parse,
        // which preserves the branch body verbatim.
        let c = Constraint::parse("dev-fix/some-bug").unwrap();
        let v = Version::parse("dev-fix/some-bug").unwrap();
        assert!(c.matches(&v));
    }
}