okf-core-0.14.0.0: src/Okf/Yaml.hs
-- | YAML 1.2 core values and source positions for frontmatter edits.
module Okf.Yaml
( Located (..),
Children (..),
parseYaml,
renderYaml,
patchYaml,
)
where
import Conduit (runConduitRes, sinkList, yieldMany, (.|))
import Control.Exception (try)
import Data.Aeson qualified as Aeson
import Data.Aeson.Key qualified as Key
import Data.Aeson.KeyMap qualified as KeyMap
import Data.Attoparsec.Text qualified as Atto
import Data.ByteString.Lazy qualified as Lazy
import Data.ByteString.Unsafe qualified as Bytes.Unsafe
import Data.Char (isDigit)
import Data.List qualified as List
import Data.Map.Strict qualified as Map
import Data.Scientific qualified as Scientific
import Data.Text qualified as Text
import Data.Text.Encoding qualified as Encoding
import Data.Vector qualified as Vector
import Data.Yaml qualified as Yaml
import Okf.Prelude (Text, Value (..), first, fromMaybe, isJust, when, (<|>))
import System.IO.Unsafe (unsafePerformIO)
import Text.Libyaml qualified as Lib
data Located = Located
{ yamlValue :: !Value,
yamlStart :: !Int,
yamlEnd :: !Int,
yamlChildren :: !Children
}
deriving stock (Show)
data Children
= Leaf
| Items [Located]
| Members Lib.MappingStyle (KeyMap.KeyMap Located)
deriving stock (Show)
-- Libyaml recognizes YAML syntax. Its events leave implicit tag resolution to
-- the caller, so this layer can apply core semantics and retain source marks.
parseYaml :: Text -> Either Text (Maybe Located)
parseYaml input = do
events <- first (Text.pack . show) (decodeEvents input)
case events of
[] -> pure Nothing
[Lib.MarkedEvent Lib.EventStreamStart _ _, Lib.MarkedEvent Lib.EventStreamEnd _ _] -> pure Nothing
Lib.MarkedEvent Lib.EventStreamStart _ _ : Lib.MarkedEvent Lib.EventDocumentStart _ _ : rest -> do
(root, _, suffix) <- readNode Map.empty rest
case map Lib.yamlEvent suffix of
[Lib.EventDocumentEnd, Lib.EventStreamEnd] -> pure (Just root)
_ -> Left "expected a single YAML document"
_ -> Left "expected a YAML document"
{-# NOINLINE decodeEvents #-}
decodeEvents :: Text -> Either Lib.YamlException [Lib.MarkedEvent]
decodeEvents input = unsafePerformIO (try (runConduitRes (Lib.decodeMarked (Encoding.encodeUtf8 input) .| sinkList)))
type Anchors = Map.Map Lib.AnchorName Value
readNode :: Anchors -> [Lib.MarkedEvent] -> Either Text (Located, Anchors, [Lib.MarkedEvent])
readNode anchors (event : rest) =
case Lib.yamlEvent event of
Lib.EventScalar bytes tag style anchor -> do
value <- scalarValue tag style (Encoding.decodeUtf8 bytes)
finish event value Leaf anchor anchors rest
Lib.EventAlias name ->
case Map.lookup name anchors of
Nothing -> Left ("unknown or cyclic YAML alias: " <> Text.pack name)
Just value -> finish event value Leaf Nothing anchors rest
Lib.EventSequenceStart tag style anchor
| tag `elem` [Lib.NoTag, Lib.SeqTag, Lib.UriTag "!"] -> do
(items, updated, end, suffix) <- readItems anchors rest
let value = Array (Vector.fromList (map yamlValue items))
let end' = case style of
Lib.BlockSequence -> contentEnd end items
_ -> end
finish end' value (Items items) anchor updated suffix
Lib.EventMappingStart tag style anchor
| tag `elem` [Lib.NoTag, Lib.MapTag, Lib.UriTag "!"] -> do
(members, updated, end, suffix) <- readMembers KeyMap.empty anchors rest
let value = Object (KeyMap.map yamlValue members)
let end' = case style of
Lib.BlockMapping -> contentEnd end (KeyMap.elems members)
_ -> end
finish end' value (Members style members) anchor updated suffix
_ -> Left "unsupported YAML tag or node"
where
contentEnd fallback children =
case map yamlEnd children of
[] -> fallback
offsets -> fallback {Lib.yamlEndMark = (Lib.yamlEndMark fallback) {Lib.yamlIndex = maximum offsets}}
finish end value children anchor updated suffix =
Right
( Located value (Lib.yamlIndex (Lib.yamlStartMark event)) (Lib.yamlIndex (Lib.yamlEndMark end)) children,
maybe updated (\name -> Map.insert name value updated) anchor,
suffix
)
readNode _ [] = Left "expected a YAML value"
readItems :: Anchors -> [Lib.MarkedEvent] -> Either Text ([Located], Anchors, Lib.MarkedEvent, [Lib.MarkedEvent])
readItems anchors (end@(Lib.MarkedEvent Lib.EventSequenceEnd _ _) : rest) = Right ([], anchors, end, rest)
readItems anchors events = do
(item, updated, rest) <- readNode anchors events
(items, final, end, suffix) <- readItems updated rest
pure (item : items, final, end, suffix)
readMembers :: KeyMap.KeyMap Located -> Anchors -> [Lib.MarkedEvent] -> Either Text (KeyMap.KeyMap Located, Anchors, Lib.MarkedEvent, [Lib.MarkedEvent])
readMembers members anchors (end@(Lib.MarkedEvent Lib.EventMappingEnd _ _) : rest) = Right (members, anchors, end, rest)
readMembers members anchors events@(Lib.MarkedEvent (Lib.EventScalar bytes _ _ _) _ _ : _) = do
let key = Key.fromText (Encoding.decodeUtf8 bytes)
when (KeyMap.member key members) (Left ("duplicate YAML key: " <> Key.toText key))
(_, withKey, afterKey) <- readNode anchors events
(value, updated, afterValue) <- readNode withKey afterKey
readMembers (KeyMap.insert key value members) updated afterValue
readMembers _ _ _ = Left "expected a scalar YAML mapping key"
scalarValue :: Lib.Tag -> Lib.Style -> Text -> Either Text Value
scalarValue tag style text =
case tag of
Lib.NoTag
| style == Lib.Plain -> Right (plainScalar text)
| otherwise -> Right (String text)
Lib.StrTag -> Right (String text)
Lib.UriTag "!" -> Right (String text)
Lib.NullTag | Null <- plainScalar text -> Right Null
Lib.BoolTag | value@(Bool _) <- plainScalar text -> Right value
Lib.IntTag | Just value <- integer text -> Right (Number (fromInteger value))
Lib.FloatTag | Just value <- number text -> Right value
Lib.UriTag "tag:yaml.org,2002:timestamp" -> Right (String text)
_ -> Left ("unsupported YAML tag or invalid tagged value: " <> Text.pack (show tag))
plainScalar :: Text -> Value
plainScalar text
| text `elem` ["", "~", "null", "Null", "NULL"] = Null
| text `elem` ["true", "True", "TRUE"] = Bool True
| text `elem` ["false", "False", "FALSE"] = Bool False
| otherwise = fromMaybe (String text) (number text)
-- JSON has no representation for non-finite numbers. Keep their spelling as
-- text in the projection while retaining the original YAML node for editing.
number :: Text -> Maybe Value
number text
| text `elem` [".inf", ".Inf", ".INF", "+.inf", "+.Inf", "+.INF", "-.inf", "-.Inf", "-.INF", ".nan", ".NaN", ".NAN"] = Just (String text)
| Just value <- integer text = Just (Number (fromInteger value))
| otherwise = Number <$> parsed decimalNumber text
decimalNumber :: Atto.Parser Scientific.Scientific
decimalNumber = do
sign <- Atto.option "" (Atto.string "-" <|> Atto.string "+")
whole <- Atto.takeWhile isDigit
fraction <- Atto.option Nothing (Just <$> (Atto.char '.' *> Atto.takeWhile isDigit))
when (Text.null whole && maybe True Text.null fraction) (fail "expected a digit")
exponentPart <- Atto.takeText
let wholeDigits = if Text.null whole then "0" else whole
decimalDigits = maybe "" (\digits -> if Text.null digits then ".0" else "." <> digits) fraction
either fail pure (Atto.parseOnly (Atto.scientific <* Atto.endOfInput) (sign <> wholeDigits <> decimalDigits <> exponentPart))
integer :: Text -> Maybe Integer
integer text =
parsed (Atto.signed Atto.decimal) text
<|> parsed (Atto.string "0x" *> Atto.hexadecimal) text
<|> parsed (Atto.string "0o" *> octal) text
where
octal = Text.foldl' (\n digit -> 8 * n + fromIntegral (fromEnum digit - fromEnum '0')) 0 <$> Atto.takeWhile1 (\c -> c >= '0' && c <= '7')
parsed :: Atto.Parser a -> Text -> Maybe a
parsed parser = either (const Nothing) Just . Atto.parseOnly (parser <* Atto.endOfInput)
renderYaml :: (Text -> (Int, Text)) -> Value -> Text
renderYaml rank value =
Encoding.decodeUtf8 (unsafePerformIO (runConduitRes (yieldMany events .| Lib.encode)))
where
events = Lib.EventStreamStart : Lib.EventDocumentStart : emit value [Lib.EventDocumentEnd, Lib.EventStreamEnd]
emit (Object members) rest =
Lib.EventMappingStart Lib.NoTag Lib.BlockMapping Nothing
: foldr emitMember (Lib.EventMappingEnd : rest) ordered
where
ordered = List.sortOn (rank . Key.toText . fst) (KeyMap.toList members)
emitMember (key, item) suffix = emit (String (Key.toText key)) (emit item suffix)
emit (Array items) rest =
Lib.EventSequenceStart Lib.NoTag Lib.BlockSequence Nothing
: foldr emit (Lib.EventSequenceEnd : rest) items
emit (String text) rest = Lib.EventScalar bytes tag style Nothing : rest
where
-- libyaml asserts that a scalar has a non-null pointer, even when its
-- length is zero. The empty ByteString may use a null pointer.
bytes
| Text.null text = Bytes.Unsafe.unsafeTake 0 "0"
| otherwise = Encoding.encodeUtf8 text
(tag, style)
| Text.null text = (Lib.NoTag, Lib.SingleQuoted)
| isJust (number text) = (Lib.NoTag, Lib.SingleQuoted)
| otherwise = Yaml.defaultStringStyle text
emit item rest = Lib.EventScalar (Lazy.toStrict (Aeson.encode item)) Lib.NoTag Lib.PlainNoTag Nothing : rest
-- Retain source around edits at the smallest unchanged collection shape.
-- Reparse the patched text in case an anchor, block indentation, or insertion
-- changes any value beyond the intended one.
patchYaml :: (Text -> (Int, Text)) -> Text -> Located -> Value -> Maybe Text
patchYaml rank source root value
| yamlValue root == value = Just source
| otherwise = do
edits <- rootEdits
let candidate = applyEdits edits
reparsed <- either (const Nothing) Prelude.id (parseYaml candidate)
if yamlValue reparsed == value then Just candidate else Nothing
where
rootEdits =
case (yamlChildren root, value) of
(Members style original, Object new)
| all (`KeyMap.member` new) (KeyMap.keys original) -> do
changed <- memberEdits original new
let additions = KeyMap.difference new original
extra <- insertMembers style original additions
pure (extra <> changed)
_ -> Just (editsFor root value)
insertMembers _ _ additions | KeyMap.null additions = Just []
insertMembers Lib.BlockMapping _ additions =
let position = yamlStart root
rendered = renderYaml rank (Object additions)
insertion = if "\r\n" `Text.isInfixOf` source then Text.replace "\n" "\r\n" rendered else rendered
in Just [(position, position, insertion)]
insertMembers Lib.FlowMapping original additions = do
brace <- Text.findIndex (== '{') (Text.drop (yamlStart root) source)
let position = yamlStart root + brace + 1
rendered = Text.dropEnd 1 (Text.drop 1 (inlineValue (Object additions)))
pure [(position, position, rendered <> if KeyMap.null original then "" else ", ")]
insertMembers _ _ _ = Nothing
memberEdits original new = concat <$> traverse member (KeyMap.toList original)
where
member (key, old) = editsFor old <$> KeyMap.lookup key new
editsFor old new
| yamlValue old == new = []
| Items items <- yamlChildren old,
Array values <- new,
length items == Vector.length values =
concat (zipWith editsFor items (Vector.toList values))
| Members _ original <- yamlChildren old,
Object members <- new,
KeyMap.size original == KeyMap.size members,
Just edits <- memberEdits original members =
edits
| otherwise =
[(yamlStart old, yamlEnd old, insertSpace <> inlineValue new)]
where
-- A YAML empty value may start immediately after the mapping colon.
insertSpace
| yamlStart old == yamlEnd old, ":" `Text.isSuffixOf` Text.take (yamlStart old) source = " "
| otherwise = ""
inlineValue = Encoding.decodeUtf8 . Lazy.toStrict . Aeson.encode
applyEdits = splice 0 . List.sortOn (\(start, _, _) -> start)
splice offset [] = Text.drop offset source
splice offset ((start, end, replacement) : rest) =
Text.take (start - offset) (Text.drop offset source) <> replacement <> splice end rest