unitype-codegen 0.2.0

TypeScript, Python, Rust, and Haskell code generation backends for unitype
Documentation
-- Generated by unitype. Do not edit.
--
-- Makes a Haskell module reachable as a proof, over standard input and output.
--
-- This is the whole of what it takes to take part: read a message, do the work,
-- write one back. One message per line, and reading lines serves both ways of
-- being called -- if the parent sends one message and closes the stream, this
-- runs once and the process exits; if the parent keeps the stream open, it keeps
-- answering. Nothing here has to know which is happening.
--
-- Give it a table of what the module proves, keyed by the entry name a manifest
-- points at. A proof is an ordinary function, of any number of arguments, over
-- types that can travel:
--
-- > {-# LANGUAGE OverloadedStrings #-}
-- > import Demo (Tally (..))
-- > import UnitypeHarness (proves, unitypeMain)
-- >
-- > tally :: [Text] -> Tally
-- > tally = ...
-- >
-- > main :: IO ()
-- > main = unitypeMain [("tally", proves tally)]
--
-- A proof that has to wait for something returns its answer in `IO`.
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE UndecidableInstances #-}
module UnitypeHarness
  ( unitypeMain
  , proves
  , Proof
  ) where

import Control.Exception (SomeException (..), displayException, evaluate, try)
import Control.Monad (unless)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as TIO
import Data.Typeable (typeOf)
import System.IO (hFlush, hSetEncoding, isEOF, stdin, stdout, utf8)
import UnitypeSupport

-- | What went wrong, as the parent is told: a code, then a message.
data Failure = Failure Text Text

-- | Something this module proves.
newtype Proof = Proof ([Json] -> IO (Either Failure Json))

-- | A function that can be a proof: it takes arguments that can be read from
-- JSON, and gives back an answer that can be written as it, possibly in `IO`.
class Proves f where
  run :: f -> [Json] -> IO (Either Failure Json)

instance {-# OVERLAPPING #-} (FromJson a, Proves b) => Proves (a -> b) where
  run _ [] = pure (Left (Failure "bad_arguments" "this proof takes more arguments than it was sent"))
  run f (x : xs) = case fromJson x of
    Left e -> pure (Left (Failure "bad_argument" (T.pack e)))
    Right a -> run (f a) xs

instance {-# OVERLAPPING #-} ToJson r => Proves (IO r) where
  run _ (_ : _) = pure (Left tooMany)
  run act [] = Right . toJson <$> act

instance {-# OVERLAPPABLE #-} ToJson r => Proves r where
  run _ (_ : _) = pure (Left tooMany)
  run r [] = pure (Right (toJson r))

tooMany :: Failure
tooMany = Failure "bad_arguments" "this proof takes fewer arguments than it was sent"

-- | Makes a function a proof.
proves :: Proves f => f -> Proof
proves = Proof . run

-- | Answers every message on standard input, until there are no more.
unitypeMain :: [(String, Proof)] -> IO ()
unitypeMain table = do
  hSetEncoding stdin utf8
  hSetEncoding stdout utf8
  loop
  where
    proofs = Map.fromList [(T.pack entry, proof) | (entry, proof) <- table]
    loop = do
      done <- isEOF
      unless done $ do
        line <- TIO.hGetLine stdin
        unless (T.all (`elem` (" \t\r" :: String)) line) (answer proofs line)
        loop

-- | Answers one message, whatever happens while doing it.
answer :: Map Text Proof -> Text -> IO ()
answer proofs line = do
  outcome <- try (respond proofs line)
  send $ case outcome of
    Right text -> text
    Left (SomeException e) -> failureLine (Failure (T.pack (show (typeOf e))) (T.pack (displayException e)))

respond :: Map Text Proof -> Text -> IO Text
respond proofs line = case parseJson line of
  Left e -> pure (failureLine (Failure "bad_request" ("could not read the request: " <> T.pack e)))
  Right (JObject request) -> case (Map.lookup "unitype" request, Map.lookup "kind" request) of
    (Just (JString "1"), Just (JString "invoke")) -> invoke proofs request
    (Just (JString "1"), other) ->
      pure (failureLine (Failure "bad_kind" ("cannot do " <> display other)))
    (other, _) ->
      pure (failureLine (Failure "bad_version" ("this module speaks version 1, not " <> display other)))
  Right _ -> pure (failureLine (Failure "bad_request" "a request is a JSON object"))

invoke :: Map Text Proof -> Map Text Json -> IO Text
invoke proofs request = case Map.lookup "entry" request of
  Just (JString entry) -> case Map.lookup entry proofs of
    Nothing ->
      pure
        ( failureLine
            ( Failure
                "no_such_entry"
                ("this module proves " <> known <> ", not " <> display (Just (JString entry)))
            )
        )
    Just (Proof prove) -> do
      let args = case Map.lookup "args" request of
            Just (JArray xs) -> xs
            _ -> []
      result <- prove args
      case result of
        Left failure -> pure (failureLine failure)
        Right v -> case renderJson (object [("ok", Just (JBool True)), ("value", Just v)]) of
          Left e -> pure (failureLine (Failure "bad_value" (T.pack e)))
          Right text -> evaluate text
  _ -> pure (failureLine (Failure "no_such_entry" "a request names the entry it wants"))
  where
    known = if Map.null proofs then "nothing" else T.intercalate ", " (Map.keys proofs)

-- | A value as it would be written in a message, or what to say if there is none.
display :: Maybe Json -> Text
display = maybe "nothing" (either (const "something unreadable") id . renderJson)

-- | A failure of the proof, not of the process: exiting non-zero would say the
-- environment is broken, which it is not.
failureLine :: Failure -> Text
failureLine (Failure code message) =
  case renderJson
    ( object
        [ ("ok", Just (JBool False))
        , ("error", Just (object [("code", Just (JString code)), ("message", Just (JString message))]))
        ]
    ) of
    Right text -> text
    Left _ -> "{\"ok\":false,\"error\":{\"code\":\"bad_value\",\"message\":\"\"}}"

-- | One line, flushed: a parent waiting on the next line would otherwise wait
-- on a buffer that never fills.
send :: Text -> IO ()
send text = TIO.putStrLn text >> hFlush stdout