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

-- | Bounded Ruby Marshal 4.8 data. Class names remain inert strings.
module Ecluse.Core.Registry.RubyGems.Marshal (
    MarshalValue (..),
    decodeMarshal,
    marshalText,
    stripInstanceVariables,
    inertNodeBudget,
) where

import Data.Bits (shiftL)
import Data.ByteString qualified as BS
import Data.ByteString.Char8 qualified as B8
import Data.IntMap.Strict qualified as IntMap
import Data.Set qualified as Set
import Data.Text.Encoding qualified as TE

import Ecluse.Core.Registry (ParseError (..), parseRefusal)
import Ecluse.Core.Security.Limits (Limits (..))

-- | A data tree with resolved, acyclic references and no executable hooks.
data MarshalValue
    = MNil
    | MBool Bool
    | MInteger Integer
    | MFloat Double
    | MString ByteString
    | MSymbol ByteString
    | MArray [MarshalValue]
    | MHash [(MarshalValue, MarshalValue)]
    | MObject ByteString [(ByteString, MarshalValue)]
    | MUserDefined ByteString ByteString
    | MUserMarshal ByteString MarshalValue
    | MInstance MarshalValue [(ByteString, MarshalValue)]
    deriving stock (MarshalValue -> MarshalValue -> Bool
(MarshalValue -> MarshalValue -> Bool)
-> (MarshalValue -> MarshalValue -> Bool) -> Eq MarshalValue
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: MarshalValue -> MarshalValue -> Bool
== :: MarshalValue -> MarshalValue -> Bool
$c/= :: MarshalValue -> MarshalValue -> Bool
/= :: MarshalValue -> MarshalValue -> Bool
Eq, Int -> MarshalValue -> ShowS
[MarshalValue] -> ShowS
MarshalValue -> String
(Int -> MarshalValue -> ShowS)
-> (MarshalValue -> String)
-> ([MarshalValue] -> ShowS)
-> Show MarshalValue
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> MarshalValue -> ShowS
showsPrec :: Int -> MarshalValue -> ShowS
$cshow :: MarshalValue -> String
show :: MarshalValue -> String
$cshowList :: [MarshalValue] -> ShowS
showList :: [MarshalValue] -> ShowS
Show)

data Cursor = Cursor
    { Cursor -> ByteString
remaining :: ByteString
    , Cursor -> IntMap ByteString
symbols :: IntMap.IntMap ByteString
    , Cursor -> IntMap (Maybe (MarshalValue, Int, Int))
objects :: IntMap.IntMap (Maybe (MarshalValue, Int, Int))
    , Cursor -> Int
nodes :: Int
    , Cursor -> Int
stringBytes :: Int
    , Cursor -> Limits
bounds :: Limits
    }

type Decoder = StateT Cursor (Either ParseError)

-- | Decode exactly one object, refusing unsupported tags, cycles and invalid references.
decodeMarshal :: Limits -> ByteString -> Either ParseError MarshalValue
decodeMarshal :: Limits -> ByteString -> Either ParseError MarshalValue
decodeMarshal Limits
limits ByteString
bytes = do
    Bool -> Either ParseError () -> Either ParseError ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (ByteString -> Int
BS.length ByteString
bytes Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Limits -> Int
maxMetadataBytes Limits
limits) (Text -> Either ParseError ()
forall a. Text -> Either ParseError a
parseRefusal Text
"Marshal body exceeds its byte bound")
    (value, cursor) <- StateT Cursor (Either ParseError) MarshalValue
-> Cursor -> Either ParseError (MarshalValue, Cursor)
forall s (m :: * -> *) a. StateT s m a -> s -> m (a, s)
runStateT StateT Cursor (Either ParseError) MarshalValue
parser (ByteString
-> IntMap ByteString
-> IntMap (Maybe (MarshalValue, Int, Int))
-> Int
-> Int
-> Limits
-> Cursor
Cursor ByteString
bytes IntMap ByteString
forall a. IntMap a
IntMap.empty IntMap (Maybe (MarshalValue, Int, Int))
forall a. IntMap a
IntMap.empty Int
0 Int
0 Limits
limits)
    unless (BS.null (remaining cursor)) (parseRefusal "Marshal has trailing bytes")
    pure value
  where
    parser :: StateT Cursor (Either ParseError) MarshalValue
