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

-- | Compact specifications retain the original zlib bytes after data-only schema checks.
module Ecluse.Core.Registry.RubyGems.CompactSpec (
    GemSpecification (..),
    CompactSpec,
    decodeGemSpecification,
    decodeCompactSpec,
    validateCompactSpec,
    checkGemSpecification,
    compactSpecBytes,
    compactSpecification,
    specificationCoordinate,
) where

import Data.ByteString qualified as BS
import Data.List (lookup)
import Data.Map.Strict qualified as Map
import Data.Text qualified as T
import UnliftIO.Exception (evaluate)

import Ecluse.Core.Ecosystem (Ecosystem (RubyGems))
import Ecluse.Core.Package (PackageName, renderPackageName)
import Ecluse.Core.Registry (ParseError (..), parseRefusal)
import Ecluse.Core.Registry.Archive.Inflate (InflateFormat (ZlibStream), inflateBounded)
import Ecluse.Core.Registry.RubyGems.Document
import Ecluse.Core.Registry.RubyGems.Marshal
import Ecluse.Core.Registry.RubyGems.Project
import Ecluse.Core.Security.Limits (Limits (..))
import Ecluse.Core.Version (Version, mkVersion, renderVersion)
import Ecluse.Core.Version.Gem (isGemRequirementOperator, parseGem)

-- | Native installation facts from the supported historical and current specification layouts.
data GemSpecification = GemSpecification
    { GemSpecification -> PackageName
specificationName :: PackageName
    , GemSpecification -> Version
specificationVersion :: Version
    , GemSpecification -> GemPlatform
specificationPlatform :: GemPlatform
    , GemSpecification -> [GemDependency]
specificationDependencies :: [GemDependency]
    , GemSpecification -> GemRequirement
specificationRequiredRuby :: GemRequirement
    , GemSpecification -> GemRequirement
specificationRequiredRubyGems :: GemRequirement
    , GemSpecification -> Map Text Text
specificationMetadata :: Map Text Text
    }
    deriving stock (GemSpecification -> GemSpecification -> Bool
(GemSpecification -> GemSpecification -> Bool)
-> (GemSpecification -> GemSpecification -> Bool)
-> Eq GemSpecification
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: GemSpecification -> GemSpecification -> Bool
== :: GemSpecification -> GemSpecification -> Bool
$c/= :: GemSpecification -> GemSpecification -> Bool
/= :: GemSpecification -> GemSpecification -> Bool
Eq, Int -> GemSpecification -> ShowS
[GemSpecification] -> ShowS
GemSpecification -> String
(Int -> GemSpecification -> ShowS)
-> (GemSpecification -> String)
-> ([GemSpecification] -> ShowS)
-> Show GemSpecification
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> GemSpecification -> ShowS
showsPrec :: Int -> GemSpecification -> ShowS
$cshow :: GemSpecification -> String
show :: GemSpecification -> String
$cshowList :: [GemSpecification] -> ShowS
showList :: [GemSpecification] -> ShowS
Show)

-- | The compressed bytes and parsed facts refer to the same fully consumed stream.
data CompactSpec = CompactSpec
    { CompactSpec -> ByteString
compactSpecBytes :: ByteString
    , CompactSpec -> GemSpecification
compactSpecification :: GemSpecification
    }
    deriving stock (CompactSpec -> CompactSpec -> Bool
(CompactSpec -> CompactSpec -> Bool)
-> (CompactSpec -> CompactSpec -> Bool) -> Eq CompactSpec
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: CompactSpec -> CompactSpec -> Bool
== :: CompactSpec -> CompactSpec -> Bool
$c/= :: CompactSpec -> CompactSpec -> Bool
/= :: CompactSpec -> CompactSpec -> Bool
Eq, Int -> CompactSpec -> ShowS
[CompactSpec] -> ShowS
CompactSpec -> String
(Int -> CompactSpec -> ShowS)
-> (CompactSpec -> String)
-> ([CompactSpec] -> ShowS)
-> Show CompactSpec
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> CompactSpec -> ShowS
showsPrec :: Int -> CompactSpec -> ShowS
$cshow :: CompactSpec -> String
show :: CompactSpec -> String
$cshowList :: [CompactSpec] -> ShowS
showList :: [CompactSpec] -> ShowS
Show)

-- | Parse the native Marshal wrapper and its bounded nested Marshal payload.
decodeGemSpecification :: Limits -> ByteString -> Either ParseError GemSpecification
decodeGemSpecification :: Limits -> ByteString -> Either ParseError GemSpecification
decodeGemSpecification Limits
limits ByteString
bytes = do
    outer <- Limits -> ByteString -> Either ParseError MarshalValue
decodeMarshal Limits
limits ByteString
bytes
    validateClasses outer
    payload <- case stripInstanceVariables outer of
        MUserDefined ByteString
"Gem::Specification" ByteString
body -> ByteString -> Either ParseError ByteString
forall a b. b -> Either a b
Right ByteString
body
        MarshalValue
