packages feed

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

{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TupleSections #-}

{- |
Module      : Language.Jsonnet.Object
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.Object (
    -- * Re-exported from Eval.Types
    Object (..),
    Field (..),
    fieldVal,
    fieldVis,
    layers,
    null,
    assertField,
    mkBaseObject,
    mkSingletonObject,

    -- * Query functions
    isVisible,
    allKeys,
    visibleKeys,
    regularKeys,
    assertionKeys,
    lookupField,
) where

import Control.Lens (view)
import Data.HashMap.Strict (HashMap)
import Data.HashMap.Strict qualified as H
import Data.List qualified as L
import Data.Text (Text)
import Language.Jsonnet.Common (Visibility (..))
import Language.Jsonnet.Eval.Types (
    Field (..),
    Object (..),
    assertField,
    fieldVal,
    fieldVis,
    layers,
    null,
    mkBaseObject,
    mkSingletonObject,
 )
import Prelude hiding (null)

isVisible :: Field -> Bool
isVisible f = view fieldVis f /= Hidden && not (view assertField f)

filterKeys :: (Field -> Bool) -> Object -> [Text]
filterKeys _ Empty = []
filterKeys p (Singleton k f) = [k | p f]
filterKeys p obj = L.sort [k | (k, f) <- H.toList (flattenFields obj), p f]

allKeys, visibleKeys, regularKeys, assertionKeys :: Object -> [Text]
allKeys = filterKeys (const True)
visibleKeys = filterKeys isVisible
regularKeys = filterKeys (not . view assertField)
assertionKeys = filterKeys (view assertField)

flattenFields :: Object -> HashMap Text Field
flattenFields = \case
    Empty -> H.empty
    Singleton k f -> H.singleton k f
    Base m -> m
    Mixin _ l (Singleton k f) -> H.insertWith (flip (<>)) k f (flattenFields l)
    Mixin _ l r -> H.unionWith (<>) (flattenFields l) (flattenFields r)

{- | Look up a field, returning the field, its depth in the prototype chain,
  and the super-object (if any) for @super@ references.
-}
lookupField :: Text -> Object -> Maybe (Field, Int, Maybe Object)
lookupField k = go 0
  where
    go !_ Empty = Nothing
    go !d (Singleton k' f)
        | k == k' = Just (f, d, Nothing)
        | otherwise = Nothing
    go !d (Base m) = (,d,Nothing) <$> H.lookup k m
    go !d (Mixin _ l r) =
        case go (d + layers l) r of
            Just (f, d', rSuper) ->
                Just (f, d', Just (maybe l (l <>) rSuper))
            Nothing -> go d l