-- | Miscellaneous utility functions

module Dhall.LSP.Util (
  tshow,
  lines',
  rightToMaybe,
  unlines'
) where

import Data.List.NonEmpty
import Data.Text

-- | Shorthand for @pack . show@. Useful since we are mostly working with Text
--   rather than String.
tshow :: Show a => a -> Text
tshow :: a -> Text
tshow = String -> Text
pack (String -> Text) -> (a -> String) -> a -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. a -> String
forall a. Show a => a -> String
show

-- | A variant of @Data.Text.lines@ that does not swallow the last empty. Always
--   returns at least the empty line!
lines' :: Text -> NonEmpty Text
lines' :: Text -> NonEmpty Text
lines' Text
text =
    case (Char -> Bool) -> Text -> [Text]
split (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'\n') Text
text of
      []     -> Text
"" Text -> [Text] -> NonEmpty Text
forall a. a -> [a] -> NonEmpty a
:| []  -- this case never occurs!
      Text
l : [Text]
ls -> Text
l  Text -> [Text] -> NonEmpty Text
forall a. a -> [a] -> NonEmpty a
:| [Text]
ls

-- | A variant of @Data.Text.unlines@ that is the exact inverse to @lines'@ (and
--   vice-versa).
unlines' :: [Text] -> Text
unlines' :: [Text] -> Text
unlines' = Text -> [Text] -> Text
intercalate Text
"\n"

rightToMaybe :: Either a b -> Maybe b
rightToMaybe :: Either a b -> Maybe b
rightToMaybe (Right b
b) = b -> Maybe b
forall a. a -> Maybe a
Just b
b
rightToMaybe (Left a
_) = Maybe b
forall a. Maybe a
Nothing