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

{- | The semver grammar and ordering (npm).
'SemverKey' wraps the [@versions@](https://hackage.haskell.org/package/versions) library's
'Data.Versions.SemVer', so precedence is the library's: semver 11 ordering, with @+build@
metadata excluded from it. 'parseSemver' scans the grammar itself. Within the length and
digit-run bounds it accepts and builds what the library's parser does. Among prerelease
identifiers numeric ones rank below alphanumeric ones, the opposite of the rule in
"Ecluse.Core.Version.Token".
-}
module Ecluse.Core.Version.Semver (
    SemverKey (..),
    parseSemver,
    renderSemver,
    isSemverStable,
) where

import Data.Char (isAlpha, isAlphaNum, isDigit)
import Data.List.NonEmpty qualified as NE
import Data.Text qualified as T
import Data.Versions (Chunk (..), Release (..), SemVer (..))

import Ecluse.Core.Version.Token (withinVersionLength)

-- | A parsed semver version, ordered by the @versions@ library's semver 11 precedence.
newtype SemverKey = SemverKey SemVer
    deriving stock (Int -> SemverKey -> ShowS
[SemverKey] -> ShowS
SemverKey -> String
(Int -> SemverKey -> ShowS)
-> (SemverKey -> String)
-> ([SemverKey] -> ShowS)
-> Show SemverKey
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> SemverKey -> ShowS
showsPrec :: Int -> SemverKey -> ShowS
$cshow :: SemverKey -> String
show :: SemverKey -> String
$cshowList :: [SemverKey] -> ShowS
showList :: [SemverKey] -> ShowS
Show)
    deriving newtype (SemverKey -> SemverKey -> Bool
(SemverKey -> SemverKey -> Bool)
-> (SemverKey -> SemverKey -> Bool) -> Eq SemverKey
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: SemverKey -> SemverKey -> Bool
== :: SemverKey -> SemverKey -> Bool
$c/= :: SemverKey -> SemverKey -> Bool
/= :: SemverKey -> SemverKey -> Bool
Eq, Eq SemverKey
Eq SemverKey =>
(SemverKey -> SemverKey -> Ordering)
-> (SemverKey -> SemverKey -> Bool)
-> (SemverKey -> SemverKey -> Bool)
-> (SemverKey -> SemverKey -> Bool)
-> (SemverKey -> SemverKey -> Bool)
-> (SemverKey -> SemverKey -> SemverKey)
-> (SemverKey -> SemverKey -> SemverKey)
-> Ord SemverKey
SemverKey -> SemverKey -> Bool
SemverKey -> SemverKey -> Ordering
SemverKey -> SemverKey -> SemverKey
forall a.
Eq a =>
(a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
$ccompare :: SemverKey -> SemverKey -> Ordering
compare :: SemverKey -> SemverKey -> Ordering
$c< :: SemverKey -> SemverKey -> Bool
< :: SemverKey -> SemverKey -> Bool
$c<= :: SemverKey -> SemverKey -> Bool
<= :: SemverKey -> SemverKey -> Bool
$c> :: SemverKey -> SemverKey -> Bool
> :: SemverKey -> SemverKey -> Bool
$c>= :: SemverKey -> SemverKey -> Bool
>= :: SemverKey -> SemverKey -> Bool
$cmax :: SemverKey -> SemverKey -> SemverKey
max :: SemverKey -> SemverKey -> SemverKey
$cmin :: SemverKey -> SemverKey -> SemverKey
min :: SemverKey -> SemverKey -> SemverKey
Ord)

-- | Parse a semver version, or 'Nothing' so an ordering rule abstains rather than drops it. The digit-run bound keeps each number within the key's fixed-width components.
parseSemver :: Text -> Maybe SemverKey
parseSemver :: Text -> Maybe SemverKey
parseSemver Text
raw = do
    Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Text -> Bool
withinVersionLength Text
raw)
    Text -> Maybe SemverKey
plainRelease Text
raw Maybe SemverKey -> Maybe SemverKey -> Maybe SemverKey
forall a. Maybe a -> Maybe a -> Maybe a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> do
        Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Bool -> Bool
not (Text -> Bool
hasOverlongNumericRun Text
raw))
        -- Evaluated in full, so a retained key holds no thunk over the scan.
        SemVer -> SemverKey
SemverKey (SemVer -> SemverKey) -> (SemVer -> SemVer) -> SemVer -> SemverKey
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SemVer -> SemVer
forall a. NFData a => a -> a
force (SemVer -> SemverKey) -> Maybe SemVer -> Maybe SemverKey
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Text -> Maybe SemVer
scanSemver Text
raw