parser = do
        header <- Int -> Decoder ByteString
takeBytes Int
2
        unless (header == "\x04\x08") (refuse "unsupported Marshal version")
        readValue 0

readValue :: Int -> Decoder MarshalValue
readValue :: Int -> StateT Cursor (Either ParseError) MarshalValue
readValue Int
depth = do
    limits <- (Cursor -> Limits) -> StateT Cursor (Either ParseError) Limits
forall s (m :: * -> *) a. MonadState s m => (s -> a) -> m a
gets Cursor -> Limits
bounds
    when (depth > maxNestingDepth limits) (refuse "Marshal nesting exceeds its bound")
    countNode
    byte >>= \case
        Word8
48 -> MarshalValue -> StateT Cursor (Either ParseError) MarshalValue
forall a. a -> StateT Cursor (Either ParseError) a
forall (f :: * -> *) a. Applicative f => a -> f a
pure MarshalValue
MNil
        Word8
84 -> MarshalValue -> StateT Cursor (Either ParseError) MarshalValue
forall a. a -> StateT Cursor (Either ParseError) a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Bool -> MarshalValue
MBool Bool
True)
        Word8
70 -> MarshalValue -> StateT Cursor (Either ParseError) MarshalValue
forall a. a -> StateT Cursor (Either ParseError) a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Bool -> MarshalValue
MBool Bool
False)
        Word8
105 -> Integer -> MarshalValue
MInteger (Integer -> MarshalValue)
-> StateT Cursor (Either ParseError) Integer
-> StateT Cursor (Either ParseError) MarshalValue
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> StateT Cursor (Either ParseError) Integer
integer
        Word8
102 -> StateT Cursor (Either ParseError) MarshalValue
-> StateT Cursor (Either ParseError) MarshalValue
tracked (StateT Cursor (Either ParseError) MarshalValue
 -> StateT Cursor (Either ParseError) MarshalValue)
-> StateT Cursor (Either ParseError) MarshalValue
-> StateT Cursor (Either ParseError) MarshalValue
forall a b. (a -> b) -> a -> b
$ do
            raw <- Decoder ByteString
string
            when (BS.length raw > 64) (refuse "Marshal float exceeds its byte bound")
            case readMaybe (B8.unpack raw) of
                Just Double
value | Bool -> Bool
not (Double -> Bool
forall a. RealFloat a => a -> Bool
isNaN Double
value Bool -> Bool -> Bool
|| Double -> Bool
forall a. RealFloat a => a -> Bool
isInfinite Double
value) -> MarshalValue -> StateT Cursor (Either ParseError) MarshalValue
forall a. a -> StateT Cursor (Either ParseError) a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Double -> MarshalValue
MFloat Double
value)
                Maybe Double
_ -> Text -> StateT Cursor (Either ParseError) MarshalValue
forall a. Text -> Decoder a
refuse Text
"invalid or non-finite Marshal float"
        Word8
34 -> StateT Cursor (Either ParseError) MarshalValue
-> StateT Cursor (Either ParseError) MarshalValue
tracked (ByteString -> MarshalValue
MString (ByteString -> MarshalValue)
-> Decoder ByteString
-> StateT Cursor (Either ParseError) MarshalValue
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Decoder ByteString
string)
        Word8
58 -> ByteString -> MarshalValue
MSymbol (ByteString -> MarshalValue)
-> Decoder ByteString
-> StateT Cursor (Either ParseError) MarshalValue
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Decoder ByteString
defineSymbol
        Word8
59 -> ByteString -> MarshalValue
MSymbol (ByteString -> MarshalValue)
-> Decoder ByteString
-> StateT Cursor (Either ParseError) MarshalValue
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Decoder ByteString
referenceSymbol
        Word8
64 -> do
            index <- Decoder Int
natural
            table <- gets objects
            case IntMap.lookup index table of
                Just (Just (MarshalValue
value, Int
cost, Int
height)) -> do
                    cursor <- StateT Cursor (Either ParseError) Cursor