_ -> Text -> Either ParseError ByteString
forall a. Text -> Either ParseError a
parseRefusal Text
"compact specification lacks Gem::Specification framing"
    inner <- decodeMarshal limits payload
    validateClasses inner
    normalised <- normaliseLayout inner
    case normalised of
        MArray [MarshalValue
rubyGems, MInteger Integer
_, MarshalValue
name, MarshalValue
version, MarshalValue
date, MarshalValue
summary, MarshalValue
ruby, MarshalValue
gems, MarshalValue
original, MarshalValue
dependencies, MarshalValue
rubyforge, MarshalValue
email, MarshalValue
authors, MarshalValue
description, MarshalValue
homepage, MarshalValue
rdoc, MarshalValue
platform, MarshalValue
licences, MarshalValue
metadata] -> do
            (MarshalValue -> Either ParseError ())
-> [MarshalValue] -> Either ParseError ()
forall (t :: * -> *) (f :: * -> *) a b.
(Foldable t, Applicative f) =>
(a -> f b) -> t a -> f ()
traverse_ MarshalValue -> Either ParseError ()
scalar [MarshalValue
rubyGems, MarshalValue
summary, MarshalValue
original, MarshalValue
rubyforge]
            (MarshalValue -> Either ParseError ())
-> [MarshalValue] -> Either ParseError ()
forall (t :: * -> *) (f :: * -> *) a b.
(Foldable t, Applicative f) =>
(a -> f b) -> t a -> f ()
traverse_ MarshalValue -> Either ParseError ()
nullable [MarshalValue
email, MarshalValue
description, MarshalValue
homepage]
            MarshalValue -> Either ParseError ()
stringArray MarshalValue
authors
            MarshalValue -> Either ParseError ()
stringArray MarshalValue
licences
            case MarshalValue
rdoc of MBool Bool
_ -> () -> Either ParseError ()
forall a b. b -> Either a b
Right (); MarshalValue
_ -> Text -> Either ParseError ()
forall a. Text -> Either ParseError a
parseRefusal Text
"invalid specification documentation flag"
            case MarshalValue -> MarshalValue
stripInstanceVariables MarshalValue
date of
                MUserDefined ByteString
"Time" ByteString
raw | ByteString -> Int
BS.length ByteString
raw Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
8 Bool -> Bool -> Bool
&& ByteString -> Int
BS.length ByteString
raw Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
122 -> () -> Either ParseError ()
forall a b. b -> Either a b
Right ()
                MUserMarshal ByteString
"Date" (MArray [MarshalValue]
values) | [MarshalValue] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [MarshalValue]
values Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
6 -> (MarshalValue -> Either ParseError ())
-> [MarshalValue] -> Either ParseError ()
forall (t :: * -> *) (f :: * -> *) a b.
(Foldable t, Applicative f) =>
(a -> f b) -> t a -> f ()
traverse_ MarshalValue -> Either ParseError ()
dateNumber [MarshalValue]
values
                MarshalValue
_ -> Text -> Either ParseError ()
forall a. Text -> Either ParseError a
parseRefusal Text
"invalid specification date"
            checkedName <- MarshalValue -> Either ParseError Text
marshalText MarshalValue
name Either ParseError Text
-> (Text -> Either ParseError PackageName)
-> Either ParseError PackageName
forall a b.
Either ParseError a
-> (a -> Either ParseError b) -> Either ParseError b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Text -> Either ParseError PackageName
projectName
            checkedVersion <- gemVersion version
            checkedPlatform <- nativePlatform original
            void (nativePlatform platform)
            requiredRuby <- requirement ruby
            requiredGems <- requirement gems
            runtime <- array dependencies >>= traverse dependency
            extras <- textMap metadata
            pure (GemSpecification checkedName checkedVersion checkedPlatform (catMaybes runtime) requiredRuby requiredGems extras)
        MarshalValue
_ -> Text -> Either ParseError GemSpecification
forall a. Text -> Either ParseError a
parseRefusal Text
"unsupported compact specification layout"
  where
    dateNumber :: MarshalValue -> Either ParseError ()
dateNumber (MInteger Integer
_) = () -> Either ParseError ()
forall a b. b -> Either a b
Right ()
    dateNumber (MFloat Double
_) = () -> Either ParseError ()
forall a b. b -> Either a b
Right ()
    dateNumber MarshalValue
_ = Text -> Either ParseError ()
forall a. Text -> Either ParseError a
parseRefusal Text
"invalid native Date component"
    scalar :: MarshalValue -> Either ParseError ()
scalar = Either ParseError Text -> Either ParseError ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (Either ParseError Text -> Either ParseError ())
-> (MarshalValue -> Either ParseError Text)
-> MarshalValue
-> Either ParseError ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. MarshalValue -> Either ParseError Text
marshalText
    nullable :: MarshalValue -> Either ParseError ()
