-- SPDX-FileCopyrightText: 2026 Alexandra de Wit
--
-- SPDX-License-Identifier: MIT

{- | The @Gem::Version@ grammar and ordering (RubyGems).

'parseGem' keys a version as a flat 'VToken' list canonicalised the way
@Gem::Version#canonical_segments@ is, so @2.0.a@ keys as @[2, "a"]@ and @1.a.0.b@ as
@[1, "a", "b"]@. Comparison zero-pads the shorter side, and a 'VStr' ranks below @VNum 0@ (see
"Ecluse.Core.Version.Token"), so a trailing letter segment sorts below the bare release.
-}
module Ecluse.Core.Version.Gem (
    GemKey (..),
    parseGem,
    renderGem,
    isGemStable,
    isGemRequirementOperator,
) where

import Data.List (dropWhileEnd)
import Data.Text qualified as T

import Ecluse.Core.Strict (strictElements)
import Ecluse.Core.Text (isAsciiAlphaNum)
import Ecluse.Core.Version.Token (VToken (..), classifyRun, digitRuns, renderToken, withinVersionLength)

-- | A parsed @Gem::Version@: a flat token list compared with zero-padding.
newtype GemKey = GemKey [VToken]
    deriving stock (GemKey -> GemKey -> Bool
(GemKey -> GemKey -> Bool)
-> (GemKey -> GemKey -> Bool) -> Eq GemKey
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: GemKey -> GemKey -> Bool
== :: GemKey -> GemKey -> Bool
$c/= :: GemKey -> GemKey -> Bool
/= :: GemKey -> GemKey -> Bool
Eq, Int -> GemKey -> ShowS
[GemKey] -> ShowS
GemKey -> String
(Int -> GemKey -> ShowS)
-> (GemKey -> String) -> ([GemKey] -> ShowS) -> Show GemKey
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> GemKey -> ShowS
showsPrec :: Int -> GemKey -> ShowS
$cshow :: GemKey -> String
show :: GemKey -> String
$cshowList :: [GemKey] -> ShowS
showList :: [GemKey] -> ShowS
Show)

instance Ord GemKey where
    compare :: GemKey -> GemKey -> Ordering
compare (GemKey [VToken]
a) (GemKey [VToken]
b) = [VToken] -> [VToken] -> Ordering
compareGemTokens [VToken]
a [VToken]
b

-- | Parse and settle canonical tokens, refusing empty or non-alphanumeric segments.
parseGem :: Text -> Maybe GemKey
parseGem :: Text -> Maybe GemKey
parseGem Text
raw = do
    Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Text -> Bool
withinVersionLength Text
raw)
    let stripped :: Text
stripped = Text -> Text
T.strip Text
raw
        -- Gem::Version canonicalises hyphens via a global gsub("-", ".pre.") before segmenting,
        -- so "1.0.0-1" is the prerelease "1.0.0.pre.1" and orders below "1.0.0".
        segs :: [Text]
segs = HasCallStack => Text -> Text -> [Text]
Text -> Text -> [Text]
T.splitOn Text
"." (HasCallStack => Text -> Text -> Text -> Text
Text -> Text -> Text -> Text
T.replace Text
"-" Text
".pre." Text
stripped)
    Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Bool -> Bool
not (Text -> Bool
T.null Text
stripped))
    Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard ((Text -> Bool) -> [Text] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all Text -> Bool
validSeg [Text]
segs)
    GemKey -> Maybe GemKey
forall a. a -> Maybe a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([VToken] -> GemKey
GemKey ([VToken] -> [VToken]
forall (t :: * -> *) a. Foldable t => t a -> t a
strictElements ([[VToken]] -> [VToken]
canonicalSegments ((Text -> [VToken]) -> [Text] -> [[VToken]]
forall a b. (a -> b) -> [a] -> [b]
map Text -> [VToken]
segTokens [Text]
segs))))
  where
    validSeg :: Text -> Bool
validSeg Text
s = Bool -> Bool
not (Text -> Bool
T.null Text
s) Bool -> Bool -> Bool
&& (Char -> Bool) -> Text -> Bool
T.all Char -> Bool
isAsciiAlphaNum Text
s
    segTokens :: Text -> [VToken]
segTokens = (Text -> VToken) -> [Text] -> [VToken]
forall a b. (a -> b) -> [a] -> [b]
map Text -> VToken
classifyRun ([Text] -> [VToken]) -> (Text -> [Text]) -> Text -> [VToken]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> [Text]
digitRuns

{- | Render canonical Gem tokens, using @0@ for an all-zero release. A key that keeps a zero before a
letter spells its first letter after a zero, which 'parseGem' drops again.
-}
renderGem :: GemKey -> Text
renderGem :: GemKey -> Text
renderGem (GemKey []) = Text
"0"
renderGem (GemKey [VToken]
tokens) = Text -> [Text] -> Text
T.intercalate Text
"." ((VToken -> Text) -> [VToken] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map VToken -> Text
renderToken (if [VToken] -> Bool
zeroBeforeLetter [VToken]
tokens then [VToken]
release [VToken] -> [VToken] -> [VToken]
forall a. Semigroup a => a -> a -> a
<> (Integer -> VToken
VNum Integer
0 VToken -> [VToken] -> [VToken]
forall a. a -> [a] -> [a]
: [VToken]
prerelease) else [VToken]
tokens))
  where
    ([VToken]
release, [VToken]
prerelease) = (VToken -> Bool) -> [VToken] -> ([VToken], [VToken])
forall a. (a -> Bool) -> [a] -> ([a], [a])
span VToken -> Bool
isNumeric [VToken]
tokens