forall s (m :: * -> *). MonadState s m => m s
get
                    when (depth + height > maxNestingDepth (bounds cursor)) (refuse "Marshal referenced depth exceeds its bound")
                    spendNodes "Marshal reference work exceeds its bound" cost
                    pure value
                Maybe (Maybe (MarshalValue, Int, Int))
_ -> Text -> StateT Cursor (Either ParseError) MarshalValue
forall a. Text -> Decoder a
refuse Text
"invalid or cyclic Marshal object reference"
        Word8
91 -> StateT Cursor (Either ParseError) MarshalValue
-> StateT Cursor (Either ParseError) MarshalValue
tracked ([MarshalValue] -> MarshalValue
MArray ([MarshalValue] -> MarshalValue)
-> StateT Cursor (Either ParseError) [MarshalValue]
-> StateT Cursor (Either ParseError) MarshalValue
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> StateT Cursor (Either ParseError) MarshalValue
-> StateT Cursor (Either ParseError) [MarshalValue]
forall a. Decoder a -> Decoder [a]
counted (Int -> StateT Cursor (Either ParseError) MarshalValue
readValue (Int
depth Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1)))
        Word8
123 -> StateT Cursor (Either ParseError) MarshalValue
-> StateT Cursor (Either ParseError) MarshalValue
tracked (Int -> StateT Cursor (Either ParseError) MarshalValue
readHash (Int
depth Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1))
        Word8
111 -> StateT Cursor (Either ParseError) MarshalValue
-> StateT Cursor (Either ParseError) MarshalValue
tracked (StateT Cursor (Either ParseError) MarshalValue
 -> StateT Cursor (Either ParseError) MarshalValue)
-> StateT Cursor (Either ParseError) MarshalValue
-> StateT Cursor (Either ParseError) MarshalValue
forall a b. (a -> b) -> a -> b
$ ByteString -> [(ByteString, MarshalValue)] -> MarshalValue
MObject (ByteString -> [(ByteString, MarshalValue)] -> MarshalValue)
-> Decoder ByteString
-> StateT
     Cursor
     (Either ParseError)
     ([(ByteString, MarshalValue)] -> MarshalValue)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Decoder ByteString
symbol StateT
  Cursor
  (Either ParseError)
  ([(ByteString, MarshalValue)] -> MarshalValue)
-> StateT Cursor (Either ParseError) [(ByteString, MarshalValue)]
-> StateT Cursor (Either ParseError) MarshalValue
forall a b.
StateT Cursor (Either ParseError) (a -> b)
-> StateT Cursor (Either ParseError) a
-> StateT Cursor (Either ParseError) b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> Int
-> StateT Cursor (Either ParseError) [(ByteString, MarshalValue)]
attributes (Int
depth Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1)
        Word8
117 -> StateT Cursor (Either ParseError) MarshalValue
-> StateT Cursor (Either ParseError) MarshalValue
tracked (StateT Cursor (Either ParseError) MarshalValue
 -> StateT Cursor (Either ParseError) MarshalValue)
-> StateT Cursor (Either ParseError) MarshalValue
-> StateT Cursor (Either ParseError) MarshalValue
forall a b. (a -> b) -> a -> b
$ ByteString -> ByteString -> MarshalValue
MUserDefined (ByteString -> ByteString -> MarshalValue)
-> Decoder ByteString
-> StateT Cursor (Either ParseError) (ByteString -> MarshalValue)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Decoder ByteString
symbol StateT Cursor (Either ParseError) (ByteString -> MarshalValue)
-> Decoder ByteString
-> StateT Cursor (Either ParseError) MarshalValue
forall a b.
StateT Cursor (Either ParseError) (a -> b)
-> StateT Cursor (Either ParseError) a
-> StateT Cursor (Either ParseError) b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> Decoder ByteString
string
        Word8
85 -> StateT Cursor (Either ParseError) MarshalValue
-> StateT Cursor (Either ParseError) MarshalValue
tracked (StateT Cursor (Either ParseError) MarshalValue
 -> StateT Cursor (Either ParseError) MarshalValue)