nullable MarshalValue
value = case MarshalValue -> MarshalValue
stripInstanceVariables MarshalValue
value of MarshalValue
MNil -> () -> Either ParseError ()
forall a b. b -> Either a b
Right (); MArray [MarshalValue]
values -> (MarshalValue -> Either ParseError ())
-> [MarshalValue] -> Either ParseError ()
forall (t :: * -> *) (f :: * -> *) a b.
(Foldable t, Applicative f) =>
(a -> f b) -> t a -> f ()
traverse_ MarshalValue -> Either ParseError ()
scalar [MarshalValue]
values; MarshalValue
other -> MarshalValue -> Either ParseError ()
scalar MarshalValue
other
    stringArray :: MarshalValue -> Either ParseError ()
stringArray MarshalValue
value = case MarshalValue -> MarshalValue
stripInstanceVariables MarshalValue
value of MarshalValue
MNil -> () -> Either ParseError ()
forall a b. b -> Either a b
Right (); MarshalValue
other -> MarshalValue -> Either ParseError [MarshalValue]
array MarshalValue
other Either ParseError [MarshalValue]
-> ([MarshalValue] -> Either ParseError ()) -> Either ParseError ()
forall a b.
Either ParseError a
-> (a -> Either ParseError b) -> Either ParseError b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (MarshalValue -> Either ParseError ())
-> [MarshalValue] -> Either ParseError ()
forall (t :: * -> *) (f :: * -> *) a b.
(Foldable t, Applicative f) =>
(a -> f b) -> t a -> f ()
traverse_ MarshalValue -> Either ParseError ()
scalar

normaliseLayout :: MarshalValue -> Either ParseError MarshalValue
normaliseLayout :: MarshalValue -> Either ParseError MarshalValue
normaliseLayout MarshalValue
value = case MarshalValue -> MarshalValue
stripInstanceVariables MarshalValue
value of
    MArray values :: [MarshalValue]
values@(MarshalValue
_ : MInteger Integer
schema : MarshalValue
_ : MarshalValue
_ : MarshalValue
_ : MarshalValue
_ : MarshalValue
_ : MarshalValue
_ : MarshalValue
original : [MarshalValue]
_)
        | Integer
schema Integer -> [Integer] -> Bool
forall (f :: * -> *) a.
(Foldable f, DisallowElem f, Eq a) =>
a -> f a -> Bool
`elem` [-Integer
1, Integer
1, Integer
2, Integer
3, Integer
4] -> do
            let count :: Int
count = [MarshalValue] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [MarshalValue]
values
                minimumFields :: Int
minimumFields
                    | Integer
schema Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
<= Integer
2 = Int
16
                    | Integer
schema Integer -> Integer -> Bool
forall a. Eq a => a -> a -> Bool
== Integer
3 = Int
17
                    | Bool
otherwise = Int
18
            Bool -> Either ParseError () -> Either ParseError ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (Int
count Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
minimumFields Bool -> Bool -> Bool
&& Int
count Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
19) (Text -> Either ParseError ()
forall a. Text -> Either ParseError a
parseRefusal Text
"invalid historical compact specification field count")
            let additions :: [MarshalValue]
additions = Int -> [MarshalValue] -> [MarshalValue]
forall a. Int -> [a] -> [a]
drop (Int
count Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
16) [MarshalValue
original, [MarshalValue] -> MarshalValue
MArray [], [(MarshalValue, MarshalValue)] -> MarshalValue
MHash []]
            MarshalValue -> Either ParseError MarshalValue
forall a. a -> Either ParseError a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([MarshalValue] -> MarshalValue
MArray ([MarshalValue]
values [MarshalValue] -> [MarshalValue] -> [MarshalValue]
forall a. Semigroup a => a -> a -> a
<> [MarshalValue]
additions))
    MarshalValue
_ -> Text -> Either ParseError MarshalValue
forall a. Text -> Either ParseError a
parseRefusal Text
"unsupported compact specification layout"

-- | Inflate one bounded zlib stream and preserve its exact original representation.
decodeCompactSpec :: Limits -> (Int -> IO ()) -> ByteString -> IO (Either ParseError CompactSpec)
decodeCompactSpec :: Limits
-> (Int -> IO ())
-> ByteString
-> IO (Either ParseError CompactSpec)
decodeCompactSpec Limits
limits Int -> IO ()
charge ByteString
bytes
    | ByteString -> Int
BS.length ByteString
bytes Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Limits -> Int
maxMetadataBytes Limits
limits = Either ParseError CompactSpec -> IO (Either ParseError CompactSpec)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Text -> Either ParseError CompactSpec
forall a. Text -> Either ParseError a
parseRefusal Text
"compact specification exceeds its compressed byte bound")
    | Bool
otherwise =
        InflateFormat
-> Text
-> Int
-> (Int -> IO ())
-> ByteString
-> IO (Either ParseError ByteString)
inflateBounded InflateFormat
ZlibStream Text
"compact specification exceeds its inflated byte bound" (Limits -> Int
maxMetadataBytes Limits
limits) Int -> IO ()
charge ByteString
bytes IO (Either ParseError ByteString)
-> (Either ParseError ByteString
    -> IO (Either ParseError CompactSpec))