-- | Render every semver field, including build metadata excluded from precedence.
renderSemver :: SemverKey -> Text
renderSemver :: SemverKey -> Text
renderSemver (SemverKey (SemVer Word
major Word
minor Word
patch Maybe Release
prerelease Maybe Text
build)) =
    Text -> [Text] -> Text
T.intercalate Text
"." ((Word -> Text) -> [Word] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map Word -> Text
forall b a. (Show a, IsString b) => a -> b
show [Word
major, Word
minor, Word
patch])
        Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text -> (Release -> Text) -> Maybe Release -> Text
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Text
"" (\(Release NonEmpty Chunk
chunks) -> Text
"-" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text -> [Text] -> Text
T.intercalate Text
"." ((Chunk -> Text) -> [Chunk] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map Chunk -> Text
renderChunk (NonEmpty Chunk -> [Chunk]
forall a. NonEmpty a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList NonEmpty Chunk
chunks))) Maybe Release
prerelease
        Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text -> (Text -> Text) -> Maybe Text -> Text
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Text
"" (Text
"+" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<>) Maybe Text
build

renderChunk :: Chunk -> Text
renderChunk :: Chunk -> Text
renderChunk = \case
    Numeric Word
n -> Word -> Text
forall b a. (Show a, IsString b) => a -> b
show Word
n
    Alphanum Text
t -> Text
t

-- | Whether a semver version is stable: a final release with no prerelease component.
isSemverStable :: SemverKey -> Bool
isSemverStable :: SemverKey -> Bool
isSemverStable (SemverKey SemVer
sv) = Maybe Release -> Bool
forall a. Maybe a -> Bool
isNothing (SemVer -> Maybe Release
_svPreRel SemVer
sv)

-- 18 digits fit the library's fixed-width numeric components on every supported platform.
maxNumericRun :: Int
maxNumericRun :: Int
maxNumericRun = Int
18

hasOverlongNumericRun :: Text -> Bool
hasOverlongNumericRun :: Text -> Bool
hasOverlongNumericRun Text
raw = (Int -> Char -> Int) -> Int -> Text -> Int
forall a. (a -> Char -> a) -> a -> Text -> a
T.foldl' Int -> Char -> Int
runLength Int
0 Text
raw Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
maxNumericRun
  where
    -- The length of the digit run that ends at this character, held once it passes the bound.
    runLength :: Int -> Char -> Int
runLength Int
run Char
c
        | Int
run Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
maxNumericRun = Int
run
        | Char -> Bool
isDigit Char
c = Int
run Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1
        | Bool
otherwise = Int
0

-- Three dot-separated numbers and nothing else, the common spelling, in one pass that allocates
-- only the key. 'scanSemver' reads every other spelling.
plainRelease :: Text -> Maybe SemverKey
plainRelease :: Text -> Maybe SemverKey
plainRelease Text
raw = case (PlainScan -> Char -> PlainScan) -> PlainScan -> Text -> PlainScan
forall a. (a -> Char -> a) -> a -> Text -> a
T.foldl' PlainScan -> Char -> PlainScan
plainStep (Int -> Int -> Word -> Word -> Word -> PlainScan
PlainScan Int
0 Int
0 Word
0 Word
0 Word
0) Text
raw of
    PlainScan Int
2 Int
digits Word
major Word
minor Word
patch | Int
digits Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
0 -> SemverKey -> Maybe SemverKey
forall a. a -> Maybe a
Just (SemVer -> SemverKey
SemverKey (Word -> Word -> Word -> Maybe Release -> Maybe Text -> SemVer
SemVer Word
major Word
minor Word
patch Maybe Release
forall a. Maybe a
Nothing Maybe Text
forall a. Maybe a
Nothing))
    PlainScan
_ -> Maybe SemverKey
forall a. Maybe a
Nothing

{- A plain-release scan: the dots passed, or 'plainRefused', the digits of the number being read,
the numbers before the first and the second dot, and the value of the number being read. -}
data PlainScan = PlainScan Int Int Word Word Word

plainRefused :: Int
plainRefused :: Int
plainRefused = -Int
1

-- Inlined into the fold, so the scan passes between characters without a heap object.
plainStep :: PlainScan -> Char -> PlainScan
plainStep :: PlainScan -> Char -> PlainScan
plainStep (PlainScan Int
dots Int
digits Word
major Word
minor Word
value) Char
c
    | Int
dots Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
plainRefused = PlainScan
refused
    | Char -> Bool