-> StateT Cursor (Either ParseError) MarshalValue
-> StateT Cursor (Either ParseError) MarshalValue
forall a b. (a -> b) -> a -> b
$ ByteString -> MarshalValue -> MarshalValue
MUserMarshal (ByteString -> MarshalValue -> MarshalValue)
-> Decoder ByteString
-> StateT Cursor (Either ParseError) (MarshalValue -> MarshalValue)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Decoder ByteString
symbol StateT Cursor (Either ParseError) (MarshalValue -> MarshalValue)
-> StateT Cursor (Either ParseError) MarshalValue
-> StateT Cursor (Either ParseError) MarshalValue
forall a b.
StateT Cursor (Either ParseError) (a -> b)
-> StateT Cursor (Either ParseError) a
-> StateT Cursor (Either ParseError) b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> Int -> StateT Cursor (Either ParseError) MarshalValue
readValue (Int
depth Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1)
        Word8
73 -> MarshalValue -> [(ByteString, MarshalValue)] -> MarshalValue
MInstance (MarshalValue -> [(ByteString, MarshalValue)] -> MarshalValue)
-> StateT Cursor (Either ParseError) MarshalValue
-> StateT
     Cursor
     (Either ParseError)
     ([(ByteString, MarshalValue)] -> MarshalValue)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Int -> StateT Cursor (Either ParseError) MarshalValue
readValue (Int
depth Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1) StateT
  Cursor
  (Either ParseError)
  ([(ByteString, MarshalValue)] -> MarshalValue)
-> StateT Cursor (Either ParseError) [(ByteString, MarshalValue)]
-> StateT Cursor (Either ParseError) MarshalValue
forall a b.
StateT Cursor (Either ParseError) (a -> b)
-> StateT Cursor (Either ParseError) a
-> StateT Cursor (Either ParseError) b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> Int
-> StateT Cursor (Either ParseError) [(ByteString, MarshalValue)]
attributes (Int
depth Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1)
        Word8
_ -> Text -> StateT Cursor (Either ParseError) MarshalValue
forall a. Text -> Decoder a
refuse Text
"unsupported Marshal tag"

readHash :: Int -> Decoder MarshalValue
readHash :: Int -> StateT Cursor (Either ParseError) MarshalValue
readHash Int
depth = do
    entries <- Decoder (MarshalValue, MarshalValue)
-> Decoder [(MarshalValue, MarshalValue)]
forall a. Decoder a -> Decoder [a]
counted ((,) (MarshalValue -> MarshalValue -> (MarshalValue, MarshalValue))
-> StateT Cursor (Either ParseError) MarshalValue
-> StateT
     Cursor
     (Either ParseError)
     (MarshalValue -> (MarshalValue, MarshalValue))
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Int -> StateT Cursor (Either ParseError) MarshalValue
readValue Int
depth StateT
  Cursor
  (Either ParseError)
  (MarshalValue -> (MarshalValue, MarshalValue))
-> StateT Cursor (Either ParseError) MarshalValue
-> Decoder (MarshalValue, MarshalValue)
forall a b.
StateT Cursor (Either ParseError) (a -> b)
-> StateT Cursor (Either ParseError) a
-> StateT Cursor (Either ParseError) b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> Int -> StateT Cursor (Either ParseError) MarshalValue
readValue Int
depth)
    keys <- traverse (lift . hashKey . fst) entries
    unless (Set.size (Set.fromList keys) == length keys) (refuse "duplicate Marshal hash key")
    pure (MHash entries)
  where
    hashKey :: MarshalValue -> Either ParseError (Bool, ByteString)
hashKey MarshalValue
value = case MarshalValue -> MarshalValue
stripInstanceVariables MarshalValue
value of
        MString ByteString
bytes -> (Bool, ByteString) -> Either ParseError (Bool, ByteString)
forall a b. b -> Either a b
Right (Bool
False, ByteString
bytes)
        MSymbol ByteString
bytes -> (Bool, ByteString) -> Either ParseError (Bool, ByteString)
forall a b. b -> Either a b
Right (Bool
True, ByteString
bytes)
        MarshalValue
_ -> Text -> Either ParseError (Bool, ByteString)
forall a. Text -> Either ParseError a
parseRefusal Text
"unsupported Marshal hash key"