-> IO (Either ParseError CompactSpec)
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
            Left ParseError
fault -> Either ParseError CompactSpec -> IO (Either ParseError CompactSpec)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ParseError -> Either ParseError CompactSpec
forall a b. a -> Either a b
Left ParseError
fault)
            Right ByteString
raw -> do
                Int -> IO ()
charge (Int
73728 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
64 Int -> Int -> Int
forall a. Num a => a -> a -> a
* ByteString -> Int
BS.length ByteString
raw)
                Either ParseError CompactSpec -> IO (Either ParseError CompactSpec)
forall (m :: * -> *) a. MonadIO m => a -> m a
evaluate (ByteString -> GemSpecification -> CompactSpec
CompactSpec ByteString
bytes (GemSpecification -> CompactSpec)
-> Either ParseError GemSpecification
-> Either ParseError CompactSpec
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Limits -> ByteString -> Either ParseError GemSpecification
decodeGemSpecification Limits
limits ByteString
raw)

-- | Bind selected source bytes to the admitted physical coordinate and native installation facts.
validateCompactSpec :: Limits -> (Int -> IO ()) -> GemCoordinate -> GemRow -> ByteString -> IO (Either ParseError CompactSpec)
validateCompactSpec :: Limits
-> (Int -> IO ())
-> GemCoordinate
-> GemRow
-> ByteString
-> IO (Either ParseError CompactSpec)
validateCompactSpec Limits
limits Int -> IO ()
charge GemCoordinate
coordinate GemRow
row ByteString
bytes = do
    decoded <- Limits
-> (Int -> IO ())
-> ByteString
-> IO (Either ParseError CompactSpec)
decodeCompactSpec Limits
limits Int -> IO ()
charge ByteString
bytes
    evaluate $ do
        compact <- decoded
        void (checkGemSpecification coordinate row (compactSpecification compact))
        pure compact

-- | Bind native archive or compact facts to the selected source coordinate and installation metadata.
checkGemSpecification :: GemCoordinate -> GemRow -> GemSpecification -> Either ParseError GemSpecification
checkGemSpecification :: GemCoordinate
-> GemRow -> GemSpecification -> Either ParseError GemSpecification
checkGemSpecification GemCoordinate
coordinate GemRow
row GemSpecification
specification = do
    actual <- GemSpecification -> Either ParseError GemCoordinate
specificationCoordinate GemSpecification
specification
    unless (actual == coordinate && grCoordinate row == coordinate) (parseRefusal "native specification identity disagrees with its selected coordinate")
    unless (normalDependencies (specificationDependencies specification) == normalDependencies (grDependencies row)) (parseRefusal "native specification runtime dependencies disagree with source metadata")
    unless (normalRequirement (specificationRequiredRuby specification) == normalRequirement (grRequiredRuby row)) (parseRefusal "native specification required Ruby disagrees with source metadata")
    unless (normalRequirement (specificationRequiredRubyGems specification) == normalRequirement (grRequiredRubyGems row)) (parseRefusal "native specification required RubyGems disagrees with source metadata")
    pure specification

-- | Build the checked physical artifact coordinate from native specification facts.
specificationCoordinate :: GemSpecification -> Either ParseError GemCoordinate
specificationCoordinate :: GemSpecification -> Either ParseError GemCoordinate
specificationCoordinate GemSpecification
specification = PackageName
-> Version -> GemPlatform -> Either ParseError GemCoordinate
mkCoordinate (GemSpecification -> PackageName
specificationName GemSpecification
specification) (GemSpecification -> Version
specificationVersion GemSpecification
specification) (GemSpecification -> GemPlatform
specificationPlatform GemSpecification
specification)

normalDependencies :: [GemDependency] -> [(Text, [Text])]
normalDependencies :: [GemDependency] -> [(Text, [Text])]
normalDependencies = [(Text, [Text])] -> [(Text, [Text])]
forall a. Ord a => [a] -> [a]
sort ([(Text, [Text])] -> [(Text, [Text])])
-> ([GemDependency] -> [(Text, [Text])])
-> [GemDependency]
-> [(Text, [Text])]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (GemDependency -> (Text, [Text]))
-> [GemDependency] -> [(Text, [Text])]
forall a b. (a -> b) -> [a] -> [b]
map (\GemDependency
dependencyValue -> (PackageName -> Text
renderPackageName (GemDependency -> PackageName
gdName GemDependency
dependencyValue), GemRequirement -> [Text]
normalRequirement (GemDependency -> GemRequirement
gdRequirement GemDependency
dependencyValue)))

