packages feed

jsonnet-0.5.0.0: src/Language/Jsonnet/Eval/Monad.hs

{-# LANGUAGE OverloadedStrings #-}

{- |
Module                  : Language.Jsonnet.Eval.Monad
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.Eval.Monad (
    -- * Monad
    EvalM (..),
    runEvalM,

    -- * Environment & state
    Env (..),
    vars,
    self,
    super,
    std,
    CallStack (..),
    spans,
    scopes,
    EvalState (..),
    env,
    baseEnv,
    callStack,
    currentPos,
    currentFile,
    loadedModules,
    importer,
    emptyStack,

    -- * Import plumbing
    ImportResult (..),
    Importer (..),
    ImpKey (..),

    -- * Error handling
    throwE,
    liftMaybe,
    asEvalError,
    (<?>),

    -- * Environment manipulation
    extendVars,
    pushVar,
    withBaseEnv,
    withEnv,
    withFieldEnv,
    withObjectEnv,
    withCurrentFile,

    -- * Call-stack / position tracking
    pushStackFrame,
    withCurrentPos,
    getBacktrace,
    getLineNum,
    getFileName,

    -- * Import helper
    fetchImport,
) where

import Control.Lens (Lens', view, (%~), (&), (.~), (^.))
import Control.Monad.Catch (SomeException, fromException, throwM, try)
import Control.Monad.Reader
import Data.IORef (IORef, readIORef, writeIORef)
import Data.Primitive (SmallArray, newSmallArray)
import Data.Primitive.SmallArray (runSmallArray)
import Data.Text qualified as T
import Language.Jsonnet.Common (Backtrace (..), Name, StackFrame (..))
import Language.Jsonnet.Core (Core)
import Language.Jsonnet.Error (Error (EvalError), EvalError (..))
import Language.Jsonnet.Eval.Types
import Language.Jsonnet.Parser.SrcSpan (SrcSpan, spanBegin)
import Text.Megaparsec.Pos (sourceLine, unPos)

throwE :: EvalError -> EvalM a
throwE e = throwM . EvalError e =<< getBacktrace
{-# INLINE throwE #-}

infixl 0 <?>
(<?>) :: EvalM (Either e a) -> (e -> EvalError) -> EvalM a
m <?> mkErr = m >>= either (throwE . mkErr) pure
{-# INLINE (<?>) #-}

liftMaybe :: EvalError -> Maybe a -> EvalM a
liftMaybe e = maybe (throwE e) pure

asEvalError :: SomeException -> EvalM a
asEvalError ex = case fromException ex of
    Just (e :: Error) -> throwM e
    Nothing -> throwE (RuntimeError (T.pack (show ex)))

{- | Strictly update 'EvalState' so closures and object caches never retain
unevaluated chains of caller environments. ('StrictData' cascades '!st''
into '_env' automatically.)
-}
localState :: (EvalState -> EvalState) -> EvalM a -> EvalM a
localState f act = do
    !st' <- asks f
    local (const st') act
{-# INLINE localState #-}

localEnv :: (Env -> Env) -> EvalM a -> EvalM a
localEnv f = localState (env %~ f)
{-# INLINE localEnv #-}

extendVars :: SmallArray Value -> EvalM a -> EvalM a
extendVars arr = localEnv (vars %~ (arr :))
{-# INLINE extendVars #-}

pushVar :: Value -> EvalM a -> EvalM a
pushVar v = extendVars (runSmallArray (newSmallArray 1 v))
{-# INLINE pushVar #-}

withBaseEnv :: EvalM a -> EvalM a
withBaseEnv = localState (\st -> st & env .~ (st ^. baseEnv))
{-# INLINE withBaseEnv #-}

withEnv :: Env -> EvalM a -> EvalM a
withEnv e = localEnv (const e)
{-# INLINE withEnv #-}

withObjectEnv :: Value -> Maybe Object -> EvalM a -> EvalM a
withObjectEnv selfVal sup =
    localEnv $ (self .~ Just selfVal) . (super .~ sup)
{-# INLINE withObjectEnv #-}

withFieldEnv :: Env -> EvalM a -> EvalM a
withFieldEnv lexEnv =
    localEnv $ \cur ->
        lexEnv & self .~ (cur ^. self) & super .~ (cur ^. super)
{-# INLINE withFieldEnv #-}

withCurrentFile :: FilePath -> EvalM a -> EvalM a
withCurrentFile fp = localState (currentFile .~ fp)
{-# INLINE withCurrentFile #-}

readRef :: Lens' EvalState (IORef a) -> EvalM a
readRef l = view l >>= liftIO . readIORef
{-# INLINE readRef #-}

{- | Temporarily update a mutable ref for the duration of an action.
Intentionally does not restore 'old' on exception so top-level 'asEvalError'
preserves the crash site's source position and call stack.
-}
withRef :: Lens' EvalState (IORef a) -> (a -> a) -> EvalM b -> EvalM b
withRef l f action = do
    ref <- view l
    old <- liftIO (readIORef ref)
    liftIO $ writeIORef ref $! f old
    res <- action
    liftIO $ writeIORef ref old
    pure res
{-# INLINE withRef #-}

pushStackFrame :: (Name, Maybe SrcSpan) -> EvalM a -> EvalM a
pushStackFrame (name, sp) =
    withRef callStack $ \(CallStack sps scs) ->
        CallStack (sp : sps) (name : scs)

withCurrentPos :: SrcSpan -> EvalM a -> EvalM a
withCurrentPos sp = withRef currentPos (const (Just sp))

getBacktrace :: EvalM (Backtrace Core)
getBacktrace = do
    mPos <- readRef currentPos
    CallStack sps scs <- readRef callStack
    pure $ Backtrace $ case sequence (mPos : sps) of
        Just sps' -> zipWith StackFrame scs sps'
        Nothing -> maybe [] (\pos -> [StackFrame "top-level" pos]) mPos

getLineNum :: EvalM (Maybe Int)
getLineNum = do
    mPos <- readRef currentPos
    pure (unPos . sourceLine . spanBegin <$> mPos)

getFileName :: EvalM FilePath
getFileName = view currentFile

fetchImport :: String -> EvalM ImportResult
fetchImport path = do
    cf <- view currentFile
    Importer resolve <- view importer
    either throwE pure =<< liftIO (try (resolve cf path))