isDigit Char
c Bool -> Bool -> Bool
&& Int
digits Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
maxNumericRun Bool -> Bool -> Bool
&& Bool -> Bool
not Bool
leadingZero = Int -> Int -> Word -> Word -> Word -> PlainScan
PlainScan Int
dots (Int
digits Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1) Word
major Word
minor (Word -> Char -> Word
addDigit Word
value Char
c)
    | Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'.' Bool -> Bool -> Bool
&& Int
digits Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
0 Bool -> Bool -> Bool
&& Int
dots Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
0 = Int -> Int -> Word -> Word -> Word -> PlainScan
PlainScan Int
1 Int
0 Word
value Word
0 Word
0
    | Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'.' Bool -> Bool -> Bool
&& Int
digits Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
0 Bool -> Bool -> Bool
&& Int
dots Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
1 = Int -> Int -> Word -> Word -> Word -> PlainScan
PlainScan Int
2 Int
0 Word
major Word
value Word
0
    | Bool
otherwise = PlainScan
refused
  where
    refused :: PlainScan
refused = Int -> Int -> Word -> Word -> Word -> PlainScan
PlainScan Int
plainRefused Int
0 Word
0 Word
0 Word
0
    -- A number that has read @0@ takes no further digit.
    leadingZero :: Bool
leadingZero = Int
digits Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
0 Bool -> Bool -> Bool
&& Word
value Word -> Word -> Bool
forall a. Eq a => a -> a -> Bool
== Word
0
{-# INLINE plainStep #-}

-- The grammar of the library's @semver@ parser, in that parser's order. @SemverSpec@ checks the
-- two against each other.
scanSemver :: Text -> Maybe SemVer
scanSemver :: Text -> Maybe SemVer
scanSemver Text
raw = do
    (major, afterMajor) <- Text -> Maybe (Word, Text)
leadingNumber Text
raw
    (minor, afterMinor) <- leadingNumber =<< afterChar '.' afterMajor
    (patch, afterPatch) <- leadingNumber =<< afterChar '.' afterMinor
    (preRel, afterPreRel) <- markedPart '-' identifiers afterPatch
    (meta, afterMeta) <- markedPart '+' buildMetadata afterPreRel
    guard (T.null afterMeta)
    pure (SemVer major minor patch (Release <$> preRel) meta)

afterChar :: Char -> Text -> Maybe Text
afterChar :: Char -> Text -> Maybe Text
afterChar Char
c Text
t = case Text -> Maybe (Char, Text)
T.uncons Text
t of
    Just (Char
lead, Text
rest) | Char
lead Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
c -> Text -> Maybe Text
forall a. a -> Maybe a
Just Text
rest
    Maybe (Char, Text)
_ -> Maybe Text
forall a. Maybe a
Nothing

-- Inlined, so the three numbers of a version pass no boxed pair between the steps.
leadingNumber :: Text -> Maybe (Word, Text)
leadingNumber :: Text -> Maybe (Word, Text)
leadingNumber Text
t = do
    let (Text
digits, Text
rest) = (Char -> Bool) -> Text -> (Text, Text)
T.span Char -> Bool
isDigit Text
t
    Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Text -> Bool
spellsNumber Text
digits)
    (Word, Text) -> Maybe (Word, Text)