normalRequirement :: GemRequirement -> [Text]
normalRequirement :: GemRequirement -> [Text]
normalRequirement = [Text] -> [Text]
forall a. Ord a => [a] -> [a]
sort ([Text] -> [Text])
-> (GemRequirement -> [Text]) -> GemRequirement -> [Text]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Text -> Text) -> [Text] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map Text -> Text
canonical ([Text] -> [Text])
-> (GemRequirement -> [Text]) -> GemRequirement -> [Text]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. GemRequirement -> [Text]
forall a. NonEmpty a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList
  where
    canonical :: Text -> Text
canonical Text
clause =
        let (Text
operator, Text
rest) = (Char -> Bool) -> Text -> (Text, Text)
T.span (Char -> String -> Bool
forall (f :: * -> *) a.
(Foldable f, DisallowElem f, Eq a) =>
a -> f a -> Bool
`elem` [Char
'=', Char
'!', Char
'<', Char
'>', Char
'~']) (Text -> Text
T.strip Text
clause)
         in Text
operator Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text -> Text
T.strip Text
rest

gemVersion :: MarshalValue -> Either ParseError Version
gemVersion :: MarshalValue -> Either ParseError Version
gemVersion MarshalValue
value = case MarshalValue -> MarshalValue
stripInstanceVariables MarshalValue
value of
    MUserMarshal ByteString
"Gem::Version" (MArray [MarshalValue
raw]) -> do
        text <- MarshalValue -> Either ParseError Text
marshalText MarshalValue
raw
        unless (isJust (parseGem text)) (parseRefusal "invalid native gem version")
        pure (mkVersion RubyGems text)
    MarshalValue
_ -> Text -> Either ParseError Version
forall a. Text -> Either ParseError a
parseRefusal Text
"invalid Gem::Version data"

requirement :: MarshalValue -> Either ParseError GemRequirement
requirement :: MarshalValue -> Either ParseError GemRequirement
requirement MarshalValue
value = case MarshalValue -> MarshalValue
stripInstanceVariables MarshalValue
value of
    MUserMarshal ByteString
"Gem::Requirement" (MArray [MArray [MarshalValue]
clauses]) -> do
        parsed <- (MarshalValue -> Either ParseError Text)
-> [MarshalValue] -> Either ParseError [Text]
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse MarshalValue -> Either ParseError Text
clause [MarshalValue]
clauses
        maybeToRight (ParseError "empty Gem::Requirement") (nonEmpty parsed)
    MarshalValue
_ -> Text -> Either ParseError GemRequirement
forall a. Text -> Either ParseError a
parseRefusal Text
"invalid Gem::Requirement data"
  where
    clause :: MarshalValue -> Either ParseError Text
clause (MArray [MarshalValue
operator, MarshalValue
version]) = do
        op <- MarshalValue -> Either ParseError Text
marshalText MarshalValue
operator
        unless (isGemRequirementOperator op) (parseRefusal "unsupported gem requirement operator")
        raw <- renderVersion <$> gemVersion version
        pure (op <> " " <> raw)
    clause MarshalValue
_ = Text -> Either ParseError Text
forall a. Text -> Either ParseError a
parseRefusal Text
"invalid gem requirement clause"

dependency :: MarshalValue -> Either ParseError (Maybe GemDependency)
dependency :: MarshalValue -> Either ParseError (Maybe GemDependency)
dependency MarshalValue
value = case MarshalValue -> MarshalValue
stripInstanceVariables MarshalValue
value of
    MObject ByteString
"Gem::Dependency" [(ByteString, MarshalValue)]
attributes -> do
        Bool -> Either ParseError () -> Either ParseError ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (((ByteString, MarshalValue) -> Bool)
-> [(ByteString, MarshalValue)] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all ((ByteString -> [ByteString] -> Bool
forall (f :: * -> *) a.
(Foldable f, DisallowElem f, Eq a) =>
a -> f a -> Bool
`elem` [ByteString
"@name", ByteString
"@requirement", ByteString
"@type", ByteString
"@prerelease", ByteString
"@version_requirements", ByteString
"@force_ruby_platform"]) (ByteString -> Bool)
-> ((ByteString, MarshalValue) -> ByteString)
-> (ByteString, MarshalValue)
-> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (ByteString, MarshalValue) -> ByteString
forall a b. (a, b) -> a
fst) [(ByteString, MarshalValue)]
attributes) (Text -> Either ParseError ()
forall a. Text -> Either ParseError a
parseRefusal Text
"unsupported Gem::Dependency field")
        name <- ByteString
-> [(ByteString, MarshalValue)] -> Either ParseError MarshalValue
field ByteString
"@name" [(ByteString, MarshalValue)]
attributes Either ParseError MarshalValue
-> (MarshalValue -> Either ParseError Text)
-> Either ParseError Text
forall a b.
Either ParseError a
-> (a -> Either ParseError b) -> Either ParseError b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= MarshalValue -> Either ParseError Text
marshalText Either ParseError Text
-> (Text -> Either ParseError PackageName)
-> Either ParseError PackageName
forall a b.
Either ParseError a
-> (a -> Either ParseError b) -> Either ParseError b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Text -> Either ParseError PackageName
projectName
        wanted <- case lookup "@requirement" attributes of
            Just MarshalValue
