Skip to content

A peer-to-peer stack for code collaboration

Proper mutable references

Julian K. Arni6f5ebeed07a1
diff --git a/.stylish-haskell.yaml b/.stylish-haskell.yaml
index 9d33231..027a6b7 100644
--- a/.stylish-haskell.yaml
+++ b/.stylish-haskell.yaml
@@ -178,6 +178,8 @@ newline: native
language_extensions:
- FlexibleContexts
+ - FunctionalDependencies
+ - MultiParamTypeClasses
- MultiWayIf
- RecordWildCards
- ScopedTypeVariables
diff --git a/package.yaml b/package.yaml
index ac17462..d9c62c6 100644
--- a/package.yaml
+++ b/package.yaml
@@ -11,18 +11,22 @@ extra-source-files:
dependencies:
- base >=4 && <5
- containers
+- deriving-compat
- haskeline
- megaparsec
- mmorph
- mtl
- prettyprinter
- prettyprinter-ansi-terminal
+- recursion-schemes
- scientific
+- STMonadTrans
- syb
- text
data-files:
- repl/config.rad
+- repl/prelude.rad
library:
source-dirs: src
@@ -36,6 +40,7 @@ tests:
ghc-options: -Wall -threaded
dependencies:
- radicle
+ - directory
- QuickCheck
- quickcheck-instances
- interpolate
@@ -72,6 +77,8 @@ default-extensions:
- ConstraintKinds
- DeriveDataTypeable
- DeriveFunctor
+- DeriveFoldable
+- DeriveTraversable
- DeriveGeneric
- FlexibleContexts
- FlexibleInstances
diff --git a/repl/prelude.rad b/repl/prelude.rad
index 3911bf3..e6d0516 100644
--- a/repl/prelude.rad
+++ b/repl/prelude.rad
@@ -1,8 +1,8 @@
(define should-be
(lambda (name x y)
(if (eq? x y)
- (print! (cons "test" (cons name (list "succeeded"))))
- (print! (cons "test" (cons name (list "failed")))))))
+ (print! (string-append "Test '" name "' succeeded"))
+ (print! (string-append "Test '" name "' failed")))))
;; empty?
(define empty? (lambda (ls) (eq? ls (list))))
@@ -55,7 +55,50 @@
(filter (lambda (x) (< x 10)) (list 3 10 11))
(list 3))
-;; The Repl
+;; modify-ref
+(define modify-ref (lambda (ref fn)
+ (write-ref ref (fn (deref ref)))))
+
+;; modify-map
+(define modify-map (lambda (key fn mp)
+ (insert key (fn (lookup key mp)) mp)))
+
+(should-be "modify-map"
+ (modify-map 'a (lambda (x) (+ x 1)) (sorted-map a 5))
+ (sorted-map a 6))
+
+;; Account stuff. Should be moved elsewhere when we have an import mechanism
+
+(define create-currency (lambda ()
+
+ ;; The map of all accounts
+ (define accounts (ref (sorted-map)))
+
+ ;; Create an account with 10 coins.
+ (define new-account (lambda (name)
+ (modify-ref accounts (lambda (acc)
+ (insert name 10 acc)))))
+
+ ;; Get an account's balance
+ (define account-balance (lambda (name)
+ (lookup name (deref accounts))))
+
+ ;; Transfer money
+ (define transfer (lambda (from to amount)
+ (define acc (deref accounts))
+ (write-ref accounts (if (> amount (lookup from acc))
+ (print! "not enough balance")
+ (modify-map
+ to
+ (lambda (x) (+ x amount))
+ (modify-map from (lambda (x) (- x amount)) acc))))))
+
+ (define dispatch (lambda (m)
+ (if (eq? m 'new-account) new-account
+ (if (eq? m 'account-balance) account-balance
+ (if (eq? m 'transfer) transfer
+ (print! "error: currency- unknown message"))))))
+ dispatch))
(define repl
(sorted-map name "repl" getter (quote (get-line!))))
diff --git a/src/Radicle.hs b/src/Radicle.hs
index 8c24c4e..e4afc80 100644
--- a/src/Radicle.hs
+++ b/src/Radicle.hs
@@ -18,6 +18,10 @@ module Radicle
, LangError(..)
, ($$)
, Ident
+ , Reference(..)
+ , makeRefs
+ , labelRefs
+ , coerceRefs
, fromIdent
, mkIdent
, Env(..)
diff --git a/src/Radicle/Internal/Core.hs b/src/Radicle/Internal/Core.hs
index 06a662c..27d229f 100644
--- a/src/Radicle/Internal/Core.hs
+++ b/src/Radicle/Internal/Core.hs
@@ -1,18 +1,22 @@
{-# LANGUAGE ScopedTypeVariables #-}
-{-# LANGUAGE UndecidableInstances #-}
+{-# LANGUAGE TemplateHaskell #-}
module Radicle.Internal.Core where
import Control.Monad.Except (ExceptT(..), MonadError, runExceptT,
throwError)
+import Control.Monad.ST.Trans (STRef, STT, newSTRef, readSTRef,
+ runSTT, writeSTRef)
import Control.Monad.State
import Data.Bifunctor (first)
-import Data.Data ((:~:)(Refl), Data, cast, eqT)
-import Data.Generics (everywhereM)
+import Data.Data (Data)
+import Data.Deriving (deriveEq1, deriveShow1)
+import Data.Functor.Foldable (Fix(..), cata)
import Data.List (foldl')
import Data.List.NonEmpty (NonEmpty)
import qualified Data.List.NonEmpty as NonEmpty
import Data.Map (Map)
import qualified Data.Map as Map
+import Data.Maybe (catMaybes, isJust)
import Data.Scientific (Scientific)
import Data.Semigroup (Semigroup, (<>))
import Data.Text (Text)
@@ -20,7 +24,7 @@ import Data.Void (Void)
import GHC.Exts (IsList(..), fromString)
import GHC.Generics (Generic)
import qualified Text.Megaparsec.Error as Par
-
+import Unsafe.Coerce (unsafeCoerce)
-- * Value
@@ -37,27 +41,76 @@ data LangError =
| Exit
deriving (Eq, Show, Read, Generic)
+newtype Reference s = Reference { getReference :: STRef s (Value (Reference s)) }
+ deriving (Eq)
+
+-- | Create a new ref with the supplied initial value.
+newRef :: Monad m => Value (Reference s) -> Lang s m (Value (Reference s))
+newRef v = LangT $ lift $ lift $ Ref . Reference <$> newSTRef v
+
+-- | Read the value of a reference.
+deref :: Monad m => Reference s -> Lang s m (Value (Reference s))
+deref (Reference r) = LangT . lift . lift $ readSTRef r
-- | An expression or value in the language.
-data Value =
+--
+-- The parameter is for refs. Usually it is 'Reference s' (with 's' being the
+-- thread param of the ST monad). However, we first parse into 'Fix Value'
+-- before converting it into 'Reference' (see 'makeRefs').
+--
+-- A Value that no longer contains any references can have type 'Value Void',
+-- indicating it is safe to share between threads or chains.
+data Value r =
-- | A regular (hyperstatic) variable.
Atom Ident
| String Text
| Number Scientific
| Boolean Bool
- | List [Value]
+ | List [Value r]
| Primop Ident
- | Apply Value [Value]
- | SortedMap (Map.Map Ident Value)
- -- | A variable that must be looked up at the *call-site*.
- | Ref Ident
+ | Apply (Value r) [Value r]
+ | SortedMap (Map.Map Ident (Value r))
+ | Ref r
-- | Takes the arguments/parameters, a body, and possibly a closure.
--
-- The value of an application of a lambda is always the last value in the
-- body. The only reason to have multiple values is thus only for (local)
-- "define"s.
- | Lambda [Ident] (NonEmpty Value) (Maybe Env)
- deriving (Eq, Ord, Show, Read, Generic, Data)
+ | Lambda [Ident] (NonEmpty (Value r)) (Maybe (Env (Value r)))
+ deriving (Eq, Show, Read, Generic, Functor, Foldable, Traversable)
+
+
+-- | Replace all Refs containing 'Fix Value' into ones containing references to
+-- those values.
+makeRefs :: Monad m => Value (Fix Value) -> Lang s m (Value (Reference s))
+makeRefs v = cata go (Fix v)
+ where
+ go x = case x of
+ Atom i -> pure $ Atom i
+ String i -> pure $ String i
+ Boolean i -> pure $ Boolean i
+ Number i -> pure $ Number i
+ Primop i -> pure $ Primop i
+ Apply f vs -> Apply <$> go f <*> sequence (go <$> vs)
+ SortedMap m -> SortedMap <$> sequence (go <$> m)
+ List vs -> List <$> sequence (go <$> vs)
+ Ref i -> i >>= newRef
+ Lambda is bd e -> Lambda is <$> sequence (go <$> bd)
+ <*> traverse sequence (fmap go <$> e)
+
+-- | Replace all refs containing a 'Reference' into ones containing a number
+-- representing that 'Reference'.
+labelRefs :: Value (Reference s) -> Value Int
+labelRefs v = evalState (traverse go v) (0, [])
+ where
+ go :: Reference s -> State (Int, [(Reference s, Int)]) Int
+ go s = get >>= \(cur, mapping) -> case lookup s mapping of
+ Nothing -> put (cur + 1, (s, cur):mapping) >> pure cur
+ Just ix -> pure ix
+
+-- | Safely coerce a 'Value' containing no refs into one of a different type.
+coerceRefs :: Value Void -> Value a
+coerceRefs = unsafeCoerce
-- | An identifier in the language.
--
@@ -72,39 +125,43 @@ toIdent :: String -> Ident
toIdent = Ident . fromString
-- | The environment, which keeps all known bindings.
-newtype Env = Env { fromEnv :: Map Ident Value }
- deriving (Eq, Show, Ord, Read, Semigroup, Monoid, Generic, Data)
+newtype Env s = Env { fromEnv :: Map Ident s }
+ deriving (Eq, Semigroup, Monoid, Show, Read, Generic, Functor, Foldable, Traversable)
-instance IsList Env where
- type Item Env = (Ident, Value)
+instance IsList (Env s) where
+ type Item (Env s) = (Ident, s)
fromList = Env . fromList
toList = GHC.Exts.toList . fromEnv
-- | Primop mappings. The parameter specifies the monad the primops run in.
-type Primops m = Map Ident ([Value] -> LangT (Bindings m) m Value)
+type Primops s m = Map Ident ([Value (Reference s)] -> Lang s m (Value (Reference s)))
-- | Bindings, either from the env or from the primops.
-data Bindings m = Bindings
- { bindingsEnv :: Env
- , bindingsPrimops :: Primops m
+data Bindings s m = Bindings
+ { bindingsEnv :: Env (Value (Reference s))
+ , bindingsPrimops :: Primops s m
} deriving (Generic)
-- | The environment in which expressions are evaluated.
-newtype LangT r m a = LangT
- { fromLangT :: ExceptT LangError (StateT r m) a }
+newtype LangT s r m a = LangT
+ { fromLangT :: ExceptT LangError (StateT r (STT s m)) a }
deriving (Functor, Applicative, Monad, MonadError LangError, MonadState r)
-instance MonadTrans (LangT r) where lift = LangT . lift . lift
+instance MonadTrans (LangT s r) where lift = LangT . lift . lift . lift
-- | A monad for language operations specialized to have as state the Bindings
-- with appropriate underlying monad.
-type Lang m = LangT (Bindings m) m
+type Lang s m = LangT s (Bindings s m) m
-runLang :: Monad m => Bindings m -> Lang m a -> m (Either LangError a)
-runLang e l = evalStateT (runExceptT $ fromLangT l) e
+runLang
+ :: Monad m
+ => (forall s. Bindings s m)
+ -> (forall s. Lang s m a)
+ -> m (Either LangError a)
+runLang e l = runSTT $ evalStateT (runExceptT $ fromLangT l) e
-- | Like 'local' or 'withState'
-withEnv :: Monad m => (Bindings m -> Bindings m) -> Lang m a -> Lang m a
+withEnv :: Monad m => (Bindings s m -> Bindings s m) -> Lang s m a -> Lang s m a
withEnv modifier action = do
oldEnv <- get
modify modifier
@@ -115,33 +172,33 @@ withEnv modifier action = do
-- * Functions
-- | A Bindings with an Env containing only 'eval' and only pure primops.
-pureEnv :: Monad m => Bindings m
+pureEnv :: (Monad m) => Bindings r m
pureEnv = Bindings e purePrimops
where
e = fromList [(toIdent "eval", Primop $ toIdent "base-eval")]
-addBinding :: Monad m => Ident -> Value -> Bindings m -> Bindings m
+addBinding :: Monad m => Ident -> Value (Reference r) -> Bindings r m -> Bindings r m
addBinding i v b = b
{ bindingsEnv = Env . Map.insert i v . fromEnv $ bindingsEnv b }
-- | Lookup an atom in the environment
-lookupAtom :: Monad m => Ident -> Lang m Value
+lookupAtom :: Monad m => Ident -> Lang r m (Value (Reference r))
lookupAtom i = get >>= \e -> case Map.lookup i . fromEnv $ bindingsEnv e of
Nothing -> throwError $ UnknownIdentifier i
Just v -> pure v
-- | Lookup a primop.
-lookupPrimop :: Monad m => Ident -> Lang m ([Value] -> Lang m Value)
+lookupPrimop :: Monad m => Ident -> Lang r m ([Value (Reference r)] -> Lang r m (Value (Reference r)))
lookupPrimop i = get >>= \e -> case Map.lookup i $ bindingsPrimops e of
Nothing -> throwError $ Impossible "Unknown primop"
Just v -> pure v
-defineAtom :: Monad m => Ident -> Value -> Lang m ()
+defineAtom :: Monad m => Ident -> Value (Reference r) -> Lang r m ()
defineAtom i v = modify $ addBinding i v
-- | The universal primops. These are available in chain evaluation, and are
-- not shadowable via 'define'.
-purePrimops :: forall m. Monad m => Primops m
+purePrimops :: forall r m. (Monad m) => Primops r m
purePrimops = Map.fromList $ first Ident <$>
[ ("base-eval", \args -> case args of
[x] -> baseEval x
@@ -149,19 +206,6 @@ purePrimops = Map.fromList $ first Ident <$>
, ("quote", \args -> case args of
[v] -> pure v
xs -> throwError $ WrongNumberOfArgs "quote" 1 (length xs))
- , ("quasiquote", \args -> case args of
- [x] -> do
- let unquote :: forall b. (Data b) => (b -> Lang m b)
- unquote e = case (cast e, eqT :: Maybe (b :~: Value)) of
- (Just (Apply (Primop p) [y]), Just Refl)
- | p == toIdent "unquote" -> eval y
- _ -> pure e
- app <- everywhereM unquote x
- pure $ case app of
- Apply f vs -> List (f:vs)
- _ -> app
- xs -> throwError $ WrongNumberOfArgs "quasiquote" 1 (length xs))
- , ("unquote", \_ -> throwError $ OtherError "unquote: must be in quasiquote")
, ("define", \args -> case args of
[Atom name, val] -> do
val' <- eval val
@@ -197,6 +241,13 @@ purePrimops = Map.fromList $ first Ident <$>
[_, SortedMap _] -> throwError
$ TypeError "lookup: first argument must be atom"
xs -> throwError $ WrongNumberOfArgs "lookup" 2 (length xs))
+ , ("string-append", evalArgs $ \args ->
+ let fromStr (String s) = Just s
+ fromStr _ = Nothing
+ ss = fromStr <$> args
+ in if all isJust ss
+ then pure . String . mconcat $ catMaybes ss
+ else throwError $ TypeError "string-append: non-string argument")
, ("insert", evalArgs $ \args -> case args of
[Atom k, v, SortedMap m] -> pure . SortedMap $ Map.insert k v m
[Atom _, _, _] -> throwError
@@ -259,23 +310,24 @@ purePrimops = Map.fromList $ first Ident <$>
-- in Lisps a lot of things that one might object to are True...
if b == Boolean False then eval f else eval t
xs -> throwError $ WrongNumberOfArgs "if" 3 (length xs))
- , ("deref-all", \args -> do
- let derefOne :: forall b. (Data b) => (b -> Lang m b)
- derefOne x = case (cast x, eqT :: Maybe (b :~: Value)) of
- (Just (Ref i), Just Refl) -> lookupAtom i
- _ -> pure x
+ , ("deref", evalArgs $ \args -> do
+ case args of
+ [Ref x] -> eval =<< deref x
+ [_] -> throwError $ TypeError "deref: argument must be a ref"
+ xs -> throwError $ WrongNumberOfArgs "deref" 1 (length xs))
+ , ("write-ref", evalArgs $ \args -> do
case args of
- [x] -> eval x >>= everywhereM derefOne
- xs -> throwError $ WrongNumberOfArgs "deref-all" 1 (length xs))
+ [Ref (Reference x), v] -> LangT (lift $ lift $ writeSTRef x v) >> pure nil
+ [_, _] -> throwError $ TypeError "write-ref: first argument must be a ref"
+ xs -> throwError $ WrongNumberOfArgs "write-ref" 2 (length xs))
]
where
-- Many primops evaluate their arguments just as normal functions do.
- evalArgs :: ([Value] -> Lang m Value) -> ([Value] -> Lang m Value)
evalArgs f args = traverse eval args >>= f
numBinop :: (Scientific -> Scientific -> Scientific)
-> Text
- -> (Text, [Value] -> Lang m Value)
+ -> (Text, [Value (Reference r)] -> Lang r m (Value (Reference r)))
numBinop fn name = (name, evalArgs $ \args -> case args of
Number x:x':xs -> foldM go (Number x) (x':xs)
where
@@ -289,7 +341,7 @@ purePrimops = Map.fromList $ first Ident <$>
-- * Eval
-- | The buck-passing eval. Uses whatever 'eval' is in scope.
-eval :: Monad m => Value -> Lang m Value
+eval :: Monad m => Value (Reference r) -> Lang r m (Value (Reference r))
eval val = do
e <- lookupAtom (toIdent "eval")
case e of
@@ -308,7 +360,7 @@ eval val = do
_ -> throwError $ TypeError "Trying to apply a non-function"
-- | The built-in, original, eval.
-baseEval :: Monad m => Value -> Lang m Value
+baseEval :: Monad m => Value (Reference r) -> Lang r m (Value (Reference r))
baseEval val = case val of
Atom i -> lookupAtom i
Ref i -> pure $ Ref i
@@ -352,8 +404,14 @@ baseEval val = case val of
-- | Infix function application
infixr 1 $$
-($$) :: Value -> [Value] -> Value
+($$) :: Value r -> [Value r] -> Value r
($$) = Apply
-nil :: Value
+nil :: Value r
nil = List []
+
+-- TH
+deriveEq1 ''Env
+deriveEq1 ''Value
+deriveShow1 ''Env
+deriveShow1 ''Value
diff --git a/src/Radicle/Internal/Parse.hs b/src/Radicle/Internal/Parse.hs
index ba63b37..b55d75e 100644
--- a/src/Radicle/Internal/Parse.hs
+++ b/src/Radicle/Internal/Parse.hs
@@ -2,13 +2,14 @@
module Radicle.Internal.Parse where
import Control.Applicative (many, (<|>))
-import Control.Monad (void)
-import Control.Monad.Except
+import Control.Monad (void, (>=>))
+import Control.Monad.Except (MonadError, throwError)
import Control.Monad.Identity (Identity)
import Control.Monad.Reader (Reader, ask, runReader)
import Control.Monad.State (gets)
import Data.Char (isAlphaNum, isLetter)
import Data.Either (partitionEithers)
+import Data.Functor.Foldable (Fix(..))
import Data.List.NonEmpty (NonEmpty((:|)), fromList)
import qualified Data.Map as Map
import Data.Text (Text)
@@ -29,6 +30,7 @@ import Radicle.Internal.Core
-- * The parser
type Parser a = ParsecT Void Text (Reader [Ident]) a
+type VParser = Parser (Value (Fix Value))
spaceConsumer :: Parser ()
spaceConsumer = L.space space1 lineComment blockComment
@@ -46,15 +48,15 @@ lexeme = L.lexeme spaceConsumer
parensP :: Parser a -> Parser a
parensP = between (symbol "(" >> spaceConsumer) (spaceConsumer >> symbol ")")
-stringLiteralP :: Parser Value
+stringLiteralP :: VParser
stringLiteralP = lexeme $
String . T.pack <$> (char '"' >> manyTill L.charLiteral (char '"'))
-boolLiteralP :: Parser Value
+boolLiteralP :: VParser
boolLiteralP = lexeme $ Boolean <$> (char '#' >>
(char 't' >> pure True) <|> (char 'f' >> pure False))
-numLiteralP :: Parser Value
+numLiteralP :: VParser
numLiteralP = Number <$> signed L.scientific
where
-- We don't allow spaces between the sign and digits so that we can remain
@@ -67,43 +69,43 @@ identP = lexeme $ do
r <- many (satisfy isValidIdentRest)
pure . Ident $ fromString (l:r)
-atomOrPrimP :: Parser Value
+atomOrPrimP :: VParser
atomOrPrimP = do
i <- identP
prims <- ask
pure $ if i `elem` prims then Primop i else Atom i
-applyP :: Parser Value
+applyP :: VParser
applyP = do
fn:args <- valueP `sepBy1` spaceConsumer
pure $ fn $$ args
-quoteP :: Parser Value
+quoteP :: VParser
quoteP = Apply (Primop $ toIdent "quote") . pure <$> (char '\'' >> valueP)
-listP :: Parser Value
+listP :: VParser
listP = List <$> (symbol "list" >> (valueP `sepBy` spaceConsumer))
-sortedMapP :: Parser Value
+sortedMapP :: VParser
sortedMapP = do
void $ symbol "sorted-map"
SortedMap . Map.fromList <$> pairP `sepBy` spaceConsumer
where
pairP = (,) <$> identP <*> valueP
-lambdaP :: Parser Value
+lambdaP :: VParser
lambdaP = do
void $ symbol "lambda"
vars <- parensP $ identP `sepBy` spaceConsumer
body <- fromList <$> some valueP
pure $ Lambda vars body Nothing
-refP :: Parser Value
+refP :: VParser
refP = do
void $ symbol "ref"
- Ref <$> identP
+ Ref . Fix <$> valueP
-valueP :: Parser Value
+valueP :: VParser
valueP = do
v <- choice
[ stringLiteralP <?> "string"
@@ -126,42 +128,52 @@ valueP = do
-- * Utilities
--- | Parse and evaluate a Text.
+-- | Parse and evaluate a Text. Replaces refs with a number representing them.
--
-- Examples:
--
--- >>> interpret "test" "((lambda (x) x) #t)" pureEnv
+-- >>> import Control.Monad.Identity
+-- >>> runIdentity $ interpret "test" "((lambda (x) x) #t)" pureEnv
-- Right (Boolean True)
--
--- >>> interpret "test" "(#t #f)" pureEnv
+-- >>> import Control.Monad.Identity
+-- >>> runIdentity $ interpret "test" "(#t #f)" pureEnv
-- Left (TypeError "Trying to apply a non-function")
-interpret :: Monad m => String -> Text -> Bindings m -> m (Either LangError Value)
+interpret
+ :: Monad m
+ => String
+ -> Text
+ -> (forall s . Bindings s m)
+ -> m (Either LangError (Value Int))
interpret sourceName expr bnds = do
let primopNames = Map.keys (bindingsPrimops bnds)
parsed = runReader (runParserT (valueP <* eof) sourceName expr) primopNames
case parsed of
Left e -> pure . Left $ ParseError e
- Right v -> runLang bnds $ eval v
+ Right v -> runLang bnds (fmap labelRefs $ makeRefs v >>= eval)
-- | Parse and evaluate a Text as multiple expressions.
--
+-- Before running the result, you must convert references so they don't escape
+-- (or use IO).
+--
-- Examples:
--
--- >>> runLang pureEnv $ interpretMany "test" "(define id (lambda (x) x))\n(id #t)"
+-- >>> runLang pureEnv $ fmap labelRefs $ interpretMany "test" "(define id (lambda (x) x))\n(id #t)"
-- Right (Boolean True)
-interpretMany :: Monad m => String -> Text -> Lang m Value
+interpretMany :: Monad m => String -> Text -> Lang r m (Value (Reference r))
interpretMany sourceName src = do
primopNames <- gets $ Map.keys . bindingsPrimops
let parsed = parseValues sourceName src primopNames
case partitionEithers parsed of
- ([], vs) -> last <$> mapM eval vs
+ ([], vs) -> last <$> mapM (makeRefs >=> eval) vs
(e:_, _) -> throwError $ ParseError e
-- | Parse a Text as a series of values.
-- 'sourceName' is used for error reporting. 'prims' are the primop names.
--
-- Note that parsing continues even if one value fails to parse.
-parseValues :: String -> Text -> [Ident] -> [Either (Par.ParseError Char Void) Value]
+parseValues :: String -> Text -> [Ident] -> [Either (Par.ParseError Char Void) (Value (Fix Value))]
parseValues sourceName srcCode prims = go $ initial
where
initial = State
@@ -178,15 +190,15 @@ parseValues sourceName srcCode prims = go $ initial
--
-- Examples:
--
--- >>> parse "test" "#t" [] :: Either String Value
+-- >>> parse "test" "#t" [] :: Either String (Value (Fix Value))
-- Right (Boolean True)
--
--- >>> parse "test" "hi" [toIdent "hi"] :: Either String Value
+-- >>> parse "test" "hi" [toIdent "hi"] :: Either String (Value (Fix Value))
-- Right (Primop (Ident {fromIdent = "hi"}))
--
--- >>> parse "test" "hi" [] :: Either String Value
+-- >>> parse "test" "hi" [] :: Either String (Value (Fix Value))
-- Right (Atom (Ident {fromIdent = "hi"}))
-parse :: MonadError String m => String -> Text -> [Ident] -> m Value
+parse :: MonadError String m => String -> Text -> [Ident] -> m (Value (Fix Value))
parse file src ids = do
let res = runReader (M.runParserT (valueP <* eof) file src) ids
case res of
@@ -195,10 +207,10 @@ parse file src ids = do
-- | Like 'parse', but uses "(test)" as the source name and the default set of
-- primops.
-parseTest :: MonadError String m => Text -> m Value
+parseTest :: MonadError String m => Text -> m (Value (Fix Value))
parseTest t = parse "(test)" t (Map.keys $ bindingsPrimops e)
where
- e :: Bindings (Lang Identity)
+ e :: Bindings (Fix Value) (Lang (Fix Value) Identity)
e = pureEnv
diff --git a/src/Radicle/Internal/Pretty.hs b/src/Radicle/Internal/Pretty.hs
index 5bcd36b..323059f 100644
--- a/src/Radicle/Internal/Pretty.hs
+++ b/src/Radicle/Internal/Pretty.hs
@@ -1,6 +1,7 @@
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Radicle.Internal.Pretty where
+import Data.Functor.Foldable (Fix, unfix)
import Data.List.NonEmpty (toList)
import qualified Data.Map as Map
import Data.Text (Text)
@@ -11,10 +12,16 @@ import Text.Megaparsec.Error (parseErrorPretty)
import Radicle.Internal.Core
+-- | We can't just pretty print the pointer id since that would break
+-- referential transparency, so instead we just label are refs as '<ref>'
+instance Pretty (Reference s) where
+ pretty _ = angles "ref"
+
instance Pretty Ident where
pretty (Ident i) = pretty i
-instance Pretty Value where
+
+instance Pretty r => Pretty (Value r) where
pretty v = case v of
Atom i -> pretty i
Ref i -> parens $ "ref" <+> pretty i
@@ -34,6 +41,10 @@ instance Pretty Value where
where
escapeStr = T.replace "\"" "\\\"" . T.replace "\\" "\\\\"
+instance Pretty (Fix Value) where
+ -- pretty indeed!
+ pretty = pretty . unfix
+
instance Pretty LangError where
pretty v = case v of
UnknownIdentifier i -> "Unknown identifier:" <+> pretty i
@@ -51,7 +62,8 @@ instance Pretty LangError where
--
-- Examples:
--
--- >>> renderCompactPretty (List [String "hi", String "there"])
+-- >>> import Data.Void
+-- >>> renderCompactPretty (List [String "hi", String "there"] :: Value Void)
-- "(list\n\"hi\"\n\"there\")"
renderCompactPretty :: Pretty v => v -> Text
renderCompactPretty = renderStrict . layoutCompact . pretty
@@ -60,10 +72,12 @@ renderCompactPretty = renderStrict . layoutCompact . pretty
--
-- Examples:
--
--- >>> renderPretty Unbounded (List [String "hi", String "there"])
+-- >>> import Data.Void
+-- >>> renderPretty Unbounded (List [String "hi", String "there"] :: Value Void)
-- "(list \"hi\" \"there\")"
--
--- >>> renderPretty (AvailablePerLine 6 0.5) (List [String "hi", String "there"])
+-- >>> import Data.Void
+-- >>> renderPretty (AvailablePerLine 6 0.5) (List [String "hi", String "there"] :: Value Void)
-- "(list\n\"hi\"\n\"there\")"
renderPretty :: Pretty v => PageWidth -> v -> Text
renderPretty pg = renderStrict . layoutSmart (LayoutOptions pg) . pretty
@@ -72,7 +86,8 @@ renderPretty pg = renderStrict . layoutSmart (LayoutOptions pg) . pretty
--
-- Examples:
--
--- >>> renderPrettyDef (List [String "hi", String "there"])
+-- >>> import Data.Void
+-- >>> renderPrettyDef (List [String "hi", String "there"] :: Value Void)
-- "(list \"hi\" \"there\")"
renderPrettyDef :: Pretty v => v -> Text
renderPrettyDef = renderStrict . layoutSmart defaultLayoutOptions . pretty
diff --git a/src/Radicle/Internal/Subscriber.hs b/src/Radicle/Internal/Subscriber.hs
index 23c0094..d98b8b0 100644
--- a/src/Radicle/Internal/Subscriber.hs
+++ b/src/Radicle/Internal/Subscriber.hs
@@ -1,10 +1,11 @@
{-# LANGUAGE ScopedTypeVariables #-}
module Radicle.Internal.Subscriber where
-import Control.Monad.Except
+import Control.Monad (void)
+import Control.Monad.Except (throwError)
import Control.Monad.State (gets)
import Data.Bifunctor (first)
-import Data.Either
+import Data.Either (partitionEithers)
import Data.List (isPrefixOf)
import qualified Data.Map as Map
import Data.Monoid ((<>))
@@ -22,8 +23,10 @@ import Radicle.Internal.Parse
import Radicle.Internal.Pretty
import Radicle.Internal.Subscriber.Capabilities
-type ReplM m = ( Monad m, Stdout (Lang m), Stdin (Lang m), GetEnv (Lang m)
- , SetEnv (Lang m))
+type ReplM s m =
+ ( Monad m, Stdout (Lang s m), Stdin (Lang s m)
+ , GetEnv (Lang s m) (Value (Reference s))
+ , SetEnv (Lang s m) (Value (Reference s)) )
repl :: FilePath -> Text -> IO ()
repl histFile preCode = do
@@ -31,16 +34,17 @@ repl histFile preCode = do
$ defaultSettings { historyFile = Just histFile }
r <- runInputT settings
$ runLang replBindings
- $ interpretMany "[pre]" preCode
+ $ void $ interpretMany "[pre]" preCode
case r of
Left Exit -> pure ()
Left e -> putDoc $ pretty e
- Right v -> putDoc $ pretty v
+ Right () -> pure ()
completion :: Monad m => CompletionFunc m
completion = completeWord Nothing ['(', ')', ' ', '\n'] go
where
- bnds :: Bindings (InputT IO)
+ -- Any type for first param will do
+ bnds :: Bindings Int (InputT IO)
bnds = replBindings
go s = pure $ fmap simpleCompletion
@@ -49,13 +53,13 @@ completion = completeWord Nothing ['(', ')', ' ', '\n'] go
$ (Map.keys . fromEnv $ bindingsEnv bnds)
<> Map.keys (bindingsPrimops bnds)
-replBindings :: forall m. ReplM m => Bindings m
+replBindings :: forall s m. ReplM s m => Bindings s m
replBindings = e { bindingsPrimops = bindingsPrimops e <> replPrimops }
where
- e :: Bindings m
+ e :: Bindings s m
e = pureEnv
-replPrimops :: forall m. ReplM m => Primops m
+replPrimops :: forall s m. ReplM s m => Primops s m
replPrimops = Map.fromList $ first toIdent <$>
[ ("print!", \args -> case args of
[x] -> do
@@ -78,7 +82,7 @@ replPrimops = Map.fromList $ first toIdent <$>
allPrims <- gets bindingsPrimops
let p = parseValues "[stdin]" ln (Map.keys allPrims)
case partitionEithers p of
- ([], results) -> pure $ List results
+ ([], results) -> makeRefs $ List results
(e:_, _) -> throwError $ ParseError e
xs -> throwError $ WrongNumberOfArgs "get-line!" 0 (length xs))
diff --git a/src/Radicle/Internal/Subscriber/Capabilities.hs b/src/Radicle/Internal/Subscriber/Capabilities.hs
index 44dae5c..764998e 100644
--- a/src/Radicle/Internal/Subscriber/Capabilities.hs
+++ b/src/Radicle/Internal/Subscriber/Capabilities.hs
@@ -15,7 +15,7 @@ import Radicle.Internal.Core
class (Monad m) => Stdin m where
getLineS :: m Text
-instance {-# OVERLAPPABLE #-} Stdin m => Stdin (Lang m) where
+instance {-# OVERLAPPABLE #-} Stdin m => Stdin (Lang r m) where
getLineS = lift getLineS
instance (MonadException m, Monad m) => Stdin (InputT m) where
getLineS = getInputLine "rad> " >>= \x -> case x of
@@ -24,26 +24,24 @@ instance (MonadException m, Monad m) => Stdin (InputT m) where
class (Monad m) => Stdout m where
putStrS :: Text -> m ()
-instance {-# OVERLAPPABLE #-} Stdout m => Stdout (Lang m) where
+instance {-# OVERLAPPABLE #-} Stdout m => Stdout (Lang r m) where
putStrS = lift . putStrS
instance (MonadException m, Monad m) => Stdout (InputT m) where
putStrS = outputStrLn . T.unpack
class (Monad m) => Exit m where
exitS :: m ()
-instance Exit m => Exit (Lang m) where
+instance Exit m => Exit (Lang r m) where
exitS = lift exitS
-class (Monad m) => GetEnv m where
- getEnvS :: m Env
-instance Monad m => GetEnv (Lang m) where
+class (Monad m) => GetEnv m r | m -> r where
+ getEnvS :: m (Env r)
+instance Monad m => GetEnv (Lang r m) (Value (Reference r)) where
getEnvS = gets bindingsEnv
-instance GetEnv m => GetEnv (InputT m) where
- getEnvS = lift getEnvS
-class (Monad m) => SetEnv m where
- setEnvS :: Env -> m ()
-instance Monad m => SetEnv (Lang m) where
+class (Monad m) => SetEnv m r | m -> r where
+ setEnvS :: Env r -> m ()
+instance Monad m => SetEnv (Lang r m) (Value (Reference r)) where
setEnvS e = modify (\bnds -> bnds {bindingsEnv = e})
class (Monad m) => GetSourceName m where
@@ -51,12 +49,12 @@ class (Monad m) => GetSourceName m where
class (Monad m) => HasPageWidth m where
getPageWidthS :: m PageWidth
class (Monad m) => GetSubs m where
- getSubsS :: m [(Text, Value -> m ())]
+ getSubsS :: m [(Text, Value r -> m ())]
class (Monad m) => SetSubs m where
- setSubS :: Text -> (Value -> m ()) -> m ()
+ setSubS :: Text -> (Value r -> m ()) -> m ()
putStrLnS :: (Stdout m) => Text -> m ()
putStrLnS t = putStrS t >> putStrS "\n"
-modifyEnvS :: (GetEnv m, SetEnv m) => (Env -> Env) -> m ()
+modifyEnvS :: (GetEnv m r, SetEnv m r) => (Env r -> Env r) -> m ()
modifyEnvS f = getEnvS >>= setEnvS . f
diff --git a/test/spec/Radicle/Internal/Arbitrary.hs b/test/spec/Radicle/Internal/Arbitrary.hs
index 0d0a29c..f52c1f0 100644
--- a/test/spec/Radicle/Internal/Arbitrary.hs
+++ b/test/spec/Radicle/Internal/Arbitrary.hs
@@ -3,10 +3,12 @@ module Radicle.Internal.Arbitrary where
import Control.Monad.Identity (Identity)
import Data.Bifunctor (first)
+import Data.Functor.Foldable (Fix(Fix))
import qualified Data.Map as Map
import Data.Maybe (isJust)
import Data.Scientific (Scientific)
import qualified Data.Text as T
+import Data.Void (Void)
import Safe (readMay)
import Test.QuickCheck
import Test.QuickCheck.Instances ()
@@ -15,14 +17,13 @@ import Radicle
import Radicle.Internal.Core (purePrimops)
import Radicle.Internal.Parse (isValidIdentFirst, isValidIdentRest)
-instance Arbitrary Env where
+instance Arbitrary r => Arbitrary (Env r) where
arbitrary = Env <$> arbitrary
-instance Arbitrary Value where
+instance {-# OVERLAPPING #-} Arbitrary (Value Void) where
arbitrary = sized go
where
freqs = [ (3, Atom <$> (arbitrary `suchThat` (\x -> not (isPrimop x || isNum x))))
- , (3, Ref <$> arbitrary)
, (3, String <$> arbitrary)
, (3, Boolean <$> arbitrary)
, (3, Number <$> arbitrary)
@@ -40,12 +41,18 @@ instance Arbitrary Value where
sizedList = sized $ \n -> do
k <- choose (0, n)
scale (`div` (k + 1)) $ vectorOf k arbitrary
- prims :: Map.Map Ident ([Value] -> Lang Identity Value)
+ prims :: Map.Map Ident ([Value (Reference s)] -> Lang s Identity (Value (Reference s)))
prims = purePrimops
isPrimop x = x `elem` Map.keys prims
isNum x = isJust (readMay (T.unpack $ fromIdent x) :: Maybe Scientific)
- shrink x = genericShrink x
+instance {-# OVERLAPPABLE #-} Arbitrary r => Arbitrary (Value r) where
+ arbitrary = frequency [ (20, coerceRefs <$> arbitrary)
+ , (3, Ref <$> arbitrary)
+ ]
+
+instance Arbitrary (Fix Value) where
+ arbitrary = Fix <$> arbitrary
instance Arbitrary Ident where
arbitrary = ((:) <$> firstL <*> rest) `suchThatMap` (mkIdent . T.pack)
diff --git a/test/spec/Radicle/Internal/TestCapabilities.hs b/test/spec/Radicle/Internal/TestCapabilities.hs
index bb18c1b..f7d5e90 100644
--- a/test/spec/Radicle/Internal/TestCapabilities.hs
+++ b/test/spec/Radicle/Internal/TestCapabilities.hs
@@ -12,39 +12,53 @@ import Radicle.Internal.Subscriber.Capabilities
data WorldState = WorldState
{ worldStateStdin :: [Text]
, worldStateStdout :: [Text]
- , worldStateEnv :: Env
+ , worldStateEnv :: forall s. Env (Value (Reference s))
}
-type TestLang = Lang (State WorldState)
+type TestLang s = Lang s (State WorldState )
-- | Run a possibly side-effecting program with the given stdin input lines.
runTestWith
- :: Bindings (State WorldState)
+ :: (forall s. Bindings s (State WorldState))
-> [Text] -- The stdin (errors if it runs out)
- -> TestLang a
- -> (Either LangError a, [Text])
+ -> Text -- The program
+ -> (Either LangError (Value Int), [Text])
runTestWith bindings inputs action =
let ws = WorldState
{ worldStateStdin = inputs
, worldStateStdout = []
, worldStateEnv = bindingsEnv bindings
}
- in case runState (runLang bindings action) ws of
+ in case runState (runLang bindings $ labelRefs <$> interpretMany "[test]" action) ws of
(val, st) -> (val, reverse $ worldStateStdout st)
-- | Like `runTestWith`, but uses the pureEnv
-runTestWith' :: [Text] -> TestLang a -> (Either LangError a, [Text])
+runTestWith'
+ :: [Text]
+ -> Text
+ -> (Either LangError (Value Int), [Text])
runTestWith' = runTestWith pureEnv
+-- | Run a test without stdin/stdout
+runTest
+ :: (forall s. Bindings s (State WorldState))
+ -> Text
+ -> Either LangError (Value Int)
+runTest bnds prog = fst $ runTestWith bnds [] prog
-instance {-# OVERLAPPING #-} Stdin TestLang where
+-- | Like 'runTest', but uses the pureEnv
+runTest' :: Text -> Either LangError (Value Int)
+runTest' = runTest pureEnv
+
+
+instance {-# OVERLAPPING #-} Stdin (TestLang s) where
getLineS = do
ws <- lift get
case worldStateStdin ws of
[] -> throwError $ OtherError "test: out of stdin"
h:hs -> lift (put $ ws { worldStateStdin = hs }) >> pure h
-instance {-# OVERLAPPING #-} Stdout TestLang where
+instance {-# OVERLAPPING #-} Stdout (TestLang s) where
putStrS t = lift $
modify (\ws -> ws { worldStateStdout = t:worldStateStdout ws })
diff --git a/test/spec/Radicle/Tests.hs b/test/spec/Radicle/Tests.hs
index c695849..400e47f 100644
--- a/test/spec/Radicle/Tests.hs
+++ b/test/spec/Radicle/Tests.hs
@@ -2,16 +2,18 @@
{-# LANGUAGE ScopedTypeVariables #-}
module Radicle.Tests where
-import Data.Data ((:~:)(Refl), Data, cast, eqT)
import Data.Either (isLeft)
+import Data.Functor.Foldable (Fix(..), unfix)
import Data.Functor.Identity (runIdentity)
-import Data.Generics (everywhere)
+import Data.List (isSuffixOf)
import Data.Semigroup ((<>))
import Data.String.Interpolate (i)
import Data.String.QQ (s)
import qualified Data.Text as T
import qualified Data.Text.IO as T
+import Data.Void (Void)
import GHC.Exts (fromList, toList)
+import System.Directory (getDirectoryContents)
import Test.Tasty
import Test.Tasty.HUnit
import Test.Tasty.QuickCheck (counterexample, testProperty, (==>))
@@ -51,21 +53,18 @@ test_eval =
let prog = [s|(cdr (list #t #f #t))|]
prog `succeedsWith` List [Boolean False, Boolean True]
- , testProperty "'eq?' considers equal values equal" $ \(val :: Value) -> do
+ , testProperty "'eq?' considers equal values equal" $ \(val :: Value Void) -> do
let prog = [i|(eq? #{renderPrettyDef val} #{renderPrettyDef val})|]
- res = runIdentity $ runLang pureEnv
- $ interpretMany "(test)" $ T.pack prog
- -- Either evaluation failed or their equal.
- counterexample prog $ isLeft res || res == Right (Boolean True)
+ res = runTest' $ T.pack prog
+ counterexample prog $ isLeft res || res == Right (Boolean True)
, testProperty "'eq?' considers different values different"
- $ \(v1 :: Value, v2 :: Value) ->
+ $ \(v1 :: Value Int, v2 :: Value Int) ->
v1 /= v2 ==> do
-- We quote the values to prevent errors from being thrown
let prog = [i|(eq? (quote #{renderPrettyDef v1})
(quote #{renderPrettyDef v2}))|]
- res = runIdentity $ runLang pureEnv
- $ interpretMany "(test)" $ T.pack prog
+ res = runTest' $ T.pack prog
-- Either evaluation failed or their equal.
counterexample prog $ isLeft res || res == Right (Boolean False)
@@ -89,6 +88,15 @@ test_eval =
let prog = [s|(lookup 'key1 (insert 'key1 "b" (sorted-map)))|]
prog `succeedsWith` String "b"
+ , testProperty "'string-append' concatenates string" $ \ss -> do
+ let args = T.unwords $ renderPrettyFix . String <$> ss
+ prog = "(string-append " <> args <> ")"
+ res = runTest' prog
+ expected = Right . String $ mconcat ss
+ info = "Expected:\n" <> prettyEither expected <>
+ "Got:\n" <> prettyEither res
+ counterexample (T.unpack info) $ res == expected
+
, testCase "'foldl' foldls the list" $ do
let prog = [s|(foldl - 0 (list 1 2 3))|]
prog `succeedsWith` Number (-6)
@@ -183,32 +191,15 @@ test_eval =
prog `succeedsWith` Number 6
, testProperty "'>' works" $ \(x, y) -> do
- let prog = [i|(> #{renderPrettyDef $ Number x} #{renderPrettyDef $ Number y})|]
- res = runIdentity $ runLang pureEnv
- $ interpretMany "(test)" $ T.pack prog
+ let prog = [i|(> #{renderPrettyFix $ Number x} #{renderPrettyFix $ Number y})|]
+ res = runTest' $ T.pack prog
counterexample prog $ res == Right (Boolean (x > y))
, testProperty "'<' works" $ \(x, y) -> do
- let prog = [i|(< #{renderPrettyDef $ Number x} #{renderPrettyDef $ Number y})|]
- res = runIdentity $ runLang pureEnv
- $ interpretMany "(test)" $ T.pack prog
+ let prog = [i|(< #{renderPrettyFix $ Number x} #{renderPrettyFix $ Number y})|]
+ res = runTest' $ T.pack prog
counterexample prog $ res == Right (Boolean (x < y))
- , testProperty "quasiquote . unquote == id" $ \(v :: Value) -> do
- -- Parse errors will differ, so we ignore them.
- let equalModuloParseErr x y = case (x, y) of
- (Left (ParseError _) , Left (ParseError _)) -> True
- _ -> x == y
- prog1 = [i|(quasiquote (unquote #{renderPrettyDef v}))|]
- prog2 = [i|#{renderPrettyDef v}|]
- run' = runIdentity . runLang pureEnv
- . interpretMany "(test)" . T.pack
- l = run' prog1
- r = run' prog2
- info = "Left:\n" <> prettyEither l <>
- "\nRight:\n" <> prettyEither r
- counterexample (T.unpack info) $ l `equalModuloParseErr` r
-
, testCase "'define' fails when first arg is not an atom" $ do
let prog = [s|(define "hi" "there")|]
prog `failsWith` OtherError "define expects atom for first arg"
@@ -219,12 +210,26 @@ test_eval =
#t
|]
prog `succeedsWith` Boolean False
+
+ , testCase "'deref' returns the most recent value" $ do
+ let prog = [s|
+ (define x (ref 5))
+ (write-ref x 6)
+ (deref x)
+ |]
+ res = runTest' prog
+ res @?= Right (Number 6)
+
+ , testProperty "deref . ref == id" $ \v -> do
+ let derefed = runTest' $ T.pack [i|(deref (ref #{renderPrettyFix v}))|]
+ orig = runTest' $ T.pack [i|#{renderPrettyFix v}|]
+ info = "Expected:\n" <> T.unpack (prettyEither orig)
+ <> "\nGot:\n" <> T.unpack (prettyEither derefed)
+ counterexample info $ derefed == orig
]
where
- run src = runIdentity $ runLang pureEnv
- $ interpretMany "(test)" src
- failsWith src err = run src @?= Left err
- succeedsWith src val = run src @?= Right val
+ failsWith src err = runTest' src @?= Left err
+ succeedsWith src val = runTest' src @?= Right val
test_parser :: [TestTree]
test_parser =
@@ -279,10 +284,10 @@ test_binding =
test_pretty :: [TestTree]
test_pretty =
- [ testProperty "pretty . parse == identity" $ \val ->
+ [ testProperty "pretty . parse == identity" $ \(val :: Value (Fix Value)) ->
let rendered = renderCompactPretty val
actual = parseTest rendered
- original = removeEnv val
+ original = removeEnv' val
info = case actual of
Left e -> "parse error in: " <> T.unpack rendered <> "\n"
<> e
@@ -294,37 +299,21 @@ test_pretty =
test_env :: [TestTree]
test_env =
- [ testProperty "fromList . toList == identity" $ \(env' :: Env) ->
+ [ testProperty "fromList . toList == identity" $ \(env' :: Env (Value Int)) ->
fromList (toList env') == env'
]
test_repl_primops :: [TestTree]
test_repl_primops =
- [ testProperty "get-line! returns the input line" $ \(v :: Value) ->
+ [ testProperty "get-line! returns the input line" $ \(v :: Value Void) ->
let res = run [renderCompactPretty v] [s|(get-line!)|]
expected = Right $ List [removeEnv v]
info = "Expected: " <> show expected <> "\nGot: " <> show res
- in counterexample info $ res == expected
-
- , testCase "'deref-all' gives the value of a binding at call site" $ do
- let prog = [s|
- (define x #f)
- (define y (ref x))
- (define x #t)
- (deref-all y)
- |]
- res = run [] prog
- res @?= Right (Boolean True)
-
- , testProperty "deref-all . ref == id" $ \(i', v) -> do
- let derefed = Primop (toIdent "deref-all") $$ [Ref i']
- atom = Atom i'
- run' p = runTestWith (addBinding i' v pureEnv) [] (eval p)
- run' derefed == run' atom
+ in counterexample info $ res == (coerceRefs <$> expected)
]
- where
- run inp prog = fst $ runTestWith replBindings inp
- $ interpretMany "(test)" prog
+ where
+ run stdin prog = fst $ runTestWith replBindings stdin prog
+
test_repl :: [TestTree]
test_repl =
@@ -368,22 +357,50 @@ test_repl =
]
where
getCfg = getDataFileName "repl/config.rad" >>= T.readFile
- runInRepl inp = runTestWith replBindings inp
- . interpretMany "(test)" <$> getCfg
+ runInRepl inp = runTestWith replBindings inp <$> getCfg
+
+-- Tests all radicle files 'repl' dir. These should use the 'should-be'
+-- function to ensure they are in the proper format.
+test_source_files :: IO TestTree
+test_source_files = testGroup "Radicle source file tests" <$> do
+ oneOf'Em <- getDataFileName "repl/config.rad"
+ let dir = reverse $ drop (length ("config.rad" :: String)) $ reverse oneOf'Em
+ files <- getDirectoryContents dir
+ let radFiles = filter (".rad" `isSuffixOf`) files
+ print radFiles
+ sequence $ radFiles <&> \file -> do
+ contents <- T.readFile $ dir <> file
+ let (_, out) = runTestWith replBindings [] contents
+ let makeTest line = let (name, result) = T.span (/= '\'')
+ $ T.drop 1
+ $ T.dropWhile (/= '\'') line
+ in testCase (T.unpack name) $ result @?= "' succeeded\""
+ print out
+ pure $ testGroup file
+ $ [ makeTest ln | ln <- out, "\"Test" `T.isPrefixOf` ln ]
+
-- * Utils
-- | Environments are neither printed nor parsed, but are generated by the
-- arbitrary instance.
-removeEnv :: Value -> Value
-removeEnv = everywhere go
- where
- go :: forall b. Data b => (b -> b)
- go x = case (cast x, eqT :: Maybe (b :~: Value)) of
- (Just (Lambda arg body _), Just Refl) -> Lambda arg body Nothing
- _ -> x
-
-prettyEither :: Either LangError Value -> T.Text
+removeEnv :: Value s -> Value s
+removeEnv v = case v of
+ List xs -> List $ removeEnv <$> xs
+ Apply fn xs -> Apply (removeEnv fn) (removeEnv <$> xs)
+ SortedMap m -> SortedMap $ removeEnv <$> m
+ Lambda ids bd _ -> Lambda ids (removeEnv <$> bd) Nothing
+ x -> x
+
+removeEnv' :: Value (Fix Value) -> Value (Fix Value)
+removeEnv' v = Fix . removeEnv' . unfix <$> removeEnv v
+
+prettyEither :: Pretty s => Either LangError (Value s) -> T.Text
prettyEither (Left e) = "Error: " <> renderPrettyDef e
prettyEither (Right v) = renderPrettyDef v
+renderPrettyFix :: Value (Fix Value) -> T.Text
+renderPrettyFix = renderPrettyDef
+
+(<&>) :: Functor f => f a -> (a -> b) -> f b
+(<&>) = flip fmap