tracked :: Decoder MarshalValue -> Decoder MarshalValue
tracked :: StateT Cursor (Either ParseError) MarshalValue
-> StateT Cursor (Either ParseError) MarshalValue
tracked StateT Cursor (Either ParseError) MarshalValue
parse = do
    before <- (Cursor -> Int) -> Decoder Int
forall s (m :: * -> *) a. MonadState s m => (s -> a) -> m a
gets Cursor -> Int
nodes
    table <- gets objects
    let index = IntMap (Maybe (MarshalValue, Int, Int)) -> Int
forall a. IntMap a -> Int
IntMap.size IntMap (Maybe (MarshalValue, Int, Int))
table
    modify' (\Cursor
cursor -> Cursor
cursor{objects = IntMap.insert index Nothing table})
    value <- parse
    after <- gets nodes
    modify' (\Cursor
cursor -> Cursor
cursor{objects = IntMap.insert index (Just (value, after - before + 1, valueDepth value)) (objects cursor)})
    pure value

valueDepth :: MarshalValue -> Int
valueDepth :: MarshalValue -> Int
valueDepth = \case
    MArray [MarshalValue]
values -> [MarshalValue] -> Int
descendants [MarshalValue]
values
    MHash [(MarshalValue, MarshalValue)]
entries -> [MarshalValue] -> Int
descendants (((MarshalValue, MarshalValue) -> [MarshalValue])
-> [(MarshalValue, MarshalValue)] -> [MarshalValue]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (\(MarshalValue
key, MarshalValue
value) -> [MarshalValue
key, MarshalValue
value]) [(MarshalValue, MarshalValue)]
entries)
    MObject ByteString
_ [(ByteString, MarshalValue)]
entries -> [MarshalValue] -> Int
descendants (((ByteString, MarshalValue) -> MarshalValue)
-> [(ByteString, MarshalValue)] -> [MarshalValue]
forall a b. (a -> b) -> [a] -> [b]
map (ByteString, MarshalValue) -> MarshalValue
forall a b. (a, b) -> b
snd [(ByteString, MarshalValue)]
entries)
    MUserMarshal ByteString
_ MarshalValue
value -> Int
1 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ MarshalValue -> Int
valueDepth MarshalValue
value
    MInstance MarshalValue
value [(ByteString, MarshalValue)]
entries -> [MarshalValue] -> Int
descendants (MarshalValue
value MarshalValue -> [MarshalValue] -> [MarshalValue]
forall a. a -> [a] -> [a]
: ((ByteString, MarshalValue) -> MarshalValue)
-> [(ByteString, MarshalValue)] -> [MarshalValue]
forall a b. (a -> b) -> [a] -> [b]
map (ByteString, MarshalValue) -> MarshalValue
forall a b. (a, b) -> b
snd [(ByteString, MarshalValue)]
entries)
    MarshalValue
_ -> Int
0
  where
    descendants :: [MarshalValue] -> Int
descendants [MarshalValue]
values = (Int -> Int -> Int) -> Int -> [Int] -> Int
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' Int -> Int -> Int
forall a. Ord a => a -> a -> a
max Int
0 ((MarshalValue -> Int) -> [MarshalValue] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map ((Int
1 Int -> Int -> Int
forall a. Num a => a -> a -> a
+) (Int -> Int) -> (MarshalValue -> Int) -> MarshalValue -> Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. MarshalValue -> Int
valueDepth) [MarshalValue]
values)

attributes :: Int -> Decoder [(ByteString, MarshalValue)]
attributes :: Int
-> StateT Cursor (Either ParseError) [(ByteString, MarshalValue)]
attributes Int
depth = do
    values <- Decoder (ByteString, MarshalValue)
-> StateT Cursor (Either ParseError) [(ByteString, MarshalValue)]
forall a. Decoder a -> Decoder [a]
counted ((,) (ByteString -> MarshalValue -> (ByteString, MarshalValue))
-> Decoder ByteString
-> StateT
     Cursor
     (Either ParseError)
     (MarshalValue -> (ByteString, MarshalValue))
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Decoder ByteString
symbol StateT
  Cursor
  (Either ParseError)
  (MarshalValue -> (ByteString, MarshalValue))
-> StateT Cursor (Either ParseError) MarshalValue
-> Decoder (ByteString, MarshalValue)
forall a b.
StateT Cursor (Either ParseError) (a -> b)
-> StateT Cursor (Either ParseError) a
-> StateT Cursor (Either ParseError) b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> Int -> StateT Cursor (Either ParseError) MarshalValue
readValue Int
depth)
    unless (length values == length (ordNub (map fst values))) (refuse "duplicate Marshal instance variable")
    pure values