MNil -> ByteString
-> [(ByteString, MarshalValue)] -> Either ParseError MarshalValue
field ByteString
"@version_requirements" [(ByteString, MarshalValue)]
attributes Either ParseError MarshalValue
-> (MarshalValue -> Either ParseError GemRequirement)
-> Either ParseError GemRequirement
forall a b.
Either ParseError a
-> (a -> Either ParseError b) -> Either ParseError b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= MarshalValue -> Either ParseError GemRequirement
requirement
            Just MarshalValue
raw -> MarshalValue -> Either ParseError GemRequirement
requirement MarshalValue
raw
            Maybe MarshalValue
Nothing -> ByteString
-> [(ByteString, MarshalValue)] -> Either ParseError MarshalValue
field ByteString
"@version_requirements" [(ByteString, MarshalValue)]
attributes Either ParseError MarshalValue
-> (MarshalValue -> Either ParseError GemRequirement)
-> Either ParseError GemRequirement
forall a b.
Either ParseError a
-> (a -> Either ParseError b) -> Either ParseError b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= MarshalValue -> Either ParseError GemRequirement
requirement
        case lookup "@version_requirements" attributes of
            Maybe MarshalValue
Nothing -> () -> Either ParseError ()
forall a b. b -> Either a b
Right ()
            Just MarshalValue
other -> do
                old <- MarshalValue -> Either ParseError GemRequirement
requirement MarshalValue
other
                unless (normalRequirement old == normalRequirement wanted) (parseRefusal "conflicting gem dependency requirements")
        for_ (lookup "@force_ruby_platform" attributes) $ \case MBool Bool
_ -> () -> Either ParseError ()
forall a b. b -> Either a b
Right (); MarshalValue
_ -> Text -> Either ParseError ()
forall a. Text -> Either ParseError a
parseRefusal Text
"invalid dependency platform flag"
        for_ (lookup "@prerelease" attributes) $ \case MBool Bool
_ -> () -> Either ParseError ()
forall a b. b -> Either a b
Right (); MarshalValue
_ -> Text -> Either ParseError ()
forall a. Text -> Either ParseError a
parseRefusal Text
"invalid dependency prerelease flag"
        field "@type" attributes >>= \case
            MSymbol ByteString
"runtime" -> Maybe GemDependency -> Either ParseError (Maybe GemDependency)
forall a b. b -> Either a b
Right (GemDependency -> Maybe GemDependency
forall a. a -> Maybe a
Just (PackageName -> GemRequirement -> GemDependency
GemDependency PackageName
name GemRequirement
wanted))
            MSymbol ByteString
"development" -> Maybe GemDependency -> Either ParseError (Maybe GemDependency)
forall a b. b -> Either a b
Right Maybe GemDependency
forall a. Maybe a
Nothing
            MarshalValue
_ -> Text -> Either ParseError (Maybe GemDependency)
forall a. Text -> Either ParseError a
parseRefusal Text
"unsupported gem dependency type"
    MarshalValue
_ -> Text -> Either ParseError (Maybe GemDependency)
forall a. Text -> Either ParseError a
parseRefusal Text
"invalid Gem::Dependency data"

nativePlatform :: MarshalValue -> Either ParseError GemPlatform
nativePlatform :: MarshalValue -> Either ParseError GemPlatform
nativePlatform MarshalValue
value = case MarshalValue -> MarshalValue
stripInstanceVariables MarshalValue
value of
    MString ByteString
_ -> MarshalValue -> Either ParseError Text
marshalText MarshalValue
value Either ParseError Text
-> (Text -> Either ParseError GemPlatform)
-> Either ParseError GemPlatform
forall a b.
Either ParseError a
-> (a -> Either ParseError b) -> Either ParseError b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Text -> Either ParseError GemPlatform
mkGemPlatform
    MObject ByteString
"Gem::Platform" [(ByteString, MarshalValue)]
attributes -> do
        Bool -> Either ParseError () -> Either ParseError ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless ([ByteString] -> [ByteString]
forall a. Ord a => [a] -> [a]
sort (((ByteString, MarshalValue) -> ByteString)
-> [(ByteString, MarshalValue)] -> [ByteString]
forall a b. (a -> b) -> [a] -> [b]
map (ByteString, MarshalValue) -> ByteString
forall a b. (a, b) -> a
fst [(ByteString, MarshalValue)]
attributes) [ByteString] -> [ByteString] -> Bool
forall a. Eq a => a -> a -> Bool
== [ByteString
"@cpu", ByteString
"@os", ByteString
"@version"]) (Text -> Either ParseError ()
forall a. Text -> Either ParseError a
parseRefusal Text
"invalid Gem::Platform fields")
        cpu <- ByteString
