packages feed

jsonnet-0.5.0.0: src/Language/Jsonnet/Value.hs

{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE UndecidableInstances #-}

{- |
Module      : Language.Jsonnet.Value
Copyright   : (c) 2020-2021 Alexandre Moreno
SPDX-License-Identifier : BSD-3-Clause OR Apache-2.0
Maintainer  : Alexandre Moreno <alexmorenocano@gmail.com>
Stability   : experimental
Portability : non-portable
-}
module Language.Jsonnet.Value (
    -- * Re-exported from Eval.Types
    Value (VNull, VBool, VStr, VNum, VObj, VArr, VFun),
    Cache,

    -- * Smart constructors & evaluation
    mkObj,
    emptyObject,
    mkIndirV,
    mkThunk,
    mkFun,
    forceWHNF,
    force,
    liftF,
    liftF2,

    -- * Operations
    objectLookup,
    superLookup,
    equals,
    primitiveEquals,
    compare,
    toString,
    showTy,
    doubleToIntegral,
    isIntegral,
    throwTypeMismatch,

    -- * Typeclasses
    Inj (..),
    Proj (..),
    HasValue,
    Arity (..),
) where

import Control.Lens (Prism', makePrisms, matching, prism', review, (^.))
import Control.Monad (forM, (>=>), (<$!>))
import Control.Monad.IO.Class (MonadIO (..))
import Data.Aeson qualified as JSON
import Data.Aeson.KeyMap qualified as KeyMap
import Data.ByteString (ByteString)
import Data.HashMap.Strict (HashMap)
import Data.HashMap.Strict qualified as H
import Data.HashSet qualified as HS
import Data.IORef (IORef, newIORef, readIORef, writeIORef)
import Data.Scientific (Scientific, fromFloatDigits, toRealFloat)
import Data.Text (Text)
import Data.Text qualified as T
import Data.Text.Encoding (decodeUtf8, encodeUtf8)
import Data.Vector (Vector)
import Data.Vector qualified as V
import Language.Jsonnet.Common (Arg (..), Visibility (..))
import Language.Jsonnet.Error (EvalError (..))
import Language.Jsonnet.Eval.Monad
import Language.Jsonnet.Eval.Types
import Language.Jsonnet.Object qualified as Object
import Language.Jsonnet.Pretty (ppJsonCompact)
import Data.Int (Int64)
import Prelude hiding (compare)
import Prelude qualified as P

makePrisms ''Value

expect :: Text -> Value -> EvalError
expect expected actual = TypeMismatch expected (showTy actual)
{-# INLINE expect #-}

throwTypeMismatch :: Text -> Value -> EvalM a
throwTypeMismatch expected = throwE . expect expected
{-# INLINE throwTypeMismatch #-}

objectLookup :: Value -> Text -> EvalM Value
objectLookup v key =
    forceWHNF v >>= \case
        selfVal@(VObj obj _) -> superLookup selfVal obj key
        v' -> throwTypeMismatch "object" v'
{-# INLINE objectLookup #-}

superLookup :: Value -> Object -> Text -> EvalM Value
superLookup selfVal@(VObj _ cache) obj key = do
    (field, layer, nextSup) <- liftMaybe (NoSuchKey key) (Object.lookupField key obj)
    case field ^. fieldVal of
        VThunk compute ->
            memoizeLookup cache layer key $
                withObjectEnv selfVal nextSup compute
        val -> forceWHNF val
superLookup v _ _ = throwTypeMismatch "object" v
{-# INLINE superLookup #-}

isFinite :: Double -> Bool
isFinite d = not (isNaN d || isInfinite d)
{-# INLINE isFinite #-}

exactIntegral :: (Integral a) => Double -> Maybe a
exactIntegral d =
    let !i = truncate d
     in if fromIntegral i == d then Just i else Nothing
{-# INLINE exactIntegral #-}

doubleToIntegral :: forall a. (Integral a, Bounded a) => Double -> Maybe a
doubleToIntegral d
    | not (isFinite d) = Nothing
    | d < fromIntegral (minBound @a) || d > fromIntegral (maxBound @a) = Nothing
    | otherwise = exactIntegral d
{-# INLINE doubleToIntegral #-}

isIntegral :: Double -> Bool
isIntegral d =
    not (isNaN d || isInfinite d)
        && (abs d >= 4503599627370496 || fromIntegral (truncate d :: Int64) == d)

_Integer :: Prism' Value Integer
_Integer = _VNum . prism' fromIntegral (\d -> if isFinite d then exactIntegral d else Nothing)
{-# INLINE _Integer #-}

_Integral :: forall a. (Integral a, Bounded a) => Prism' Value a
_Integral = _VNum . prism' fromIntegral doubleToIntegral
{-# INLINE _Integral #-}

_Scientific :: Prism' Value Scientific
_Scientific = _VNum . prism' toRealFloat (\d -> if isFinite d then Just (fromFloatDigits d) else Nothing)
{-# INLINE _Scientific #-}

forceWHNF :: Value -> EvalM Value
forceWHNF = \case
    VIndir ref -> memoize ref
    VThunk m -> m >>= forceWHNF
    v -> pure v

memoize :: IORef Value -> EvalM Value
memoize ref =
    liftIO (readIORef ref) >>= \case
        VBlackhole -> throwE InfiniteRecursion
        VThunk m -> do
            liftIO (writeIORef ref VBlackhole)
            val <- m >>= forceWHNF
            liftIO (writeIORef ref val)
            pure val
        val -> pure val

memoizeLookup :: Cache -> Int -> Text -> EvalM Value -> EvalM Value
memoizeLookup (Cache ref) !depth key compute = do
    let !k = (depth, key)
    m <- liftIO (readIORef ref)
    cell <- case H.lookup k m of
        Just c -> pure c
        Nothing -> liftIO $ do
            c <- newIORef (VThunk compute)
            writeIORef ref $! H.insert k c m
            pure c
    memoize cell

mkFun :: Int -> (Value -> EvalM Value) -> Value
mkFun !n g = VFun n go
  where
    go (Named k _ : _) = throwE (BadParam (T.pack k))
    go args | length args < n = throwE (TooFewArgs n)
    go [] = throwE (TooFewArgs n)
    go [Pos x] = g x >>= forceWHNF
    go (Pos x : rest) =
        g x >>= forceWHNF >>= \case
            VFun _ k -> k rest
            v -> throwTypeMismatch "function" v

toString :: Value -> EvalM Text
toString =
    forceWHNF >=> \case
        VStr s -> pure s
        v -> T.show . ppJsonCompact <$> proj @JSON.Value v

showTy :: Value -> Text
showTy = \case
    VNull -> "null"
    VBool _ -> "boolean"
    VNum _ -> "number"
    VStr _ -> "string"
    VArr _ -> "array"
    VObj _ _ -> "object"
    VFun _ _ -> "function"
    VThunk _ -> "thunk"
    VIndir _ -> "pointer"
    VBlackhole -> "blackhole"

primitiveEquals :: Value -> Value -> EvalM Bool
primitiveEquals e1 e2 = do
    v1 <- forceWHNF e1
    v2 <- forceWHNF e2
    case (v1, v2) of
        (VNull, VNull) -> pure True
        (VBool a, VBool b) -> pure (a == b)
        (VStr a, VStr b) -> pure (a == b)
        (VNum a, VNum b) -> pure (a == b)
        _
            | showTy v1 /= showTy v2 -> pure False
            | otherwise -> throwE (StdError "primitiveEquals operates on primitive types ")

equals :: Value -> Value -> EvalM Bool
equals e1 e2 = do
    v1 <- forceWHNF e1
    v2 <- forceWHNF e2
    go v1 v2
  where
    go (VArr a) (VArr b)
        | V.length a == V.length b =
            allM (\i -> equals (a V.! i) (b V.! i)) [0 .. V.length a - 1]
        | otherwise = pure False
    go (VObj a c1) (VObj b c2) = do
        let keysA = Object.visibleKeys a
            keysB = Object.visibleKeys b
        if length keysA /= length keysB || HS.fromList keysA /= HS.fromList keysB
            then pure False
            else do
                ok <- allM (uncurry checkAssertions) [(selfA, a), (selfB, b)]
                if ok then allM compareField keysA else pure False
      where
        selfA = VObj a c1
        selfB = VObj b c2
        compareField k = do
            va <- objectLookup selfA k
            vb <- objectLookup selfB k
            equals va vb
    go a b = primitiveEquals a b

    checkAssertions :: Value -> Object -> EvalM Bool
    checkAssertions selfVal obj =
        allM
            ( \k ->
                objectLookup selfVal k >>= \case
                    VBool b -> pure b
                    _ -> pure True
            )
            (Object.assertionKeys obj)

compare :: Value -> Value -> EvalM Ordering
compare (VNum a) (VNum b) = pure (P.compare a b)
compare (VStr a) (VStr b) = pure (P.compare a b)
compare (VArr a) (VArr b) = do
    as <- mapM proj (V.toList a)
    bs <- mapM proj (V.toList b)
    go as bs
  where
    go [] [] = pure EQ
    go [] _ = pure LT
    go _ [] = pure GT
    go (x : xs) (y : ys) = do
        ord <- compare x y
        case ord of
            EQ -> go xs ys
            _ -> pure ord
compare v1 _ = throwTypeMismatch "number, string, or array" v1

allM :: (Monad m, Foldable t) => (a -> m Bool) -> t a -> m Bool
allM p = foldr (\x acc -> p x >>= \b -> if b then acc else pure False) (pure True)

force :: Prism' Value a -> Value -> EvalM (Either Value a)
force p = fmap (matching p) . forceWHNF
{-# INLINE force #-}

-- ---------------------------------------------------------------------------
-- Inj / Proj type classes
-- ---------------------------------------------------------------------------

class Inj a where
    inj :: a -> Value

class Proj a where
    proj :: Value -> EvalM a

type HasValue a = (Inj a, Proj a)

instance Inj Value where
    inj = id
    {-# INLINE inj #-}
instance Proj Value where
    proj = forceWHNF
    {-# INLINE proj #-}

instance Inj Bool where
    inj = VBool
    {-# INLINE inj #-}
instance Proj Bool where
    proj v = force _VBool v <?> expect "bool"
    {-# INLINE proj #-}

instance Inj Text where
    inj = VStr
    {-# INLINE inj #-}
instance Proj Text where
    proj v = force _VStr v <?> expect "string"
    {-# INLINE proj #-}

instance {-# OVERLAPPING #-} Inj [Char] where
    inj = VStr . T.pack
    {-# INLINE inj #-}
instance {-# OVERLAPPING #-} Proj [Char] where
    proj = fmap T.unpack . proj
    {-# INLINE proj #-}

instance Inj ByteString where
    inj = VStr . decodeUtf8
    {-# INLINE inj #-}
instance Proj ByteString where
    proj = fmap encodeUtf8 . proj
    {-# INLINE proj #-}

instance Inj Double where
    inj = VNum
    {-# INLINE inj #-}
instance Proj Double where
    proj v = force _VNum v <?> expect "number"
    {-# INLINE proj #-}

instance Inj Scientific where
    inj = review _Scientific
    {-# INLINE inj #-}
instance Proj Scientific where
    proj v = force _Scientific v <?> expect "number"
    {-# INLINE proj #-}

instance Inj Integer where
    inj = review _Integer
    {-# INLINE inj #-}
instance Proj Integer where
    proj v = force _Integer v <?> expect "integer"
    {-# INLINE proj #-}

instance {-# OVERLAPPABLE #-} (Integral a, Bounded a) => Inj a where
    inj = review _Integral
    {-# INLINE inj #-}
instance {-# OVERLAPPABLE #-} (Integral a, Bounded a) => Proj a where
    proj v = force _Integral v <?> expect "integer"
    {-# INLINE proj #-}

instance (Inj a) => Inj (Maybe a) where
    inj = maybe VNull inj
    {-# INLINE inj #-}
instance (Proj a) => Proj (Maybe a) where
    proj =
        forceWHNF >=> \case
            VNull -> pure Nothing
            v -> Just <$> proj v

instance Inj Object where
    inj = VThunk . mkObj
    {-# INLINE inj #-}
instance Proj Object where
    proj v = fst <$> (force _VObj v <?> expect "object")
    {-# INLINE proj #-}

instance (Inj a) => Inj (Vector a) where
    inj = VArr . fmap inj
    {-# INLINE inj #-}
instance (Proj a) => Proj (Vector a) where
    proj v = (force _VArr v <?> expect "array") >>= V.mapM proj
    {-# INLINE proj #-}

instance {-# OVERLAPPABLE #-} (Inj a) => Inj [a] where
    inj = VArr . V.fromList . map inj
    {-# INLINE inj #-}
instance {-# OVERLAPPABLE #-} (Proj a) => Proj [a] where
    proj v = (force _VArr v <?> expect "array") >>= traverse proj . V.toList
    {-# INLINE proj #-}

instance (Inj a) => Inj (HashMap Text a) where
    inj = VThunk . mkObj . mkBaseObject . H.map (\v -> Field (inj v) Visible False)

instance (Proj a) => Proj (HashMap Text a) where
    proj =
        forceWHNF >=> \case
            v@(VObj obj _) -> do
                pairs <- forM (Object.visibleKeys obj) $ \k -> do
                    val <- proj =<< objectLookup v k
                    pure (k, val)
                pure (H.fromList pairs)
            v -> throwTypeMismatch "object" v

instance (Inj a) => Inj (EvalM a) where
    inj = VThunk . fmap inj
    {-# INLINE inj #-}

class Arity a where
    arityOf :: Int

instance {-# OVERLAPPABLE #-} Arity a where
    arityOf = 0
    {-# INLINE arityOf #-}

instance (Arity b) => Arity (a -> b) where
    arityOf = 1 + arityOf @b
    {-# INLINE arityOf #-}

instance (Proj a, Inj r, Arity (a -> r)) => Inj (a -> r) where
    inj f = mkFun (arityOf @(a -> r)) (fmap (inj . f) . proj)
    {-# INLINE inj #-}

instance (Inj a, Proj b) => Proj (a -> EvalM b) where
    proj v = do
        (_, f) <- force _VFun v <?> expect "function"
        pure (\x -> f [Pos (inj x)] >>= proj)
    {-# INLINE proj #-}

instance (Inj a) => Inj (KeyMap.KeyMap a) where
    inj = inj . KeyMap.toHashMapText
    {-# INLINE inj #-}

instance (Proj a) => Proj (KeyMap.KeyMap a) where
    proj = fmap KeyMap.fromHashMapText . proj
    {-# INLINE proj #-}

instance Inj JSON.Value where
    inj = \case
        JSON.Null -> VNull
        JSON.Bool b -> inj b
        JSON.Number n -> inj n
        JSON.String s -> inj s
        JSON.Array a -> inj a
        JSON.Object o -> inj o

instance Proj JSON.Value where
    proj =
        forceWHNF >=> \case
            VNull -> pure JSON.Null
            VBool b -> pure (JSON.Bool b)
            VStr s -> pure (JSON.String s)
            v@(VNum _) -> JSON.Number <$> proj v
            VArr a -> JSON.Array <$> V.mapM proj a
            v@(VObj _ _) -> JSON.Object <$> proj v
            VFun{} -> throwE (ManifestError "function")
            _ -> throwE (ManifestError "impossible")

liftF :: (Proj a, Inj b) => (a -> b) -> (Value -> EvalM Value)
liftF f v = (inj $!) . f <$!> proj v
{-# INLINE liftF #-}

liftF2 :: (Proj a, Proj b, Inj c) => (a -> b -> c) -> Value -> Value -> EvalM Value
liftF2 f v1 v2 = (inj $!) <$!> liftA2 f (proj v1) (proj v2)
{-# INLINE liftF2 #-}