symbol :: Decoder ByteString
symbol :: Decoder ByteString
symbol = do
    StateT Cursor (Either ParseError) ()
countNode
    Decoder Word8
byte Decoder Word8
-> (Word8 -> Decoder ByteString) -> Decoder ByteString
forall a b.
StateT Cursor (Either ParseError) a
-> (a -> StateT Cursor (Either ParseError) b)
-> StateT Cursor (Either ParseError) b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
        Word8
58 -> Decoder ByteString
defineSymbol
        Word8
59 -> Decoder ByteString
referenceSymbol
        Word8
_ -> Text -> Decoder ByteString
forall a. Text -> Decoder a
refuse Text
"Marshal class or field name is not a symbol"

defineSymbol :: Decoder ByteString
defineSymbol :: Decoder ByteString
defineSymbol = do
    value <- Decoder ByteString
string
    table <- gets symbols
    modify' (\Cursor
cursor -> Cursor
cursor{symbols = IntMap.insert (IntMap.size table) value table})
    pure value

referenceSymbol :: Decoder ByteString
referenceSymbol :: Decoder ByteString
referenceSymbol = do
    index <- Decoder Int
natural
    table <- gets symbols
    maybe (refuse "invalid Marshal symbol reference") pure (IntMap.lookup index table)

countNode :: Decoder ()
countNode :: StateT Cursor (Either ParseError) ()
countNode = Text -> Int -> StateT Cursor (Either ParseError) ()
spendNodes Text
"Marshal node count exceeds its bound" Int
1

-- Spend node work against the inert budget, refusing with the reason once it would pass the budget.
spendNodes :: Text -> Int -> Decoder ()
spendNodes :: Text -> Int -> StateT Cursor (Either ParseError) ()
spendNodes Text
reason Int
amount = do
    cursor <- StateT Cursor (Either ParseError) Cursor
forall s (m :: * -> *). MonadState s m => m s
get
    when (amount > inertNodeBudget (bounds cursor) - nodes cursor) (refuse reason)
    modify' (\Cursor
current -> Cursor
current{nodes = nodes current + amount})

-- | The node and alias work one inert Marshal or YAML decode may do.
inertNodeBudget :: Limits -> Int
inertNodeBudget :: Limits -> Int
inertNodeBudget Limits
limits = Int -> Int -> Int
forall a. Ord a => a -> a -> a
min (Limits -> Int
inertNodeCeiling Limits
limits) (Limits -> Int
maxMetadataBytes Limits
limits Int -> Int -> Int
forall a. Integral a => a -> a -> a
`div` Int
8)

counted :: Decoder a -> Decoder [a]
counted :: forall a. Decoder a -> Decoder [a]
counted Decoder a
parse = do
    count <- Decoder Int
natural
    cap <- gets (inertNodeCeiling . bounds)
    available <- gets (BS.length . remaining)
    when (count > cap || count > available) (refuse "Marshal collection count exceeds its bound")
    replicateM count parse

string :: Decoder ByteString
string :: Decoder ByteString
string = do
    count <- Decoder Int
natural
    cursor <- get
    when (count > maxMetadataBytes (bounds cursor) - stringBytes cursor) (refuse "Marshal strings exceed their byte bound")
    modify' (\Cursor
current -> Cursor
current{stringBytes = stringBytes current + count})
    BS.copy <$> takeBytes count

natural :: Decoder Int
natural :: Decoder Int
natural = do
    value <- StateT Cursor (Either ParseError) Integer
integer
    if value < 0 || value > toInteger (maxBound :: Int)
        then refuse "invalid Marshal length or reference"
        else pure (fromInteger value)

integer :: Decoder Integer
integer :: StateT Cursor (Either ParseError) Integer
integer = do
    tag <- Decoder Word8