-> [(ByteString, MarshalValue)] -> Either ParseError MarshalValue
field ByteString
"@cpu" [(ByteString, MarshalValue)]
attributes Either ParseError MarshalValue
-> (MarshalValue -> Either ParseError (Maybe Text))
-> Either ParseError (Maybe Text)
forall a b.
Either ParseError a
-> (a -> Either ParseError b) -> Either ParseError b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= MarshalValue -> Either ParseError (Maybe Text)
part
        os <- field "@os" attributes >>= marshalText
        version <- field "@version" attributes >>= part
        mkGemPlatform (T.intercalate "-" (catMaybes [cpu, Just os, version]))
    MarshalValue
_ -> Text -> Either ParseError GemPlatform
forall a. Text -> Either ParseError a
parseRefusal Text
"invalid specification platform"
  where
    part :: MarshalValue -> Either ParseError (Maybe Text)
part MarshalValue
MNil = Maybe Text -> Either ParseError (Maybe Text)
forall a b. b -> Either a b
Right Maybe Text
forall a. Maybe a
Nothing
    part MarshalValue
other = Text -> Maybe Text
forall a. a -> Maybe a
Just (Text -> Maybe Text)
-> Either ParseError Text -> Either ParseError (Maybe Text)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> MarshalValue -> Either ParseError Text
marshalText MarshalValue
other

textMap :: MarshalValue -> Either ParseError (Map Text Text)
textMap :: MarshalValue -> Either ParseError (Map Text Text)
textMap MarshalValue
value = case MarshalValue -> MarshalValue
stripInstanceVariables MarshalValue
value of
    MarshalValue
MNil -> Map Text Text -> Either ParseError (Map Text Text)
forall a b. b -> Either a b
Right Map Text Text
forall k a. Map k a
Map.empty
    MHash [(MarshalValue, MarshalValue)]
entries -> do
        pairs <- ((MarshalValue, MarshalValue) -> Either ParseError (Text, Text))
-> [(MarshalValue, MarshalValue)]
-> Either ParseError [(Text, Text)]
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse (\(MarshalValue
key, MarshalValue
item) -> (,) (Text -> Text -> (Text, Text))
-> Either ParseError Text
-> Either ParseError (Text -> (Text, Text))
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> MarshalValue -> Either ParseError Text
marshalText MarshalValue
key Either ParseError (Text -> (Text, Text))
-> Either ParseError Text -> Either ParseError (Text, Text)
forall a b.
Either ParseError (a -> b)
-> Either ParseError a -> Either ParseError b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> MarshalValue -> Either ParseError Text
marshalText MarshalValue
item) [(MarshalValue, MarshalValue)]
entries
        let result = [(Text, Text)] -> Map Text Text
forall k a. Ord k => [(k, a)] -> Map k a
Map.fromList [(Text, Text)]
pairs
        unless (Map.size result == length pairs) (parseRefusal "duplicate specification metadata key")
        pure result
    MarshalValue
_ -> Text -> Either ParseError (Map Text Text)
forall a. Text -> Either ParseError a
parseRefusal Text
"invalid specification metadata"

validateClasses :: MarshalValue -> Either ParseError ()
validateClasses :: MarshalValue -> Either ParseError ()
validateClasses = \case
    MUserDefined ByteString
className ByteString
_ | ByteString
className ByteString -> [ByteString] -> Bool
forall (f :: * -> *) a.
(Foldable f, DisallowElem f, Eq a) =>
a -> f a -> Bool
`elem` [ByteString
"Gem::Specification", ByteString
"Time"] -> () -> Either ParseError ()
forall a b. b -> Either a b
Right ()
    MUserDefined ByteString
_ ByteString
_ -> Text -> Either ParseError ()
forall a. Text -> Either ParseError a
parseRefusal Text
"unsupported Marshal user-defined class"
    MUserMarshal ByteString
className MarshalValue
value | ByteString
className ByteString -> [ByteString] -> Bool
forall (f :: * -> *) a.
(Foldable f, DisallowElem f, Eq a) =>
a -> f a -> Bool
`elem` [ByteString
"Gem::Version", ByteString
"Gem::Requirement", ByteString
"Date"] -> MarshalValue -> Either ParseError ()
validateClasses MarshalValue
value
    MUserMarshal ByteString
_ MarshalValue
_ -> Text -> Either ParseError ()
forall a. Text -> Either ParseError a
parseRefusal Text
"unsupported Marshal user-marshal class"
    MObject ByteString
className [(ByteString, MarshalValue)]
attributes | ByteString
className ByteString -> [ByteString] -> Bool
forall (f :: * -> *) a.
(Foldable f, DisallowElem f, Eq a) =>
a -> f a -> Bool
`elem` [ByteString
"Gem::Dependency", ByteString
"Gem::Platform"] -> ((ByteString, MarshalValue) -> Either ParseError ())
-> [(ByteString, MarshalValue)] -> Either ParseError ()
forall (t :: * -> *) (f :: * -> *) a b.
(Foldable t, Applicative f) =>
(a -> f b) -> t a -> f ()
traverse_ (MarshalValue -> Either ParseError ()
validateClasses (MarshalValue -> Either ParseError ())
-> ((ByteString, MarshalValue) -> MarshalValue)
-> (ByteString, MarshalValue)
-> Either ParseError ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (ByteString, MarshalValue) -> MarshalValue
forall a b. (a, b) -> b
snd) [(ByteString, MarshalValue)]
attributes
    MObject ByteString