forall a. a -> Maybe a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Text -> Word
digitsValue Text
digits, Text
rest)
{-# INLINE leadingNumber #-}

-- Expects digits only. Semver allows a leading zero in @0@ alone.
spellsNumber :: Text -> Bool
spellsNumber :: Text -> Bool
spellsNumber Text
digits = case Text -> Maybe (Char, Text)
T.uncons Text
digits of
    Maybe (Char, Text)
Nothing -> Bool
False
    Just (Char
lead, Text
more) -> Char
lead Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
'0' Bool -> Bool -> Bool
|| Text -> Bool
T.null Text
more

-- Expects digits only. The digit-run bound keeps the value within a 'Word'.
digitsValue :: Text -> Word
digitsValue :: Text -> Word
digitsValue = (Word -> Char -> Word) -> Word -> Text -> Word
forall a. (a -> Char -> a) -> a -> Text -> a
T.foldl' Word -> Char -> Word
addDigit Word
0

-- Expects an ASCII digit.
addDigit :: Word -> Char -> Word
addDigit :: Word -> Char -> Word
addDigit Word
value Char
digit = Word
value Word -> Word -> Word
forall a. Num a => a -> a -> a
* Word
10 Word -> Word -> Word
forall a. Num a => a -> a -> a
+ Int -> Word
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Char -> Int
ord Char
digit Int -> Int -> Int
forall a. Num a => a -> a -> a
- Char -> Int
ord Char
'0')
{-# INLINE addDigit #-}

markedPart :: Char -> (Text -> Maybe (a, Text)) -> Text -> Maybe (Maybe a, Text)
markedPart :: forall a.
Char -> (Text -> Maybe (a, Text)) -> Text -> Maybe (Maybe a, Text)
markedPart Char
marker Text -> Maybe (a, Text)
part Text
t = case Char -> Text -> Maybe Text
afterChar Char
marker Text
t of
    Maybe Text
Nothing -> (Maybe a, Text) -> Maybe (Maybe a, Text)
forall a. a -> Maybe a
Just (Maybe a
forall a. Maybe a
Nothing, Text
t)
    Just Text
marked -> (a -> Maybe a) -> (a, Text) -> (Maybe a, Text)
forall a b c. (a -> b) -> (a, c) -> (b, c)
forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first a -> Maybe a
forall a. a -> Maybe a
Just ((a, Text) -> (Maybe a, Text))
-> Maybe (a, Text) -> Maybe (Maybe a, Text)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Text -> Maybe (a, Text)
part Text
marked

identifiers :: Text -> Maybe (NonEmpty Chunk, Text)
identifiers :: Text -> Maybe (NonEmpty Chunk, Text)
identifiers Text
t = do
    let (Text
piece, Text
rest) = (Char -> Bool) -> Text -> (Text, Text)
T.span Char -> Bool
isIdentifierChar Text
t
    chunk <- Text -> Maybe Chunk
identifier Text
piece
    case afterChar '.' rest of
        Maybe Text
Nothing -> (NonEmpty Chunk, Text) -> Maybe (NonEmpty Chunk, Text)
forall a. a -> Maybe a
Just (Chunk
chunk Chunk -> [Chunk] -> NonEmpty Chunk
forall a. a -> [a] -> NonEmpty a
:| [], Text
rest)
        Just Text
more -> (NonEmpty Chunk -> NonEmpty Chunk)
-> (NonEmpty Chunk, Text) -> (NonEmpty Chunk, Text)
forall a b c. (a -> b) -> (a, c) -> (b, c)
forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first (Chunk -> NonEmpty Chunk -> NonEmpty Chunk
forall a. a -> NonEmpty a -> NonEmpty a
NE.cons Chunk
chunk) ((NonEmpty Chunk, Text) -> (NonEmpty Chunk, Text))
-> Maybe (NonEmpty Chunk, Text) -> Maybe (NonEmpty Chunk, Text)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Text -> Maybe (NonEmpty Chunk, Text)
identifiers Text
more

identifier :: Text -> Maybe Chunk
identifier :: Text -> Maybe Chunk
identifier Text
piece
    | (Char -> Bool) -> Text -> Bool
T.any (\Char
c -> Char -> Bool
isAlpha Char
c Bool -> Bool -> Bool
|| Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'-') Text
piece = Chunk -> Maybe Chunk
forall a. a -> Maybe a
Just (Text -> Chunk
Alphanum Text
piece)
    | (Char -> Bool) -> Text -> Bool
T.all Char -> Bool
isDigit Text
piece Bool -> Bool -> Bool
&& Text -> Bool
spellsNumber Text
piece = Chunk -> Maybe Chunk
forall a. a -> Maybe a
Just (Word -> Chunk
Numeric (Text -> Word
digitsValue Text
piece))
    | Bool
otherwise = Maybe Chunk
forall a. Maybe a
Nothing

buildMetadata :: Text -> Maybe (Text, Text)
buildMetadata :: Text -> Maybe (Text, Text)
buildMetadata Text
t = do
    let (Text
body, Text
rest) = (Char -> Bool) -> Text -> (Text, Text)
T.span (\Char
c -> Char -> Bool
isIdentifierChar Char
c Bool -> Bool -> Bool
|| Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'.') Text
t
    Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Bool -> Bool
not ((Text -> Bool) -> [Text] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Text -> Bool
T.null ((Char -> Bool) -> Text -> [Text]
T.split (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'.') Text
body)))
    (Text, Text) -> Maybe (Text, Text)
forall a. a -> Maybe a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Text
body, Text
rest)

-- 'isAlphaNum' and 'isAlpha' are the library's own Unicode-aware classes, so a non-ASCII letter
-- or numeral is an identifier character.
isIdentifierChar :: Char -> Bool
isIdentifierChar :: Char -> Bool
isIdentifierChar Char
c = Char -> Bool
isAlphaNum Char
c Bool -> Bool -> Bool
|| Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'-'