byte
    let signed = if Word8
tag Word8 -> Word8 -> Bool
forall a. Ord a => a -> a -> Bool
>= Word8
128 then Word8 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word8
tag Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
256 else Word8 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word8
tag :: Int
    case signed of
        Int
0 -> Integer -> StateT Cursor (Either ParseError) Integer
forall a. a -> StateT Cursor (Either ParseError) a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Integer
0
        Int
n | Int
n Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
4 -> Integer -> StateT Cursor (Either ParseError) Integer
forall a. a -> StateT Cursor (Either ParseError) a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Int -> Integer
forall a. Integral a => a -> Integer
toInteger (Int
n Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
5))
        Int
n | Int
n Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< -Int
4 -> Integer -> StateT Cursor (Either ParseError) Integer
forall a. a -> StateT Cursor (Either ParseError) a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Int -> Integer
forall a. Integral a => a -> Integer
toInteger (Int
n Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
5))
        Int
n -> do
            bytes <- Int -> Decoder ByteString
takeBytes (Int -> Int
forall a. Num a => a -> a
abs Int
n)
            let magnitude = (Word8 -> Integer -> Integer) -> Integer -> ByteString -> Integer
forall a. (Word8 -> a -> a) -> a -> ByteString -> a
BS.foldr (\Word8
part Integer
value -> Word8 -> Integer
forall a. Integral a => a -> Integer
toInteger Word8
part Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Integer
value Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
* Integer
256) Integer
0 ByteString
bytes
            pure (if n < 0 then magnitude - (1 `shiftL` (8 * abs n)) else magnitude)

byte :: Decoder Word8
byte :: Decoder Word8
byte = do
    bytes <- Int -> Decoder ByteString
takeBytes Int
1
    maybe (refuse "truncated Marshal input") (pure . fst) (BS.uncons bytes)

takeBytes :: Int -> Decoder ByteString
takeBytes :: Int -> Decoder ByteString
takeBytes Int
count = do
    cursor <- StateT Cursor (Either ParseError) Cursor
forall s (m :: * -> *). MonadState s m => m s
get
    when (count < 0 || count > BS.length (remaining cursor)) (refuse "truncated Marshal input")
    let (bytes, rest) = BS.splitAt count (remaining cursor)
    put cursor{remaining = rest}
    pure bytes

refuse :: Text -> Decoder a
refuse :: forall a. Text -> Decoder a
refuse = Either ParseError a -> StateT Cursor (Either ParseError) a
forall (m :: * -> *) a. Monad m => m a -> StateT Cursor m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (Either ParseError a -> StateT Cursor (Either ParseError) a)
-> (Text -> Either ParseError a)
-> Text
-> StateT Cursor (Either ParseError) a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Either ParseError a
forall a. Text -> Either ParseError a
parseRefusal

-- | Remove inert encoding and instance-variable wrappers when reading scalar fields.
stripInstanceVariables :: MarshalValue -> MarshalValue
stripInstanceVariables :: MarshalValue -> MarshalValue
stripInstanceVariables (MInstance MarshalValue
value [(ByteString, MarshalValue)]
_) = MarshalValue -> MarshalValue
stripInstanceVariables MarshalValue
value
stripInstanceVariables MarshalValue
value = MarshalValue
value

-- | Require a valid UTF-8 native string, preserving its spelling.
marshalText :: MarshalValue -> Either ParseError Text
marshalText :: MarshalValue -> Either ParseError Text
marshalText MarshalValue
value = case MarshalValue -> MarshalValue
stripInstanceVariables MarshalValue
value of
    MString ByteString
bytes -> (UnicodeException -> ParseError)
-> Either UnicodeException Text -> Either ParseError Text
forall a b c. (a -> b) -> Either a c -> Either b c
forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first (ParseError -> UnicodeException -> ParseError
forall a b. a -> b -> a
const (Text -> ParseError
ParseError Text
"Marshal string is not UTF-8")) (ByteString -> Either UnicodeException Text
TE.decodeUtf8' ByteString
bytes)
    MarshalValue
_ -> Text -> Either ParseError Text
forall a. Text -> Either ParseError a
parseRefusal Text
"expected Marshal string"