_ [(ByteString, MarshalValue)]
_ -> Text -> Either ParseError ()
forall a. Text -> Either ParseError a
parseRefusal Text
"unsupported Marshal object class"
    MInstance MarshalValue
value [(ByteString, MarshalValue)]
attributes -> do
        Bool -> Either ParseError () -> Either ParseError ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (((ByteString, MarshalValue) -> Bool)
-> [(ByteString, MarshalValue)] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all ((ByteString -> [ByteString] -> Bool
forall (f :: * -> *) a.
(Foldable f, DisallowElem f, Eq a) =>
a -> f a -> Bool
`elem` [ByteString
"E", ByteString
"encoding", ByteString
"zone", ByteString
"offset", ByteString
"nano_num", ByteString
"nano_den", ByteString
"submicro", ByteString
"@_zone", ByteString
"@marshal_with_utc_coercion", ByteString
"@taguri", ByteString
"@debug_created_info"]) (ByteString -> Bool)
-> ((ByteString, MarshalValue) -> ByteString)
-> (ByteString, MarshalValue)
-> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (ByteString, MarshalValue) -> ByteString
forall a b. (a, b) -> a
fst) [(ByteString, MarshalValue)]
attributes) (Text -> Either ParseError ()
forall a. Text -> Either ParseError a
parseRefusal Text
"unsupported Marshal instance variable")
        MarshalValue -> Either ParseError ()
validateClasses MarshalValue
value
        ((ByteString, MarshalValue) -> Either ParseError ())
-> [(ByteString, MarshalValue)] -> Either ParseError ()
forall (t :: * -> *) (f :: * -> *) a b.
(Foldable t, Applicative f) =>
(a -> f b) -> t a -> f ()
traverse_ (MarshalValue -> Either ParseError ()
validateClasses (MarshalValue -> Either ParseError ())
-> ((ByteString, MarshalValue) -> MarshalValue)
-> (ByteString, MarshalValue)
-> Either ParseError ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (ByteString, MarshalValue) -> MarshalValue
forall a b. (a, b) -> b
snd) [(ByteString, MarshalValue)]
attributes
    MArray [MarshalValue]
values -> (MarshalValue -> Either ParseError ())
-> [MarshalValue] -> Either ParseError ()
forall (t :: * -> *) (f :: * -> *) a b.
(Foldable t, Applicative f) =>
(a -> f b) -> t a -> f ()
traverse_ MarshalValue -> Either ParseError ()
validateClasses [MarshalValue]
values
    MHash [(MarshalValue, MarshalValue)]
values -> ((MarshalValue, MarshalValue) -> Either ParseError ())
-> [(MarshalValue, MarshalValue)] -> Either ParseError ()
forall (t :: * -> *) (f :: * -> *) a b.
(Foldable t, Applicative f) =>
(a -> f b) -> t a -> f ()
traverse_ (\(MarshalValue
key, MarshalValue
value) -> MarshalValue -> Either ParseError ()
validateClasses MarshalValue
key Either ParseError ()
-> Either ParseError () -> Either ParseError ()
forall a b.
Either ParseError a -> Either ParseError b -> Either ParseError b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> MarshalValue -> Either ParseError ()
validateClasses MarshalValue
value) [(MarshalValue, MarshalValue)]
values
    MarshalValue
_ -> () -> Either ParseError ()
forall a b. b -> Either a b
Right ()

array :: MarshalValue -> Either ParseError [MarshalValue]
array :: MarshalValue -> Either ParseError [MarshalValue]
array MarshalValue
value = case MarshalValue -> MarshalValue
stripInstanceVariables MarshalValue
value of MArray [MarshalValue]
values -> [MarshalValue] -> Either ParseError [MarshalValue]
forall a b. b -> Either a b
Right [MarshalValue]
values; MarshalValue
_ -> Text -> Either ParseError [MarshalValue]
forall a. Text -> Either ParseError a
parseRefusal Text
"expected Marshal array"

field :: ByteString -> [(ByteString, MarshalValue)] -> Either ParseError MarshalValue
field :: ByteString
-> [(ByteString, MarshalValue)] -> Either ParseError MarshalValue
field ByteString
key = ParseError -> Maybe MarshalValue -> Either ParseError MarshalValue
forall l r. l -> Maybe r -> Either l r
maybeToRight (Text -> ParseError
ParseError Text
"missing native specification field") (Maybe MarshalValue -> Either ParseError MarshalValue)
-> ([(ByteString, MarshalValue)] -> Maybe MarshalValue)
-> [(ByteString, MarshalValue)]
-> Either ParseError MarshalValue
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> [(ByteString, MarshalValue)] -> Maybe MarshalValue
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup ByteString
key