-- | Whether a gem version is stable: every token is numeric, so no prerelease marker.
isGemStable :: GemKey -> Bool
isGemStable :: GemKey -> Bool
isGemStable (GemKey [VToken]
toks) = (VToken -> Bool) -> [VToken] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all VToken -> Bool
isNumeric [VToken]
toks

{- | Whether a @Gem::Requirement@ clause may use this comparison operator. INLINE keeps the
literals at each call site, because a shared operator list allocates on every parsed clause.
-}
isGemRequirementOperator :: Text -> Bool
isGemRequirementOperator :: Text -> Bool
isGemRequirementOperator Text
operator = Text
operator Text -> [Text] -> Bool
forall (f :: * -> *) a.
(Foldable f, DisallowElem f, Eq a) =>
a -> f a -> Bool
`elem` [Text
"=", Text
"!=", Text
">", Text
"<", Text
">=", Text
"<=", Text
"~>"]
{-# INLINE isGemRequirementOperator #-}

-- Compare gem token lists, zero-padding the shorter side.
compareGemTokens :: [VToken] -> [VToken] -> Ordering
compareGemTokens :: [VToken] -> [VToken] -> Ordering
compareGemTokens [] [] = Ordering
EQ
compareGemTokens (VToken
x : [VToken]
xs) (VToken
y : [VToken]
ys) = VToken -> VToken -> Ordering
forall a. Ord a => a -> a -> Ordering
compare VToken
x VToken
y Ordering -> Ordering -> Ordering
forall a. Semigroup a => a -> a -> a
<> [VToken] -> [VToken] -> Ordering
compareGemTokens [VToken]
xs [VToken]
ys
compareGemTokens (VToken
x : [VToken]
xs) [] = VToken -> VToken -> Ordering
forall a. Ord a => a -> a -> Ordering
compare VToken
x (Integer -> VToken
VNum Integer
0) Ordering -> Ordering -> Ordering
forall a. Semigroup a => a -> a -> a
<> [VToken] -> [VToken] -> Ordering
compareGemTokens [VToken]
xs []
compareGemTokens [] (VToken
y : [VToken]
ys) = VToken -> VToken -> Ordering
forall a. Ord a => a -> a -> Ordering
compare (Integer -> VToken
VNum Integer
0) VToken
y Ordering -> Ordering -> Ordering
forall a. Semigroup a => a -> a -> a
<> [VToken] -> [VToken] -> Ordering
compareGemTokens [] [VToken]
ys

{- Gem::Version#canonical_segments drops the trailing zeros, and the first run of zeros that starts
a segment and directly precedes a letter, wherever that run falls. -}
canonicalSegments :: [[VToken]] -> [VToken]
canonicalSegments :: [[VToken]] -> [VToken]
canonicalSegments = (VToken -> Bool) -> [VToken] -> [VToken]
forall a. (a -> Bool) -> [a] -> [a]
dropWhileEnd (VToken -> VToken -> Bool
forall a. Eq a => a -> a -> Bool
== Integer -> VToken
VNum Integer
0) ([VToken] -> [VToken])
-> ([[VToken]] -> [VToken]) -> [[VToken]] -> [VToken]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> [[VToken]] -> [VToken]
go Int
0
  where
    -- The count is the zero segments of the run so far, kept unless a letter follows them.
    go :: Int -> [[VToken]] -> [VToken]
    go :: Int -> [[VToken]] -> [VToken]
go Int
zeros = \case
        (VNum Integer
0 : letters :: [VToken]
letters@(VStr Text
_ : [VToken]
_)) : [[VToken]]
rest -> [VToken]
letters [VToken] -> [VToken] -> [VToken]
forall a. Semigroup a => a -> a -> a
<> [[VToken]] -> [VToken]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat [[VToken]]
rest
        [VNum Integer
0] : [[VToken]]
rest -> Int -> [[VToken]] -> [VToken]
go (Int
zeros Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1) [[VToken]]
rest
        rest :: [[VToken]]
rest@((VStr Text
_ : [VToken]
_) : [[VToken]]
_) | Int
zeros Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
0 -> [[VToken]] -> [VToken]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat [[VToken]]
rest
        [VToken]
segment : [[VToken]]
rest -> Int -> VToken -> [VToken]
forall a. Int -> a -> [a]
replicate Int
zeros (Integer -> VToken
VNum Integer
0) [VToken] -> [VToken] -> [VToken]
forall a. Semigroup a => a -> a -> a
<> [VToken]
segment [VToken] -> [VToken] -> [VToken]
forall a. Semigroup a => a -> a -> a
<> Int -> [[VToken]] -> [VToken]
go Int
0 [[VToken]]
rest
        [] -> Int -> VToken -> [VToken]
forall a. Int -> a -> [a]
replicate Int
zeros (Integer -> VToken
VNum Integer
0)

-- Whether a zero directly precedes a letter, which a plain dotted spelling would let parsing drop.
zeroBeforeLetter :: [VToken] -> Bool
zeroBeforeLetter :: [VToken] -> Bool
zeroBeforeLetter [VToken]
tokens = [Bool] -> Bool
forall (t :: * -> *). Foldable t => t Bool -> Bool
or ((VToken -> VToken -> Bool) -> [VToken] -> [VToken] -> [Bool]
forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
zipWith (\VToken
token VToken
next -> VToken
token VToken -> VToken -> Bool
forall a. Eq a => a -> a -> Bool
== Integer -> VToken
VNum Integer
0 Bool -> Bool -> Bool
&& Bool -> Bool
not (VToken -> Bool
isNumeric VToken
next)) [VToken]
tokens (Int -> [VToken] -> [VToken]
forall a. Int -> [a] -> [a]
drop Int
1 [VToken]
tokens))

isNumeric :: VToken -> Bool
isNumeric :: VToken -> Bool
isNumeric = \case
    VNum Integer
_ -> Bool
True
    VStr Text
_ -> Bool
False