summaryrefslogtreecommitdiff
path: root/lambda-calcul/haskell/src/Minilang/IO.hs
blob: bfcb12503c0bc61f96a4773938609ac128b629c9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC "-fno-warn-orphans" #-}

module Minilang.IO where

import qualified Data.ByteString as BS
import Data.Text.Encoding
  ( decodeUtf8With,
    encodeUtf8,
  )
import Data.Text.Encoding.Error (lenientDecode)
import Minilang.Lambda.Eval hiding (rho)
import Minilang.Parser
import Minilang.Type
import Prettyprinter
import Prettyprinter.Render.Text
import System.IO (Handle)

-- | Read an `AST` from @hin@ handle, evaluate it and dump the result
-- on @hout@.
runEval :: Handle -> Handle -> IO ()
runEval hin hout = do
  programText <- decodeUtf8With lenientDecode <$> BS.hGetContents hin
  let ast = parseProgram False programText
      ρ = EmptyEnv
      γ = EmptyContext
  (ρ', _) <- loadProgram ast ρ γ
  let val = eval ast ρ'

  BS.hPut
    hout
    ( encodeUtf8
        ( renderStrict $ layoutPretty defaultLayoutOptions $ pretty val
        )
        <> "\n"
    )